GNU Linux-libre 4.14.254-gnu1
[releases.git] / fs / crypto / fname.c
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         digested_name.hash = hash;
308         digested_name.minor_hash = minor_hash;
309         memcpy(digested_name.digest,
310                FSCRYPT_FNAME_DIGEST(iname->name, iname->len),
311                FSCRYPT_FNAME_DIGEST_SIZE);
312         oname->name[0] = '_';
313         oname->len = 1 + digest_encode((const char *)&digested_name,
314                                        sizeof(digested_name), oname->name + 1);
315         return 0;
316 }
317 EXPORT_SYMBOL(fscrypt_fname_disk_to_usr);
318
319 /**
320  * fscrypt_fname_usr_to_disk() - converts a filename from user space to disk
321  * space
322  *
323  * The caller must have allocated sufficient memory for the @oname string.
324  *
325  * Return: 0 on success, -errno on failure
326  */
327 int fscrypt_fname_usr_to_disk(struct inode *inode,
328                         const struct qstr *iname,
329                         struct fscrypt_str *oname)
330 {
331         if (fscrypt_is_dot_dotdot(iname)) {
332                 oname->name[0] = '.';
333                 oname->name[iname->len - 1] = '.';
334                 oname->len = iname->len;
335                 return 0;
336         }
337         if (inode->i_crypt_info)
338                 return fname_encrypt(inode, iname, oname);
339         /*
340          * Without a proper key, a user is not allowed to modify the filenames
341          * in a directory. Consequently, a user space name cannot be mapped to
342          * a disk-space name
343          */
344         return -ENOKEY;
345 }
346 EXPORT_SYMBOL(fscrypt_fname_usr_to_disk);
347
348 /**
349  * fscrypt_setup_filename() - prepare to search a possibly encrypted directory
350  * @dir: the directory that will be searched
351  * @iname: the user-provided filename being searched for
352  * @lookup: 1 if we're allowed to proceed without the key because it's
353  *      ->lookup() or we're finding the dir_entry for deletion; 0 if we cannot
354  *      proceed without the key because we're going to create the dir_entry.
355  * @fname: the filename information to be filled in
356  *
357  * Given a user-provided filename @iname, this function sets @fname->disk_name
358  * to the name that would be stored in the on-disk directory entry, if possible.
359  * If the directory is unencrypted this is simply @iname.  Else, if we have the
360  * directory's encryption key, then @iname is the plaintext, so we encrypt it to
361  * get the disk_name.
362  *
363  * Else, for keyless @lookup operations, @iname is the presented ciphertext, so
364  * we decode it to get either the ciphertext disk_name (for short names) or the
365  * fscrypt_digested_name (for long names).  Non-@lookup operations will be
366  * impossible in this case, so we fail them with ENOKEY.
367  *
368  * If successful, fscrypt_free_filename() must be called later to clean up.
369  *
370  * Return: 0 on success, -errno on failure
371  */
372 int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,
373                               int lookup, struct fscrypt_name *fname)
374 {
375         int ret;
376         int digested;
377
378         memset(fname, 0, sizeof(struct fscrypt_name));
379         fname->usr_fname = iname;
380
381         if (!dir->i_sb->s_cop->is_encrypted(dir) ||
382                                 fscrypt_is_dot_dotdot(iname)) {
383                 fname->disk_name.name = (unsigned char *)iname->name;
384                 fname->disk_name.len = iname->len;
385                 return 0;
386         }
387         ret = fscrypt_get_encryption_info(dir);
388         if (ret && ret != -EOPNOTSUPP)
389                 return ret;
390
391         if (dir->i_crypt_info) {
392                 ret = fscrypt_fname_alloc_buffer(dir, iname->len,
393                                                         &fname->crypto_buf);
394                 if (ret)
395                         return ret;
396                 ret = fname_encrypt(dir, iname, &fname->crypto_buf);
397                 if (ret)
398                         goto errout;
399                 fname->disk_name.name = fname->crypto_buf.name;
400                 fname->disk_name.len = fname->crypto_buf.len;
401                 return 0;
402         }
403         if (!lookup)
404                 return -ENOKEY;
405
406         /*
407          * We don't have the key and we are doing a lookup; decode the
408          * user-supplied name
409          */
410         if (iname->name[0] == '_') {
411                 if (iname->len !=
412                     1 + BASE64_CHARS(sizeof(struct fscrypt_digested_name)))
413                         return -ENOENT;
414                 digested = 1;
415         } else {
416                 if (iname->len >
417                     BASE64_CHARS(FSCRYPT_FNAME_MAX_UNDIGESTED_SIZE))
418                         return -ENOENT;
419                 digested = 0;
420         }
421
422         fname->crypto_buf.name =
423                 kmalloc(max_t(size_t, FSCRYPT_FNAME_MAX_UNDIGESTED_SIZE,
424                               sizeof(struct fscrypt_digested_name)),
425                         GFP_KERNEL);
426         if (fname->crypto_buf.name == NULL)
427                 return -ENOMEM;
428
429         ret = digest_decode(iname->name + digested, iname->len - digested,
430                                 fname->crypto_buf.name);
431         if (ret < 0) {
432                 ret = -ENOENT;
433                 goto errout;
434         }
435         fname->crypto_buf.len = ret;
436         if (digested) {
437                 const struct fscrypt_digested_name *n =
438                         (const void *)fname->crypto_buf.name;
439                 fname->hash = n->hash;
440                 fname->minor_hash = n->minor_hash;
441         } else {
442                 fname->disk_name.name = fname->crypto_buf.name;
443                 fname->disk_name.len = fname->crypto_buf.len;
444         }
445         return 0;
446
447 errout:
448         fscrypt_fname_free_buffer(&fname->crypto_buf);
449         return ret;
450 }
451 EXPORT_SYMBOL(fscrypt_setup_filename);