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