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