xref: /linux/fs/crypto/crypto.c (revision 12d5fc96ebbb3b948861805b32a4c3a96105ccd9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * This contains encryption functions for per-file encryption.
4  *
5  * Copyright (C) 2015, Google, Inc.
6  * Copyright (C) 2015, Motorola Mobility
7  *
8  * Written by Michael Halcrow, 2014.
9  *
10  * Filename encryption additions
11  *	Uday Savagaonkar, 2014
12  * Encryption policy handling additions
13  *	Ildar Muslukhov, 2014
14  * Add fscrypt_pullback_bio_page()
15  *	Jaegeuk Kim, 2015.
16  *
17  * This has not yet undergone a rigorous security audit.
18  *
19  * The usage of AES-XTS should conform to recommendations in NIST
20  * Special Publication 800-38E and IEEE P1619/D16.
21  */
22 
23 #include <crypto/skcipher.h>
24 #include <linux/export.h>
25 #include <linux/mempool.h>
26 #include <linux/module.h>
27 #include <linux/pagemap.h>
28 #include <linux/ratelimit.h>
29 #include <linux/scatterlist.h>
30 
31 #include "fscrypt_private.h"
32 
33 static unsigned int num_prealloc_crypto_pages = 32;
34 
35 module_param(num_prealloc_crypto_pages, uint, 0444);
36 MODULE_PARM_DESC(num_prealloc_crypto_pages,
37 		"Number of crypto pages to preallocate");
38 
39 static mempool_t *fscrypt_bounce_page_pool = NULL;
40 
41 static DEFINE_MUTEX(fscrypt_init_mutex);
42 
43 struct kmem_cache *fscrypt_inode_info_cachep;
44 
45 static struct page *fscrypt_alloc_bounce_page(gfp_t gfp_flags)
46 {
47 	if (WARN_ON_ONCE(!fscrypt_bounce_page_pool)) {
48 		/*
49 		 * Oops, the filesystem called a function that uses the bounce
50 		 * page pool, but it didn't set needs_bounce_pages.
51 		 */
52 		return NULL;
53 	}
54 	return mempool_alloc(fscrypt_bounce_page_pool, gfp_flags);
55 }
56 
57 /**
58  * fscrypt_free_bounce_page() - free a ciphertext bounce page
59  * @bounce_page: the bounce page to free, or NULL
60  *
61  * Free a bounce page that was allocated by fscrypt_encrypt_pagecache_blocks().
62  */
63 void fscrypt_free_bounce_page(struct page *bounce_page)
64 {
65 	if (!bounce_page)
66 		return;
67 	set_page_private(bounce_page, (unsigned long)NULL);
68 	ClearPagePrivate(bounce_page);
69 	mempool_free(bounce_page, fscrypt_bounce_page_pool);
70 }
71 EXPORT_SYMBOL(fscrypt_free_bounce_page);
72 
73 /*
74  * Generate the IV for the given data unit index within the given file.
75  * For filenames encryption, index == 0.
76  *
77  * Keep this in sync with fscrypt_limit_io_blocks().  fscrypt_limit_io_blocks()
78  * needs to know about any IV generation methods where the low bits of IV don't
79  * simply contain the data unit index (e.g., IV_INO_LBLK_32).
80  */
81 void fscrypt_generate_iv(union fscrypt_iv *iv, u64 index,
82 			 const struct fscrypt_inode_info *ci)
83 {
84 	u8 flags = fscrypt_policy_flags(&ci->ci_policy);
85 
86 	memset(iv, 0, sizeof(*iv));
87 
88 	if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
89 		WARN_ON_ONCE(index > U32_MAX);
90 		WARN_ON_ONCE(ci->ci_inode->i_ino > U32_MAX);
91 		index |= (u64)ci->ci_inode->i_ino << 32;
92 	} else if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
93 		WARN_ON_ONCE(index > U32_MAX);
94 		index = (u32)(ci->ci_hashed_ino + index);
95 	} else if (flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
96 		memcpy(iv->nonce, ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE);
97 	}
98 	iv->index = cpu_to_le64(index);
99 }
100 
101 typedef enum {
102 	FS_DECRYPT = 0,
103 	FS_ENCRYPT,
104 } fscrypt_direction_t;
105 
106 /* Encrypt or decrypt a single "data unit" of file contents. */
107 static int fscrypt_crypt_data_unit(const struct fscrypt_inode_info *ci,
108 				   fscrypt_direction_t rw, u64 index,
109 				   struct page *src_page,
110 				   struct page *dest_page, unsigned int len,
111 				   unsigned int offs)
112 {
113 	struct crypto_sync_skcipher *tfm;
114 	union fscrypt_iv iv;
115 	struct scatterlist dst, src;
116 	int err;
117 
118 	if (WARN_ON_ONCE(ci == NULL)) /* File hasn't been opened yet? */
119 		return -ENOKEY;
120 	tfm = ci->ci_enc_key.tfm;
121 	if (WARN_ON_ONCE(tfm == NULL)) /* Called on block-based filesystem? */
122 		return -ENOKEY;
123 
124 	if (WARN_ON_ONCE(len <= 0))
125 		return -EINVAL;
126 	if (WARN_ON_ONCE(len % FSCRYPT_CONTENTS_ALIGNMENT != 0))
127 		return -EINVAL;
128 
129 	fscrypt_generate_iv(&iv, index, ci);
130 
131 	{
132 		SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);
133 		skcipher_request_set_callback(req,
134 					      CRYPTO_TFM_REQ_MAY_BACKLOG |
135 						      CRYPTO_TFM_REQ_MAY_SLEEP,
136 					      NULL, NULL);
137 		sg_init_table(&dst, 1);
138 		sg_set_page(&dst, dest_page, len, offs);
139 		sg_init_table(&src, 1);
140 		sg_set_page(&src, src_page, len, offs);
141 		skcipher_request_set_crypt(req, &src, &dst, len, &iv);
142 		if (rw == FS_DECRYPT)
143 			err = crypto_skcipher_decrypt(req);
144 		else
145 			err = crypto_skcipher_encrypt(req);
146 	}
147 	if (err)
148 		fscrypt_err(ci->ci_inode,
149 			    "%scryption failed for data unit %llu: %d",
150 			    (rw == FS_DECRYPT ? "De" : "En"), index, err);
151 	return err;
152 }
153 
154 /**
155  * fscrypt_encrypt_pagecache_blocks() - Encrypt data from a pagecache folio
156  * @folio: the locked pagecache folio containing the data to encrypt
157  * @len: size of the data to encrypt, in bytes
158  * @offs: offset within @page of the data to encrypt, in bytes
159  * @gfp_flags: memory allocation flags; see details below
160  *
161  * This allocates a new bounce page and encrypts the given data into it.  The
162  * length and offset of the data must be aligned to the file's crypto data unit
163  * size.  Alignment to the filesystem block size fulfills this requirement, as
164  * the filesystem block size is always a multiple of the data unit size.
165  *
166  * In the bounce page, the ciphertext data will be located at the same offset at
167  * which the plaintext data was located in the source page.  Any other parts of
168  * the bounce page will be left uninitialized.
169  *
170  * This is for use by the ->writepages() method of non-block-based filesystems.
171  *
172  * The bounce page allocation is mempool-backed, so it will always succeed when
173  * @gfp_flags includes __GFP_DIRECT_RECLAIM, e.g. when it's GFP_NOFS.  However,
174  * only the first page of each bio can be allocated this way.  To prevent
175  * deadlocks, for any additional pages a mask like GFP_NOWAIT must be used.
176  *
177  * Return: the new encrypted bounce page on success; an ERR_PTR() on failure
178  */
179 struct page *fscrypt_encrypt_pagecache_blocks(struct folio *folio,
180 		size_t len, size_t offs, gfp_t gfp_flags)
181 {
182 	const struct inode *inode = folio->mapping->host;
183 	const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
184 	unsigned int du_bits;
185 	unsigned int du_size;
186 	struct page *ciphertext_page;
187 	u64 index;
188 	unsigned int i;
189 	int err;
190 
191 	if (WARN_ON_ONCE(ci == NULL)) /* File hasn't been opened yet? */
192 		return ERR_PTR(-ENOKEY);
193 
194 	du_bits = ci->ci_data_unit_bits;
195 	du_size = 1U << du_bits;
196 	index = (folio_pos(folio) + offs) >> du_bits;
197 
198 	VM_BUG_ON_FOLIO(folio_test_large(folio), folio);
199 	if (WARN_ON_ONCE(!folio_test_locked(folio)))
200 		return ERR_PTR(-EINVAL);
201 
202 	if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, du_size)))
203 		return ERR_PTR(-EINVAL);
204 
205 	ciphertext_page = fscrypt_alloc_bounce_page(gfp_flags);
206 	if (!ciphertext_page)
207 		return ERR_PTR(-ENOMEM);
208 
209 	for (i = offs; i < offs + len; i += du_size, index++) {
210 		err = fscrypt_crypt_data_unit(ci, FS_ENCRYPT, index,
211 					      &folio->page, ciphertext_page,
212 					      du_size, i);
213 		if (err) {
214 			fscrypt_free_bounce_page(ciphertext_page);
215 			return ERR_PTR(err);
216 		}
217 	}
218 	SetPagePrivate(ciphertext_page);
219 	set_page_private(ciphertext_page, (unsigned long)folio);
220 	return ciphertext_page;
221 }
222 EXPORT_SYMBOL(fscrypt_encrypt_pagecache_blocks);
223 
224 /**
225  * fscrypt_encrypt_block_inplace() - Encrypt a filesystem block in-place
226  * @inode:     The inode to which this block belongs
227  * @page:      The page containing the block to encrypt
228  * @len:       Size of block to encrypt.  This must be a multiple of
229  *		FSCRYPT_CONTENTS_ALIGNMENT.
230  * @offs:      Byte offset within @page at which the block to encrypt begins
231  * @lblk_num:  Filesystem logical block number of the block, i.e. the 0-based
232  *		number of the block within the file
233  *
234  * Encrypt a possibly-compressed filesystem block that is located in an
235  * arbitrary page, not necessarily in the original pagecache page.  The @inode
236  * and @lblk_num must be specified, as they can't be determined from @page.
237  *
238  * This function only supports non-block-based filesystems that don't support
239  * sub-block data units (as indicated by the fscrypt_operations fields).
240  *
241  * Return: 0 on success; -errno on failure
242  */
243 int fscrypt_encrypt_block_inplace(const struct inode *inode, struct page *page,
244 				  unsigned int len, unsigned int offs,
245 				  u64 lblk_num)
246 {
247 	if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))
248 		return -EOPNOTSUPP;
249 	return fscrypt_crypt_data_unit(fscrypt_get_inode_info_raw(inode),
250 				       FS_ENCRYPT, lblk_num, page, page, len,
251 				       offs);
252 }
253 EXPORT_SYMBOL(fscrypt_encrypt_block_inplace);
254 
255 /**
256  * fscrypt_decrypt_block_inplace() - Decrypt a filesystem block in-place
257  * @inode:     The inode to which this block belongs
258  * @page:      The page containing the block to decrypt
259  * @len:       Size of block to decrypt.  This must be a multiple of
260  *		FSCRYPT_CONTENTS_ALIGNMENT.
261  * @offs:      Byte offset within @page at which the block to decrypt begins
262  * @lblk_num:  Filesystem logical block number of the block, i.e. the 0-based
263  *		number of the block within the file
264  *
265  * Decrypt a possibly-compressed filesystem block that is located in an
266  * arbitrary page, not necessarily in the original pagecache page.  The @inode
267  * and @lblk_num must be specified, as they can't be determined from @page.
268  *
269  * This function only supports non-block-based filesystems that don't support
270  * sub-block data units (as indicated by the fscrypt_operations fields).
271  *
272  * Return: 0 on success; -errno on failure
273  */
274 int fscrypt_decrypt_block_inplace(const struct inode *inode, struct page *page,
275 				  unsigned int len, unsigned int offs,
276 				  u64 lblk_num)
277 {
278 	if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))
279 		return -EOPNOTSUPP;
280 	return fscrypt_crypt_data_unit(fscrypt_get_inode_info_raw(inode),
281 				       FS_DECRYPT, lblk_num, page, page, len,
282 				       offs);
283 }
284 EXPORT_SYMBOL(fscrypt_decrypt_block_inplace);
285 
286 /**
287  * fscrypt_initialize() - allocate major buffers for fs encryption.
288  * @sb: the filesystem superblock
289  *
290  * We only call this when we start accessing encrypted files, since it
291  * results in memory getting allocated that wouldn't otherwise be used.
292  *
293  * Return: 0 on success; -errno on failure
294  */
295 int fscrypt_initialize(struct super_block *sb)
296 {
297 	mempool_t *pool;
298 
299 	/* pairs with smp_store_release() below */
300 	if (smp_load_acquire(&fscrypt_bounce_page_pool))
301 		return 0;
302 
303 	/* No need to allocate a bounce page pool if this FS won't use it. */
304 	if (!sb->s_cop->needs_bounce_pages)
305 		return 0;
306 
307 	guard(mutex)(&fscrypt_init_mutex);
308 	if (fscrypt_bounce_page_pool)
309 		return 0;
310 
311 	pool = mempool_create_page_pool(num_prealloc_crypto_pages, 0);
312 	if (!pool)
313 		return -ENOMEM;
314 	/* pairs with smp_load_acquire() above */
315 	smp_store_release(&fscrypt_bounce_page_pool, pool);
316 	return 0;
317 }
318 
319 void fscrypt_msg(const struct inode *inode, const char *level,
320 		 const char *fmt, ...)
321 {
322 	static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
323 				      DEFAULT_RATELIMIT_BURST);
324 	struct va_format vaf;
325 	va_list args;
326 
327 	if (!__ratelimit(&rs))
328 		return;
329 
330 	va_start(args, fmt);
331 	vaf.fmt = fmt;
332 	vaf.va = &args;
333 	if (inode && inode->i_ino)
334 		printk("%sfscrypt (%s, inode %llu): %pV\n",
335 		       level, inode->i_sb->s_id, inode->i_ino, &vaf);
336 	else if (inode)
337 		printk("%sfscrypt (%s): %pV\n", level, inode->i_sb->s_id, &vaf);
338 	else
339 		printk("%sfscrypt: %pV\n", level, &vaf);
340 	va_end(args);
341 }
342 
343 static int __init fscrypt_init(void)
344 {
345 	fscrypt_inode_info_cachep = KMEM_CACHE(fscrypt_inode_info,
346 					       SLAB_RECLAIM_ACCOUNT |
347 					       SLAB_PANIC);
348 	fscrypt_init_keyring();
349 	return 0;
350 }
351 late_initcall(fscrypt_init)
352