xref: /linux/fs/crypto/fname.c (revision b24413180f5600bcb3bb70fbed5cf186b60864bd)
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 <linux/scatterlist.h>
15 #include <linux/ratelimit.h>
16 #include "fscrypt_private.h"
17 
18 /**
19  * fname_crypt_complete() - completion callback for filename crypto
20  * @req: The asynchronous cipher request context
21  * @res: The result of the cipher operation
22  */
23 static void fname_crypt_complete(struct crypto_async_request *req, int res)
24 {
25 	struct fscrypt_completion_result *ecr = req->data;
26 
27 	if (res == -EINPROGRESS)
28 		return;
29 	ecr->res = res;
30 	complete(&ecr->completion);
31 }
32 
33 /**
34  * fname_encrypt() - encrypt a filename
35  *
36  * The caller must have allocated sufficient memory for the @oname string.
37  *
38  * Return: 0 on success, -errno on failure
39  */
40 static int fname_encrypt(struct inode *inode,
41 			const struct qstr *iname, struct fscrypt_str *oname)
42 {
43 	struct skcipher_request *req = NULL;
44 	DECLARE_FS_COMPLETION_RESULT(ecr);
45 	struct fscrypt_info *ci = inode->i_crypt_info;
46 	struct crypto_skcipher *tfm = ci->ci_ctfm;
47 	int res = 0;
48 	char iv[FS_CRYPTO_BLOCK_SIZE];
49 	struct scatterlist sg;
50 	int padding = 4 << (ci->ci_flags & FS_POLICY_FLAGS_PAD_MASK);
51 	unsigned int lim;
52 	unsigned int cryptlen;
53 
54 	lim = inode->i_sb->s_cop->max_namelen(inode);
55 	if (iname->len <= 0 || iname->len > lim)
56 		return -EIO;
57 
58 	/*
59 	 * Copy the filename to the output buffer for encrypting in-place and
60 	 * pad it with the needed number of NUL bytes.
61 	 */
62 	cryptlen = max_t(unsigned int, iname->len, FS_CRYPTO_BLOCK_SIZE);
63 	cryptlen = round_up(cryptlen, padding);
64 	cryptlen = min(cryptlen, lim);
65 	memcpy(oname->name, iname->name, iname->len);
66 	memset(oname->name + iname->len, 0, cryptlen - iname->len);
67 
68 	/* Initialize the IV */
69 	memset(iv, 0, FS_CRYPTO_BLOCK_SIZE);
70 
71 	/* Set up the encryption request */
72 	req = skcipher_request_alloc(tfm, GFP_NOFS);
73 	if (!req) {
74 		printk_ratelimited(KERN_ERR
75 			"%s: skcipher_request_alloc() failed\n", __func__);
76 		return -ENOMEM;
77 	}
78 	skcipher_request_set_callback(req,
79 			CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
80 			fname_crypt_complete, &ecr);
81 	sg_init_one(&sg, oname->name, cryptlen);
82 	skcipher_request_set_crypt(req, &sg, &sg, cryptlen, iv);
83 
84 	/* Do the encryption */
85 	res = crypto_skcipher_encrypt(req);
86 	if (res == -EINPROGRESS || res == -EBUSY) {
87 		/* Request is being completed asynchronously; wait for it */
88 		wait_for_completion(&ecr.completion);
89 		res = ecr.res;
90 	}
91 	skcipher_request_free(req);
92 	if (res < 0) {
93 		printk_ratelimited(KERN_ERR
94 				"%s: Error (error code %d)\n", __func__, res);
95 		return res;
96 	}
97 
98 	oname->len = cryptlen;
99 	return 0;
100 }
101 
102 /**
103  * fname_decrypt() - decrypt a filename
104  *
105  * The caller must have allocated sufficient memory for the @oname string.
106  *
107  * Return: 0 on success, -errno on failure
108  */
109 static int fname_decrypt(struct inode *inode,
110 				const struct fscrypt_str *iname,
111 				struct fscrypt_str *oname)
112 {
113 	struct skcipher_request *req = NULL;
114 	DECLARE_FS_COMPLETION_RESULT(ecr);
115 	struct scatterlist src_sg, dst_sg;
116 	struct fscrypt_info *ci = inode->i_crypt_info;
117 	struct crypto_skcipher *tfm = ci->ci_ctfm;
118 	int res = 0;
119 	char iv[FS_CRYPTO_BLOCK_SIZE];
120 	unsigned lim;
121 
122 	lim = inode->i_sb->s_cop->max_namelen(inode);
123 	if (iname->len <= 0 || iname->len > lim)
124 		return -EIO;
125 
126 	/* Allocate request */
127 	req = skcipher_request_alloc(tfm, GFP_NOFS);
128 	if (!req) {
129 		printk_ratelimited(KERN_ERR
130 			"%s: crypto_request_alloc() failed\n",  __func__);
131 		return -ENOMEM;
132 	}
133 	skcipher_request_set_callback(req,
134 		CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
135 		fname_crypt_complete, &ecr);
136 
137 	/* Initialize IV */
138 	memset(iv, 0, FS_CRYPTO_BLOCK_SIZE);
139 
140 	/* Create decryption request */
141 	sg_init_one(&src_sg, iname->name, iname->len);
142 	sg_init_one(&dst_sg, oname->name, oname->len);
143 	skcipher_request_set_crypt(req, &src_sg, &dst_sg, iname->len, iv);
144 	res = crypto_skcipher_decrypt(req);
145 	if (res == -EINPROGRESS || res == -EBUSY) {
146 		wait_for_completion(&ecr.completion);
147 		res = ecr.res;
148 	}
149 	skcipher_request_free(req);
150 	if (res < 0) {
151 		printk_ratelimited(KERN_ERR
152 				"%s: Error (error code %d)\n", __func__, res);
153 		return res;
154 	}
155 
156 	oname->len = strnlen(oname->name, iname->len);
157 	return 0;
158 }
159 
160 static const char *lookup_table =
161 	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
162 
163 #define BASE64_CHARS(nbytes)	DIV_ROUND_UP((nbytes) * 4, 3)
164 
165 /**
166  * digest_encode() -
167  *
168  * Encodes the input digest using characters from the set [a-zA-Z0-9_+].
169  * The encoded string is roughly 4/3 times the size of the input string.
170  */
171 static int digest_encode(const char *src, int len, char *dst)
172 {
173 	int i = 0, bits = 0, ac = 0;
174 	char *cp = dst;
175 
176 	while (i < len) {
177 		ac += (((unsigned char) src[i]) << bits);
178 		bits += 8;
179 		do {
180 			*cp++ = lookup_table[ac & 0x3f];
181 			ac >>= 6;
182 			bits -= 6;
183 		} while (bits >= 6);
184 		i++;
185 	}
186 	if (bits)
187 		*cp++ = lookup_table[ac & 0x3f];
188 	return cp - dst;
189 }
190 
191 static int digest_decode(const char *src, int len, char *dst)
192 {
193 	int i = 0, bits = 0, ac = 0;
194 	const char *p;
195 	char *cp = dst;
196 
197 	while (i < len) {
198 		p = strchr(lookup_table, src[i]);
199 		if (p == NULL || src[i] == 0)
200 			return -2;
201 		ac += (p - lookup_table) << bits;
202 		bits += 6;
203 		if (bits >= 8) {
204 			*cp++ = ac & 0xff;
205 			ac >>= 8;
206 			bits -= 8;
207 		}
208 		i++;
209 	}
210 	if (ac)
211 		return -1;
212 	return cp - dst;
213 }
214 
215 u32 fscrypt_fname_encrypted_size(const struct inode *inode, u32 ilen)
216 {
217 	int padding = 32;
218 	struct fscrypt_info *ci = inode->i_crypt_info;
219 
220 	if (ci)
221 		padding = 4 << (ci->ci_flags & FS_POLICY_FLAGS_PAD_MASK);
222 	ilen = max(ilen, (u32)FS_CRYPTO_BLOCK_SIZE);
223 	return round_up(ilen, padding);
224 }
225 EXPORT_SYMBOL(fscrypt_fname_encrypted_size);
226 
227 /**
228  * fscrypt_fname_crypto_alloc_obuff() -
229  *
230  * Allocates an output buffer that is sufficient for the crypto operation
231  * specified by the context and the direction.
232  */
233 int fscrypt_fname_alloc_buffer(const struct inode *inode,
234 				u32 ilen, struct fscrypt_str *crypto_str)
235 {
236 	u32 olen = fscrypt_fname_encrypted_size(inode, ilen);
237 	const u32 max_encoded_len =
238 		max_t(u32, BASE64_CHARS(FSCRYPT_FNAME_MAX_UNDIGESTED_SIZE),
239 		      1 + BASE64_CHARS(sizeof(struct fscrypt_digested_name)));
240 
241 	crypto_str->len = olen;
242 	olen = max(olen, max_encoded_len);
243 
244 	/*
245 	 * Allocated buffer can hold one more character to null-terminate the
246 	 * string
247 	 */
248 	crypto_str->name = kmalloc(olen + 1, GFP_NOFS);
249 	if (!(crypto_str->name))
250 		return -ENOMEM;
251 	return 0;
252 }
253 EXPORT_SYMBOL(fscrypt_fname_alloc_buffer);
254 
255 /**
256  * fscrypt_fname_crypto_free_buffer() -
257  *
258  * Frees the buffer allocated for crypto operation.
259  */
260 void fscrypt_fname_free_buffer(struct fscrypt_str *crypto_str)
261 {
262 	if (!crypto_str)
263 		return;
264 	kfree(crypto_str->name);
265 	crypto_str->name = NULL;
266 }
267 EXPORT_SYMBOL(fscrypt_fname_free_buffer);
268 
269 /**
270  * fscrypt_fname_disk_to_usr() - converts a filename from disk space to user
271  * space
272  *
273  * The caller must have allocated sufficient memory for the @oname string.
274  *
275  * If the key is available, we'll decrypt the disk name; otherwise, we'll encode
276  * it for presentation.  Short names are directly base64-encoded, while long
277  * names are encoded in fscrypt_digested_name format.
278  *
279  * Return: 0 on success, -errno on failure
280  */
281 int fscrypt_fname_disk_to_usr(struct inode *inode,
282 			u32 hash, u32 minor_hash,
283 			const struct fscrypt_str *iname,
284 			struct fscrypt_str *oname)
285 {
286 	const struct qstr qname = FSTR_TO_QSTR(iname);
287 	struct fscrypt_digested_name digested_name;
288 
289 	if (fscrypt_is_dot_dotdot(&qname)) {
290 		oname->name[0] = '.';
291 		oname->name[iname->len - 1] = '.';
292 		oname->len = iname->len;
293 		return 0;
294 	}
295 
296 	if (iname->len < FS_CRYPTO_BLOCK_SIZE)
297 		return -EUCLEAN;
298 
299 	if (inode->i_crypt_info)
300 		return fname_decrypt(inode, iname, oname);
301 
302 	if (iname->len <= FSCRYPT_FNAME_MAX_UNDIGESTED_SIZE) {
303 		oname->len = digest_encode(iname->name, iname->len,
304 					   oname->name);
305 		return 0;
306 	}
307 	if (hash) {
308 		digested_name.hash = hash;
309 		digested_name.minor_hash = minor_hash;
310 	} else {
311 		digested_name.hash = 0;
312 		digested_name.minor_hash = 0;
313 	}
314 	memcpy(digested_name.digest,
315 	       FSCRYPT_FNAME_DIGEST(iname->name, iname->len),
316 	       FSCRYPT_FNAME_DIGEST_SIZE);
317 	oname->name[0] = '_';
318 	oname->len = 1 + digest_encode((const char *)&digested_name,
319 				       sizeof(digested_name), oname->name + 1);
320 	return 0;
321 }
322 EXPORT_SYMBOL(fscrypt_fname_disk_to_usr);
323 
324 /**
325  * fscrypt_fname_usr_to_disk() - converts a filename from user space to disk
326  * space
327  *
328  * The caller must have allocated sufficient memory for the @oname string.
329  *
330  * Return: 0 on success, -errno on failure
331  */
332 int fscrypt_fname_usr_to_disk(struct inode *inode,
333 			const struct qstr *iname,
334 			struct fscrypt_str *oname)
335 {
336 	if (fscrypt_is_dot_dotdot(iname)) {
337 		oname->name[0] = '.';
338 		oname->name[iname->len - 1] = '.';
339 		oname->len = iname->len;
340 		return 0;
341 	}
342 	if (inode->i_crypt_info)
343 		return fname_encrypt(inode, iname, oname);
344 	/*
345 	 * Without a proper key, a user is not allowed to modify the filenames
346 	 * in a directory. Consequently, a user space name cannot be mapped to
347 	 * a disk-space name
348 	 */
349 	return -ENOKEY;
350 }
351 EXPORT_SYMBOL(fscrypt_fname_usr_to_disk);
352 
353 /**
354  * fscrypt_setup_filename() - prepare to search a possibly encrypted directory
355  * @dir: the directory that will be searched
356  * @iname: the user-provided filename being searched for
357  * @lookup: 1 if we're allowed to proceed without the key because it's
358  *	->lookup() or we're finding the dir_entry for deletion; 0 if we cannot
359  *	proceed without the key because we're going to create the dir_entry.
360  * @fname: the filename information to be filled in
361  *
362  * Given a user-provided filename @iname, this function sets @fname->disk_name
363  * to the name that would be stored in the on-disk directory entry, if possible.
364  * If the directory is unencrypted this is simply @iname.  Else, if we have the
365  * directory's encryption key, then @iname is the plaintext, so we encrypt it to
366  * get the disk_name.
367  *
368  * Else, for keyless @lookup operations, @iname is the presented ciphertext, so
369  * we decode it to get either the ciphertext disk_name (for short names) or the
370  * fscrypt_digested_name (for long names).  Non-@lookup operations will be
371  * impossible in this case, so we fail them with ENOKEY.
372  *
373  * If successful, fscrypt_free_filename() must be called later to clean up.
374  *
375  * Return: 0 on success, -errno on failure
376  */
377 int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,
378 			      int lookup, struct fscrypt_name *fname)
379 {
380 	int ret;
381 	int digested;
382 
383 	memset(fname, 0, sizeof(struct fscrypt_name));
384 	fname->usr_fname = iname;
385 
386 	if (!dir->i_sb->s_cop->is_encrypted(dir) ||
387 				fscrypt_is_dot_dotdot(iname)) {
388 		fname->disk_name.name = (unsigned char *)iname->name;
389 		fname->disk_name.len = iname->len;
390 		return 0;
391 	}
392 	ret = fscrypt_get_encryption_info(dir);
393 	if (ret && ret != -EOPNOTSUPP)
394 		return ret;
395 
396 	if (dir->i_crypt_info) {
397 		ret = fscrypt_fname_alloc_buffer(dir, iname->len,
398 							&fname->crypto_buf);
399 		if (ret)
400 			return ret;
401 		ret = fname_encrypt(dir, iname, &fname->crypto_buf);
402 		if (ret)
403 			goto errout;
404 		fname->disk_name.name = fname->crypto_buf.name;
405 		fname->disk_name.len = fname->crypto_buf.len;
406 		return 0;
407 	}
408 	if (!lookup)
409 		return -ENOKEY;
410 
411 	/*
412 	 * We don't have the key and we are doing a lookup; decode the
413 	 * user-supplied name
414 	 */
415 	if (iname->name[0] == '_') {
416 		if (iname->len !=
417 		    1 + BASE64_CHARS(sizeof(struct fscrypt_digested_name)))
418 			return -ENOENT;
419 		digested = 1;
420 	} else {
421 		if (iname->len >
422 		    BASE64_CHARS(FSCRYPT_FNAME_MAX_UNDIGESTED_SIZE))
423 			return -ENOENT;
424 		digested = 0;
425 	}
426 
427 	fname->crypto_buf.name =
428 		kmalloc(max_t(size_t, FSCRYPT_FNAME_MAX_UNDIGESTED_SIZE,
429 			      sizeof(struct fscrypt_digested_name)),
430 			GFP_KERNEL);
431 	if (fname->crypto_buf.name == NULL)
432 		return -ENOMEM;
433 
434 	ret = digest_decode(iname->name + digested, iname->len - digested,
435 				fname->crypto_buf.name);
436 	if (ret < 0) {
437 		ret = -ENOENT;
438 		goto errout;
439 	}
440 	fname->crypto_buf.len = ret;
441 	if (digested) {
442 		const struct fscrypt_digested_name *n =
443 			(const void *)fname->crypto_buf.name;
444 		fname->hash = n->hash;
445 		fname->minor_hash = n->minor_hash;
446 	} else {
447 		fname->disk_name.name = fname->crypto_buf.name;
448 		fname->disk_name.len = fname->crypto_buf.len;
449 	}
450 	return 0;
451 
452 errout:
453 	fscrypt_fname_free_buffer(&fname->crypto_buf);
454 	return ret;
455 }
456 EXPORT_SYMBOL(fscrypt_setup_filename);
457