xref: /openbmc/linux/fs/crypto/fname.c (revision 34d6f206a88c2651d216bd3487ac956a40b2ba8e)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
20b81d077SJaegeuk Kim /*
30b81d077SJaegeuk Kim  * This contains functions for filename crypto management
40b81d077SJaegeuk Kim  *
50b81d077SJaegeuk Kim  * Copyright (C) 2015, Google, Inc.
60b81d077SJaegeuk Kim  * Copyright (C) 2015, Motorola Mobility
70b81d077SJaegeuk Kim  *
80b81d077SJaegeuk Kim  * Written by Uday Savagaonkar, 2014.
90b81d077SJaegeuk Kim  * Modified by Jaegeuk Kim, 2015.
100b81d077SJaegeuk Kim  *
110b81d077SJaegeuk Kim  * This has not yet undergone a rigorous security audit.
120b81d077SJaegeuk Kim  */
130b81d077SJaegeuk Kim 
142ebdef6dSEric Biggers #include <linux/namei.h>
150b81d077SJaegeuk Kim #include <linux/scatterlist.h>
16edc440e3SDaniel Rosenberg #include <crypto/hash.h>
17a24d22b2SEric Biggers #include <crypto/sha2.h>
18a575784cSEric Biggers #include <crypto/skcipher.h>
193325bea5STheodore Ts'o #include "fscrypt_private.h"
200b81d077SJaegeuk Kim 
21d2fe9754SEric Biggers /*
2263cec138SEric Biggers  * The minimum message length (input and output length), in bytes, for all
2363cec138SEric Biggers  * filenames encryption modes.  Filenames shorter than this will be zero-padded
2463cec138SEric Biggers  * before being encrypted.
2563cec138SEric Biggers  */
2663cec138SEric Biggers #define FSCRYPT_FNAME_MIN_MSG_LEN 16
2763cec138SEric Biggers 
2863cec138SEric Biggers /*
29edc440e3SDaniel Rosenberg  * struct fscrypt_nokey_name - identifier for directory entry when key is absent
30edc440e3SDaniel Rosenberg  *
31edc440e3SDaniel Rosenberg  * When userspace lists an encrypted directory without access to the key, the
32edc440e3SDaniel Rosenberg  * filesystem must present a unique "no-key name" for each filename that allows
33edc440e3SDaniel Rosenberg  * it to find the directory entry again if requested.  Naively, that would just
34edc440e3SDaniel Rosenberg  * mean using the ciphertext filenames.  However, since the ciphertext filenames
35edc440e3SDaniel Rosenberg  * can contain illegal characters ('\0' and '/'), they must be encoded in some
36ba47b515SEric Biggers  * way.  We use base64url.  But that can cause names to exceed NAME_MAX (255
37edc440e3SDaniel Rosenberg  * bytes), so we also need to use a strong hash to abbreviate long names.
38edc440e3SDaniel Rosenberg  *
39edc440e3SDaniel Rosenberg  * The filesystem may also need another kind of hash, the "dirhash", to quickly
40edc440e3SDaniel Rosenberg  * find the directory entry.  Since filesystems normally compute the dirhash
41edc440e3SDaniel Rosenberg  * over the on-disk filename (i.e. the ciphertext), it's not computable from
42edc440e3SDaniel Rosenberg  * no-key names that abbreviate the ciphertext using the strong hash to fit in
43edc440e3SDaniel Rosenberg  * NAME_MAX.  It's also not computable if it's a keyed hash taken over the
44edc440e3SDaniel Rosenberg  * plaintext (but it may still be available in the on-disk directory entry);
45edc440e3SDaniel Rosenberg  * casefolded directories use this type of dirhash.  At least in these cases,
46edc440e3SDaniel Rosenberg  * each no-key name must include the name's dirhash too.
47edc440e3SDaniel Rosenberg  *
48ba47b515SEric Biggers  * To meet all these requirements, we base64url-encode the following
49edc440e3SDaniel Rosenberg  * variable-length structure.  It contains the dirhash, or 0's if the filesystem
50edc440e3SDaniel Rosenberg  * didn't provide one; up to 149 bytes of the ciphertext name; and for
51edc440e3SDaniel Rosenberg  * ciphertexts longer than 149 bytes, also the SHA-256 of the remaining bytes.
52edc440e3SDaniel Rosenberg  *
53edc440e3SDaniel Rosenberg  * This ensures that each no-key name contains everything needed to find the
54edc440e3SDaniel Rosenberg  * directory entry again, contains only legal characters, doesn't exceed
55edc440e3SDaniel Rosenberg  * NAME_MAX, is unambiguous unless there's a SHA-256 collision, and that we only
56edc440e3SDaniel Rosenberg  * take the performance hit of SHA-256 on very long filenames (which are rare).
57edc440e3SDaniel Rosenberg  */
58edc440e3SDaniel Rosenberg struct fscrypt_nokey_name {
59edc440e3SDaniel Rosenberg 	u32 dirhash[2];
60edc440e3SDaniel Rosenberg 	u8 bytes[149];
61edc440e3SDaniel Rosenberg 	u8 sha256[SHA256_DIGEST_SIZE];
62ba47b515SEric Biggers }; /* 189 bytes => 252 bytes base64url-encoded, which is <= NAME_MAX (255) */
63edc440e3SDaniel Rosenberg 
64edc440e3SDaniel Rosenberg /*
65ba47b515SEric Biggers  * Decoded size of max-size no-key name, i.e. a name that was abbreviated using
66edc440e3SDaniel Rosenberg  * the strong hash and thus includes the 'sha256' field.  This isn't simply
67edc440e3SDaniel Rosenberg  * sizeof(struct fscrypt_nokey_name), as the padding at the end isn't included.
68edc440e3SDaniel Rosenberg  */
69edc440e3SDaniel Rosenberg #define FSCRYPT_NOKEY_NAME_MAX	offsetofend(struct fscrypt_nokey_name, sha256)
70edc440e3SDaniel Rosenberg 
71ba47b515SEric Biggers /* Encoded size of max-size no-key name */
72ba47b515SEric Biggers #define FSCRYPT_NOKEY_NAME_MAX_ENCODED \
73ba47b515SEric Biggers 		FSCRYPT_BASE64URL_CHARS(FSCRYPT_NOKEY_NAME_MAX)
74ba47b515SEric Biggers 
fscrypt_is_dot_dotdot(const struct qstr * str)75dcf0db9eSEric Biggers static inline bool fscrypt_is_dot_dotdot(const struct qstr *str)
76dcf0db9eSEric Biggers {
77*ef836204SChuck Lever 	return is_dot_dotdot(str->name, str->len);
78dcf0db9eSEric Biggers }
79dcf0db9eSEric Biggers 
800b81d077SJaegeuk Kim /**
811b3b827eSEric Biggers  * fscrypt_fname_encrypt() - encrypt a filename
82d2fe9754SEric Biggers  * @inode: inode of the parent directory (for regular filenames)
83d3e94fdcSJeff Layton  *	   or of the symlink (for symlink targets). Key must already be
84d3e94fdcSJeff Layton  *	   set up.
85d2fe9754SEric Biggers  * @iname: the filename to encrypt
86d2fe9754SEric Biggers  * @out: (output) the encrypted filename
87d2fe9754SEric Biggers  * @olen: size of the encrypted filename.  It must be at least @iname->len.
8850c961deSEric Biggers  *	  Any extra space is filled with NUL padding before encryption.
89ef1eb3aaSEric Biggers  *
90ef1eb3aaSEric Biggers  * Return: 0 on success, -errno on failure
910b81d077SJaegeuk Kim  */
fscrypt_fname_encrypt(const struct inode * inode,const struct qstr * iname,u8 * out,unsigned int olen)921b3b827eSEric Biggers int fscrypt_fname_encrypt(const struct inode *inode, const struct qstr *iname,
9350c961deSEric Biggers 			  u8 *out, unsigned int olen)
940b81d077SJaegeuk Kim {
95d407574eSLinus Torvalds 	struct skcipher_request *req = NULL;
96d0082e1aSGilad Ben-Yossef 	DECLARE_CRYPTO_WAIT(wait);
978a4ab0b8SEric Biggers 	const struct fscrypt_info *ci = inode->i_crypt_info;
985fee3609SSatya Tangirala 	struct crypto_skcipher *tfm = ci->ci_enc_key.tfm;
998094c3ceSEric Biggers 	union fscrypt_iv iv;
10008ae877fSEric Biggers 	struct scatterlist sg;
1018094c3ceSEric Biggers 	int res;
1020b81d077SJaegeuk Kim 
10308ae877fSEric Biggers 	/*
10408ae877fSEric Biggers 	 * Copy the filename to the output buffer for encrypting in-place and
10508ae877fSEric Biggers 	 * pad it with the needed number of NUL bytes.
10608ae877fSEric Biggers 	 */
10741b2ad80SEric Biggers 	if (WARN_ON_ONCE(olen < iname->len))
10876e81d6dSEric Biggers 		return -ENOBUFS;
10950c961deSEric Biggers 	memcpy(out, iname->name, iname->len);
11050c961deSEric Biggers 	memset(out + iname->len, 0, olen - iname->len);
1110b81d077SJaegeuk Kim 
11208ae877fSEric Biggers 	/* Initialize the IV */
1138094c3ceSEric Biggers 	fscrypt_generate_iv(&iv, 0, ci);
1140b81d077SJaegeuk Kim 
11508ae877fSEric Biggers 	/* Set up the encryption request */
116d407574eSLinus Torvalds 	req = skcipher_request_alloc(tfm, GFP_NOFS);
117c90fd775SEric Biggers 	if (!req)
1180b81d077SJaegeuk Kim 		return -ENOMEM;
119d407574eSLinus Torvalds 	skcipher_request_set_callback(req,
1200b81d077SJaegeuk Kim 			CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
121d0082e1aSGilad Ben-Yossef 			crypto_req_done, &wait);
12250c961deSEric Biggers 	sg_init_one(&sg, out, olen);
1238094c3ceSEric Biggers 	skcipher_request_set_crypt(req, &sg, &sg, olen, &iv);
1240b81d077SJaegeuk Kim 
12508ae877fSEric Biggers 	/* Do the encryption */
126d0082e1aSGilad Ben-Yossef 	res = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
127d407574eSLinus Torvalds 	skcipher_request_free(req);
128ef1eb3aaSEric Biggers 	if (res < 0) {
129886da8b3SEric Biggers 		fscrypt_err(inode, "Filename encryption failed: %d", res);
1300b81d077SJaegeuk Kim 		return res;
1310b81d077SJaegeuk Kim 	}
1320b81d077SJaegeuk Kim 
133ef1eb3aaSEric Biggers 	return 0;
134ef1eb3aaSEric Biggers }
135d3e94fdcSJeff Layton EXPORT_SYMBOL_GPL(fscrypt_fname_encrypt);
136ef1eb3aaSEric Biggers 
137ef1eb3aaSEric Biggers /**
138ef1eb3aaSEric Biggers  * fname_decrypt() - decrypt a filename
139d2fe9754SEric Biggers  * @inode: inode of the parent directory (for regular filenames)
140d2fe9754SEric Biggers  *	   or of the symlink (for symlink targets)
141d2fe9754SEric Biggers  * @iname: the encrypted filename to decrypt
142d2fe9754SEric Biggers  * @oname: (output) the decrypted filename.  The caller must have allocated
143d2fe9754SEric Biggers  *	   enough space for this, e.g. using fscrypt_fname_alloc_buffer().
144ef1eb3aaSEric Biggers  *
145ef1eb3aaSEric Biggers  * Return: 0 on success, -errno on failure
1460b81d077SJaegeuk Kim  */
fname_decrypt(const struct inode * inode,const struct fscrypt_str * iname,struct fscrypt_str * oname)1478a4ab0b8SEric Biggers static int fname_decrypt(const struct inode *inode,
1480b81d077SJaegeuk Kim 			 const struct fscrypt_str *iname,
1490b81d077SJaegeuk Kim 			 struct fscrypt_str *oname)
1500b81d077SJaegeuk Kim {
151d407574eSLinus Torvalds 	struct skcipher_request *req = NULL;
152d0082e1aSGilad Ben-Yossef 	DECLARE_CRYPTO_WAIT(wait);
1530b81d077SJaegeuk Kim 	struct scatterlist src_sg, dst_sg;
1548a4ab0b8SEric Biggers 	const struct fscrypt_info *ci = inode->i_crypt_info;
1555fee3609SSatya Tangirala 	struct crypto_skcipher *tfm = ci->ci_enc_key.tfm;
1568094c3ceSEric Biggers 	union fscrypt_iv iv;
1578094c3ceSEric Biggers 	int res;
1580b81d077SJaegeuk Kim 
1590b81d077SJaegeuk Kim 	/* Allocate request */
160d407574eSLinus Torvalds 	req = skcipher_request_alloc(tfm, GFP_NOFS);
161c90fd775SEric Biggers 	if (!req)
1620b81d077SJaegeuk Kim 		return -ENOMEM;
163d407574eSLinus Torvalds 	skcipher_request_set_callback(req,
1640b81d077SJaegeuk Kim 		CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
165d0082e1aSGilad Ben-Yossef 		crypto_req_done, &wait);
1660b81d077SJaegeuk Kim 
1670b81d077SJaegeuk Kim 	/* Initialize IV */
1688094c3ceSEric Biggers 	fscrypt_generate_iv(&iv, 0, ci);
1690b81d077SJaegeuk Kim 
1700b81d077SJaegeuk Kim 	/* Create decryption request */
1710b81d077SJaegeuk Kim 	sg_init_one(&src_sg, iname->name, iname->len);
1720b81d077SJaegeuk Kim 	sg_init_one(&dst_sg, oname->name, oname->len);
1738094c3ceSEric Biggers 	skcipher_request_set_crypt(req, &src_sg, &dst_sg, iname->len, &iv);
174d0082e1aSGilad Ben-Yossef 	res = crypto_wait_req(crypto_skcipher_decrypt(req), &wait);
175d407574eSLinus Torvalds 	skcipher_request_free(req);
1760b81d077SJaegeuk Kim 	if (res < 0) {
177886da8b3SEric Biggers 		fscrypt_err(inode, "Filename decryption failed: %d", res);
1780b81d077SJaegeuk Kim 		return res;
1790b81d077SJaegeuk Kim 	}
1800b81d077SJaegeuk Kim 
1810b81d077SJaegeuk Kim 	oname->len = strnlen(oname->name, iname->len);
182ef1eb3aaSEric Biggers 	return 0;
1830b81d077SJaegeuk Kim }
1840b81d077SJaegeuk Kim 
185ba47b515SEric Biggers static const char base64url_table[65] =
186ba47b515SEric Biggers 	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1870b81d077SJaegeuk Kim 
188ba47b515SEric Biggers #define FSCRYPT_BASE64URL_CHARS(nbytes)	DIV_ROUND_UP((nbytes) * 4, 3)
18917159420SEric Biggers 
1900b81d077SJaegeuk Kim /**
191ba47b515SEric Biggers  * fscrypt_base64url_encode() - base64url-encode some binary data
192ba47b515SEric Biggers  * @src: the binary data to encode
193ba47b515SEric Biggers  * @srclen: the length of @src in bytes
194ba47b515SEric Biggers  * @dst: (output) the base64url-encoded string.  Not NUL-terminated.
1950b81d077SJaegeuk Kim  *
196ba47b515SEric Biggers  * Encodes data using base64url encoding, i.e. the "Base 64 Encoding with URL
197ba47b515SEric Biggers  * and Filename Safe Alphabet" specified by RFC 4648.  '='-padding isn't used,
198ba47b515SEric Biggers  * as it's unneeded and not required by the RFC.  base64url is used instead of
199ba47b515SEric Biggers  * base64 to avoid the '/' character, which isn't allowed in filenames.
2001c5100a2SEric Biggers  *
201ba47b515SEric Biggers  * Return: the length of the resulting base64url-encoded string in bytes.
202ba47b515SEric Biggers  *	   This will be equal to FSCRYPT_BASE64URL_CHARS(srclen).
2030b81d077SJaegeuk Kim  */
fscrypt_base64url_encode(const u8 * src,int srclen,char * dst)204ba47b515SEric Biggers static int fscrypt_base64url_encode(const u8 *src, int srclen, char *dst)
2050b81d077SJaegeuk Kim {
206ba47b515SEric Biggers 	u32 ac = 0;
207ba47b515SEric Biggers 	int bits = 0;
208ba47b515SEric Biggers 	int i;
2090b81d077SJaegeuk Kim 	char *cp = dst;
2100b81d077SJaegeuk Kim 
211ba47b515SEric Biggers 	for (i = 0; i < srclen; i++) {
212ba47b515SEric Biggers 		ac = (ac << 8) | src[i];
2130b81d077SJaegeuk Kim 		bits += 8;
2140b81d077SJaegeuk Kim 		do {
2150b81d077SJaegeuk Kim 			bits -= 6;
216ba47b515SEric Biggers 			*cp++ = base64url_table[(ac >> bits) & 0x3f];
2170b81d077SJaegeuk Kim 		} while (bits >= 6);
2180b81d077SJaegeuk Kim 	}
2190b81d077SJaegeuk Kim 	if (bits)
220ba47b515SEric Biggers 		*cp++ = base64url_table[(ac << (6 - bits)) & 0x3f];
2210b81d077SJaegeuk Kim 	return cp - dst;
2220b81d077SJaegeuk Kim }
2230b81d077SJaegeuk Kim 
224ba47b515SEric Biggers /**
225ba47b515SEric Biggers  * fscrypt_base64url_decode() - base64url-decode a string
226ba47b515SEric Biggers  * @src: the string to decode.  Doesn't need to be NUL-terminated.
227ba47b515SEric Biggers  * @srclen: the length of @src in bytes
228ba47b515SEric Biggers  * @dst: (output) the decoded binary data
229ba47b515SEric Biggers  *
230ba47b515SEric Biggers  * Decodes a string using base64url encoding, i.e. the "Base 64 Encoding with
231ba47b515SEric Biggers  * URL and Filename Safe Alphabet" specified by RFC 4648.  '='-padding isn't
232ba47b515SEric Biggers  * accepted, nor are non-encoding characters such as whitespace.
233ba47b515SEric Biggers  *
234ba47b515SEric Biggers  * This implementation hasn't been optimized for performance.
235ba47b515SEric Biggers  *
236ba47b515SEric Biggers  * Return: the length of the resulting decoded binary data in bytes,
237ba47b515SEric Biggers  *	   or -1 if the string isn't a valid base64url string.
238ba47b515SEric Biggers  */
fscrypt_base64url_decode(const char * src,int srclen,u8 * dst)239ba47b515SEric Biggers static int fscrypt_base64url_decode(const char *src, int srclen, u8 *dst)
2400b81d077SJaegeuk Kim {
241ba47b515SEric Biggers 	u32 ac = 0;
242ba47b515SEric Biggers 	int bits = 0;
243ba47b515SEric Biggers 	int i;
244ba47b515SEric Biggers 	u8 *bp = dst;
2450b81d077SJaegeuk Kim 
246ba47b515SEric Biggers 	for (i = 0; i < srclen; i++) {
247ba47b515SEric Biggers 		const char *p = strchr(base64url_table, src[i]);
248ba47b515SEric Biggers 
2490b81d077SJaegeuk Kim 		if (p == NULL || src[i] == 0)
250ba47b515SEric Biggers 			return -1;
251ba47b515SEric Biggers 		ac = (ac << 6) | (p - base64url_table);
2520b81d077SJaegeuk Kim 		bits += 6;
2530b81d077SJaegeuk Kim 		if (bits >= 8) {
2540b81d077SJaegeuk Kim 			bits -= 8;
255ba47b515SEric Biggers 			*bp++ = (u8)(ac >> bits);
2560b81d077SJaegeuk Kim 		}
2570b81d077SJaegeuk Kim 	}
258ba47b515SEric Biggers 	if (ac & ((1 << bits) - 1))
2590b81d077SJaegeuk Kim 		return -1;
260ba47b515SEric Biggers 	return bp - dst;
2610b81d077SJaegeuk Kim }
2620b81d077SJaegeuk Kim 
__fscrypt_fname_encrypted_size(const union fscrypt_policy * policy,u32 orig_len,u32 max_len,u32 * encrypted_len_ret)263d3e94fdcSJeff Layton bool __fscrypt_fname_encrypted_size(const union fscrypt_policy *policy,
264ac4acb1fSEric Biggers 				    u32 orig_len, u32 max_len,
265ac4acb1fSEric Biggers 				    u32 *encrypted_len_ret)
2660b81d077SJaegeuk Kim {
267ac4acb1fSEric Biggers 	int padding = 4 << (fscrypt_policy_flags(policy) &
2683b6df59bSEric Biggers 			    FSCRYPT_POLICY_FLAGS_PAD_MASK);
269b9db0b4aSEric Biggers 	u32 encrypted_len;
2700b81d077SJaegeuk Kim 
271b9db0b4aSEric Biggers 	if (orig_len > max_len)
272b9db0b4aSEric Biggers 		return false;
27363cec138SEric Biggers 	encrypted_len = max_t(u32, orig_len, FSCRYPT_FNAME_MIN_MSG_LEN);
274b9db0b4aSEric Biggers 	encrypted_len = round_up(encrypted_len, padding);
275b9db0b4aSEric Biggers 	*encrypted_len_ret = min(encrypted_len, max_len);
276b9db0b4aSEric Biggers 	return true;
2770b81d077SJaegeuk Kim }
2780b81d077SJaegeuk Kim 
2790b81d077SJaegeuk Kim /**
280d3e94fdcSJeff Layton  * fscrypt_fname_encrypted_size() - calculate length of encrypted filename
281d3e94fdcSJeff Layton  * @inode:		parent inode of dentry name being encrypted. Key must
282d3e94fdcSJeff Layton  *			already be set up.
283d3e94fdcSJeff Layton  * @orig_len:		length of the original filename
284d3e94fdcSJeff Layton  * @max_len:		maximum length to return
285d3e94fdcSJeff Layton  * @encrypted_len_ret:	where calculated length should be returned (on success)
286d3e94fdcSJeff Layton  *
287d3e94fdcSJeff Layton  * Filenames that are shorter than the maximum length may have their lengths
288d3e94fdcSJeff Layton  * increased slightly by encryption, due to padding that is applied.
289d3e94fdcSJeff Layton  *
290d3e94fdcSJeff Layton  * Return: false if the orig_len is greater than max_len. Otherwise, true and
291d3e94fdcSJeff Layton  *	   fill out encrypted_len_ret with the length (up to max_len).
292d3e94fdcSJeff Layton  */
fscrypt_fname_encrypted_size(const struct inode * inode,u32 orig_len,u32 max_len,u32 * encrypted_len_ret)293d3e94fdcSJeff Layton bool fscrypt_fname_encrypted_size(const struct inode *inode, u32 orig_len,
294d3e94fdcSJeff Layton 				  u32 max_len, u32 *encrypted_len_ret)
295d3e94fdcSJeff Layton {
296d3e94fdcSJeff Layton 	return __fscrypt_fname_encrypted_size(&inode->i_crypt_info->ci_policy,
297d3e94fdcSJeff Layton 					      orig_len, max_len,
298d3e94fdcSJeff Layton 					      encrypted_len_ret);
299d3e94fdcSJeff Layton }
300d3e94fdcSJeff Layton EXPORT_SYMBOL_GPL(fscrypt_fname_encrypted_size);
301d3e94fdcSJeff Layton 
302d3e94fdcSJeff Layton /**
303d2fe9754SEric Biggers  * fscrypt_fname_alloc_buffer() - allocate a buffer for presented filenames
304d2fe9754SEric Biggers  * @max_encrypted_len: maximum length of encrypted filenames the buffer will be
305d2fe9754SEric Biggers  *		       used to present
306d2fe9754SEric Biggers  * @crypto_str: (output) buffer to allocate
3070b81d077SJaegeuk Kim  *
3082cbadadcSEric Biggers  * Allocate a buffer that is large enough to hold any decrypted or encoded
3092cbadadcSEric Biggers  * filename (null-terminated), for the given maximum encrypted filename length.
3102cbadadcSEric Biggers  *
3112cbadadcSEric Biggers  * Return: 0 on success, -errno on failure
3120b81d077SJaegeuk Kim  */
fscrypt_fname_alloc_buffer(u32 max_encrypted_len,struct fscrypt_str * crypto_str)3138b10fe68SJeff Layton int fscrypt_fname_alloc_buffer(u32 max_encrypted_len,
3142cbadadcSEric Biggers 			       struct fscrypt_str *crypto_str)
3150b81d077SJaegeuk Kim {
316ba47b515SEric Biggers 	u32 max_presented_len = max_t(u32, FSCRYPT_NOKEY_NAME_MAX_ENCODED,
317ba47b515SEric Biggers 				      max_encrypted_len);
31817159420SEric Biggers 
3192cbadadcSEric Biggers 	crypto_str->name = kmalloc(max_presented_len + 1, GFP_NOFS);
3202cbadadcSEric Biggers 	if (!crypto_str->name)
3210b81d077SJaegeuk Kim 		return -ENOMEM;
3222cbadadcSEric Biggers 	crypto_str->len = max_presented_len;
3230b81d077SJaegeuk Kim 	return 0;
3240b81d077SJaegeuk Kim }
3250b81d077SJaegeuk Kim EXPORT_SYMBOL(fscrypt_fname_alloc_buffer);
3260b81d077SJaegeuk Kim 
3270b81d077SJaegeuk Kim /**
328d2fe9754SEric Biggers  * fscrypt_fname_free_buffer() - free a buffer for presented filenames
329d2fe9754SEric Biggers  * @crypto_str: the buffer to free
3300b81d077SJaegeuk Kim  *
331d2fe9754SEric Biggers  * Free a buffer that was allocated by fscrypt_fname_alloc_buffer().
3320b81d077SJaegeuk Kim  */
fscrypt_fname_free_buffer(struct fscrypt_str * crypto_str)3330b81d077SJaegeuk Kim void fscrypt_fname_free_buffer(struct fscrypt_str *crypto_str)
3340b81d077SJaegeuk Kim {
3350b81d077SJaegeuk Kim 	if (!crypto_str)
3360b81d077SJaegeuk Kim 		return;
3370b81d077SJaegeuk Kim 	kfree(crypto_str->name);
3380b81d077SJaegeuk Kim 	crypto_str->name = NULL;
3390b81d077SJaegeuk Kim }
3400b81d077SJaegeuk Kim EXPORT_SYMBOL(fscrypt_fname_free_buffer);
3410b81d077SJaegeuk Kim 
3420b81d077SJaegeuk Kim /**
343d2fe9754SEric Biggers  * fscrypt_fname_disk_to_usr() - convert an encrypted filename to
344d2fe9754SEric Biggers  *				 user-presentable form
345d2fe9754SEric Biggers  * @inode: inode of the parent directory (for regular filenames)
346d2fe9754SEric Biggers  *	   or of the symlink (for symlink targets)
347d2fe9754SEric Biggers  * @hash: first part of the name's dirhash, if applicable.  This only needs to
348d2fe9754SEric Biggers  *	  be provided if the filename is located in an indexed directory whose
349d2fe9754SEric Biggers  *	  encryption key may be unavailable.  Not needed for symlink targets.
350d2fe9754SEric Biggers  * @minor_hash: second part of the name's dirhash, if applicable
351d2fe9754SEric Biggers  * @iname: encrypted filename to convert.  May also be "." or "..", which
352d2fe9754SEric Biggers  *	   aren't actually encrypted.
353d2fe9754SEric Biggers  * @oname: output buffer for the user-presentable filename.  The caller must
354d2fe9754SEric Biggers  *	   have allocated enough space for this, e.g. using
355d2fe9754SEric Biggers  *	   fscrypt_fname_alloc_buffer().
356ef1eb3aaSEric Biggers  *
357edc440e3SDaniel Rosenberg  * If the key is available, we'll decrypt the disk name.  Otherwise, we'll
358edc440e3SDaniel Rosenberg  * encode it for presentation in fscrypt_nokey_name format.
359edc440e3SDaniel Rosenberg  * See struct fscrypt_nokey_name for details.
36017159420SEric Biggers  *
361ef1eb3aaSEric Biggers  * Return: 0 on success, -errno on failure
3620b81d077SJaegeuk Kim  */
fscrypt_fname_disk_to_usr(const struct inode * inode,u32 hash,u32 minor_hash,const struct fscrypt_str * iname,struct fscrypt_str * oname)3638a4ab0b8SEric Biggers int fscrypt_fname_disk_to_usr(const struct inode *inode,
3640b81d077SJaegeuk Kim 			      u32 hash, u32 minor_hash,
3650b81d077SJaegeuk Kim 			      const struct fscrypt_str *iname,
3660b81d077SJaegeuk Kim 			      struct fscrypt_str *oname)
3670b81d077SJaegeuk Kim {
3680b81d077SJaegeuk Kim 	const struct qstr qname = FSTR_TO_QSTR(iname);
369edc440e3SDaniel Rosenberg 	struct fscrypt_nokey_name nokey_name;
370edc440e3SDaniel Rosenberg 	u32 size; /* size of the unencoded no-key name */
3710b81d077SJaegeuk Kim 
3720b81d077SJaegeuk Kim 	if (fscrypt_is_dot_dotdot(&qname)) {
3730b81d077SJaegeuk Kim 		oname->name[0] = '.';
3740b81d077SJaegeuk Kim 		oname->name[iname->len - 1] = '.';
3750b81d077SJaegeuk Kim 		oname->len = iname->len;
376ef1eb3aaSEric Biggers 		return 0;
3770b81d077SJaegeuk Kim 	}
3780b81d077SJaegeuk Kim 
37963cec138SEric Biggers 	if (iname->len < FSCRYPT_FNAME_MIN_MSG_LEN)
3800b81d077SJaegeuk Kim 		return -EUCLEAN;
3810b81d077SJaegeuk Kim 
382e37a784dSEric Biggers 	if (fscrypt_has_encryption_key(inode))
3830b81d077SJaegeuk Kim 		return fname_decrypt(inode, iname, oname);
3840b81d077SJaegeuk Kim 
385edc440e3SDaniel Rosenberg 	/*
386edc440e3SDaniel Rosenberg 	 * Sanity check that struct fscrypt_nokey_name doesn't have padding
387edc440e3SDaniel Rosenberg 	 * between fields and that its encoded size never exceeds NAME_MAX.
388edc440e3SDaniel Rosenberg 	 */
389edc440e3SDaniel Rosenberg 	BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, dirhash) !=
390edc440e3SDaniel Rosenberg 		     offsetof(struct fscrypt_nokey_name, bytes));
391edc440e3SDaniel Rosenberg 	BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, bytes) !=
392edc440e3SDaniel Rosenberg 		     offsetof(struct fscrypt_nokey_name, sha256));
393ba47b515SEric Biggers 	BUILD_BUG_ON(FSCRYPT_NOKEY_NAME_MAX_ENCODED > NAME_MAX);
394edc440e3SDaniel Rosenberg 
395edc440e3SDaniel Rosenberg 	nokey_name.dirhash[0] = hash;
396edc440e3SDaniel Rosenberg 	nokey_name.dirhash[1] = minor_hash;
39777f30bfcSEric Biggers 
398edc440e3SDaniel Rosenberg 	if (iname->len <= sizeof(nokey_name.bytes)) {
399edc440e3SDaniel Rosenberg 		memcpy(nokey_name.bytes, iname->name, iname->len);
400edc440e3SDaniel Rosenberg 		size = offsetof(struct fscrypt_nokey_name, bytes[iname->len]);
401edc440e3SDaniel Rosenberg 	} else {
402edc440e3SDaniel Rosenberg 		memcpy(nokey_name.bytes, iname->name, sizeof(nokey_name.bytes));
403edc440e3SDaniel Rosenberg 		/* Compute strong hash of remaining part of name. */
4040c6a113bSEric Biggers 		sha256(&iname->name[sizeof(nokey_name.bytes)],
405edc440e3SDaniel Rosenberg 		       iname->len - sizeof(nokey_name.bytes),
406edc440e3SDaniel Rosenberg 		       nokey_name.sha256);
407edc440e3SDaniel Rosenberg 		size = FSCRYPT_NOKEY_NAME_MAX;
408edc440e3SDaniel Rosenberg 	}
409ba47b515SEric Biggers 	oname->len = fscrypt_base64url_encode((const u8 *)&nokey_name, size,
410ba47b515SEric Biggers 					      oname->name);
411ef1eb3aaSEric Biggers 	return 0;
4120b81d077SJaegeuk Kim }
4130b81d077SJaegeuk Kim EXPORT_SYMBOL(fscrypt_fname_disk_to_usr);
4140b81d077SJaegeuk Kim 
4150b81d077SJaegeuk Kim /**
41617159420SEric Biggers  * fscrypt_setup_filename() - prepare to search a possibly encrypted directory
41717159420SEric Biggers  * @dir: the directory that will be searched
41817159420SEric Biggers  * @iname: the user-provided filename being searched for
41917159420SEric Biggers  * @lookup: 1 if we're allowed to proceed without the key because it's
42017159420SEric Biggers  *	->lookup() or we're finding the dir_entry for deletion; 0 if we cannot
42117159420SEric Biggers  *	proceed without the key because we're going to create the dir_entry.
42217159420SEric Biggers  * @fname: the filename information to be filled in
42317159420SEric Biggers  *
42417159420SEric Biggers  * Given a user-provided filename @iname, this function sets @fname->disk_name
42517159420SEric Biggers  * to the name that would be stored in the on-disk directory entry, if possible.
42617159420SEric Biggers  * If the directory is unencrypted this is simply @iname.  Else, if we have the
42717159420SEric Biggers  * directory's encryption key, then @iname is the plaintext, so we encrypt it to
42817159420SEric Biggers  * get the disk_name.
42917159420SEric Biggers  *
43070fb2612SEric Biggers  * Else, for keyless @lookup operations, @iname should be a no-key name, so we
43170fb2612SEric Biggers  * decode it to get the struct fscrypt_nokey_name.  Non-@lookup operations will
43270fb2612SEric Biggers  * be impossible in this case, so we fail them with ENOKEY.
43317159420SEric Biggers  *
43417159420SEric Biggers  * If successful, fscrypt_free_filename() must be called later to clean up.
43517159420SEric Biggers  *
43617159420SEric Biggers  * Return: 0 on success, -errno on failure
43717159420SEric Biggers  */
fscrypt_setup_filename(struct inode * dir,const struct qstr * iname,int lookup,struct fscrypt_name * fname)4380b81d077SJaegeuk Kim int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,
4390b81d077SJaegeuk Kim 			      int lookup, struct fscrypt_name *fname)
4400b81d077SJaegeuk Kim {
441edc440e3SDaniel Rosenberg 	struct fscrypt_nokey_name *nokey_name;
44217159420SEric Biggers 	int ret;
4430b81d077SJaegeuk Kim 
4440b81d077SJaegeuk Kim 	memset(fname, 0, sizeof(struct fscrypt_name));
4450b81d077SJaegeuk Kim 	fname->usr_fname = iname;
4460b81d077SJaegeuk Kim 
447e0428a26SEric Biggers 	if (!IS_ENCRYPTED(dir) || fscrypt_is_dot_dotdot(iname)) {
4480b81d077SJaegeuk Kim 		fname->disk_name.name = (unsigned char *)iname->name;
4490b81d077SJaegeuk Kim 		fname->disk_name.len = iname->len;
4500b81d077SJaegeuk Kim 		return 0;
4510b81d077SJaegeuk Kim 	}
452a14d0b67SEric Biggers 	ret = fscrypt_get_encryption_info(dir, lookup);
45317bfde60SEric Biggers 	if (ret)
4540b81d077SJaegeuk Kim 		return ret;
4550b81d077SJaegeuk Kim 
456e37a784dSEric Biggers 	if (fscrypt_has_encryption_key(dir)) {
457d3e94fdcSJeff Layton 		if (!fscrypt_fname_encrypted_size(dir, iname->len, NAME_MAX,
458b9db0b4aSEric Biggers 						  &fname->crypto_buf.len))
45950c961deSEric Biggers 			return -ENAMETOOLONG;
46050c961deSEric Biggers 		fname->crypto_buf.name = kmalloc(fname->crypto_buf.len,
46150c961deSEric Biggers 						 GFP_NOFS);
46250c961deSEric Biggers 		if (!fname->crypto_buf.name)
46350c961deSEric Biggers 			return -ENOMEM;
46450c961deSEric Biggers 
4651b3b827eSEric Biggers 		ret = fscrypt_fname_encrypt(dir, iname, fname->crypto_buf.name,
46650c961deSEric Biggers 					    fname->crypto_buf.len);
467ef1eb3aaSEric Biggers 		if (ret)
4680b81d077SJaegeuk Kim 			goto errout;
4690b81d077SJaegeuk Kim 		fname->disk_name.name = fname->crypto_buf.name;
4700b81d077SJaegeuk Kim 		fname->disk_name.len = fname->crypto_buf.len;
4710b81d077SJaegeuk Kim 		return 0;
4720b81d077SJaegeuk Kim 	}
4730b81d077SJaegeuk Kim 	if (!lookup)
47454475f53SEric Biggers 		return -ENOKEY;
47570fb2612SEric Biggers 	fname->is_nokey_name = true;
4760b81d077SJaegeuk Kim 
4770b81d077SJaegeuk Kim 	/*
4780b81d077SJaegeuk Kim 	 * We don't have the key and we are doing a lookup; decode the
4790b81d077SJaegeuk Kim 	 * user-supplied name
4800b81d077SJaegeuk Kim 	 */
4810b81d077SJaegeuk Kim 
482ba47b515SEric Biggers 	if (iname->len > FSCRYPT_NOKEY_NAME_MAX_ENCODED)
483edc440e3SDaniel Rosenberg 		return -ENOENT;
484edc440e3SDaniel Rosenberg 
485edc440e3SDaniel Rosenberg 	fname->crypto_buf.name = kmalloc(FSCRYPT_NOKEY_NAME_MAX, GFP_KERNEL);
4860b81d077SJaegeuk Kim 	if (fname->crypto_buf.name == NULL)
4870b81d077SJaegeuk Kim 		return -ENOMEM;
4880b81d077SJaegeuk Kim 
489ba47b515SEric Biggers 	ret = fscrypt_base64url_decode(iname->name, iname->len,
490ba47b515SEric Biggers 				       fname->crypto_buf.name);
491edc440e3SDaniel Rosenberg 	if (ret < (int)offsetof(struct fscrypt_nokey_name, bytes[1]) ||
492edc440e3SDaniel Rosenberg 	    (ret > offsetof(struct fscrypt_nokey_name, sha256) &&
493edc440e3SDaniel Rosenberg 	     ret != FSCRYPT_NOKEY_NAME_MAX)) {
4940b81d077SJaegeuk Kim 		ret = -ENOENT;
4950b81d077SJaegeuk Kim 		goto errout;
4960b81d077SJaegeuk Kim 	}
4970b81d077SJaegeuk Kim 	fname->crypto_buf.len = ret;
498edc440e3SDaniel Rosenberg 
499edc440e3SDaniel Rosenberg 	nokey_name = (void *)fname->crypto_buf.name;
500edc440e3SDaniel Rosenberg 	fname->hash = nokey_name->dirhash[0];
501edc440e3SDaniel Rosenberg 	fname->minor_hash = nokey_name->dirhash[1];
502edc440e3SDaniel Rosenberg 	if (ret != FSCRYPT_NOKEY_NAME_MAX) {
503edc440e3SDaniel Rosenberg 		/* The full ciphertext filename is available. */
504edc440e3SDaniel Rosenberg 		fname->disk_name.name = nokey_name->bytes;
505edc440e3SDaniel Rosenberg 		fname->disk_name.len =
506edc440e3SDaniel Rosenberg 			ret - offsetof(struct fscrypt_nokey_name, bytes);
5070b81d077SJaegeuk Kim 	}
5080b81d077SJaegeuk Kim 	return 0;
5090b81d077SJaegeuk Kim 
5100b81d077SJaegeuk Kim errout:
51150c961deSEric Biggers 	kfree(fname->crypto_buf.name);
5120b81d077SJaegeuk Kim 	return ret;
5130b81d077SJaegeuk Kim }
5140b81d077SJaegeuk Kim EXPORT_SYMBOL(fscrypt_setup_filename);
5152ebdef6dSEric Biggers 
516aa408f83SDaniel Rosenberg /**
517edc440e3SDaniel Rosenberg  * fscrypt_match_name() - test whether the given name matches a directory entry
518edc440e3SDaniel Rosenberg  * @fname: the name being searched for
519edc440e3SDaniel Rosenberg  * @de_name: the name from the directory entry
520edc440e3SDaniel Rosenberg  * @de_name_len: the length of @de_name in bytes
521edc440e3SDaniel Rosenberg  *
522edc440e3SDaniel Rosenberg  * Normally @fname->disk_name will be set, and in that case we simply compare
523edc440e3SDaniel Rosenberg  * that to the name stored in the directory entry.  The only exception is that
524edc440e3SDaniel Rosenberg  * if we don't have the key for an encrypted directory and the name we're
525edc440e3SDaniel Rosenberg  * looking for is very long, then we won't have the full disk_name and instead
526edc440e3SDaniel Rosenberg  * we'll need to match against a fscrypt_nokey_name that includes a strong hash.
527edc440e3SDaniel Rosenberg  *
528edc440e3SDaniel Rosenberg  * Return: %true if the name matches, otherwise %false.
529edc440e3SDaniel Rosenberg  */
fscrypt_match_name(const struct fscrypt_name * fname,const u8 * de_name,u32 de_name_len)530edc440e3SDaniel Rosenberg bool fscrypt_match_name(const struct fscrypt_name *fname,
531edc440e3SDaniel Rosenberg 			const u8 *de_name, u32 de_name_len)
532edc440e3SDaniel Rosenberg {
533edc440e3SDaniel Rosenberg 	const struct fscrypt_nokey_name *nokey_name =
534edc440e3SDaniel Rosenberg 		(const void *)fname->crypto_buf.name;
5350c6a113bSEric Biggers 	u8 digest[SHA256_DIGEST_SIZE];
536edc440e3SDaniel Rosenberg 
537edc440e3SDaniel Rosenberg 	if (likely(fname->disk_name.name)) {
538edc440e3SDaniel Rosenberg 		if (de_name_len != fname->disk_name.len)
539edc440e3SDaniel Rosenberg 			return false;
540edc440e3SDaniel Rosenberg 		return !memcmp(de_name, fname->disk_name.name, de_name_len);
541edc440e3SDaniel Rosenberg 	}
542edc440e3SDaniel Rosenberg 	if (de_name_len <= sizeof(nokey_name->bytes))
543edc440e3SDaniel Rosenberg 		return false;
544edc440e3SDaniel Rosenberg 	if (memcmp(de_name, nokey_name->bytes, sizeof(nokey_name->bytes)))
545edc440e3SDaniel Rosenberg 		return false;
5460c6a113bSEric Biggers 	sha256(&de_name[sizeof(nokey_name->bytes)],
5470c6a113bSEric Biggers 	       de_name_len - sizeof(nokey_name->bytes), digest);
5480c6a113bSEric Biggers 	return !memcmp(digest, nokey_name->sha256, sizeof(digest));
549edc440e3SDaniel Rosenberg }
550edc440e3SDaniel Rosenberg EXPORT_SYMBOL_GPL(fscrypt_match_name);
551edc440e3SDaniel Rosenberg 
552edc440e3SDaniel Rosenberg /**
553aa408f83SDaniel Rosenberg  * fscrypt_fname_siphash() - calculate the SipHash of a filename
554aa408f83SDaniel Rosenberg  * @dir: the parent directory
555aa408f83SDaniel Rosenberg  * @name: the filename to calculate the SipHash of
556aa408f83SDaniel Rosenberg  *
557aa408f83SDaniel Rosenberg  * Given a plaintext filename @name and a directory @dir which uses SipHash as
558aa408f83SDaniel Rosenberg  * its dirhash method and has had its fscrypt key set up, this function
559aa408f83SDaniel Rosenberg  * calculates the SipHash of that name using the directory's secret dirhash key.
560aa408f83SDaniel Rosenberg  *
561aa408f83SDaniel Rosenberg  * Return: the SipHash of @name using the hash key of @dir
562aa408f83SDaniel Rosenberg  */
fscrypt_fname_siphash(const struct inode * dir,const struct qstr * name)563aa408f83SDaniel Rosenberg u64 fscrypt_fname_siphash(const struct inode *dir, const struct qstr *name)
564aa408f83SDaniel Rosenberg {
565aa408f83SDaniel Rosenberg 	const struct fscrypt_info *ci = dir->i_crypt_info;
566aa408f83SDaniel Rosenberg 
56741b2ad80SEric Biggers 	WARN_ON_ONCE(!ci->ci_dirhash_key_initialized);
568aa408f83SDaniel Rosenberg 
569aa408f83SDaniel Rosenberg 	return siphash(name->name, name->len, &ci->ci_dirhash_key);
570aa408f83SDaniel Rosenberg }
571aa408f83SDaniel Rosenberg EXPORT_SYMBOL_GPL(fscrypt_fname_siphash);
572aa408f83SDaniel Rosenberg 
5732ebdef6dSEric Biggers /*
5742ebdef6dSEric Biggers  * Validate dentries in encrypted directories to make sure we aren't potentially
5752ebdef6dSEric Biggers  * caching stale dentries after a key has been added.
5762ebdef6dSEric Biggers  */
fscrypt_d_revalidate(struct dentry * dentry,unsigned int flags)5775b2a828bSEric Biggers int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags)
5782ebdef6dSEric Biggers {
5792ebdef6dSEric Biggers 	struct dentry *dir;
5802ebdef6dSEric Biggers 	int err;
5812ebdef6dSEric Biggers 	int valid;
5822ebdef6dSEric Biggers 
5832ebdef6dSEric Biggers 	/*
5842ebdef6dSEric Biggers 	 * Plaintext names are always valid, since fscrypt doesn't support
58570fb2612SEric Biggers 	 * reverting to no-key names without evicting the directory's inode
5862ebdef6dSEric Biggers 	 * -- which implies eviction of the dentries in the directory.
5872ebdef6dSEric Biggers 	 */
588501e43fbSEric Biggers 	if (!(dentry->d_flags & DCACHE_NOKEY_NAME))
5892ebdef6dSEric Biggers 		return 1;
5902ebdef6dSEric Biggers 
5912ebdef6dSEric Biggers 	/*
59270fb2612SEric Biggers 	 * No-key name; valid if the directory's key is still unavailable.
5932ebdef6dSEric Biggers 	 *
59470fb2612SEric Biggers 	 * Although fscrypt forbids rename() on no-key names, we still must use
59570fb2612SEric Biggers 	 * dget_parent() here rather than use ->d_parent directly.  That's
5962ebdef6dSEric Biggers 	 * because a corrupted fs image may contain directory hard links, which
5972ebdef6dSEric Biggers 	 * the VFS handles by moving the directory's dentry tree in the dcache
5982ebdef6dSEric Biggers 	 * each time ->lookup() finds the directory and it already has a dentry
5992ebdef6dSEric Biggers 	 * elsewhere.  Thus ->d_parent can be changing, and we must safely grab
6002ebdef6dSEric Biggers 	 * a reference to some ->d_parent to prevent it from being freed.
6012ebdef6dSEric Biggers 	 */
6022ebdef6dSEric Biggers 
6032ebdef6dSEric Biggers 	if (flags & LOOKUP_RCU)
6042ebdef6dSEric Biggers 		return -ECHILD;
6052ebdef6dSEric Biggers 
6062ebdef6dSEric Biggers 	dir = dget_parent(dentry);
607a14d0b67SEric Biggers 	/*
608a14d0b67SEric Biggers 	 * Pass allow_unsupported=true, so that files with an unsupported
609a14d0b67SEric Biggers 	 * encryption policy can be deleted.
610a14d0b67SEric Biggers 	 */
611a14d0b67SEric Biggers 	err = fscrypt_get_encryption_info(d_inode(dir), true);
6122ebdef6dSEric Biggers 	valid = !fscrypt_has_encryption_key(d_inode(dir));
6132ebdef6dSEric Biggers 	dput(dir);
6142ebdef6dSEric Biggers 
6152ebdef6dSEric Biggers 	if (err < 0)
6162ebdef6dSEric Biggers 		return err;
6172ebdef6dSEric Biggers 
6182ebdef6dSEric Biggers 	return valid;
6192ebdef6dSEric Biggers }
6205b2a828bSEric Biggers EXPORT_SYMBOL_GPL(fscrypt_d_revalidate);
621