// SPDX-License-Identifier: GPL-2.01/*2* This contains functions for filename crypto management3*4* Copyright (C) 2015, Google, Inc.5* Copyright (C) 2015, Motorola Mobility6*7* Written by Uday Savagaonkar, 2014.8* Modified by Jaegeuk Kim, 2015.9*10* This has not yet undergone a rigorous security audit.11*/1213#include <crypto/sha2.h>14#include <crypto/skcipher.h>15#include <linux/export.h>16#include <linux/namei.h>17#include <linux/scatterlist.h>18#include <linux/base64.h>1920#include "fscrypt_private.h"2122/*23* The minimum message length (input and output length), in bytes, for all24* filenames encryption modes. Filenames shorter than this will be zero-padded25* before being encrypted.26*/27#define FSCRYPT_FNAME_MIN_MSG_LEN 162829/*30* struct fscrypt_nokey_name - identifier for directory entry when key is absent31*32* When userspace lists an encrypted directory without access to the key, the33* filesystem must present a unique "no-key name" for each filename that allows34* it to find the directory entry again if requested. Naively, that would just35* mean using the ciphertext filenames. However, since the ciphertext filenames36* can contain illegal characters ('\0' and '/'), they must be encoded in some37* way. We use base64url. But that can cause names to exceed NAME_MAX (25538* bytes), so we also need to use a strong hash to abbreviate long names.39*40* The filesystem may also need another kind of hash, the "dirhash", to quickly41* find the directory entry. Since filesystems normally compute the dirhash42* over the on-disk filename (i.e. the ciphertext), it's not computable from43* no-key names that abbreviate the ciphertext using the strong hash to fit in44* NAME_MAX. It's also not computable if it's a keyed hash taken over the45* plaintext (but it may still be available in the on-disk directory entry);46* casefolded directories use this type of dirhash. At least in these cases,47* each no-key name must include the name's dirhash too.48*49* To meet all these requirements, we base64url-encode the following50* variable-length structure. It contains the dirhash, or 0's if the filesystem51* didn't provide one; up to 149 bytes of the ciphertext name; and for52* ciphertexts longer than 149 bytes, also the SHA-256 of the remaining bytes.53*54* This ensures that each no-key name contains everything needed to find the55* directory entry again, contains only legal characters, doesn't exceed56* NAME_MAX, is unambiguous unless there's a SHA-256 collision, and that we only57* take the performance hit of SHA-256 on very long filenames (which are rare).58*/59struct fscrypt_nokey_name {60u32 dirhash[2];61u8 bytes[149];62u8 sha256[SHA256_DIGEST_SIZE];63}; /* 189 bytes => 252 bytes base64url-encoded, which is <= NAME_MAX (255) */6465/*66* Decoded size of max-size no-key name, i.e. a name that was abbreviated using67* the strong hash and thus includes the 'sha256' field. This isn't simply68* sizeof(struct fscrypt_nokey_name), as the padding at the end isn't included.69*/70#define FSCRYPT_NOKEY_NAME_MAX offsetofend(struct fscrypt_nokey_name, sha256)7172/* Encoded size of max-size no-key name */73#define FSCRYPT_NOKEY_NAME_MAX_ENCODED \74BASE64_CHARS(FSCRYPT_NOKEY_NAME_MAX)7576static inline bool fscrypt_is_dot_dotdot(const struct qstr *str)77{78return is_dot_dotdot(str->name, str->len);79}8081/**82* fscrypt_fname_encrypt() - encrypt a filename83* @inode: inode of the parent directory (for regular filenames)84* or of the symlink (for symlink targets). Key must already be85* set up.86* @iname: the filename to encrypt87* @out: (output) the encrypted filename88* @olen: size of the encrypted filename. It must be at least @iname->len.89* Any extra space is filled with NUL padding before encryption.90*91* Return: 0 on success, -errno on failure92*/93int fscrypt_fname_encrypt(const struct inode *inode, const struct qstr *iname,94u8 *out, unsigned int olen)95{96const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);97struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;98SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);99union fscrypt_iv iv;100struct scatterlist sg;101int err;102103/*104* Copy the filename to the output buffer for encrypting in-place and105* pad it with the needed number of NUL bytes.106*/107if (WARN_ON_ONCE(olen < iname->len))108return -ENOBUFS;109memcpy(out, iname->name, iname->len);110memset(out + iname->len, 0, olen - iname->len);111112fscrypt_generate_iv(&iv, 0, ci);113114skcipher_request_set_callback(115req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,116NULL, NULL);117sg_init_one(&sg, out, olen);118skcipher_request_set_crypt(req, &sg, &sg, olen, &iv);119err = crypto_skcipher_encrypt(req);120if (err)121fscrypt_err(inode, "Filename encryption failed: %d", err);122return err;123}124EXPORT_SYMBOL_GPL(fscrypt_fname_encrypt);125126/**127* fname_decrypt() - decrypt a filename128* @inode: inode of the parent directory (for regular filenames)129* or of the symlink (for symlink targets)130* @iname: the encrypted filename to decrypt131* @oname: (output) the decrypted filename. The caller must have allocated132* enough space for this, e.g. using fscrypt_fname_alloc_buffer().133*134* Return: 0 on success, -errno on failure135*/136static int fname_decrypt(const struct inode *inode,137const struct fscrypt_str *iname,138struct fscrypt_str *oname)139{140const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);141struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;142SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);143union fscrypt_iv iv;144struct scatterlist src_sg, dst_sg;145int err;146147fscrypt_generate_iv(&iv, 0, ci);148149skcipher_request_set_callback(150req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,151NULL, NULL);152sg_init_one(&src_sg, iname->name, iname->len);153sg_init_one(&dst_sg, oname->name, oname->len);154skcipher_request_set_crypt(req, &src_sg, &dst_sg, iname->len, &iv);155err = crypto_skcipher_decrypt(req);156if (err) {157fscrypt_err(inode, "Filename decryption failed: %d", err);158return err;159}160161oname->len = strnlen(oname->name, iname->len);162return 0;163}164165bool __fscrypt_fname_encrypted_size(const union fscrypt_policy *policy,166u32 orig_len, u32 max_len,167u32 *encrypted_len_ret)168{169int padding = 4 << (fscrypt_policy_flags(policy) &170FSCRYPT_POLICY_FLAGS_PAD_MASK);171u32 encrypted_len;172173if (orig_len > max_len)174return false;175encrypted_len = max_t(u32, orig_len, FSCRYPT_FNAME_MIN_MSG_LEN);176encrypted_len = round_up(encrypted_len, padding);177*encrypted_len_ret = min(encrypted_len, max_len);178return true;179}180181/**182* fscrypt_fname_encrypted_size() - calculate length of encrypted filename183* @inode: parent inode of dentry name being encrypted. Key must184* already be set up.185* @orig_len: length of the original filename186* @max_len: maximum length to return187* @encrypted_len_ret: where calculated length should be returned (on success)188*189* Filenames that are shorter than the maximum length may have their lengths190* increased slightly by encryption, due to padding that is applied.191*192* Return: false if the orig_len is greater than max_len. Otherwise, true and193* fill out encrypted_len_ret with the length (up to max_len).194*/195bool fscrypt_fname_encrypted_size(const struct inode *inode, u32 orig_len,196u32 max_len, u32 *encrypted_len_ret)197{198const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);199200return __fscrypt_fname_encrypted_size(&ci->ci_policy, orig_len, max_len,201encrypted_len_ret);202}203EXPORT_SYMBOL_GPL(fscrypt_fname_encrypted_size);204205/**206* fscrypt_fname_alloc_buffer() - allocate a buffer for presented filenames207* @max_encrypted_len: maximum length of encrypted filenames the buffer will be208* used to present209* @crypto_str: (output) buffer to allocate210*211* Allocate a buffer that is large enough to hold any decrypted or encoded212* filename (null-terminated), for the given maximum encrypted filename length.213*214* Return: 0 on success, -errno on failure215*/216int fscrypt_fname_alloc_buffer(u32 max_encrypted_len,217struct fscrypt_str *crypto_str)218{219u32 max_presented_len = max_t(u32, FSCRYPT_NOKEY_NAME_MAX_ENCODED,220max_encrypted_len);221222crypto_str->name = kmalloc(max_presented_len + 1, GFP_NOFS);223if (!crypto_str->name)224return -ENOMEM;225crypto_str->len = max_presented_len;226return 0;227}228EXPORT_SYMBOL(fscrypt_fname_alloc_buffer);229230/**231* fscrypt_fname_free_buffer() - free a buffer for presented filenames232* @crypto_str: the buffer to free233*234* Free a buffer that was allocated by fscrypt_fname_alloc_buffer().235*/236void fscrypt_fname_free_buffer(struct fscrypt_str *crypto_str)237{238if (!crypto_str)239return;240kfree(crypto_str->name);241crypto_str->name = NULL;242}243EXPORT_SYMBOL(fscrypt_fname_free_buffer);244245/**246* fscrypt_fname_disk_to_usr() - convert an encrypted filename to247* user-presentable form248* @inode: inode of the parent directory (for regular filenames)249* or of the symlink (for symlink targets)250* @hash: first part of the name's dirhash, if applicable. This only needs to251* be provided if the filename is located in an indexed directory whose252* encryption key may be unavailable. Not needed for symlink targets.253* @minor_hash: second part of the name's dirhash, if applicable254* @iname: encrypted filename to convert. May also be "." or "..", which255* aren't actually encrypted.256* @oname: output buffer for the user-presentable filename. The caller must257* have allocated enough space for this, e.g. using258* fscrypt_fname_alloc_buffer().259*260* If the key is available, we'll decrypt the disk name. Otherwise, we'll261* encode it for presentation in fscrypt_nokey_name format.262* See struct fscrypt_nokey_name for details.263*264* Return: 0 on success, -errno on failure265*/266int fscrypt_fname_disk_to_usr(const struct inode *inode,267u32 hash, u32 minor_hash,268const struct fscrypt_str *iname,269struct fscrypt_str *oname)270{271const struct qstr qname = FSTR_TO_QSTR(iname);272struct fscrypt_nokey_name nokey_name;273u32 size; /* size of the unencoded no-key name */274275if (fscrypt_is_dot_dotdot(&qname)) {276oname->name[0] = '.';277oname->name[iname->len - 1] = '.';278oname->len = iname->len;279return 0;280}281282if (iname->len < FSCRYPT_FNAME_MIN_MSG_LEN)283return -EUCLEAN;284285if (fscrypt_has_encryption_key(inode))286return fname_decrypt(inode, iname, oname);287288/*289* Sanity check that struct fscrypt_nokey_name doesn't have padding290* between fields and that its encoded size never exceeds NAME_MAX.291*/292BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, dirhash) !=293offsetof(struct fscrypt_nokey_name, bytes));294BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, bytes) !=295offsetof(struct fscrypt_nokey_name, sha256));296BUILD_BUG_ON(FSCRYPT_NOKEY_NAME_MAX_ENCODED > NAME_MAX);297298nokey_name.dirhash[0] = hash;299nokey_name.dirhash[1] = minor_hash;300301if (iname->len <= sizeof(nokey_name.bytes)) {302memcpy(nokey_name.bytes, iname->name, iname->len);303size = offsetof(struct fscrypt_nokey_name, bytes[iname->len]);304} else {305memcpy(nokey_name.bytes, iname->name, sizeof(nokey_name.bytes));306/* Compute strong hash of remaining part of name. */307sha256(&iname->name[sizeof(nokey_name.bytes)],308iname->len - sizeof(nokey_name.bytes),309nokey_name.sha256);310size = FSCRYPT_NOKEY_NAME_MAX;311}312oname->len = base64_encode((const u8 *)&nokey_name, size,313oname->name, false, BASE64_URLSAFE);314return 0;315}316EXPORT_SYMBOL(fscrypt_fname_disk_to_usr);317318/**319* fscrypt_setup_filename() - prepare to search a possibly encrypted directory320* @dir: the directory that will be searched321* @iname: the user-provided filename being searched for322* @lookup: 1 if we're allowed to proceed without the key because it's323* ->lookup() or we're finding the dir_entry for deletion; 0 if we cannot324* proceed without the key because we're going to create the dir_entry.325* @fname: the filename information to be filled in326*327* Given a user-provided filename @iname, this function sets @fname->disk_name328* to the name that would be stored in the on-disk directory entry, if possible.329* If the directory is unencrypted this is simply @iname. Else, if we have the330* directory's encryption key, then @iname is the plaintext, so we encrypt it to331* get the disk_name.332*333* Else, for keyless @lookup operations, @iname should be a no-key name, so we334* decode it to get the struct fscrypt_nokey_name. Non-@lookup operations will335* be impossible in this case, so we fail them with ENOKEY.336*337* If successful, fscrypt_free_filename() must be called later to clean up.338*339* Return: 0 on success, -errno on failure340*/341int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,342int lookup, struct fscrypt_name *fname)343{344struct fscrypt_nokey_name *nokey_name;345int ret;346347memset(fname, 0, sizeof(struct fscrypt_name));348fname->usr_fname = iname;349350if (!IS_ENCRYPTED(dir) || fscrypt_is_dot_dotdot(iname)) {351fname->disk_name.name = (unsigned char *)iname->name;352fname->disk_name.len = iname->len;353return 0;354}355ret = fscrypt_get_encryption_info(dir, lookup);356if (ret)357return ret;358359if (fscrypt_has_encryption_key(dir)) {360if (!fscrypt_fname_encrypted_size(dir, iname->len, NAME_MAX,361&fname->crypto_buf.len))362return -ENAMETOOLONG;363fname->crypto_buf.name = kmalloc(fname->crypto_buf.len,364GFP_NOFS);365if (!fname->crypto_buf.name)366return -ENOMEM;367368ret = fscrypt_fname_encrypt(dir, iname, fname->crypto_buf.name,369fname->crypto_buf.len);370if (ret)371goto errout;372fname->disk_name.name = fname->crypto_buf.name;373fname->disk_name.len = fname->crypto_buf.len;374return 0;375}376if (!lookup)377return -ENOKEY;378fname->is_nokey_name = true;379380/*381* We don't have the key and we are doing a lookup; decode the382* user-supplied name383*/384385if (iname->len > FSCRYPT_NOKEY_NAME_MAX_ENCODED)386return -ENOENT;387388fname->crypto_buf.name = kmalloc(FSCRYPT_NOKEY_NAME_MAX, GFP_KERNEL);389if (fname->crypto_buf.name == NULL)390return -ENOMEM;391392ret = base64_decode(iname->name, iname->len,393fname->crypto_buf.name, false, BASE64_URLSAFE);394if (ret < (int)offsetof(struct fscrypt_nokey_name, bytes[1]) ||395(ret > offsetof(struct fscrypt_nokey_name, sha256) &&396ret != FSCRYPT_NOKEY_NAME_MAX)) {397ret = -ENOENT;398goto errout;399}400fname->crypto_buf.len = ret;401402nokey_name = (void *)fname->crypto_buf.name;403fname->hash = nokey_name->dirhash[0];404fname->minor_hash = nokey_name->dirhash[1];405if (ret != FSCRYPT_NOKEY_NAME_MAX) {406/* The full ciphertext filename is available. */407fname->disk_name.name = nokey_name->bytes;408fname->disk_name.len =409ret - offsetof(struct fscrypt_nokey_name, bytes);410}411return 0;412413errout:414kfree(fname->crypto_buf.name);415return ret;416}417EXPORT_SYMBOL(fscrypt_setup_filename);418419/**420* fscrypt_match_name() - test whether the given name matches a directory entry421* @fname: the name being searched for422* @de_name: the name from the directory entry423* @de_name_len: the length of @de_name in bytes424*425* Normally @fname->disk_name will be set, and in that case we simply compare426* that to the name stored in the directory entry. The only exception is that427* if we don't have the key for an encrypted directory and the name we're428* looking for is very long, then we won't have the full disk_name and instead429* we'll need to match against a fscrypt_nokey_name that includes a strong hash.430*431* Return: %true if the name matches, otherwise %false.432*/433bool fscrypt_match_name(const struct fscrypt_name *fname,434const u8 *de_name, u32 de_name_len)435{436const struct fscrypt_nokey_name *nokey_name =437(const void *)fname->crypto_buf.name;438u8 digest[SHA256_DIGEST_SIZE];439440if (likely(fname->disk_name.name)) {441if (de_name_len != fname->disk_name.len)442return false;443return !memcmp(de_name, fname->disk_name.name, de_name_len);444}445if (de_name_len <= sizeof(nokey_name->bytes))446return false;447if (memcmp(de_name, nokey_name->bytes, sizeof(nokey_name->bytes)))448return false;449sha256(&de_name[sizeof(nokey_name->bytes)],450de_name_len - sizeof(nokey_name->bytes), digest);451return !memcmp(digest, nokey_name->sha256, sizeof(digest));452}453EXPORT_SYMBOL_GPL(fscrypt_match_name);454455/**456* fscrypt_fname_siphash() - calculate the SipHash of a filename457* @dir: the parent directory458* @name: the filename to calculate the SipHash of459*460* Given a plaintext filename @name and a directory @dir which uses SipHash as461* its dirhash method and has had its fscrypt key set up, this function462* calculates the SipHash of that name using the directory's secret dirhash key.463*464* Return: the SipHash of @name using the hash key of @dir465*/466u64 fscrypt_fname_siphash(const struct inode *dir, const struct qstr *name)467{468const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(dir);469470WARN_ON_ONCE(!ci->ci_dirhash_key_initialized);471472return siphash(name->name, name->len, &ci->ci_dirhash_key);473}474EXPORT_SYMBOL_GPL(fscrypt_fname_siphash);475476/*477* Validate dentries in encrypted directories to make sure we aren't potentially478* caching stale dentries after a key has been added.479*/480int fscrypt_d_revalidate(struct inode *dir, const struct qstr *name,481struct dentry *dentry, unsigned int flags)482{483int err;484485/*486* Plaintext names are always valid, since fscrypt doesn't support487* reverting to no-key names without evicting the directory's inode488* -- which implies eviction of the dentries in the directory.489*/490if (!(dentry->d_flags & DCACHE_NOKEY_NAME))491return 1;492493/*494* No-key name; valid if the directory's key is still unavailable.495*496* Note in RCU mode we have to bail if we get here -497* fscrypt_get_encryption_info() may block.498*/499500if (flags & LOOKUP_RCU)501return -ECHILD;502503/*504* Pass allow_unsupported=true, so that files with an unsupported505* encryption policy can be deleted.506*/507err = fscrypt_get_encryption_info(dir, true);508if (err < 0)509return err;510511return !fscrypt_has_encryption_key(dir);512}513EXPORT_SYMBOL_GPL(fscrypt_d_revalidate);514515516