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_inode_info * ci)42 static unsigned int fscrypt_get_dun_bytes(const struct fscrypt_inode_info *ci)
43 {
44 const struct super_block *sb = ci->ci_inode->i_sb;
45 unsigned int flags = fscrypt_policy_flags(&ci->ci_policy);
46 int dun_bits;
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 data unit index */
58 dun_bits = fscrypt_max_file_dun_bits(sb, ci->ci_data_unit_bits);
59 return DIV_ROUND_UP(dun_bits, 8);
60 }
61
62 /*
63 * Log a message when starting to use blk-crypto (native) or blk-crypto-fallback
64 * for an encryption mode for the first time. This is the blk-crypto
65 * counterpart to the message logged when starting to use the crypto API for the
66 * first time. A limitation is that these messages don't convey which specific
67 * filesystems or files are using each implementation. However, *usually*
68 * systems use just one implementation per mode, which makes these messages
69 * helpful for debugging problems where the "wrong" implementation is used.
70 */
fscrypt_log_blk_crypto_impl(struct fscrypt_mode * mode,struct block_device ** devs,unsigned int num_devs,const struct blk_crypto_config * cfg)71 static void fscrypt_log_blk_crypto_impl(struct fscrypt_mode *mode,
72 struct block_device **devs,
73 unsigned int num_devs,
74 const struct blk_crypto_config *cfg)
75 {
76 unsigned int i;
77
78 for (i = 0; i < num_devs; i++) {
79 if (!IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) ||
80 blk_crypto_config_supported_natively(devs[i], cfg)) {
81 if (!xchg(&mode->logged_blk_crypto_native, 1))
82 pr_info("fscrypt: %s using blk-crypto (native)\n",
83 mode->friendly_name);
84 } else if (!xchg(&mode->logged_blk_crypto_fallback, 1)) {
85 pr_info("fscrypt: %s using blk-crypto-fallback\n",
86 mode->friendly_name);
87 }
88 }
89 }
90
91 /* Enable inline encryption for this file if supported. */
fscrypt_select_encryption_impl(struct fscrypt_inode_info * ci,bool is_hw_wrapped_key)92 int fscrypt_select_encryption_impl(struct fscrypt_inode_info *ci,
93 bool is_hw_wrapped_key)
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 = 1U << ci->ci_data_unit_bits;
133 crypto_cfg.dun_bytes = fscrypt_get_dun_bytes(ci);
134 crypto_cfg.key_type =
135 is_hw_wrapped_key ? BLK_CRYPTO_KEY_TYPE_HW_WRAPPED :
136 BLK_CRYPTO_KEY_TYPE_STANDARD;
137
138 devs = fscrypt_get_devices(sb, &num_devs);
139 if (IS_ERR(devs))
140 return PTR_ERR(devs);
141
142 for (i = 0; i < num_devs; i++) {
143 if (!blk_crypto_config_supported(devs[i], &crypto_cfg))
144 goto out_free_devs;
145 }
146
147 fscrypt_log_blk_crypto_impl(ci->ci_mode, devs, num_devs, &crypto_cfg);
148
149 ci->ci_inlinecrypt = true;
150 out_free_devs:
151 kfree(devs);
152
153 return 0;
154 }
155
fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key * prep_key,const u8 * raw_key,size_t raw_key_size,bool is_hw_wrapped,const struct fscrypt_inode_info * ci)156 int fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key *prep_key,
157 const u8 *raw_key, size_t raw_key_size,
158 bool is_hw_wrapped,
159 const struct fscrypt_inode_info *ci)
160 {
161 const struct inode *inode = ci->ci_inode;
162 struct super_block *sb = inode->i_sb;
163 enum blk_crypto_mode_num crypto_mode = ci->ci_mode->blk_crypto_mode;
164 enum blk_crypto_key_type key_type = is_hw_wrapped ?
165 BLK_CRYPTO_KEY_TYPE_HW_WRAPPED : BLK_CRYPTO_KEY_TYPE_STANDARD;
166 struct blk_crypto_key *blk_key;
167 struct block_device **devs;
168 unsigned int num_devs;
169 unsigned int i;
170 int err;
171
172 blk_key = kmalloc(sizeof(*blk_key), GFP_KERNEL);
173 if (!blk_key)
174 return -ENOMEM;
175
176 err = blk_crypto_init_key(blk_key, raw_key, raw_key_size, key_type,
177 crypto_mode, fscrypt_get_dun_bytes(ci),
178 1U << ci->ci_data_unit_bits);
179 if (err) {
180 fscrypt_err(inode, "error %d initializing blk-crypto key", err);
181 goto fail;
182 }
183
184 /* Start using blk-crypto on all the filesystem's block devices. */
185 devs = fscrypt_get_devices(sb, &num_devs);
186 if (IS_ERR(devs)) {
187 err = PTR_ERR(devs);
188 goto fail;
189 }
190 for (i = 0; i < num_devs; i++) {
191 err = blk_crypto_start_using_key(devs[i], blk_key);
192 if (err)
193 break;
194 }
195 kfree(devs);
196 if (err) {
197 fscrypt_err(inode, "error %d starting to use blk-crypto", err);
198 goto fail;
199 }
200
201 /*
202 * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
203 * I.e., here we publish ->blk_key with a RELEASE barrier so that
204 * concurrent tasks can ACQUIRE it. Note that this concurrency is only
205 * possible for per-mode keys, not for per-file keys.
206 */
207 smp_store_release(&prep_key->blk_key, blk_key);
208 return 0;
209
210 fail:
211 kfree_sensitive(blk_key);
212 return err;
213 }
214
fscrypt_destroy_inline_crypt_key(struct super_block * sb,struct fscrypt_prepared_key * prep_key)215 void fscrypt_destroy_inline_crypt_key(struct super_block *sb,
216 struct fscrypt_prepared_key *prep_key)
217 {
218 struct blk_crypto_key *blk_key = prep_key->blk_key;
219 struct block_device **devs;
220 unsigned int num_devs;
221 unsigned int i;
222
223 if (!blk_key)
224 return;
225
226 /* Evict the key from all the filesystem's block devices. */
227 devs = fscrypt_get_devices(sb, &num_devs);
228 if (!IS_ERR(devs)) {
229 for (i = 0; i < num_devs; i++)
230 blk_crypto_evict_key(devs[i], blk_key);
231 kfree(devs);
232 }
233 kfree_sensitive(blk_key);
234 }
235
236 /*
237 * Ask the inline encryption hardware to derive the software secret from a
238 * hardware-wrapped key. Returns -EOPNOTSUPP if hardware-wrapped keys aren't
239 * supported on this filesystem or hardware.
240 */
fscrypt_derive_sw_secret(struct super_block * sb,const u8 * wrapped_key,size_t wrapped_key_size,u8 sw_secret[BLK_CRYPTO_SW_SECRET_SIZE])241 int fscrypt_derive_sw_secret(struct super_block *sb,
242 const u8 *wrapped_key, size_t wrapped_key_size,
243 u8 sw_secret[BLK_CRYPTO_SW_SECRET_SIZE])
244 {
245 int err;
246
247 /* The filesystem must be mounted with -o inlinecrypt. */
248 if (!(sb->s_flags & SB_INLINECRYPT)) {
249 fscrypt_warn(NULL,
250 "%s: filesystem not mounted with inlinecrypt\n",
251 sb->s_id);
252 return -EOPNOTSUPP;
253 }
254
255 err = blk_crypto_derive_sw_secret(sb->s_bdev, wrapped_key,
256 wrapped_key_size, sw_secret);
257 if (err == -EOPNOTSUPP)
258 fscrypt_warn(NULL,
259 "%s: block device doesn't support hardware-wrapped keys\n",
260 sb->s_id);
261 return err;
262 }
263
__fscrypt_inode_uses_inline_crypto(const struct inode * inode)264 bool __fscrypt_inode_uses_inline_crypto(const struct inode *inode)
265 {
266 return inode->i_crypt_info->ci_inlinecrypt;
267 }
268 EXPORT_SYMBOL_GPL(__fscrypt_inode_uses_inline_crypto);
269
fscrypt_generate_dun(const struct fscrypt_inode_info * ci,u64 lblk_num,u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])270 static void fscrypt_generate_dun(const struct fscrypt_inode_info *ci,
271 u64 lblk_num,
272 u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
273 {
274 u64 index = lblk_num << ci->ci_data_units_per_block_bits;
275 union fscrypt_iv iv;
276 int i;
277
278 fscrypt_generate_iv(&iv, index, ci);
279
280 BUILD_BUG_ON(FSCRYPT_MAX_IV_SIZE > BLK_CRYPTO_MAX_IV_SIZE);
281 memset(dun, 0, BLK_CRYPTO_MAX_IV_SIZE);
282 for (i = 0; i < ci->ci_mode->ivsize/sizeof(dun[0]); i++)
283 dun[i] = le64_to_cpu(iv.dun[i]);
284 }
285
286 /**
287 * fscrypt_set_bio_crypt_ctx() - prepare a file contents bio for inline crypto
288 * @bio: a bio which will eventually be submitted to the file
289 * @inode: the file's inode
290 * @first_lblk: the first file logical block number in the I/O
291 * @gfp_mask: memory allocation flags - these must be a waiting mask so that
292 * bio_crypt_set_ctx can't fail.
293 *
294 * If the contents of the file should be encrypted (or decrypted) with inline
295 * encryption, then assign the appropriate encryption context to the bio.
296 *
297 * Normally the bio should be newly allocated (i.e. no pages added yet), as
298 * otherwise fscrypt_mergeable_bio() won't work as intended.
299 *
300 * The encryption context will be freed automatically when the bio is freed.
301 *
302 * This function also handles setting bi_skip_dm_default_key when needed.
303 */
fscrypt_set_bio_crypt_ctx(struct bio * bio,const struct inode * inode,u64 first_lblk,gfp_t gfp_mask)304 void fscrypt_set_bio_crypt_ctx(struct bio *bio, const struct inode *inode,
305 u64 first_lblk, gfp_t gfp_mask)
306 {
307 const struct fscrypt_inode_info *ci;
308 u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
309
310 if (fscrypt_inode_should_skip_dm_default_key(inode))
311 bio_set_skip_dm_default_key(bio);
312
313 if (!fscrypt_inode_uses_inline_crypto(inode))
314 return;
315 ci = inode->i_crypt_info;
316
317 fscrypt_generate_dun(ci, first_lblk, dun);
318 bio_crypt_set_ctx(bio, ci->ci_enc_key.blk_key, dun, gfp_mask);
319 }
320 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx);
321
322 /* 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)323 static bool bh_get_inode_and_lblk_num(const struct buffer_head *bh,
324 const struct inode **inode_ret,
325 u64 *lblk_num_ret)
326 {
327 struct folio *folio = bh->b_folio;
328 const struct address_space *mapping;
329 const struct inode *inode;
330
331 /*
332 * The ext4 journal (jbd2) can submit a buffer_head it directly created
333 * for a non-pagecache page. fscrypt doesn't care about these.
334 */
335 mapping = folio_mapping(folio);
336 if (!mapping)
337 return false;
338 inode = mapping->host;
339
340 *inode_ret = inode;
341 *lblk_num_ret = ((u64)folio->index << (PAGE_SHIFT - inode->i_blkbits)) +
342 (bh_offset(bh) >> inode->i_blkbits);
343 return true;
344 }
345
346 /**
347 * fscrypt_set_bio_crypt_ctx_bh() - prepare a file contents bio for inline
348 * crypto
349 * @bio: a bio which will eventually be submitted to the file
350 * @first_bh: the first buffer_head for which I/O will be submitted
351 * @gfp_mask: memory allocation flags
352 *
353 * Same as fscrypt_set_bio_crypt_ctx(), except this takes a buffer_head instead
354 * of an inode and block number directly.
355 */
fscrypt_set_bio_crypt_ctx_bh(struct bio * bio,const struct buffer_head * first_bh,gfp_t gfp_mask)356 void fscrypt_set_bio_crypt_ctx_bh(struct bio *bio,
357 const struct buffer_head *first_bh,
358 gfp_t gfp_mask)
359 {
360 const struct inode *inode;
361 u64 first_lblk;
362
363 if (bh_get_inode_and_lblk_num(first_bh, &inode, &first_lblk))
364 fscrypt_set_bio_crypt_ctx(bio, inode, first_lblk, gfp_mask);
365 }
366 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx_bh);
367
368 /**
369 * fscrypt_mergeable_bio() - test whether data can be added to a bio
370 * @bio: the bio being built up
371 * @inode: the inode for the next part of the I/O
372 * @next_lblk: the next file logical block number in the I/O
373 *
374 * When building a bio which may contain data which should undergo inline
375 * encryption (or decryption) via fscrypt, filesystems should call this function
376 * to ensure that the resulting bio contains only contiguous data unit numbers.
377 * This will return false if the next part of the I/O cannot be merged with the
378 * bio because either the encryption key would be different or the encryption
379 * data unit numbers would be discontiguous.
380 *
381 * fscrypt_set_bio_crypt_ctx() must have already been called on the bio.
382 *
383 * This function isn't required in cases where crypto-mergeability is ensured in
384 * another way, such as I/O targeting only a single file (and thus a single key)
385 * combined with fscrypt_limit_io_blocks() to ensure DUN contiguity.
386 *
387 * This function also returns false if the next part of the I/O would need to
388 * have a different value for the bi_skip_dm_default_key flag.
389 *
390 * Return: true iff the I/O is mergeable
391 */
fscrypt_mergeable_bio(struct bio * bio,const struct inode * inode,u64 next_lblk)392 bool fscrypt_mergeable_bio(struct bio *bio, const struct inode *inode,
393 u64 next_lblk)
394 {
395 const struct bio_crypt_ctx *bc = bio->bi_crypt_context;
396 u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
397
398 if (!!bc != fscrypt_inode_uses_inline_crypto(inode))
399 return false;
400 if (bio_should_skip_dm_default_key(bio) !=
401 fscrypt_inode_should_skip_dm_default_key(inode))
402 return false;
403 if (!bc)
404 return true;
405
406 /*
407 * Comparing the key pointers is good enough, as all I/O for each key
408 * uses the same pointer. I.e., there's currently no need to support
409 * merging requests where the keys are the same but the pointers differ.
410 */
411 if (bc->bc_key != inode->i_crypt_info->ci_enc_key.blk_key)
412 return false;
413
414 fscrypt_generate_dun(inode->i_crypt_info, next_lblk, next_dun);
415 return bio_crypt_dun_is_contiguous(bc, bio->bi_iter.bi_size, next_dun);
416 }
417 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio);
418
419 /**
420 * fscrypt_mergeable_bio_bh() - test whether data can be added to a bio
421 * @bio: the bio being built up
422 * @next_bh: the next buffer_head for which I/O will be submitted
423 *
424 * Same as fscrypt_mergeable_bio(), except this takes a buffer_head instead of
425 * an inode and block number directly.
426 *
427 * Return: true iff the I/O is mergeable
428 */
fscrypt_mergeable_bio_bh(struct bio * bio,const struct buffer_head * next_bh)429 bool fscrypt_mergeable_bio_bh(struct bio *bio,
430 const struct buffer_head *next_bh)
431 {
432 const struct inode *inode;
433 u64 next_lblk;
434
435 if (!bh_get_inode_and_lblk_num(next_bh, &inode, &next_lblk))
436 return !bio->bi_crypt_context &&
437 !bio_should_skip_dm_default_key(bio);
438
439 return fscrypt_mergeable_bio(bio, inode, next_lblk);
440 }
441 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio_bh);
442
443 /**
444 * fscrypt_dio_supported() - check whether DIO (direct I/O) is supported on an
445 * inode, as far as encryption is concerned
446 * @inode: the inode in question
447 *
448 * Return: %true if there are no encryption constraints that prevent DIO from
449 * being supported; %false if DIO is unsupported. (Note that in the
450 * %true case, the filesystem might have other, non-encryption-related
451 * constraints that prevent DIO from actually being supported. Also, on
452 * encrypted files the filesystem is still responsible for only allowing
453 * DIO when requests are filesystem-block-aligned.)
454 */
fscrypt_dio_supported(struct inode * inode)455 bool fscrypt_dio_supported(struct inode *inode)
456 {
457 int err;
458
459 /* If the file is unencrypted, no veto from us. */
460 if (!fscrypt_needs_contents_encryption(inode))
461 return true;
462
463 /*
464 * We only support DIO with inline crypto, not fs-layer crypto.
465 *
466 * To determine whether the inode is using inline crypto, we have to set
467 * up the key if it wasn't already done. This is because in the current
468 * design of fscrypt, the decision of whether to use inline crypto or
469 * not isn't made until the inode's encryption key is being set up. In
470 * the DIO read/write case, the key will always be set up already, since
471 * the file will be open. But in the case of statx(), the key might not
472 * be set up yet, as the file might not have been opened yet.
473 */
474 err = fscrypt_require_key(inode);
475 if (err) {
476 /*
477 * Key unavailable or couldn't be set up. This edge case isn't
478 * worth worrying about; just report that DIO is unsupported.
479 */
480 return false;
481 }
482 return fscrypt_inode_uses_inline_crypto(inode);
483 }
484 EXPORT_SYMBOL_GPL(fscrypt_dio_supported);
485
486 /**
487 * fscrypt_limit_io_blocks() - limit I/O blocks to avoid discontiguous DUNs
488 * @inode: the file on which I/O is being done
489 * @lblk: the block at which the I/O is being started from
490 * @nr_blocks: the number of blocks we want to submit starting at @lblk
491 *
492 * Determine the limit to the number of blocks that can be submitted in a bio
493 * targeting @lblk without causing a data unit number (DUN) discontiguity.
494 *
495 * This is normally just @nr_blocks, as normally the DUNs just increment along
496 * with the logical blocks. (Or the file is not encrypted.)
497 *
498 * In rare cases, fscrypt can be using an IV generation method that allows the
499 * DUN to wrap around within logically contiguous blocks, and that wraparound
500 * will occur. If this happens, a value less than @nr_blocks will be returned
501 * so that the wraparound doesn't occur in the middle of a bio, which would
502 * cause encryption/decryption to produce wrong results.
503 *
504 * Return: the actual number of blocks that can be submitted
505 */
fscrypt_limit_io_blocks(const struct inode * inode,u64 lblk,u64 nr_blocks)506 u64 fscrypt_limit_io_blocks(const struct inode *inode, u64 lblk, u64 nr_blocks)
507 {
508 const struct fscrypt_inode_info *ci;
509 u32 dun;
510
511 if (!fscrypt_inode_uses_inline_crypto(inode))
512 return nr_blocks;
513
514 if (nr_blocks <= 1)
515 return nr_blocks;
516
517 ci = inode->i_crypt_info;
518 if (!(fscrypt_policy_flags(&ci->ci_policy) &
519 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32))
520 return nr_blocks;
521
522 /* With IV_INO_LBLK_32, the DUN can wrap around from U32_MAX to 0. */
523
524 dun = ci->ci_hashed_ino + lblk;
525
526 return min_t(u64, nr_blocks, (u64)U32_MAX + 1 - dun);
527 }
528 EXPORT_SYMBOL_GPL(fscrypt_limit_io_blocks);
529