]> err.no Git - linux-2.6/blob - fs/ecryptfs/crypto.c
[PATCH] eCryptfs: Hash code to new crypto API
[linux-2.6] / 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-2006 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 <linux/fs.h>
27 #include <linux/mount.h>
28 #include <linux/pagemap.h>
29 #include <linux/random.h>
30 #include <linux/compiler.h>
31 #include <linux/key.h>
32 #include <linux/namei.h>
33 #include <linux/crypto.h>
34 #include <linux/file.h>
35 #include <linux/scatterlist.h>
36 #include "ecryptfs_kernel.h"
37
38 static int
39 ecryptfs_decrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
40                              struct page *dst_page, int dst_offset,
41                              struct page *src_page, int src_offset, int size,
42                              unsigned char *iv);
43 static int
44 ecryptfs_encrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
45                              struct page *dst_page, int dst_offset,
46                              struct page *src_page, int src_offset, int size,
47                              unsigned char *iv);
48
49 /**
50  * ecryptfs_to_hex
51  * @dst: Buffer to take hex character representation of contents of
52  *       src; must be at least of size (src_size * 2)
53  * @src: Buffer to be converted to a hex string respresentation
54  * @src_size: number of bytes to convert
55  */
56 void ecryptfs_to_hex(char *dst, char *src, size_t src_size)
57 {
58         int x;
59
60         for (x = 0; x < src_size; x++)
61                 sprintf(&dst[x * 2], "%.2x", (unsigned char)src[x]);
62 }
63
64 /**
65  * ecryptfs_from_hex
66  * @dst: Buffer to take the bytes from src hex; must be at least of
67  *       size (src_size / 2)
68  * @src: Buffer to be converted from a hex string respresentation to raw value
69  * @dst_size: size of dst buffer, or number of hex characters pairs to convert
70  */
71 void ecryptfs_from_hex(char *dst, char *src, int dst_size)
72 {
73         int x;
74         char tmp[3] = { 0, };
75
76         for (x = 0; x < dst_size; x++) {
77                 tmp[0] = src[x * 2];
78                 tmp[1] = src[x * 2 + 1];
79                 dst[x] = (unsigned char)simple_strtol(tmp, NULL, 16);
80         }
81 }
82
83 /**
84  * ecryptfs_calculate_md5 - calculates the md5 of @src
85  * @dst: Pointer to 16 bytes of allocated memory
86  * @crypt_stat: Pointer to crypt_stat struct for the current inode
87  * @src: Data to be md5'd
88  * @len: Length of @src
89  *
90  * Uses the allocated crypto context that crypt_stat references to
91  * generate the MD5 sum of the contents of src.
92  */
93 static int ecryptfs_calculate_md5(char *dst,
94                                   struct ecryptfs_crypt_stat *crypt_stat,
95                                   char *src, int len)
96 {
97         struct scatterlist sg;
98         struct hash_desc desc = {
99                 .tfm = crypt_stat->hash_tfm,
100                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
101         };
102         int rc = 0;
103
104         mutex_lock(&crypt_stat->cs_hash_tfm_mutex);
105         sg_init_one(&sg, (u8 *)src, len);
106         if (!desc.tfm) {
107                 desc.tfm = crypto_alloc_hash(ECRYPTFS_DEFAULT_HASH, 0,
108                                              CRYPTO_ALG_ASYNC);
109                 if (IS_ERR(desc.tfm)) {
110                         rc = PTR_ERR(desc.tfm);
111                         ecryptfs_printk(KERN_ERR, "Error attempting to "
112                                         "allocate crypto context; rc = [%d]\n",
113                                         rc);
114                         goto out;
115                 }
116                 crypt_stat->hash_tfm = desc.tfm;
117         }
118         crypto_hash_init(&desc);
119         crypto_hash_update(&desc, &sg, len);
120         crypto_hash_final(&desc, dst);
121         mutex_unlock(&crypt_stat->cs_hash_tfm_mutex);
122 out:
123         return rc;
124 }
125
126 /**
127  * ecryptfs_derive_iv
128  * @iv: destination for the derived iv vale
129  * @crypt_stat: Pointer to crypt_stat struct for the current inode
130  * @offset: Offset of the page whose's iv we are to derive
131  *
132  * Generate the initialization vector from the given root IV and page
133  * offset.
134  *
135  * Returns zero on success; non-zero on error.
136  */
137 static int ecryptfs_derive_iv(char *iv, struct ecryptfs_crypt_stat *crypt_stat,
138                               pgoff_t offset)
139 {
140         int rc = 0;
141         char dst[MD5_DIGEST_SIZE];
142         char src[ECRYPTFS_MAX_IV_BYTES + 16];
143
144         if (unlikely(ecryptfs_verbosity > 0)) {
145                 ecryptfs_printk(KERN_DEBUG, "root iv:\n");
146                 ecryptfs_dump_hex(crypt_stat->root_iv, crypt_stat->iv_bytes);
147         }
148         /* TODO: It is probably secure to just cast the least
149          * significant bits of the root IV into an unsigned long and
150          * add the offset to that rather than go through all this
151          * hashing business. -Halcrow */
152         memcpy(src, crypt_stat->root_iv, crypt_stat->iv_bytes);
153         memset((src + crypt_stat->iv_bytes), 0, 16);
154         snprintf((src + crypt_stat->iv_bytes), 16, "%ld", offset);
155         if (unlikely(ecryptfs_verbosity > 0)) {
156                 ecryptfs_printk(KERN_DEBUG, "source:\n");
157                 ecryptfs_dump_hex(src, (crypt_stat->iv_bytes + 16));
158         }
159         rc = ecryptfs_calculate_md5(dst, crypt_stat, src,
160                                     (crypt_stat->iv_bytes + 16));
161         if (rc) {
162                 ecryptfs_printk(KERN_WARNING, "Error attempting to compute "
163                                 "MD5 while generating IV for a page\n");
164                 goto out;
165         }
166         memcpy(iv, dst, crypt_stat->iv_bytes);
167         if (unlikely(ecryptfs_verbosity > 0)) {
168                 ecryptfs_printk(KERN_DEBUG, "derived iv:\n");
169                 ecryptfs_dump_hex(iv, crypt_stat->iv_bytes);
170         }
171 out:
172         return rc;
173 }
174
175 /**
176  * ecryptfs_init_crypt_stat
177  * @crypt_stat: Pointer to the crypt_stat struct to initialize.
178  *
179  * Initialize the crypt_stat structure.
180  */
181 void
182 ecryptfs_init_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
183 {
184         memset((void *)crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
185         mutex_init(&crypt_stat->cs_mutex);
186         mutex_init(&crypt_stat->cs_tfm_mutex);
187         mutex_init(&crypt_stat->cs_hash_tfm_mutex);
188         ECRYPTFS_SET_FLAG(crypt_stat->flags, ECRYPTFS_STRUCT_INITIALIZED);
189 }
190
191 /**
192  * ecryptfs_destruct_crypt_stat
193  * @crypt_stat: Pointer to the crypt_stat struct to initialize.
194  *
195  * Releases all memory associated with a crypt_stat struct.
196  */
197 void ecryptfs_destruct_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
198 {
199         if (crypt_stat->tfm)
200                 crypto_free_tfm(crypt_stat->tfm);
201         if (crypt_stat->hash_tfm)
202                 crypto_free_hash(crypt_stat->hash_tfm);
203         memset(crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
204 }
205
206 void ecryptfs_destruct_mount_crypt_stat(
207         struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
208 {
209         if (mount_crypt_stat->global_auth_tok_key)
210                 key_put(mount_crypt_stat->global_auth_tok_key);
211         if (mount_crypt_stat->global_key_tfm)
212                 crypto_free_tfm(mount_crypt_stat->global_key_tfm);
213         memset(mount_crypt_stat, 0, sizeof(struct ecryptfs_mount_crypt_stat));
214 }
215
216 /**
217  * virt_to_scatterlist
218  * @addr: Virtual address
219  * @size: Size of data; should be an even multiple of the block size
220  * @sg: Pointer to scatterlist array; set to NULL to obtain only
221  *      the number of scatterlist structs required in array
222  * @sg_size: Max array size
223  *
224  * Fills in a scatterlist array with page references for a passed
225  * virtual address.
226  *
227  * Returns the number of scatterlist structs in array used
228  */
229 int virt_to_scatterlist(const void *addr, int size, struct scatterlist *sg,
230                         int sg_size)
231 {
232         int i = 0;
233         struct page *pg;
234         int offset;
235         int remainder_of_page;
236
237         while (size > 0 && i < sg_size) {
238                 pg = virt_to_page(addr);
239                 offset = offset_in_page(addr);
240                 if (sg) {
241                         sg[i].page = pg;
242                         sg[i].offset = offset;
243                 }
244                 remainder_of_page = PAGE_CACHE_SIZE - offset;
245                 if (size >= remainder_of_page) {
246                         if (sg)
247                                 sg[i].length = remainder_of_page;
248                         addr += remainder_of_page;
249                         size -= remainder_of_page;
250                 } else {
251                         if (sg)
252                                 sg[i].length = size;
253                         addr += size;
254                         size = 0;
255                 }
256                 i++;
257         }
258         if (size > 0)
259                 return -ENOMEM;
260         return i;
261 }
262
263 /**
264  * encrypt_scatterlist
265  * @crypt_stat: Pointer to the crypt_stat struct to initialize.
266  * @dest_sg: Destination of encrypted data
267  * @src_sg: Data to be encrypted
268  * @size: Length of data to be encrypted
269  * @iv: iv to use during encryption
270  *
271  * Returns the number of bytes encrypted; negative value on error
272  */
273 static int encrypt_scatterlist(struct ecryptfs_crypt_stat *crypt_stat,
274                                struct scatterlist *dest_sg,
275                                struct scatterlist *src_sg, int size,
276                                unsigned char *iv)
277 {
278         int rc = 0;
279
280         BUG_ON(!crypt_stat || !crypt_stat->tfm
281                || !ECRYPTFS_CHECK_FLAG(crypt_stat->flags,
282                                        ECRYPTFS_STRUCT_INITIALIZED));
283         if (unlikely(ecryptfs_verbosity > 0)) {
284                 ecryptfs_printk(KERN_DEBUG, "Key size [%d]; key:\n",
285                                 crypt_stat->key_size);
286                 ecryptfs_dump_hex(crypt_stat->key,
287                                   crypt_stat->key_size);
288         }
289         /* Consider doing this once, when the file is opened */
290         mutex_lock(&crypt_stat->cs_tfm_mutex);
291         rc = crypto_cipher_setkey(crypt_stat->tfm, crypt_stat->key,
292                                   crypt_stat->key_size);
293         if (rc) {
294                 ecryptfs_printk(KERN_ERR, "Error setting key; rc = [%d]\n",
295                                 rc);
296                 mutex_unlock(&crypt_stat->cs_tfm_mutex);
297                 rc = -EINVAL;
298                 goto out;
299         }
300         ecryptfs_printk(KERN_DEBUG, "Encrypting [%d] bytes.\n", size);
301         crypto_cipher_encrypt_iv(crypt_stat->tfm, dest_sg, src_sg, size, iv);
302         mutex_unlock(&crypt_stat->cs_tfm_mutex);
303 out:
304         return rc;
305 }
306
307 static void
308 ecryptfs_extent_to_lwr_pg_idx_and_offset(unsigned long *lower_page_idx,
309                                          int *byte_offset,
310                                          struct ecryptfs_crypt_stat *crypt_stat,
311                                          unsigned long extent_num)
312 {
313         unsigned long lower_extent_num;
314         int extents_occupied_by_headers_at_front;
315         int bytes_occupied_by_headers_at_front;
316         int extent_offset;
317         int extents_per_page;
318
319         bytes_occupied_by_headers_at_front =
320                 ( crypt_stat->header_extent_size
321                   * crypt_stat->num_header_extents_at_front );
322         extents_occupied_by_headers_at_front =
323                 ( bytes_occupied_by_headers_at_front
324                   / crypt_stat->extent_size );
325         lower_extent_num = extents_occupied_by_headers_at_front + extent_num;
326         extents_per_page = PAGE_CACHE_SIZE / crypt_stat->extent_size;
327         (*lower_page_idx) = lower_extent_num / extents_per_page;
328         extent_offset = lower_extent_num % extents_per_page;
329         (*byte_offset) = extent_offset * crypt_stat->extent_size;
330         ecryptfs_printk(KERN_DEBUG, " * crypt_stat->header_extent_size = "
331                         "[%d]\n", crypt_stat->header_extent_size);
332         ecryptfs_printk(KERN_DEBUG, " * crypt_stat->"
333                         "num_header_extents_at_front = [%d]\n",
334                         crypt_stat->num_header_extents_at_front);
335         ecryptfs_printk(KERN_DEBUG, " * extents_occupied_by_headers_at_"
336                         "front = [%d]\n", extents_occupied_by_headers_at_front);
337         ecryptfs_printk(KERN_DEBUG, " * lower_extent_num = [0x%.16x]\n",
338                         lower_extent_num);
339         ecryptfs_printk(KERN_DEBUG, " * extents_per_page = [%d]\n",
340                         extents_per_page);
341         ecryptfs_printk(KERN_DEBUG, " * (*lower_page_idx) = [0x%.16x]\n",
342                         (*lower_page_idx));
343         ecryptfs_printk(KERN_DEBUG, " * extent_offset = [%d]\n",
344                         extent_offset);
345         ecryptfs_printk(KERN_DEBUG, " * (*byte_offset) = [%d]\n",
346                         (*byte_offset));
347 }
348
349 static int ecryptfs_write_out_page(struct ecryptfs_page_crypt_context *ctx,
350                                    struct page *lower_page,
351                                    struct inode *lower_inode,
352                                    int byte_offset_in_page, int bytes_to_write)
353 {
354         int rc = 0;
355
356         if (ctx->mode == ECRYPTFS_PREPARE_COMMIT_MODE) {
357                 rc = ecryptfs_commit_lower_page(lower_page, lower_inode,
358                                                 ctx->param.lower_file,
359                                                 byte_offset_in_page,
360                                                 bytes_to_write);
361                 if (rc) {
362                         ecryptfs_printk(KERN_ERR, "Error calling lower "
363                                         "commit; rc = [%d]\n", rc);
364                         goto out;
365                 }
366         } else {
367                 rc = ecryptfs_writepage_and_release_lower_page(lower_page,
368                                                                lower_inode,
369                                                                ctx->param.wbc);
370                 if (rc) {
371                         ecryptfs_printk(KERN_ERR, "Error calling lower "
372                                         "writepage(); rc = [%d]\n", rc);
373                         goto out;
374                 }
375         }
376 out:
377         return rc;
378 }
379
380 static int ecryptfs_read_in_page(struct ecryptfs_page_crypt_context *ctx,
381                                  struct page **lower_page,
382                                  struct inode *lower_inode,
383                                  unsigned long lower_page_idx,
384                                  int byte_offset_in_page)
385 {
386         int rc = 0;
387
388         if (ctx->mode == ECRYPTFS_PREPARE_COMMIT_MODE) {
389                 /* TODO: Limit this to only the data extents that are
390                  * needed */
391                 rc = ecryptfs_get_lower_page(lower_page, lower_inode,
392                                              ctx->param.lower_file,
393                                              lower_page_idx,
394                                              byte_offset_in_page,
395                                              (PAGE_CACHE_SIZE
396                                               - byte_offset_in_page));
397                 if (rc) {
398                         ecryptfs_printk(
399                                 KERN_ERR, "Error attempting to grab, map, "
400                                 "and prepare_write lower page with index "
401                                 "[0x%.16x]; rc = [%d]\n", lower_page_idx, rc);
402                         goto out;
403                 }
404         } else {
405                 rc = ecryptfs_grab_and_map_lower_page(lower_page, NULL,
406                                                       lower_inode,
407                                                       lower_page_idx);
408                 if (rc) {
409                         ecryptfs_printk(
410                                 KERN_ERR, "Error attempting to grab and map "
411                                 "lower page with index [0x%.16x]; rc = [%d]\n",
412                                 lower_page_idx, rc);
413                         goto out;
414                 }
415         }
416 out:
417         return rc;
418 }
419
420 /**
421  * ecryptfs_encrypt_page
422  * @ctx: The context of the page
423  *
424  * Encrypt an eCryptfs page. This is done on a per-extent basis. Note
425  * that eCryptfs pages may straddle the lower pages -- for instance,
426  * if the file was created on a machine with an 8K page size
427  * (resulting in an 8K header), and then the file is copied onto a
428  * host with a 32K page size, then when reading page 0 of the eCryptfs
429  * file, 24K of page 0 of the lower file will be read and decrypted,
430  * and then 8K of page 1 of the lower file will be read and decrypted.
431  *
432  * The actual operations performed on each page depends on the
433  * contents of the ecryptfs_page_crypt_context struct.
434  *
435  * Returns zero on success; negative on error
436  */
437 int ecryptfs_encrypt_page(struct ecryptfs_page_crypt_context *ctx)
438 {
439         char extent_iv[ECRYPTFS_MAX_IV_BYTES];
440         unsigned long base_extent;
441         unsigned long extent_offset = 0;
442         unsigned long lower_page_idx = 0;
443         unsigned long prior_lower_page_idx = 0;
444         struct page *lower_page;
445         struct inode *lower_inode;
446         struct ecryptfs_inode_info *inode_info;
447         struct ecryptfs_crypt_stat *crypt_stat;
448         int rc = 0;
449         int lower_byte_offset = 0;
450         int orig_byte_offset = 0;
451         int num_extents_per_page;
452 #define ECRYPTFS_PAGE_STATE_UNREAD    0
453 #define ECRYPTFS_PAGE_STATE_READ      1
454 #define ECRYPTFS_PAGE_STATE_MODIFIED  2
455 #define ECRYPTFS_PAGE_STATE_WRITTEN   3
456         int page_state;
457
458         lower_inode = ecryptfs_inode_to_lower(ctx->page->mapping->host);
459         inode_info = ecryptfs_inode_to_private(ctx->page->mapping->host);
460         crypt_stat = &inode_info->crypt_stat;
461         if (!ECRYPTFS_CHECK_FLAG(crypt_stat->flags, ECRYPTFS_ENCRYPTED)) {
462                 rc = ecryptfs_copy_page_to_lower(ctx->page, lower_inode,
463                                                  ctx->param.lower_file);
464                 if (rc)
465                         ecryptfs_printk(KERN_ERR, "Error attempting to copy "
466                                         "page at index [0x%.16x]\n",
467                                         ctx->page->index);
468                 goto out;
469         }
470         num_extents_per_page = PAGE_CACHE_SIZE / crypt_stat->extent_size;
471         base_extent = (ctx->page->index * num_extents_per_page);
472         page_state = ECRYPTFS_PAGE_STATE_UNREAD;
473         while (extent_offset < num_extents_per_page) {
474                 ecryptfs_extent_to_lwr_pg_idx_and_offset(
475                         &lower_page_idx, &lower_byte_offset, crypt_stat,
476                         (base_extent + extent_offset));
477                 if (prior_lower_page_idx != lower_page_idx
478                     && page_state == ECRYPTFS_PAGE_STATE_MODIFIED) {
479                         rc = ecryptfs_write_out_page(ctx, lower_page,
480                                                      lower_inode,
481                                                      orig_byte_offset,
482                                                      (PAGE_CACHE_SIZE
483                                                       - orig_byte_offset));
484                         if (rc) {
485                                 ecryptfs_printk(KERN_ERR, "Error attempting "
486                                                 "to write out page; rc = [%d]"
487                                                 "\n", rc);
488                                 goto out;
489                         }
490                         page_state = ECRYPTFS_PAGE_STATE_WRITTEN;
491                 }
492                 if (page_state == ECRYPTFS_PAGE_STATE_UNREAD
493                     || page_state == ECRYPTFS_PAGE_STATE_WRITTEN) {
494                         rc = ecryptfs_read_in_page(ctx, &lower_page,
495                                                    lower_inode, lower_page_idx,
496                                                    lower_byte_offset);
497                         if (rc) {
498                                 ecryptfs_printk(KERN_ERR, "Error attempting "
499                                                 "to read in lower page with "
500                                                 "index [0x%.16x]; rc = [%d]\n",
501                                                 lower_page_idx, rc);
502                                 goto out;
503                         }
504                         orig_byte_offset = lower_byte_offset;
505                         prior_lower_page_idx = lower_page_idx;
506                         page_state = ECRYPTFS_PAGE_STATE_READ;
507                 }
508                 BUG_ON(!(page_state == ECRYPTFS_PAGE_STATE_MODIFIED
509                          || page_state == ECRYPTFS_PAGE_STATE_READ));
510                 rc = ecryptfs_derive_iv(extent_iv, crypt_stat,
511                                         (base_extent + extent_offset));
512                 if (rc) {
513                         ecryptfs_printk(KERN_ERR, "Error attempting to "
514                                         "derive IV for extent [0x%.16x]; "
515                                         "rc = [%d]\n",
516                                         (base_extent + extent_offset), rc);
517                         goto out;
518                 }
519                 if (unlikely(ecryptfs_verbosity > 0)) {
520                         ecryptfs_printk(KERN_DEBUG, "Encrypting extent "
521                                         "with iv:\n");
522                         ecryptfs_dump_hex(extent_iv, crypt_stat->iv_bytes);
523                         ecryptfs_printk(KERN_DEBUG, "First 8 bytes before "
524                                         "encryption:\n");
525                         ecryptfs_dump_hex((char *)
526                                           (page_address(ctx->page)
527                                            + (extent_offset
528                                               * crypt_stat->extent_size)), 8);
529                 }
530                 rc = ecryptfs_encrypt_page_offset(
531                         crypt_stat, lower_page, lower_byte_offset, ctx->page,
532                         (extent_offset * crypt_stat->extent_size),
533                         crypt_stat->extent_size, extent_iv);
534                 ecryptfs_printk(KERN_DEBUG, "Encrypt extent [0x%.16x]; "
535                                 "rc = [%d]\n",
536                                 (base_extent + extent_offset), rc);
537                 if (unlikely(ecryptfs_verbosity > 0)) {
538                         ecryptfs_printk(KERN_DEBUG, "First 8 bytes after "
539                                         "encryption:\n");
540                         ecryptfs_dump_hex((char *)(page_address(lower_page)
541                                                    + lower_byte_offset), 8);
542                 }
543                 page_state = ECRYPTFS_PAGE_STATE_MODIFIED;
544                 extent_offset++;
545         }
546         BUG_ON(orig_byte_offset != 0);
547         rc = ecryptfs_write_out_page(ctx, lower_page, lower_inode, 0,
548                                      (lower_byte_offset
549                                       + crypt_stat->extent_size));
550         if (rc) {
551                 ecryptfs_printk(KERN_ERR, "Error attempting to write out "
552                                 "page; rc = [%d]\n", rc);
553                                 goto out;
554         }
555 out:
556         return rc;
557 }
558
559 /**
560  * ecryptfs_decrypt_page
561  * @file: The ecryptfs file
562  * @page: The page in ecryptfs to decrypt
563  *
564  * Decrypt an eCryptfs page. This is done on a per-extent basis. Note
565  * that eCryptfs pages may straddle the lower pages -- for instance,
566  * if the file was created on a machine with an 8K page size
567  * (resulting in an 8K header), and then the file is copied onto a
568  * host with a 32K page size, then when reading page 0 of the eCryptfs
569  * file, 24K of page 0 of the lower file will be read and decrypted,
570  * and then 8K of page 1 of the lower file will be read and decrypted.
571  *
572  * Returns zero on success; negative on error
573  */
574 int ecryptfs_decrypt_page(struct file *file, struct page *page)
575 {
576         char extent_iv[ECRYPTFS_MAX_IV_BYTES];
577         unsigned long base_extent;
578         unsigned long extent_offset = 0;
579         unsigned long lower_page_idx = 0;
580         unsigned long prior_lower_page_idx = 0;
581         struct page *lower_page;
582         char *lower_page_virt = NULL;
583         struct inode *lower_inode;
584         struct ecryptfs_crypt_stat *crypt_stat;
585         int rc = 0;
586         int byte_offset;
587         int num_extents_per_page;
588         int page_state;
589
590         crypt_stat = &(ecryptfs_inode_to_private(
591                                page->mapping->host)->crypt_stat);
592         lower_inode = ecryptfs_inode_to_lower(page->mapping->host);
593         if (!ECRYPTFS_CHECK_FLAG(crypt_stat->flags, ECRYPTFS_ENCRYPTED)) {
594                 rc = ecryptfs_do_readpage(file, page, page->index);
595                 if (rc)
596                         ecryptfs_printk(KERN_ERR, "Error attempting to copy "
597                                         "page at index [0x%.16x]\n",
598                                         page->index);
599                 goto out;
600         }
601         num_extents_per_page = PAGE_CACHE_SIZE / crypt_stat->extent_size;
602         base_extent = (page->index * num_extents_per_page);
603         lower_page_virt = kmem_cache_alloc(ecryptfs_lower_page_cache,
604                                            SLAB_KERNEL);
605         if (!lower_page_virt) {
606                 rc = -ENOMEM;
607                 ecryptfs_printk(KERN_ERR, "Error getting page for encrypted "
608                                 "lower page(s)\n");
609                 goto out;
610         }
611         lower_page = virt_to_page(lower_page_virt);
612         page_state = ECRYPTFS_PAGE_STATE_UNREAD;
613         while (extent_offset < num_extents_per_page) {
614                 ecryptfs_extent_to_lwr_pg_idx_and_offset(
615                         &lower_page_idx, &byte_offset, crypt_stat,
616                         (base_extent + extent_offset));
617                 if (prior_lower_page_idx != lower_page_idx
618                     || page_state == ECRYPTFS_PAGE_STATE_UNREAD) {
619                         rc = ecryptfs_do_readpage(file, lower_page,
620                                                   lower_page_idx);
621                         if (rc) {
622                                 ecryptfs_printk(KERN_ERR, "Error reading "
623                                                 "lower encrypted page; rc = "
624                                                 "[%d]\n", rc);
625                                 goto out;
626                         }
627                         prior_lower_page_idx = lower_page_idx;
628                         page_state = ECRYPTFS_PAGE_STATE_READ;
629                 }
630                 rc = ecryptfs_derive_iv(extent_iv, crypt_stat,
631                                         (base_extent + extent_offset));
632                 if (rc) {
633                         ecryptfs_printk(KERN_ERR, "Error attempting to "
634                                         "derive IV for extent [0x%.16x]; rc = "
635                                         "[%d]\n",
636                                         (base_extent + extent_offset), rc);
637                         goto out;
638                 }
639                 if (unlikely(ecryptfs_verbosity > 0)) {
640                         ecryptfs_printk(KERN_DEBUG, "Decrypting extent "
641                                         "with iv:\n");
642                         ecryptfs_dump_hex(extent_iv, crypt_stat->iv_bytes);
643                         ecryptfs_printk(KERN_DEBUG, "First 8 bytes before "
644                                         "decryption:\n");
645                         ecryptfs_dump_hex((lower_page_virt + byte_offset), 8);
646                 }
647                 rc = ecryptfs_decrypt_page_offset(crypt_stat, page,
648                                                   (extent_offset
649                                                    * crypt_stat->extent_size),
650                                                   lower_page, byte_offset,
651                                                   crypt_stat->extent_size,
652                                                   extent_iv);
653                 if (rc != crypt_stat->extent_size) {
654                         ecryptfs_printk(KERN_ERR, "Error attempting to "
655                                         "decrypt extent [0x%.16x]\n",
656                                         (base_extent + extent_offset));
657                         goto out;
658                 }
659                 rc = 0;
660                 if (unlikely(ecryptfs_verbosity > 0)) {
661                         ecryptfs_printk(KERN_DEBUG, "First 8 bytes after "
662                                         "decryption:\n");
663                         ecryptfs_dump_hex((char *)(page_address(page)
664                                                    + byte_offset), 8);
665                 }
666                 extent_offset++;
667         }
668 out:
669         if (lower_page_virt)
670                 kmem_cache_free(ecryptfs_lower_page_cache, lower_page_virt);
671         return rc;
672 }
673
674 /**
675  * decrypt_scatterlist
676  *
677  * Returns the number of bytes decrypted; negative value on error
678  */
679 static int decrypt_scatterlist(struct ecryptfs_crypt_stat *crypt_stat,
680                                struct scatterlist *dest_sg,
681                                struct scatterlist *src_sg, int size,
682                                unsigned char *iv)
683 {
684         int rc = 0;
685
686         /* Consider doing this once, when the file is opened */
687         mutex_lock(&crypt_stat->cs_tfm_mutex);
688         rc = crypto_cipher_setkey(crypt_stat->tfm, crypt_stat->key,
689                                   crypt_stat->key_size);
690         if (rc) {
691                 ecryptfs_printk(KERN_ERR, "Error setting key; rc = [%d]\n",
692                                 rc);
693                 mutex_unlock(&crypt_stat->cs_tfm_mutex);
694                 rc = -EINVAL;
695                 goto out;
696         }
697         ecryptfs_printk(KERN_DEBUG, "Decrypting [%d] bytes.\n", size);
698         rc = crypto_cipher_decrypt_iv(crypt_stat->tfm, dest_sg, src_sg, size,
699                                       iv);
700         mutex_unlock(&crypt_stat->cs_tfm_mutex);
701         if (rc) {
702                 ecryptfs_printk(KERN_ERR, "Error decrypting; rc = [%d]\n",
703                                 rc);
704                 goto out;
705         }
706         rc = size;
707 out:
708         return rc;
709 }
710
711 /**
712  * ecryptfs_encrypt_page_offset
713  *
714  * Returns the number of bytes encrypted
715  */
716 static int
717 ecryptfs_encrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
718                              struct page *dst_page, int dst_offset,
719                              struct page *src_page, int src_offset, int size,
720                              unsigned char *iv)
721 {
722         struct scatterlist src_sg, dst_sg;
723
724         src_sg.page = src_page;
725         src_sg.offset = src_offset;
726         src_sg.length = size;
727         dst_sg.page = dst_page;
728         dst_sg.offset = dst_offset;
729         dst_sg.length = size;
730         return encrypt_scatterlist(crypt_stat, &dst_sg, &src_sg, size, iv);
731 }
732
733 /**
734  * ecryptfs_decrypt_page_offset
735  *
736  * Returns the number of bytes decrypted
737  */
738 static int
739 ecryptfs_decrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
740                              struct page *dst_page, int dst_offset,
741                              struct page *src_page, int src_offset, int size,
742                              unsigned char *iv)
743 {
744         struct scatterlist src_sg, dst_sg;
745
746         src_sg.page = src_page;
747         src_sg.offset = src_offset;
748         src_sg.length = size;
749         dst_sg.page = dst_page;
750         dst_sg.offset = dst_offset;
751         dst_sg.length = size;
752         return decrypt_scatterlist(crypt_stat, &dst_sg, &src_sg, size, iv);
753 }
754
755 #define ECRYPTFS_MAX_SCATTERLIST_LEN 4
756
757 /**
758  * ecryptfs_init_crypt_ctx
759  * @crypt_stat: Uninitilized crypt stats structure
760  *
761  * Initialize the crypto context.
762  *
763  * TODO: Performance: Keep a cache of initialized cipher contexts;
764  * only init if needed
765  */
766 int ecryptfs_init_crypt_ctx(struct ecryptfs_crypt_stat *crypt_stat)
767 {
768         int rc = -EINVAL;
769
770         if (!crypt_stat->cipher) {
771                 ecryptfs_printk(KERN_ERR, "No cipher specified\n");
772                 goto out;
773         }
774         ecryptfs_printk(KERN_DEBUG,
775                         "Initializing cipher [%s]; strlen = [%d]; "
776                         "key_size_bits = [%d]\n",
777                         crypt_stat->cipher, (int)strlen(crypt_stat->cipher),
778                         crypt_stat->key_size << 3);
779         if (crypt_stat->tfm) {
780                 rc = 0;
781                 goto out;
782         }
783         mutex_lock(&crypt_stat->cs_tfm_mutex);
784         crypt_stat->tfm = crypto_alloc_tfm(crypt_stat->cipher,
785                                            ECRYPTFS_DEFAULT_CHAINING_MODE
786                                            | CRYPTO_TFM_REQ_WEAK_KEY);
787         mutex_unlock(&crypt_stat->cs_tfm_mutex);
788         if (!crypt_stat->tfm) {
789                 ecryptfs_printk(KERN_ERR, "cryptfs: init_crypt_ctx(): "
790                                 "Error initializing cipher [%s]\n",
791                                 crypt_stat->cipher);
792                 goto out;
793         }
794         rc = 0;
795 out:
796         return rc;
797 }
798
799 static void set_extent_mask_and_shift(struct ecryptfs_crypt_stat *crypt_stat)
800 {
801         int extent_size_tmp;
802
803         crypt_stat->extent_mask = 0xFFFFFFFF;
804         crypt_stat->extent_shift = 0;
805         if (crypt_stat->extent_size == 0)
806                 return;
807         extent_size_tmp = crypt_stat->extent_size;
808         while ((extent_size_tmp & 0x01) == 0) {
809                 extent_size_tmp >>= 1;
810                 crypt_stat->extent_mask <<= 1;
811                 crypt_stat->extent_shift++;
812         }
813 }
814
815 void ecryptfs_set_default_sizes(struct ecryptfs_crypt_stat *crypt_stat)
816 {
817         /* Default values; may be overwritten as we are parsing the
818          * packets. */
819         crypt_stat->extent_size = ECRYPTFS_DEFAULT_EXTENT_SIZE;
820         set_extent_mask_and_shift(crypt_stat);
821         crypt_stat->iv_bytes = ECRYPTFS_DEFAULT_IV_BYTES;
822         if (PAGE_CACHE_SIZE <= ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE) {
823                 crypt_stat->header_extent_size =
824                         ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
825         } else
826                 crypt_stat->header_extent_size = PAGE_CACHE_SIZE;
827         crypt_stat->num_header_extents_at_front = 1;
828 }
829
830 /**
831  * ecryptfs_compute_root_iv
832  * @crypt_stats
833  *
834  * On error, sets the root IV to all 0's.
835  */
836 int ecryptfs_compute_root_iv(struct ecryptfs_crypt_stat *crypt_stat)
837 {
838         int rc = 0;
839         char dst[MD5_DIGEST_SIZE];
840
841         BUG_ON(crypt_stat->iv_bytes > MD5_DIGEST_SIZE);
842         BUG_ON(crypt_stat->iv_bytes <= 0);
843         if (!ECRYPTFS_CHECK_FLAG(crypt_stat->flags, ECRYPTFS_KEY_VALID)) {
844                 rc = -EINVAL;
845                 ecryptfs_printk(KERN_WARNING, "Session key not valid; "
846                                 "cannot generate root IV\n");
847                 goto out;
848         }
849         rc = ecryptfs_calculate_md5(dst, crypt_stat, crypt_stat->key,
850                                     crypt_stat->key_size);
851         if (rc) {
852                 ecryptfs_printk(KERN_WARNING, "Error attempting to compute "
853                                 "MD5 while generating root IV\n");
854                 goto out;
855         }
856         memcpy(crypt_stat->root_iv, dst, crypt_stat->iv_bytes);
857 out:
858         if (rc) {
859                 memset(crypt_stat->root_iv, 0, crypt_stat->iv_bytes);
860                 ECRYPTFS_SET_FLAG(crypt_stat->flags,
861                                   ECRYPTFS_SECURITY_WARNING);
862         }
863         return rc;
864 }
865
866 static void ecryptfs_generate_new_key(struct ecryptfs_crypt_stat *crypt_stat)
867 {
868         get_random_bytes(crypt_stat->key, crypt_stat->key_size);
869         ECRYPTFS_SET_FLAG(crypt_stat->flags, ECRYPTFS_KEY_VALID);
870         ecryptfs_compute_root_iv(crypt_stat);
871         if (unlikely(ecryptfs_verbosity > 0)) {
872                 ecryptfs_printk(KERN_DEBUG, "Generated new session key:\n");
873                 ecryptfs_dump_hex(crypt_stat->key,
874                                   crypt_stat->key_size);
875         }
876 }
877
878 /**
879  * ecryptfs_set_default_crypt_stat_vals
880  * @crypt_stat
881  *
882  * Default values in the event that policy does not override them.
883  */
884 static void ecryptfs_set_default_crypt_stat_vals(
885         struct ecryptfs_crypt_stat *crypt_stat,
886         struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
887 {
888         ecryptfs_set_default_sizes(crypt_stat);
889         strcpy(crypt_stat->cipher, ECRYPTFS_DEFAULT_CIPHER);
890         crypt_stat->key_size = ECRYPTFS_DEFAULT_KEY_BYTES;
891         ECRYPTFS_CLEAR_FLAG(crypt_stat->flags, ECRYPTFS_KEY_VALID);
892         crypt_stat->file_version = ECRYPTFS_FILE_VERSION;
893         crypt_stat->mount_crypt_stat = mount_crypt_stat;
894 }
895
896 /**
897  * ecryptfs_new_file_context
898  * @ecryptfs_dentry
899  *
900  * If the crypto context for the file has not yet been established,
901  * this is where we do that.  Establishing a new crypto context
902  * involves the following decisions:
903  *  - What cipher to use?
904  *  - What set of authentication tokens to use?
905  * Here we just worry about getting enough information into the
906  * authentication tokens so that we know that they are available.
907  * We associate the available authentication tokens with the new file
908  * via the set of signatures in the crypt_stat struct.  Later, when
909  * the headers are actually written out, we may again defer to
910  * userspace to perform the encryption of the session key; for the
911  * foreseeable future, this will be the case with public key packets.
912  *
913  * Returns zero on success; non-zero otherwise
914  */
915 /* Associate an authentication token(s) with the file */
916 int ecryptfs_new_file_context(struct dentry *ecryptfs_dentry)
917 {
918         int rc = 0;
919         struct ecryptfs_crypt_stat *crypt_stat =
920             &ecryptfs_inode_to_private(ecryptfs_dentry->d_inode)->crypt_stat;
921         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
922             &ecryptfs_superblock_to_private(
923                     ecryptfs_dentry->d_sb)->mount_crypt_stat;
924         int cipher_name_len;
925
926         ecryptfs_set_default_crypt_stat_vals(crypt_stat, mount_crypt_stat);
927         /* See if there are mount crypt options */
928         if (mount_crypt_stat->global_auth_tok) {
929                 ecryptfs_printk(KERN_DEBUG, "Initializing context for new "
930                                 "file using mount_crypt_stat\n");
931                 ECRYPTFS_SET_FLAG(crypt_stat->flags, ECRYPTFS_ENCRYPTED);
932                 ECRYPTFS_SET_FLAG(crypt_stat->flags, ECRYPTFS_KEY_VALID);
933                 memcpy(crypt_stat->keysigs[crypt_stat->num_keysigs++],
934                        mount_crypt_stat->global_auth_tok_sig,
935                        ECRYPTFS_SIG_SIZE_HEX);
936                 cipher_name_len =
937                     strlen(mount_crypt_stat->global_default_cipher_name);
938                 memcpy(crypt_stat->cipher,
939                        mount_crypt_stat->global_default_cipher_name,
940                        cipher_name_len);
941                 crypt_stat->cipher[cipher_name_len] = '\0';
942                 crypt_stat->key_size =
943                         mount_crypt_stat->global_default_cipher_key_size;
944                 ecryptfs_generate_new_key(crypt_stat);
945         } else
946                 /* We should not encounter this scenario since we
947                  * should detect lack of global_auth_tok at mount time
948                  * TODO: Applies to 0.1 release only; remove in future
949                  * release */
950                 BUG();
951         rc = ecryptfs_init_crypt_ctx(crypt_stat);
952         if (rc)
953                 ecryptfs_printk(KERN_ERR, "Error initializing cryptographic "
954                                 "context for cipher [%s]: rc = [%d]\n",
955                                 crypt_stat->cipher, rc);
956         return rc;
957 }
958
959 /**
960  * contains_ecryptfs_marker - check for the ecryptfs marker
961  * @data: The data block in which to check
962  *
963  * Returns one if marker found; zero if not found
964  */
965 int contains_ecryptfs_marker(char *data)
966 {
967         u32 m_1, m_2;
968
969         memcpy(&m_1, data, 4);
970         m_1 = be32_to_cpu(m_1);
971         memcpy(&m_2, (data + 4), 4);
972         m_2 = be32_to_cpu(m_2);
973         if ((m_1 ^ MAGIC_ECRYPTFS_MARKER) == m_2)
974                 return 1;
975         ecryptfs_printk(KERN_DEBUG, "m_1 = [0x%.8x]; m_2 = [0x%.8x]; "
976                         "MAGIC_ECRYPTFS_MARKER = [0x%.8x]\n", m_1, m_2,
977                         MAGIC_ECRYPTFS_MARKER);
978         ecryptfs_printk(KERN_DEBUG, "(m_1 ^ MAGIC_ECRYPTFS_MARKER) = "
979                         "[0x%.8x]\n", (m_1 ^ MAGIC_ECRYPTFS_MARKER));
980         return 0;
981 }
982
983 struct ecryptfs_flag_map_elem {
984         u32 file_flag;
985         u32 local_flag;
986 };
987
988 /* Add support for additional flags by adding elements here. */
989 static struct ecryptfs_flag_map_elem ecryptfs_flag_map[] = {
990         {0x00000001, ECRYPTFS_ENABLE_HMAC},
991         {0x00000002, ECRYPTFS_ENCRYPTED}
992 };
993
994 /**
995  * ecryptfs_process_flags
996  * @crypt_stat
997  * @page_virt: Source data to be parsed
998  * @bytes_read: Updated with the number of bytes read
999  *
1000  * Returns zero on success; non-zero if the flag set is invalid
1001  */
1002 static int ecryptfs_process_flags(struct ecryptfs_crypt_stat *crypt_stat,
1003                                   char *page_virt, int *bytes_read)
1004 {
1005         int rc = 0;
1006         int i;
1007         u32 flags;
1008
1009         memcpy(&flags, page_virt, 4);
1010         flags = be32_to_cpu(flags);
1011         for (i = 0; i < ((sizeof(ecryptfs_flag_map)
1012                           / sizeof(struct ecryptfs_flag_map_elem))); i++)
1013                 if (flags & ecryptfs_flag_map[i].file_flag) {
1014                         ECRYPTFS_SET_FLAG(crypt_stat->flags,
1015                                           ecryptfs_flag_map[i].local_flag);
1016                 } else
1017                         ECRYPTFS_CLEAR_FLAG(crypt_stat->flags,
1018                                             ecryptfs_flag_map[i].local_flag);
1019         /* Version is in top 8 bits of the 32-bit flag vector */
1020         crypt_stat->file_version = ((flags >> 24) & 0xFF);
1021         (*bytes_read) = 4;
1022         return rc;
1023 }
1024
1025 /**
1026  * write_ecryptfs_marker
1027  * @page_virt: The pointer to in a page to begin writing the marker
1028  * @written: Number of bytes written
1029  *
1030  * Marker = 0x3c81b7f5
1031  */
1032 static void write_ecryptfs_marker(char *page_virt, size_t *written)
1033 {
1034         u32 m_1, m_2;
1035
1036         get_random_bytes(&m_1, (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
1037         m_2 = (m_1 ^ MAGIC_ECRYPTFS_MARKER);
1038         m_1 = cpu_to_be32(m_1);
1039         memcpy(page_virt, &m_1, (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
1040         m_2 = cpu_to_be32(m_2);
1041         memcpy(page_virt + (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2), &m_2,
1042                (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
1043         (*written) = MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
1044 }
1045
1046 static void
1047 write_ecryptfs_flags(char *page_virt, struct ecryptfs_crypt_stat *crypt_stat,
1048                      size_t *written)
1049 {
1050         u32 flags = 0;
1051         int i;
1052
1053         for (i = 0; i < ((sizeof(ecryptfs_flag_map)
1054                           / sizeof(struct ecryptfs_flag_map_elem))); i++)
1055                 if (ECRYPTFS_CHECK_FLAG(crypt_stat->flags,
1056                                         ecryptfs_flag_map[i].local_flag))
1057                         flags |= ecryptfs_flag_map[i].file_flag;
1058         /* Version is in top 8 bits of the 32-bit flag vector */
1059         flags |= ((((u8)crypt_stat->file_version) << 24) & 0xFF000000);
1060         flags = cpu_to_be32(flags);
1061         memcpy(page_virt, &flags, 4);
1062         (*written) = 4;
1063 }
1064
1065 struct ecryptfs_cipher_code_str_map_elem {
1066         char cipher_str[16];
1067         u16 cipher_code;
1068 };
1069
1070 /* Add support for additional ciphers by adding elements here. The
1071  * cipher_code is whatever OpenPGP applicatoins use to identify the
1072  * ciphers. List in order of probability. */
1073 static struct ecryptfs_cipher_code_str_map_elem
1074 ecryptfs_cipher_code_str_map[] = {
1075         {"aes",RFC2440_CIPHER_AES_128 },
1076         {"blowfish", RFC2440_CIPHER_BLOWFISH},
1077         {"des3_ede", RFC2440_CIPHER_DES3_EDE},
1078         {"cast5", RFC2440_CIPHER_CAST_5},
1079         {"twofish", RFC2440_CIPHER_TWOFISH},
1080         {"cast6", RFC2440_CIPHER_CAST_6},
1081         {"aes", RFC2440_CIPHER_AES_192},
1082         {"aes", RFC2440_CIPHER_AES_256}
1083 };
1084
1085 /**
1086  * ecryptfs_code_for_cipher_string
1087  * @str: The string representing the cipher name
1088  *
1089  * Returns zero on no match, or the cipher code on match
1090  */
1091 u16 ecryptfs_code_for_cipher_string(struct ecryptfs_crypt_stat *crypt_stat)
1092 {
1093         int i;
1094         u16 code = 0;
1095         struct ecryptfs_cipher_code_str_map_elem *map =
1096                 ecryptfs_cipher_code_str_map;
1097
1098         if (strcmp(crypt_stat->cipher, "aes") == 0) {
1099                 switch (crypt_stat->key_size) {
1100                 case 16:
1101                         code = RFC2440_CIPHER_AES_128;
1102                         break;
1103                 case 24:
1104                         code = RFC2440_CIPHER_AES_192;
1105                         break;
1106                 case 32:
1107                         code = RFC2440_CIPHER_AES_256;
1108                 }
1109         } else {
1110                 for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
1111                         if (strcmp(crypt_stat->cipher, map[i].cipher_str) == 0){
1112                                 code = map[i].cipher_code;
1113                                 break;
1114                         }
1115         }
1116         return code;
1117 }
1118
1119 /**
1120  * ecryptfs_cipher_code_to_string
1121  * @str: Destination to write out the cipher name
1122  * @cipher_code: The code to convert to cipher name string
1123  *
1124  * Returns zero on success
1125  */
1126 int ecryptfs_cipher_code_to_string(char *str, u16 cipher_code)
1127 {
1128         int rc = 0;
1129         int i;
1130
1131         str[0] = '\0';
1132         for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
1133                 if (cipher_code == ecryptfs_cipher_code_str_map[i].cipher_code)
1134                         strcpy(str, ecryptfs_cipher_code_str_map[i].cipher_str);
1135         if (str[0] == '\0') {
1136                 ecryptfs_printk(KERN_WARNING, "Cipher code not recognized: "
1137                                 "[%d]\n", cipher_code);
1138                 rc = -EINVAL;
1139         }
1140         return rc;
1141 }
1142
1143 /**
1144  * ecryptfs_read_header_region
1145  * @data
1146  * @dentry
1147  * @nd
1148  *
1149  * Returns zero on success; non-zero otherwise
1150  */
1151 int ecryptfs_read_header_region(char *data, struct dentry *dentry,
1152                                 struct vfsmount *mnt)
1153 {
1154         struct file *file;
1155         mm_segment_t oldfs;
1156         int rc;
1157
1158         mnt = mntget(mnt);
1159         file = dentry_open(dentry, mnt, O_RDONLY);
1160         if (IS_ERR(file)) {
1161                 ecryptfs_printk(KERN_DEBUG, "Error opening file to "
1162                                 "read header region\n");
1163                 mntput(mnt);
1164                 rc = PTR_ERR(file);
1165                 goto out;
1166         }
1167         file->f_pos = 0;
1168         oldfs = get_fs();
1169         set_fs(get_ds());
1170         /* For releases 0.1 and 0.2, all of the header information
1171          * fits in the first data extent-sized region. */
1172         rc = file->f_op->read(file, (char __user *)data,
1173                               ECRYPTFS_DEFAULT_EXTENT_SIZE, &file->f_pos);
1174         set_fs(oldfs);
1175         fput(file);
1176         rc = 0;
1177 out:
1178         return rc;
1179 }
1180
1181 static void
1182 write_header_metadata(char *virt, struct ecryptfs_crypt_stat *crypt_stat,
1183                       size_t *written)
1184 {
1185         u32 header_extent_size;
1186         u16 num_header_extents_at_front;
1187
1188         header_extent_size = (u32)crypt_stat->header_extent_size;
1189         num_header_extents_at_front =
1190                 (u16)crypt_stat->num_header_extents_at_front;
1191         header_extent_size = cpu_to_be32(header_extent_size);
1192         memcpy(virt, &header_extent_size, 4);
1193         virt += 4;
1194         num_header_extents_at_front = cpu_to_be16(num_header_extents_at_front);
1195         memcpy(virt, &num_header_extents_at_front, 2);
1196         (*written) = 6;
1197 }
1198
1199 struct kmem_cache *ecryptfs_header_cache_0;
1200 struct kmem_cache *ecryptfs_header_cache_1;
1201 struct kmem_cache *ecryptfs_header_cache_2;
1202
1203 /**
1204  * ecryptfs_write_headers_virt
1205  * @page_virt
1206  * @crypt_stat
1207  * @ecryptfs_dentry
1208  *
1209  * Format version: 1
1210  *
1211  *   Header Extent:
1212  *     Octets 0-7:        Unencrypted file size (big-endian)
1213  *     Octets 8-15:       eCryptfs special marker
1214  *     Octets 16-19:      Flags
1215  *      Octet 16:         File format version number (between 0 and 255)
1216  *      Octets 17-18:     Reserved
1217  *      Octet 19:         Bit 1 (lsb): Reserved
1218  *                        Bit 2: Encrypted?
1219  *                        Bits 3-8: Reserved
1220  *     Octets 20-23:      Header extent size (big-endian)
1221  *     Octets 24-25:      Number of header extents at front of file
1222  *                        (big-endian)
1223  *     Octet  26:         Begin RFC 2440 authentication token packet set
1224  *   Data Extent 0:
1225  *     Lower data (CBC encrypted)
1226  *   Data Extent 1:
1227  *     Lower data (CBC encrypted)
1228  *   ...
1229  *
1230  * Returns zero on success
1231  */
1232 int ecryptfs_write_headers_virt(char *page_virt,
1233                                 struct ecryptfs_crypt_stat *crypt_stat,
1234                                 struct dentry *ecryptfs_dentry)
1235 {
1236         int rc;
1237         size_t written;
1238         size_t offset;
1239
1240         offset = ECRYPTFS_FILE_SIZE_BYTES;
1241         write_ecryptfs_marker((page_virt + offset), &written);
1242         offset += written;
1243         write_ecryptfs_flags((page_virt + offset), crypt_stat, &written);
1244         offset += written;
1245         write_header_metadata((page_virt + offset), crypt_stat, &written);
1246         offset += written;
1247         rc = ecryptfs_generate_key_packet_set((page_virt + offset), crypt_stat,
1248                                               ecryptfs_dentry, &written,
1249                                               PAGE_CACHE_SIZE - offset);
1250         if (rc)
1251                 ecryptfs_printk(KERN_WARNING, "Error generating key packet "
1252                                 "set; rc = [%d]\n", rc);
1253         return rc;
1254 }
1255
1256 /**
1257  * ecryptfs_write_headers
1258  * @lower_file: The lower file struct, which was returned from dentry_open
1259  *
1260  * Write the file headers out.  This will likely involve a userspace
1261  * callout, in which the session key is encrypted with one or more
1262  * public keys and/or the passphrase necessary to do the encryption is
1263  * retrieved via a prompt.  Exactly what happens at this point should
1264  * be policy-dependent.
1265  *
1266  * Returns zero on success; non-zero on error
1267  */
1268 int ecryptfs_write_headers(struct dentry *ecryptfs_dentry,
1269                            struct file *lower_file)
1270 {
1271         mm_segment_t oldfs;
1272         struct ecryptfs_crypt_stat *crypt_stat;
1273         char *page_virt;
1274         int current_header_page;
1275         int header_pages;
1276         int rc = 0;
1277
1278         crypt_stat = &ecryptfs_inode_to_private(
1279                 ecryptfs_dentry->d_inode)->crypt_stat;
1280         if (likely(ECRYPTFS_CHECK_FLAG(crypt_stat->flags,
1281                                        ECRYPTFS_ENCRYPTED))) {
1282                 if (!ECRYPTFS_CHECK_FLAG(crypt_stat->flags,
1283                                          ECRYPTFS_KEY_VALID)) {
1284                         ecryptfs_printk(KERN_DEBUG, "Key is "
1285                                         "invalid; bailing out\n");
1286                         rc = -EINVAL;
1287                         goto out;
1288                 }
1289         } else {
1290                 rc = -EINVAL;
1291                 ecryptfs_printk(KERN_WARNING,
1292                                 "Called with crypt_stat->encrypted == 0\n");
1293                 goto out;
1294         }
1295         /* Released in this function */
1296         page_virt = kmem_cache_alloc(ecryptfs_header_cache_0, SLAB_USER);
1297         if (!page_virt) {
1298                 ecryptfs_printk(KERN_ERR, "Out of memory\n");
1299                 rc = -ENOMEM;
1300                 goto out;
1301         }
1302         memset(page_virt, 0, PAGE_CACHE_SIZE);
1303         rc = ecryptfs_write_headers_virt(page_virt, crypt_stat,
1304                                          ecryptfs_dentry);
1305         if (unlikely(rc)) {
1306                 ecryptfs_printk(KERN_ERR, "Error whilst writing headers\n");
1307                 memset(page_virt, 0, PAGE_CACHE_SIZE);
1308                 goto out_free;
1309         }
1310         ecryptfs_printk(KERN_DEBUG,
1311                         "Writing key packet set to underlying file\n");
1312         lower_file->f_pos = 0;
1313         oldfs = get_fs();
1314         set_fs(get_ds());
1315         ecryptfs_printk(KERN_DEBUG, "Calling lower_file->f_op->"
1316                         "write() w/ header page; lower_file->f_pos = "
1317                         "[0x%.16x]\n", lower_file->f_pos);
1318         lower_file->f_op->write(lower_file, (char __user *)page_virt,
1319                                 PAGE_CACHE_SIZE, &lower_file->f_pos);
1320         header_pages = ((crypt_stat->header_extent_size
1321                          * crypt_stat->num_header_extents_at_front)
1322                         / PAGE_CACHE_SIZE);
1323         memset(page_virt, 0, PAGE_CACHE_SIZE);
1324         current_header_page = 1;
1325         while (current_header_page < header_pages) {
1326                 ecryptfs_printk(KERN_DEBUG, "Calling lower_file->f_op->"
1327                                 "write() w/ zero'd page; lower_file->f_pos = "
1328                                 "[0x%.16x]\n", lower_file->f_pos);
1329                 lower_file->f_op->write(lower_file, (char __user *)page_virt,
1330                                         PAGE_CACHE_SIZE, &lower_file->f_pos);
1331                 current_header_page++;
1332         }
1333         set_fs(oldfs);
1334         ecryptfs_printk(KERN_DEBUG,
1335                         "Done writing key packet set to underlying file.\n");
1336 out_free:
1337         kmem_cache_free(ecryptfs_header_cache_0, page_virt);
1338 out:
1339         return rc;
1340 }
1341
1342 static int parse_header_metadata(struct ecryptfs_crypt_stat *crypt_stat,
1343                                  char *virt, int *bytes_read)
1344 {
1345         int rc = 0;
1346         u32 header_extent_size;
1347         u16 num_header_extents_at_front;
1348
1349         memcpy(&header_extent_size, virt, 4);
1350         header_extent_size = be32_to_cpu(header_extent_size);
1351         virt += 4;
1352         memcpy(&num_header_extents_at_front, virt, 2);
1353         num_header_extents_at_front = be16_to_cpu(num_header_extents_at_front);
1354         crypt_stat->header_extent_size = (int)header_extent_size;
1355         crypt_stat->num_header_extents_at_front =
1356                 (int)num_header_extents_at_front;
1357         (*bytes_read) = 6;
1358         if ((crypt_stat->header_extent_size
1359              * crypt_stat->num_header_extents_at_front)
1360             < ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE) {
1361                 rc = -EINVAL;
1362                 ecryptfs_printk(KERN_WARNING, "Invalid header extent size: "
1363                                 "[%d]\n", crypt_stat->header_extent_size);
1364         }
1365         return rc;
1366 }
1367
1368 /**
1369  * set_default_header_data
1370  *
1371  * For version 0 file format; this function is only for backwards
1372  * compatibility for files created with the prior versions of
1373  * eCryptfs.
1374  */
1375 static void set_default_header_data(struct ecryptfs_crypt_stat *crypt_stat)
1376 {
1377         crypt_stat->header_extent_size = 4096;
1378         crypt_stat->num_header_extents_at_front = 1;
1379 }
1380
1381 /**
1382  * ecryptfs_read_headers_virt
1383  *
1384  * Read/parse the header data. The header format is detailed in the
1385  * comment block for the ecryptfs_write_headers_virt() function.
1386  *
1387  * Returns zero on success
1388  */
1389 static int ecryptfs_read_headers_virt(char *page_virt,
1390                                       struct ecryptfs_crypt_stat *crypt_stat,
1391                                       struct dentry *ecryptfs_dentry)
1392 {
1393         int rc = 0;
1394         int offset;
1395         int bytes_read;
1396
1397         ecryptfs_set_default_sizes(crypt_stat);
1398         crypt_stat->mount_crypt_stat = &ecryptfs_superblock_to_private(
1399                 ecryptfs_dentry->d_sb)->mount_crypt_stat;
1400         offset = ECRYPTFS_FILE_SIZE_BYTES;
1401         rc = contains_ecryptfs_marker(page_virt + offset);
1402         if (rc == 0) {
1403                 rc = -EINVAL;
1404                 goto out;
1405         }
1406         offset += MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
1407         rc = ecryptfs_process_flags(crypt_stat, (page_virt + offset),
1408                                     &bytes_read);
1409         if (rc) {
1410                 ecryptfs_printk(KERN_WARNING, "Error processing flags\n");
1411                 goto out;
1412         }
1413         if (crypt_stat->file_version > ECRYPTFS_SUPPORTED_FILE_VERSION) {
1414                 ecryptfs_printk(KERN_WARNING, "File version is [%d]; only "
1415                                 "file version [%d] is supported by this "
1416                                 "version of eCryptfs\n",
1417                                 crypt_stat->file_version,
1418                                 ECRYPTFS_SUPPORTED_FILE_VERSION);
1419                 rc = -EINVAL;
1420                 goto out;
1421         }
1422         offset += bytes_read;
1423         if (crypt_stat->file_version >= 1) {
1424                 rc = parse_header_metadata(crypt_stat, (page_virt + offset),
1425                                            &bytes_read);
1426                 if (rc) {
1427                         ecryptfs_printk(KERN_WARNING, "Error reading header "
1428                                         "metadata; rc = [%d]\n", rc);
1429                 }
1430                 offset += bytes_read;
1431         } else
1432                 set_default_header_data(crypt_stat);
1433         rc = ecryptfs_parse_packet_set(crypt_stat, (page_virt + offset),
1434                                        ecryptfs_dentry);
1435 out:
1436         return rc;
1437 }
1438
1439 /**
1440  * ecryptfs_read_headers
1441  *
1442  * Returns zero if valid headers found and parsed; non-zero otherwise
1443  */
1444 int ecryptfs_read_headers(struct dentry *ecryptfs_dentry,
1445                           struct file *lower_file)
1446 {
1447         int rc = 0;
1448         char *page_virt = NULL;
1449         mm_segment_t oldfs;
1450         ssize_t bytes_read;
1451         struct ecryptfs_crypt_stat *crypt_stat =
1452             &ecryptfs_inode_to_private(ecryptfs_dentry->d_inode)->crypt_stat;
1453
1454         /* Read the first page from the underlying file */
1455         page_virt = kmem_cache_alloc(ecryptfs_header_cache_1, SLAB_USER);
1456         if (!page_virt) {
1457                 rc = -ENOMEM;
1458                 ecryptfs_printk(KERN_ERR, "Unable to allocate page_virt\n");
1459                 goto out;
1460         }
1461         lower_file->f_pos = 0;
1462         oldfs = get_fs();
1463         set_fs(get_ds());
1464         bytes_read = lower_file->f_op->read(lower_file,
1465                                             (char __user *)page_virt,
1466                                             ECRYPTFS_DEFAULT_EXTENT_SIZE,
1467                                             &lower_file->f_pos);
1468         set_fs(oldfs);
1469         if (bytes_read != ECRYPTFS_DEFAULT_EXTENT_SIZE) {
1470                 rc = -EINVAL;
1471                 goto out;
1472         }
1473         rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
1474                                         ecryptfs_dentry);
1475         if (rc) {
1476                 ecryptfs_printk(KERN_DEBUG, "Valid eCryptfs headers not "
1477                                 "found\n");
1478                 rc = -EINVAL;
1479         }
1480 out:
1481         if (page_virt) {
1482                 memset(page_virt, 0, PAGE_CACHE_SIZE);
1483                 kmem_cache_free(ecryptfs_header_cache_1, page_virt);
1484         }
1485         return rc;
1486 }
1487
1488 /**
1489  * ecryptfs_encode_filename - converts a plaintext file name to cipher text
1490  * @crypt_stat: The crypt_stat struct associated with the file anem to encode
1491  * @name: The plaintext name
1492  * @length: The length of the plaintext
1493  * @encoded_name: The encypted name
1494  *
1495  * Encrypts and encodes a filename into something that constitutes a
1496  * valid filename for a filesystem, with printable characters.
1497  *
1498  * We assume that we have a properly initialized crypto context,
1499  * pointed to by crypt_stat->tfm.
1500  *
1501  * TODO: Implement filename decoding and decryption here, in place of
1502  * memcpy. We are keeping the framework around for now to (1)
1503  * facilitate testing of the components needed to implement filename
1504  * encryption and (2) to provide a code base from which other
1505  * developers in the community can easily implement this feature.
1506  *
1507  * Returns the length of encoded filename; negative if error
1508  */
1509 int
1510 ecryptfs_encode_filename(struct ecryptfs_crypt_stat *crypt_stat,
1511                          const char *name, int length, char **encoded_name)
1512 {
1513         int error = 0;
1514
1515         (*encoded_name) = kmalloc(length + 2, GFP_KERNEL);
1516         if (!(*encoded_name)) {
1517                 error = -ENOMEM;
1518                 goto out;
1519         }
1520         /* TODO: Filename encryption is a scheduled feature for a
1521          * future version of eCryptfs. This function is here only for
1522          * the purpose of providing a framework for other developers
1523          * to easily implement filename encryption. Hint: Replace this
1524          * memcpy() with a call to encrypt and encode the
1525          * filename, the set the length accordingly. */
1526         memcpy((void *)(*encoded_name), (void *)name, length);
1527         (*encoded_name)[length] = '\0';
1528         error = length + 1;
1529 out:
1530         return error;
1531 }
1532
1533 /**
1534  * ecryptfs_decode_filename - converts the cipher text name to plaintext
1535  * @crypt_stat: The crypt_stat struct associated with the file
1536  * @name: The filename in cipher text
1537  * @length: The length of the cipher text name
1538  * @decrypted_name: The plaintext name
1539  *
1540  * Decodes and decrypts the filename.
1541  *
1542  * We assume that we have a properly initialized crypto context,
1543  * pointed to by crypt_stat->tfm.
1544  *
1545  * TODO: Implement filename decoding and decryption here, in place of
1546  * memcpy. We are keeping the framework around for now to (1)
1547  * facilitate testing of the components needed to implement filename
1548  * encryption and (2) to provide a code base from which other
1549  * developers in the community can easily implement this feature.
1550  *
1551  * Returns the length of decoded filename; negative if error
1552  */
1553 int
1554 ecryptfs_decode_filename(struct ecryptfs_crypt_stat *crypt_stat,
1555                          const char *name, int length, char **decrypted_name)
1556 {
1557         int error = 0;
1558
1559         (*decrypted_name) = kmalloc(length + 2, GFP_KERNEL);
1560         if (!(*decrypted_name)) {
1561                 error = -ENOMEM;
1562                 goto out;
1563         }
1564         /* TODO: Filename encryption is a scheduled feature for a
1565          * future version of eCryptfs. This function is here only for
1566          * the purpose of providing a framework for other developers
1567          * to easily implement filename encryption. Hint: Replace this
1568          * memcpy() with a call to decode and decrypt the
1569          * filename, the set the length accordingly. */
1570         memcpy((void *)(*decrypted_name), (void *)name, length);
1571         (*decrypted_name)[length + 1] = '\0';   /* Only for convenience
1572                                                  * in printing out the
1573                                                  * string in debug
1574                                                  * messages */
1575         error = length;
1576 out:
1577         return error;
1578 }
1579
1580 /**
1581  * ecryptfs_process_cipher - Perform cipher initialization.
1582  * @key_tfm: Crypto context for key material, set by this function
1583  * @cipher_name: Name of the cipher
1584  * @key_size: Size of the key in bytes
1585  *
1586  * Returns zero on success. Any crypto_tfm structs allocated here
1587  * should be released by other functions, such as on a superblock put
1588  * event, regardless of whether this function succeeds for fails.
1589  */
1590 int
1591 ecryptfs_process_cipher(struct crypto_tfm **key_tfm, char *cipher_name,
1592                         size_t *key_size)
1593 {
1594         char dummy_key[ECRYPTFS_MAX_KEY_BYTES];
1595         int rc;
1596
1597         *key_tfm = NULL;
1598         if (*key_size > ECRYPTFS_MAX_KEY_BYTES) {
1599                 rc = -EINVAL;
1600                 printk(KERN_ERR "Requested key size is [%Zd] bytes; maximum "
1601                       "allowable is [%d]\n", *key_size, ECRYPTFS_MAX_KEY_BYTES);
1602                 goto out;
1603         }
1604         *key_tfm = crypto_alloc_tfm(cipher_name, CRYPTO_TFM_REQ_WEAK_KEY);
1605         if (!(*key_tfm)) {
1606                 rc = -EINVAL;
1607                 printk(KERN_ERR "Unable to allocate crypto cipher with name "
1608                        "[%s]\n", cipher_name);
1609                 goto out;
1610         }
1611         if (*key_size == 0)
1612                 *key_size = crypto_tfm_alg_max_keysize(*key_tfm);
1613         get_random_bytes(dummy_key, *key_size);
1614         rc = crypto_cipher_setkey(*key_tfm, dummy_key, *key_size);
1615         if (rc) {
1616                 printk(KERN_ERR "Error attempting to set key of size [%Zd] for "
1617                        "cipher [%s]; rc = [%d]\n", *key_size, cipher_name, rc);
1618                 rc = -EINVAL;
1619                 goto out;
1620         }
1621 out:
1622         return rc;
1623 }