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