// SPDX-License-Identifier: GPL-2.0-only1/*2* This contains encryption functions for per-file encryption.3*4* Copyright (C) 2015, Google, Inc.5* Copyright (C) 2015, Motorola Mobility6*7* Written by Michael Halcrow, 2014.8*9* Filename encryption additions10* Uday Savagaonkar, 201411* Encryption policy handling additions12* Ildar Muslukhov, 201413* Add fscrypt_pullback_bio_page()14* Jaegeuk Kim, 2015.15*16* This has not yet undergone a rigorous security audit.17*18* The usage of AES-XTS should conform to recommendations in NIST19* Special Publication 800-38E and IEEE P1619/D16.20*/2122#include <crypto/skcipher.h>23#include <linux/export.h>24#include <linux/mempool.h>25#include <linux/module.h>26#include <linux/pagemap.h>27#include <linux/ratelimit.h>28#include <linux/scatterlist.h>2930#include "fscrypt_private.h"3132static unsigned int num_prealloc_crypto_pages = 32;3334module_param(num_prealloc_crypto_pages, uint, 0444);35MODULE_PARM_DESC(num_prealloc_crypto_pages,36"Number of crypto pages to preallocate");3738static mempool_t *fscrypt_bounce_page_pool = NULL;3940static struct workqueue_struct *fscrypt_read_workqueue;41static DEFINE_MUTEX(fscrypt_init_mutex);4243struct kmem_cache *fscrypt_inode_info_cachep;4445void fscrypt_enqueue_decrypt_work(struct work_struct *work)46{47queue_work(fscrypt_read_workqueue, work);48}49EXPORT_SYMBOL(fscrypt_enqueue_decrypt_work);5051struct page *fscrypt_alloc_bounce_page(gfp_t gfp_flags)52{53if (WARN_ON_ONCE(!fscrypt_bounce_page_pool)) {54/*55* Oops, the filesystem called a function that uses the bounce56* page pool, but it didn't set needs_bounce_pages.57*/58return NULL;59}60return mempool_alloc(fscrypt_bounce_page_pool, gfp_flags);61}6263/**64* fscrypt_free_bounce_page() - free a ciphertext bounce page65* @bounce_page: the bounce page to free, or NULL66*67* Free a bounce page that was allocated by fscrypt_encrypt_pagecache_blocks(),68* or by fscrypt_alloc_bounce_page() directly.69*/70void fscrypt_free_bounce_page(struct page *bounce_page)71{72if (!bounce_page)73return;74set_page_private(bounce_page, (unsigned long)NULL);75ClearPagePrivate(bounce_page);76mempool_free(bounce_page, fscrypt_bounce_page_pool);77}78EXPORT_SYMBOL(fscrypt_free_bounce_page);7980/*81* Generate the IV for the given data unit index within the given file.82* For filenames encryption, index == 0.83*84* Keep this in sync with fscrypt_limit_io_blocks(). fscrypt_limit_io_blocks()85* needs to know about any IV generation methods where the low bits of IV don't86* simply contain the data unit index (e.g., IV_INO_LBLK_32).87*/88void fscrypt_generate_iv(union fscrypt_iv *iv, u64 index,89const struct fscrypt_inode_info *ci)90{91u8 flags = fscrypt_policy_flags(&ci->ci_policy);9293memset(iv, 0, ci->ci_mode->ivsize);9495if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {96WARN_ON_ONCE(index > U32_MAX);97WARN_ON_ONCE(ci->ci_inode->i_ino > U32_MAX);98index |= (u64)ci->ci_inode->i_ino << 32;99} else if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {100WARN_ON_ONCE(index > U32_MAX);101index = (u32)(ci->ci_hashed_ino + index);102} else if (flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {103memcpy(iv->nonce, ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE);104}105iv->index = cpu_to_le64(index);106}107108/* Encrypt or decrypt a single "data unit" of file contents. */109int fscrypt_crypt_data_unit(const struct fscrypt_inode_info *ci,110fscrypt_direction_t rw, u64 index,111struct page *src_page, struct page *dest_page,112unsigned int len, unsigned int offs)113{114struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;115SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);116union fscrypt_iv iv;117struct scatterlist dst, src;118int err;119120if (WARN_ON_ONCE(len <= 0))121return -EINVAL;122if (WARN_ON_ONCE(len % FSCRYPT_CONTENTS_ALIGNMENT != 0))123return -EINVAL;124125fscrypt_generate_iv(&iv, index, ci);126127skcipher_request_set_callback(128req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,129NULL, NULL);130sg_init_table(&dst, 1);131sg_set_page(&dst, dest_page, len, offs);132sg_init_table(&src, 1);133sg_set_page(&src, src_page, len, offs);134skcipher_request_set_crypt(req, &src, &dst, len, &iv);135if (rw == FS_DECRYPT)136err = crypto_skcipher_decrypt(req);137else138err = crypto_skcipher_encrypt(req);139if (err)140fscrypt_err(ci->ci_inode,141"%scryption failed for data unit %llu: %d",142(rw == FS_DECRYPT ? "De" : "En"), index, err);143return err;144}145146/**147* fscrypt_encrypt_pagecache_blocks() - Encrypt data from a pagecache folio148* @folio: the locked pagecache folio containing the data to encrypt149* @len: size of the data to encrypt, in bytes150* @offs: offset within @page of the data to encrypt, in bytes151* @gfp_flags: memory allocation flags; see details below152*153* This allocates a new bounce page and encrypts the given data into it. The154* length and offset of the data must be aligned to the file's crypto data unit155* size. Alignment to the filesystem block size fulfills this requirement, as156* the filesystem block size is always a multiple of the data unit size.157*158* In the bounce page, the ciphertext data will be located at the same offset at159* which the plaintext data was located in the source page. Any other parts of160* the bounce page will be left uninitialized.161*162* This is for use by the filesystem's ->writepages() method.163*164* The bounce page allocation is mempool-backed, so it will always succeed when165* @gfp_flags includes __GFP_DIRECT_RECLAIM, e.g. when it's GFP_NOFS. However,166* only the first page of each bio can be allocated this way. To prevent167* deadlocks, for any additional pages a mask like GFP_NOWAIT must be used.168*169* Return: the new encrypted bounce page on success; an ERR_PTR() on failure170*/171struct page *fscrypt_encrypt_pagecache_blocks(struct folio *folio,172size_t len, size_t offs, gfp_t gfp_flags)173{174const struct inode *inode = folio->mapping->host;175const struct fscrypt_inode_info *ci = inode->i_crypt_info;176const unsigned int du_bits = ci->ci_data_unit_bits;177const unsigned int du_size = 1U << du_bits;178struct page *ciphertext_page;179u64 index = ((u64)folio->index << (PAGE_SHIFT - du_bits)) +180(offs >> du_bits);181unsigned int i;182int err;183184VM_BUG_ON_FOLIO(folio_test_large(folio), folio);185if (WARN_ON_ONCE(!folio_test_locked(folio)))186return ERR_PTR(-EINVAL);187188if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, du_size)))189return ERR_PTR(-EINVAL);190191ciphertext_page = fscrypt_alloc_bounce_page(gfp_flags);192if (!ciphertext_page)193return ERR_PTR(-ENOMEM);194195for (i = offs; i < offs + len; i += du_size, index++) {196err = fscrypt_crypt_data_unit(ci, FS_ENCRYPT, index,197&folio->page, ciphertext_page,198du_size, i);199if (err) {200fscrypt_free_bounce_page(ciphertext_page);201return ERR_PTR(err);202}203}204SetPagePrivate(ciphertext_page);205set_page_private(ciphertext_page, (unsigned long)folio);206return ciphertext_page;207}208EXPORT_SYMBOL(fscrypt_encrypt_pagecache_blocks);209210/**211* fscrypt_encrypt_block_inplace() - Encrypt a filesystem block in-place212* @inode: The inode to which this block belongs213* @page: The page containing the block to encrypt214* @len: Size of block to encrypt. This must be a multiple of215* FSCRYPT_CONTENTS_ALIGNMENT.216* @offs: Byte offset within @page at which the block to encrypt begins217* @lblk_num: Filesystem logical block number of the block, i.e. the 0-based218* number of the block within the file219*220* Encrypt a possibly-compressed filesystem block that is located in an221* arbitrary page, not necessarily in the original pagecache page. The @inode222* and @lblk_num must be specified, as they can't be determined from @page.223*224* This is not compatible with fscrypt_operations::supports_subblock_data_units.225*226* Return: 0 on success; -errno on failure227*/228int fscrypt_encrypt_block_inplace(const struct inode *inode, struct page *page,229unsigned int len, unsigned int offs,230u64 lblk_num)231{232if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))233return -EOPNOTSUPP;234return fscrypt_crypt_data_unit(inode->i_crypt_info, FS_ENCRYPT,235lblk_num, page, page, len, offs);236}237EXPORT_SYMBOL(fscrypt_encrypt_block_inplace);238239/**240* fscrypt_decrypt_pagecache_blocks() - Decrypt data from a pagecache folio241* @folio: the pagecache folio containing the data to decrypt242* @len: size of the data to decrypt, in bytes243* @offs: offset within @folio of the data to decrypt, in bytes244*245* Decrypt data that has just been read from an encrypted file. The data must246* be located in a pagecache folio that is still locked and not yet uptodate.247* The length and offset of the data must be aligned to the file's crypto data248* unit size. Alignment to the filesystem block size fulfills this requirement,249* as the filesystem block size is always a multiple of the data unit size.250*251* Return: 0 on success; -errno on failure252*/253int fscrypt_decrypt_pagecache_blocks(struct folio *folio, size_t len,254size_t offs)255{256const struct inode *inode = folio->mapping->host;257const struct fscrypt_inode_info *ci = inode->i_crypt_info;258const unsigned int du_bits = ci->ci_data_unit_bits;259const unsigned int du_size = 1U << du_bits;260u64 index = ((u64)folio->index << (PAGE_SHIFT - du_bits)) +261(offs >> du_bits);262size_t i;263int err;264265if (WARN_ON_ONCE(!folio_test_locked(folio)))266return -EINVAL;267268if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, du_size)))269return -EINVAL;270271for (i = offs; i < offs + len; i += du_size, index++) {272struct page *page = folio_page(folio, i >> PAGE_SHIFT);273274err = fscrypt_crypt_data_unit(ci, FS_DECRYPT, index, page,275page, du_size, i & ~PAGE_MASK);276if (err)277return err;278}279return 0;280}281EXPORT_SYMBOL(fscrypt_decrypt_pagecache_blocks);282283/**284* fscrypt_decrypt_block_inplace() - Decrypt a filesystem block in-place285* @inode: The inode to which this block belongs286* @page: The page containing the block to decrypt287* @len: Size of block to decrypt. This must be a multiple of288* FSCRYPT_CONTENTS_ALIGNMENT.289* @offs: Byte offset within @page at which the block to decrypt begins290* @lblk_num: Filesystem logical block number of the block, i.e. the 0-based291* number of the block within the file292*293* Decrypt a possibly-compressed filesystem block that is located in an294* arbitrary page, not necessarily in the original pagecache page. The @inode295* and @lblk_num must be specified, as they can't be determined from @page.296*297* This is not compatible with fscrypt_operations::supports_subblock_data_units.298*299* Return: 0 on success; -errno on failure300*/301int fscrypt_decrypt_block_inplace(const struct inode *inode, struct page *page,302unsigned int len, unsigned int offs,303u64 lblk_num)304{305if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))306return -EOPNOTSUPP;307return fscrypt_crypt_data_unit(inode->i_crypt_info, FS_DECRYPT,308lblk_num, page, page, len, offs);309}310EXPORT_SYMBOL(fscrypt_decrypt_block_inplace);311312/**313* fscrypt_initialize() - allocate major buffers for fs encryption.314* @sb: the filesystem superblock315*316* We only call this when we start accessing encrypted files, since it317* results in memory getting allocated that wouldn't otherwise be used.318*319* Return: 0 on success; -errno on failure320*/321int fscrypt_initialize(struct super_block *sb)322{323int err = 0;324mempool_t *pool;325326/* pairs with smp_store_release() below */327if (likely(smp_load_acquire(&fscrypt_bounce_page_pool)))328return 0;329330/* No need to allocate a bounce page pool if this FS won't use it. */331if (!sb->s_cop->needs_bounce_pages)332return 0;333334mutex_lock(&fscrypt_init_mutex);335if (fscrypt_bounce_page_pool)336goto out_unlock;337338err = -ENOMEM;339pool = mempool_create_page_pool(num_prealloc_crypto_pages, 0);340if (!pool)341goto out_unlock;342/* pairs with smp_load_acquire() above */343smp_store_release(&fscrypt_bounce_page_pool, pool);344err = 0;345out_unlock:346mutex_unlock(&fscrypt_init_mutex);347return err;348}349350void fscrypt_msg(const struct inode *inode, const char *level,351const char *fmt, ...)352{353static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,354DEFAULT_RATELIMIT_BURST);355struct va_format vaf;356va_list args;357358if (!__ratelimit(&rs))359return;360361va_start(args, fmt);362vaf.fmt = fmt;363vaf.va = &args;364if (inode && inode->i_ino)365printk("%sfscrypt (%s, inode %lu): %pV\n",366level, inode->i_sb->s_id, inode->i_ino, &vaf);367else if (inode)368printk("%sfscrypt (%s): %pV\n", level, inode->i_sb->s_id, &vaf);369else370printk("%sfscrypt: %pV\n", level, &vaf);371va_end(args);372}373374/**375* fscrypt_init() - Set up for fs encryption.376*377* Return: 0 on success; -errno on failure378*/379static int __init fscrypt_init(void)380{381int err = -ENOMEM;382383/*384* Use an unbound workqueue to allow bios to be decrypted in parallel385* even when they happen to complete on the same CPU. This sacrifices386* locality, but it's worthwhile since decryption is CPU-intensive.387*388* Also use a high-priority workqueue to prioritize decryption work,389* which blocks reads from completing, over regular application tasks.390*/391fscrypt_read_workqueue = alloc_workqueue("fscrypt_read_queue",392WQ_UNBOUND | WQ_HIGHPRI,393num_online_cpus());394if (!fscrypt_read_workqueue)395goto fail;396397fscrypt_inode_info_cachep = KMEM_CACHE(fscrypt_inode_info,398SLAB_RECLAIM_ACCOUNT);399if (!fscrypt_inode_info_cachep)400goto fail_free_queue;401402err = fscrypt_init_keyring();403if (err)404goto fail_free_inode_info;405406return 0;407408fail_free_inode_info:409kmem_cache_destroy(fscrypt_inode_info_cachep);410fail_free_queue:411destroy_workqueue(fscrypt_read_workqueue);412fail:413return err;414}415late_initcall(fscrypt_init)416417418