1 // SPDX-License-Identifier: GPL-2.0
3 * This contains functions for filename crypto management
5 * Copyright (C) 2015, Google, Inc.
6 * Copyright (C) 2015, Motorola Mobility
8 * Written by Uday Savagaonkar, 2014.
9 * Modified by Jaegeuk Kim, 2015.
11 * This has not yet undergone a rigorous security audit.
14 #include <linux/namei.h>
15 #include <linux/scatterlist.h>
16 #include <crypto/hash.h>
17 #include <crypto/sha2.h>
18 #include <crypto/skcipher.h>
19 #include "fscrypt_private.h"
22 * struct fscrypt_nokey_name - identifier for directory entry when key is absent
24 * When userspace lists an encrypted directory without access to the key, the
25 * filesystem must present a unique "no-key name" for each filename that allows
26 * it to find the directory entry again if requested. Naively, that would just
27 * mean using the ciphertext filenames. However, since the ciphertext filenames
28 * can contain illegal characters ('\0' and '/'), they must be encoded in some
29 * way. We use base64url. But that can cause names to exceed NAME_MAX (255
30 * bytes), so we also need to use a strong hash to abbreviate long names.
32 * The filesystem may also need another kind of hash, the "dirhash", to quickly
33 * find the directory entry. Since filesystems normally compute the dirhash
34 * over the on-disk filename (i.e. the ciphertext), it's not computable from
35 * no-key names that abbreviate the ciphertext using the strong hash to fit in
36 * NAME_MAX. It's also not computable if it's a keyed hash taken over the
37 * plaintext (but it may still be available in the on-disk directory entry);
38 * casefolded directories use this type of dirhash. At least in these cases,
39 * each no-key name must include the name's dirhash too.
41 * To meet all these requirements, we base64url-encode the following
42 * variable-length structure. It contains the dirhash, or 0's if the filesystem
43 * didn't provide one; up to 149 bytes of the ciphertext name; and for
44 * ciphertexts longer than 149 bytes, also the SHA-256 of the remaining bytes.
46 * This ensures that each no-key name contains everything needed to find the
47 * directory entry again, contains only legal characters, doesn't exceed
48 * NAME_MAX, is unambiguous unless there's a SHA-256 collision, and that we only
49 * take the performance hit of SHA-256 on very long filenames (which are rare).
51 struct fscrypt_nokey_name {
54 u8 sha256[SHA256_DIGEST_SIZE];
55 }; /* 189 bytes => 252 bytes base64url-encoded, which is <= NAME_MAX (255) */
58 * Decoded size of max-size no-key name, i.e. a name that was abbreviated using
59 * the strong hash and thus includes the 'sha256' field. This isn't simply
60 * sizeof(struct fscrypt_nokey_name), as the padding at the end isn't included.
62 #define FSCRYPT_NOKEY_NAME_MAX offsetofend(struct fscrypt_nokey_name, sha256)
64 /* Encoded size of max-size no-key name */
65 #define FSCRYPT_NOKEY_NAME_MAX_ENCODED \
66 FSCRYPT_BASE64URL_CHARS(FSCRYPT_NOKEY_NAME_MAX)
68 static inline bool fscrypt_is_dot_dotdot(const struct qstr *str)
70 if (str->len == 1 && str->name[0] == '.')
73 if (str->len == 2 && str->name[0] == '.' && str->name[1] == '.')
80 * fscrypt_fname_encrypt() - encrypt a filename
81 * @inode: inode of the parent directory (for regular filenames)
82 * or of the symlink (for symlink targets)
83 * @iname: the filename to encrypt
84 * @out: (output) the encrypted filename
85 * @olen: size of the encrypted filename. It must be at least @iname->len.
86 * Any extra space is filled with NUL padding before encryption.
88 * Return: 0 on success, -errno on failure
90 int fscrypt_fname_encrypt(const struct inode *inode, const struct qstr *iname,
91 u8 *out, unsigned int olen)
93 struct skcipher_request *req = NULL;
94 DECLARE_CRYPTO_WAIT(wait);
95 const struct fscrypt_info *ci = inode->i_crypt_info;
96 struct crypto_skcipher *tfm = ci->ci_enc_key.tfm;
98 struct scatterlist sg;
102 * Copy the filename to the output buffer for encrypting in-place and
103 * pad it with the needed number of NUL bytes.
105 if (WARN_ON(olen < iname->len))
107 memcpy(out, iname->name, iname->len);
108 memset(out + iname->len, 0, olen - iname->len);
110 /* Initialize the IV */
111 fscrypt_generate_iv(&iv, 0, ci);
113 /* Set up the encryption request */
114 req = skcipher_request_alloc(tfm, GFP_NOFS);
117 skcipher_request_set_callback(req,
118 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
119 crypto_req_done, &wait);
120 sg_init_one(&sg, out, olen);
121 skcipher_request_set_crypt(req, &sg, &sg, olen, &iv);
123 /* Do the encryption */
124 res = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
125 skcipher_request_free(req);
127 fscrypt_err(inode, "Filename encryption failed: %d", res);
135 * fname_decrypt() - decrypt a filename
136 * @inode: inode of the parent directory (for regular filenames)
137 * or of the symlink (for symlink targets)
138 * @iname: the encrypted filename to decrypt
139 * @oname: (output) the decrypted filename. The caller must have allocated
140 * enough space for this, e.g. using fscrypt_fname_alloc_buffer().
142 * Return: 0 on success, -errno on failure
144 static int fname_decrypt(const struct inode *inode,
145 const struct fscrypt_str *iname,
146 struct fscrypt_str *oname)
148 struct skcipher_request *req = NULL;
149 DECLARE_CRYPTO_WAIT(wait);
150 struct scatterlist src_sg, dst_sg;
151 const struct fscrypt_info *ci = inode->i_crypt_info;
152 struct crypto_skcipher *tfm = ci->ci_enc_key.tfm;
156 /* Allocate request */
157 req = skcipher_request_alloc(tfm, GFP_NOFS);
160 skcipher_request_set_callback(req,
161 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
162 crypto_req_done, &wait);
165 fscrypt_generate_iv(&iv, 0, ci);
167 /* Create decryption request */
168 sg_init_one(&src_sg, iname->name, iname->len);
169 sg_init_one(&dst_sg, oname->name, oname->len);
170 skcipher_request_set_crypt(req, &src_sg, &dst_sg, iname->len, &iv);
171 res = crypto_wait_req(crypto_skcipher_decrypt(req), &wait);
172 skcipher_request_free(req);
174 fscrypt_err(inode, "Filename decryption failed: %d", res);
178 oname->len = strnlen(oname->name, iname->len);
182 static const char base64url_table[65] =
183 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
185 #define FSCRYPT_BASE64URL_CHARS(nbytes) DIV_ROUND_UP((nbytes) * 4, 3)
188 * fscrypt_base64url_encode() - base64url-encode some binary data
189 * @src: the binary data to encode
190 * @srclen: the length of @src in bytes
191 * @dst: (output) the base64url-encoded string. Not NUL-terminated.
193 * Encodes data using base64url encoding, i.e. the "Base 64 Encoding with URL
194 * and Filename Safe Alphabet" specified by RFC 4648. '='-padding isn't used,
195 * as it's unneeded and not required by the RFC. base64url is used instead of
196 * base64 to avoid the '/' character, which isn't allowed in filenames.
198 * Return: the length of the resulting base64url-encoded string in bytes.
199 * This will be equal to FSCRYPT_BASE64URL_CHARS(srclen).
201 static int fscrypt_base64url_encode(const u8 *src, int srclen, char *dst)
208 for (i = 0; i < srclen; i++) {
209 ac = (ac << 8) | src[i];
213 *cp++ = base64url_table[(ac >> bits) & 0x3f];
217 *cp++ = base64url_table[(ac << (6 - bits)) & 0x3f];
222 * fscrypt_base64url_decode() - base64url-decode a string
223 * @src: the string to decode. Doesn't need to be NUL-terminated.
224 * @srclen: the length of @src in bytes
225 * @dst: (output) the decoded binary data
227 * Decodes a string using base64url encoding, i.e. the "Base 64 Encoding with
228 * URL and Filename Safe Alphabet" specified by RFC 4648. '='-padding isn't
229 * accepted, nor are non-encoding characters such as whitespace.
231 * This implementation hasn't been optimized for performance.
233 * Return: the length of the resulting decoded binary data in bytes,
234 * or -1 if the string isn't a valid base64url string.
236 static int fscrypt_base64url_decode(const char *src, int srclen, u8 *dst)
243 for (i = 0; i < srclen; i++) {
244 const char *p = strchr(base64url_table, src[i]);
246 if (p == NULL || src[i] == 0)
248 ac = (ac << 6) | (p - base64url_table);
252 *bp++ = (u8)(ac >> bits);
255 if (ac & ((1 << bits) - 1))
260 bool fscrypt_fname_encrypted_size(const union fscrypt_policy *policy,
261 u32 orig_len, u32 max_len,
262 u32 *encrypted_len_ret)
264 int padding = 4 << (fscrypt_policy_flags(policy) &
265 FSCRYPT_POLICY_FLAGS_PAD_MASK);
268 if (orig_len > max_len)
270 encrypted_len = max(orig_len, (u32)FS_CRYPTO_BLOCK_SIZE);
271 encrypted_len = round_up(encrypted_len, padding);
272 *encrypted_len_ret = min(encrypted_len, max_len);
277 * fscrypt_fname_alloc_buffer() - allocate a buffer for presented filenames
278 * @max_encrypted_len: maximum length of encrypted filenames the buffer will be
280 * @crypto_str: (output) buffer to allocate
282 * Allocate a buffer that is large enough to hold any decrypted or encoded
283 * filename (null-terminated), for the given maximum encrypted filename length.
285 * Return: 0 on success, -errno on failure
287 int fscrypt_fname_alloc_buffer(u32 max_encrypted_len,
288 struct fscrypt_str *crypto_str)
290 u32 max_presented_len = max_t(u32, FSCRYPT_NOKEY_NAME_MAX_ENCODED,
293 crypto_str->name = kmalloc(max_presented_len + 1, GFP_NOFS);
294 if (!crypto_str->name)
296 crypto_str->len = max_presented_len;
299 EXPORT_SYMBOL(fscrypt_fname_alloc_buffer);
302 * fscrypt_fname_free_buffer() - free a buffer for presented filenames
303 * @crypto_str: the buffer to free
305 * Free a buffer that was allocated by fscrypt_fname_alloc_buffer().
307 void fscrypt_fname_free_buffer(struct fscrypt_str *crypto_str)
311 kfree(crypto_str->name);
312 crypto_str->name = NULL;
314 EXPORT_SYMBOL(fscrypt_fname_free_buffer);
317 * fscrypt_fname_disk_to_usr() - convert an encrypted filename to
318 * user-presentable form
319 * @inode: inode of the parent directory (for regular filenames)
320 * or of the symlink (for symlink targets)
321 * @hash: first part of the name's dirhash, if applicable. This only needs to
322 * be provided if the filename is located in an indexed directory whose
323 * encryption key may be unavailable. Not needed for symlink targets.
324 * @minor_hash: second part of the name's dirhash, if applicable
325 * @iname: encrypted filename to convert. May also be "." or "..", which
326 * aren't actually encrypted.
327 * @oname: output buffer for the user-presentable filename. The caller must
328 * have allocated enough space for this, e.g. using
329 * fscrypt_fname_alloc_buffer().
331 * If the key is available, we'll decrypt the disk name. Otherwise, we'll
332 * encode it for presentation in fscrypt_nokey_name format.
333 * See struct fscrypt_nokey_name for details.
335 * Return: 0 on success, -errno on failure
337 int fscrypt_fname_disk_to_usr(const struct inode *inode,
338 u32 hash, u32 minor_hash,
339 const struct fscrypt_str *iname,
340 struct fscrypt_str *oname)
342 const struct qstr qname = FSTR_TO_QSTR(iname);
343 struct fscrypt_nokey_name nokey_name;
344 u32 size; /* size of the unencoded no-key name */
346 if (fscrypt_is_dot_dotdot(&qname)) {
347 oname->name[0] = '.';
348 oname->name[iname->len - 1] = '.';
349 oname->len = iname->len;
353 if (iname->len < FS_CRYPTO_BLOCK_SIZE)
356 if (fscrypt_has_encryption_key(inode))
357 return fname_decrypt(inode, iname, oname);
360 * Sanity check that struct fscrypt_nokey_name doesn't have padding
361 * between fields and that its encoded size never exceeds NAME_MAX.
363 BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, dirhash) !=
364 offsetof(struct fscrypt_nokey_name, bytes));
365 BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, bytes) !=
366 offsetof(struct fscrypt_nokey_name, sha256));
367 BUILD_BUG_ON(FSCRYPT_NOKEY_NAME_MAX_ENCODED > NAME_MAX);
369 nokey_name.dirhash[0] = hash;
370 nokey_name.dirhash[1] = minor_hash;
372 if (iname->len <= sizeof(nokey_name.bytes)) {
373 memcpy(nokey_name.bytes, iname->name, iname->len);
374 size = offsetof(struct fscrypt_nokey_name, bytes[iname->len]);
376 memcpy(nokey_name.bytes, iname->name, sizeof(nokey_name.bytes));
377 /* Compute strong hash of remaining part of name. */
378 sha256(&iname->name[sizeof(nokey_name.bytes)],
379 iname->len - sizeof(nokey_name.bytes),
381 size = FSCRYPT_NOKEY_NAME_MAX;
383 oname->len = fscrypt_base64url_encode((const u8 *)&nokey_name, size,
387 EXPORT_SYMBOL(fscrypt_fname_disk_to_usr);
390 * fscrypt_setup_filename() - prepare to search a possibly encrypted directory
391 * @dir: the directory that will be searched
392 * @iname: the user-provided filename being searched for
393 * @lookup: 1 if we're allowed to proceed without the key because it's
394 * ->lookup() or we're finding the dir_entry for deletion; 0 if we cannot
395 * proceed without the key because we're going to create the dir_entry.
396 * @fname: the filename information to be filled in
398 * Given a user-provided filename @iname, this function sets @fname->disk_name
399 * to the name that would be stored in the on-disk directory entry, if possible.
400 * If the directory is unencrypted this is simply @iname. Else, if we have the
401 * directory's encryption key, then @iname is the plaintext, so we encrypt it to
404 * Else, for keyless @lookup operations, @iname should be a no-key name, so we
405 * decode it to get the struct fscrypt_nokey_name. Non-@lookup operations will
406 * be impossible in this case, so we fail them with ENOKEY.
408 * If successful, fscrypt_free_filename() must be called later to clean up.
410 * Return: 0 on success, -errno on failure
412 int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,
413 int lookup, struct fscrypt_name *fname)
415 struct fscrypt_nokey_name *nokey_name;
418 memset(fname, 0, sizeof(struct fscrypt_name));
419 fname->usr_fname = iname;
421 if (!IS_ENCRYPTED(dir) || fscrypt_is_dot_dotdot(iname)) {
422 fname->disk_name.name = (unsigned char *)iname->name;
423 fname->disk_name.len = iname->len;
426 ret = fscrypt_get_encryption_info(dir, lookup);
430 if (fscrypt_has_encryption_key(dir)) {
431 if (!fscrypt_fname_encrypted_size(&dir->i_crypt_info->ci_policy,
433 dir->i_sb->s_cop->max_namelen,
434 &fname->crypto_buf.len))
435 return -ENAMETOOLONG;
436 fname->crypto_buf.name = kmalloc(fname->crypto_buf.len,
438 if (!fname->crypto_buf.name)
441 ret = fscrypt_fname_encrypt(dir, iname, fname->crypto_buf.name,
442 fname->crypto_buf.len);
445 fname->disk_name.name = fname->crypto_buf.name;
446 fname->disk_name.len = fname->crypto_buf.len;
451 fname->is_nokey_name = true;
454 * We don't have the key and we are doing a lookup; decode the
458 if (iname->len > FSCRYPT_NOKEY_NAME_MAX_ENCODED)
461 fname->crypto_buf.name = kmalloc(FSCRYPT_NOKEY_NAME_MAX, GFP_KERNEL);
462 if (fname->crypto_buf.name == NULL)
465 ret = fscrypt_base64url_decode(iname->name, iname->len,
466 fname->crypto_buf.name);
467 if (ret < (int)offsetof(struct fscrypt_nokey_name, bytes[1]) ||
468 (ret > offsetof(struct fscrypt_nokey_name, sha256) &&
469 ret != FSCRYPT_NOKEY_NAME_MAX)) {
473 fname->crypto_buf.len = ret;
475 nokey_name = (void *)fname->crypto_buf.name;
476 fname->hash = nokey_name->dirhash[0];
477 fname->minor_hash = nokey_name->dirhash[1];
478 if (ret != FSCRYPT_NOKEY_NAME_MAX) {
479 /* The full ciphertext filename is available. */
480 fname->disk_name.name = nokey_name->bytes;
481 fname->disk_name.len =
482 ret - offsetof(struct fscrypt_nokey_name, bytes);
487 kfree(fname->crypto_buf.name);
490 EXPORT_SYMBOL(fscrypt_setup_filename);
493 * fscrypt_match_name() - test whether the given name matches a directory entry
494 * @fname: the name being searched for
495 * @de_name: the name from the directory entry
496 * @de_name_len: the length of @de_name in bytes
498 * Normally @fname->disk_name will be set, and in that case we simply compare
499 * that to the name stored in the directory entry. The only exception is that
500 * if we don't have the key for an encrypted directory and the name we're
501 * looking for is very long, then we won't have the full disk_name and instead
502 * we'll need to match against a fscrypt_nokey_name that includes a strong hash.
504 * Return: %true if the name matches, otherwise %false.
506 bool fscrypt_match_name(const struct fscrypt_name *fname,
507 const u8 *de_name, u32 de_name_len)
509 const struct fscrypt_nokey_name *nokey_name =
510 (const void *)fname->crypto_buf.name;
511 u8 digest[SHA256_DIGEST_SIZE];
513 if (likely(fname->disk_name.name)) {
514 if (de_name_len != fname->disk_name.len)
516 return !memcmp(de_name, fname->disk_name.name, de_name_len);
518 if (de_name_len <= sizeof(nokey_name->bytes))
520 if (memcmp(de_name, nokey_name->bytes, sizeof(nokey_name->bytes)))
522 sha256(&de_name[sizeof(nokey_name->bytes)],
523 de_name_len - sizeof(nokey_name->bytes), digest);
524 return !memcmp(digest, nokey_name->sha256, sizeof(digest));
526 EXPORT_SYMBOL_GPL(fscrypt_match_name);
529 * fscrypt_fname_siphash() - calculate the SipHash of a filename
530 * @dir: the parent directory
531 * @name: the filename to calculate the SipHash of
533 * Given a plaintext filename @name and a directory @dir which uses SipHash as
534 * its dirhash method and has had its fscrypt key set up, this function
535 * calculates the SipHash of that name using the directory's secret dirhash key.
537 * Return: the SipHash of @name using the hash key of @dir
539 u64 fscrypt_fname_siphash(const struct inode *dir, const struct qstr *name)
541 const struct fscrypt_info *ci = dir->i_crypt_info;
543 WARN_ON(!ci->ci_dirhash_key_initialized);
545 return siphash(name->name, name->len, &ci->ci_dirhash_key);
547 EXPORT_SYMBOL_GPL(fscrypt_fname_siphash);
550 * Validate dentries in encrypted directories to make sure we aren't potentially
551 * caching stale dentries after a key has been added.
553 int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags)
560 * Plaintext names are always valid, since fscrypt doesn't support
561 * reverting to no-key names without evicting the directory's inode
562 * -- which implies eviction of the dentries in the directory.
564 if (!(dentry->d_flags & DCACHE_NOKEY_NAME))
568 * No-key name; valid if the directory's key is still unavailable.
570 * Although fscrypt forbids rename() on no-key names, we still must use
571 * dget_parent() here rather than use ->d_parent directly. That's
572 * because a corrupted fs image may contain directory hard links, which
573 * the VFS handles by moving the directory's dentry tree in the dcache
574 * each time ->lookup() finds the directory and it already has a dentry
575 * elsewhere. Thus ->d_parent can be changing, and we must safely grab
576 * a reference to some ->d_parent to prevent it from being freed.
579 if (flags & LOOKUP_RCU)
582 dir = dget_parent(dentry);
584 * Pass allow_unsupported=true, so that files with an unsupported
585 * encryption policy can be deleted.
587 err = fscrypt_get_encryption_info(d_inode(dir), true);
588 valid = !fscrypt_has_encryption_key(d_inode(dir));
596 EXPORT_SYMBOL_GPL(fscrypt_d_revalidate);