2 * eCryptfs: Linux filesystem encryption layer
4 * Copyright (C) 1997-2004 Erez Zadok
5 * Copyright (C) 2001-2004 Stony Brook University
6 * Copyright (C) 2004-2007 International Business Machines Corp.
7 * Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
8 * Michael C. Thompson <mcthomps@us.ibm.com>
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.
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.
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
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"
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,
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,
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
56 void ecryptfs_to_hex(char *dst, char *src, size_t src_size)
60 for (x = 0; x < src_size; x++)
61 sprintf(&dst[x * 2], "%.2x", (unsigned char)src[x]);
66 * @dst: Buffer to take the bytes from src hex; must be at least of
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
71 void ecryptfs_from_hex(char *dst, char *src, int dst_size)
76 for (x = 0; x < dst_size; x++) {
78 tmp[1] = src[x * 2 + 1];
79 dst[x] = (unsigned char)simple_strtol(tmp, NULL, 16);
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
90 * Uses the allocated crypto context that crypt_stat references to
91 * generate the MD5 sum of the contents of src.
93 static int ecryptfs_calculate_md5(char *dst,
94 struct ecryptfs_crypt_stat *crypt_stat,
97 struct scatterlist sg;
98 struct hash_desc desc = {
99 .tfm = crypt_stat->hash_tfm,
100 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
104 mutex_lock(&crypt_stat->cs_hash_tfm_mutex);
105 sg_init_one(&sg, (u8 *)src, len);
107 desc.tfm = crypto_alloc_hash(ECRYPTFS_DEFAULT_HASH, 0,
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",
116 crypt_stat->hash_tfm = desc.tfm;
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);
126 static int ecryptfs_crypto_api_algify_cipher_name(char **algified_name,
128 char *chaining_modifier)
130 int cipher_name_len = strlen(cipher_name);
131 int chaining_modifier_len = strlen(chaining_modifier);
132 int algified_name_len;
135 algified_name_len = (chaining_modifier_len + cipher_name_len + 3);
136 (*algified_name) = kmalloc(algified_name_len, GFP_KERNEL);
137 if (!(*algified_name)) {
141 snprintf((*algified_name), algified_name_len, "%s(%s)",
142 chaining_modifier, cipher_name);
150 * @iv: destination for the derived iv vale
151 * @crypt_stat: Pointer to crypt_stat struct for the current inode
152 * @offset: Offset of the page whose's iv we are to derive
154 * Generate the initialization vector from the given root IV and page
157 * Returns zero on success; non-zero on error.
159 static int ecryptfs_derive_iv(char *iv, struct ecryptfs_crypt_stat *crypt_stat,
163 char dst[MD5_DIGEST_SIZE];
164 char src[ECRYPTFS_MAX_IV_BYTES + 16];
166 if (unlikely(ecryptfs_verbosity > 0)) {
167 ecryptfs_printk(KERN_DEBUG, "root iv:\n");
168 ecryptfs_dump_hex(crypt_stat->root_iv, crypt_stat->iv_bytes);
170 /* TODO: It is probably secure to just cast the least
171 * significant bits of the root IV into an unsigned long and
172 * add the offset to that rather than go through all this
173 * hashing business. -Halcrow */
174 memcpy(src, crypt_stat->root_iv, crypt_stat->iv_bytes);
175 memset((src + crypt_stat->iv_bytes), 0, 16);
176 snprintf((src + crypt_stat->iv_bytes), 16, "%ld", offset);
177 if (unlikely(ecryptfs_verbosity > 0)) {
178 ecryptfs_printk(KERN_DEBUG, "source:\n");
179 ecryptfs_dump_hex(src, (crypt_stat->iv_bytes + 16));
181 rc = ecryptfs_calculate_md5(dst, crypt_stat, src,
182 (crypt_stat->iv_bytes + 16));
184 ecryptfs_printk(KERN_WARNING, "Error attempting to compute "
185 "MD5 while generating IV for a page\n");
188 memcpy(iv, dst, crypt_stat->iv_bytes);
189 if (unlikely(ecryptfs_verbosity > 0)) {
190 ecryptfs_printk(KERN_DEBUG, "derived iv:\n");
191 ecryptfs_dump_hex(iv, crypt_stat->iv_bytes);
198 * ecryptfs_init_crypt_stat
199 * @crypt_stat: Pointer to the crypt_stat struct to initialize.
201 * Initialize the crypt_stat structure.
204 ecryptfs_init_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
206 memset((void *)crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
207 INIT_LIST_HEAD(&crypt_stat->keysig_list);
208 mutex_init(&crypt_stat->keysig_list_mutex);
209 mutex_init(&crypt_stat->cs_mutex);
210 mutex_init(&crypt_stat->cs_tfm_mutex);
211 mutex_init(&crypt_stat->cs_hash_tfm_mutex);
212 crypt_stat->flags |= ECRYPTFS_STRUCT_INITIALIZED;
216 * ecryptfs_destroy_crypt_stat
217 * @crypt_stat: Pointer to the crypt_stat struct to initialize.
219 * Releases all memory associated with a crypt_stat struct.
221 void ecryptfs_destroy_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
223 struct ecryptfs_key_sig *key_sig, *key_sig_tmp;
226 crypto_free_blkcipher(crypt_stat->tfm);
227 if (crypt_stat->hash_tfm)
228 crypto_free_hash(crypt_stat->hash_tfm);
229 mutex_lock(&crypt_stat->keysig_list_mutex);
230 list_for_each_entry_safe(key_sig, key_sig_tmp,
231 &crypt_stat->keysig_list, crypt_stat_list) {
232 list_del(&key_sig->crypt_stat_list);
233 kmem_cache_free(ecryptfs_key_sig_cache, key_sig);
235 mutex_unlock(&crypt_stat->keysig_list_mutex);
236 memset(crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
239 void ecryptfs_destroy_mount_crypt_stat(
240 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
242 struct ecryptfs_global_auth_tok *auth_tok, *auth_tok_tmp;
244 if (!(mount_crypt_stat->flags & ECRYPTFS_MOUNT_CRYPT_STAT_INITIALIZED))
246 mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
247 list_for_each_entry_safe(auth_tok, auth_tok_tmp,
248 &mount_crypt_stat->global_auth_tok_list,
249 mount_crypt_stat_list) {
250 list_del(&auth_tok->mount_crypt_stat_list);
251 mount_crypt_stat->num_global_auth_toks--;
252 if (auth_tok->global_auth_tok_key
253 && !(auth_tok->flags & ECRYPTFS_AUTH_TOK_INVALID))
254 key_put(auth_tok->global_auth_tok_key);
255 kmem_cache_free(ecryptfs_global_auth_tok_cache, auth_tok);
257 mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
258 memset(mount_crypt_stat, 0, sizeof(struct ecryptfs_mount_crypt_stat));
262 * virt_to_scatterlist
263 * @addr: Virtual address
264 * @size: Size of data; should be an even multiple of the block size
265 * @sg: Pointer to scatterlist array; set to NULL to obtain only
266 * the number of scatterlist structs required in array
267 * @sg_size: Max array size
269 * Fills in a scatterlist array with page references for a passed
272 * Returns the number of scatterlist structs in array used
274 int virt_to_scatterlist(const void *addr, int size, struct scatterlist *sg,
280 int remainder_of_page;
282 while (size > 0 && i < sg_size) {
283 pg = virt_to_page(addr);
284 offset = offset_in_page(addr);
287 sg[i].offset = offset;
289 remainder_of_page = PAGE_CACHE_SIZE - offset;
290 if (size >= remainder_of_page) {
292 sg[i].length = remainder_of_page;
293 addr += remainder_of_page;
294 size -= remainder_of_page;
309 * encrypt_scatterlist
310 * @crypt_stat: Pointer to the crypt_stat struct to initialize.
311 * @dest_sg: Destination of encrypted data
312 * @src_sg: Data to be encrypted
313 * @size: Length of data to be encrypted
314 * @iv: iv to use during encryption
316 * Returns the number of bytes encrypted; negative value on error
318 static int encrypt_scatterlist(struct ecryptfs_crypt_stat *crypt_stat,
319 struct scatterlist *dest_sg,
320 struct scatterlist *src_sg, int size,
323 struct blkcipher_desc desc = {
324 .tfm = crypt_stat->tfm,
326 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
330 BUG_ON(!crypt_stat || !crypt_stat->tfm
331 || !(crypt_stat->flags & ECRYPTFS_STRUCT_INITIALIZED));
332 if (unlikely(ecryptfs_verbosity > 0)) {
333 ecryptfs_printk(KERN_DEBUG, "Key size [%d]; key:\n",
334 crypt_stat->key_size);
335 ecryptfs_dump_hex(crypt_stat->key,
336 crypt_stat->key_size);
338 /* Consider doing this once, when the file is opened */
339 mutex_lock(&crypt_stat->cs_tfm_mutex);
340 rc = crypto_blkcipher_setkey(crypt_stat->tfm, crypt_stat->key,
341 crypt_stat->key_size);
343 ecryptfs_printk(KERN_ERR, "Error setting key; rc = [%d]\n",
345 mutex_unlock(&crypt_stat->cs_tfm_mutex);
349 ecryptfs_printk(KERN_DEBUG, "Encrypting [%d] bytes.\n", size);
350 crypto_blkcipher_encrypt_iv(&desc, dest_sg, src_sg, size);
351 mutex_unlock(&crypt_stat->cs_tfm_mutex);
357 ecryptfs_extent_to_lwr_pg_idx_and_offset(unsigned long *lower_page_idx,
359 struct ecryptfs_crypt_stat *crypt_stat,
360 unsigned long extent_num)
362 unsigned long lower_extent_num;
363 int extents_occupied_by_headers_at_front;
364 int bytes_occupied_by_headers_at_front;
366 int extents_per_page;
368 bytes_occupied_by_headers_at_front =
369 (crypt_stat->extent_size
370 * crypt_stat->num_header_extents_at_front);
371 extents_occupied_by_headers_at_front =
372 ( bytes_occupied_by_headers_at_front
373 / crypt_stat->extent_size );
374 lower_extent_num = extents_occupied_by_headers_at_front + extent_num;
375 extents_per_page = PAGE_CACHE_SIZE / crypt_stat->extent_size;
376 (*lower_page_idx) = lower_extent_num / extents_per_page;
377 extent_offset = lower_extent_num % extents_per_page;
378 (*byte_offset) = extent_offset * crypt_stat->extent_size;
379 ecryptfs_printk(KERN_DEBUG, " * crypt_stat->extent_size = "
380 "[%d]\n", crypt_stat->extent_size);
381 ecryptfs_printk(KERN_DEBUG, " * crypt_stat->"
382 "num_header_extents_at_front = [%d]\n",
383 crypt_stat->num_header_extents_at_front);
384 ecryptfs_printk(KERN_DEBUG, " * extents_occupied_by_headers_at_"
385 "front = [%d]\n", extents_occupied_by_headers_at_front);
386 ecryptfs_printk(KERN_DEBUG, " * lower_extent_num = [0x%.16x]\n",
388 ecryptfs_printk(KERN_DEBUG, " * extents_per_page = [%d]\n",
390 ecryptfs_printk(KERN_DEBUG, " * (*lower_page_idx) = [0x%.16x]\n",
392 ecryptfs_printk(KERN_DEBUG, " * extent_offset = [%d]\n",
394 ecryptfs_printk(KERN_DEBUG, " * (*byte_offset) = [%d]\n",
398 static int ecryptfs_write_out_page(struct ecryptfs_page_crypt_context *ctx,
399 struct page *lower_page,
400 struct inode *lower_inode,
401 int byte_offset_in_page, int bytes_to_write)
405 if (ctx->mode == ECRYPTFS_PREPARE_COMMIT_MODE) {
406 rc = ecryptfs_commit_lower_page(lower_page, lower_inode,
407 ctx->param.lower_file,
411 ecryptfs_printk(KERN_ERR, "Error calling lower "
412 "commit; rc = [%d]\n", rc);
416 rc = ecryptfs_writepage_and_release_lower_page(lower_page,
420 ecryptfs_printk(KERN_ERR, "Error calling lower "
421 "writepage(); rc = [%d]\n", rc);
429 static int ecryptfs_read_in_page(struct ecryptfs_page_crypt_context *ctx,
430 struct page **lower_page,
431 struct inode *lower_inode,
432 unsigned long lower_page_idx,
433 int byte_offset_in_page)
437 if (ctx->mode == ECRYPTFS_PREPARE_COMMIT_MODE) {
438 /* TODO: Limit this to only the data extents that are
440 rc = ecryptfs_get_lower_page(lower_page, lower_inode,
441 ctx->param.lower_file,
445 - byte_offset_in_page));
448 KERN_ERR, "Error attempting to grab, map, "
449 "and prepare_write lower page with index "
450 "[0x%.16x]; rc = [%d]\n", lower_page_idx, rc);
454 *lower_page = grab_cache_page(lower_inode->i_mapping,
456 if (!(*lower_page)) {
459 KERN_ERR, "Error attempting to grab and map "
460 "lower page with index [0x%.16x]; rc = [%d]\n",
470 * ecryptfs_encrypt_page
471 * @ctx: The context of the page
473 * Encrypt an eCryptfs page. This is done on a per-extent basis. Note
474 * that eCryptfs pages may straddle the lower pages -- for instance,
475 * if the file was created on a machine with an 8K page size
476 * (resulting in an 8K header), and then the file is copied onto a
477 * host with a 32K page size, then when reading page 0 of the eCryptfs
478 * file, 24K of page 0 of the lower file will be read and decrypted,
479 * and then 8K of page 1 of the lower file will be read and decrypted.
481 * The actual operations performed on each page depends on the
482 * contents of the ecryptfs_page_crypt_context struct.
484 * Returns zero on success; negative on error
486 int ecryptfs_encrypt_page(struct ecryptfs_page_crypt_context *ctx)
488 char extent_iv[ECRYPTFS_MAX_IV_BYTES];
489 unsigned long base_extent;
490 unsigned long extent_offset = 0;
491 unsigned long lower_page_idx = 0;
492 unsigned long prior_lower_page_idx = 0;
493 struct page *lower_page;
494 struct inode *lower_inode;
495 struct ecryptfs_inode_info *inode_info;
496 struct ecryptfs_crypt_stat *crypt_stat;
498 int lower_byte_offset = 0;
499 int orig_byte_offset = 0;
500 int num_extents_per_page;
501 #define ECRYPTFS_PAGE_STATE_UNREAD 0
502 #define ECRYPTFS_PAGE_STATE_READ 1
503 #define ECRYPTFS_PAGE_STATE_MODIFIED 2
504 #define ECRYPTFS_PAGE_STATE_WRITTEN 3
507 lower_inode = ecryptfs_inode_to_lower(ctx->page->mapping->host);
508 inode_info = ecryptfs_inode_to_private(ctx->page->mapping->host);
509 crypt_stat = &inode_info->crypt_stat;
510 if (!(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
511 rc = ecryptfs_copy_page_to_lower(ctx->page, lower_inode,
512 ctx->param.lower_file);
514 ecryptfs_printk(KERN_ERR, "Error attempting to copy "
515 "page at index [0x%.16x]\n",
519 num_extents_per_page = PAGE_CACHE_SIZE / crypt_stat->extent_size;
520 base_extent = (ctx->page->index * num_extents_per_page);
521 page_state = ECRYPTFS_PAGE_STATE_UNREAD;
522 while (extent_offset < num_extents_per_page) {
523 ecryptfs_extent_to_lwr_pg_idx_and_offset(
524 &lower_page_idx, &lower_byte_offset, crypt_stat,
525 (base_extent + extent_offset));
526 if (prior_lower_page_idx != lower_page_idx
527 && page_state == ECRYPTFS_PAGE_STATE_MODIFIED) {
528 rc = ecryptfs_write_out_page(ctx, lower_page,
532 - orig_byte_offset));
534 ecryptfs_printk(KERN_ERR, "Error attempting "
535 "to write out page; rc = [%d]"
539 page_state = ECRYPTFS_PAGE_STATE_WRITTEN;
541 if (page_state == ECRYPTFS_PAGE_STATE_UNREAD
542 || page_state == ECRYPTFS_PAGE_STATE_WRITTEN) {
543 rc = ecryptfs_read_in_page(ctx, &lower_page,
544 lower_inode, lower_page_idx,
547 ecryptfs_printk(KERN_ERR, "Error attempting "
548 "to read in lower page with "
549 "index [0x%.16x]; rc = [%d]\n",
553 orig_byte_offset = lower_byte_offset;
554 prior_lower_page_idx = lower_page_idx;
555 page_state = ECRYPTFS_PAGE_STATE_READ;
557 BUG_ON(!(page_state == ECRYPTFS_PAGE_STATE_MODIFIED
558 || page_state == ECRYPTFS_PAGE_STATE_READ));
559 rc = ecryptfs_derive_iv(extent_iv, crypt_stat,
560 (base_extent + extent_offset));
562 ecryptfs_printk(KERN_ERR, "Error attempting to "
563 "derive IV for extent [0x%.16x]; "
565 (base_extent + extent_offset), rc);
568 if (unlikely(ecryptfs_verbosity > 0)) {
569 ecryptfs_printk(KERN_DEBUG, "Encrypting extent "
571 ecryptfs_dump_hex(extent_iv, crypt_stat->iv_bytes);
572 ecryptfs_printk(KERN_DEBUG, "First 8 bytes before "
574 ecryptfs_dump_hex((char *)
575 (page_address(ctx->page)
577 * crypt_stat->extent_size)), 8);
579 rc = ecryptfs_encrypt_page_offset(
580 crypt_stat, lower_page, lower_byte_offset, ctx->page,
581 (extent_offset * crypt_stat->extent_size),
582 crypt_stat->extent_size, extent_iv);
583 ecryptfs_printk(KERN_DEBUG, "Encrypt extent [0x%.16x]; "
585 (base_extent + extent_offset), rc);
586 if (unlikely(ecryptfs_verbosity > 0)) {
587 ecryptfs_printk(KERN_DEBUG, "First 8 bytes after "
589 ecryptfs_dump_hex((char *)(page_address(lower_page)
590 + lower_byte_offset), 8);
592 page_state = ECRYPTFS_PAGE_STATE_MODIFIED;
595 BUG_ON(orig_byte_offset != 0);
596 rc = ecryptfs_write_out_page(ctx, lower_page, lower_inode, 0,
598 + crypt_stat->extent_size));
600 ecryptfs_printk(KERN_ERR, "Error attempting to write out "
601 "page; rc = [%d]\n", rc);
609 * ecryptfs_decrypt_page
610 * @file: The ecryptfs file
611 * @page: The page in ecryptfs to decrypt
613 * Decrypt an eCryptfs page. This is done on a per-extent basis. Note
614 * that eCryptfs pages may straddle the lower pages -- for instance,
615 * if the file was created on a machine with an 8K page size
616 * (resulting in an 8K header), and then the file is copied onto a
617 * host with a 32K page size, then when reading page 0 of the eCryptfs
618 * file, 24K of page 0 of the lower file will be read and decrypted,
619 * and then 8K of page 1 of the lower file will be read and decrypted.
621 * Returns zero on success; negative on error
623 int ecryptfs_decrypt_page(struct file *file, struct page *page)
625 char extent_iv[ECRYPTFS_MAX_IV_BYTES];
626 unsigned long base_extent;
627 unsigned long extent_offset = 0;
628 unsigned long lower_page_idx = 0;
629 unsigned long prior_lower_page_idx = 0;
630 struct page *lower_page;
631 char *lower_page_virt = NULL;
632 struct inode *lower_inode;
633 struct ecryptfs_crypt_stat *crypt_stat;
636 int num_extents_per_page;
639 crypt_stat = &(ecryptfs_inode_to_private(
640 page->mapping->host)->crypt_stat);
641 lower_inode = ecryptfs_inode_to_lower(page->mapping->host);
642 if (!(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
643 rc = ecryptfs_do_readpage(file, page, page->index);
645 ecryptfs_printk(KERN_ERR, "Error attempting to copy "
646 "page at index [0x%.16x]\n",
650 num_extents_per_page = PAGE_CACHE_SIZE / crypt_stat->extent_size;
651 base_extent = (page->index * num_extents_per_page);
652 lower_page_virt = kmem_cache_alloc(ecryptfs_lower_page_cache,
654 if (!lower_page_virt) {
656 ecryptfs_printk(KERN_ERR, "Error getting page for encrypted "
660 lower_page = virt_to_page(lower_page_virt);
661 page_state = ECRYPTFS_PAGE_STATE_UNREAD;
662 while (extent_offset < num_extents_per_page) {
663 ecryptfs_extent_to_lwr_pg_idx_and_offset(
664 &lower_page_idx, &byte_offset, crypt_stat,
665 (base_extent + extent_offset));
666 if (prior_lower_page_idx != lower_page_idx
667 || page_state == ECRYPTFS_PAGE_STATE_UNREAD) {
668 rc = ecryptfs_do_readpage(file, lower_page,
671 ecryptfs_printk(KERN_ERR, "Error reading "
672 "lower encrypted page; rc = "
676 prior_lower_page_idx = lower_page_idx;
677 page_state = ECRYPTFS_PAGE_STATE_READ;
679 rc = ecryptfs_derive_iv(extent_iv, crypt_stat,
680 (base_extent + extent_offset));
682 ecryptfs_printk(KERN_ERR, "Error attempting to "
683 "derive IV for extent [0x%.16x]; rc = "
685 (base_extent + extent_offset), rc);
688 if (unlikely(ecryptfs_verbosity > 0)) {
689 ecryptfs_printk(KERN_DEBUG, "Decrypting extent "
691 ecryptfs_dump_hex(extent_iv, crypt_stat->iv_bytes);
692 ecryptfs_printk(KERN_DEBUG, "First 8 bytes before "
694 ecryptfs_dump_hex((lower_page_virt + byte_offset), 8);
696 rc = ecryptfs_decrypt_page_offset(crypt_stat, page,
698 * crypt_stat->extent_size),
699 lower_page, byte_offset,
700 crypt_stat->extent_size,
702 if (rc != crypt_stat->extent_size) {
703 ecryptfs_printk(KERN_ERR, "Error attempting to "
704 "decrypt extent [0x%.16x]\n",
705 (base_extent + extent_offset));
709 if (unlikely(ecryptfs_verbosity > 0)) {
710 ecryptfs_printk(KERN_DEBUG, "First 8 bytes after "
712 ecryptfs_dump_hex((char *)(page_address(page)
719 kmem_cache_free(ecryptfs_lower_page_cache, lower_page_virt);
724 * decrypt_scatterlist
725 * @crypt_stat: Cryptographic context
726 * @dest_sg: The destination scatterlist to decrypt into
727 * @src_sg: The source scatterlist to decrypt from
728 * @size: The number of bytes to decrypt
729 * @iv: The initialization vector to use for the decryption
731 * Returns the number of bytes decrypted; negative value on error
733 static int decrypt_scatterlist(struct ecryptfs_crypt_stat *crypt_stat,
734 struct scatterlist *dest_sg,
735 struct scatterlist *src_sg, int size,
738 struct blkcipher_desc desc = {
739 .tfm = crypt_stat->tfm,
741 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
745 /* Consider doing this once, when the file is opened */
746 mutex_lock(&crypt_stat->cs_tfm_mutex);
747 rc = crypto_blkcipher_setkey(crypt_stat->tfm, crypt_stat->key,
748 crypt_stat->key_size);
750 ecryptfs_printk(KERN_ERR, "Error setting key; rc = [%d]\n",
752 mutex_unlock(&crypt_stat->cs_tfm_mutex);
756 ecryptfs_printk(KERN_DEBUG, "Decrypting [%d] bytes.\n", size);
757 rc = crypto_blkcipher_decrypt_iv(&desc, dest_sg, src_sg, size);
758 mutex_unlock(&crypt_stat->cs_tfm_mutex);
760 ecryptfs_printk(KERN_ERR, "Error decrypting; rc = [%d]\n",
770 * ecryptfs_encrypt_page_offset
771 * @crypt_stat: The cryptographic context
772 * @dst_page: The page to encrypt into
773 * @dst_offset: The offset in the page to encrypt into
774 * @src_page: The page to encrypt from
775 * @src_offset: The offset in the page to encrypt from
776 * @size: The number of bytes to encrypt
777 * @iv: The initialization vector to use for the encryption
779 * Returns the number of bytes encrypted
782 ecryptfs_encrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
783 struct page *dst_page, int dst_offset,
784 struct page *src_page, int src_offset, int size,
787 struct scatterlist src_sg, dst_sg;
789 src_sg.page = src_page;
790 src_sg.offset = src_offset;
791 src_sg.length = size;
792 dst_sg.page = dst_page;
793 dst_sg.offset = dst_offset;
794 dst_sg.length = size;
795 return encrypt_scatterlist(crypt_stat, &dst_sg, &src_sg, size, iv);
799 * ecryptfs_decrypt_page_offset
800 * @crypt_stat: The cryptographic context
801 * @dst_page: The page to decrypt into
802 * @dst_offset: The offset in the page to decrypt into
803 * @src_page: The page to decrypt from
804 * @src_offset: The offset in the page to decrypt from
805 * @size: The number of bytes to decrypt
806 * @iv: The initialization vector to use for the decryption
808 * Returns the number of bytes decrypted
811 ecryptfs_decrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
812 struct page *dst_page, int dst_offset,
813 struct page *src_page, int src_offset, int size,
816 struct scatterlist src_sg, dst_sg;
818 src_sg.page = src_page;
819 src_sg.offset = src_offset;
820 src_sg.length = size;
821 dst_sg.page = dst_page;
822 dst_sg.offset = dst_offset;
823 dst_sg.length = size;
824 return decrypt_scatterlist(crypt_stat, &dst_sg, &src_sg, size, iv);
827 #define ECRYPTFS_MAX_SCATTERLIST_LEN 4
830 * ecryptfs_init_crypt_ctx
831 * @crypt_stat: Uninitilized crypt stats structure
833 * Initialize the crypto context.
835 * TODO: Performance: Keep a cache of initialized cipher contexts;
836 * only init if needed
838 int ecryptfs_init_crypt_ctx(struct ecryptfs_crypt_stat *crypt_stat)
843 if (!crypt_stat->cipher) {
844 ecryptfs_printk(KERN_ERR, "No cipher specified\n");
847 ecryptfs_printk(KERN_DEBUG,
848 "Initializing cipher [%s]; strlen = [%d]; "
849 "key_size_bits = [%d]\n",
850 crypt_stat->cipher, (int)strlen(crypt_stat->cipher),
851 crypt_stat->key_size << 3);
852 if (crypt_stat->tfm) {
856 mutex_lock(&crypt_stat->cs_tfm_mutex);
857 rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name,
858 crypt_stat->cipher, "cbc");
861 crypt_stat->tfm = crypto_alloc_blkcipher(full_alg_name, 0,
863 kfree(full_alg_name);
864 if (IS_ERR(crypt_stat->tfm)) {
865 rc = PTR_ERR(crypt_stat->tfm);
866 ecryptfs_printk(KERN_ERR, "cryptfs: init_crypt_ctx(): "
867 "Error initializing cipher [%s]\n",
869 mutex_unlock(&crypt_stat->cs_tfm_mutex);
872 crypto_blkcipher_set_flags(crypt_stat->tfm, CRYPTO_TFM_REQ_WEAK_KEY);
873 mutex_unlock(&crypt_stat->cs_tfm_mutex);
879 static void set_extent_mask_and_shift(struct ecryptfs_crypt_stat *crypt_stat)
883 crypt_stat->extent_mask = 0xFFFFFFFF;
884 crypt_stat->extent_shift = 0;
885 if (crypt_stat->extent_size == 0)
887 extent_size_tmp = crypt_stat->extent_size;
888 while ((extent_size_tmp & 0x01) == 0) {
889 extent_size_tmp >>= 1;
890 crypt_stat->extent_mask <<= 1;
891 crypt_stat->extent_shift++;
895 void ecryptfs_set_default_sizes(struct ecryptfs_crypt_stat *crypt_stat)
897 /* Default values; may be overwritten as we are parsing the
899 crypt_stat->extent_size = ECRYPTFS_DEFAULT_EXTENT_SIZE;
900 set_extent_mask_and_shift(crypt_stat);
901 crypt_stat->iv_bytes = ECRYPTFS_DEFAULT_IV_BYTES;
902 if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
903 crypt_stat->num_header_extents_at_front = 0;
905 if (PAGE_CACHE_SIZE <= ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE)
906 crypt_stat->num_header_extents_at_front =
907 (ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE
908 / crypt_stat->extent_size);
910 crypt_stat->num_header_extents_at_front =
911 (PAGE_CACHE_SIZE / crypt_stat->extent_size);
916 * ecryptfs_compute_root_iv
919 * On error, sets the root IV to all 0's.
921 int ecryptfs_compute_root_iv(struct ecryptfs_crypt_stat *crypt_stat)
924 char dst[MD5_DIGEST_SIZE];
926 BUG_ON(crypt_stat->iv_bytes > MD5_DIGEST_SIZE);
927 BUG_ON(crypt_stat->iv_bytes <= 0);
928 if (!(crypt_stat->flags & ECRYPTFS_KEY_VALID)) {
930 ecryptfs_printk(KERN_WARNING, "Session key not valid; "
931 "cannot generate root IV\n");
934 rc = ecryptfs_calculate_md5(dst, crypt_stat, crypt_stat->key,
935 crypt_stat->key_size);
937 ecryptfs_printk(KERN_WARNING, "Error attempting to compute "
938 "MD5 while generating root IV\n");
941 memcpy(crypt_stat->root_iv, dst, crypt_stat->iv_bytes);
944 memset(crypt_stat->root_iv, 0, crypt_stat->iv_bytes);
945 crypt_stat->flags |= ECRYPTFS_SECURITY_WARNING;
950 static void ecryptfs_generate_new_key(struct ecryptfs_crypt_stat *crypt_stat)
952 get_random_bytes(crypt_stat->key, crypt_stat->key_size);
953 crypt_stat->flags |= ECRYPTFS_KEY_VALID;
954 ecryptfs_compute_root_iv(crypt_stat);
955 if (unlikely(ecryptfs_verbosity > 0)) {
956 ecryptfs_printk(KERN_DEBUG, "Generated new session key:\n");
957 ecryptfs_dump_hex(crypt_stat->key,
958 crypt_stat->key_size);
963 * ecryptfs_copy_mount_wide_flags_to_inode_flags
964 * @crypt_stat: The inode's cryptographic context
965 * @mount_crypt_stat: The mount point's cryptographic context
967 * This function propagates the mount-wide flags to individual inode
970 static void ecryptfs_copy_mount_wide_flags_to_inode_flags(
971 struct ecryptfs_crypt_stat *crypt_stat,
972 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
974 if (mount_crypt_stat->flags & ECRYPTFS_XATTR_METADATA_ENABLED)
975 crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
976 if (mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED)
977 crypt_stat->flags |= ECRYPTFS_VIEW_AS_ENCRYPTED;
980 static int ecryptfs_copy_mount_wide_sigs_to_inode_sigs(
981 struct ecryptfs_crypt_stat *crypt_stat,
982 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
984 struct ecryptfs_global_auth_tok *global_auth_tok;
987 mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
988 list_for_each_entry(global_auth_tok,
989 &mount_crypt_stat->global_auth_tok_list,
990 mount_crypt_stat_list) {
991 rc = ecryptfs_add_keysig(crypt_stat, global_auth_tok->sig);
993 printk(KERN_ERR "Error adding keysig; rc = [%d]\n", rc);
995 &mount_crypt_stat->global_auth_tok_list_mutex);
999 mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
1005 * ecryptfs_set_default_crypt_stat_vals
1006 * @crypt_stat: The inode's cryptographic context
1007 * @mount_crypt_stat: The mount point's cryptographic context
1009 * Default values in the event that policy does not override them.
1011 static void ecryptfs_set_default_crypt_stat_vals(
1012 struct ecryptfs_crypt_stat *crypt_stat,
1013 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
1015 ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
1017 ecryptfs_set_default_sizes(crypt_stat);
1018 strcpy(crypt_stat->cipher, ECRYPTFS_DEFAULT_CIPHER);
1019 crypt_stat->key_size = ECRYPTFS_DEFAULT_KEY_BYTES;
1020 crypt_stat->flags &= ~(ECRYPTFS_KEY_VALID);
1021 crypt_stat->file_version = ECRYPTFS_FILE_VERSION;
1022 crypt_stat->mount_crypt_stat = mount_crypt_stat;
1026 * ecryptfs_new_file_context
1027 * @ecryptfs_dentry: The eCryptfs dentry
1029 * If the crypto context for the file has not yet been established,
1030 * this is where we do that. Establishing a new crypto context
1031 * involves the following decisions:
1032 * - What cipher to use?
1033 * - What set of authentication tokens to use?
1034 * Here we just worry about getting enough information into the
1035 * authentication tokens so that we know that they are available.
1036 * We associate the available authentication tokens with the new file
1037 * via the set of signatures in the crypt_stat struct. Later, when
1038 * the headers are actually written out, we may again defer to
1039 * userspace to perform the encryption of the session key; for the
1040 * foreseeable future, this will be the case with public key packets.
1042 * Returns zero on success; non-zero otherwise
1044 int ecryptfs_new_file_context(struct dentry *ecryptfs_dentry)
1046 struct ecryptfs_crypt_stat *crypt_stat =
1047 &ecryptfs_inode_to_private(ecryptfs_dentry->d_inode)->crypt_stat;
1048 struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1049 &ecryptfs_superblock_to_private(
1050 ecryptfs_dentry->d_sb)->mount_crypt_stat;
1051 int cipher_name_len;
1054 ecryptfs_set_default_crypt_stat_vals(crypt_stat, mount_crypt_stat);
1055 crypt_stat->flags |= (ECRYPTFS_ENCRYPTED | ECRYPTFS_KEY_VALID);
1056 ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
1058 rc = ecryptfs_copy_mount_wide_sigs_to_inode_sigs(crypt_stat,
1061 printk(KERN_ERR "Error attempting to copy mount-wide key sigs "
1062 "to the inode key sigs; rc = [%d]\n", rc);
1066 strlen(mount_crypt_stat->global_default_cipher_name);
1067 memcpy(crypt_stat->cipher,
1068 mount_crypt_stat->global_default_cipher_name,
1070 crypt_stat->cipher[cipher_name_len] = '\0';
1071 crypt_stat->key_size =
1072 mount_crypt_stat->global_default_cipher_key_size;
1073 ecryptfs_generate_new_key(crypt_stat);
1074 rc = ecryptfs_init_crypt_ctx(crypt_stat);
1076 ecryptfs_printk(KERN_ERR, "Error initializing cryptographic "
1077 "context for cipher [%s]: rc = [%d]\n",
1078 crypt_stat->cipher, rc);
1084 * contains_ecryptfs_marker - check for the ecryptfs marker
1085 * @data: The data block in which to check
1087 * Returns one if marker found; zero if not found
1089 static int contains_ecryptfs_marker(char *data)
1093 memcpy(&m_1, data, 4);
1094 m_1 = be32_to_cpu(m_1);
1095 memcpy(&m_2, (data + 4), 4);
1096 m_2 = be32_to_cpu(m_2);
1097 if ((m_1 ^ MAGIC_ECRYPTFS_MARKER) == m_2)
1099 ecryptfs_printk(KERN_DEBUG, "m_1 = [0x%.8x]; m_2 = [0x%.8x]; "
1100 "MAGIC_ECRYPTFS_MARKER = [0x%.8x]\n", m_1, m_2,
1101 MAGIC_ECRYPTFS_MARKER);
1102 ecryptfs_printk(KERN_DEBUG, "(m_1 ^ MAGIC_ECRYPTFS_MARKER) = "
1103 "[0x%.8x]\n", (m_1 ^ MAGIC_ECRYPTFS_MARKER));
1107 struct ecryptfs_flag_map_elem {
1112 /* Add support for additional flags by adding elements here. */
1113 static struct ecryptfs_flag_map_elem ecryptfs_flag_map[] = {
1114 {0x00000001, ECRYPTFS_ENABLE_HMAC},
1115 {0x00000002, ECRYPTFS_ENCRYPTED},
1116 {0x00000004, ECRYPTFS_METADATA_IN_XATTR}
1120 * ecryptfs_process_flags
1121 * @crypt_stat: The cryptographic context
1122 * @page_virt: Source data to be parsed
1123 * @bytes_read: Updated with the number of bytes read
1125 * Returns zero on success; non-zero if the flag set is invalid
1127 static int ecryptfs_process_flags(struct ecryptfs_crypt_stat *crypt_stat,
1128 char *page_virt, int *bytes_read)
1134 memcpy(&flags, page_virt, 4);
1135 flags = be32_to_cpu(flags);
1136 for (i = 0; i < ((sizeof(ecryptfs_flag_map)
1137 / sizeof(struct ecryptfs_flag_map_elem))); i++)
1138 if (flags & ecryptfs_flag_map[i].file_flag) {
1139 crypt_stat->flags |= ecryptfs_flag_map[i].local_flag;
1141 crypt_stat->flags &= ~(ecryptfs_flag_map[i].local_flag);
1142 /* Version is in top 8 bits of the 32-bit flag vector */
1143 crypt_stat->file_version = ((flags >> 24) & 0xFF);
1149 * write_ecryptfs_marker
1150 * @page_virt: The pointer to in a page to begin writing the marker
1151 * @written: Number of bytes written
1153 * Marker = 0x3c81b7f5
1155 static void write_ecryptfs_marker(char *page_virt, size_t *written)
1159 get_random_bytes(&m_1, (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
1160 m_2 = (m_1 ^ MAGIC_ECRYPTFS_MARKER);
1161 m_1 = cpu_to_be32(m_1);
1162 memcpy(page_virt, &m_1, (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
1163 m_2 = cpu_to_be32(m_2);
1164 memcpy(page_virt + (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2), &m_2,
1165 (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
1166 (*written) = MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
1170 write_ecryptfs_flags(char *page_virt, struct ecryptfs_crypt_stat *crypt_stat,
1176 for (i = 0; i < ((sizeof(ecryptfs_flag_map)
1177 / sizeof(struct ecryptfs_flag_map_elem))); i++)
1178 if (crypt_stat->flags & ecryptfs_flag_map[i].local_flag)
1179 flags |= ecryptfs_flag_map[i].file_flag;
1180 /* Version is in top 8 bits of the 32-bit flag vector */
1181 flags |= ((((u8)crypt_stat->file_version) << 24) & 0xFF000000);
1182 flags = cpu_to_be32(flags);
1183 memcpy(page_virt, &flags, 4);
1187 struct ecryptfs_cipher_code_str_map_elem {
1188 char cipher_str[16];
1192 /* Add support for additional ciphers by adding elements here. The
1193 * cipher_code is whatever OpenPGP applicatoins use to identify the
1194 * ciphers. List in order of probability. */
1195 static struct ecryptfs_cipher_code_str_map_elem
1196 ecryptfs_cipher_code_str_map[] = {
1197 {"aes",RFC2440_CIPHER_AES_128 },
1198 {"blowfish", RFC2440_CIPHER_BLOWFISH},
1199 {"des3_ede", RFC2440_CIPHER_DES3_EDE},
1200 {"cast5", RFC2440_CIPHER_CAST_5},
1201 {"twofish", RFC2440_CIPHER_TWOFISH},
1202 {"cast6", RFC2440_CIPHER_CAST_6},
1203 {"aes", RFC2440_CIPHER_AES_192},
1204 {"aes", RFC2440_CIPHER_AES_256}
1208 * ecryptfs_code_for_cipher_string
1209 * @crypt_stat: The cryptographic context
1211 * Returns zero on no match, or the cipher code on match
1213 u16 ecryptfs_code_for_cipher_string(struct ecryptfs_crypt_stat *crypt_stat)
1217 struct ecryptfs_cipher_code_str_map_elem *map =
1218 ecryptfs_cipher_code_str_map;
1220 if (strcmp(crypt_stat->cipher, "aes") == 0) {
1221 switch (crypt_stat->key_size) {
1223 code = RFC2440_CIPHER_AES_128;
1226 code = RFC2440_CIPHER_AES_192;
1229 code = RFC2440_CIPHER_AES_256;
1232 for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
1233 if (strcmp(crypt_stat->cipher, map[i].cipher_str) == 0){
1234 code = map[i].cipher_code;
1242 * ecryptfs_cipher_code_to_string
1243 * @str: Destination to write out the cipher name
1244 * @cipher_code: The code to convert to cipher name string
1246 * Returns zero on success
1248 int ecryptfs_cipher_code_to_string(char *str, u16 cipher_code)
1254 for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
1255 if (cipher_code == ecryptfs_cipher_code_str_map[i].cipher_code)
1256 strcpy(str, ecryptfs_cipher_code_str_map[i].cipher_str);
1257 if (str[0] == '\0') {
1258 ecryptfs_printk(KERN_WARNING, "Cipher code not recognized: "
1259 "[%d]\n", cipher_code);
1266 * ecryptfs_read_header_region
1267 * @data: The virtual address to write header region data into
1268 * @dentry: The lower dentry
1269 * @mnt: The lower VFS mount
1271 * Returns zero on success; non-zero otherwise
1273 static int ecryptfs_read_header_region(char *data, struct dentry *dentry,
1274 struct vfsmount *mnt)
1276 struct file *lower_file;
1280 rc = ecryptfs_open_lower_file(&lower_file, dentry, mnt, O_RDONLY);
1283 "Error opening lower_file to read header region\n");
1286 lower_file->f_pos = 0;
1289 rc = lower_file->f_op->read(lower_file, (char __user *)data,
1290 ECRYPTFS_DEFAULT_EXTENT_SIZE, &lower_file->f_pos);
1292 rc = ecryptfs_close_lower_file(lower_file);
1294 printk(KERN_ERR "Error closing lower_file\n");
1302 int ecryptfs_read_and_validate_header_region(char *data, struct dentry *dentry,
1303 struct vfsmount *mnt)
1307 rc = ecryptfs_read_header_region(data, dentry, mnt);
1310 if (!contains_ecryptfs_marker(data + ECRYPTFS_FILE_SIZE_BYTES))
1318 ecryptfs_write_header_metadata(char *virt,
1319 struct ecryptfs_crypt_stat *crypt_stat,
1322 u32 header_extent_size;
1323 u16 num_header_extents_at_front;
1325 header_extent_size = (u32)crypt_stat->extent_size;
1326 num_header_extents_at_front =
1327 (u16)crypt_stat->num_header_extents_at_front;
1328 header_extent_size = cpu_to_be32(header_extent_size);
1329 memcpy(virt, &header_extent_size, 4);
1331 num_header_extents_at_front = cpu_to_be16(num_header_extents_at_front);
1332 memcpy(virt, &num_header_extents_at_front, 2);
1336 struct kmem_cache *ecryptfs_header_cache_0;
1337 struct kmem_cache *ecryptfs_header_cache_1;
1338 struct kmem_cache *ecryptfs_header_cache_2;
1341 * ecryptfs_write_headers_virt
1342 * @page_virt: The virtual address to write the headers to
1343 * @size: Set to the number of bytes written by this function
1344 * @crypt_stat: The cryptographic context
1345 * @ecryptfs_dentry: The eCryptfs dentry
1350 * Octets 0-7: Unencrypted file size (big-endian)
1351 * Octets 8-15: eCryptfs special marker
1352 * Octets 16-19: Flags
1353 * Octet 16: File format version number (between 0 and 255)
1354 * Octets 17-18: Reserved
1355 * Octet 19: Bit 1 (lsb): Reserved
1357 * Bits 3-8: Reserved
1358 * Octets 20-23: Header extent size (big-endian)
1359 * Octets 24-25: Number of header extents at front of file
1361 * Octet 26: Begin RFC 2440 authentication token packet set
1363 * Lower data (CBC encrypted)
1365 * Lower data (CBC encrypted)
1368 * Returns zero on success
1370 static int ecryptfs_write_headers_virt(char *page_virt, size_t *size,
1371 struct ecryptfs_crypt_stat *crypt_stat,
1372 struct dentry *ecryptfs_dentry)
1378 offset = ECRYPTFS_FILE_SIZE_BYTES;
1379 write_ecryptfs_marker((page_virt + offset), &written);
1381 write_ecryptfs_flags((page_virt + offset), crypt_stat, &written);
1383 ecryptfs_write_header_metadata((page_virt + offset), crypt_stat,
1386 rc = ecryptfs_generate_key_packet_set((page_virt + offset), crypt_stat,
1387 ecryptfs_dentry, &written,
1388 PAGE_CACHE_SIZE - offset);
1390 ecryptfs_printk(KERN_WARNING, "Error generating key packet "
1391 "set; rc = [%d]\n", rc);
1400 ecryptfs_write_metadata_to_contents(struct ecryptfs_crypt_stat *crypt_stat,
1401 struct file *lower_file, char *page_virt)
1404 int current_header_page;
1409 lower_file->f_pos = 0;
1412 size = vfs_write(lower_file, (char __user *)page_virt, PAGE_CACHE_SIZE,
1413 &lower_file->f_pos);
1416 printk(KERN_ERR "Error attempting to write lower page; "
1421 header_pages = ((crypt_stat->extent_size
1422 * crypt_stat->num_header_extents_at_front)
1424 memset(page_virt, 0, PAGE_CACHE_SIZE);
1425 current_header_page = 1;
1426 while (current_header_page < header_pages) {
1427 size = vfs_write(lower_file, (char __user *)page_virt,
1428 PAGE_CACHE_SIZE, &lower_file->f_pos);
1431 printk(KERN_ERR "Error attempting to write lower page; "
1436 current_header_page++;
1444 ecryptfs_write_metadata_to_xattr(struct dentry *ecryptfs_dentry,
1445 struct ecryptfs_crypt_stat *crypt_stat,
1446 char *page_virt, size_t size)
1450 rc = ecryptfs_setxattr(ecryptfs_dentry, ECRYPTFS_XATTR_NAME, page_virt,
1456 * ecryptfs_write_metadata
1457 * @ecryptfs_dentry: The eCryptfs dentry
1458 * @lower_file: The lower file struct, which was returned from dentry_open
1460 * Write the file headers out. This will likely involve a userspace
1461 * callout, in which the session key is encrypted with one or more
1462 * public keys and/or the passphrase necessary to do the encryption is
1463 * retrieved via a prompt. Exactly what happens at this point should
1464 * be policy-dependent.
1466 * Returns zero on success; non-zero on error
1468 int ecryptfs_write_metadata(struct dentry *ecryptfs_dentry,
1469 struct file *lower_file)
1471 struct ecryptfs_crypt_stat *crypt_stat;
1476 crypt_stat = &ecryptfs_inode_to_private(
1477 ecryptfs_dentry->d_inode)->crypt_stat;
1478 if (likely(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
1479 if (!(crypt_stat->flags & ECRYPTFS_KEY_VALID)) {
1480 ecryptfs_printk(KERN_DEBUG, "Key is "
1481 "invalid; bailing out\n");
1487 ecryptfs_printk(KERN_WARNING,
1488 "Called with crypt_stat->encrypted == 0\n");
1491 /* Released in this function */
1492 page_virt = kmem_cache_zalloc(ecryptfs_header_cache_0, GFP_USER);
1494 ecryptfs_printk(KERN_ERR, "Out of memory\n");
1498 rc = ecryptfs_write_headers_virt(page_virt, &size, crypt_stat,
1501 ecryptfs_printk(KERN_ERR, "Error whilst writing headers\n");
1502 memset(page_virt, 0, PAGE_CACHE_SIZE);
1505 if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
1506 rc = ecryptfs_write_metadata_to_xattr(ecryptfs_dentry,
1507 crypt_stat, page_virt,
1510 rc = ecryptfs_write_metadata_to_contents(crypt_stat, lower_file,
1513 printk(KERN_ERR "Error writing metadata out to lower file; "
1518 kmem_cache_free(ecryptfs_header_cache_0, page_virt);
1523 #define ECRYPTFS_DONT_VALIDATE_HEADER_SIZE 0
1524 #define ECRYPTFS_VALIDATE_HEADER_SIZE 1
1525 static int parse_header_metadata(struct ecryptfs_crypt_stat *crypt_stat,
1526 char *virt, int *bytes_read,
1527 int validate_header_size)
1530 u32 header_extent_size;
1531 u16 num_header_extents_at_front;
1533 memcpy(&header_extent_size, virt, 4);
1534 header_extent_size = be32_to_cpu(header_extent_size);
1536 memcpy(&num_header_extents_at_front, virt, 2);
1537 num_header_extents_at_front = be16_to_cpu(num_header_extents_at_front);
1538 crypt_stat->num_header_extents_at_front =
1539 (int)num_header_extents_at_front;
1540 (*bytes_read) = (sizeof(u32) + sizeof(u16));
1541 if ((validate_header_size == ECRYPTFS_VALIDATE_HEADER_SIZE)
1542 && ((crypt_stat->extent_size
1543 * crypt_stat->num_header_extents_at_front)
1544 < ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE)) {
1546 printk(KERN_WARNING "Invalid number of header extents: [%zd]\n",
1547 crypt_stat->num_header_extents_at_front);
1553 * set_default_header_data
1554 * @crypt_stat: The cryptographic context
1556 * For version 0 file format; this function is only for backwards
1557 * compatibility for files created with the prior versions of
1560 static void set_default_header_data(struct ecryptfs_crypt_stat *crypt_stat)
1562 crypt_stat->num_header_extents_at_front = 2;
1566 * ecryptfs_read_headers_virt
1567 * @page_virt: The virtual address into which to read the headers
1568 * @crypt_stat: The cryptographic context
1569 * @ecryptfs_dentry: The eCryptfs dentry
1570 * @validate_header_size: Whether to validate the header size while reading
1572 * Read/parse the header data. The header format is detailed in the
1573 * comment block for the ecryptfs_write_headers_virt() function.
1575 * Returns zero on success
1577 static int ecryptfs_read_headers_virt(char *page_virt,
1578 struct ecryptfs_crypt_stat *crypt_stat,
1579 struct dentry *ecryptfs_dentry,
1580 int validate_header_size)
1586 ecryptfs_set_default_sizes(crypt_stat);
1587 crypt_stat->mount_crypt_stat = &ecryptfs_superblock_to_private(
1588 ecryptfs_dentry->d_sb)->mount_crypt_stat;
1589 offset = ECRYPTFS_FILE_SIZE_BYTES;
1590 rc = contains_ecryptfs_marker(page_virt + offset);
1595 offset += MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
1596 rc = ecryptfs_process_flags(crypt_stat, (page_virt + offset),
1599 ecryptfs_printk(KERN_WARNING, "Error processing flags\n");
1602 if (crypt_stat->file_version > ECRYPTFS_SUPPORTED_FILE_VERSION) {
1603 ecryptfs_printk(KERN_WARNING, "File version is [%d]; only "
1604 "file version [%d] is supported by this "
1605 "version of eCryptfs\n",
1606 crypt_stat->file_version,
1607 ECRYPTFS_SUPPORTED_FILE_VERSION);
1611 offset += bytes_read;
1612 if (crypt_stat->file_version >= 1) {
1613 rc = parse_header_metadata(crypt_stat, (page_virt + offset),
1614 &bytes_read, validate_header_size);
1616 ecryptfs_printk(KERN_WARNING, "Error reading header "
1617 "metadata; rc = [%d]\n", rc);
1619 offset += bytes_read;
1621 set_default_header_data(crypt_stat);
1622 rc = ecryptfs_parse_packet_set(crypt_stat, (page_virt + offset),
1629 * ecryptfs_read_xattr_region
1630 * @page_virt: The vitual address into which to read the xattr data
1631 * @ecryptfs_dentry: The eCryptfs dentry
1633 * Attempts to read the crypto metadata from the extended attribute
1634 * region of the lower file.
1636 * Returns zero on success; non-zero on error
1638 int ecryptfs_read_xattr_region(char *page_virt, struct dentry *ecryptfs_dentry)
1643 size = ecryptfs_getxattr(ecryptfs_dentry, ECRYPTFS_XATTR_NAME,
1644 page_virt, ECRYPTFS_DEFAULT_EXTENT_SIZE);
1646 printk(KERN_DEBUG "Error attempting to read the [%s] "
1647 "xattr from the lower file; return value = [%zd]\n",
1648 ECRYPTFS_XATTR_NAME, size);
1656 int ecryptfs_read_and_validate_xattr_region(char *page_virt,
1657 struct dentry *ecryptfs_dentry)
1661 rc = ecryptfs_read_xattr_region(page_virt, ecryptfs_dentry);
1664 if (!contains_ecryptfs_marker(page_virt + ECRYPTFS_FILE_SIZE_BYTES)) {
1665 printk(KERN_WARNING "Valid data found in [%s] xattr, but "
1666 "the marker is invalid\n", ECRYPTFS_XATTR_NAME);
1674 * ecryptfs_read_metadata
1675 * @ecryptfs_dentry: The eCryptfs dentry
1676 * @lower_file: The lower file from which to read the metadata
1678 * Common entry point for reading file metadata. From here, we could
1679 * retrieve the header information from the header region of the file,
1680 * the xattr region of the file, or some other repostory that is
1681 * stored separately from the file itself. The current implementation
1682 * supports retrieving the metadata information from the file contents
1683 * and from the xattr region.
1685 * Returns zero if valid headers found and parsed; non-zero otherwise
1687 int ecryptfs_read_metadata(struct dentry *ecryptfs_dentry,
1688 struct file *lower_file)
1691 char *page_virt = NULL;
1694 struct ecryptfs_crypt_stat *crypt_stat =
1695 &ecryptfs_inode_to_private(ecryptfs_dentry->d_inode)->crypt_stat;
1696 struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1697 &ecryptfs_superblock_to_private(
1698 ecryptfs_dentry->d_sb)->mount_crypt_stat;
1700 ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
1702 /* Read the first page from the underlying file */
1703 page_virt = kmem_cache_alloc(ecryptfs_header_cache_1, GFP_USER);
1706 ecryptfs_printk(KERN_ERR, "Unable to allocate page_virt\n");
1709 lower_file->f_pos = 0;
1712 bytes_read = lower_file->f_op->read(lower_file,
1713 (char __user *)page_virt,
1714 ECRYPTFS_DEFAULT_EXTENT_SIZE,
1715 &lower_file->f_pos);
1717 if (bytes_read != ECRYPTFS_DEFAULT_EXTENT_SIZE) {
1721 rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
1723 ECRYPTFS_VALIDATE_HEADER_SIZE);
1725 rc = ecryptfs_read_xattr_region(page_virt,
1728 printk(KERN_DEBUG "Valid eCryptfs headers not found in "
1729 "file header region or xattr region\n");
1733 rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
1735 ECRYPTFS_DONT_VALIDATE_HEADER_SIZE);
1737 printk(KERN_DEBUG "Valid eCryptfs headers not found in "
1738 "file xattr region either\n");
1741 if (crypt_stat->mount_crypt_stat->flags
1742 & ECRYPTFS_XATTR_METADATA_ENABLED) {
1743 crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
1745 printk(KERN_WARNING "Attempt to access file with "
1746 "crypto metadata only in the extended attribute "
1747 "region, but eCryptfs was mounted without "
1748 "xattr support enabled. eCryptfs will not treat "
1749 "this like an encrypted file.\n");
1755 memset(page_virt, 0, PAGE_CACHE_SIZE);
1756 kmem_cache_free(ecryptfs_header_cache_1, page_virt);
1762 * ecryptfs_encode_filename - converts a plaintext file name to cipher text
1763 * @crypt_stat: The crypt_stat struct associated with the file anem to encode
1764 * @name: The plaintext name
1765 * @length: The length of the plaintext
1766 * @encoded_name: The encypted name
1768 * Encrypts and encodes a filename into something that constitutes a
1769 * valid filename for a filesystem, with printable characters.
1771 * We assume that we have a properly initialized crypto context,
1772 * pointed to by crypt_stat->tfm.
1774 * TODO: Implement filename decoding and decryption here, in place of
1775 * memcpy. We are keeping the framework around for now to (1)
1776 * facilitate testing of the components needed to implement filename
1777 * encryption and (2) to provide a code base from which other
1778 * developers in the community can easily implement this feature.
1780 * Returns the length of encoded filename; negative if error
1783 ecryptfs_encode_filename(struct ecryptfs_crypt_stat *crypt_stat,
1784 const char *name, int length, char **encoded_name)
1788 (*encoded_name) = kmalloc(length + 2, GFP_KERNEL);
1789 if (!(*encoded_name)) {
1793 /* TODO: Filename encryption is a scheduled feature for a
1794 * future version of eCryptfs. This function is here only for
1795 * the purpose of providing a framework for other developers
1796 * to easily implement filename encryption. Hint: Replace this
1797 * memcpy() with a call to encrypt and encode the
1798 * filename, the set the length accordingly. */
1799 memcpy((void *)(*encoded_name), (void *)name, length);
1800 (*encoded_name)[length] = '\0';
1807 * ecryptfs_decode_filename - converts the cipher text name to plaintext
1808 * @crypt_stat: The crypt_stat struct associated with the file
1809 * @name: The filename in cipher text
1810 * @length: The length of the cipher text name
1811 * @decrypted_name: The plaintext name
1813 * Decodes and decrypts the filename.
1815 * We assume that we have a properly initialized crypto context,
1816 * pointed to by crypt_stat->tfm.
1818 * TODO: Implement filename decoding and decryption here, in place of
1819 * memcpy. We are keeping the framework around for now to (1)
1820 * facilitate testing of the components needed to implement filename
1821 * encryption and (2) to provide a code base from which other
1822 * developers in the community can easily implement this feature.
1824 * Returns the length of decoded filename; negative if error
1827 ecryptfs_decode_filename(struct ecryptfs_crypt_stat *crypt_stat,
1828 const char *name, int length, char **decrypted_name)
1832 (*decrypted_name) = kmalloc(length + 2, GFP_KERNEL);
1833 if (!(*decrypted_name)) {
1837 /* TODO: Filename encryption is a scheduled feature for a
1838 * future version of eCryptfs. This function is here only for
1839 * the purpose of providing a framework for other developers
1840 * to easily implement filename encryption. Hint: Replace this
1841 * memcpy() with a call to decode and decrypt the
1842 * filename, the set the length accordingly. */
1843 memcpy((void *)(*decrypted_name), (void *)name, length);
1844 (*decrypted_name)[length + 1] = '\0'; /* Only for convenience
1845 * in printing out the
1854 * ecryptfs_process_key_cipher - Perform key cipher initialization.
1855 * @key_tfm: Crypto context for key material, set by this function
1856 * @cipher_name: Name of the cipher
1857 * @key_size: Size of the key in bytes
1859 * Returns zero on success. Any crypto_tfm structs allocated here
1860 * should be released by other functions, such as on a superblock put
1861 * event, regardless of whether this function succeeds for fails.
1864 ecryptfs_process_key_cipher(struct crypto_blkcipher **key_tfm,
1865 char *cipher_name, size_t *key_size)
1867 char dummy_key[ECRYPTFS_MAX_KEY_BYTES];
1868 char *full_alg_name;
1872 if (*key_size > ECRYPTFS_MAX_KEY_BYTES) {
1874 printk(KERN_ERR "Requested key size is [%Zd] bytes; maximum "
1875 "allowable is [%d]\n", *key_size, ECRYPTFS_MAX_KEY_BYTES);
1878 rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name, cipher_name,
1882 *key_tfm = crypto_alloc_blkcipher(full_alg_name, 0, CRYPTO_ALG_ASYNC);
1883 kfree(full_alg_name);
1884 if (IS_ERR(*key_tfm)) {
1885 rc = PTR_ERR(*key_tfm);
1886 printk(KERN_ERR "Unable to allocate crypto cipher with name "
1887 "[%s]; rc = [%d]\n", cipher_name, rc);
1890 crypto_blkcipher_set_flags(*key_tfm, CRYPTO_TFM_REQ_WEAK_KEY);
1891 if (*key_size == 0) {
1892 struct blkcipher_alg *alg = crypto_blkcipher_alg(*key_tfm);
1894 *key_size = alg->max_keysize;
1896 get_random_bytes(dummy_key, *key_size);
1897 rc = crypto_blkcipher_setkey(*key_tfm, dummy_key, *key_size);
1899 printk(KERN_ERR "Error attempting to set key of size [%Zd] for "
1900 "cipher [%s]; rc = [%d]\n", *key_size, cipher_name, rc);
1908 struct kmem_cache *ecryptfs_key_tfm_cache;
1909 struct list_head key_tfm_list;
1910 struct mutex key_tfm_list_mutex;
1912 int ecryptfs_init_crypto(void)
1914 mutex_init(&key_tfm_list_mutex);
1915 INIT_LIST_HEAD(&key_tfm_list);
1919 int ecryptfs_destroy_crypto(void)
1921 struct ecryptfs_key_tfm *key_tfm, *key_tfm_tmp;
1923 mutex_lock(&key_tfm_list_mutex);
1924 list_for_each_entry_safe(key_tfm, key_tfm_tmp, &key_tfm_list,
1926 list_del(&key_tfm->key_tfm_list);
1927 if (key_tfm->key_tfm)
1928 crypto_free_blkcipher(key_tfm->key_tfm);
1929 kmem_cache_free(ecryptfs_key_tfm_cache, key_tfm);
1931 mutex_unlock(&key_tfm_list_mutex);
1936 ecryptfs_add_new_key_tfm(struct ecryptfs_key_tfm **key_tfm, char *cipher_name,
1939 struct ecryptfs_key_tfm *tmp_tfm;
1942 tmp_tfm = kmem_cache_alloc(ecryptfs_key_tfm_cache, GFP_KERNEL);
1943 if (key_tfm != NULL)
1944 (*key_tfm) = tmp_tfm;
1947 printk(KERN_ERR "Error attempting to allocate from "
1948 "ecryptfs_key_tfm_cache\n");
1951 mutex_init(&tmp_tfm->key_tfm_mutex);
1952 strncpy(tmp_tfm->cipher_name, cipher_name,
1953 ECRYPTFS_MAX_CIPHER_NAME_SIZE);
1954 tmp_tfm->key_size = key_size;
1955 rc = ecryptfs_process_key_cipher(&tmp_tfm->key_tfm,
1956 tmp_tfm->cipher_name,
1957 &tmp_tfm->key_size);
1959 printk(KERN_ERR "Error attempting to initialize key TFM "
1960 "cipher with name = [%s]; rc = [%d]\n",
1961 tmp_tfm->cipher_name, rc);
1962 kmem_cache_free(ecryptfs_key_tfm_cache, tmp_tfm);
1963 if (key_tfm != NULL)
1967 mutex_lock(&key_tfm_list_mutex);
1968 list_add(&tmp_tfm->key_tfm_list, &key_tfm_list);
1969 mutex_unlock(&key_tfm_list_mutex);
1974 int ecryptfs_get_tfm_and_mutex_for_cipher_name(struct crypto_blkcipher **tfm,
1975 struct mutex **tfm_mutex,
1978 struct ecryptfs_key_tfm *key_tfm;
1982 (*tfm_mutex) = NULL;
1983 mutex_lock(&key_tfm_list_mutex);
1984 list_for_each_entry(key_tfm, &key_tfm_list, key_tfm_list) {
1985 if (strcmp(key_tfm->cipher_name, cipher_name) == 0) {
1986 (*tfm) = key_tfm->key_tfm;
1987 (*tfm_mutex) = &key_tfm->key_tfm_mutex;
1988 mutex_unlock(&key_tfm_list_mutex);
1992 mutex_unlock(&key_tfm_list_mutex);
1993 rc = ecryptfs_add_new_key_tfm(&key_tfm, cipher_name, 0);
1995 printk(KERN_ERR "Error adding new key_tfm to list; rc = [%d]\n",
1999 (*tfm) = key_tfm->key_tfm;
2000 (*tfm_mutex) = &key_tfm->key_tfm_mutex;