xref: /openbmc/linux/fs/crypto/inline_crypt.c (revision 6715c98b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Inline encryption support for fscrypt
4  *
5  * Copyright 2019 Google LLC
6  */
7 
8 /*
9  * With "inline encryption", the block layer handles the decryption/encryption
10  * as part of the bio, instead of the filesystem doing the crypto itself via
11  * crypto API.  See Documentation/block/inline-encryption.rst.  fscrypt still
12  * provides the key and IV to use.
13  */
14 
15 #include <linux/blk-crypto.h>
16 #include <linux/blkdev.h>
17 #include <linux/buffer_head.h>
18 #include <linux/sched/mm.h>
19 #include <linux/slab.h>
20 #include <linux/uio.h>
21 
22 #include "fscrypt_private.h"
23 
fscrypt_get_devices(struct super_block * sb,unsigned int * num_devs)24 static struct block_device **fscrypt_get_devices(struct super_block *sb,
25 						 unsigned int *num_devs)
26 {
27 	struct block_device **devs;
28 
29 	if (sb->s_cop->get_devices) {
30 		devs = sb->s_cop->get_devices(sb, num_devs);
31 		if (devs)
32 			return devs;
33 	}
34 	devs = kmalloc(sizeof(*devs), GFP_KERNEL);
35 	if (!devs)
36 		return ERR_PTR(-ENOMEM);
37 	devs[0] = sb->s_bdev;
38 	*num_devs = 1;
39 	return devs;
40 }
41 
fscrypt_get_dun_bytes(const struct fscrypt_info * ci)42 static unsigned int fscrypt_get_dun_bytes(const struct fscrypt_info *ci)
43 {
44 	struct super_block *sb = ci->ci_inode->i_sb;
45 	unsigned int flags = fscrypt_policy_flags(&ci->ci_policy);
46 	int ino_bits = 64, lblk_bits = 64;
47 
48 	if (flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY)
49 		return offsetofend(union fscrypt_iv, nonce);
50 
51 	if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64)
52 		return sizeof(__le64);
53 
54 	if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)
55 		return sizeof(__le32);
56 
57 	/* Default case: IVs are just the file logical block number */
58 	if (sb->s_cop->get_ino_and_lblk_bits)
59 		sb->s_cop->get_ino_and_lblk_bits(sb, &ino_bits, &lblk_bits);
60 	return DIV_ROUND_UP(lblk_bits, 8);
61 }
62 
63 /*
64  * Log a message when starting to use blk-crypto (native) or blk-crypto-fallback
65  * for an encryption mode for the first time.  This is the blk-crypto
66  * counterpart to the message logged when starting to use the crypto API for the
67  * first time.  A limitation is that these messages don't convey which specific
68  * filesystems or files are using each implementation.  However, *usually*
69  * systems use just one implementation per mode, which makes these messages
70  * helpful for debugging problems where the "wrong" implementation is used.
71  */
fscrypt_log_blk_crypto_impl(struct fscrypt_mode * mode,struct block_device ** devs,unsigned int num_devs,const struct blk_crypto_config * cfg)72 static void fscrypt_log_blk_crypto_impl(struct fscrypt_mode *mode,
73 					struct block_device **devs,
74 					unsigned int num_devs,
75 					const struct blk_crypto_config *cfg)
76 {
77 	unsigned int i;
78 
79 	for (i = 0; i < num_devs; i++) {
80 		if (!IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) ||
81 		    blk_crypto_config_supported_natively(devs[i], cfg)) {
82 			if (!xchg(&mode->logged_blk_crypto_native, 1))
83 				pr_info("fscrypt: %s using blk-crypto (native)\n",
84 					mode->friendly_name);
85 		} else if (!xchg(&mode->logged_blk_crypto_fallback, 1)) {
86 			pr_info("fscrypt: %s using blk-crypto-fallback\n",
87 				mode->friendly_name);
88 		}
89 	}
90 }
91 
92 /* Enable inline encryption for this file if supported. */
fscrypt_select_encryption_impl(struct fscrypt_info * ci)93 int fscrypt_select_encryption_impl(struct fscrypt_info *ci)
94 {
95 	const struct inode *inode = ci->ci_inode;
96 	struct super_block *sb = inode->i_sb;
97 	struct blk_crypto_config crypto_cfg;
98 	struct block_device **devs;
99 	unsigned int num_devs;
100 	unsigned int i;
101 
102 	/* The file must need contents encryption, not filenames encryption */
103 	if (!S_ISREG(inode->i_mode))
104 		return 0;
105 
106 	/* The crypto mode must have a blk-crypto counterpart */
107 	if (ci->ci_mode->blk_crypto_mode == BLK_ENCRYPTION_MODE_INVALID)
108 		return 0;
109 
110 	/* The filesystem must be mounted with -o inlinecrypt */
111 	if (!(sb->s_flags & SB_INLINECRYPT))
112 		return 0;
113 
114 	/*
115 	 * When a page contains multiple logically contiguous filesystem blocks,
116 	 * some filesystem code only calls fscrypt_mergeable_bio() for the first
117 	 * block in the page. This is fine for most of fscrypt's IV generation
118 	 * strategies, where contiguous blocks imply contiguous IVs. But it
119 	 * doesn't work with IV_INO_LBLK_32. For now, simply exclude
120 	 * IV_INO_LBLK_32 with blocksize != PAGE_SIZE from inline encryption.
121 	 */
122 	if ((fscrypt_policy_flags(&ci->ci_policy) &
123 	     FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
124 	    sb->s_blocksize != PAGE_SIZE)
125 		return 0;
126 
127 	/*
128 	 * On all the filesystem's block devices, blk-crypto must support the
129 	 * crypto configuration that the file would use.
130 	 */
131 	crypto_cfg.crypto_mode = ci->ci_mode->blk_crypto_mode;
132 	crypto_cfg.data_unit_size = sb->s_blocksize;
133 	crypto_cfg.dun_bytes = fscrypt_get_dun_bytes(ci);
134 
135 	devs = fscrypt_get_devices(sb, &num_devs);
136 	if (IS_ERR(devs))
137 		return PTR_ERR(devs);
138 
139 	for (i = 0; i < num_devs; i++) {
140 		if (!blk_crypto_config_supported(devs[i], &crypto_cfg))
141 			goto out_free_devs;
142 	}
143 
144 	fscrypt_log_blk_crypto_impl(ci->ci_mode, devs, num_devs, &crypto_cfg);
145 
146 	ci->ci_inlinecrypt = true;
147 out_free_devs:
148 	kfree(devs);
149 
150 	return 0;
151 }
152 
fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key * prep_key,const u8 * raw_key,const struct fscrypt_info * ci)153 int fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key *prep_key,
154 				     const u8 *raw_key,
155 				     const struct fscrypt_info *ci)
156 {
157 	const struct inode *inode = ci->ci_inode;
158 	struct super_block *sb = inode->i_sb;
159 	enum blk_crypto_mode_num crypto_mode = ci->ci_mode->blk_crypto_mode;
160 	struct blk_crypto_key *blk_key;
161 	struct block_device **devs;
162 	unsigned int num_devs;
163 	unsigned int i;
164 	int err;
165 
166 	blk_key = kmalloc(sizeof(*blk_key), GFP_KERNEL);
167 	if (!blk_key)
168 		return -ENOMEM;
169 
170 	err = blk_crypto_init_key(blk_key, raw_key, crypto_mode,
171 				  fscrypt_get_dun_bytes(ci), sb->s_blocksize);
172 	if (err) {
173 		fscrypt_err(inode, "error %d initializing blk-crypto key", err);
174 		goto fail;
175 	}
176 
177 	/* Start using blk-crypto on all the filesystem's block devices. */
178 	devs = fscrypt_get_devices(sb, &num_devs);
179 	if (IS_ERR(devs)) {
180 		err = PTR_ERR(devs);
181 		goto fail;
182 	}
183 	for (i = 0; i < num_devs; i++) {
184 		err = blk_crypto_start_using_key(devs[i], blk_key);
185 		if (err)
186 			break;
187 	}
188 	kfree(devs);
189 	if (err) {
190 		fscrypt_err(inode, "error %d starting to use blk-crypto", err);
191 		goto fail;
192 	}
193 
194 	/*
195 	 * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
196 	 * I.e., here we publish ->blk_key with a RELEASE barrier so that
197 	 * concurrent tasks can ACQUIRE it.  Note that this concurrency is only
198 	 * possible for per-mode keys, not for per-file keys.
199 	 */
200 	smp_store_release(&prep_key->blk_key, blk_key);
201 	return 0;
202 
203 fail:
204 	kfree_sensitive(blk_key);
205 	return err;
206 }
207 
fscrypt_destroy_inline_crypt_key(struct super_block * sb,struct fscrypt_prepared_key * prep_key)208 void fscrypt_destroy_inline_crypt_key(struct super_block *sb,
209 				      struct fscrypt_prepared_key *prep_key)
210 {
211 	struct blk_crypto_key *blk_key = prep_key->blk_key;
212 	struct block_device **devs;
213 	unsigned int num_devs;
214 	unsigned int i;
215 
216 	if (!blk_key)
217 		return;
218 
219 	/* Evict the key from all the filesystem's block devices. */
220 	devs = fscrypt_get_devices(sb, &num_devs);
221 	if (!IS_ERR(devs)) {
222 		for (i = 0; i < num_devs; i++)
223 			blk_crypto_evict_key(devs[i], blk_key);
224 		kfree(devs);
225 	}
226 	kfree_sensitive(blk_key);
227 }
228 
__fscrypt_inode_uses_inline_crypto(const struct inode * inode)229 bool __fscrypt_inode_uses_inline_crypto(const struct inode *inode)
230 {
231 	return inode->i_crypt_info->ci_inlinecrypt;
232 }
233 EXPORT_SYMBOL_GPL(__fscrypt_inode_uses_inline_crypto);
234 
fscrypt_generate_dun(const struct fscrypt_info * ci,u64 lblk_num,u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])235 static void fscrypt_generate_dun(const struct fscrypt_info *ci, u64 lblk_num,
236 				 u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
237 {
238 	union fscrypt_iv iv;
239 	int i;
240 
241 	fscrypt_generate_iv(&iv, lblk_num, ci);
242 
243 	BUILD_BUG_ON(FSCRYPT_MAX_IV_SIZE > BLK_CRYPTO_MAX_IV_SIZE);
244 	memset(dun, 0, BLK_CRYPTO_MAX_IV_SIZE);
245 	for (i = 0; i < ci->ci_mode->ivsize/sizeof(dun[0]); i++)
246 		dun[i] = le64_to_cpu(iv.dun[i]);
247 }
248 
249 /**
250  * fscrypt_set_bio_crypt_ctx() - prepare a file contents bio for inline crypto
251  * @bio: a bio which will eventually be submitted to the file
252  * @inode: the file's inode
253  * @first_lblk: the first file logical block number in the I/O
254  * @gfp_mask: memory allocation flags - these must be a waiting mask so that
255  *					bio_crypt_set_ctx can't fail.
256  *
257  * If the contents of the file should be encrypted (or decrypted) with inline
258  * encryption, then assign the appropriate encryption context to the bio.
259  *
260  * Normally the bio should be newly allocated (i.e. no pages added yet), as
261  * otherwise fscrypt_mergeable_bio() won't work as intended.
262  *
263  * The encryption context will be freed automatically when the bio is freed.
264  */
fscrypt_set_bio_crypt_ctx(struct bio * bio,const struct inode * inode,u64 first_lblk,gfp_t gfp_mask)265 void fscrypt_set_bio_crypt_ctx(struct bio *bio, const struct inode *inode,
266 			       u64 first_lblk, gfp_t gfp_mask)
267 {
268 	const struct fscrypt_info *ci;
269 	u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
270 
271 	if (!fscrypt_inode_uses_inline_crypto(inode))
272 		return;
273 	ci = inode->i_crypt_info;
274 
275 	fscrypt_generate_dun(ci, first_lblk, dun);
276 	bio_crypt_set_ctx(bio, ci->ci_enc_key.blk_key, dun, gfp_mask);
277 }
278 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx);
279 
280 /* Extract the inode and logical block number from a buffer_head. */
bh_get_inode_and_lblk_num(const struct buffer_head * bh,const struct inode ** inode_ret,u64 * lblk_num_ret)281 static bool bh_get_inode_and_lblk_num(const struct buffer_head *bh,
282 				      const struct inode **inode_ret,
283 				      u64 *lblk_num_ret)
284 {
285 	struct page *page = bh->b_page;
286 	const struct address_space *mapping;
287 	const struct inode *inode;
288 
289 	/*
290 	 * The ext4 journal (jbd2) can submit a buffer_head it directly created
291 	 * for a non-pagecache page.  fscrypt doesn't care about these.
292 	 */
293 	mapping = page_mapping(page);
294 	if (!mapping)
295 		return false;
296 	inode = mapping->host;
297 
298 	*inode_ret = inode;
299 	*lblk_num_ret = ((u64)page->index << (PAGE_SHIFT - inode->i_blkbits)) +
300 			(bh_offset(bh) >> inode->i_blkbits);
301 	return true;
302 }
303 
304 /**
305  * fscrypt_set_bio_crypt_ctx_bh() - prepare a file contents bio for inline
306  *				    crypto
307  * @bio: a bio which will eventually be submitted to the file
308  * @first_bh: the first buffer_head for which I/O will be submitted
309  * @gfp_mask: memory allocation flags
310  *
311  * Same as fscrypt_set_bio_crypt_ctx(), except this takes a buffer_head instead
312  * of an inode and block number directly.
313  */
fscrypt_set_bio_crypt_ctx_bh(struct bio * bio,const struct buffer_head * first_bh,gfp_t gfp_mask)314 void fscrypt_set_bio_crypt_ctx_bh(struct bio *bio,
315 				  const struct buffer_head *first_bh,
316 				  gfp_t gfp_mask)
317 {
318 	const struct inode *inode;
319 	u64 first_lblk;
320 
321 	if (bh_get_inode_and_lblk_num(first_bh, &inode, &first_lblk))
322 		fscrypt_set_bio_crypt_ctx(bio, inode, first_lblk, gfp_mask);
323 }
324 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx_bh);
325 
326 /**
327  * fscrypt_mergeable_bio() - test whether data can be added to a bio
328  * @bio: the bio being built up
329  * @inode: the inode for the next part of the I/O
330  * @next_lblk: the next file logical block number in the I/O
331  *
332  * When building a bio which may contain data which should undergo inline
333  * encryption (or decryption) via fscrypt, filesystems should call this function
334  * to ensure that the resulting bio contains only contiguous data unit numbers.
335  * This will return false if the next part of the I/O cannot be merged with the
336  * bio because either the encryption key would be different or the encryption
337  * data unit numbers would be discontiguous.
338  *
339  * fscrypt_set_bio_crypt_ctx() must have already been called on the bio.
340  *
341  * This function isn't required in cases where crypto-mergeability is ensured in
342  * another way, such as I/O targeting only a single file (and thus a single key)
343  * combined with fscrypt_limit_io_blocks() to ensure DUN contiguity.
344  *
345  * Return: true iff the I/O is mergeable
346  */
fscrypt_mergeable_bio(struct bio * bio,const struct inode * inode,u64 next_lblk)347 bool fscrypt_mergeable_bio(struct bio *bio, const struct inode *inode,
348 			   u64 next_lblk)
349 {
350 	const struct bio_crypt_ctx *bc = bio->bi_crypt_context;
351 	u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
352 
353 	if (!!bc != fscrypt_inode_uses_inline_crypto(inode))
354 		return false;
355 	if (!bc)
356 		return true;
357 
358 	/*
359 	 * Comparing the key pointers is good enough, as all I/O for each key
360 	 * uses the same pointer.  I.e., there's currently no need to support
361 	 * merging requests where the keys are the same but the pointers differ.
362 	 */
363 	if (bc->bc_key != inode->i_crypt_info->ci_enc_key.blk_key)
364 		return false;
365 
366 	fscrypt_generate_dun(inode->i_crypt_info, next_lblk, next_dun);
367 	return bio_crypt_dun_is_contiguous(bc, bio->bi_iter.bi_size, next_dun);
368 }
369 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio);
370 
371 /**
372  * fscrypt_mergeable_bio_bh() - test whether data can be added to a bio
373  * @bio: the bio being built up
374  * @next_bh: the next buffer_head for which I/O will be submitted
375  *
376  * Same as fscrypt_mergeable_bio(), except this takes a buffer_head instead of
377  * an inode and block number directly.
378  *
379  * Return: true iff the I/O is mergeable
380  */
fscrypt_mergeable_bio_bh(struct bio * bio,const struct buffer_head * next_bh)381 bool fscrypt_mergeable_bio_bh(struct bio *bio,
382 			      const struct buffer_head *next_bh)
383 {
384 	const struct inode *inode;
385 	u64 next_lblk;
386 
387 	if (!bh_get_inode_and_lblk_num(next_bh, &inode, &next_lblk))
388 		return !bio->bi_crypt_context;
389 
390 	return fscrypt_mergeable_bio(bio, inode, next_lblk);
391 }
392 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio_bh);
393 
394 /**
395  * fscrypt_dio_supported() - check whether DIO (direct I/O) is supported on an
396  *			     inode, as far as encryption is concerned
397  * @inode: the inode in question
398  *
399  * Return: %true if there are no encryption constraints that prevent DIO from
400  *	   being supported; %false if DIO is unsupported.  (Note that in the
401  *	   %true case, the filesystem might have other, non-encryption-related
402  *	   constraints that prevent DIO from actually being supported.  Also, on
403  *	   encrypted files the filesystem is still responsible for only allowing
404  *	   DIO when requests are filesystem-block-aligned.)
405  */
fscrypt_dio_supported(struct inode * inode)406 bool fscrypt_dio_supported(struct inode *inode)
407 {
408 	int err;
409 
410 	/* If the file is unencrypted, no veto from us. */
411 	if (!fscrypt_needs_contents_encryption(inode))
412 		return true;
413 
414 	/*
415 	 * We only support DIO with inline crypto, not fs-layer crypto.
416 	 *
417 	 * To determine whether the inode is using inline crypto, we have to set
418 	 * up the key if it wasn't already done.  This is because in the current
419 	 * design of fscrypt, the decision of whether to use inline crypto or
420 	 * not isn't made until the inode's encryption key is being set up.  In
421 	 * the DIO read/write case, the key will always be set up already, since
422 	 * the file will be open.  But in the case of statx(), the key might not
423 	 * be set up yet, as the file might not have been opened yet.
424 	 */
425 	err = fscrypt_require_key(inode);
426 	if (err) {
427 		/*
428 		 * Key unavailable or couldn't be set up.  This edge case isn't
429 		 * worth worrying about; just report that DIO is unsupported.
430 		 */
431 		return false;
432 	}
433 	return fscrypt_inode_uses_inline_crypto(inode);
434 }
435 EXPORT_SYMBOL_GPL(fscrypt_dio_supported);
436 
437 /**
438  * fscrypt_limit_io_blocks() - limit I/O blocks to avoid discontiguous DUNs
439  * @inode: the file on which I/O is being done
440  * @lblk: the block at which the I/O is being started from
441  * @nr_blocks: the number of blocks we want to submit starting at @lblk
442  *
443  * Determine the limit to the number of blocks that can be submitted in a bio
444  * targeting @lblk without causing a data unit number (DUN) discontiguity.
445  *
446  * This is normally just @nr_blocks, as normally the DUNs just increment along
447  * with the logical blocks.  (Or the file is not encrypted.)
448  *
449  * In rare cases, fscrypt can be using an IV generation method that allows the
450  * DUN to wrap around within logically contiguous blocks, and that wraparound
451  * will occur.  If this happens, a value less than @nr_blocks will be returned
452  * so that the wraparound doesn't occur in the middle of a bio, which would
453  * cause encryption/decryption to produce wrong results.
454  *
455  * Return: the actual number of blocks that can be submitted
456  */
fscrypt_limit_io_blocks(const struct inode * inode,u64 lblk,u64 nr_blocks)457 u64 fscrypt_limit_io_blocks(const struct inode *inode, u64 lblk, u64 nr_blocks)
458 {
459 	const struct fscrypt_info *ci;
460 	u32 dun;
461 
462 	if (!fscrypt_inode_uses_inline_crypto(inode))
463 		return nr_blocks;
464 
465 	if (nr_blocks <= 1)
466 		return nr_blocks;
467 
468 	ci = inode->i_crypt_info;
469 	if (!(fscrypt_policy_flags(&ci->ci_policy) &
470 	      FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32))
471 		return nr_blocks;
472 
473 	/* With IV_INO_LBLK_32, the DUN can wrap around from U32_MAX to 0. */
474 
475 	dun = ci->ci_hashed_ino + lblk;
476 
477 	return min_t(u64, nr_blocks, (u64)U32_MAX + 1 - dun);
478 }
479 EXPORT_SYMBOL_GPL(fscrypt_limit_io_blocks);
480