1 // SPDX-License-Identifier: GPL-2.0
3 * Inline encryption support for fscrypt
5 * Copyright 2019 Google LLC
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.
15 #include <linux/blk-crypto-profile.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>
22 #include "fscrypt_private.h"
24 static struct block_device **fscrypt_get_devices(struct super_block *sb,
25 unsigned int *num_devs)
27 struct block_device **devs;
29 if (sb->s_cop->get_devices) {
30 devs = sb->s_cop->get_devices(sb, num_devs);
34 devs = kmalloc(sizeof(*devs), GFP_KERNEL);
36 return ERR_PTR(-ENOMEM);
42 static unsigned int fscrypt_get_dun_bytes(const struct fscrypt_info *ci)
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;
48 if (flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY)
49 return offsetofend(union fscrypt_iv, nonce);
51 if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64)
52 return sizeof(__le64);
54 if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)
55 return sizeof(__le32);
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);
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.
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)
79 for (i = 0; i < num_devs; i++) {
80 struct request_queue *q = bdev_get_queue(devs[i]);
82 if (!IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) ||
83 __blk_crypto_cfg_supported(q->crypto_profile, cfg)) {
84 if (!xchg(&mode->logged_blk_crypto_native, 1))
85 pr_info("fscrypt: %s using blk-crypto (native)\n",
87 } else if (!xchg(&mode->logged_blk_crypto_fallback, 1)) {
88 pr_info("fscrypt: %s using blk-crypto-fallback\n",
94 /* Enable inline encryption for this file if supported. */
95 int fscrypt_select_encryption_impl(struct fscrypt_info *ci)
97 const struct inode *inode = ci->ci_inode;
98 struct super_block *sb = inode->i_sb;
99 struct blk_crypto_config crypto_cfg;
100 struct block_device **devs;
101 unsigned int num_devs;
104 /* The file must need contents encryption, not filenames encryption */
105 if (!S_ISREG(inode->i_mode))
108 /* The crypto mode must have a blk-crypto counterpart */
109 if (ci->ci_mode->blk_crypto_mode == BLK_ENCRYPTION_MODE_INVALID)
112 /* The filesystem must be mounted with -o inlinecrypt */
113 if (!(sb->s_flags & SB_INLINECRYPT))
117 * When a page contains multiple logically contiguous filesystem blocks,
118 * some filesystem code only calls fscrypt_mergeable_bio() for the first
119 * block in the page. This is fine for most of fscrypt's IV generation
120 * strategies, where contiguous blocks imply contiguous IVs. But it
121 * doesn't work with IV_INO_LBLK_32. For now, simply exclude
122 * IV_INO_LBLK_32 with blocksize != PAGE_SIZE from inline encryption.
124 if ((fscrypt_policy_flags(&ci->ci_policy) &
125 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
126 sb->s_blocksize != PAGE_SIZE)
130 * On all the filesystem's block devices, blk-crypto must support the
131 * crypto configuration that the file would use.
133 crypto_cfg.crypto_mode = ci->ci_mode->blk_crypto_mode;
134 crypto_cfg.data_unit_size = sb->s_blocksize;
135 crypto_cfg.dun_bytes = fscrypt_get_dun_bytes(ci);
137 devs = fscrypt_get_devices(sb, &num_devs);
139 return PTR_ERR(devs);
141 for (i = 0; i < num_devs; i++) {
142 if (!blk_crypto_config_supported(bdev_get_queue(devs[i]),
147 fscrypt_log_blk_crypto_impl(ci->ci_mode, devs, num_devs, &crypto_cfg);
149 ci->ci_inlinecrypt = true;
156 int fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key *prep_key,
158 const struct fscrypt_info *ci)
160 const struct inode *inode = ci->ci_inode;
161 struct super_block *sb = inode->i_sb;
162 enum blk_crypto_mode_num crypto_mode = ci->ci_mode->blk_crypto_mode;
163 struct blk_crypto_key *blk_key;
164 struct block_device **devs;
165 unsigned int num_devs;
169 blk_key = kmalloc(sizeof(*blk_key), GFP_KERNEL);
173 err = blk_crypto_init_key(blk_key, raw_key, crypto_mode,
174 fscrypt_get_dun_bytes(ci), sb->s_blocksize);
176 fscrypt_err(inode, "error %d initializing blk-crypto key", err);
180 /* Start using blk-crypto on all the filesystem's block devices. */
181 devs = fscrypt_get_devices(sb, &num_devs);
186 for (i = 0; i < num_devs; i++) {
187 err = blk_crypto_start_using_key(blk_key,
188 bdev_get_queue(devs[i]));
194 fscrypt_err(inode, "error %d starting to use blk-crypto", err);
199 * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
200 * I.e., here we publish ->blk_key with a RELEASE barrier so that
201 * concurrent tasks can ACQUIRE it. Note that this concurrency is only
202 * possible for per-mode keys, not for per-file keys.
204 smp_store_release(&prep_key->blk_key, blk_key);
208 kfree_sensitive(blk_key);
212 void fscrypt_destroy_inline_crypt_key(struct super_block *sb,
213 struct fscrypt_prepared_key *prep_key)
215 struct blk_crypto_key *blk_key = prep_key->blk_key;
216 struct block_device **devs;
217 unsigned int num_devs;
223 /* Evict the key from all the filesystem's block devices. */
224 devs = fscrypt_get_devices(sb, &num_devs);
226 for (i = 0; i < num_devs; i++)
227 blk_crypto_evict_key(bdev_get_queue(devs[i]), blk_key);
230 kfree_sensitive(blk_key);
233 bool __fscrypt_inode_uses_inline_crypto(const struct inode *inode)
235 return inode->i_crypt_info->ci_inlinecrypt;
237 EXPORT_SYMBOL_GPL(__fscrypt_inode_uses_inline_crypto);
239 static void fscrypt_generate_dun(const struct fscrypt_info *ci, u64 lblk_num,
240 u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
245 fscrypt_generate_iv(&iv, lblk_num, ci);
247 BUILD_BUG_ON(FSCRYPT_MAX_IV_SIZE > BLK_CRYPTO_MAX_IV_SIZE);
248 memset(dun, 0, BLK_CRYPTO_MAX_IV_SIZE);
249 for (i = 0; i < ci->ci_mode->ivsize/sizeof(dun[0]); i++)
250 dun[i] = le64_to_cpu(iv.dun[i]);
254 * fscrypt_set_bio_crypt_ctx() - prepare a file contents bio for inline crypto
255 * @bio: a bio which will eventually be submitted to the file
256 * @inode: the file's inode
257 * @first_lblk: the first file logical block number in the I/O
258 * @gfp_mask: memory allocation flags - these must be a waiting mask so that
259 * bio_crypt_set_ctx can't fail.
261 * If the contents of the file should be encrypted (or decrypted) with inline
262 * encryption, then assign the appropriate encryption context to the bio.
264 * Normally the bio should be newly allocated (i.e. no pages added yet), as
265 * otherwise fscrypt_mergeable_bio() won't work as intended.
267 * The encryption context will be freed automatically when the bio is freed.
269 void fscrypt_set_bio_crypt_ctx(struct bio *bio, const struct inode *inode,
270 u64 first_lblk, gfp_t gfp_mask)
272 const struct fscrypt_info *ci;
273 u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
275 if (!fscrypt_inode_uses_inline_crypto(inode))
277 ci = inode->i_crypt_info;
279 fscrypt_generate_dun(ci, first_lblk, dun);
280 bio_crypt_set_ctx(bio, ci->ci_enc_key.blk_key, dun, gfp_mask);
282 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx);
284 /* Extract the inode and logical block number from a buffer_head. */
285 static bool bh_get_inode_and_lblk_num(const struct buffer_head *bh,
286 const struct inode **inode_ret,
289 struct page *page = bh->b_page;
290 const struct address_space *mapping;
291 const struct inode *inode;
294 * The ext4 journal (jbd2) can submit a buffer_head it directly created
295 * for a non-pagecache page. fscrypt doesn't care about these.
297 mapping = page_mapping(page);
300 inode = mapping->host;
303 *lblk_num_ret = ((u64)page->index << (PAGE_SHIFT - inode->i_blkbits)) +
304 (bh_offset(bh) >> inode->i_blkbits);
309 * fscrypt_set_bio_crypt_ctx_bh() - prepare a file contents bio for inline
311 * @bio: a bio which will eventually be submitted to the file
312 * @first_bh: the first buffer_head for which I/O will be submitted
313 * @gfp_mask: memory allocation flags
315 * Same as fscrypt_set_bio_crypt_ctx(), except this takes a buffer_head instead
316 * of an inode and block number directly.
318 void fscrypt_set_bio_crypt_ctx_bh(struct bio *bio,
319 const struct buffer_head *first_bh,
322 const struct inode *inode;
325 if (bh_get_inode_and_lblk_num(first_bh, &inode, &first_lblk))
326 fscrypt_set_bio_crypt_ctx(bio, inode, first_lblk, gfp_mask);
328 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx_bh);
331 * fscrypt_mergeable_bio() - test whether data can be added to a bio
332 * @bio: the bio being built up
333 * @inode: the inode for the next part of the I/O
334 * @next_lblk: the next file logical block number in the I/O
336 * When building a bio which may contain data which should undergo inline
337 * encryption (or decryption) via fscrypt, filesystems should call this function
338 * to ensure that the resulting bio contains only contiguous data unit numbers.
339 * This will return false if the next part of the I/O cannot be merged with the
340 * bio because either the encryption key would be different or the encryption
341 * data unit numbers would be discontiguous.
343 * fscrypt_set_bio_crypt_ctx() must have already been called on the bio.
345 * This function isn't required in cases where crypto-mergeability is ensured in
346 * another way, such as I/O targeting only a single file (and thus a single key)
347 * combined with fscrypt_limit_io_blocks() to ensure DUN contiguity.
349 * Return: true iff the I/O is mergeable
351 bool fscrypt_mergeable_bio(struct bio *bio, const struct inode *inode,
354 const struct bio_crypt_ctx *bc = bio->bi_crypt_context;
355 u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
357 if (!!bc != fscrypt_inode_uses_inline_crypto(inode))
363 * Comparing the key pointers is good enough, as all I/O for each key
364 * uses the same pointer. I.e., there's currently no need to support
365 * merging requests where the keys are the same but the pointers differ.
367 if (bc->bc_key != inode->i_crypt_info->ci_enc_key.blk_key)
370 fscrypt_generate_dun(inode->i_crypt_info, next_lblk, next_dun);
371 return bio_crypt_dun_is_contiguous(bc, bio->bi_iter.bi_size, next_dun);
373 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio);
376 * fscrypt_mergeable_bio_bh() - test whether data can be added to a bio
377 * @bio: the bio being built up
378 * @next_bh: the next buffer_head for which I/O will be submitted
380 * Same as fscrypt_mergeable_bio(), except this takes a buffer_head instead of
381 * an inode and block number directly.
383 * Return: true iff the I/O is mergeable
385 bool fscrypt_mergeable_bio_bh(struct bio *bio,
386 const struct buffer_head *next_bh)
388 const struct inode *inode;
391 if (!bh_get_inode_and_lblk_num(next_bh, &inode, &next_lblk))
392 return !bio->bi_crypt_context;
394 return fscrypt_mergeable_bio(bio, inode, next_lblk);
396 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio_bh);
399 * fscrypt_dio_supported() - check whether a DIO (direct I/O) request is
400 * supported as far as encryption is concerned
401 * @iocb: the file and position the I/O is targeting
402 * @iter: the I/O data segment(s)
404 * Return: %true if there are no encryption constraints that prevent DIO from
405 * being supported; %false if DIO is unsupported. (Note that in the
406 * %true case, the filesystem might have other, non-encryption-related
407 * constraints that prevent DIO from actually being supported.)
409 bool fscrypt_dio_supported(struct kiocb *iocb, struct iov_iter *iter)
411 const struct inode *inode = file_inode(iocb->ki_filp);
412 const unsigned int blocksize = i_blocksize(inode);
414 /* If the file is unencrypted, no veto from us. */
415 if (!fscrypt_needs_contents_encryption(inode))
418 /* We only support DIO with inline crypto, not fs-layer crypto. */
419 if (!fscrypt_inode_uses_inline_crypto(inode))
423 * Since the granularity of encryption is filesystem blocks, the file
424 * position and total I/O length must be aligned to the filesystem block
425 * size -- not just to the block device's logical block size as is
426 * traditionally the case for DIO on many filesystems.
428 * We require that the user-provided memory buffers be filesystem block
429 * aligned too. It is simpler to have a single alignment value required
430 * for all properties of the I/O, as is normally the case for DIO.
431 * Also, allowing less aligned buffers would imply that data units could
432 * cross bvecs, which would greatly complicate the I/O stack, which
433 * assumes that bios can be split at any bvec boundary.
435 if (!IS_ALIGNED(iocb->ki_pos | iov_iter_alignment(iter), blocksize))
440 EXPORT_SYMBOL_GPL(fscrypt_dio_supported);
443 * fscrypt_limit_io_blocks() - limit I/O blocks to avoid discontiguous DUNs
444 * @inode: the file on which I/O is being done
445 * @lblk: the block at which the I/O is being started from
446 * @nr_blocks: the number of blocks we want to submit starting at @lblk
448 * Determine the limit to the number of blocks that can be submitted in a bio
449 * targeting @lblk without causing a data unit number (DUN) discontiguity.
451 * This is normally just @nr_blocks, as normally the DUNs just increment along
452 * with the logical blocks. (Or the file is not encrypted.)
454 * In rare cases, fscrypt can be using an IV generation method that allows the
455 * DUN to wrap around within logically contiguous blocks, and that wraparound
456 * will occur. If this happens, a value less than @nr_blocks will be returned
457 * so that the wraparound doesn't occur in the middle of a bio, which would
458 * cause encryption/decryption to produce wrong results.
460 * Return: the actual number of blocks that can be submitted
462 u64 fscrypt_limit_io_blocks(const struct inode *inode, u64 lblk, u64 nr_blocks)
464 const struct fscrypt_info *ci;
467 if (!fscrypt_inode_uses_inline_crypto(inode))
473 ci = inode->i_crypt_info;
474 if (!(fscrypt_policy_flags(&ci->ci_policy) &
475 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32))
478 /* With IV_INO_LBLK_32, the DUN can wrap around from U32_MAX to 0. */
480 dun = ci->ci_hashed_ino + lblk;
482 return min_t(u64, nr_blocks, (u64)U32_MAX + 1 - dun);
484 EXPORT_SYMBOL_GPL(fscrypt_limit_io_blocks);