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