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