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