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/keyslot-manager.h>
19 #include <linux/uio.h>
20
21 #include "fscrypt_private.h"
22
23 struct fscrypt_blk_crypto_key {
24 struct blk_crypto_key base;
25 int num_devs;
26 struct request_queue *devs[];
27 };
28
fscrypt_get_num_devices(struct super_block * sb)29 static int fscrypt_get_num_devices(struct super_block *sb)
30 {
31 if (sb->s_cop->get_num_devices)
32 return sb->s_cop->get_num_devices(sb);
33 return 1;
34 }
35
fscrypt_get_devices(struct super_block * sb,int num_devs,struct request_queue ** devs)36 static void fscrypt_get_devices(struct super_block *sb, int num_devs,
37 struct request_queue **devs)
38 {
39 if (num_devs == 1)
40 devs[0] = bdev_get_queue(sb->s_bdev);
41 else
42 sb->s_cop->get_devices(sb, devs);
43 }
44
fscrypt_get_dun_bytes(const struct fscrypt_info * ci)45 static unsigned int fscrypt_get_dun_bytes(const struct fscrypt_info *ci)
46 {
47 struct super_block *sb = ci->ci_inode->i_sb;
48 unsigned int flags = fscrypt_policy_flags(&ci->ci_policy);
49 int ino_bits = 64, lblk_bits = 64;
50
51 if (flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY)
52 return offsetofend(union fscrypt_iv, nonce);
53
54 if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64)
55 return sizeof(__le64);
56
57 if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)
58 return sizeof(__le32);
59
60 /* Default case: IVs are just the file logical block number */
61 if (sb->s_cop->get_ino_and_lblk_bits)
62 sb->s_cop->get_ino_and_lblk_bits(sb, &ino_bits, &lblk_bits);
63 return DIV_ROUND_UP(lblk_bits, 8);
64 }
65
66 /* Enable inline encryption for this file if supported. */
fscrypt_select_encryption_impl(struct fscrypt_info * ci,bool is_hw_wrapped_key)67 int fscrypt_select_encryption_impl(struct fscrypt_info *ci,
68 bool is_hw_wrapped_key)
69 {
70 const struct inode *inode = ci->ci_inode;
71 struct super_block *sb = inode->i_sb;
72 enum blk_crypto_mode_num crypto_mode = ci->ci_mode->blk_crypto_mode;
73 unsigned int dun_bytes;
74 struct request_queue **devs;
75 int num_devs;
76 int i;
77
78 /* The file must need contents encryption, not filenames encryption */
79 if (!S_ISREG(inode->i_mode))
80 return 0;
81
82 /* blk-crypto must implement the needed encryption algorithm */
83 if (crypto_mode == BLK_ENCRYPTION_MODE_INVALID)
84 return 0;
85
86 /* The filesystem must be mounted with -o inlinecrypt */
87 if (!sb->s_cop->inline_crypt_enabled ||
88 !sb->s_cop->inline_crypt_enabled(sb))
89 return 0;
90
91 /*
92 * When a page contains multiple logically contiguous filesystem blocks,
93 * some filesystem code only calls fscrypt_mergeable_bio() for the first
94 * block in the page. This is fine for most of fscrypt's IV generation
95 * strategies, where contiguous blocks imply contiguous IVs. But it
96 * doesn't work with IV_INO_LBLK_32. For now, simply exclude
97 * IV_INO_LBLK_32 with blocksize != PAGE_SIZE from inline encryption.
98 */
99 if ((fscrypt_policy_flags(&ci->ci_policy) &
100 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
101 sb->s_blocksize != PAGE_SIZE)
102 return 0;
103
104 /*
105 * The needed encryption settings must be supported either by
106 * blk-crypto-fallback, or by hardware on all the filesystem's devices.
107 */
108
109 if (IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) &&
110 !is_hw_wrapped_key) {
111 ci->ci_inlinecrypt = true;
112 return 0;
113 }
114
115 num_devs = fscrypt_get_num_devices(sb);
116 devs = kmalloc_array(num_devs, sizeof(*devs), GFP_NOFS);
117 if (!devs)
118 return -ENOMEM;
119
120 fscrypt_get_devices(sb, num_devs, devs);
121
122 dun_bytes = fscrypt_get_dun_bytes(ci);
123
124 for (i = 0; i < num_devs; i++) {
125 if (!keyslot_manager_crypto_mode_supported(devs[i]->ksm,
126 crypto_mode,
127 dun_bytes,
128 sb->s_blocksize,
129 is_hw_wrapped_key))
130 goto out_free_devs;
131 }
132
133 ci->ci_inlinecrypt = true;
134 out_free_devs:
135 kfree(devs);
136 return 0;
137 }
138
fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key * prep_key,const u8 * raw_key,unsigned int raw_key_size,bool is_hw_wrapped,const struct fscrypt_info * ci)139 int fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key *prep_key,
140 const u8 *raw_key,
141 unsigned int raw_key_size,
142 bool is_hw_wrapped,
143 const struct fscrypt_info *ci)
144 {
145 const struct inode *inode = ci->ci_inode;
146 struct super_block *sb = inode->i_sb;
147 enum blk_crypto_mode_num crypto_mode = ci->ci_mode->blk_crypto_mode;
148 unsigned int dun_bytes;
149 int num_devs;
150 int queue_refs = 0;
151 struct fscrypt_blk_crypto_key *blk_key;
152 int err;
153 int i;
154
155 num_devs = fscrypt_get_num_devices(sb);
156 if (WARN_ON(num_devs < 1))
157 return -EINVAL;
158
159 blk_key = kzalloc(struct_size(blk_key, devs, num_devs), GFP_NOFS);
160 if (!blk_key)
161 return -ENOMEM;
162
163 blk_key->num_devs = num_devs;
164 fscrypt_get_devices(sb, num_devs, blk_key->devs);
165
166 dun_bytes = fscrypt_get_dun_bytes(ci);
167
168 BUILD_BUG_ON(FSCRYPT_MAX_HW_WRAPPED_KEY_SIZE >
169 BLK_CRYPTO_MAX_WRAPPED_KEY_SIZE);
170
171 err = blk_crypto_init_key(&blk_key->base, raw_key, raw_key_size,
172 is_hw_wrapped, crypto_mode, dun_bytes,
173 sb->s_blocksize);
174 if (err) {
175 fscrypt_err(inode, "error %d initializing blk-crypto key", err);
176 goto fail;
177 }
178
179 /*
180 * We have to start using blk-crypto on all the filesystem's devices.
181 * We also have to save all the request_queue's for later so that the
182 * key can be evicted from them. This is needed because some keys
183 * aren't destroyed until after the filesystem was already unmounted
184 * (namely, the per-mode keys in struct fscrypt_master_key).
185 */
186 for (i = 0; i < num_devs; i++) {
187 if (!blk_get_queue(blk_key->devs[i])) {
188 fscrypt_err(inode, "couldn't get request_queue");
189 err = -EAGAIN;
190 goto fail;
191 }
192 queue_refs++;
193
194 err = blk_crypto_start_using_mode(crypto_mode, dun_bytes,
195 sb->s_blocksize,
196 is_hw_wrapped,
197 blk_key->devs[i]);
198 if (err) {
199 fscrypt_err(inode,
200 "error %d starting to use blk-crypto", err);
201 goto fail;
202 }
203 }
204 /*
205 * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
206 * I.e., here we publish ->blk_key with a RELEASE barrier so that
207 * concurrent tasks can ACQUIRE it. Note that this concurrency is only
208 * possible for per-mode keys, not for per-file keys.
209 */
210 smp_store_release(&prep_key->blk_key, blk_key);
211 return 0;
212
213 fail:
214 for (i = 0; i < queue_refs; i++)
215 blk_put_queue(blk_key->devs[i]);
216 kzfree(blk_key);
217 return err;
218 }
219
fscrypt_destroy_inline_crypt_key(struct fscrypt_prepared_key * prep_key)220 void fscrypt_destroy_inline_crypt_key(struct fscrypt_prepared_key *prep_key)
221 {
222 struct fscrypt_blk_crypto_key *blk_key = prep_key->blk_key;
223 int i;
224
225 if (blk_key) {
226 for (i = 0; i < blk_key->num_devs; i++) {
227 blk_crypto_evict_key(blk_key->devs[i], &blk_key->base);
228 blk_put_queue(blk_key->devs[i]);
229 }
230 kzfree(blk_key);
231 }
232 }
233
fscrypt_derive_raw_secret(struct super_block * sb,const u8 * wrapped_key,unsigned int wrapped_key_size,u8 * raw_secret,unsigned int raw_secret_size)234 int fscrypt_derive_raw_secret(struct super_block *sb,
235 const u8 *wrapped_key,
236 unsigned int wrapped_key_size,
237 u8 *raw_secret, unsigned int raw_secret_size)
238 {
239 struct request_queue *q;
240
241 q = sb->s_bdev->bd_queue;
242 if (!q->ksm)
243 return -EOPNOTSUPP;
244
245 return keyslot_manager_derive_raw_secret(q->ksm,
246 wrapped_key, wrapped_key_size,
247 raw_secret, raw_secret_size);
248 }
249
250 /**
251 * fscrypt_inode_uses_inline_crypto - test whether an inode uses inline
252 * encryption
253 * @inode: an inode
254 *
255 * Return: true if the inode requires file contents encryption and if the
256 * encryption should be done in the block layer via blk-crypto rather
257 * than in the filesystem layer.
258 */
fscrypt_inode_uses_inline_crypto(const struct inode * inode)259 bool fscrypt_inode_uses_inline_crypto(const struct inode *inode)
260 {
261 return IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode) &&
262 inode->i_crypt_info->ci_inlinecrypt;
263 }
264 EXPORT_SYMBOL_GPL(fscrypt_inode_uses_inline_crypto);
265
266 /**
267 * fscrypt_inode_uses_fs_layer_crypto - test whether an inode uses fs-layer
268 * encryption
269 * @inode: an inode
270 *
271 * Return: true if the inode requires file contents encryption and if the
272 * encryption should be done in the filesystem layer rather than in the
273 * block layer via blk-crypto.
274 */
fscrypt_inode_uses_fs_layer_crypto(const struct inode * inode)275 bool fscrypt_inode_uses_fs_layer_crypto(const struct inode *inode)
276 {
277 return IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode) &&
278 !inode->i_crypt_info->ci_inlinecrypt;
279 }
280 EXPORT_SYMBOL_GPL(fscrypt_inode_uses_fs_layer_crypto);
281
fscrypt_generate_dun(const struct fscrypt_info * ci,u64 lblk_num,u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])282 static void fscrypt_generate_dun(const struct fscrypt_info *ci, u64 lblk_num,
283 u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
284 {
285 union fscrypt_iv iv;
286 int i;
287
288 fscrypt_generate_iv(&iv, lblk_num, ci);
289
290 BUILD_BUG_ON(FSCRYPT_MAX_IV_SIZE > BLK_CRYPTO_MAX_IV_SIZE);
291 memset(dun, 0, BLK_CRYPTO_MAX_IV_SIZE);
292 for (i = 0; i < ci->ci_mode->ivsize/sizeof(dun[0]); i++)
293 dun[i] = le64_to_cpu(iv.dun[i]);
294 }
295
296 /**
297 * fscrypt_set_bio_crypt_ctx - prepare a file contents bio for inline encryption
298 * @bio: a bio which will eventually be submitted to the file
299 * @inode: the file's inode
300 * @first_lblk: the first file logical block number in the I/O
301 * @gfp_mask: memory allocation flags - these must be a waiting mask so that
302 * bio_crypt_set_ctx can't fail.
303 *
304 * If the contents of the file should be encrypted (or decrypted) with inline
305 * encryption, then assign the appropriate encryption context to the bio.
306 *
307 * Normally the bio should be newly allocated (i.e. no pages added yet), as
308 * otherwise fscrypt_mergeable_bio() won't work as intended.
309 *
310 * The encryption context will be freed automatically when the bio is freed.
311 *
312 * This function also handles setting bi_skip_dm_default_key when needed.
313 */
fscrypt_set_bio_crypt_ctx(struct bio * bio,const struct inode * inode,u64 first_lblk,gfp_t gfp_mask)314 void fscrypt_set_bio_crypt_ctx(struct bio *bio, const struct inode *inode,
315 u64 first_lblk, gfp_t gfp_mask)
316 {
317 const struct fscrypt_info *ci = inode->i_crypt_info;
318 u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
319
320 if (fscrypt_inode_should_skip_dm_default_key(inode))
321 bio_set_skip_dm_default_key(bio);
322
323 if (!fscrypt_inode_uses_inline_crypto(inode))
324 return;
325
326 fscrypt_generate_dun(ci, first_lblk, dun);
327 bio_crypt_set_ctx(bio, &ci->ci_key.blk_key->base, dun, gfp_mask);
328 }
329 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx);
330
331 /* 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)332 static bool bh_get_inode_and_lblk_num(const struct buffer_head *bh,
333 const struct inode **inode_ret,
334 u64 *lblk_num_ret)
335 {
336 struct page *page = bh->b_page;
337 const struct address_space *mapping;
338 const struct inode *inode;
339
340 /*
341 * The ext4 journal (jbd2) can submit a buffer_head it directly created
342 * for a non-pagecache page. fscrypt doesn't care about these.
343 */
344 mapping = page_mapping(page);
345 if (!mapping)
346 return false;
347 inode = mapping->host;
348
349 *inode_ret = inode;
350 *lblk_num_ret = ((u64)page->index << (PAGE_SHIFT - inode->i_blkbits)) +
351 (bh_offset(bh) >> inode->i_blkbits);
352 return true;
353 }
354
355 /**
356 * fscrypt_set_bio_crypt_ctx_bh - prepare a file contents bio for inline
357 * encryption
358 * @bio: a bio which will eventually be submitted to the file
359 * @first_bh: the first buffer_head for which I/O will be submitted
360 * @gfp_mask: memory allocation flags
361 *
362 * Same as fscrypt_set_bio_crypt_ctx(), except this takes a buffer_head instead
363 * of an inode and block number directly.
364 */
fscrypt_set_bio_crypt_ctx_bh(struct bio * bio,const struct buffer_head * first_bh,gfp_t gfp_mask)365 void fscrypt_set_bio_crypt_ctx_bh(struct bio *bio,
366 const struct buffer_head *first_bh,
367 gfp_t gfp_mask)
368 {
369 const struct inode *inode;
370 u64 first_lblk;
371
372 if (bh_get_inode_and_lblk_num(first_bh, &inode, &first_lblk))
373 fscrypt_set_bio_crypt_ctx(bio, inode, first_lblk, gfp_mask);
374 }
375 EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx_bh);
376
377 /**
378 * fscrypt_mergeable_bio - test whether data can be added to a bio
379 * @bio: the bio being built up
380 * @inode: the inode for the next part of the I/O
381 * @next_lblk: the next file logical block number in the I/O
382 *
383 * When building a bio which may contain data which should undergo inline
384 * encryption (or decryption) via fscrypt, filesystems should call this function
385 * to ensure that the resulting bio contains only logically contiguous data.
386 * This will return false if the next part of the I/O cannot be merged with the
387 * bio because either the encryption key would be different or the encryption
388 * data unit numbers would be discontiguous.
389 *
390 * fscrypt_set_bio_crypt_ctx() must have already been called on the bio.
391 *
392 * This function also returns false if the next part of the I/O would need to
393 * have a different value for the bi_skip_dm_default_key flag.
394 *
395 * Return: true iff the I/O is mergeable
396 */
fscrypt_mergeable_bio(struct bio * bio,const struct inode * inode,u64 next_lblk)397 bool fscrypt_mergeable_bio(struct bio *bio, const struct inode *inode,
398 u64 next_lblk)
399 {
400 const struct bio_crypt_ctx *bc = bio->bi_crypt_context;
401 u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
402
403 if (!!bc != fscrypt_inode_uses_inline_crypto(inode))
404 return false;
405 if (bio_should_skip_dm_default_key(bio) !=
406 fscrypt_inode_should_skip_dm_default_key(inode))
407 return false;
408 if (!bc)
409 return true;
410
411 /*
412 * Comparing the key pointers is good enough, as all I/O for each key
413 * uses the same pointer. I.e., there's currently no need to support
414 * merging requests where the keys are the same but the pointers differ.
415 */
416 if (bc->bc_key != &inode->i_crypt_info->ci_key.blk_key->base)
417 return false;
418
419 fscrypt_generate_dun(inode->i_crypt_info, next_lblk, next_dun);
420 return bio_crypt_dun_is_contiguous(bc, bio->bi_iter.bi_size, next_dun);
421 }
422 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio);
423
424 /**
425 * fscrypt_mergeable_bio_bh - test whether data can be added to a bio
426 * @bio: the bio being built up
427 * @next_bh: the next buffer_head for which I/O will be submitted
428 *
429 * Same as fscrypt_mergeable_bio(), except this takes a buffer_head instead of
430 * an inode and block number directly.
431 *
432 * Return: true iff the I/O is mergeable
433 */
fscrypt_mergeable_bio_bh(struct bio * bio,const struct buffer_head * next_bh)434 bool fscrypt_mergeable_bio_bh(struct bio *bio,
435 const struct buffer_head *next_bh)
436 {
437 const struct inode *inode;
438 u64 next_lblk;
439
440 if (!bh_get_inode_and_lblk_num(next_bh, &inode, &next_lblk))
441 return !bio->bi_crypt_context &&
442 !bio_should_skip_dm_default_key(bio);
443
444 return fscrypt_mergeable_bio(bio, inode, next_lblk);
445 }
446 EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio_bh);
447
448 /**
449 * fscrypt_dio_supported() - check whether a direct I/O request is unsupported
450 * due to encryption constraints
451 * @iocb: the file and position the I/O is targeting
452 * @iter: the I/O data segment(s)
453 *
454 * Return: true if direct I/O is supported
455 */
fscrypt_dio_supported(struct kiocb * iocb,struct iov_iter * iter)456 bool fscrypt_dio_supported(struct kiocb *iocb, struct iov_iter *iter)
457 {
458 const struct inode *inode = file_inode(iocb->ki_filp);
459 const unsigned int blocksize = i_blocksize(inode);
460
461 /* If the file is unencrypted, no veto from us. */
462 if (!fscrypt_needs_contents_encryption(inode))
463 return true;
464
465 /* We only support direct I/O with inline crypto, not fs-layer crypto */
466 if (!fscrypt_inode_uses_inline_crypto(inode))
467 return false;
468
469 /*
470 * Since the granularity of encryption is filesystem blocks, the I/O
471 * must be block aligned -- not just disk sector aligned.
472 */
473 if (!IS_ALIGNED(iocb->ki_pos | iov_iter_alignment(iter), blocksize))
474 return false;
475
476 return true;
477 }
478 EXPORT_SYMBOL_GPL(fscrypt_dio_supported);
479
480 /**
481 * fscrypt_limit_dio_pages() - limit I/O pages to avoid discontiguous DUNs
482 * @inode: the file on which I/O is being done
483 * @pos: the file position (in bytes) at which the I/O is being done
484 * @nr_pages: the number of pages we want to submit starting at @pos
485 *
486 * For direct I/O: limit the number of pages that will be submitted in the bio
487 * targeting @pos, in order to avoid crossing a data unit number (DUN)
488 * discontinuity. This is only needed for certain IV generation methods.
489 *
490 * Return: the actual number of pages that can be submitted
491 */
fscrypt_limit_dio_pages(const struct inode * inode,loff_t pos,int nr_pages)492 int fscrypt_limit_dio_pages(const struct inode *inode, loff_t pos, int nr_pages)
493 {
494 const struct fscrypt_info *ci = inode->i_crypt_info;
495 u32 dun;
496
497 if (!fscrypt_inode_uses_inline_crypto(inode))
498 return nr_pages;
499
500 if (nr_pages <= 1)
501 return nr_pages;
502
503 if (!(fscrypt_policy_flags(&ci->ci_policy) &
504 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32))
505 return nr_pages;
506
507 /*
508 * fscrypt_select_encryption_impl() ensures that block_size == PAGE_SIZE
509 * when using FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32.
510 */
511 if (WARN_ON_ONCE(i_blocksize(inode) != PAGE_SIZE))
512 return 1;
513
514 /* With IV_INO_LBLK_32, the DUN can wrap around from U32_MAX to 0. */
515
516 dun = ci->ci_hashed_ino + (pos >> inode->i_blkbits);
517
518 return min_t(u64, nr_pages, (u64)U32_MAX + 1 - dun);
519 }
520