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