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