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