xref: /linux/fs/crypto/fname.c (revision 509d3f45847627f4c5cdce004c3ec79262b5239c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This contains functions for filename crypto management
4  *
5  * Copyright (C) 2015, Google, Inc.
6  * Copyright (C) 2015, Motorola Mobility
7  *
8  * Written by Uday Savagaonkar, 2014.
9  * Modified by Jaegeuk Kim, 2015.
10  *
11  * This has not yet undergone a rigorous security audit.
12  */
13 
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>
19 #include <linux/base64.h>
20 
21 #include "fscrypt_private.h"
22 
23 /*
24  * The minimum message length (input and output length), in bytes, for all
25  * filenames encryption modes.  Filenames shorter than this will be zero-padded
26  * before being encrypted.
27  */
28 #define FSCRYPT_FNAME_MIN_MSG_LEN 16
29 
30 /*
31  * struct fscrypt_nokey_name - identifier for directory entry when key is absent
32  *
33  * When userspace lists an encrypted directory without access to the key, the
34  * filesystem must present a unique "no-key name" for each filename that allows
35  * it to find the directory entry again if requested.  Naively, that would just
36  * mean using the ciphertext filenames.  However, since the ciphertext filenames
37  * can contain illegal characters ('\0' and '/'), they must be encoded in some
38  * way.  We use base64url.  But that can cause names to exceed NAME_MAX (255
39  * bytes), so we also need to use a strong hash to abbreviate long names.
40  *
41  * The filesystem may also need another kind of hash, the "dirhash", to quickly
42  * find the directory entry.  Since filesystems normally compute the dirhash
43  * over the on-disk filename (i.e. the ciphertext), it's not computable from
44  * no-key names that abbreviate the ciphertext using the strong hash to fit in
45  * NAME_MAX.  It's also not computable if it's a keyed hash taken over the
46  * plaintext (but it may still be available in the on-disk directory entry);
47  * casefolded directories use this type of dirhash.  At least in these cases,
48  * each no-key name must include the name's dirhash too.
49  *
50  * To meet all these requirements, we base64url-encode the following
51  * variable-length structure.  It contains the dirhash, or 0's if the filesystem
52  * didn't provide one; up to 149 bytes of the ciphertext name; and for
53  * ciphertexts longer than 149 bytes, also the SHA-256 of the remaining bytes.
54  *
55  * This ensures that each no-key name contains everything needed to find the
56  * directory entry again, contains only legal characters, doesn't exceed
57  * NAME_MAX, is unambiguous unless there's a SHA-256 collision, and that we only
58  * take the performance hit of SHA-256 on very long filenames (which are rare).
59  */
60 struct fscrypt_nokey_name {
61 	u32 dirhash[2];
62 	u8 bytes[149];
63 	u8 sha256[SHA256_DIGEST_SIZE];
64 }; /* 189 bytes => 252 bytes base64url-encoded, which is <= NAME_MAX (255) */
65 
66 /*
67  * Decoded size of max-size no-key name, i.e. a name that was abbreviated using
68  * the strong hash and thus includes the 'sha256' field.  This isn't simply
69  * sizeof(struct fscrypt_nokey_name), as the padding at the end isn't included.
70  */
71 #define FSCRYPT_NOKEY_NAME_MAX	offsetofend(struct fscrypt_nokey_name, sha256)
72 
73 /* Encoded size of max-size no-key name */
74 #define FSCRYPT_NOKEY_NAME_MAX_ENCODED \
75 		BASE64_CHARS(FSCRYPT_NOKEY_NAME_MAX)
76 
fscrypt_is_dot_dotdot(const struct qstr * str)77 static inline bool fscrypt_is_dot_dotdot(const struct qstr *str)
78 {
79 	return is_dot_dotdot(str->name, str->len);
80 }
81 
82 /**
83  * fscrypt_fname_encrypt() - encrypt a filename
84  * @inode: inode of the parent directory (for regular filenames)
85  *	   or of the symlink (for symlink targets). Key must already be
86  *	   set up.
87  * @iname: the filename to encrypt
88  * @out: (output) the encrypted filename
89  * @olen: size of the encrypted filename.  It must be at least @iname->len.
90  *	  Any extra space is filled with NUL padding before encryption.
91  *
92  * Return: 0 on success, -errno on failure
93  */
fscrypt_fname_encrypt(const struct inode * inode,const struct qstr * iname,u8 * out,unsigned int olen)94 int fscrypt_fname_encrypt(const struct inode *inode, const struct qstr *iname,
95 			  u8 *out, unsigned int olen)
96 {
97 	const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
98 	struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;
99 	SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);
100 	union fscrypt_iv iv;
101 	struct scatterlist sg;
102 	int err;
103 
104 	/*
105 	 * Copy the filename to the output buffer for encrypting in-place and
106 	 * pad it with the needed number of NUL bytes.
107 	 */
108 	if (WARN_ON_ONCE(olen < iname->len))
109 		return -ENOBUFS;
110 	memcpy(out, iname->name, iname->len);
111 	memset(out + iname->len, 0, olen - iname->len);
112 
113 	fscrypt_generate_iv(&iv, 0, ci);
114 
115 	skcipher_request_set_callback(
116 		req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
117 		NULL, NULL);
118 	sg_init_one(&sg, out, olen);
119 	skcipher_request_set_crypt(req, &sg, &sg, olen, &iv);
120 	err = crypto_skcipher_encrypt(req);
121 	if (err)
122 		fscrypt_err(inode, "Filename encryption failed: %d", err);
123 	return err;
124 }
125 EXPORT_SYMBOL_GPL(fscrypt_fname_encrypt);
126 
127 /**
128  * fname_decrypt() - decrypt a filename
129  * @inode: inode of the parent directory (for regular filenames)
130  *	   or of the symlink (for symlink targets)
131  * @iname: the encrypted filename to decrypt
132  * @oname: (output) the decrypted filename.  The caller must have allocated
133  *	   enough space for this, e.g. using fscrypt_fname_alloc_buffer().
134  *
135  * Return: 0 on success, -errno on failure
136  */
fname_decrypt(const struct inode * inode,const struct fscrypt_str * iname,struct fscrypt_str * oname)137 static int fname_decrypt(const struct inode *inode,
138 			 const struct fscrypt_str *iname,
139 			 struct fscrypt_str *oname)
140 {
141 	const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
142 	struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;
143 	SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);
144 	union fscrypt_iv iv;
145 	struct scatterlist src_sg, dst_sg;
146 	int err;
147 
148 	fscrypt_generate_iv(&iv, 0, ci);
149 
150 	skcipher_request_set_callback(
151 		req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
152 		NULL, NULL);
153 	sg_init_one(&src_sg, iname->name, iname->len);
154 	sg_init_one(&dst_sg, oname->name, oname->len);
155 	skcipher_request_set_crypt(req, &src_sg, &dst_sg, iname->len, &iv);
156 	err = crypto_skcipher_decrypt(req);
157 	if (err) {
158 		fscrypt_err(inode, "Filename decryption failed: %d", err);
159 		return err;
160 	}
161 
162 	oname->len = strnlen(oname->name, iname->len);
163 	return 0;
164 }
165 
__fscrypt_fname_encrypted_size(const union fscrypt_policy * policy,u32 orig_len,u32 max_len,u32 * encrypted_len_ret)166 bool __fscrypt_fname_encrypted_size(const union fscrypt_policy *policy,
167 				    u32 orig_len, u32 max_len,
168 				    u32 *encrypted_len_ret)
169 {
170 	int padding = 4 << (fscrypt_policy_flags(policy) &
171 			    FSCRYPT_POLICY_FLAGS_PAD_MASK);
172 	u32 encrypted_len;
173 
174 	if (orig_len > max_len)
175 		return false;
176 	encrypted_len = max_t(u32, orig_len, FSCRYPT_FNAME_MIN_MSG_LEN);
177 	encrypted_len = round_up(encrypted_len, padding);
178 	*encrypted_len_ret = min(encrypted_len, max_len);
179 	return true;
180 }
181 
182 /**
183  * fscrypt_fname_encrypted_size() - calculate length of encrypted filename
184  * @inode:		parent inode of dentry name being encrypted. Key must
185  *			already be set up.
186  * @orig_len:		length of the original filename
187  * @max_len:		maximum length to return
188  * @encrypted_len_ret:	where calculated length should be returned (on success)
189  *
190  * Filenames that are shorter than the maximum length may have their lengths
191  * increased slightly by encryption, due to padding that is applied.
192  *
193  * Return: false if the orig_len is greater than max_len. Otherwise, true and
194  *	   fill out encrypted_len_ret with the length (up to max_len).
195  */
fscrypt_fname_encrypted_size(const struct inode * inode,u32 orig_len,u32 max_len,u32 * encrypted_len_ret)196 bool fscrypt_fname_encrypted_size(const struct inode *inode, u32 orig_len,
197 				  u32 max_len, u32 *encrypted_len_ret)
198 {
199 	const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
200 
201 	return __fscrypt_fname_encrypted_size(&ci->ci_policy, orig_len, max_len,
202 					      encrypted_len_ret);
203 }
204 EXPORT_SYMBOL_GPL(fscrypt_fname_encrypted_size);
205 
206 /**
207  * fscrypt_fname_alloc_buffer() - allocate a buffer for presented filenames
208  * @max_encrypted_len: maximum length of encrypted filenames the buffer will be
209  *		       used to present
210  * @crypto_str: (output) buffer to allocate
211  *
212  * Allocate a buffer that is large enough to hold any decrypted or encoded
213  * filename (null-terminated), for the given maximum encrypted filename length.
214  *
215  * Return: 0 on success, -errno on failure
216  */
fscrypt_fname_alloc_buffer(u32 max_encrypted_len,struct fscrypt_str * crypto_str)217 int fscrypt_fname_alloc_buffer(u32 max_encrypted_len,
218 			       struct fscrypt_str *crypto_str)
219 {
220 	u32 max_presented_len = max_t(u32, FSCRYPT_NOKEY_NAME_MAX_ENCODED,
221 				      max_encrypted_len);
222 
223 	crypto_str->name = kmalloc(max_presented_len + 1, GFP_NOFS);
224 	if (!crypto_str->name)
225 		return -ENOMEM;
226 	crypto_str->len = max_presented_len;
227 	return 0;
228 }
229 EXPORT_SYMBOL(fscrypt_fname_alloc_buffer);
230 
231 /**
232  * fscrypt_fname_free_buffer() - free a buffer for presented filenames
233  * @crypto_str: the buffer to free
234  *
235  * Free a buffer that was allocated by fscrypt_fname_alloc_buffer().
236  */
fscrypt_fname_free_buffer(struct fscrypt_str * crypto_str)237 void fscrypt_fname_free_buffer(struct fscrypt_str *crypto_str)
238 {
239 	if (!crypto_str)
240 		return;
241 	kfree(crypto_str->name);
242 	crypto_str->name = NULL;
243 }
244 EXPORT_SYMBOL(fscrypt_fname_free_buffer);
245 
246 /**
247  * fscrypt_fname_disk_to_usr() - convert an encrypted filename to
248  *				 user-presentable form
249  * @inode: inode of the parent directory (for regular filenames)
250  *	   or of the symlink (for symlink targets)
251  * @hash: first part of the name's dirhash, if applicable.  This only needs to
252  *	  be provided if the filename is located in an indexed directory whose
253  *	  encryption key may be unavailable.  Not needed for symlink targets.
254  * @minor_hash: second part of the name's dirhash, if applicable
255  * @iname: encrypted filename to convert.  May also be "." or "..", which
256  *	   aren't actually encrypted.
257  * @oname: output buffer for the user-presentable filename.  The caller must
258  *	   have allocated enough space for this, e.g. using
259  *	   fscrypt_fname_alloc_buffer().
260  *
261  * If the key is available, we'll decrypt the disk name.  Otherwise, we'll
262  * encode it for presentation in fscrypt_nokey_name format.
263  * See struct fscrypt_nokey_name for details.
264  *
265  * Return: 0 on success, -errno on failure
266  */
fscrypt_fname_disk_to_usr(const struct inode * inode,u32 hash,u32 minor_hash,const struct fscrypt_str * iname,struct fscrypt_str * oname)267 int fscrypt_fname_disk_to_usr(const struct inode *inode,
268 			      u32 hash, u32 minor_hash,
269 			      const struct fscrypt_str *iname,
270 			      struct fscrypt_str *oname)
271 {
272 	const struct qstr qname = FSTR_TO_QSTR(iname);
273 	struct fscrypt_nokey_name nokey_name;
274 	u32 size; /* size of the unencoded no-key name */
275 
276 	if (fscrypt_is_dot_dotdot(&qname)) {
277 		oname->name[0] = '.';
278 		oname->name[iname->len - 1] = '.';
279 		oname->len = iname->len;
280 		return 0;
281 	}
282 
283 	if (iname->len < FSCRYPT_FNAME_MIN_MSG_LEN)
284 		return -EUCLEAN;
285 
286 	if (fscrypt_has_encryption_key(inode))
287 		return fname_decrypt(inode, iname, oname);
288 
289 	/*
290 	 * Sanity check that struct fscrypt_nokey_name doesn't have padding
291 	 * between fields and that its encoded size never exceeds NAME_MAX.
292 	 */
293 	BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, dirhash) !=
294 		     offsetof(struct fscrypt_nokey_name, bytes));
295 	BUILD_BUG_ON(offsetofend(struct fscrypt_nokey_name, bytes) !=
296 		     offsetof(struct fscrypt_nokey_name, sha256));
297 	BUILD_BUG_ON(FSCRYPT_NOKEY_NAME_MAX_ENCODED > NAME_MAX);
298 
299 	nokey_name.dirhash[0] = hash;
300 	nokey_name.dirhash[1] = minor_hash;
301 
302 	if (iname->len <= sizeof(nokey_name.bytes)) {
303 		memcpy(nokey_name.bytes, iname->name, iname->len);
304 		size = offsetof(struct fscrypt_nokey_name, bytes[iname->len]);
305 	} else {
306 		memcpy(nokey_name.bytes, iname->name, sizeof(nokey_name.bytes));
307 		/* Compute strong hash of remaining part of name. */
308 		sha256(&iname->name[sizeof(nokey_name.bytes)],
309 		       iname->len - sizeof(nokey_name.bytes),
310 		       nokey_name.sha256);
311 		size = FSCRYPT_NOKEY_NAME_MAX;
312 	}
313 	oname->len = base64_encode((const u8 *)&nokey_name, size,
314 				   oname->name, false, BASE64_URLSAFE);
315 	return 0;
316 }
317 EXPORT_SYMBOL(fscrypt_fname_disk_to_usr);
318 
319 /**
320  * fscrypt_setup_filename() - prepare to search a possibly encrypted directory
321  * @dir: the directory that will be searched
322  * @iname: the user-provided filename being searched for
323  * @lookup: 1 if we're allowed to proceed without the key because it's
324  *	->lookup() or we're finding the dir_entry for deletion; 0 if we cannot
325  *	proceed without the key because we're going to create the dir_entry.
326  * @fname: the filename information to be filled in
327  *
328  * Given a user-provided filename @iname, this function sets @fname->disk_name
329  * to the name that would be stored in the on-disk directory entry, if possible.
330  * If the directory is unencrypted this is simply @iname.  Else, if we have the
331  * directory's encryption key, then @iname is the plaintext, so we encrypt it to
332  * get the disk_name.
333  *
334  * Else, for keyless @lookup operations, @iname should be a no-key name, so we
335  * decode it to get the struct fscrypt_nokey_name.  Non-@lookup operations will
336  * be impossible in this case, so we fail them with ENOKEY.
337  *
338  * If successful, fscrypt_free_filename() must be called later to clean up.
339  *
340  * Return: 0 on success, -errno on failure
341  */
fscrypt_setup_filename(struct inode * dir,const struct qstr * iname,int lookup,struct fscrypt_name * fname)342 int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,
343 			      int lookup, struct fscrypt_name *fname)
344 {
345 	struct fscrypt_nokey_name *nokey_name;
346 	int ret;
347 
348 	memset(fname, 0, sizeof(struct fscrypt_name));
349 	fname->usr_fname = iname;
350 
351 	if (!IS_ENCRYPTED(dir) || fscrypt_is_dot_dotdot(iname)) {
352 		fname->disk_name.name = (unsigned char *)iname->name;
353 		fname->disk_name.len = iname->len;
354 		return 0;
355 	}
356 	ret = fscrypt_get_encryption_info(dir, lookup);
357 	if (ret)
358 		return ret;
359 
360 	if (fscrypt_has_encryption_key(dir)) {
361 		if (!fscrypt_fname_encrypted_size(dir, iname->len, NAME_MAX,
362 						  &fname->crypto_buf.len))
363 			return -ENAMETOOLONG;
364 		fname->crypto_buf.name = kmalloc(fname->crypto_buf.len,
365 						 GFP_NOFS);
366 		if (!fname->crypto_buf.name)
367 			return -ENOMEM;
368 
369 		ret = fscrypt_fname_encrypt(dir, iname, fname->crypto_buf.name,
370 					    fname->crypto_buf.len);
371 		if (ret)
372 			goto errout;
373 		fname->disk_name.name = fname->crypto_buf.name;
374 		fname->disk_name.len = fname->crypto_buf.len;
375 		return 0;
376 	}
377 	if (!lookup)
378 		return -ENOKEY;
379 	fname->is_nokey_name = true;
380 
381 	/*
382 	 * We don't have the key and we are doing a lookup; decode the
383 	 * user-supplied name
384 	 */
385 
386 	if (iname->len > FSCRYPT_NOKEY_NAME_MAX_ENCODED)
387 		return -ENOENT;
388 
389 	fname->crypto_buf.name = kmalloc(FSCRYPT_NOKEY_NAME_MAX, GFP_KERNEL);
390 	if (fname->crypto_buf.name == NULL)
391 		return -ENOMEM;
392 
393 	ret = base64_decode(iname->name, iname->len,
394 			    fname->crypto_buf.name, false, BASE64_URLSAFE);
395 	if (ret < (int)offsetof(struct fscrypt_nokey_name, bytes[1]) ||
396 	    (ret > offsetof(struct fscrypt_nokey_name, sha256) &&
397 	     ret != FSCRYPT_NOKEY_NAME_MAX)) {
398 		ret = -ENOENT;
399 		goto errout;
400 	}
401 	fname->crypto_buf.len = ret;
402 
403 	nokey_name = (void *)fname->crypto_buf.name;
404 	fname->hash = nokey_name->dirhash[0];
405 	fname->minor_hash = nokey_name->dirhash[1];
406 	if (ret != FSCRYPT_NOKEY_NAME_MAX) {
407 		/* The full ciphertext filename is available. */
408 		fname->disk_name.name = nokey_name->bytes;
409 		fname->disk_name.len =
410 			ret - offsetof(struct fscrypt_nokey_name, bytes);
411 	}
412 	return 0;
413 
414 errout:
415 	kfree(fname->crypto_buf.name);
416 	return ret;
417 }
418 EXPORT_SYMBOL(fscrypt_setup_filename);
419 
420 /**
421  * fscrypt_match_name() - test whether the given name matches a directory entry
422  * @fname: the name being searched for
423  * @de_name: the name from the directory entry
424  * @de_name_len: the length of @de_name in bytes
425  *
426  * Normally @fname->disk_name will be set, and in that case we simply compare
427  * that to the name stored in the directory entry.  The only exception is that
428  * if we don't have the key for an encrypted directory and the name we're
429  * looking for is very long, then we won't have the full disk_name and instead
430  * we'll need to match against a fscrypt_nokey_name that includes a strong hash.
431  *
432  * Return: %true if the name matches, otherwise %false.
433  */
fscrypt_match_name(const struct fscrypt_name * fname,const u8 * de_name,u32 de_name_len)434 bool fscrypt_match_name(const struct fscrypt_name *fname,
435 			const u8 *de_name, u32 de_name_len)
436 {
437 	const struct fscrypt_nokey_name *nokey_name =
438 		(const void *)fname->crypto_buf.name;
439 	u8 digest[SHA256_DIGEST_SIZE];
440 
441 	if (likely(fname->disk_name.name)) {
442 		if (de_name_len != fname->disk_name.len)
443 			return false;
444 		return !memcmp(de_name, fname->disk_name.name, de_name_len);
445 	}
446 	if (de_name_len <= sizeof(nokey_name->bytes))
447 		return false;
448 	if (memcmp(de_name, nokey_name->bytes, sizeof(nokey_name->bytes)))
449 		return false;
450 	sha256(&de_name[sizeof(nokey_name->bytes)],
451 	       de_name_len - sizeof(nokey_name->bytes), digest);
452 	return !memcmp(digest, nokey_name->sha256, sizeof(digest));
453 }
454 EXPORT_SYMBOL_GPL(fscrypt_match_name);
455 
456 /**
457  * fscrypt_fname_siphash() - calculate the SipHash of a filename
458  * @dir: the parent directory
459  * @name: the filename to calculate the SipHash of
460  *
461  * Given a plaintext filename @name and a directory @dir which uses SipHash as
462  * its dirhash method and has had its fscrypt key set up, this function
463  * calculates the SipHash of that name using the directory's secret dirhash key.
464  *
465  * Return: the SipHash of @name using the hash key of @dir
466  */
fscrypt_fname_siphash(const struct inode * dir,const struct qstr * name)467 u64 fscrypt_fname_siphash(const struct inode *dir, const struct qstr *name)
468 {
469 	const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(dir);
470 
471 	WARN_ON_ONCE(!ci->ci_dirhash_key_initialized);
472 
473 	return siphash(name->name, name->len, &ci->ci_dirhash_key);
474 }
475 EXPORT_SYMBOL_GPL(fscrypt_fname_siphash);
476 
477 /*
478  * Validate dentries in encrypted directories to make sure we aren't potentially
479  * caching stale dentries after a key has been added.
480  */
fscrypt_d_revalidate(struct inode * dir,const struct qstr * name,struct dentry * dentry,unsigned int flags)481 int fscrypt_d_revalidate(struct inode *dir, const struct qstr *name,
482 			 struct dentry *dentry, unsigned int flags)
483 {
484 	int err;
485 
486 	/*
487 	 * Plaintext names are always valid, since fscrypt doesn't support
488 	 * reverting to no-key names without evicting the directory's inode
489 	 * -- which implies eviction of the dentries in the directory.
490 	 */
491 	if (!(dentry->d_flags & DCACHE_NOKEY_NAME))
492 		return 1;
493 
494 	/*
495 	 * No-key name; valid if the directory's key is still unavailable.
496 	 *
497 	 * Note in RCU mode we have to bail if we get here -
498 	 * fscrypt_get_encryption_info() may block.
499 	 */
500 
501 	if (flags & LOOKUP_RCU)
502 		return -ECHILD;
503 
504 	/*
505 	 * Pass allow_unsupported=true, so that files with an unsupported
506 	 * encryption policy can be deleted.
507 	 */
508 	err = fscrypt_get_encryption_info(dir, true);
509 	if (err < 0)
510 		return err;
511 
512 	return !fscrypt_has_encryption_key(dir);
513 }
514 EXPORT_SYMBOL_GPL(fscrypt_d_revalidate);
515