xref: /openbmc/linux/fs/crypto/policy.c (revision 3f58ff6b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Encryption policy functions for per-file encryption support.
4  *
5  * Copyright (C) 2015, Google, Inc.
6  * Copyright (C) 2015, Motorola Mobility.
7  *
8  * Originally written by Michael Halcrow, 2015.
9  * Modified by Jaegeuk Kim, 2015.
10  * Modified by Eric Biggers, 2019 for v2 policy support.
11  */
12 
13 #include <linux/fs_context.h>
14 #include <linux/random.h>
15 #include <linux/seq_file.h>
16 #include <linux/string.h>
17 #include <linux/mount.h>
18 #include "fscrypt_private.h"
19 
20 /**
21  * fscrypt_policies_equal() - check whether two encryption policies are the same
22  * @policy1: the first policy
23  * @policy2: the second policy
24  *
25  * Return: %true if equal, else %false
26  */
27 bool fscrypt_policies_equal(const union fscrypt_policy *policy1,
28 			    const union fscrypt_policy *policy2)
29 {
30 	if (policy1->version != policy2->version)
31 		return false;
32 
33 	return !memcmp(policy1, policy2, fscrypt_policy_size(policy1));
34 }
35 
36 int fscrypt_policy_to_key_spec(const union fscrypt_policy *policy,
37 			       struct fscrypt_key_specifier *key_spec)
38 {
39 	switch (policy->version) {
40 	case FSCRYPT_POLICY_V1:
41 		key_spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
42 		memcpy(key_spec->u.descriptor, policy->v1.master_key_descriptor,
43 		       FSCRYPT_KEY_DESCRIPTOR_SIZE);
44 		return 0;
45 	case FSCRYPT_POLICY_V2:
46 		key_spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
47 		memcpy(key_spec->u.identifier, policy->v2.master_key_identifier,
48 		       FSCRYPT_KEY_IDENTIFIER_SIZE);
49 		return 0;
50 	default:
51 		WARN_ON(1);
52 		return -EINVAL;
53 	}
54 }
55 
56 static const union fscrypt_policy *
57 fscrypt_get_dummy_policy(struct super_block *sb)
58 {
59 	if (!sb->s_cop->get_dummy_policy)
60 		return NULL;
61 	return sb->s_cop->get_dummy_policy(sb);
62 }
63 
64 /*
65  * Return %true if the given combination of encryption modes is supported for v1
66  * (and later) encryption policies.
67  *
68  * Do *not* add anything new here, since v1 encryption policies are deprecated.
69  * New combinations of modes should go in fscrypt_valid_enc_modes_v2() only.
70  */
71 static bool fscrypt_valid_enc_modes_v1(u32 contents_mode, u32 filenames_mode)
72 {
73 	if (contents_mode == FSCRYPT_MODE_AES_256_XTS &&
74 	    filenames_mode == FSCRYPT_MODE_AES_256_CTS)
75 		return true;
76 
77 	if (contents_mode == FSCRYPT_MODE_AES_128_CBC &&
78 	    filenames_mode == FSCRYPT_MODE_AES_128_CTS)
79 		return true;
80 
81 	if (contents_mode == FSCRYPT_MODE_ADIANTUM &&
82 	    filenames_mode == FSCRYPT_MODE_ADIANTUM)
83 		return true;
84 
85 	return false;
86 }
87 
88 static bool fscrypt_valid_enc_modes_v2(u32 contents_mode, u32 filenames_mode)
89 {
90 	if (contents_mode == FSCRYPT_MODE_AES_256_XTS &&
91 	    filenames_mode == FSCRYPT_MODE_AES_256_HCTR2)
92 		return true;
93 
94 	if (contents_mode == FSCRYPT_MODE_SM4_XTS &&
95 	    filenames_mode == FSCRYPT_MODE_SM4_CTS)
96 		return true;
97 
98 	return fscrypt_valid_enc_modes_v1(contents_mode, filenames_mode);
99 }
100 
101 static bool supported_direct_key_modes(const struct inode *inode,
102 				       u32 contents_mode, u32 filenames_mode)
103 {
104 	const struct fscrypt_mode *mode;
105 
106 	if (contents_mode != filenames_mode) {
107 		fscrypt_warn(inode,
108 			     "Direct key flag not allowed with different contents and filenames modes");
109 		return false;
110 	}
111 	mode = &fscrypt_modes[contents_mode];
112 
113 	if (mode->ivsize < offsetofend(union fscrypt_iv, nonce)) {
114 		fscrypt_warn(inode, "Direct key flag not allowed with %s",
115 			     mode->friendly_name);
116 		return false;
117 	}
118 	return true;
119 }
120 
121 static bool supported_iv_ino_lblk_policy(const struct fscrypt_policy_v2 *policy,
122 					 const struct inode *inode,
123 					 const char *type,
124 					 int max_ino_bits, int max_lblk_bits)
125 {
126 	struct super_block *sb = inode->i_sb;
127 	int ino_bits = 64, lblk_bits = 64;
128 
129 	/*
130 	 * IV_INO_LBLK_* exist only because of hardware limitations, and
131 	 * currently the only known use case for them involves AES-256-XTS.
132 	 * That's also all we test currently.  For these reasons, for now only
133 	 * allow AES-256-XTS here.  This can be relaxed later if a use case for
134 	 * IV_INO_LBLK_* with other encryption modes arises.
135 	 */
136 	if (policy->contents_encryption_mode != FSCRYPT_MODE_AES_256_XTS) {
137 		fscrypt_warn(inode,
138 			     "Can't use %s policy with contents mode other than AES-256-XTS",
139 			     type);
140 		return false;
141 	}
142 
143 	/*
144 	 * It's unsafe to include inode numbers in the IVs if the filesystem can
145 	 * potentially renumber inodes, e.g. via filesystem shrinking.
146 	 */
147 	if (!sb->s_cop->has_stable_inodes ||
148 	    !sb->s_cop->has_stable_inodes(sb)) {
149 		fscrypt_warn(inode,
150 			     "Can't use %s policy on filesystem '%s' because it doesn't have stable inode numbers",
151 			     type, sb->s_id);
152 		return false;
153 	}
154 	if (sb->s_cop->get_ino_and_lblk_bits)
155 		sb->s_cop->get_ino_and_lblk_bits(sb, &ino_bits, &lblk_bits);
156 	if (ino_bits > max_ino_bits) {
157 		fscrypt_warn(inode,
158 			     "Can't use %s policy on filesystem '%s' because its inode numbers are too long",
159 			     type, sb->s_id);
160 		return false;
161 	}
162 	if (lblk_bits > max_lblk_bits) {
163 		fscrypt_warn(inode,
164 			     "Can't use %s policy on filesystem '%s' because its block numbers are too long",
165 			     type, sb->s_id);
166 		return false;
167 	}
168 	return true;
169 }
170 
171 static bool fscrypt_supported_v1_policy(const struct fscrypt_policy_v1 *policy,
172 					const struct inode *inode)
173 {
174 	if (!fscrypt_valid_enc_modes_v1(policy->contents_encryption_mode,
175 				     policy->filenames_encryption_mode)) {
176 		fscrypt_warn(inode,
177 			     "Unsupported encryption modes (contents %d, filenames %d)",
178 			     policy->contents_encryption_mode,
179 			     policy->filenames_encryption_mode);
180 		return false;
181 	}
182 
183 	if (policy->flags & ~(FSCRYPT_POLICY_FLAGS_PAD_MASK |
184 			      FSCRYPT_POLICY_FLAG_DIRECT_KEY)) {
185 		fscrypt_warn(inode, "Unsupported encryption flags (0x%02x)",
186 			     policy->flags);
187 		return false;
188 	}
189 
190 	if ((policy->flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) &&
191 	    !supported_direct_key_modes(inode, policy->contents_encryption_mode,
192 					policy->filenames_encryption_mode))
193 		return false;
194 
195 	if (IS_CASEFOLDED(inode)) {
196 		/* With v1, there's no way to derive dirhash keys. */
197 		fscrypt_warn(inode,
198 			     "v1 policies can't be used on casefolded directories");
199 		return false;
200 	}
201 
202 	return true;
203 }
204 
205 static bool fscrypt_supported_v2_policy(const struct fscrypt_policy_v2 *policy,
206 					const struct inode *inode)
207 {
208 	int count = 0;
209 
210 	if (!fscrypt_valid_enc_modes_v2(policy->contents_encryption_mode,
211 				     policy->filenames_encryption_mode)) {
212 		fscrypt_warn(inode,
213 			     "Unsupported encryption modes (contents %d, filenames %d)",
214 			     policy->contents_encryption_mode,
215 			     policy->filenames_encryption_mode);
216 		return false;
217 	}
218 
219 	if (policy->flags & ~(FSCRYPT_POLICY_FLAGS_PAD_MASK |
220 			      FSCRYPT_POLICY_FLAG_DIRECT_KEY |
221 			      FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 |
222 			      FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)) {
223 		fscrypt_warn(inode, "Unsupported encryption flags (0x%02x)",
224 			     policy->flags);
225 		return false;
226 	}
227 
228 	count += !!(policy->flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY);
229 	count += !!(policy->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64);
230 	count += !!(policy->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32);
231 	if (count > 1) {
232 		fscrypt_warn(inode, "Mutually exclusive encryption flags (0x%02x)",
233 			     policy->flags);
234 		return false;
235 	}
236 
237 	if ((policy->flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) &&
238 	    !supported_direct_key_modes(inode, policy->contents_encryption_mode,
239 					policy->filenames_encryption_mode))
240 		return false;
241 
242 	if ((policy->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) &&
243 	    !supported_iv_ino_lblk_policy(policy, inode, "IV_INO_LBLK_64",
244 					  32, 32))
245 		return false;
246 
247 	/*
248 	 * IV_INO_LBLK_32 hashes the inode number, so in principle it can
249 	 * support any ino_bits.  However, currently the inode number is gotten
250 	 * from inode::i_ino which is 'unsigned long'.  So for now the
251 	 * implementation limit is 32 bits.
252 	 */
253 	if ((policy->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
254 	    !supported_iv_ino_lblk_policy(policy, inode, "IV_INO_LBLK_32",
255 					  32, 32))
256 		return false;
257 
258 	if (memchr_inv(policy->__reserved, 0, sizeof(policy->__reserved))) {
259 		fscrypt_warn(inode, "Reserved bits set in encryption policy");
260 		return false;
261 	}
262 
263 	return true;
264 }
265 
266 /**
267  * fscrypt_supported_policy() - check whether an encryption policy is supported
268  * @policy_u: the encryption policy
269  * @inode: the inode on which the policy will be used
270  *
271  * Given an encryption policy, check whether all its encryption modes and other
272  * settings are supported by this kernel on the given inode.  (But we don't
273  * currently don't check for crypto API support here, so attempting to use an
274  * algorithm not configured into the crypto API will still fail later.)
275  *
276  * Return: %true if supported, else %false
277  */
278 bool fscrypt_supported_policy(const union fscrypt_policy *policy_u,
279 			      const struct inode *inode)
280 {
281 	switch (policy_u->version) {
282 	case FSCRYPT_POLICY_V1:
283 		return fscrypt_supported_v1_policy(&policy_u->v1, inode);
284 	case FSCRYPT_POLICY_V2:
285 		return fscrypt_supported_v2_policy(&policy_u->v2, inode);
286 	}
287 	return false;
288 }
289 
290 /**
291  * fscrypt_new_context() - create a new fscrypt_context
292  * @ctx_u: output context
293  * @policy_u: input policy
294  * @nonce: nonce to use
295  *
296  * Create an fscrypt_context for an inode that is being assigned the given
297  * encryption policy.  @nonce must be a new random nonce.
298  *
299  * Return: the size of the new context in bytes.
300  */
301 static int fscrypt_new_context(union fscrypt_context *ctx_u,
302 			       const union fscrypt_policy *policy_u,
303 			       const u8 nonce[FSCRYPT_FILE_NONCE_SIZE])
304 {
305 	memset(ctx_u, 0, sizeof(*ctx_u));
306 
307 	switch (policy_u->version) {
308 	case FSCRYPT_POLICY_V1: {
309 		const struct fscrypt_policy_v1 *policy = &policy_u->v1;
310 		struct fscrypt_context_v1 *ctx = &ctx_u->v1;
311 
312 		ctx->version = FSCRYPT_CONTEXT_V1;
313 		ctx->contents_encryption_mode =
314 			policy->contents_encryption_mode;
315 		ctx->filenames_encryption_mode =
316 			policy->filenames_encryption_mode;
317 		ctx->flags = policy->flags;
318 		memcpy(ctx->master_key_descriptor,
319 		       policy->master_key_descriptor,
320 		       sizeof(ctx->master_key_descriptor));
321 		memcpy(ctx->nonce, nonce, FSCRYPT_FILE_NONCE_SIZE);
322 		return sizeof(*ctx);
323 	}
324 	case FSCRYPT_POLICY_V2: {
325 		const struct fscrypt_policy_v2 *policy = &policy_u->v2;
326 		struct fscrypt_context_v2 *ctx = &ctx_u->v2;
327 
328 		ctx->version = FSCRYPT_CONTEXT_V2;
329 		ctx->contents_encryption_mode =
330 			policy->contents_encryption_mode;
331 		ctx->filenames_encryption_mode =
332 			policy->filenames_encryption_mode;
333 		ctx->flags = policy->flags;
334 		memcpy(ctx->master_key_identifier,
335 		       policy->master_key_identifier,
336 		       sizeof(ctx->master_key_identifier));
337 		memcpy(ctx->nonce, nonce, FSCRYPT_FILE_NONCE_SIZE);
338 		return sizeof(*ctx);
339 	}
340 	}
341 	BUG();
342 }
343 
344 /**
345  * fscrypt_policy_from_context() - convert an fscrypt_context to
346  *				   an fscrypt_policy
347  * @policy_u: output policy
348  * @ctx_u: input context
349  * @ctx_size: size of input context in bytes
350  *
351  * Given an fscrypt_context, build the corresponding fscrypt_policy.
352  *
353  * Return: 0 on success, or -EINVAL if the fscrypt_context has an unrecognized
354  * version number or size.
355  *
356  * This does *not* validate the settings within the policy itself, e.g. the
357  * modes, flags, and reserved bits.  Use fscrypt_supported_policy() for that.
358  */
359 int fscrypt_policy_from_context(union fscrypt_policy *policy_u,
360 				const union fscrypt_context *ctx_u,
361 				int ctx_size)
362 {
363 	memset(policy_u, 0, sizeof(*policy_u));
364 
365 	if (!fscrypt_context_is_valid(ctx_u, ctx_size))
366 		return -EINVAL;
367 
368 	switch (ctx_u->version) {
369 	case FSCRYPT_CONTEXT_V1: {
370 		const struct fscrypt_context_v1 *ctx = &ctx_u->v1;
371 		struct fscrypt_policy_v1 *policy = &policy_u->v1;
372 
373 		policy->version = FSCRYPT_POLICY_V1;
374 		policy->contents_encryption_mode =
375 			ctx->contents_encryption_mode;
376 		policy->filenames_encryption_mode =
377 			ctx->filenames_encryption_mode;
378 		policy->flags = ctx->flags;
379 		memcpy(policy->master_key_descriptor,
380 		       ctx->master_key_descriptor,
381 		       sizeof(policy->master_key_descriptor));
382 		return 0;
383 	}
384 	case FSCRYPT_CONTEXT_V2: {
385 		const struct fscrypt_context_v2 *ctx = &ctx_u->v2;
386 		struct fscrypt_policy_v2 *policy = &policy_u->v2;
387 
388 		policy->version = FSCRYPT_POLICY_V2;
389 		policy->contents_encryption_mode =
390 			ctx->contents_encryption_mode;
391 		policy->filenames_encryption_mode =
392 			ctx->filenames_encryption_mode;
393 		policy->flags = ctx->flags;
394 		memcpy(policy->__reserved, ctx->__reserved,
395 		       sizeof(policy->__reserved));
396 		memcpy(policy->master_key_identifier,
397 		       ctx->master_key_identifier,
398 		       sizeof(policy->master_key_identifier));
399 		return 0;
400 	}
401 	}
402 	/* unreachable */
403 	return -EINVAL;
404 }
405 
406 /* Retrieve an inode's encryption policy */
407 static int fscrypt_get_policy(struct inode *inode, union fscrypt_policy *policy)
408 {
409 	const struct fscrypt_info *ci;
410 	union fscrypt_context ctx;
411 	int ret;
412 
413 	ci = fscrypt_get_info(inode);
414 	if (ci) {
415 		/* key available, use the cached policy */
416 		*policy = ci->ci_policy;
417 		return 0;
418 	}
419 
420 	if (!IS_ENCRYPTED(inode))
421 		return -ENODATA;
422 
423 	ret = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
424 	if (ret < 0)
425 		return (ret == -ERANGE) ? -EINVAL : ret;
426 
427 	return fscrypt_policy_from_context(policy, &ctx, ret);
428 }
429 
430 static int set_encryption_policy(struct inode *inode,
431 				 const union fscrypt_policy *policy)
432 {
433 	u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
434 	union fscrypt_context ctx;
435 	int ctxsize;
436 	int err;
437 
438 	if (!fscrypt_supported_policy(policy, inode))
439 		return -EINVAL;
440 
441 	switch (policy->version) {
442 	case FSCRYPT_POLICY_V1:
443 		/*
444 		 * The original encryption policy version provided no way of
445 		 * verifying that the correct master key was supplied, which was
446 		 * insecure in scenarios where multiple users have access to the
447 		 * same encrypted files (even just read-only access).  The new
448 		 * encryption policy version fixes this and also implies use of
449 		 * an improved key derivation function and allows non-root users
450 		 * to securely remove keys.  So as long as compatibility with
451 		 * old kernels isn't required, it is recommended to use the new
452 		 * policy version for all new encrypted directories.
453 		 */
454 		pr_warn_once("%s (pid %d) is setting deprecated v1 encryption policy; recommend upgrading to v2.\n",
455 			     current->comm, current->pid);
456 		break;
457 	case FSCRYPT_POLICY_V2:
458 		err = fscrypt_verify_key_added(inode->i_sb,
459 					       policy->v2.master_key_identifier);
460 		if (err)
461 			return err;
462 		if (policy->v2.flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)
463 			pr_warn_once("%s (pid %d) is setting an IV_INO_LBLK_32 encryption policy.  This should only be used if there are certain hardware limitations.\n",
464 				     current->comm, current->pid);
465 		break;
466 	default:
467 		WARN_ON(1);
468 		return -EINVAL;
469 	}
470 
471 	get_random_bytes(nonce, FSCRYPT_FILE_NONCE_SIZE);
472 	ctxsize = fscrypt_new_context(&ctx, policy, nonce);
473 
474 	return inode->i_sb->s_cop->set_context(inode, &ctx, ctxsize, NULL);
475 }
476 
477 int fscrypt_ioctl_set_policy(struct file *filp, const void __user *arg)
478 {
479 	union fscrypt_policy policy;
480 	union fscrypt_policy existing_policy;
481 	struct inode *inode = file_inode(filp);
482 	u8 version;
483 	int size;
484 	int ret;
485 
486 	if (get_user(policy.version, (const u8 __user *)arg))
487 		return -EFAULT;
488 
489 	size = fscrypt_policy_size(&policy);
490 	if (size <= 0)
491 		return -EINVAL;
492 
493 	/*
494 	 * We should just copy the remaining 'size - 1' bytes here, but a
495 	 * bizarre bug in gcc 7 and earlier (fixed by gcc r255731) causes gcc to
496 	 * think that size can be 0 here (despite the check above!) *and* that
497 	 * it's a compile-time constant.  Thus it would think copy_from_user()
498 	 * is passed compile-time constant ULONG_MAX, causing the compile-time
499 	 * buffer overflow check to fail, breaking the build. This only occurred
500 	 * when building an i386 kernel with -Os and branch profiling enabled.
501 	 *
502 	 * Work around it by just copying the first byte again...
503 	 */
504 	version = policy.version;
505 	if (copy_from_user(&policy, arg, size))
506 		return -EFAULT;
507 	policy.version = version;
508 
509 	if (!inode_owner_or_capable(&init_user_ns, inode))
510 		return -EACCES;
511 
512 	ret = mnt_want_write_file(filp);
513 	if (ret)
514 		return ret;
515 
516 	inode_lock(inode);
517 
518 	ret = fscrypt_get_policy(inode, &existing_policy);
519 	if (ret == -ENODATA) {
520 		if (!S_ISDIR(inode->i_mode))
521 			ret = -ENOTDIR;
522 		else if (IS_DEADDIR(inode))
523 			ret = -ENOENT;
524 		else if (!inode->i_sb->s_cop->empty_dir(inode))
525 			ret = -ENOTEMPTY;
526 		else
527 			ret = set_encryption_policy(inode, &policy);
528 	} else if (ret == -EINVAL ||
529 		   (ret == 0 && !fscrypt_policies_equal(&policy,
530 							&existing_policy))) {
531 		/* The file already uses a different encryption policy. */
532 		ret = -EEXIST;
533 	}
534 
535 	inode_unlock(inode);
536 
537 	mnt_drop_write_file(filp);
538 	return ret;
539 }
540 EXPORT_SYMBOL(fscrypt_ioctl_set_policy);
541 
542 /* Original ioctl version; can only get the original policy version */
543 int fscrypt_ioctl_get_policy(struct file *filp, void __user *arg)
544 {
545 	union fscrypt_policy policy;
546 	int err;
547 
548 	err = fscrypt_get_policy(file_inode(filp), &policy);
549 	if (err)
550 		return err;
551 
552 	if (policy.version != FSCRYPT_POLICY_V1)
553 		return -EINVAL;
554 
555 	if (copy_to_user(arg, &policy, sizeof(policy.v1)))
556 		return -EFAULT;
557 	return 0;
558 }
559 EXPORT_SYMBOL(fscrypt_ioctl_get_policy);
560 
561 /* Extended ioctl version; can get policies of any version */
562 int fscrypt_ioctl_get_policy_ex(struct file *filp, void __user *uarg)
563 {
564 	struct fscrypt_get_policy_ex_arg arg;
565 	union fscrypt_policy *policy = (union fscrypt_policy *)&arg.policy;
566 	size_t policy_size;
567 	int err;
568 
569 	/* arg is policy_size, then policy */
570 	BUILD_BUG_ON(offsetof(typeof(arg), policy_size) != 0);
571 	BUILD_BUG_ON(offsetofend(typeof(arg), policy_size) !=
572 		     offsetof(typeof(arg), policy));
573 	BUILD_BUG_ON(sizeof(arg.policy) != sizeof(*policy));
574 
575 	err = fscrypt_get_policy(file_inode(filp), policy);
576 	if (err)
577 		return err;
578 	policy_size = fscrypt_policy_size(policy);
579 
580 	if (copy_from_user(&arg, uarg, sizeof(arg.policy_size)))
581 		return -EFAULT;
582 
583 	if (policy_size > arg.policy_size)
584 		return -EOVERFLOW;
585 	arg.policy_size = policy_size;
586 
587 	if (copy_to_user(uarg, &arg, sizeof(arg.policy_size) + policy_size))
588 		return -EFAULT;
589 	return 0;
590 }
591 EXPORT_SYMBOL_GPL(fscrypt_ioctl_get_policy_ex);
592 
593 /* FS_IOC_GET_ENCRYPTION_NONCE: retrieve file's encryption nonce for testing */
594 int fscrypt_ioctl_get_nonce(struct file *filp, void __user *arg)
595 {
596 	struct inode *inode = file_inode(filp);
597 	union fscrypt_context ctx;
598 	int ret;
599 
600 	ret = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
601 	if (ret < 0)
602 		return ret;
603 	if (!fscrypt_context_is_valid(&ctx, ret))
604 		return -EINVAL;
605 	if (copy_to_user(arg, fscrypt_context_nonce(&ctx),
606 			 FSCRYPT_FILE_NONCE_SIZE))
607 		return -EFAULT;
608 	return 0;
609 }
610 EXPORT_SYMBOL_GPL(fscrypt_ioctl_get_nonce);
611 
612 /**
613  * fscrypt_has_permitted_context() - is a file's encryption policy permitted
614  *				     within its directory?
615  *
616  * @parent: inode for parent directory
617  * @child: inode for file being looked up, opened, or linked into @parent
618  *
619  * Filesystems must call this before permitting access to an inode in a
620  * situation where the parent directory is encrypted (either before allowing
621  * ->lookup() to succeed, or for a regular file before allowing it to be opened)
622  * and before any operation that involves linking an inode into an encrypted
623  * directory, including link, rename, and cross rename.  It enforces the
624  * constraint that within a given encrypted directory tree, all files use the
625  * same encryption policy.  The pre-access check is needed to detect potentially
626  * malicious offline violations of this constraint, while the link and rename
627  * checks are needed to prevent online violations of this constraint.
628  *
629  * Return: 1 if permitted, 0 if forbidden.
630  */
631 int fscrypt_has_permitted_context(struct inode *parent, struct inode *child)
632 {
633 	union fscrypt_policy parent_policy, child_policy;
634 	int err, err1, err2;
635 
636 	/* No restrictions on file types which are never encrypted */
637 	if (!S_ISREG(child->i_mode) && !S_ISDIR(child->i_mode) &&
638 	    !S_ISLNK(child->i_mode))
639 		return 1;
640 
641 	/* No restrictions if the parent directory is unencrypted */
642 	if (!IS_ENCRYPTED(parent))
643 		return 1;
644 
645 	/* Encrypted directories must not contain unencrypted files */
646 	if (!IS_ENCRYPTED(child))
647 		return 0;
648 
649 	/*
650 	 * Both parent and child are encrypted, so verify they use the same
651 	 * encryption policy.  Compare the fscrypt_info structs if the keys are
652 	 * available, otherwise retrieve and compare the fscrypt_contexts.
653 	 *
654 	 * Note that the fscrypt_context retrieval will be required frequently
655 	 * when accessing an encrypted directory tree without the key.
656 	 * Performance-wise this is not a big deal because we already don't
657 	 * really optimize for file access without the key (to the extent that
658 	 * such access is even possible), given that any attempted access
659 	 * already causes a fscrypt_context retrieval and keyring search.
660 	 *
661 	 * In any case, if an unexpected error occurs, fall back to "forbidden".
662 	 */
663 
664 	err = fscrypt_get_encryption_info(parent, true);
665 	if (err)
666 		return 0;
667 	err = fscrypt_get_encryption_info(child, true);
668 	if (err)
669 		return 0;
670 
671 	err1 = fscrypt_get_policy(parent, &parent_policy);
672 	err2 = fscrypt_get_policy(child, &child_policy);
673 
674 	/*
675 	 * Allow the case where the parent and child both have an unrecognized
676 	 * encryption policy, so that files with an unrecognized encryption
677 	 * policy can be deleted.
678 	 */
679 	if (err1 == -EINVAL && err2 == -EINVAL)
680 		return 1;
681 
682 	if (err1 || err2)
683 		return 0;
684 
685 	return fscrypt_policies_equal(&parent_policy, &child_policy);
686 }
687 EXPORT_SYMBOL(fscrypt_has_permitted_context);
688 
689 /*
690  * Return the encryption policy that new files in the directory will inherit, or
691  * NULL if none, or an ERR_PTR() on error.  If the directory is encrypted, also
692  * ensure that its key is set up, so that the new filename can be encrypted.
693  */
694 const union fscrypt_policy *fscrypt_policy_to_inherit(struct inode *dir)
695 {
696 	int err;
697 
698 	if (IS_ENCRYPTED(dir)) {
699 		err = fscrypt_require_key(dir);
700 		if (err)
701 			return ERR_PTR(err);
702 		return &dir->i_crypt_info->ci_policy;
703 	}
704 
705 	return fscrypt_get_dummy_policy(dir->i_sb);
706 }
707 
708 /**
709  * fscrypt_context_for_new_inode() - create an encryption context for a new inode
710  * @ctx: where context should be written
711  * @inode: inode from which to fetch policy and nonce
712  *
713  * Given an in-core "prepared" (via fscrypt_prepare_new_inode) inode,
714  * generate a new context and write it to ctx. ctx _must_ be at least
715  * FSCRYPT_SET_CONTEXT_MAX_SIZE bytes.
716  *
717  * Return: size of the resulting context or a negative error code.
718  */
719 int fscrypt_context_for_new_inode(void *ctx, struct inode *inode)
720 {
721 	struct fscrypt_info *ci = inode->i_crypt_info;
722 
723 	BUILD_BUG_ON(sizeof(union fscrypt_context) !=
724 			FSCRYPT_SET_CONTEXT_MAX_SIZE);
725 
726 	/* fscrypt_prepare_new_inode() should have set up the key already. */
727 	if (WARN_ON_ONCE(!ci))
728 		return -ENOKEY;
729 
730 	return fscrypt_new_context(ctx, &ci->ci_policy, ci->ci_nonce);
731 }
732 EXPORT_SYMBOL_GPL(fscrypt_context_for_new_inode);
733 
734 /**
735  * fscrypt_set_context() - Set the fscrypt context of a new inode
736  * @inode: a new inode
737  * @fs_data: private data given by FS and passed to ->set_context()
738  *
739  * This should be called after fscrypt_prepare_new_inode(), generally during a
740  * filesystem transaction.  Everything here must be %GFP_NOFS-safe.
741  *
742  * Return: 0 on success, -errno on failure
743  */
744 int fscrypt_set_context(struct inode *inode, void *fs_data)
745 {
746 	struct fscrypt_info *ci = inode->i_crypt_info;
747 	union fscrypt_context ctx;
748 	int ctxsize;
749 
750 	ctxsize = fscrypt_context_for_new_inode(&ctx, inode);
751 	if (ctxsize < 0)
752 		return ctxsize;
753 
754 	/*
755 	 * This may be the first time the inode number is available, so do any
756 	 * delayed key setup that requires the inode number.
757 	 */
758 	if (ci->ci_policy.version == FSCRYPT_POLICY_V2 &&
759 	    (ci->ci_policy.v2.flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32))
760 		fscrypt_hash_inode_number(ci, ci->ci_master_key);
761 
762 	return inode->i_sb->s_cop->set_context(inode, &ctx, ctxsize, fs_data);
763 }
764 EXPORT_SYMBOL_GPL(fscrypt_set_context);
765 
766 /**
767  * fscrypt_parse_test_dummy_encryption() - parse the test_dummy_encryption mount option
768  * @param: the mount option
769  * @dummy_policy: (input/output) the place to write the dummy policy that will
770  *	result from parsing the option.  Zero-initialize this.  If a policy is
771  *	already set here (due to test_dummy_encryption being given multiple
772  *	times), then this function will verify that the policies are the same.
773  *
774  * Return: 0 on success; -EINVAL if the argument is invalid; -EEXIST if the
775  *	   argument conflicts with one already specified; or -ENOMEM.
776  */
777 int fscrypt_parse_test_dummy_encryption(const struct fs_parameter *param,
778 				struct fscrypt_dummy_policy *dummy_policy)
779 {
780 	const char *arg = "v2";
781 	union fscrypt_policy *policy;
782 	int err;
783 
784 	if (param->type == fs_value_is_string && *param->string)
785 		arg = param->string;
786 
787 	policy = kzalloc(sizeof(*policy), GFP_KERNEL);
788 	if (!policy)
789 		return -ENOMEM;
790 
791 	if (!strcmp(arg, "v1")) {
792 		policy->version = FSCRYPT_POLICY_V1;
793 		policy->v1.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS;
794 		policy->v1.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS;
795 		memset(policy->v1.master_key_descriptor, 0x42,
796 		       FSCRYPT_KEY_DESCRIPTOR_SIZE);
797 	} else if (!strcmp(arg, "v2")) {
798 		policy->version = FSCRYPT_POLICY_V2;
799 		policy->v2.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS;
800 		policy->v2.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS;
801 		err = fscrypt_get_test_dummy_key_identifier(
802 				policy->v2.master_key_identifier);
803 		if (err)
804 			goto out;
805 	} else {
806 		err = -EINVAL;
807 		goto out;
808 	}
809 
810 	if (dummy_policy->policy) {
811 		if (fscrypt_policies_equal(policy, dummy_policy->policy))
812 			err = 0;
813 		else
814 			err = -EEXIST;
815 		goto out;
816 	}
817 	dummy_policy->policy = policy;
818 	policy = NULL;
819 	err = 0;
820 out:
821 	kfree(policy);
822 	return err;
823 }
824 EXPORT_SYMBOL_GPL(fscrypt_parse_test_dummy_encryption);
825 
826 /**
827  * fscrypt_dummy_policies_equal() - check whether two dummy policies are equal
828  * @p1: the first test dummy policy (may be unset)
829  * @p2: the second test dummy policy (may be unset)
830  *
831  * Return: %true if the dummy policies are both set and equal, or both unset.
832  */
833 bool fscrypt_dummy_policies_equal(const struct fscrypt_dummy_policy *p1,
834 				  const struct fscrypt_dummy_policy *p2)
835 {
836 	if (!p1->policy && !p2->policy)
837 		return true;
838 	if (!p1->policy || !p2->policy)
839 		return false;
840 	return fscrypt_policies_equal(p1->policy, p2->policy);
841 }
842 EXPORT_SYMBOL_GPL(fscrypt_dummy_policies_equal);
843 
844 /**
845  * fscrypt_show_test_dummy_encryption() - show '-o test_dummy_encryption'
846  * @seq: the seq_file to print the option to
847  * @sep: the separator character to use
848  * @sb: the filesystem whose options are being shown
849  *
850  * Show the test_dummy_encryption mount option, if it was specified.
851  * This is mainly used for /proc/mounts.
852  */
853 void fscrypt_show_test_dummy_encryption(struct seq_file *seq, char sep,
854 					struct super_block *sb)
855 {
856 	const union fscrypt_policy *policy = fscrypt_get_dummy_policy(sb);
857 	int vers;
858 
859 	if (!policy)
860 		return;
861 
862 	vers = policy->version;
863 	if (vers == FSCRYPT_POLICY_V1) /* Handle numbering quirk */
864 		vers = 1;
865 
866 	seq_printf(seq, "%ctest_dummy_encryption=v%d", sep, vers);
867 }
868 EXPORT_SYMBOL_GPL(fscrypt_show_test_dummy_encryption);
869