// 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>1819#include "fscrypt_private.h"2021/*22* The minimum message length (input and output length), in bytes, for all23* filenames encryption modes. Filenames shorter than this will be zero-padded24* before being encrypted.25*/26#define FSCRYPT_FNAME_MIN_MSG_LEN 162728/*29* struct fscrypt_nokey_name - identifier for directory entry when key is absent30*31* When userspace lists an encrypted directory without access to the key, the32* filesystem must present a unique "no-key name" for each filename that allows33* it to find the directory entry again if requested. Naively, that would just34* mean using the ciphertext filenames. However, since the ciphertext filenames35* can contain illegal characters ('\0' and '/'), they must be encoded in some36* way. We use base64url. But that can cause names to exceed NAME_MAX (25537* bytes), so we also need to use a strong hash to abbreviate long names.38*39* The filesystem may also need another kind of hash, the "dirhash", to quickly40* find the directory entry. Since filesystems normally compute the dirhash41* over the on-disk filename (i.e. the ciphertext), it's not computable from42* no-key names that abbreviate the ciphertext using the strong hash to fit in43* NAME_MAX. It's also not computable if it's a keyed hash taken over the44* plaintext (but it may still be available in the on-disk directory entry);45* casefolded directories use this type of dirhash. At least in these cases,46* each no-key name must include the name's dirhash too.47*48* To meet all these requirements, we base64url-encode the following49* variable-length structure. It contains the dirhash, or 0's if the filesystem50* didn't provide one; up to 149 bytes of the ciphertext name; and for51* ciphertexts longer than 149 bytes, also the SHA-256 of the remaining bytes.52*53* This ensures that each no-key name contains everything needed to find the54* directory entry again, contains only legal characters, doesn't exceed55* NAME_MAX, is unambiguous unless there's a SHA-256 collision, and that we only56* take the performance hit of SHA-256 on very long filenames (which are rare).57*/58struct fscrypt_nokey_name {59u32 dirhash[2];60u8 bytes[149];61u8 sha256[SHA256_DIGEST_SIZE];62}; /* 189 bytes => 252 bytes base64url-encoded, which is <= NAME_MAX (255) */6364/*65* Decoded size of max-size no-key name, i.e. a name that was abbreviated using66* the strong hash and thus includes the 'sha256' field. This isn't simply67* sizeof(struct fscrypt_nokey_name), as the padding at the end isn't included.68*/69#define FSCRYPT_NOKEY_NAME_MAX offsetofend(struct fscrypt_nokey_name, sha256)7071/* Encoded size of max-size no-key name */72#define FSCRYPT_NOKEY_NAME_MAX_ENCODED \73FSCRYPT_BASE64URL_CHARS(FSCRYPT_NOKEY_NAME_MAX)7475static inline bool fscrypt_is_dot_dotdot(const struct qstr *str)76{77return is_dot_dotdot(str->name, str->len);78}7980/**81* fscrypt_fname_encrypt() - encrypt a filename82* @inode: inode of the parent directory (for regular filenames)83* or of the symlink (for symlink targets). Key must already be84* set up.85* @iname: the filename to encrypt86* @out: (output) the encrypted filename87* @olen: size of the encrypted filename. It must be at least @iname->len.88* Any extra space is filled with NUL padding before encryption.89*90* Return: 0 on success, -errno on failure91*/92int fscrypt_fname_encrypt(const struct inode *inode, const struct qstr *iname,93u8 *out, unsigned int olen)94{95const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);96struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;97SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);98union fscrypt_iv iv;99struct scatterlist sg;100int err;101102/*103* Copy the filename to the output buffer for encrypting in-place and104* pad it with the needed number of NUL bytes.105*/106if (WARN_ON_ONCE(olen < iname->len))107return -ENOBUFS;108memcpy(out, iname->name, iname->len);109memset(out + iname->len, 0, olen - iname->len);110111fscrypt_generate_iv(&iv, 0, ci);112113skcipher_request_set_callback(114req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,115NULL, NULL);116sg_init_one(&sg, out, olen);117skcipher_request_set_crypt(req, &sg, &sg, olen, &iv);118err = crypto_skcipher_encrypt(req);119if (err)120fscrypt_err(inode, "Filename encryption failed: %d", err);121return err;122}123EXPORT_SYMBOL_GPL(fscrypt_fname_encrypt);124125/**126* fname_decrypt() - decrypt a filename127* @inode: inode of the parent directory (for regular filenames)128* or of the symlink (for symlink targets)129* @iname: the encrypted filename to decrypt130* @oname: (output) the decrypted filename. The caller must have allocated131* enough space for this, e.g. using fscrypt_fname_alloc_buffer().132*133* Return: 0 on success, -errno on failure134*/135static int fname_decrypt(const struct inode *inode,136const struct fscrypt_str *iname,137struct fscrypt_str *oname)138{139const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);140struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;141SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);142union fscrypt_iv iv;143struct scatterlist src_sg, dst_sg;144int err;145146fscrypt_generate_iv(&iv, 0, ci);147148skcipher_request_set_callback(149req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,150NULL, NULL);151sg_init_one(&src_sg, iname->name, iname->len);152sg_init_one(&dst_sg, oname->name, oname->len);153skcipher_request_set_crypt(req, &src_sg, &dst_sg, iname->len, &iv);154err = crypto_skcipher_decrypt(req);155if (err) {156fscrypt_err(inode, "Filename decryption failed: %d", err);157return err;158}159160oname->len = strnlen(oname->name, iname->len);161return 0;162}163164static const char base64url_table[65] =165"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";166167#define FSCRYPT_BASE64URL_CHARS(nbytes) DIV_ROUND_UP((nbytes) * 4, 3)168169/**170* fscrypt_base64url_encode() - base64url-encode some binary data171* @src: the binary data to encode172* @srclen: the length of @src in bytes173* @dst: (output) the base64url-encoded string. Not NUL-terminated.174*175* Encodes data using base64url encoding, i.e. the "Base 64 Encoding with URL176* and Filename Safe Alphabet" specified by RFC 4648. '='-padding isn't used,177* as it's unneeded and not required by the RFC. base64url is used instead of178* base64 to avoid the '/' character, which isn't allowed in filenames.179*180* Return: the length of the resulting base64url-encoded string in bytes.181* This will be equal to FSCRYPT_BASE64URL_CHARS(srclen).182*/183static int fscrypt_base64url_encode(const u8 *src, int srclen, char *dst)184{185u32 ac = 0;186int bits = 0;187int i;188char *cp = dst;189190for (i = 0; i < srclen; i++) {191ac = (ac << 8) | src[i];192bits += 8;193do {194bits -= 6;195*cp++ = base64url_table[(ac >> bits) & 0x3f];196} while (bits >= 6);197}198if (bits)199*cp++ = base64url_table[(ac << (6 - bits)) & 0x3f];200return cp - dst;201}202203/**204* fscrypt_base64url_decode() - base64url-decode a string205* @src: the string to decode. Doesn't need to be NUL-terminated.206* @srclen: the length of @src in bytes207* @dst: (output) the decoded binary data208*209* Decodes a string using base64url encoding, i.e. the "Base 64 Encoding with210* URL and Filename Safe Alphabet" specified by RFC 4648. '='-padding isn't211* accepted, nor are non-encoding characters such as whitespace.212*213* This implementation hasn't been optimized for performance.214*215* Return: the length of the resulting decoded binary data in bytes,216* or -1 if the string isn't a valid base64url string.217*/218static int fscrypt_base64url_decode(const char *src, int srclen, u8 *dst)219{220u32 ac = 0;221int bits = 0;222int i;223u8 *bp = dst;224225for (i = 0; i < srclen; i++) {226const char *p = strchr(base64url_table, src[i]);227228if (p == NULL || src[i] == 0)229return -1;230ac = (ac << 6) | (p - base64url_table);231bits += 6;232if (bits >= 8) {233bits -= 8;234*bp++ = (u8)(ac >> bits);235}236}237if (ac & ((1 << bits) - 1))238return -1;239return bp - dst;240}241242bool __fscrypt_fname_encrypted_size(const union fscrypt_policy *policy,243u32 orig_len, u32 max_len,244u32 *encrypted_len_ret)245{246int padding = 4 << (fscrypt_policy_flags(policy) &247FSCRYPT_POLICY_FLAGS_PAD_MASK);248u32 encrypted_len;249250if (orig_len > max_len)251return false;252encrypted_len = max_t(u32, orig_len, FSCRYPT_FNAME_MIN_MSG_LEN);253encrypted_len = round_up(encrypted_len, padding);254*encrypted_len_ret = min(encrypted_len, max_len);255return true;256}257258/**259* fscrypt_fname_encrypted_size() - calculate length of encrypted filename260* @inode: parent inode of dentry name being encrypted. Key must261* already be set up.262* @orig_len: length of the original filename263* @max_len: maximum length to return264* @encrypted_len_ret: where calculated length should be returned (on success)265*266* Filenames that are shorter than the maximum length may have their lengths267* increased slightly by encryption, due to padding that is applied.268*269* Return: false if the orig_len is greater than max_len. Otherwise, true and270* fill out encrypted_len_ret with the length (up to max_len).271*/272bool fscrypt_fname_encrypted_size(const struct inode *inode, u32 orig_len,273u32 max_len, u32 *encrypted_len_ret)274{275const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);276277return __fscrypt_fname_encrypted_size(&ci->ci_policy, orig_len, max_len,278encrypted_len_ret);279}280EXPORT_SYMBOL_GPL(fscrypt_fname_encrypted_size);281282/**283* fscrypt_fname_alloc_buffer() - allocate a buffer for presented filenames284* @max_encrypted_len: maximum length of encrypted filenames the buffer will be285* used to present286* @crypto_str: (output) buffer to allocate287*288* Allocate a buffer that is large enough to hold any decrypted or encoded289* filename (null-terminated), for the given maximum encrypted filename length.290*291* Return: 0 on success, -errno on failure292*/293int fscrypt_fname_alloc_buffer(u32 max_encrypted_len,294struct fscrypt_str *crypto_str)295{296u32 max_presented_len = max_t(u32, FSCRYPT_NOKEY_NAME_MAX_ENCODED,297max_encrypted_len);298299crypto_str->name = kmalloc(max_presented_len + 1, GFP_NOFS);300if (!crypto_str->name)301return -ENOMEM;302crypto_str->len = max_presented_len;303return 0;304}305EXPORT_SYMBOL(fscrypt_fname_alloc_buffer);306307/**308* fscrypt_fname_free_buffer() - free a buffer for presented filenames309* @crypto_str: the buffer to free310*311* Free a buffer that was allocated by fscrypt_fname_alloc_buffer().312*/313void fscrypt_fname_free_buffer(struct fscrypt_str *crypto_str)314{315if (!crypto_str)316return;317kfree(crypto_str->name);318crypto_str->name = NULL;319}320EXPORT_SYMBOL(fscrypt_fname_free_buffer);321322/**323* fscrypt_fname_disk_to_usr() - convert an encrypted filename to324* user-presentable form325* @inode: inode of the parent directory (for regular filenames)326* or of the symlink (for symlink targets)327* @hash: first part of the name's dirhash, if applicable. This only needs to328* be provided if the filename is located in an indexed directory whose329* encryption key may be unavailable. Not needed for symlink targets.330* @minor_hash: second part of the name's dirhash, if applicable331* @iname: encrypted filename to convert. May also be "." or "..", which332* aren't actually encrypted.333* @oname: output buffer for the user-presentable filename. The caller must334* have allocated enough space for this, e.g. using335* fscrypt_fname_alloc_buffer().336*337* If the key is available, we'll decrypt the disk name. Otherwise, we'll338* encode it for presentation in fscrypt_nokey_name format.339* See struct fscrypt_nokey_name for details.340*341* Return: 0 on success, -errno on failure342*/343int fscrypt_fname_disk_to_usr(const struct inode *inode,344u32 hash, u32 minor_hash,345const struct fscrypt_str *iname,346struct fscrypt_str *oname)347{348const struct qstr qname = FSTR_TO_QSTR(iname);349struct fscrypt_nokey_name nokey_name;350u32 size; /* size of the unencoded no-key name */351352if (fscrypt_is_dot_dotdot(&qname)) {353oname->name[0] = '.';354oname->name[iname->len - 1] = '.';355oname->len = iname->len;356return 0;357}358359if (iname->len < FSCRYPT_FNAME_MIN_MSG_LEN)360return -EUCLEAN;361362if (fscrypt_has_encryption_key(inode))363return fname_decrypt(inode, iname, oname);364365/*366* Sanity check that struct fscrypt_nokey_name doesn't have padding367* between fields and that its encoded size never exceeds NAME_MAX.368*/369BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, dirhash) !=370offsetof(struct fscrypt_nokey_name, bytes));371BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, bytes) !=372offsetof(struct fscrypt_nokey_name, sha256));373BUILD_BUG_ON(FSCRYPT_NOKEY_NAME_MAX_ENCODED > NAME_MAX);374375nokey_name.dirhash[0] = hash;376nokey_name.dirhash[1] = minor_hash;377378if (iname->len <= sizeof(nokey_name.bytes)) {379memcpy(nokey_name.bytes, iname->name, iname->len);380size = offsetof(struct fscrypt_nokey_name, bytes[iname->len]);381} else {382memcpy(nokey_name.bytes, iname->name, sizeof(nokey_name.bytes));383/* Compute strong hash of remaining part of name. */384sha256(&iname->name[sizeof(nokey_name.bytes)],385iname->len - sizeof(nokey_name.bytes),386nokey_name.sha256);387size = FSCRYPT_NOKEY_NAME_MAX;388}389oname->len = fscrypt_base64url_encode((const u8 *)&nokey_name, size,390oname->name);391return 0;392}393EXPORT_SYMBOL(fscrypt_fname_disk_to_usr);394395/**396* fscrypt_setup_filename() - prepare to search a possibly encrypted directory397* @dir: the directory that will be searched398* @iname: the user-provided filename being searched for399* @lookup: 1 if we're allowed to proceed without the key because it's400* ->lookup() or we're finding the dir_entry for deletion; 0 if we cannot401* proceed without the key because we're going to create the dir_entry.402* @fname: the filename information to be filled in403*404* Given a user-provided filename @iname, this function sets @fname->disk_name405* to the name that would be stored in the on-disk directory entry, if possible.406* If the directory is unencrypted this is simply @iname. Else, if we have the407* directory's encryption key, then @iname is the plaintext, so we encrypt it to408* get the disk_name.409*410* Else, for keyless @lookup operations, @iname should be a no-key name, so we411* decode it to get the struct fscrypt_nokey_name. Non-@lookup operations will412* be impossible in this case, so we fail them with ENOKEY.413*414* If successful, fscrypt_free_filename() must be called later to clean up.415*416* Return: 0 on success, -errno on failure417*/418int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,419int lookup, struct fscrypt_name *fname)420{421struct fscrypt_nokey_name *nokey_name;422int ret;423424memset(fname, 0, sizeof(struct fscrypt_name));425fname->usr_fname = iname;426427if (!IS_ENCRYPTED(dir) || fscrypt_is_dot_dotdot(iname)) {428fname->disk_name.name = (unsigned char *)iname->name;429fname->disk_name.len = iname->len;430return 0;431}432ret = fscrypt_get_encryption_info(dir, lookup);433if (ret)434return ret;435436if (fscrypt_has_encryption_key(dir)) {437if (!fscrypt_fname_encrypted_size(dir, iname->len, NAME_MAX,438&fname->crypto_buf.len))439return -ENAMETOOLONG;440fname->crypto_buf.name = kmalloc(fname->crypto_buf.len,441GFP_NOFS);442if (!fname->crypto_buf.name)443return -ENOMEM;444445ret = fscrypt_fname_encrypt(dir, iname, fname->crypto_buf.name,446fname->crypto_buf.len);447if (ret)448goto errout;449fname->disk_name.name = fname->crypto_buf.name;450fname->disk_name.len = fname->crypto_buf.len;451return 0;452}453if (!lookup)454return -ENOKEY;455fname->is_nokey_name = true;456457/*458* We don't have the key and we are doing a lookup; decode the459* user-supplied name460*/461462if (iname->len > FSCRYPT_NOKEY_NAME_MAX_ENCODED)463return -ENOENT;464465fname->crypto_buf.name = kmalloc(FSCRYPT_NOKEY_NAME_MAX, GFP_KERNEL);466if (fname->crypto_buf.name == NULL)467return -ENOMEM;468469ret = fscrypt_base64url_decode(iname->name, iname->len,470fname->crypto_buf.name);471if (ret < (int)offsetof(struct fscrypt_nokey_name, bytes[1]) ||472(ret > offsetof(struct fscrypt_nokey_name, sha256) &&473ret != FSCRYPT_NOKEY_NAME_MAX)) {474ret = -ENOENT;475goto errout;476}477fname->crypto_buf.len = ret;478479nokey_name = (void *)fname->crypto_buf.name;480fname->hash = nokey_name->dirhash[0];481fname->minor_hash = nokey_name->dirhash[1];482if (ret != FSCRYPT_NOKEY_NAME_MAX) {483/* The full ciphertext filename is available. */484fname->disk_name.name = nokey_name->bytes;485fname->disk_name.len =486ret - offsetof(struct fscrypt_nokey_name, bytes);487}488return 0;489490errout:491kfree(fname->crypto_buf.name);492return ret;493}494EXPORT_SYMBOL(fscrypt_setup_filename);495496/**497* fscrypt_match_name() - test whether the given name matches a directory entry498* @fname: the name being searched for499* @de_name: the name from the directory entry500* @de_name_len: the length of @de_name in bytes501*502* Normally @fname->disk_name will be set, and in that case we simply compare503* that to the name stored in the directory entry. The only exception is that504* if we don't have the key for an encrypted directory and the name we're505* looking for is very long, then we won't have the full disk_name and instead506* we'll need to match against a fscrypt_nokey_name that includes a strong hash.507*508* Return: %true if the name matches, otherwise %false.509*/510bool fscrypt_match_name(const struct fscrypt_name *fname,511const u8 *de_name, u32 de_name_len)512{513const struct fscrypt_nokey_name *nokey_name =514(const void *)fname->crypto_buf.name;515u8 digest[SHA256_DIGEST_SIZE];516517if (likely(fname->disk_name.name)) {518if (de_name_len != fname->disk_name.len)519return false;520return !memcmp(de_name, fname->disk_name.name, de_name_len);521}522if (de_name_len <= sizeof(nokey_name->bytes))523return false;524if (memcmp(de_name, nokey_name->bytes, sizeof(nokey_name->bytes)))525return false;526sha256(&de_name[sizeof(nokey_name->bytes)],527de_name_len - sizeof(nokey_name->bytes), digest);528return !memcmp(digest, nokey_name->sha256, sizeof(digest));529}530EXPORT_SYMBOL_GPL(fscrypt_match_name);531532/**533* fscrypt_fname_siphash() - calculate the SipHash of a filename534* @dir: the parent directory535* @name: the filename to calculate the SipHash of536*537* Given a plaintext filename @name and a directory @dir which uses SipHash as538* its dirhash method and has had its fscrypt key set up, this function539* calculates the SipHash of that name using the directory's secret dirhash key.540*541* Return: the SipHash of @name using the hash key of @dir542*/543u64 fscrypt_fname_siphash(const struct inode *dir, const struct qstr *name)544{545const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(dir);546547WARN_ON_ONCE(!ci->ci_dirhash_key_initialized);548549return siphash(name->name, name->len, &ci->ci_dirhash_key);550}551EXPORT_SYMBOL_GPL(fscrypt_fname_siphash);552553/*554* Validate dentries in encrypted directories to make sure we aren't potentially555* caching stale dentries after a key has been added.556*/557int fscrypt_d_revalidate(struct inode *dir, const struct qstr *name,558struct dentry *dentry, unsigned int flags)559{560int err;561562/*563* Plaintext names are always valid, since fscrypt doesn't support564* reverting to no-key names without evicting the directory's inode565* -- which implies eviction of the dentries in the directory.566*/567if (!(dentry->d_flags & DCACHE_NOKEY_NAME))568return 1;569570/*571* No-key name; valid if the directory's key is still unavailable.572*573* Note in RCU mode we have to bail if we get here -574* fscrypt_get_encryption_info() may block.575*/576577if (flags & LOOKUP_RCU)578return -ECHILD;579580/*581* Pass allow_unsupported=true, so that files with an unsupported582* encryption policy can be deleted.583*/584err = fscrypt_get_encryption_info(dir, true);585if (err < 0)586return err;587588return !fscrypt_has_encryption_key(dir);589}590EXPORT_SYMBOL_GPL(fscrypt_d_revalidate);591592593