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