// 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/hash.h>14#include <crypto/sha2.h>15#include <crypto/skcipher.h>16#include <linux/export.h>17#include <linux/namei.h>18#include <linux/scatterlist.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 \74FSCRYPT_BASE64URL_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 = inode->i_crypt_info;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 = inode->i_crypt_info;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}164165static const char base64url_table[65] =166"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";167168#define FSCRYPT_BASE64URL_CHARS(nbytes) DIV_ROUND_UP((nbytes) * 4, 3)169170/**171* fscrypt_base64url_encode() - base64url-encode some binary data172* @src: the binary data to encode173* @srclen: the length of @src in bytes174* @dst: (output) the base64url-encoded string. Not NUL-terminated.175*176* Encodes data using base64url encoding, i.e. the "Base 64 Encoding with URL177* and Filename Safe Alphabet" specified by RFC 4648. '='-padding isn't used,178* as it's unneeded and not required by the RFC. base64url is used instead of179* base64 to avoid the '/' character, which isn't allowed in filenames.180*181* Return: the length of the resulting base64url-encoded string in bytes.182* This will be equal to FSCRYPT_BASE64URL_CHARS(srclen).183*/184static int fscrypt_base64url_encode(const u8 *src, int srclen, char *dst)185{186u32 ac = 0;187int bits = 0;188int i;189char *cp = dst;190191for (i = 0; i < srclen; i++) {192ac = (ac << 8) | src[i];193bits += 8;194do {195bits -= 6;196*cp++ = base64url_table[(ac >> bits) & 0x3f];197} while (bits >= 6);198}199if (bits)200*cp++ = base64url_table[(ac << (6 - bits)) & 0x3f];201return cp - dst;202}203204/**205* fscrypt_base64url_decode() - base64url-decode a string206* @src: the string to decode. Doesn't need to be NUL-terminated.207* @srclen: the length of @src in bytes208* @dst: (output) the decoded binary data209*210* Decodes a string using base64url encoding, i.e. the "Base 64 Encoding with211* URL and Filename Safe Alphabet" specified by RFC 4648. '='-padding isn't212* accepted, nor are non-encoding characters such as whitespace.213*214* This implementation hasn't been optimized for performance.215*216* Return: the length of the resulting decoded binary data in bytes,217* or -1 if the string isn't a valid base64url string.218*/219static int fscrypt_base64url_decode(const char *src, int srclen, u8 *dst)220{221u32 ac = 0;222int bits = 0;223int i;224u8 *bp = dst;225226for (i = 0; i < srclen; i++) {227const char *p = strchr(base64url_table, src[i]);228229if (p == NULL || src[i] == 0)230return -1;231ac = (ac << 6) | (p - base64url_table);232bits += 6;233if (bits >= 8) {234bits -= 8;235*bp++ = (u8)(ac >> bits);236}237}238if (ac & ((1 << bits) - 1))239return -1;240return bp - dst;241}242243bool __fscrypt_fname_encrypted_size(const union fscrypt_policy *policy,244u32 orig_len, u32 max_len,245u32 *encrypted_len_ret)246{247int padding = 4 << (fscrypt_policy_flags(policy) &248FSCRYPT_POLICY_FLAGS_PAD_MASK);249u32 encrypted_len;250251if (orig_len > max_len)252return false;253encrypted_len = max_t(u32, orig_len, FSCRYPT_FNAME_MIN_MSG_LEN);254encrypted_len = round_up(encrypted_len, padding);255*encrypted_len_ret = min(encrypted_len, max_len);256return true;257}258259/**260* fscrypt_fname_encrypted_size() - calculate length of encrypted filename261* @inode: parent inode of dentry name being encrypted. Key must262* already be set up.263* @orig_len: length of the original filename264* @max_len: maximum length to return265* @encrypted_len_ret: where calculated length should be returned (on success)266*267* Filenames that are shorter than the maximum length may have their lengths268* increased slightly by encryption, due to padding that is applied.269*270* Return: false if the orig_len is greater than max_len. Otherwise, true and271* fill out encrypted_len_ret with the length (up to max_len).272*/273bool fscrypt_fname_encrypted_size(const struct inode *inode, u32 orig_len,274u32 max_len, u32 *encrypted_len_ret)275{276return __fscrypt_fname_encrypted_size(&inode->i_crypt_info->ci_policy,277orig_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 = dir->i_crypt_info;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