// 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 = fscrypt_get_inode_info_raw(inode);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(fscrypt_get_inode_info_raw(inode),235FS_ENCRYPT, lblk_num, page, page, len,236offs);237}238EXPORT_SYMBOL(fscrypt_encrypt_block_inplace);239240/**241* fscrypt_decrypt_pagecache_blocks() - Decrypt data from a pagecache folio242* @folio: the pagecache folio containing the data to decrypt243* @len: size of the data to decrypt, in bytes244* @offs: offset within @folio of the data to decrypt, in bytes245*246* Decrypt data that has just been read from an encrypted file. The data must247* be located in a pagecache folio that is still locked and not yet uptodate.248* The length and offset of the data must be aligned to the file's crypto data249* unit size. Alignment to the filesystem block size fulfills this requirement,250* as the filesystem block size is always a multiple of the data unit size.251*252* Return: 0 on success; -errno on failure253*/254int fscrypt_decrypt_pagecache_blocks(struct folio *folio, size_t len,255size_t offs)256{257const struct inode *inode = folio->mapping->host;258const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);259const unsigned int du_bits = ci->ci_data_unit_bits;260const unsigned int du_size = 1U << du_bits;261u64 index = ((u64)folio->index << (PAGE_SHIFT - du_bits)) +262(offs >> du_bits);263size_t i;264int err;265266if (WARN_ON_ONCE(!folio_test_locked(folio)))267return -EINVAL;268269if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, du_size)))270return -EINVAL;271272for (i = offs; i < offs + len; i += du_size, index++) {273struct page *page = folio_page(folio, i >> PAGE_SHIFT);274275err = fscrypt_crypt_data_unit(ci, FS_DECRYPT, index, page,276page, du_size, i & ~PAGE_MASK);277if (err)278return err;279}280return 0;281}282EXPORT_SYMBOL(fscrypt_decrypt_pagecache_blocks);283284/**285* fscrypt_decrypt_block_inplace() - Decrypt a filesystem block in-place286* @inode: The inode to which this block belongs287* @page: The page containing the block to decrypt288* @len: Size of block to decrypt. This must be a multiple of289* FSCRYPT_CONTENTS_ALIGNMENT.290* @offs: Byte offset within @page at which the block to decrypt begins291* @lblk_num: Filesystem logical block number of the block, i.e. the 0-based292* number of the block within the file293*294* Decrypt a possibly-compressed filesystem block that is located in an295* arbitrary page, not necessarily in the original pagecache page. The @inode296* and @lblk_num must be specified, as they can't be determined from @page.297*298* This is not compatible with fscrypt_operations::supports_subblock_data_units.299*300* Return: 0 on success; -errno on failure301*/302int fscrypt_decrypt_block_inplace(const struct inode *inode, struct page *page,303unsigned int len, unsigned int offs,304u64 lblk_num)305{306if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))307return -EOPNOTSUPP;308return fscrypt_crypt_data_unit(fscrypt_get_inode_info_raw(inode),309FS_DECRYPT, lblk_num, page, page, len,310offs);311}312EXPORT_SYMBOL(fscrypt_decrypt_block_inplace);313314/**315* fscrypt_initialize() - allocate major buffers for fs encryption.316* @sb: the filesystem superblock317*318* We only call this when we start accessing encrypted files, since it319* results in memory getting allocated that wouldn't otherwise be used.320*321* Return: 0 on success; -errno on failure322*/323int fscrypt_initialize(struct super_block *sb)324{325int err = 0;326mempool_t *pool;327328/* pairs with smp_store_release() below */329if (likely(smp_load_acquire(&fscrypt_bounce_page_pool)))330return 0;331332/* No need to allocate a bounce page pool if this FS won't use it. */333if (!sb->s_cop->needs_bounce_pages)334return 0;335336mutex_lock(&fscrypt_init_mutex);337if (fscrypt_bounce_page_pool)338goto out_unlock;339340err = -ENOMEM;341pool = mempool_create_page_pool(num_prealloc_crypto_pages, 0);342if (!pool)343goto out_unlock;344/* pairs with smp_load_acquire() above */345smp_store_release(&fscrypt_bounce_page_pool, pool);346err = 0;347out_unlock:348mutex_unlock(&fscrypt_init_mutex);349return err;350}351352void fscrypt_msg(const struct inode *inode, const char *level,353const char *fmt, ...)354{355static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,356DEFAULT_RATELIMIT_BURST);357struct va_format vaf;358va_list args;359360if (!__ratelimit(&rs))361return;362363va_start(args, fmt);364vaf.fmt = fmt;365vaf.va = &args;366if (inode && inode->i_ino)367printk("%sfscrypt (%s, inode %lu): %pV\n",368level, inode->i_sb->s_id, inode->i_ino, &vaf);369else if (inode)370printk("%sfscrypt (%s): %pV\n", level, inode->i_sb->s_id, &vaf);371else372printk("%sfscrypt: %pV\n", level, &vaf);373va_end(args);374}375376/**377* fscrypt_init() - Set up for fs encryption.378*379* Return: 0 on success; -errno on failure380*/381static int __init fscrypt_init(void)382{383int err = -ENOMEM;384385/*386* Use an unbound workqueue to allow bios to be decrypted in parallel387* even when they happen to complete on the same CPU. This sacrifices388* locality, but it's worthwhile since decryption is CPU-intensive.389*390* Also use a high-priority workqueue to prioritize decryption work,391* which blocks reads from completing, over regular application tasks.392*/393fscrypt_read_workqueue = alloc_workqueue("fscrypt_read_queue",394WQ_UNBOUND | WQ_HIGHPRI,395num_online_cpus());396if (!fscrypt_read_workqueue)397goto fail;398399fscrypt_inode_info_cachep = KMEM_CACHE(fscrypt_inode_info,400SLAB_RECLAIM_ACCOUNT);401if (!fscrypt_inode_info_cachep)402goto fail_free_queue;403404err = fscrypt_init_keyring();405if (err)406goto fail_free_inode_info;407408return 0;409410fail_free_inode_info:411kmem_cache_destroy(fscrypt_inode_info_cachep);412fail_free_queue:413destroy_workqueue(fscrypt_read_workqueue);414fail:415return err;416}417late_initcall(fscrypt_init)418419420