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/export.h>
19 #include <linux/sched/mm.h>
20 #include <linux/slab.h>
21 #include <linux/uio.h>
22
23 #include "fscrypt_private.h"
24
fscrypt_get_devices(struct super_block * sb,unsigned int * num_devs)25 static struct block_device **fscrypt_get_devices(struct super_block *sb,
26 unsigned int *num_devs)
27 {
28 struct block_device **devs;
29
30 if (sb->s_cop->get_devices) {
31 devs = sb->s_cop->get_devices(sb, num_devs);
32 if (devs)
33 return devs;
34 }
35 devs = kmalloc_obj(*devs);
36 if (!devs)
37 return ERR_PTR(-ENOMEM);
38 devs[0] = sb->s_bdev;
39 *num_devs = 1;
40 return devs;
41 }
42
fscrypt_get_dun_bytes(const struct fscrypt_inode_info * ci)43 static unsigned int fscrypt_get_dun_bytes(const struct fscrypt_inode_info *ci)
44 {
45 const struct super_block *sb = ci->ci_inode->i_sb;
46 unsigned int flags = fscrypt_policy_flags(&ci->ci_policy);
47 int dun_bits;
48
49 if (flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY)
50 return offsetofend(union fscrypt_iv, nonce);
51
52 if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64)
53 return sizeof(__le64);
54
55 if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)
56 return sizeof(__le32);
57
58 /* Default case: IVs are just the file data unit index */
59 dun_bits = fscrypt_max_file_dun_bits(sb, ci->ci_data_unit_bits);
60 return DIV_ROUND_UP(dun_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_inode_info * ci,bool is_hw_wrapped_key)93 int fscrypt_select_encryption_impl(struct fscrypt_inode_info *ci,
94 bool is_hw_wrapped_key)
95 {
96 const struct inode *inode = ci->ci_inode;
97 struct super_block *sb = inode->i_sb;
98 struct blk_crypto_config crypto_cfg;
99 struct block_device **devs;
100 unsigned int num_devs;
101 unsigned int i;
102
103 /* The file must need contents encryption, not filenames encryption */
104 if (!S_ISREG(inode->i_mode))
105 return 0;
106
107 /* The crypto mode must have a blk-crypto counterpart */
108 if (ci->ci_mode->blk_crypto_mode == BLK_ENCRYPTION_MODE_INVALID)
109 return 0;
110
111 /* The filesystem must be mounted with -o inlinecrypt */
112 if (!(sb->s_flags & SB_INLINECRYPT))
113 return 0;
114
115 /*
116 * When a page contains multiple logically contiguous filesystem blocks,
117 * some filesystem code only calls fscrypt_mergeable_bio() for the first
118 * block in the page. This is fine for most of fscrypt's IV generation
119 * strategies, where contiguous blocks imply contiguous IVs. But it
120 * doesn't work with IV_INO_LBLK_32. For now, simply exclude
121 * IV_INO_LBLK_32 with blocksize != PAGE_SIZE from inline encryption.
122 */
123 if ((fscrypt_policy_flags(&ci->ci_policy) &
124 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
125 sb->s_blocksize != PAGE_SIZE)
126 return 0;
127
128 /*
129 * On all the filesystem's block devices, blk-crypto must support the
130 * crypto configuration that the file would use.
131 */
132 crypto_cfg.crypto_mode = ci->ci_mode->blk_crypto_mode;
133 crypto_cfg.data_unit_size = 1U << ci->ci_data_unit_bits;
134 crypto_cfg.dun_bytes = fscrypt_get_dun_bytes(ci);
135 crypto_cfg.key_type = is_hw_wrapped_key ?
136 BLK_CRYPTO_KEY_TYPE_HW_WRAPPED : BLK_CRYPTO_KEY_TYPE_RAW;
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 * key_bytes,size_t 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 *key_bytes, size_t 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_RAW;
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_obj(*blk_key);
173 if (!blk_key)
174 return -ENOMEM;
175
176 err = blk_crypto_init_key(blk_key, key_bytes, 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 fscrypt_get_inode_info_raw(inode)->ci_inlinecrypt;
267 }
268 EXPORT_SYMBOL_GPL(__fscrypt_inode_uses_inline_crypto);
269
fscrypt_generate_dun(const struct fscrypt_inode_info * ci,loff_t pos,u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])270 static void fscrypt_generate_dun(const struct fscrypt_inode_info *ci,
271 loff_t pos, u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
272 {
273 union fscrypt_iv iv;
274 int i;
275
276 fscrypt_generate_iv(&iv, pos >> ci->ci_data_unit_bits, ci);
277
278 BUILD_BUG_ON(FSCRYPT_MAX_IV_SIZE > BLK_CRYPTO_MAX_IV_SIZE);
279 memset(dun, 0, BLK_CRYPTO_MAX_IV_SIZE);
280 for (i = 0; i < ci->ci_mode->ivsize/sizeof(dun[0]); i++)
281 dun[i] = le64_to_cpu(iv.dun[i]);
282 }
283
284 /**
285 * fscrypt_set_bio_crypt_ctx() - prepare a file contents bio for inline crypto
286 * @bio: a bio which will eventually be submitted to the file
287 * @inode: the file's inode
288 * @pos: the first file position (in bytes) in the I/O
289 * @gfp_mask: memory allocation flags - these must be a waiting mask so that
290 * bio_crypt_set_ctx can't fail.
291 *
292 * If the contents of the file should be encrypted (or decrypted) with inline
293 * encryption, then assign the appropriate encryption context to the bio.
294 *
295 * Normally the bio should be newly allocated (i.e. no pages added yet), as
296 * otherwise fscrypt_mergeable_bio() won't work as intended.
297 *
298 * The encryption context will be freed automatically when the bio is freed.
299 */
fscrypt_set_bio_crypt_ctx(struct bio * bio,const struct inode * inode,loff_t pos,gfp_t gfp_mask)300 void fscrypt_set_bio_crypt_ctx(struct bio *bio, const struct inode *inode,
301 loff_t pos, gfp_t gfp_mask)
302 {
303 const struct fscrypt_inode_info *ci;
304 u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
305
306 if (!fscrypt_inode_uses_inline_crypto(inode))
307 return;
308 ci = fscrypt_get_inode_info_raw(inode);
309
310 fscrypt_generate_dun(ci, pos, dun);
311 bio_crypt_set_ctx(bio, ci->ci_enc_key.blk_key, dun, gfp_mask);
312 }
313 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx);
314
315 /**
316 * fscrypt_mergeable_bio() - test whether data can be added to a bio
317 * @bio: the bio being built up
318 * @inode: the inode for the next part of the I/O
319 * @pos: the next file position (in bytes) in the I/O
320 *
321 * When building a bio which may contain data which should undergo inline
322 * encryption (or decryption) via fscrypt, filesystems should call this function
323 * to ensure that the resulting bio contains only contiguous data unit numbers.
324 * This will return false if the next part of the I/O cannot be merged with the
325 * bio because either the encryption key would be different or the encryption
326 * data unit numbers would be discontiguous.
327 *
328 * fscrypt_set_bio_crypt_ctx() must have already been called on the bio.
329 *
330 * This function isn't required in cases where crypto-mergeability is ensured in
331 * another way, such as I/O targeting only a single file (and thus a single key)
332 * combined with fscrypt_limit_io_blocks() to ensure DUN contiguity.
333 *
334 * Return: true iff the I/O is mergeable
335 */
fscrypt_mergeable_bio(struct bio * bio,const struct inode * inode,loff_t pos)336 bool fscrypt_mergeable_bio(struct bio *bio, const struct inode *inode,
337 loff_t pos)
338 {
339 const struct bio_crypt_ctx *bc = bio->bi_crypt_context;
340 const struct fscrypt_inode_info *ci;
341 u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
342
343 if (!!bc != fscrypt_inode_uses_inline_crypto(inode))
344 return false;
345 if (!bc)
346 return true;
347 ci = fscrypt_get_inode_info_raw(inode);
348
349 /*
350 * Comparing the key pointers is good enough, as all I/O for each key
351 * uses the same pointer. I.e., there's currently no need to support
352 * merging requests where the keys are the same but the pointers differ.
353 */
354 if (bc->bc_key != ci->ci_enc_key.blk_key)
355 return false;
356
357 fscrypt_generate_dun(ci, pos, next_dun);
358 return bio_crypt_dun_is_contiguous(bc, bio->bi_iter.bi_size, next_dun);
359 }
360 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio);
361
362 /**
363 * fscrypt_dio_supported() - check whether DIO (direct I/O) is supported on an
364 * inode, as far as encryption is concerned
365 * @inode: the inode in question
366 *
367 * Return: %true if there are no encryption constraints that prevent DIO from
368 * being supported; %false if DIO is unsupported. (Note that in the
369 * %true case, the filesystem might have other, non-encryption-related
370 * constraints that prevent DIO from actually being supported. Also, on
371 * encrypted files the filesystem is still responsible for only allowing
372 * DIO when requests are filesystem-block-aligned.)
373 */
fscrypt_dio_supported(struct inode * inode)374 bool fscrypt_dio_supported(struct inode *inode)
375 {
376 int err;
377
378 /* If the file is unencrypted, no veto from us. */
379 if (!fscrypt_needs_contents_encryption(inode))
380 return true;
381
382 /*
383 * We only support DIO with inline crypto, not fs-layer crypto.
384 *
385 * To determine whether the inode is using inline crypto, we have to set
386 * up the key if it wasn't already done. This is because in the current
387 * design of fscrypt, the decision of whether to use inline crypto or
388 * not isn't made until the inode's encryption key is being set up. In
389 * the DIO read/write case, the key will always be set up already, since
390 * the file will be open. But in the case of statx(), the key might not
391 * be set up yet, as the file might not have been opened yet.
392 */
393 err = fscrypt_require_key(inode);
394 if (err) {
395 /*
396 * Key unavailable or couldn't be set up. This edge case isn't
397 * worth worrying about; just report that DIO is unsupported.
398 */
399 return false;
400 }
401 return fscrypt_inode_uses_inline_crypto(inode);
402 }
403 EXPORT_SYMBOL_GPL(fscrypt_dio_supported);
404
405 /**
406 * fscrypt_limit_io_blocks() - limit I/O blocks to avoid discontiguous DUNs
407 * @inode: the file on which I/O is being done
408 * @lblk: the block at which the I/O is being started from
409 * @nr_blocks: the number of blocks we want to submit starting at @lblk
410 *
411 * Determine the limit to the number of blocks that can be submitted in a bio
412 * targeting @lblk without causing a data unit number (DUN) discontiguity.
413 *
414 * This is normally just @nr_blocks, as normally the DUNs just increment along
415 * with the logical blocks. (Or the file is not encrypted.)
416 *
417 * In rare cases, fscrypt can be using an IV generation method that allows the
418 * DUN to wrap around within logically contiguous blocks, and that wraparound
419 * will occur. If this happens, a value less than @nr_blocks will be returned
420 * so that the wraparound doesn't occur in the middle of a bio, which would
421 * cause encryption/decryption to produce wrong results.
422 *
423 * Return: the actual number of blocks that can be submitted
424 */
fscrypt_limit_io_blocks(const struct inode * inode,u64 lblk,u64 nr_blocks)425 u64 fscrypt_limit_io_blocks(const struct inode *inode, u64 lblk, u64 nr_blocks)
426 {
427 const struct fscrypt_inode_info *ci;
428 u32 dun;
429
430 if (!fscrypt_inode_uses_inline_crypto(inode))
431 return nr_blocks;
432
433 if (nr_blocks <= 1)
434 return nr_blocks;
435
436 ci = fscrypt_get_inode_info_raw(inode);
437 if (!(fscrypt_policy_flags(&ci->ci_policy) &
438 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32))
439 return nr_blocks;
440
441 /* With IV_INO_LBLK_32, the DUN can wrap around from U32_MAX to 0. */
442
443 dun = ci->ci_hashed_ino + lblk;
444
445 return min_t(u64, nr_blocks, (u64)U32_MAX + 1 - dun);
446 }
447 EXPORT_SYMBOL_GPL(fscrypt_limit_io_blocks);
448