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