xref: /linux/fs/crypto/crypto.c (revision 59e6295fac26b8e85c1ea859cdd89fa1e47519d7)
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 /* Encrypt or decrypt a single "data unit" of file contents. */
102 static int fscrypt_crypt_data_unit(const struct fscrypt_inode_info *ci,
103 				   fscrypt_direction_t rw, u64 index,
104 				   struct page *src_page,
105 				   struct page *dest_page, unsigned int len,
106 				   unsigned int offs)
107 {
108 	struct crypto_sync_skcipher *tfm;
109 	union fscrypt_iv iv;
110 	struct scatterlist dst, src;
111 	int err;
112 
113 	if (WARN_ON_ONCE(ci == NULL)) /* File hasn't been opened yet? */
114 		return -ENOKEY;
115 	tfm = ci->ci_enc_key.tfm;
116 	if (WARN_ON_ONCE(tfm == NULL)) /* Called on block-based filesystem? */
117 		return -ENOKEY;
118 
119 	if (WARN_ON_ONCE(len <= 0))
120 		return -EINVAL;
121 	if (WARN_ON_ONCE(len % FSCRYPT_CONTENTS_ALIGNMENT != 0))
122 		return -EINVAL;
123 
124 	fscrypt_generate_iv(&iv, index, ci);
125 
126 	{
127 		SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);
128 		skcipher_request_set_callback(req,
129 					      CRYPTO_TFM_REQ_MAY_BACKLOG |
130 						      CRYPTO_TFM_REQ_MAY_SLEEP,
131 					      NULL, NULL);
132 		sg_init_table(&dst, 1);
133 		sg_set_page(&dst, dest_page, len, offs);
134 		sg_init_table(&src, 1);
135 		sg_set_page(&src, src_page, len, offs);
136 		skcipher_request_set_crypt(req, &src, &dst, len, &iv);
137 		if (rw == FS_DECRYPT)
138 			err = crypto_skcipher_decrypt(req);
139 		else
140 			err = crypto_skcipher_encrypt(req);
141 	}
142 	if (err)
143 		fscrypt_err(ci->ci_inode,
144 			    "%scryption failed for data unit %llu: %d",
145 			    (rw == FS_DECRYPT ? "De" : "En"), index, err);
146 	return err;
147 }
148 
149 /**
150  * fscrypt_encrypt_pagecache_blocks() - Encrypt data from a pagecache folio
151  * @folio: the locked pagecache folio containing the data to encrypt
152  * @len: size of the data to encrypt, in bytes
153  * @offs: offset within @page of the data to encrypt, in bytes
154  * @gfp_flags: memory allocation flags; see details below
155  *
156  * This allocates a new bounce page and encrypts the given data into it.  The
157  * length and offset of the data must be aligned to the file's crypto data unit
158  * size.  Alignment to the filesystem block size fulfills this requirement, as
159  * the filesystem block size is always a multiple of the data unit size.
160  *
161  * In the bounce page, the ciphertext data will be located at the same offset at
162  * which the plaintext data was located in the source page.  Any other parts of
163  * the bounce page will be left uninitialized.
164  *
165  * This is for use by the ->writepages() method of non-block-based filesystems.
166  *
167  * The bounce page allocation is mempool-backed, so it will always succeed when
168  * @gfp_flags includes __GFP_DIRECT_RECLAIM, e.g. when it's GFP_NOFS.  However,
169  * only the first page of each bio can be allocated this way.  To prevent
170  * deadlocks, for any additional pages a mask like GFP_NOWAIT must be used.
171  *
172  * Return: the new encrypted bounce page on success; an ERR_PTR() on failure
173  */
174 struct page *fscrypt_encrypt_pagecache_blocks(struct folio *folio,
175 		size_t len, size_t offs, gfp_t gfp_flags)
176 {
177 	const struct inode *inode = folio->mapping->host;
178 	const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
179 	unsigned int du_bits;
180 	unsigned int du_size;
181 	struct page *ciphertext_page;
182 	u64 index;
183 	unsigned int i;
184 	int err;
185 
186 	if (WARN_ON_ONCE(ci == NULL)) /* File hasn't been opened yet? */
187 		return ERR_PTR(-ENOKEY);
188 
189 	du_bits = ci->ci_data_unit_bits;
190 	du_size = 1U << du_bits;
191 	index = (folio_pos(folio) + offs) >> du_bits;
192 
193 	VM_BUG_ON_FOLIO(folio_test_large(folio), folio);
194 	if (WARN_ON_ONCE(!folio_test_locked(folio)))
195 		return ERR_PTR(-EINVAL);
196 
197 	if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, du_size)))
198 		return ERR_PTR(-EINVAL);
199 
200 	ciphertext_page = fscrypt_alloc_bounce_page(gfp_flags);
201 	if (!ciphertext_page)
202 		return ERR_PTR(-ENOMEM);
203 
204 	for (i = offs; i < offs + len; i += du_size, index++) {
205 		err = fscrypt_crypt_data_unit(ci, FS_ENCRYPT, index,
206 					      &folio->page, ciphertext_page,
207 					      du_size, i);
208 		if (err) {
209 			fscrypt_free_bounce_page(ciphertext_page);
210 			return ERR_PTR(err);
211 		}
212 	}
213 	SetPagePrivate(ciphertext_page);
214 	set_page_private(ciphertext_page, (unsigned long)folio);
215 	return ciphertext_page;
216 }
217 EXPORT_SYMBOL(fscrypt_encrypt_pagecache_blocks);
218 
219 /**
220  * fscrypt_encrypt_block_inplace() - Encrypt a filesystem block in-place
221  * @inode:     The inode to which this block belongs
222  * @page:      The page containing the block to encrypt
223  * @len:       Size of block to encrypt.  This must be a multiple of
224  *		FSCRYPT_CONTENTS_ALIGNMENT.
225  * @offs:      Byte offset within @page at which the block to encrypt begins
226  * @lblk_num:  Filesystem logical block number of the block, i.e. the 0-based
227  *		number of the block within the file
228  *
229  * Encrypt a possibly-compressed filesystem block that is located in an
230  * arbitrary page, not necessarily in the original pagecache page.  The @inode
231  * and @lblk_num must be specified, as they can't be determined from @page.
232  *
233  * This function only supports non-block-based filesystems that don't support
234  * sub-block data units (as indicated by the fscrypt_operations fields).
235  *
236  * Return: 0 on success; -errno on failure
237  */
238 int fscrypt_encrypt_block_inplace(const struct inode *inode, struct page *page,
239 				  unsigned int len, unsigned int offs,
240 				  u64 lblk_num)
241 {
242 	if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))
243 		return -EOPNOTSUPP;
244 	return fscrypt_crypt_data_unit(fscrypt_get_inode_info_raw(inode),
245 				       FS_ENCRYPT, lblk_num, page, page, len,
246 				       offs);
247 }
248 EXPORT_SYMBOL(fscrypt_encrypt_block_inplace);
249 
250 /**
251  * fscrypt_decrypt_block_inplace() - Decrypt a filesystem block in-place
252  * @inode:     The inode to which this block belongs
253  * @page:      The page containing the block to decrypt
254  * @len:       Size of block to decrypt.  This must be a multiple of
255  *		FSCRYPT_CONTENTS_ALIGNMENT.
256  * @offs:      Byte offset within @page at which the block to decrypt begins
257  * @lblk_num:  Filesystem logical block number of the block, i.e. the 0-based
258  *		number of the block within the file
259  *
260  * Decrypt a possibly-compressed filesystem block that is located in an
261  * arbitrary page, not necessarily in the original pagecache page.  The @inode
262  * and @lblk_num must be specified, as they can't be determined from @page.
263  *
264  * This function only supports non-block-based filesystems that don't support
265  * sub-block data units (as indicated by the fscrypt_operations fields).
266  *
267  * Return: 0 on success; -errno on failure
268  */
269 int fscrypt_decrypt_block_inplace(const struct inode *inode, struct page *page,
270 				  unsigned int len, unsigned int offs,
271 				  u64 lblk_num)
272 {
273 	if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))
274 		return -EOPNOTSUPP;
275 	return fscrypt_crypt_data_unit(fscrypt_get_inode_info_raw(inode),
276 				       FS_DECRYPT, lblk_num, page, page, len,
277 				       offs);
278 }
279 EXPORT_SYMBOL(fscrypt_decrypt_block_inplace);
280 
281 /**
282  * fscrypt_initialize() - allocate major buffers for fs encryption.
283  * @sb: the filesystem superblock
284  *
285  * We only call this when we start accessing encrypted files, since it
286  * results in memory getting allocated that wouldn't otherwise be used.
287  *
288  * Return: 0 on success; -errno on failure
289  */
290 int fscrypt_initialize(struct super_block *sb)
291 {
292 	mempool_t *pool;
293 
294 	/* pairs with smp_store_release() below */
295 	if (smp_load_acquire(&fscrypt_bounce_page_pool))
296 		return 0;
297 
298 	/* No need to allocate a bounce page pool if this FS won't use it. */
299 	if (!sb->s_cop->needs_bounce_pages)
300 		return 0;
301 
302 	guard(mutex)(&fscrypt_init_mutex);
303 	if (fscrypt_bounce_page_pool)
304 		return 0;
305 
306 	pool = mempool_create_page_pool(num_prealloc_crypto_pages, 0);
307 	if (!pool)
308 		return -ENOMEM;
309 	/* pairs with smp_load_acquire() above */
310 	smp_store_release(&fscrypt_bounce_page_pool, pool);
311 	return 0;
312 }
313 
314 void fscrypt_msg(const struct inode *inode, const char *level,
315 		 const char *fmt, ...)
316 {
317 	static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
318 				      DEFAULT_RATELIMIT_BURST);
319 	struct va_format vaf;
320 	va_list args;
321 
322 	if (!__ratelimit(&rs))
323 		return;
324 
325 	va_start(args, fmt);
326 	vaf.fmt = fmt;
327 	vaf.va = &args;
328 	if (inode && inode->i_ino)
329 		printk("%sfscrypt (%s, inode %llu): %pV\n",
330 		       level, inode->i_sb->s_id, inode->i_ino, &vaf);
331 	else if (inode)
332 		printk("%sfscrypt (%s): %pV\n", level, inode->i_sb->s_id, &vaf);
333 	else
334 		printk("%sfscrypt: %pV\n", level, &vaf);
335 	va_end(args);
336 }
337 
338 static int __init fscrypt_init(void)
339 {
340 	fscrypt_inode_info_cachep = KMEM_CACHE(fscrypt_inode_info,
341 					       SLAB_RECLAIM_ACCOUNT |
342 					       SLAB_PANIC);
343 	fscrypt_init_keyring();
344 	return 0;
345 }
346 late_initcall(fscrypt_init)
347