xref: /linux/fs/ecryptfs/crypto.c (revision 2ed2e359dea752e7758d29a423033031a0b96584)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * eCryptfs: Linux filesystem encryption layer
4  *
5  * Copyright (C) 1997-2004 Erez Zadok
6  * Copyright (C) 2001-2004 Stony Brook University
7  * Copyright (C) 2004-2007 International Business Machines Corp.
8  *   Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
9  *   		Michael C. Thompson <mcthomps@us.ibm.com>
10  */
11 
12 #include <crypto/skcipher.h>
13 #include <linux/fs.h>
14 #include <linux/mount.h>
15 #include <linux/pagemap.h>
16 #include <linux/random.h>
17 #include <linux/compiler.h>
18 #include <linux/key.h>
19 #include <linux/namei.h>
20 #include <linux/file.h>
21 #include <linux/scatterlist.h>
22 #include <linux/slab.h>
23 #include <linux/string.h>
24 #include <linux/unaligned.h>
25 #include <linux/kernel.h>
26 #include <linux/xattr.h>
27 #include "ecryptfs_kernel.h"
28 
29 #define DECRYPT		0
30 #define ENCRYPT		1
31 
32 /**
33  * ecryptfs_from_hex
34  * @dst: Buffer to take the bytes from src hex; must be at least of
35  *       size (src_size / 2)
36  * @src: Buffer to be converted from a hex string representation to raw value
37  * @dst_size: size of dst buffer, or number of hex characters pairs to convert
38  */
ecryptfs_from_hex(char * dst,char * src,int dst_size)39 void ecryptfs_from_hex(char *dst, char *src, int dst_size)
40 {
41 	int x;
42 	char tmp[3] = { 0, };
43 
44 	for (x = 0; x < dst_size; x++) {
45 		tmp[0] = src[x * 2];
46 		tmp[1] = src[x * 2 + 1];
47 		dst[x] = (unsigned char)simple_strtol(tmp, NULL, 16);
48 	}
49 }
50 
ecryptfs_crypto_api_algify_cipher_name(char ** algified_name,const char * cipher_name,const char * chaining_modifier)51 static int ecryptfs_crypto_api_algify_cipher_name(char **algified_name,
52 						  const char *cipher_name,
53 						  const char *chaining_modifier)
54 {
55 	(*algified_name) = kasprintf(GFP_KERNEL, "%s(%s)", chaining_modifier,
56 				     cipher_name);
57 	if (!(*algified_name))
58 		return -ENOMEM;
59 
60 	return 0;
61 }
62 
63 /**
64  * ecryptfs_derive_iv
65  * @iv: destination for the derived iv value
66  * @crypt_stat: Pointer to crypt_stat struct for the current inode
67  * @offset: Offset of the extent whose IV we are to derive
68  *
69  * Generate the initialization vector from the given root IV and page
70  * offset.
71  */
ecryptfs_derive_iv(char * iv,struct ecryptfs_crypt_stat * crypt_stat,loff_t offset)72 void ecryptfs_derive_iv(char *iv, struct ecryptfs_crypt_stat *crypt_stat,
73 			loff_t offset)
74 {
75 	char dst[MD5_DIGEST_SIZE];
76 	char src[ECRYPTFS_MAX_IV_BYTES + 16];
77 
78 	if (unlikely(ecryptfs_verbosity > 0)) {
79 		ecryptfs_printk(KERN_DEBUG, "root iv:\n");
80 		ecryptfs_dump_hex(crypt_stat->root_iv, crypt_stat->iv_bytes);
81 	}
82 	memcpy(src, crypt_stat->root_iv, crypt_stat->iv_bytes);
83 	memset((src + crypt_stat->iv_bytes), 0, 16);
84 	snprintf((src + crypt_stat->iv_bytes), 16, "%lld", offset);
85 	if (unlikely(ecryptfs_verbosity > 0)) {
86 		ecryptfs_printk(KERN_DEBUG, "source:\n");
87 		ecryptfs_dump_hex(src, (crypt_stat->iv_bytes + 16));
88 	}
89 	md5(src, crypt_stat->iv_bytes + 16, dst);
90 	memcpy(iv, dst, crypt_stat->iv_bytes);
91 	if (unlikely(ecryptfs_verbosity > 0)) {
92 		ecryptfs_printk(KERN_DEBUG, "derived iv:\n");
93 		ecryptfs_dump_hex(iv, crypt_stat->iv_bytes);
94 	}
95 }
96 
97 /**
98  * ecryptfs_init_crypt_stat
99  * @crypt_stat: Pointer to the crypt_stat struct to initialize.
100  *
101  * Initialize the crypt_stat structure.
102  */
ecryptfs_init_crypt_stat(struct ecryptfs_crypt_stat * crypt_stat)103 void ecryptfs_init_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
104 {
105 	memset((void *)crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
106 	INIT_LIST_HEAD(&crypt_stat->keysig_list);
107 	mutex_init(&crypt_stat->keysig_list_mutex);
108 	mutex_init(&crypt_stat->cs_mutex);
109 	mutex_init(&crypt_stat->cs_tfm_mutex);
110 	crypt_stat->flags |= ECRYPTFS_STRUCT_INITIALIZED;
111 }
112 
113 /**
114  * ecryptfs_destroy_crypt_stat
115  * @crypt_stat: Pointer to the crypt_stat struct to initialize.
116  *
117  * Releases all memory associated with a crypt_stat struct.
118  */
ecryptfs_destroy_crypt_stat(struct ecryptfs_crypt_stat * crypt_stat)119 void ecryptfs_destroy_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
120 {
121 	struct ecryptfs_key_sig *key_sig, *key_sig_tmp;
122 
123 	crypto_free_skcipher(crypt_stat->tfm);
124 	list_for_each_entry_safe(key_sig, key_sig_tmp,
125 				 &crypt_stat->keysig_list, crypt_stat_list) {
126 		list_del(&key_sig->crypt_stat_list);
127 		kmem_cache_free(ecryptfs_key_sig_cache, key_sig);
128 	}
129 	memset(crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
130 }
131 
ecryptfs_destroy_mount_crypt_stat(struct ecryptfs_mount_crypt_stat * mount_crypt_stat)132 void ecryptfs_destroy_mount_crypt_stat(
133 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
134 {
135 	struct ecryptfs_global_auth_tok *auth_tok, *auth_tok_tmp;
136 
137 	if (!(mount_crypt_stat->flags & ECRYPTFS_MOUNT_CRYPT_STAT_INITIALIZED))
138 		return;
139 	mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
140 	list_for_each_entry_safe(auth_tok, auth_tok_tmp,
141 				 &mount_crypt_stat->global_auth_tok_list,
142 				 mount_crypt_stat_list) {
143 		list_del(&auth_tok->mount_crypt_stat_list);
144 		if (!(auth_tok->flags & ECRYPTFS_AUTH_TOK_INVALID))
145 			key_put(auth_tok->global_auth_tok_key);
146 		kmem_cache_free(ecryptfs_global_auth_tok_cache, auth_tok);
147 	}
148 	mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
149 	memset(mount_crypt_stat, 0, sizeof(struct ecryptfs_mount_crypt_stat));
150 }
151 
152 /**
153  * virt_to_scatterlist
154  * @addr: Virtual address
155  * @size: Size of data; should be an even multiple of the block size
156  * @sg: Pointer to scatterlist array; set to NULL to obtain only
157  *      the number of scatterlist structs required in array
158  * @sg_size: Max array size
159  *
160  * Fills in a scatterlist array with page references for a passed
161  * virtual address.
162  *
163  * Returns the number of scatterlist structs in array used
164  */
virt_to_scatterlist(const void * addr,int size,struct scatterlist * sg,int sg_size)165 int virt_to_scatterlist(const void *addr, int size, struct scatterlist *sg,
166 			int sg_size)
167 {
168 	int i = 0;
169 	struct page *pg;
170 	int offset;
171 	int remainder_of_page;
172 
173 	sg_init_table(sg, sg_size);
174 
175 	while (size > 0 && i < sg_size) {
176 		pg = virt_to_page(addr);
177 		offset = offset_in_page(addr);
178 		sg_set_page(&sg[i], pg, 0, offset);
179 		remainder_of_page = PAGE_SIZE - offset;
180 		if (size >= remainder_of_page) {
181 			sg[i].length = remainder_of_page;
182 			addr += remainder_of_page;
183 			size -= remainder_of_page;
184 		} else {
185 			sg[i].length = size;
186 			addr += size;
187 			size = 0;
188 		}
189 		i++;
190 	}
191 	if (size > 0)
192 		return -ENOMEM;
193 	return i;
194 }
195 
196 /**
197  * crypt_scatterlist
198  * @crypt_stat: Pointer to the crypt_stat struct to initialize.
199  * @dst_sg: Destination of the data after performing the crypto operation
200  * @src_sg: Data to be encrypted or decrypted
201  * @size: Length of data
202  * @iv: IV to use
203  * @op: ENCRYPT or DECRYPT to indicate the desired operation
204  *
205  * Returns the number of bytes encrypted or decrypted; negative value on error
206  */
crypt_scatterlist(struct ecryptfs_crypt_stat * crypt_stat,struct scatterlist * dst_sg,struct scatterlist * src_sg,int size,unsigned char * iv,int op)207 static int crypt_scatterlist(struct ecryptfs_crypt_stat *crypt_stat,
208 			     struct scatterlist *dst_sg,
209 			     struct scatterlist *src_sg, int size,
210 			     unsigned char *iv, int op)
211 {
212 	struct skcipher_request *req = NULL;
213 	DECLARE_CRYPTO_WAIT(ecr);
214 	int rc = 0;
215 
216 	if (unlikely(ecryptfs_verbosity > 0)) {
217 		ecryptfs_printk(KERN_DEBUG, "Key size [%zd]; key:\n",
218 				crypt_stat->key_size);
219 		ecryptfs_dump_hex(crypt_stat->key,
220 				  crypt_stat->key_size);
221 	}
222 
223 	mutex_lock(&crypt_stat->cs_tfm_mutex);
224 	req = skcipher_request_alloc(crypt_stat->tfm, GFP_NOFS);
225 	if (!req) {
226 		mutex_unlock(&crypt_stat->cs_tfm_mutex);
227 		rc = -ENOMEM;
228 		goto out;
229 	}
230 
231 	skcipher_request_set_callback(req,
232 			CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
233 			crypto_req_done, &ecr);
234 	/* Consider doing this once, when the file is opened */
235 	if (!(crypt_stat->flags & ECRYPTFS_KEY_SET)) {
236 		rc = crypto_skcipher_setkey(crypt_stat->tfm, crypt_stat->key,
237 					    crypt_stat->key_size);
238 		if (rc) {
239 			ecryptfs_printk(KERN_ERR,
240 					"Error setting key; rc = [%d]\n",
241 					rc);
242 			mutex_unlock(&crypt_stat->cs_tfm_mutex);
243 			rc = -EINVAL;
244 			goto out;
245 		}
246 		crypt_stat->flags |= ECRYPTFS_KEY_SET;
247 	}
248 	mutex_unlock(&crypt_stat->cs_tfm_mutex);
249 	skcipher_request_set_crypt(req, src_sg, dst_sg, size, iv);
250 	rc = op == ENCRYPT ? crypto_skcipher_encrypt(req) :
251 			     crypto_skcipher_decrypt(req);
252 	rc = crypto_wait_req(rc, &ecr);
253 out:
254 	skcipher_request_free(req);
255 	return rc;
256 }
257 
258 /*
259  * lower_offset_for_page
260  *
261  * Convert an eCryptfs page index into a lower byte offset
262  */
lower_offset_for_page(struct ecryptfs_crypt_stat * crypt_stat,struct folio * folio)263 static loff_t lower_offset_for_page(struct ecryptfs_crypt_stat *crypt_stat,
264 				    struct folio *folio)
265 {
266 	return ecryptfs_lower_header_size(crypt_stat) +
267 	       (loff_t)folio->index * PAGE_SIZE;
268 }
269 
270 /**
271  * crypt_extent
272  * @crypt_stat: crypt_stat containing cryptographic context for the
273  *              encryption operation
274  * @dst_page: The page to write the result into
275  * @src_page: The page to read from
276  * @page_index: The offset in the file (in units of PAGE_SIZE)
277  * @extent_offset: Page extent offset for use in generating IV
278  * @op: ENCRYPT or DECRYPT to indicate the desired operation
279  *
280  * Encrypts or decrypts one extent of data.
281  *
282  * Return zero on success; non-zero otherwise
283  */
crypt_extent(struct ecryptfs_crypt_stat * crypt_stat,struct page * dst_page,struct page * src_page,pgoff_t page_index,unsigned long extent_offset,int op)284 static int crypt_extent(struct ecryptfs_crypt_stat *crypt_stat,
285 			struct page *dst_page,
286 			struct page *src_page,
287 			pgoff_t page_index,
288 			unsigned long extent_offset, int op)
289 {
290 	loff_t extent_base;
291 	char extent_iv[ECRYPTFS_MAX_IV_BYTES];
292 	struct scatterlist src_sg, dst_sg;
293 	size_t extent_size = crypt_stat->extent_size;
294 	int rc;
295 
296 	extent_base = (((loff_t)page_index) * (PAGE_SIZE / extent_size));
297 	ecryptfs_derive_iv(extent_iv, crypt_stat, extent_base + extent_offset);
298 
299 	sg_init_table(&src_sg, 1);
300 	sg_init_table(&dst_sg, 1);
301 
302 	sg_set_page(&src_sg, src_page, extent_size,
303 		    extent_offset * extent_size);
304 	sg_set_page(&dst_sg, dst_page, extent_size,
305 		    extent_offset * extent_size);
306 
307 	rc = crypt_scatterlist(crypt_stat, &dst_sg, &src_sg, extent_size,
308 			       extent_iv, op);
309 	if (rc < 0) {
310 		printk(KERN_ERR "%s: Error attempting to crypt page with "
311 		       "page_index = [%ld], extent_offset = [%ld]; "
312 		       "rc = [%d]\n", __func__, page_index, extent_offset, rc);
313 		goto out;
314 	}
315 	rc = 0;
316 out:
317 	return rc;
318 }
319 
320 /**
321  * ecryptfs_encrypt_page
322  * @folio: Folio mapped from the eCryptfs inode for the file; contains
323  *        decrypted content that needs to be encrypted (to a temporary
324  *        page; not in place) and written out to the lower file
325  *
326  * Encrypt an eCryptfs page. This is done on a per-extent basis. Note
327  * that eCryptfs pages may straddle the lower pages -- for instance,
328  * if the file was created on a machine with an 8K page size
329  * (resulting in an 8K header), and then the file is copied onto a
330  * host with a 32K page size, then when reading page 0 of the eCryptfs
331  * file, 24K of page 0 of the lower file will be read and decrypted,
332  * and then 8K of page 1 of the lower file will be read and decrypted.
333  *
334  * Returns zero on success; negative on error
335  */
ecryptfs_encrypt_page(struct folio * folio)336 int ecryptfs_encrypt_page(struct folio *folio)
337 {
338 	struct inode *ecryptfs_inode;
339 	struct ecryptfs_crypt_stat *crypt_stat;
340 	char *enc_extent_virt;
341 	struct page *enc_extent_page = NULL;
342 	loff_t extent_offset;
343 	loff_t lower_offset;
344 	int rc = 0;
345 
346 	ecryptfs_inode = folio->mapping->host;
347 	crypt_stat =
348 		&(ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat);
349 	BUG_ON(!(crypt_stat->flags & ECRYPTFS_ENCRYPTED));
350 	enc_extent_page = alloc_page(GFP_USER);
351 	if (!enc_extent_page) {
352 		rc = -ENOMEM;
353 		ecryptfs_printk(KERN_ERR, "Error allocating memory for "
354 				"encrypted extent\n");
355 		goto out;
356 	}
357 
358 	for (extent_offset = 0;
359 	     extent_offset < (PAGE_SIZE / crypt_stat->extent_size);
360 	     extent_offset++) {
361 		rc = crypt_extent(crypt_stat, enc_extent_page,
362 				folio_page(folio, 0), folio->index,
363 				extent_offset, ENCRYPT);
364 		if (rc) {
365 			printk(KERN_ERR "%s: Error encrypting extent; "
366 			       "rc = [%d]\n", __func__, rc);
367 			goto out;
368 		}
369 	}
370 
371 	lower_offset = lower_offset_for_page(crypt_stat, folio);
372 	enc_extent_virt = kmap_local_page(enc_extent_page);
373 	rc = ecryptfs_write_lower(ecryptfs_inode, enc_extent_virt, lower_offset,
374 				  PAGE_SIZE);
375 	kunmap_local(enc_extent_virt);
376 	if (rc < 0) {
377 		ecryptfs_printk(KERN_ERR,
378 			"Error attempting to write lower page; rc = [%d]\n",
379 			rc);
380 		goto out;
381 	}
382 	rc = 0;
383 out:
384 	if (enc_extent_page) {
385 		__free_page(enc_extent_page);
386 	}
387 	return rc;
388 }
389 
390 /**
391  * ecryptfs_decrypt_page
392  * @folio: Folio mapped from the eCryptfs inode for the file; data read
393  *        and decrypted from the lower file will be written into this
394  *        page
395  *
396  * Decrypt an eCryptfs page. This is done on a per-extent basis. Note
397  * that eCryptfs pages may straddle the lower pages -- for instance,
398  * if the file was created on a machine with an 8K page size
399  * (resulting in an 8K header), and then the file is copied onto a
400  * host with a 32K page size, then when reading page 0 of the eCryptfs
401  * file, 24K of page 0 of the lower file will be read and decrypted,
402  * and then 8K of page 1 of the lower file will be read and decrypted.
403  *
404  * Returns zero on success; negative on error
405  */
ecryptfs_decrypt_page(struct folio * folio)406 int ecryptfs_decrypt_page(struct folio *folio)
407 {
408 	struct inode *ecryptfs_inode;
409 	struct ecryptfs_crypt_stat *crypt_stat;
410 	char *page_virt;
411 	unsigned long extent_offset;
412 	loff_t lower_offset;
413 	int rc = 0;
414 
415 	ecryptfs_inode = folio->mapping->host;
416 	crypt_stat =
417 		&(ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat);
418 	BUG_ON(!(crypt_stat->flags & ECRYPTFS_ENCRYPTED));
419 
420 	lower_offset = lower_offset_for_page(crypt_stat, folio);
421 	page_virt = kmap_local_folio(folio, 0);
422 	rc = ecryptfs_read_lower(page_virt, lower_offset, PAGE_SIZE,
423 				 ecryptfs_inode);
424 	kunmap_local(page_virt);
425 	if (rc < 0) {
426 		ecryptfs_printk(KERN_ERR,
427 			"Error attempting to read lower page; rc = [%d]\n",
428 			rc);
429 		goto out;
430 	}
431 
432 	for (extent_offset = 0;
433 	     extent_offset < (PAGE_SIZE / crypt_stat->extent_size);
434 	     extent_offset++) {
435 		struct page *page = folio_page(folio, 0);
436 		rc = crypt_extent(crypt_stat, page, page, folio->index,
437 				extent_offset, DECRYPT);
438 		if (rc) {
439 			printk(KERN_ERR "%s: Error decrypting extent; "
440 			       "rc = [%d]\n", __func__, rc);
441 			goto out;
442 		}
443 	}
444 out:
445 	return rc;
446 }
447 
448 #define ECRYPTFS_MAX_SCATTERLIST_LEN 4
449 
450 /**
451  * ecryptfs_init_crypt_ctx
452  * @crypt_stat: Uninitialized crypt stats structure
453  *
454  * Initialize the crypto context.
455  *
456  * TODO: Performance: Keep a cache of initialized cipher contexts;
457  * only init if needed
458  */
ecryptfs_init_crypt_ctx(struct ecryptfs_crypt_stat * crypt_stat)459 int ecryptfs_init_crypt_ctx(struct ecryptfs_crypt_stat *crypt_stat)
460 {
461 	char *full_alg_name;
462 	int rc = -EINVAL;
463 
464 	ecryptfs_printk(KERN_DEBUG,
465 			"Initializing cipher [%s]; strlen = [%d]; "
466 			"key_size_bits = [%zd]\n",
467 			crypt_stat->cipher, (int)strlen(crypt_stat->cipher),
468 			crypt_stat->key_size << 3);
469 	mutex_lock(&crypt_stat->cs_tfm_mutex);
470 	if (crypt_stat->tfm) {
471 		rc = 0;
472 		goto out_unlock;
473 	}
474 	rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name,
475 						    crypt_stat->cipher, "cbc");
476 	if (rc)
477 		goto out_unlock;
478 	crypt_stat->tfm = crypto_alloc_skcipher(full_alg_name, 0, 0);
479 	if (IS_ERR(crypt_stat->tfm)) {
480 		rc = PTR_ERR(crypt_stat->tfm);
481 		crypt_stat->tfm = NULL;
482 		ecryptfs_printk(KERN_ERR, "cryptfs: init_crypt_ctx(): "
483 				"Error initializing cipher [%s]\n",
484 				full_alg_name);
485 		goto out_free;
486 	}
487 	crypto_skcipher_set_flags(crypt_stat->tfm,
488 				  CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
489 	rc = 0;
490 out_free:
491 	kfree(full_alg_name);
492 out_unlock:
493 	mutex_unlock(&crypt_stat->cs_tfm_mutex);
494 	return rc;
495 }
496 
set_extent_mask_and_shift(struct ecryptfs_crypt_stat * crypt_stat)497 static void set_extent_mask_and_shift(struct ecryptfs_crypt_stat *crypt_stat)
498 {
499 	int extent_size_tmp;
500 
501 	crypt_stat->extent_mask = 0xFFFFFFFF;
502 	crypt_stat->extent_shift = 0;
503 	if (crypt_stat->extent_size == 0)
504 		return;
505 	extent_size_tmp = crypt_stat->extent_size;
506 	while ((extent_size_tmp & 0x01) == 0) {
507 		extent_size_tmp >>= 1;
508 		crypt_stat->extent_mask <<= 1;
509 		crypt_stat->extent_shift++;
510 	}
511 }
512 
ecryptfs_set_default_sizes(struct ecryptfs_crypt_stat * crypt_stat)513 void ecryptfs_set_default_sizes(struct ecryptfs_crypt_stat *crypt_stat)
514 {
515 	/* Default values; may be overwritten as we are parsing the
516 	 * packets. */
517 	crypt_stat->extent_size = ECRYPTFS_DEFAULT_EXTENT_SIZE;
518 	set_extent_mask_and_shift(crypt_stat);
519 	crypt_stat->iv_bytes = ECRYPTFS_DEFAULT_IV_BYTES;
520 	if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
521 		crypt_stat->metadata_size = ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
522 	else {
523 		if (PAGE_SIZE <= ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE)
524 			crypt_stat->metadata_size =
525 				ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
526 		else
527 			crypt_stat->metadata_size = PAGE_SIZE;
528 	}
529 }
530 
531 /*
532  * ecryptfs_compute_root_iv
533  *
534  * On error, sets the root IV to all 0's.
535  */
ecryptfs_compute_root_iv(struct ecryptfs_crypt_stat * crypt_stat)536 int ecryptfs_compute_root_iv(struct ecryptfs_crypt_stat *crypt_stat)
537 {
538 	char dst[MD5_DIGEST_SIZE];
539 
540 	BUG_ON(crypt_stat->iv_bytes > MD5_DIGEST_SIZE);
541 	BUG_ON(crypt_stat->iv_bytes <= 0);
542 	if (!(crypt_stat->flags & ECRYPTFS_KEY_VALID)) {
543 		ecryptfs_printk(KERN_WARNING, "Session key not valid; "
544 				"cannot generate root IV\n");
545 		memset(crypt_stat->root_iv, 0, crypt_stat->iv_bytes);
546 		crypt_stat->flags |= ECRYPTFS_SECURITY_WARNING;
547 		return -EINVAL;
548 	}
549 	md5(crypt_stat->key, crypt_stat->key_size, dst);
550 	memcpy(crypt_stat->root_iv, dst, crypt_stat->iv_bytes);
551 	return 0;
552 }
553 
ecryptfs_generate_new_key(struct ecryptfs_crypt_stat * crypt_stat)554 static void ecryptfs_generate_new_key(struct ecryptfs_crypt_stat *crypt_stat)
555 {
556 	get_random_bytes(crypt_stat->key, crypt_stat->key_size);
557 	crypt_stat->flags |= ECRYPTFS_KEY_VALID;
558 	ecryptfs_compute_root_iv(crypt_stat);
559 	if (unlikely(ecryptfs_verbosity > 0)) {
560 		ecryptfs_printk(KERN_DEBUG, "Generated new session key:\n");
561 		ecryptfs_dump_hex(crypt_stat->key,
562 				  crypt_stat->key_size);
563 	}
564 }
565 
566 /**
567  * ecryptfs_copy_mount_wide_flags_to_inode_flags
568  * @crypt_stat: The inode's cryptographic context
569  * @mount_crypt_stat: The mount point's cryptographic context
570  *
571  * This function propagates the mount-wide flags to individual inode
572  * flags.
573  */
ecryptfs_copy_mount_wide_flags_to_inode_flags(struct ecryptfs_crypt_stat * crypt_stat,struct ecryptfs_mount_crypt_stat * mount_crypt_stat)574 static void ecryptfs_copy_mount_wide_flags_to_inode_flags(
575 	struct ecryptfs_crypt_stat *crypt_stat,
576 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
577 {
578 	if (mount_crypt_stat->flags & ECRYPTFS_XATTR_METADATA_ENABLED)
579 		crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
580 	if (mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED)
581 		crypt_stat->flags |= ECRYPTFS_VIEW_AS_ENCRYPTED;
582 	if (mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) {
583 		crypt_stat->flags |= ECRYPTFS_ENCRYPT_FILENAMES;
584 		if (mount_crypt_stat->flags
585 		    & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK)
586 			crypt_stat->flags |= ECRYPTFS_ENCFN_USE_MOUNT_FNEK;
587 		else if (mount_crypt_stat->flags
588 			 & ECRYPTFS_GLOBAL_ENCFN_USE_FEK)
589 			crypt_stat->flags |= ECRYPTFS_ENCFN_USE_FEK;
590 	}
591 }
592 
ecryptfs_copy_mount_wide_sigs_to_inode_sigs(struct ecryptfs_crypt_stat * crypt_stat,struct ecryptfs_mount_crypt_stat * mount_crypt_stat)593 static int ecryptfs_copy_mount_wide_sigs_to_inode_sigs(
594 	struct ecryptfs_crypt_stat *crypt_stat,
595 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
596 {
597 	struct ecryptfs_global_auth_tok *global_auth_tok;
598 	int rc = 0;
599 
600 	mutex_lock(&crypt_stat->keysig_list_mutex);
601 	mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
602 
603 	list_for_each_entry(global_auth_tok,
604 			    &mount_crypt_stat->global_auth_tok_list,
605 			    mount_crypt_stat_list) {
606 		if (global_auth_tok->flags & ECRYPTFS_AUTH_TOK_FNEK)
607 			continue;
608 		rc = ecryptfs_add_keysig(crypt_stat, global_auth_tok->sig);
609 		if (rc) {
610 			printk(KERN_ERR "Error adding keysig; rc = [%d]\n", rc);
611 			goto out;
612 		}
613 	}
614 
615 out:
616 	mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
617 	mutex_unlock(&crypt_stat->keysig_list_mutex);
618 	return rc;
619 }
620 
621 /**
622  * ecryptfs_set_default_crypt_stat_vals
623  * @crypt_stat: The inode's cryptographic context
624  * @mount_crypt_stat: The mount point's cryptographic context
625  *
626  * Default values in the event that policy does not override them.
627  */
ecryptfs_set_default_crypt_stat_vals(struct ecryptfs_crypt_stat * crypt_stat,struct ecryptfs_mount_crypt_stat * mount_crypt_stat)628 static void ecryptfs_set_default_crypt_stat_vals(
629 	struct ecryptfs_crypt_stat *crypt_stat,
630 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
631 {
632 	ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
633 						      mount_crypt_stat);
634 	ecryptfs_set_default_sizes(crypt_stat);
635 	strscpy(crypt_stat->cipher, ECRYPTFS_DEFAULT_CIPHER);
636 	crypt_stat->key_size = ECRYPTFS_DEFAULT_KEY_BYTES;
637 	crypt_stat->flags &= ~(ECRYPTFS_KEY_VALID);
638 	crypt_stat->file_version = ECRYPTFS_FILE_VERSION;
639 	crypt_stat->mount_crypt_stat = mount_crypt_stat;
640 }
641 
642 /**
643  * ecryptfs_new_file_context
644  * @ecryptfs_inode: The eCryptfs inode
645  *
646  * If the crypto context for the file has not yet been established,
647  * this is where we do that.  Establishing a new crypto context
648  * involves the following decisions:
649  *  - What cipher to use?
650  *  - What set of authentication tokens to use?
651  * Here we just worry about getting enough information into the
652  * authentication tokens so that we know that they are available.
653  * We associate the available authentication tokens with the new file
654  * via the set of signatures in the crypt_stat struct.  Later, when
655  * the headers are actually written out, we may again defer to
656  * userspace to perform the encryption of the session key; for the
657  * foreseeable future, this will be the case with public key packets.
658  *
659  * Returns zero on success; non-zero otherwise
660  */
ecryptfs_new_file_context(struct inode * ecryptfs_inode)661 int ecryptfs_new_file_context(struct inode *ecryptfs_inode)
662 {
663 	struct ecryptfs_crypt_stat *crypt_stat =
664 	    &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
665 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
666 	    &ecryptfs_superblock_to_private(
667 		    ecryptfs_inode->i_sb)->mount_crypt_stat;
668 	int rc = 0;
669 
670 	ecryptfs_set_default_crypt_stat_vals(crypt_stat, mount_crypt_stat);
671 	crypt_stat->flags |= (ECRYPTFS_ENCRYPTED | ECRYPTFS_KEY_VALID);
672 	ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
673 						      mount_crypt_stat);
674 	rc = ecryptfs_copy_mount_wide_sigs_to_inode_sigs(crypt_stat,
675 							 mount_crypt_stat);
676 	if (rc) {
677 		printk(KERN_ERR "Error attempting to copy mount-wide key sigs "
678 		       "to the inode key sigs; rc = [%d]\n", rc);
679 		goto out;
680 	}
681 	strscpy(crypt_stat->cipher,
682 		mount_crypt_stat->global_default_cipher_name);
683 	crypt_stat->key_size =
684 		mount_crypt_stat->global_default_cipher_key_size;
685 	ecryptfs_generate_new_key(crypt_stat);
686 	rc = ecryptfs_init_crypt_ctx(crypt_stat);
687 	if (rc)
688 		ecryptfs_printk(KERN_ERR, "Error initializing cryptographic "
689 				"context for cipher [%s]: rc = [%d]\n",
690 				crypt_stat->cipher, rc);
691 out:
692 	return rc;
693 }
694 
695 /**
696  * ecryptfs_validate_marker - check for the ecryptfs marker
697  * @data: The data block in which to check
698  *
699  * Returns zero if marker found; -EINVAL if not found
700  */
ecryptfs_validate_marker(char * data)701 static int ecryptfs_validate_marker(char *data)
702 {
703 	u32 m_1, m_2;
704 
705 	m_1 = get_unaligned_be32(data);
706 	m_2 = get_unaligned_be32(data + 4);
707 	if ((m_1 ^ MAGIC_ECRYPTFS_MARKER) == m_2)
708 		return 0;
709 	ecryptfs_printk(KERN_DEBUG, "m_1 = [0x%.8x]; m_2 = [0x%.8x]; "
710 			"MAGIC_ECRYPTFS_MARKER = [0x%.8x]\n", m_1, m_2,
711 			MAGIC_ECRYPTFS_MARKER);
712 	ecryptfs_printk(KERN_DEBUG, "(m_1 ^ MAGIC_ECRYPTFS_MARKER) = "
713 			"[0x%.8x]\n", (m_1 ^ MAGIC_ECRYPTFS_MARKER));
714 	return -EINVAL;
715 }
716 
717 struct ecryptfs_flag_map_elem {
718 	u32 file_flag;
719 	u32 local_flag;
720 };
721 
722 /* Add support for additional flags by adding elements here. */
723 static struct ecryptfs_flag_map_elem ecryptfs_flag_map[] = {
724 	{0x00000001, ECRYPTFS_ENABLE_HMAC},
725 	{0x00000002, ECRYPTFS_ENCRYPTED},
726 	{0x00000004, ECRYPTFS_METADATA_IN_XATTR},
727 	{0x00000008, ECRYPTFS_ENCRYPT_FILENAMES}
728 };
729 
730 /**
731  * ecryptfs_process_flags
732  * @crypt_stat: The cryptographic context
733  * @page_virt: Source data to be parsed
734  * @bytes_read: Updated with the number of bytes read
735  */
ecryptfs_process_flags(struct ecryptfs_crypt_stat * crypt_stat,char * page_virt,int * bytes_read)736 static void ecryptfs_process_flags(struct ecryptfs_crypt_stat *crypt_stat,
737 				  char *page_virt, int *bytes_read)
738 {
739 	int i;
740 	u32 flags;
741 
742 	flags = get_unaligned_be32(page_virt);
743 	for (i = 0; i < ARRAY_SIZE(ecryptfs_flag_map); i++)
744 		if (flags & ecryptfs_flag_map[i].file_flag) {
745 			crypt_stat->flags |= ecryptfs_flag_map[i].local_flag;
746 		} else
747 			crypt_stat->flags &= ~(ecryptfs_flag_map[i].local_flag);
748 	/* Version is in top 8 bits of the 32-bit flag vector */
749 	crypt_stat->file_version = ((flags >> 24) & 0xFF);
750 	(*bytes_read) = 4;
751 }
752 
753 /**
754  * write_ecryptfs_marker
755  * @page_virt: The pointer to in a page to begin writing the marker
756  * @written: Number of bytes written
757  *
758  * Marker = 0x3c81b7f5
759  */
write_ecryptfs_marker(char * page_virt,size_t * written)760 static void write_ecryptfs_marker(char *page_virt, size_t *written)
761 {
762 	u32 m_1, m_2;
763 
764 	get_random_bytes(&m_1, (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
765 	m_2 = (m_1 ^ MAGIC_ECRYPTFS_MARKER);
766 	put_unaligned_be32(m_1, page_virt);
767 	page_virt += (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2);
768 	put_unaligned_be32(m_2, page_virt);
769 	(*written) = MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
770 }
771 
ecryptfs_write_crypt_stat_flags(char * page_virt,struct ecryptfs_crypt_stat * crypt_stat,size_t * written)772 void ecryptfs_write_crypt_stat_flags(char *page_virt,
773 				     struct ecryptfs_crypt_stat *crypt_stat,
774 				     size_t *written)
775 {
776 	u32 flags = 0;
777 	int i;
778 
779 	for (i = 0; i < ARRAY_SIZE(ecryptfs_flag_map); i++)
780 		if (crypt_stat->flags & ecryptfs_flag_map[i].local_flag)
781 			flags |= ecryptfs_flag_map[i].file_flag;
782 	/* Version is in top 8 bits of the 32-bit flag vector */
783 	flags |= ((((u8)crypt_stat->file_version) << 24) & 0xFF000000);
784 	put_unaligned_be32(flags, page_virt);
785 	(*written) = 4;
786 }
787 
788 struct ecryptfs_cipher_code_str_map_elem {
789 	char cipher_str[16];
790 	u8 cipher_code;
791 };
792 
793 /* Add support for additional ciphers by adding elements here. The
794  * cipher_code is whatever OpenPGP applications use to identify the
795  * ciphers. List in order of probability. */
796 static struct ecryptfs_cipher_code_str_map_elem
797 ecryptfs_cipher_code_str_map[] = {
798 	{"aes",RFC2440_CIPHER_AES_128 },
799 	{"blowfish", RFC2440_CIPHER_BLOWFISH},
800 	{"des3_ede", RFC2440_CIPHER_DES3_EDE},
801 	{"cast5", RFC2440_CIPHER_CAST_5},
802 	{"twofish", RFC2440_CIPHER_TWOFISH},
803 	{"cast6", RFC2440_CIPHER_CAST_6},
804 	{"aes", RFC2440_CIPHER_AES_192},
805 	{"aes", RFC2440_CIPHER_AES_256}
806 };
807 
808 /**
809  * ecryptfs_code_for_cipher_string
810  * @cipher_name: The string alias for the cipher
811  * @key_bytes: Length of key in bytes; used for AES code selection
812  *
813  * Returns zero on no match, or the cipher code on match
814  */
ecryptfs_code_for_cipher_string(char * cipher_name,size_t key_bytes)815 u8 ecryptfs_code_for_cipher_string(char *cipher_name, size_t key_bytes)
816 {
817 	int i;
818 	u8 code = 0;
819 	struct ecryptfs_cipher_code_str_map_elem *map =
820 		ecryptfs_cipher_code_str_map;
821 
822 	if (strcmp(cipher_name, "aes") == 0) {
823 		switch (key_bytes) {
824 		case 16:
825 			code = RFC2440_CIPHER_AES_128;
826 			break;
827 		case 24:
828 			code = RFC2440_CIPHER_AES_192;
829 			break;
830 		case 32:
831 			code = RFC2440_CIPHER_AES_256;
832 		}
833 	} else {
834 		for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
835 			if (strcmp(cipher_name, map[i].cipher_str) == 0) {
836 				code = map[i].cipher_code;
837 				break;
838 			}
839 	}
840 	return code;
841 }
842 
843 /**
844  * ecryptfs_cipher_code_to_string
845  * @str: Destination to write out the cipher name
846  * @size: Destination buffer size
847  * @cipher_code: The code to convert to cipher name string
848  *
849  * Returns zero on success
850  */
ecryptfs_cipher_code_to_string(char * str,size_t size,u8 cipher_code)851 int ecryptfs_cipher_code_to_string(char *str, size_t size, u8 cipher_code)
852 {
853 	int rc = 0;
854 	int i;
855 
856 	str[0] = '\0';
857 	for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
858 		if (cipher_code == ecryptfs_cipher_code_str_map[i].cipher_code)
859 			strscpy(str, ecryptfs_cipher_code_str_map[i].cipher_str,
860 				size);
861 	if (str[0] == '\0') {
862 		ecryptfs_printk(KERN_WARNING, "Cipher code not recognized: "
863 				"[%d]\n", cipher_code);
864 		rc = -EINVAL;
865 	}
866 	return rc;
867 }
868 
ecryptfs_read_and_validate_header_region(struct inode * inode)869 int ecryptfs_read_and_validate_header_region(struct inode *inode)
870 {
871 	u8 file_size[ECRYPTFS_SIZE_AND_MARKER_BYTES];
872 	u8 *marker = file_size + ECRYPTFS_FILE_SIZE_BYTES;
873 	int rc;
874 
875 	rc = ecryptfs_read_lower(file_size, 0, ECRYPTFS_SIZE_AND_MARKER_BYTES,
876 				 inode);
877 	if (rc < 0)
878 		return rc;
879 	else if (rc < ECRYPTFS_SIZE_AND_MARKER_BYTES)
880 		return -EINVAL;
881 	rc = ecryptfs_validate_marker(marker);
882 	if (!rc)
883 		ecryptfs_i_size_init(file_size, inode);
884 	return rc;
885 }
886 
887 void
ecryptfs_write_header_metadata(char * virt,struct ecryptfs_crypt_stat * crypt_stat,size_t * written)888 ecryptfs_write_header_metadata(char *virt,
889 			       struct ecryptfs_crypt_stat *crypt_stat,
890 			       size_t *written)
891 {
892 	u32 header_extent_size;
893 	u16 num_header_extents_at_front;
894 
895 	header_extent_size = (u32)crypt_stat->extent_size;
896 	num_header_extents_at_front =
897 		(u16)(crypt_stat->metadata_size / crypt_stat->extent_size);
898 	put_unaligned_be32(header_extent_size, virt);
899 	virt += 4;
900 	put_unaligned_be16(num_header_extents_at_front, virt);
901 	(*written) = 6;
902 }
903 
904 struct kmem_cache *ecryptfs_header_cache;
905 
906 /**
907  * ecryptfs_write_headers_virt
908  * @page_virt: The virtual address to write the headers to
909  * @max: The size of memory allocated at page_virt
910  * @size: Set to the number of bytes written by this function
911  * @crypt_stat: The cryptographic context
912  * @ecryptfs_dentry: The eCryptfs dentry
913  *
914  * Format version: 1
915  *
916  *   Header Extent:
917  *     Octets 0-7:        Unencrypted file size (big-endian)
918  *     Octets 8-15:       eCryptfs special marker
919  *     Octets 16-19:      Flags
920  *      Octet 16:         File format version number (between 0 and 255)
921  *      Octets 17-18:     Reserved
922  *      Octet 19:         Bit 1 (lsb): Reserved
923  *                        Bit 2: Encrypted?
924  *                        Bits 3-8: Reserved
925  *     Octets 20-23:      Header extent size (big-endian)
926  *     Octets 24-25:      Number of header extents at front of file
927  *                        (big-endian)
928  *     Octet  26:         Begin RFC 2440 authentication token packet set
929  *   Data Extent 0:
930  *     Lower data (CBC encrypted)
931  *   Data Extent 1:
932  *     Lower data (CBC encrypted)
933  *   ...
934  *
935  * Returns zero on success
936  */
ecryptfs_write_headers_virt(char * page_virt,size_t max,size_t * size,struct ecryptfs_crypt_stat * crypt_stat,struct dentry * ecryptfs_dentry)937 static int ecryptfs_write_headers_virt(char *page_virt, size_t max,
938 				       size_t *size,
939 				       struct ecryptfs_crypt_stat *crypt_stat,
940 				       struct dentry *ecryptfs_dentry)
941 {
942 	int rc;
943 	size_t written;
944 	size_t offset;
945 
946 	offset = ECRYPTFS_FILE_SIZE_BYTES;
947 	write_ecryptfs_marker((page_virt + offset), &written);
948 	offset += written;
949 	ecryptfs_write_crypt_stat_flags((page_virt + offset), crypt_stat,
950 					&written);
951 	offset += written;
952 	ecryptfs_write_header_metadata((page_virt + offset), crypt_stat,
953 				       &written);
954 	offset += written;
955 	rc = ecryptfs_generate_key_packet_set((page_virt + offset), crypt_stat,
956 					      ecryptfs_dentry, &written,
957 					      max - offset);
958 	if (rc)
959 		ecryptfs_printk(KERN_WARNING, "Error generating key packet "
960 				"set; rc = [%d]\n", rc);
961 	if (size) {
962 		offset += written;
963 		*size = offset;
964 	}
965 	return rc;
966 }
967 
968 static int
ecryptfs_write_metadata_to_contents(struct inode * ecryptfs_inode,char * virt,size_t virt_len)969 ecryptfs_write_metadata_to_contents(struct inode *ecryptfs_inode,
970 				    char *virt, size_t virt_len)
971 {
972 	int rc;
973 
974 	rc = ecryptfs_write_lower(ecryptfs_inode, virt,
975 				  0, virt_len);
976 	if (rc < 0)
977 		printk(KERN_ERR "%s: Error attempting to write header "
978 		       "information to lower file; rc = [%d]\n", __func__, rc);
979 	else
980 		rc = 0;
981 	return rc;
982 }
983 
984 static int
ecryptfs_write_metadata_to_xattr(struct dentry * ecryptfs_dentry,struct inode * ecryptfs_inode,char * page_virt,size_t size)985 ecryptfs_write_metadata_to_xattr(struct dentry *ecryptfs_dentry,
986 				 struct inode *ecryptfs_inode,
987 				 char *page_virt, size_t size)
988 {
989 	int rc;
990 	struct dentry *lower_dentry = ecryptfs_dentry_to_lower(ecryptfs_dentry);
991 	struct inode *lower_inode = d_inode(lower_dentry);
992 
993 	if (!(lower_inode->i_opflags & IOP_XATTR)) {
994 		rc = -EOPNOTSUPP;
995 		goto out;
996 	}
997 
998 	inode_lock(lower_inode);
999 	rc = __vfs_setxattr(&nop_mnt_idmap, lower_dentry, lower_inode,
1000 			    ECRYPTFS_XATTR_NAME, page_virt, size, 0);
1001 	if (!rc && ecryptfs_inode)
1002 		fsstack_copy_attr_all(ecryptfs_inode, lower_inode);
1003 	inode_unlock(lower_inode);
1004 out:
1005 	return rc;
1006 }
1007 
ecryptfs_get_zeroed_pages(gfp_t gfp_mask,unsigned int order)1008 static unsigned long ecryptfs_get_zeroed_pages(gfp_t gfp_mask,
1009 					       unsigned int order)
1010 {
1011 	struct page *page;
1012 
1013 	page = alloc_pages(gfp_mask | __GFP_ZERO, order);
1014 	if (page)
1015 		return (unsigned long) page_address(page);
1016 	return 0;
1017 }
1018 
1019 /**
1020  * ecryptfs_write_metadata
1021  * @ecryptfs_dentry: The eCryptfs dentry, which should be negative
1022  * @ecryptfs_inode: The newly created eCryptfs inode
1023  *
1024  * Write the file headers out.  This will likely involve a userspace
1025  * callout, in which the session key is encrypted with one or more
1026  * public keys and/or the passphrase necessary to do the encryption is
1027  * retrieved via a prompt.  Exactly what happens at this point should
1028  * be policy-dependent.
1029  *
1030  * Returns zero on success; non-zero on error
1031  */
ecryptfs_write_metadata(struct dentry * ecryptfs_dentry,struct inode * ecryptfs_inode)1032 int ecryptfs_write_metadata(struct dentry *ecryptfs_dentry,
1033 			    struct inode *ecryptfs_inode)
1034 {
1035 	struct ecryptfs_crypt_stat *crypt_stat =
1036 		&ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
1037 	unsigned int order;
1038 	char *virt;
1039 	size_t virt_len;
1040 	size_t size = 0;
1041 	int rc = 0;
1042 
1043 	if (likely(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
1044 		if (!(crypt_stat->flags & ECRYPTFS_KEY_VALID)) {
1045 			printk(KERN_ERR "Key is invalid; bailing out\n");
1046 			rc = -EINVAL;
1047 			goto out;
1048 		}
1049 	} else {
1050 		printk(KERN_WARNING "%s: Encrypted flag not set\n",
1051 		       __func__);
1052 		rc = -EINVAL;
1053 		goto out;
1054 	}
1055 	virt_len = crypt_stat->metadata_size;
1056 	order = get_order(virt_len);
1057 	/* Released in this function */
1058 	virt = (char *)ecryptfs_get_zeroed_pages(GFP_KERNEL, order);
1059 	if (!virt) {
1060 		printk(KERN_ERR "%s: Out of memory\n", __func__);
1061 		rc = -ENOMEM;
1062 		goto out;
1063 	}
1064 	/* Zeroed page ensures the in-header unencrypted i_size is set to 0 */
1065 	rc = ecryptfs_write_headers_virt(virt, virt_len, &size, crypt_stat,
1066 					 ecryptfs_dentry);
1067 	if (unlikely(rc)) {
1068 		printk(KERN_ERR "%s: Error whilst writing headers; rc = [%d]\n",
1069 		       __func__, rc);
1070 		goto out_free;
1071 	}
1072 	if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
1073 		rc = ecryptfs_write_metadata_to_xattr(ecryptfs_dentry, ecryptfs_inode,
1074 						      virt, size);
1075 	else
1076 		rc = ecryptfs_write_metadata_to_contents(ecryptfs_inode, virt,
1077 							 virt_len);
1078 	if (rc) {
1079 		printk(KERN_ERR "%s: Error writing metadata out to lower file; "
1080 		       "rc = [%d]\n", __func__, rc);
1081 		goto out_free;
1082 	}
1083 out_free:
1084 	free_pages((unsigned long)virt, order);
1085 out:
1086 	return rc;
1087 }
1088 
1089 #define ECRYPTFS_DONT_VALIDATE_HEADER_SIZE 0
1090 #define ECRYPTFS_VALIDATE_HEADER_SIZE 1
parse_header_metadata(struct ecryptfs_crypt_stat * crypt_stat,char * virt,int * bytes_read,int validate_header_size)1091 static int parse_header_metadata(struct ecryptfs_crypt_stat *crypt_stat,
1092 				 char *virt, int *bytes_read,
1093 				 int validate_header_size)
1094 {
1095 	int rc = 0;
1096 	u32 header_extent_size;
1097 	u16 num_header_extents_at_front;
1098 
1099 	header_extent_size = get_unaligned_be32(virt);
1100 	virt += sizeof(__be32);
1101 	num_header_extents_at_front = get_unaligned_be16(virt);
1102 	crypt_stat->metadata_size = (((size_t)num_header_extents_at_front
1103 				     * (size_t)header_extent_size));
1104 	(*bytes_read) = (sizeof(__be32) + sizeof(__be16));
1105 	if ((validate_header_size == ECRYPTFS_VALIDATE_HEADER_SIZE)
1106 	    && (crypt_stat->metadata_size
1107 		< ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE)) {
1108 		rc = -EINVAL;
1109 		printk(KERN_WARNING "Invalid header size: [%zd]\n",
1110 		       crypt_stat->metadata_size);
1111 	}
1112 	return rc;
1113 }
1114 
1115 /**
1116  * set_default_header_data
1117  * @crypt_stat: The cryptographic context
1118  *
1119  * For version 0 file format; this function is only for backwards
1120  * compatibility for files created with the prior versions of
1121  * eCryptfs.
1122  */
set_default_header_data(struct ecryptfs_crypt_stat * crypt_stat)1123 static void set_default_header_data(struct ecryptfs_crypt_stat *crypt_stat)
1124 {
1125 	crypt_stat->metadata_size = ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
1126 }
1127 
ecryptfs_i_size_init(const char * page_virt,struct inode * inode)1128 void ecryptfs_i_size_init(const char *page_virt, struct inode *inode)
1129 {
1130 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat;
1131 	struct ecryptfs_crypt_stat *crypt_stat;
1132 	u64 file_size;
1133 
1134 	crypt_stat = &ecryptfs_inode_to_private(inode)->crypt_stat;
1135 	mount_crypt_stat =
1136 		&ecryptfs_superblock_to_private(inode->i_sb)->mount_crypt_stat;
1137 	if (mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED) {
1138 		file_size = i_size_read(ecryptfs_inode_to_lower(inode));
1139 		if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
1140 			file_size += crypt_stat->metadata_size;
1141 	} else
1142 		file_size = get_unaligned_be64(page_virt);
1143 	i_size_write(inode, (loff_t)file_size);
1144 	crypt_stat->flags |= ECRYPTFS_I_SIZE_INITIALIZED;
1145 }
1146 
1147 /**
1148  * ecryptfs_read_headers_virt
1149  * @page_virt: The virtual address into which to read the headers
1150  * @crypt_stat: The cryptographic context
1151  * @ecryptfs_dentry: The eCryptfs dentry
1152  * @validate_header_size: Whether to validate the header size while reading
1153  *
1154  * Read/parse the header data. The header format is detailed in the
1155  * comment block for the ecryptfs_write_headers_virt() function.
1156  *
1157  * Returns zero on success
1158  */
ecryptfs_read_headers_virt(char * page_virt,struct ecryptfs_crypt_stat * crypt_stat,struct dentry * ecryptfs_dentry,int validate_header_size)1159 static int ecryptfs_read_headers_virt(char *page_virt,
1160 				      struct ecryptfs_crypt_stat *crypt_stat,
1161 				      struct dentry *ecryptfs_dentry,
1162 				      int validate_header_size)
1163 {
1164 	int rc = 0;
1165 	int offset;
1166 	int bytes_read;
1167 
1168 	ecryptfs_set_default_sizes(crypt_stat);
1169 	crypt_stat->mount_crypt_stat = &ecryptfs_superblock_to_private(
1170 		ecryptfs_dentry->d_sb)->mount_crypt_stat;
1171 	offset = ECRYPTFS_FILE_SIZE_BYTES;
1172 	rc = ecryptfs_validate_marker(page_virt + offset);
1173 	if (rc)
1174 		goto out;
1175 	if (!(crypt_stat->flags & ECRYPTFS_I_SIZE_INITIALIZED))
1176 		ecryptfs_i_size_init(page_virt, d_inode(ecryptfs_dentry));
1177 	offset += MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
1178 	ecryptfs_process_flags(crypt_stat, (page_virt + offset), &bytes_read);
1179 	if (crypt_stat->file_version > ECRYPTFS_SUPPORTED_FILE_VERSION) {
1180 		ecryptfs_printk(KERN_WARNING, "File version is [%d]; only "
1181 				"file version [%d] is supported by this "
1182 				"version of eCryptfs\n",
1183 				crypt_stat->file_version,
1184 				ECRYPTFS_SUPPORTED_FILE_VERSION);
1185 		rc = -EINVAL;
1186 		goto out;
1187 	}
1188 	offset += bytes_read;
1189 	if (crypt_stat->file_version >= 1) {
1190 		rc = parse_header_metadata(crypt_stat, (page_virt + offset),
1191 					   &bytes_read, validate_header_size);
1192 		if (rc) {
1193 			ecryptfs_printk(KERN_WARNING, "Error reading header "
1194 					"metadata; rc = [%d]\n", rc);
1195 		}
1196 		offset += bytes_read;
1197 	} else
1198 		set_default_header_data(crypt_stat);
1199 	rc = ecryptfs_parse_packet_set(crypt_stat, (page_virt + offset),
1200 				       ecryptfs_dentry);
1201 out:
1202 	return rc;
1203 }
1204 
1205 /**
1206  * ecryptfs_read_xattr_region
1207  * @page_virt: The virtual address into which to read the xattr data
1208  * @ecryptfs_inode: The eCryptfs inode
1209  *
1210  * Attempts to read the crypto metadata from the extended attribute
1211  * region of the lower file.
1212  *
1213  * Returns zero on success; non-zero on error
1214  */
ecryptfs_read_xattr_region(char * page_virt,struct inode * ecryptfs_inode)1215 int ecryptfs_read_xattr_region(char *page_virt, struct inode *ecryptfs_inode)
1216 {
1217 	struct dentry *lower_dentry =
1218 		ecryptfs_inode_to_private(ecryptfs_inode)->lower_file->f_path.dentry;
1219 	ssize_t size;
1220 	int rc = 0;
1221 
1222 	size = ecryptfs_getxattr_lower(lower_dentry,
1223 				       ecryptfs_inode_to_lower(ecryptfs_inode),
1224 				       ECRYPTFS_XATTR_NAME,
1225 				       page_virt, ECRYPTFS_DEFAULT_EXTENT_SIZE);
1226 	if (size < 0) {
1227 		if (unlikely(ecryptfs_verbosity > 0))
1228 			printk(KERN_INFO "Error attempting to read the [%s] "
1229 			       "xattr from the lower file; return value = "
1230 			       "[%zd]\n", ECRYPTFS_XATTR_NAME, size);
1231 		rc = -EINVAL;
1232 		goto out;
1233 	}
1234 out:
1235 	return rc;
1236 }
1237 
ecryptfs_read_and_validate_xattr_region(struct dentry * dentry,struct inode * inode)1238 int ecryptfs_read_and_validate_xattr_region(struct dentry *dentry,
1239 					    struct inode *inode)
1240 {
1241 	u8 file_size[ECRYPTFS_SIZE_AND_MARKER_BYTES];
1242 	u8 *marker = file_size + ECRYPTFS_FILE_SIZE_BYTES;
1243 	int rc;
1244 
1245 	rc = ecryptfs_getxattr_lower(ecryptfs_dentry_to_lower(dentry),
1246 				     ecryptfs_inode_to_lower(inode),
1247 				     ECRYPTFS_XATTR_NAME, file_size,
1248 				     ECRYPTFS_SIZE_AND_MARKER_BYTES);
1249 	if (rc < 0)
1250 		return rc;
1251 	else if (rc < ECRYPTFS_SIZE_AND_MARKER_BYTES)
1252 		return -EINVAL;
1253 	rc = ecryptfs_validate_marker(marker);
1254 	if (!rc)
1255 		ecryptfs_i_size_init(file_size, inode);
1256 	return rc;
1257 }
1258 
1259 /*
1260  * ecryptfs_read_metadata
1261  *
1262  * Common entry point for reading file metadata. From here, we could
1263  * retrieve the header information from the header region of the file,
1264  * the xattr region of the file, or some other repository that is
1265  * stored separately from the file itself. The current implementation
1266  * supports retrieving the metadata information from the file contents
1267  * and from the xattr region.
1268  *
1269  * Returns zero if valid headers found and parsed; non-zero otherwise
1270  */
ecryptfs_read_metadata(struct dentry * ecryptfs_dentry)1271 int ecryptfs_read_metadata(struct dentry *ecryptfs_dentry)
1272 {
1273 	int rc;
1274 	char *page_virt;
1275 	struct inode *ecryptfs_inode = d_inode(ecryptfs_dentry);
1276 	struct ecryptfs_crypt_stat *crypt_stat =
1277 	    &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
1278 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1279 		&ecryptfs_superblock_to_private(
1280 			ecryptfs_dentry->d_sb)->mount_crypt_stat;
1281 
1282 	ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
1283 						      mount_crypt_stat);
1284 	/* Read the first page from the underlying file */
1285 	page_virt = kmem_cache_alloc(ecryptfs_header_cache, GFP_USER);
1286 	if (!page_virt) {
1287 		rc = -ENOMEM;
1288 		goto out;
1289 	}
1290 	rc = ecryptfs_read_lower(page_virt, 0, crypt_stat->extent_size,
1291 				 ecryptfs_inode);
1292 	if (rc >= 0)
1293 		rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
1294 						ecryptfs_dentry,
1295 						ECRYPTFS_VALIDATE_HEADER_SIZE);
1296 	if (rc) {
1297 		/* metadata is not in the file header, so try xattrs */
1298 		memset(page_virt, 0, PAGE_SIZE);
1299 		rc = ecryptfs_read_xattr_region(page_virt, ecryptfs_inode);
1300 		if (rc) {
1301 			printk(KERN_DEBUG "Valid eCryptfs headers not found in "
1302 			       "file header region or xattr region, inode %llu\n",
1303 				ecryptfs_inode->i_ino);
1304 			rc = -EINVAL;
1305 			goto out;
1306 		}
1307 		rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
1308 						ecryptfs_dentry,
1309 						ECRYPTFS_DONT_VALIDATE_HEADER_SIZE);
1310 		if (rc) {
1311 			printk(KERN_DEBUG "Valid eCryptfs headers not found in "
1312 			       "file xattr region either, inode %llu\n",
1313 				ecryptfs_inode->i_ino);
1314 			rc = -EINVAL;
1315 		}
1316 		if (crypt_stat->mount_crypt_stat->flags
1317 		    & ECRYPTFS_XATTR_METADATA_ENABLED) {
1318 			crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
1319 		} else {
1320 			printk(KERN_WARNING "Attempt to access file with "
1321 			       "crypto metadata only in the extended attribute "
1322 			       "region, but eCryptfs was mounted without "
1323 			       "xattr support enabled. eCryptfs will not treat "
1324 			       "this like an encrypted file, inode %llu\n",
1325 				ecryptfs_inode->i_ino);
1326 			rc = -EINVAL;
1327 		}
1328 	}
1329 out:
1330 	if (page_virt) {
1331 		memset(page_virt, 0, PAGE_SIZE);
1332 		kmem_cache_free(ecryptfs_header_cache, page_virt);
1333 	}
1334 	return rc;
1335 }
1336 
1337 /*
1338  * ecryptfs_encrypt_filename - encrypt filename
1339  *
1340  * CBC-encrypts the filename. We do not want to encrypt the same
1341  * filename with the same key and IV, which may happen with hard
1342  * links, so we prepend random bits to each filename.
1343  *
1344  * Returns zero on success; non-zero otherwise
1345  */
1346 static int
ecryptfs_encrypt_filename(struct ecryptfs_filename * filename,struct ecryptfs_mount_crypt_stat * mount_crypt_stat)1347 ecryptfs_encrypt_filename(struct ecryptfs_filename *filename,
1348 			  struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
1349 {
1350 	int rc = 0;
1351 
1352 	filename->encrypted_filename = NULL;
1353 	filename->encrypted_filename_size = 0;
1354 	if (mount_crypt_stat && (mount_crypt_stat->flags
1355 				     & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK)) {
1356 		size_t packet_size;
1357 		size_t remaining_bytes;
1358 
1359 		rc = ecryptfs_write_tag_70_packet(
1360 			NULL, NULL,
1361 			&filename->encrypted_filename_size,
1362 			mount_crypt_stat, NULL,
1363 			filename->filename_size);
1364 		if (rc) {
1365 			ecryptfs_printk(KERN_ERR,
1366 				"Error attempting to get packet size for tag 70; rc = [%d]\n",
1367 				rc);
1368 			filename->encrypted_filename_size = 0;
1369 			goto out;
1370 		}
1371 		filename->encrypted_filename =
1372 			kmalloc(filename->encrypted_filename_size, GFP_KERNEL);
1373 		if (!filename->encrypted_filename) {
1374 			rc = -ENOMEM;
1375 			goto out;
1376 		}
1377 		remaining_bytes = filename->encrypted_filename_size;
1378 		rc = ecryptfs_write_tag_70_packet(filename->encrypted_filename,
1379 						  &remaining_bytes,
1380 						  &packet_size,
1381 						  mount_crypt_stat,
1382 						  filename->filename,
1383 						  filename->filename_size);
1384 		if (rc) {
1385 			printk(KERN_ERR "%s: Error attempting to generate "
1386 			       "tag 70 packet; rc = [%d]\n", __func__,
1387 			       rc);
1388 			kfree(filename->encrypted_filename);
1389 			filename->encrypted_filename = NULL;
1390 			filename->encrypted_filename_size = 0;
1391 			goto out;
1392 		}
1393 		filename->encrypted_filename_size = packet_size;
1394 	} else {
1395 		printk(KERN_ERR "%s: No support for requested filename "
1396 		       "encryption method in this release\n", __func__);
1397 		rc = -EOPNOTSUPP;
1398 		goto out;
1399 	}
1400 out:
1401 	return rc;
1402 }
1403 
ecryptfs_copy_filename(char ** copied_name,size_t * copied_name_size,const char * name,size_t name_size)1404 static int ecryptfs_copy_filename(char **copied_name, size_t *copied_name_size,
1405 				  const char *name, size_t name_size)
1406 {
1407 	(*copied_name) = kmemdup_nul(name, name_size, GFP_KERNEL);
1408 	if (!(*copied_name))
1409 		return -ENOMEM;
1410 	(*copied_name_size) = name_size;
1411 	return 0;
1412 }
1413 
1414 /**
1415  * ecryptfs_process_key_cipher - Perform key cipher initialization.
1416  * @key_tfm: Crypto context for key material, set by this function
1417  * @cipher_name: Name of the cipher
1418  * @key_size: Size of the key in bytes
1419  *
1420  * Returns zero on success. Any crypto_tfm structs allocated here
1421  * should be released by other functions, such as on a superblock put
1422  * event, regardless of whether this function succeeds for fails.
1423  */
1424 static int
ecryptfs_process_key_cipher(struct crypto_skcipher ** key_tfm,char * cipher_name,size_t * key_size)1425 ecryptfs_process_key_cipher(struct crypto_skcipher **key_tfm,
1426 			    char *cipher_name, size_t *key_size)
1427 {
1428 	char dummy_key[ECRYPTFS_MAX_KEY_BYTES];
1429 	char *full_alg_name = NULL;
1430 	int rc;
1431 
1432 	*key_tfm = NULL;
1433 	if (*key_size > ECRYPTFS_MAX_KEY_BYTES) {
1434 		rc = -EINVAL;
1435 		printk(KERN_ERR "Requested key size is [%zd] bytes; maximum "
1436 		      "allowable is [%d]\n", *key_size, ECRYPTFS_MAX_KEY_BYTES);
1437 		goto out;
1438 	}
1439 	rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name, cipher_name,
1440 						    "ecb");
1441 	if (rc)
1442 		goto out;
1443 	*key_tfm = crypto_alloc_skcipher(full_alg_name, 0, CRYPTO_ALG_ASYNC);
1444 	if (IS_ERR(*key_tfm)) {
1445 		rc = PTR_ERR(*key_tfm);
1446 		printk(KERN_ERR "Unable to allocate crypto cipher with name "
1447 		       "[%s]; rc = [%d]\n", full_alg_name, rc);
1448 		goto out;
1449 	}
1450 	crypto_skcipher_set_flags(*key_tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
1451 	if (*key_size == 0)
1452 		*key_size = crypto_skcipher_max_keysize(*key_tfm);
1453 	get_random_bytes(dummy_key, *key_size);
1454 	rc = crypto_skcipher_setkey(*key_tfm, dummy_key, *key_size);
1455 	if (rc) {
1456 		printk(KERN_ERR "Error attempting to set key of size [%zd] for "
1457 		       "cipher [%s]; rc = [%d]\n", *key_size, full_alg_name,
1458 		       rc);
1459 		rc = -EINVAL;
1460 		goto out;
1461 	}
1462 out:
1463 	kfree(full_alg_name);
1464 	return rc;
1465 }
1466 
1467 struct kmem_cache *ecryptfs_key_tfm_cache;
1468 static struct list_head key_tfm_list;
1469 DEFINE_MUTEX(key_tfm_list_mutex);
1470 
ecryptfs_init_crypto(void)1471 int __init ecryptfs_init_crypto(void)
1472 {
1473 	INIT_LIST_HEAD(&key_tfm_list);
1474 	return 0;
1475 }
1476 
1477 /**
1478  * ecryptfs_destroy_crypto - free all cached key_tfms on key_tfm_list
1479  *
1480  * Called only at module unload time
1481  */
ecryptfs_destroy_crypto(void)1482 int ecryptfs_destroy_crypto(void)
1483 {
1484 	struct ecryptfs_key_tfm *key_tfm, *key_tfm_tmp;
1485 
1486 	mutex_lock(&key_tfm_list_mutex);
1487 	list_for_each_entry_safe(key_tfm, key_tfm_tmp, &key_tfm_list,
1488 				 key_tfm_list) {
1489 		list_del(&key_tfm->key_tfm_list);
1490 		crypto_free_skcipher(key_tfm->key_tfm);
1491 		kmem_cache_free(ecryptfs_key_tfm_cache, key_tfm);
1492 	}
1493 	mutex_unlock(&key_tfm_list_mutex);
1494 	return 0;
1495 }
1496 
1497 int
ecryptfs_add_new_key_tfm(struct ecryptfs_key_tfm ** key_tfm,char * cipher_name,size_t key_size)1498 ecryptfs_add_new_key_tfm(struct ecryptfs_key_tfm **key_tfm, char *cipher_name,
1499 			 size_t key_size)
1500 {
1501 	struct ecryptfs_key_tfm *tmp_tfm;
1502 	int rc = 0;
1503 
1504 	BUG_ON(!mutex_is_locked(&key_tfm_list_mutex));
1505 
1506 	tmp_tfm = kmem_cache_alloc(ecryptfs_key_tfm_cache, GFP_KERNEL);
1507 	if (key_tfm)
1508 		(*key_tfm) = tmp_tfm;
1509 	if (!tmp_tfm) {
1510 		rc = -ENOMEM;
1511 		goto out;
1512 	}
1513 	mutex_init(&tmp_tfm->key_tfm_mutex);
1514 	strscpy(tmp_tfm->cipher_name, cipher_name);
1515 	tmp_tfm->key_size = key_size;
1516 	rc = ecryptfs_process_key_cipher(&tmp_tfm->key_tfm,
1517 					 tmp_tfm->cipher_name,
1518 					 &tmp_tfm->key_size);
1519 	if (rc) {
1520 		printk(KERN_ERR "Error attempting to initialize key TFM "
1521 		       "cipher with name = [%s]; rc = [%d]\n",
1522 		       tmp_tfm->cipher_name, rc);
1523 		kmem_cache_free(ecryptfs_key_tfm_cache, tmp_tfm);
1524 		if (key_tfm)
1525 			(*key_tfm) = NULL;
1526 		goto out;
1527 	}
1528 	list_add(&tmp_tfm->key_tfm_list, &key_tfm_list);
1529 out:
1530 	return rc;
1531 }
1532 
1533 /**
1534  * ecryptfs_tfm_exists - Search for existing tfm for cipher_name.
1535  * @cipher_name: the name of the cipher to search for
1536  * @key_tfm: set to corresponding tfm if found
1537  *
1538  * Searches for cached key_tfm matching @cipher_name
1539  * Must be called with &key_tfm_list_mutex held
1540  * Returns 1 if found, with @key_tfm set
1541  * Returns 0 if not found, with @key_tfm set to NULL
1542  */
ecryptfs_tfm_exists(char * cipher_name,struct ecryptfs_key_tfm ** key_tfm)1543 int ecryptfs_tfm_exists(char *cipher_name, struct ecryptfs_key_tfm **key_tfm)
1544 {
1545 	struct ecryptfs_key_tfm *tmp_key_tfm;
1546 
1547 	BUG_ON(!mutex_is_locked(&key_tfm_list_mutex));
1548 
1549 	list_for_each_entry(tmp_key_tfm, &key_tfm_list, key_tfm_list) {
1550 		if (strcmp(tmp_key_tfm->cipher_name, cipher_name) == 0) {
1551 			if (key_tfm)
1552 				(*key_tfm) = tmp_key_tfm;
1553 			return 1;
1554 		}
1555 	}
1556 	if (key_tfm)
1557 		(*key_tfm) = NULL;
1558 	return 0;
1559 }
1560 
1561 /**
1562  * ecryptfs_get_tfm_and_mutex_for_cipher_name
1563  *
1564  * @tfm: set to cached tfm found, or new tfm created
1565  * @tfm_mutex: set to mutex for cached tfm found, or new tfm created
1566  * @cipher_name: the name of the cipher to search for and/or add
1567  *
1568  * Sets pointers to @tfm & @tfm_mutex matching @cipher_name.
1569  * Searches for cached item first, and creates new if not found.
1570  * Returns 0 on success, non-zero if adding new cipher failed
1571  */
ecryptfs_get_tfm_and_mutex_for_cipher_name(struct crypto_skcipher ** tfm,struct mutex ** tfm_mutex,char * cipher_name)1572 int ecryptfs_get_tfm_and_mutex_for_cipher_name(struct crypto_skcipher **tfm,
1573 					       struct mutex **tfm_mutex,
1574 					       char *cipher_name)
1575 {
1576 	struct ecryptfs_key_tfm *key_tfm;
1577 	int rc = 0;
1578 
1579 	(*tfm) = NULL;
1580 	(*tfm_mutex) = NULL;
1581 
1582 	mutex_lock(&key_tfm_list_mutex);
1583 	if (!ecryptfs_tfm_exists(cipher_name, &key_tfm)) {
1584 		rc = ecryptfs_add_new_key_tfm(&key_tfm, cipher_name, 0);
1585 		if (rc) {
1586 			printk(KERN_ERR "Error adding new key_tfm to list; "
1587 					"rc = [%d]\n", rc);
1588 			goto out;
1589 		}
1590 	}
1591 	(*tfm) = key_tfm->key_tfm;
1592 	(*tfm_mutex) = &key_tfm->key_tfm_mutex;
1593 out:
1594 	mutex_unlock(&key_tfm_list_mutex);
1595 	return rc;
1596 }
1597 
1598 /* 64 characters forming a 6-bit target field */
1599 static unsigned char *portable_filename_chars = ("-.0123456789ABCD"
1600 						 "EFGHIJKLMNOPQRST"
1601 						 "UVWXYZabcdefghij"
1602 						 "klmnopqrstuvwxyz");
1603 
1604 /* We could either offset on every reverse map or just pad some 0x00's
1605  * at the front here */
1606 static const unsigned char filename_rev_map[256] = {
1607 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 7 */
1608 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 15 */
1609 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 23 */
1610 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 31 */
1611 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 39 */
1612 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, /* 47 */
1613 	0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, /* 55 */
1614 	0x0A, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 63 */
1615 	0x00, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, /* 71 */
1616 	0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, /* 79 */
1617 	0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, /* 87 */
1618 	0x23, 0x24, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, /* 95 */
1619 	0x00, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, /* 103 */
1620 	0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, /* 111 */
1621 	0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, /* 119 */
1622 	0x3D, 0x3E, 0x3F /* 123 - 255 initialized to 0x00 */
1623 };
1624 
1625 /**
1626  * ecryptfs_encode_for_filename
1627  * @dst: Destination location for encoded filename
1628  * @dst_size: Size of the encoded filename in bytes
1629  * @src: Source location for the filename to encode
1630  * @src_size: Size of the source in bytes
1631  */
ecryptfs_encode_for_filename(unsigned char * dst,size_t * dst_size,unsigned char * src,size_t src_size)1632 static void ecryptfs_encode_for_filename(unsigned char *dst, size_t *dst_size,
1633 				  unsigned char *src, size_t src_size)
1634 {
1635 	size_t num_blocks;
1636 	size_t block_num = 0;
1637 	size_t dst_offset = 0;
1638 	unsigned char last_block[3];
1639 
1640 	if (src_size == 0) {
1641 		(*dst_size) = 0;
1642 		goto out;
1643 	}
1644 	num_blocks = (src_size / 3);
1645 	if ((src_size % 3) == 0) {
1646 		memcpy(last_block, (&src[src_size - 3]), 3);
1647 	} else {
1648 		num_blocks++;
1649 		last_block[2] = 0x00;
1650 		switch (src_size % 3) {
1651 		case 1:
1652 			last_block[0] = src[src_size - 1];
1653 			last_block[1] = 0x00;
1654 			break;
1655 		case 2:
1656 			last_block[0] = src[src_size - 2];
1657 			last_block[1] = src[src_size - 1];
1658 		}
1659 	}
1660 	(*dst_size) = (num_blocks * 4);
1661 	if (!dst)
1662 		goto out;
1663 	while (block_num < num_blocks) {
1664 		unsigned char *src_block;
1665 		unsigned char dst_block[4];
1666 
1667 		if (block_num == (num_blocks - 1))
1668 			src_block = last_block;
1669 		else
1670 			src_block = &src[block_num * 3];
1671 		dst_block[0] = ((src_block[0] >> 2) & 0x3F);
1672 		dst_block[1] = (((src_block[0] << 4) & 0x30)
1673 				| ((src_block[1] >> 4) & 0x0F));
1674 		dst_block[2] = (((src_block[1] << 2) & 0x3C)
1675 				| ((src_block[2] >> 6) & 0x03));
1676 		dst_block[3] = (src_block[2] & 0x3F);
1677 		dst[dst_offset++] = portable_filename_chars[dst_block[0]];
1678 		dst[dst_offset++] = portable_filename_chars[dst_block[1]];
1679 		dst[dst_offset++] = portable_filename_chars[dst_block[2]];
1680 		dst[dst_offset++] = portable_filename_chars[dst_block[3]];
1681 		block_num++;
1682 	}
1683 out:
1684 	return;
1685 }
1686 
ecryptfs_max_decoded_size(size_t encoded_size)1687 static size_t ecryptfs_max_decoded_size(size_t encoded_size)
1688 {
1689 	/* Not exact; conservatively long. Every block of 4
1690 	 * encoded characters decodes into a block of 3
1691 	 * decoded characters. This segment of code provides
1692 	 * the caller with the maximum amount of allocated
1693 	 * space that @dst will need to point to in a
1694 	 * subsequent call. */
1695 	return ((encoded_size + 1) * 3) / 4;
1696 }
1697 
1698 /**
1699  * ecryptfs_decode_from_filename
1700  * @dst: If NULL, this function only sets @dst_size and returns. If
1701  *       non-NULL, this function decodes the encoded octets in @src
1702  *       into the memory that @dst points to.
1703  * @dst_size: Set to the size of the decoded string.
1704  * @src: The encoded set of octets to decode.
1705  * @src_size: The size of the encoded set of octets to decode.
1706  */
1707 static void
ecryptfs_decode_from_filename(unsigned char * dst,size_t * dst_size,const unsigned char * src,size_t src_size)1708 ecryptfs_decode_from_filename(unsigned char *dst, size_t *dst_size,
1709 			      const unsigned char *src, size_t src_size)
1710 {
1711 	u8 current_bit_offset = 0;
1712 	size_t src_byte_offset = 0;
1713 	size_t dst_byte_offset = 0;
1714 
1715 	if (!dst) {
1716 		(*dst_size) = ecryptfs_max_decoded_size(src_size);
1717 		goto out;
1718 	}
1719 	while (src_byte_offset < src_size) {
1720 		unsigned char src_byte =
1721 				filename_rev_map[(int)src[src_byte_offset]];
1722 
1723 		switch (current_bit_offset) {
1724 		case 0:
1725 			dst[dst_byte_offset] = (src_byte << 2);
1726 			current_bit_offset = 6;
1727 			break;
1728 		case 6:
1729 			dst[dst_byte_offset++] |= (src_byte >> 4);
1730 			dst[dst_byte_offset] = ((src_byte & 0xF)
1731 						 << 4);
1732 			current_bit_offset = 4;
1733 			break;
1734 		case 4:
1735 			dst[dst_byte_offset++] |= (src_byte >> 2);
1736 			dst[dst_byte_offset] = (src_byte << 6);
1737 			current_bit_offset = 2;
1738 			break;
1739 		case 2:
1740 			dst[dst_byte_offset++] |= (src_byte);
1741 			current_bit_offset = 0;
1742 			break;
1743 		}
1744 		src_byte_offset++;
1745 	}
1746 	(*dst_size) = dst_byte_offset;
1747 out:
1748 	return;
1749 }
1750 
1751 /**
1752  * ecryptfs_encrypt_and_encode_filename - converts a plaintext file name to cipher text
1753  * @encoded_name: The encrypted name
1754  * @encoded_name_size: Length of the encrypted name
1755  * @mount_crypt_stat: The crypt_stat struct associated with the file name to encode
1756  * @name: The plaintext name
1757  * @name_size: The length of the plaintext name
1758  *
1759  * Encrypts and encodes a filename into something that constitutes a
1760  * valid filename for a filesystem, with printable characters.
1761  *
1762  * We assume that we have a properly initialized crypto context,
1763  * pointed to by crypt_stat->tfm.
1764  *
1765  * Returns zero on success; non-zero on otherwise
1766  */
ecryptfs_encrypt_and_encode_filename(char ** encoded_name,size_t * encoded_name_size,struct ecryptfs_mount_crypt_stat * mount_crypt_stat,const char * name,size_t name_size)1767 int ecryptfs_encrypt_and_encode_filename(
1768 	char **encoded_name,
1769 	size_t *encoded_name_size,
1770 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
1771 	const char *name, size_t name_size)
1772 {
1773 	size_t encoded_name_no_prefix_size;
1774 	int rc = 0;
1775 
1776 	(*encoded_name) = NULL;
1777 	(*encoded_name_size) = 0;
1778 	if (mount_crypt_stat && (mount_crypt_stat->flags
1779 				     & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)) {
1780 		struct ecryptfs_filename *filename;
1781 
1782 		filename = kzalloc_obj(*filename);
1783 		if (!filename) {
1784 			rc = -ENOMEM;
1785 			goto out;
1786 		}
1787 		filename->filename = (char *)name;
1788 		filename->filename_size = name_size;
1789 		rc = ecryptfs_encrypt_filename(filename, mount_crypt_stat);
1790 		if (rc) {
1791 			ecryptfs_printk(KERN_ERR,
1792 				"Error attempting to encrypt filename; rc = [%d]\n",
1793 				rc);
1794 			kfree(filename);
1795 			goto out;
1796 		}
1797 		ecryptfs_encode_for_filename(
1798 			NULL, &encoded_name_no_prefix_size,
1799 			filename->encrypted_filename,
1800 			filename->encrypted_filename_size);
1801 		if (mount_crypt_stat->flags
1802 		    & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK)
1803 			(*encoded_name_size) =
1804 				(ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE
1805 				 + encoded_name_no_prefix_size);
1806 		else
1807 			(*encoded_name_size) =
1808 				(ECRYPTFS_FEK_ENCRYPTED_FILENAME_PREFIX_SIZE
1809 				 + encoded_name_no_prefix_size);
1810 		(*encoded_name) = kmalloc((*encoded_name_size) + 1, GFP_KERNEL);
1811 		if (!(*encoded_name)) {
1812 			rc = -ENOMEM;
1813 			kfree(filename->encrypted_filename);
1814 			kfree(filename);
1815 			goto out;
1816 		}
1817 		if (mount_crypt_stat->flags
1818 		    & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK) {
1819 			memcpy((*encoded_name),
1820 			       ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX,
1821 			       ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE);
1822 			ecryptfs_encode_for_filename(
1823 			    ((*encoded_name)
1824 			     + ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE),
1825 			    &encoded_name_no_prefix_size,
1826 			    filename->encrypted_filename,
1827 			    filename->encrypted_filename_size);
1828 			(*encoded_name_size) =
1829 				(ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE
1830 				 + encoded_name_no_prefix_size);
1831 			(*encoded_name)[(*encoded_name_size)] = '\0';
1832 		} else {
1833 			rc = -EOPNOTSUPP;
1834 		}
1835 		if (rc) {
1836 			ecryptfs_printk(KERN_ERR,
1837 				"Error attempting to encode encrypted filename; rc = [%d]\n",
1838 				rc);
1839 			kfree((*encoded_name));
1840 			(*encoded_name) = NULL;
1841 			(*encoded_name_size) = 0;
1842 		}
1843 		kfree(filename->encrypted_filename);
1844 		kfree(filename);
1845 	} else {
1846 		rc = ecryptfs_copy_filename(encoded_name,
1847 					    encoded_name_size,
1848 					    name, name_size);
1849 	}
1850 out:
1851 	return rc;
1852 }
1853 
1854 /**
1855  * ecryptfs_decode_and_decrypt_filename - converts the encoded cipher text name to decoded plaintext
1856  * @plaintext_name: The plaintext name
1857  * @plaintext_name_size: The plaintext name size
1858  * @sb: Ecryptfs's super_block
1859  * @name: The filename in cipher text
1860  * @name_size: The cipher text name size
1861  *
1862  * Decrypts and decodes the filename.
1863  *
1864  * Returns zero on error; non-zero otherwise
1865  */
ecryptfs_decode_and_decrypt_filename(char ** plaintext_name,size_t * plaintext_name_size,struct super_block * sb,const char * name,size_t name_size)1866 int ecryptfs_decode_and_decrypt_filename(char **plaintext_name,
1867 					 size_t *plaintext_name_size,
1868 					 struct super_block *sb,
1869 					 const char *name, size_t name_size)
1870 {
1871 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1872 		&ecryptfs_superblock_to_private(sb)->mount_crypt_stat;
1873 	char *decoded_name;
1874 	size_t decoded_name_size;
1875 	size_t packet_size;
1876 	int rc = 0;
1877 
1878 	if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) &&
1879 	    !(mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED)) {
1880 		if (name_is_dot_dotdot(name, name_size)) {
1881 			rc = ecryptfs_copy_filename(plaintext_name,
1882 						    plaintext_name_size,
1883 						    name, name_size);
1884 			goto out;
1885 		}
1886 
1887 		if (name_size <= ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE ||
1888 		    strncmp(name, ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX,
1889 			    ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE)) {
1890 			rc = -EINVAL;
1891 			goto out;
1892 		}
1893 
1894 		name += ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE;
1895 		name_size -= ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE;
1896 		ecryptfs_decode_from_filename(NULL, &decoded_name_size,
1897 					      name, name_size);
1898 		decoded_name = kmalloc(decoded_name_size, GFP_KERNEL);
1899 		if (!decoded_name) {
1900 			rc = -ENOMEM;
1901 			goto out;
1902 		}
1903 		ecryptfs_decode_from_filename(decoded_name, &decoded_name_size,
1904 					      name, name_size);
1905 		rc = ecryptfs_parse_tag_70_packet(plaintext_name,
1906 						  plaintext_name_size,
1907 						  &packet_size,
1908 						  mount_crypt_stat,
1909 						  decoded_name,
1910 						  decoded_name_size);
1911 		if (rc) {
1912 			ecryptfs_printk(KERN_DEBUG,
1913 					"Could not parse tag 70 packet from filename\n");
1914 			goto out_free;
1915 		}
1916 	} else {
1917 		rc = ecryptfs_copy_filename(plaintext_name,
1918 					    plaintext_name_size,
1919 					    name, name_size);
1920 		goto out;
1921 	}
1922 out_free:
1923 	kfree(decoded_name);
1924 out:
1925 	return rc;
1926 }
1927 
1928 #define ENC_NAME_MAX_BLOCKLEN_8_OR_16	143
1929 
ecryptfs_set_f_namelen(long * namelen,long lower_namelen,struct ecryptfs_mount_crypt_stat * mount_crypt_stat)1930 int ecryptfs_set_f_namelen(long *namelen, long lower_namelen,
1931 			   struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
1932 {
1933 	struct crypto_skcipher *tfm;
1934 	struct mutex *tfm_mutex;
1935 	size_t cipher_blocksize;
1936 	int rc;
1937 
1938 	if (!(mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)) {
1939 		(*namelen) = lower_namelen;
1940 		return 0;
1941 	}
1942 
1943 	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&tfm, &tfm_mutex,
1944 			mount_crypt_stat->global_default_fn_cipher_name);
1945 	if (unlikely(rc)) {
1946 		(*namelen) = 0;
1947 		return rc;
1948 	}
1949 
1950 	mutex_lock(tfm_mutex);
1951 	cipher_blocksize = crypto_skcipher_blocksize(tfm);
1952 	mutex_unlock(tfm_mutex);
1953 
1954 	/* Return an exact amount for the common cases */
1955 	if (lower_namelen == NAME_MAX
1956 	    && (cipher_blocksize == 8 || cipher_blocksize == 16)) {
1957 		(*namelen) = ENC_NAME_MAX_BLOCKLEN_8_OR_16;
1958 		return 0;
1959 	}
1960 
1961 	/* Return a safe estimate for the uncommon cases */
1962 	(*namelen) = lower_namelen;
1963 	(*namelen) -= ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE;
1964 	/* Since this is the max decoded size, subtract 1 "decoded block" len */
1965 	(*namelen) = ecryptfs_max_decoded_size(*namelen) - 3;
1966 	(*namelen) -= ECRYPTFS_TAG_70_MAX_METADATA_SIZE;
1967 	(*namelen) -= ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES;
1968 	/* Worst case is that the filename is padded nearly a full block size */
1969 	(*namelen) -= cipher_blocksize - 1;
1970 
1971 	if ((*namelen) < 0)
1972 		(*namelen) = 0;
1973 
1974 	return 0;
1975 }
1976