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