1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * eCryptfs: Linux filesystem encryption layer
5 * Copyright (C) 1997-2004 Erez Zadok
6 * Copyright (C) 2001-2004 Stony Brook University
7 * Copyright (C) 2004-2007 International Business Machines Corp.
8 * Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
9 * Michael C. Thompson <mcthomps@us.ibm.com>
12 #include <crypto/hash.h>
13 #include <crypto/skcipher.h>
15 #include <linux/mount.h>
16 #include <linux/pagemap.h>
17 #include <linux/random.h>
18 #include <linux/compiler.h>
19 #include <linux/key.h>
20 #include <linux/namei.h>
21 #include <linux/file.h>
22 #include <linux/scatterlist.h>
23 #include <linux/slab.h>
24 #include <asm/unaligned.h>
25 #include <linux/kernel.h>
26 #include <linux/xattr.h>
27 #include "ecryptfs_kernel.h"
34 * @dst: Buffer to take the bytes from src hex; must be at least of
36 * @src: Buffer to be converted from a hex string representation to raw value
37 * @dst_size: size of dst buffer, or number of hex characters pairs to convert
39 void ecryptfs_from_hex(char *dst, char *src, int dst_size)
44 for (x = 0; x < dst_size; x++) {
46 tmp[1] = src[x * 2 + 1];
47 dst[x] = (unsigned char)simple_strtol(tmp, NULL, 16);
51 static int ecryptfs_hash_digest(struct crypto_shash *tfm,
52 char *src, int len, char *dst)
54 SHASH_DESC_ON_STACK(desc, tfm);
58 err = crypto_shash_digest(desc, src, len, dst);
59 shash_desc_zero(desc);
64 * ecryptfs_calculate_md5 - calculates the md5 of @src
65 * @dst: Pointer to 16 bytes of allocated memory
66 * @crypt_stat: Pointer to crypt_stat struct for the current inode
67 * @src: Data to be md5'd
68 * @len: Length of @src
70 * Uses the allocated crypto context that crypt_stat references to
71 * generate the MD5 sum of the contents of src.
73 static int ecryptfs_calculate_md5(char *dst,
74 struct ecryptfs_crypt_stat *crypt_stat,
77 struct crypto_shash *tfm;
80 tfm = crypt_stat->hash_tfm;
81 rc = ecryptfs_hash_digest(tfm, src, len, dst);
84 "%s: Error computing crypto hash; rc = [%d]\n",
92 static int ecryptfs_crypto_api_algify_cipher_name(char **algified_name,
94 char *chaining_modifier)
96 int cipher_name_len = strlen(cipher_name);
97 int chaining_modifier_len = strlen(chaining_modifier);
98 int algified_name_len;
101 algified_name_len = (chaining_modifier_len + cipher_name_len + 3);
102 (*algified_name) = kmalloc(algified_name_len, GFP_KERNEL);
103 if (!(*algified_name)) {
107 snprintf((*algified_name), algified_name_len, "%s(%s)",
108 chaining_modifier, cipher_name);
116 * @iv: destination for the derived iv vale
117 * @crypt_stat: Pointer to crypt_stat struct for the current inode
118 * @offset: Offset of the extent whose IV we are to derive
120 * Generate the initialization vector from the given root IV and page
123 * Returns zero on success; non-zero on error.
125 int ecryptfs_derive_iv(char *iv, struct ecryptfs_crypt_stat *crypt_stat,
129 char dst[MD5_DIGEST_SIZE];
130 char src[ECRYPTFS_MAX_IV_BYTES + 16];
132 if (unlikely(ecryptfs_verbosity > 0)) {
133 ecryptfs_printk(KERN_DEBUG, "root iv:\n");
134 ecryptfs_dump_hex(crypt_stat->root_iv, crypt_stat->iv_bytes);
136 /* TODO: It is probably secure to just cast the least
137 * significant bits of the root IV into an unsigned long and
138 * add the offset to that rather than go through all this
139 * hashing business. -Halcrow */
140 memcpy(src, crypt_stat->root_iv, crypt_stat->iv_bytes);
141 memset((src + crypt_stat->iv_bytes), 0, 16);
142 snprintf((src + crypt_stat->iv_bytes), 16, "%lld", offset);
143 if (unlikely(ecryptfs_verbosity > 0)) {
144 ecryptfs_printk(KERN_DEBUG, "source:\n");
145 ecryptfs_dump_hex(src, (crypt_stat->iv_bytes + 16));
147 rc = ecryptfs_calculate_md5(dst, crypt_stat, src,
148 (crypt_stat->iv_bytes + 16));
150 ecryptfs_printk(KERN_WARNING, "Error attempting to compute "
151 "MD5 while generating IV for a page\n");
154 memcpy(iv, dst, crypt_stat->iv_bytes);
155 if (unlikely(ecryptfs_verbosity > 0)) {
156 ecryptfs_printk(KERN_DEBUG, "derived iv:\n");
157 ecryptfs_dump_hex(iv, crypt_stat->iv_bytes);
164 * ecryptfs_init_crypt_stat
165 * @crypt_stat: Pointer to the crypt_stat struct to initialize.
167 * Initialize the crypt_stat structure.
169 int ecryptfs_init_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
171 struct crypto_shash *tfm;
174 tfm = crypto_alloc_shash(ECRYPTFS_DEFAULT_HASH, 0, 0);
177 ecryptfs_printk(KERN_ERR, "Error attempting to "
178 "allocate crypto context; rc = [%d]\n",
183 memset((void *)crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
184 INIT_LIST_HEAD(&crypt_stat->keysig_list);
185 mutex_init(&crypt_stat->keysig_list_mutex);
186 mutex_init(&crypt_stat->cs_mutex);
187 mutex_init(&crypt_stat->cs_tfm_mutex);
188 crypt_stat->hash_tfm = tfm;
189 crypt_stat->flags |= ECRYPTFS_STRUCT_INITIALIZED;
195 * ecryptfs_destroy_crypt_stat
196 * @crypt_stat: Pointer to the crypt_stat struct to initialize.
198 * Releases all memory associated with a crypt_stat struct.
200 void ecryptfs_destroy_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
202 struct ecryptfs_key_sig *key_sig, *key_sig_tmp;
204 crypto_free_skcipher(crypt_stat->tfm);
205 crypto_free_shash(crypt_stat->hash_tfm);
206 list_for_each_entry_safe(key_sig, key_sig_tmp,
207 &crypt_stat->keysig_list, crypt_stat_list) {
208 list_del(&key_sig->crypt_stat_list);
209 kmem_cache_free(ecryptfs_key_sig_cache, key_sig);
211 memset(crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
214 void ecryptfs_destroy_mount_crypt_stat(
215 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
217 struct ecryptfs_global_auth_tok *auth_tok, *auth_tok_tmp;
219 if (!(mount_crypt_stat->flags & ECRYPTFS_MOUNT_CRYPT_STAT_INITIALIZED))
221 mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
222 list_for_each_entry_safe(auth_tok, auth_tok_tmp,
223 &mount_crypt_stat->global_auth_tok_list,
224 mount_crypt_stat_list) {
225 list_del(&auth_tok->mount_crypt_stat_list);
226 if (!(auth_tok->flags & ECRYPTFS_AUTH_TOK_INVALID))
227 key_put(auth_tok->global_auth_tok_key);
228 kmem_cache_free(ecryptfs_global_auth_tok_cache, auth_tok);
230 mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
231 memset(mount_crypt_stat, 0, sizeof(struct ecryptfs_mount_crypt_stat));
235 * virt_to_scatterlist
236 * @addr: Virtual address
237 * @size: Size of data; should be an even multiple of the block size
238 * @sg: Pointer to scatterlist array; set to NULL to obtain only
239 * the number of scatterlist structs required in array
240 * @sg_size: Max array size
242 * Fills in a scatterlist array with page references for a passed
245 * Returns the number of scatterlist structs in array used
247 int virt_to_scatterlist(const void *addr, int size, struct scatterlist *sg,
253 int remainder_of_page;
255 sg_init_table(sg, sg_size);
257 while (size > 0 && i < sg_size) {
258 pg = virt_to_page(addr);
259 offset = offset_in_page(addr);
260 sg_set_page(&sg[i], pg, 0, offset);
261 remainder_of_page = PAGE_SIZE - offset;
262 if (size >= remainder_of_page) {
263 sg[i].length = remainder_of_page;
264 addr += remainder_of_page;
265 size -= remainder_of_page;
278 struct extent_crypt_result {
279 struct completion completion;
283 static void extent_crypt_complete(struct crypto_async_request *req, int rc)
285 struct extent_crypt_result *ecr = req->data;
287 if (rc == -EINPROGRESS)
291 complete(&ecr->completion);
296 * @crypt_stat: Pointer to the crypt_stat struct to initialize.
297 * @dst_sg: Destination of the data after performing the crypto operation
298 * @src_sg: Data to be encrypted or decrypted
299 * @size: Length of data
301 * @op: ENCRYPT or DECRYPT to indicate the desired operation
303 * Returns the number of bytes encrypted or decrypted; negative value on error
305 static int crypt_scatterlist(struct ecryptfs_crypt_stat *crypt_stat,
306 struct scatterlist *dst_sg,
307 struct scatterlist *src_sg, int size,
308 unsigned char *iv, int op)
310 struct skcipher_request *req = NULL;
311 struct extent_crypt_result ecr;
314 if (!crypt_stat || !crypt_stat->tfm
315 || !(crypt_stat->flags & ECRYPTFS_STRUCT_INITIALIZED))
318 if (unlikely(ecryptfs_verbosity > 0)) {
319 ecryptfs_printk(KERN_DEBUG, "Key size [%zd]; key:\n",
320 crypt_stat->key_size);
321 ecryptfs_dump_hex(crypt_stat->key,
322 crypt_stat->key_size);
325 init_completion(&ecr.completion);
327 mutex_lock(&crypt_stat->cs_tfm_mutex);
328 req = skcipher_request_alloc(crypt_stat->tfm, GFP_NOFS);
330 mutex_unlock(&crypt_stat->cs_tfm_mutex);
335 skcipher_request_set_callback(req,
336 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
337 extent_crypt_complete, &ecr);
338 /* Consider doing this once, when the file is opened */
339 if (!(crypt_stat->flags & ECRYPTFS_KEY_SET)) {
340 rc = crypto_skcipher_setkey(crypt_stat->tfm, crypt_stat->key,
341 crypt_stat->key_size);
343 ecryptfs_printk(KERN_ERR,
344 "Error setting key; rc = [%d]\n",
346 mutex_unlock(&crypt_stat->cs_tfm_mutex);
350 crypt_stat->flags |= ECRYPTFS_KEY_SET;
352 mutex_unlock(&crypt_stat->cs_tfm_mutex);
353 skcipher_request_set_crypt(req, src_sg, dst_sg, size, iv);
354 rc = op == ENCRYPT ? crypto_skcipher_encrypt(req) :
355 crypto_skcipher_decrypt(req);
356 if (rc == -EINPROGRESS || rc == -EBUSY) {
357 struct extent_crypt_result *ecr = req->base.data;
359 wait_for_completion(&ecr->completion);
361 reinit_completion(&ecr->completion);
364 skcipher_request_free(req);
369 * lower_offset_for_page
371 * Convert an eCryptfs page index into a lower byte offset
373 static loff_t lower_offset_for_page(struct ecryptfs_crypt_stat *crypt_stat,
376 return ecryptfs_lower_header_size(crypt_stat) +
377 ((loff_t)page->index << PAGE_SHIFT);
382 * @crypt_stat: crypt_stat containing cryptographic context for the
383 * encryption operation
384 * @dst_page: The page to write the result into
385 * @src_page: The page to read from
386 * @extent_offset: Page extent offset for use in generating IV
387 * @op: ENCRYPT or DECRYPT to indicate the desired operation
389 * Encrypts or decrypts one extent of data.
391 * Return zero on success; non-zero otherwise
393 static int crypt_extent(struct ecryptfs_crypt_stat *crypt_stat,
394 struct page *dst_page,
395 struct page *src_page,
396 unsigned long extent_offset, int op)
398 pgoff_t page_index = op == ENCRYPT ? src_page->index : dst_page->index;
400 char extent_iv[ECRYPTFS_MAX_IV_BYTES];
401 struct scatterlist src_sg, dst_sg;
402 size_t extent_size = crypt_stat->extent_size;
405 extent_base = (((loff_t)page_index) * (PAGE_SIZE / extent_size));
406 rc = ecryptfs_derive_iv(extent_iv, crypt_stat,
407 (extent_base + extent_offset));
409 ecryptfs_printk(KERN_ERR, "Error attempting to derive IV for "
410 "extent [0x%.16llx]; rc = [%d]\n",
411 (unsigned long long)(extent_base + extent_offset), rc);
415 sg_init_table(&src_sg, 1);
416 sg_init_table(&dst_sg, 1);
418 sg_set_page(&src_sg, src_page, extent_size,
419 extent_offset * extent_size);
420 sg_set_page(&dst_sg, dst_page, extent_size,
421 extent_offset * extent_size);
423 rc = crypt_scatterlist(crypt_stat, &dst_sg, &src_sg, extent_size,
426 printk(KERN_ERR "%s: Error attempting to crypt page with "
427 "page_index = [%ld], extent_offset = [%ld]; "
428 "rc = [%d]\n", __func__, page_index, extent_offset, rc);
437 * ecryptfs_encrypt_page
438 * @page: Page mapped from the eCryptfs inode for the file; contains
439 * decrypted content that needs to be encrypted (to a temporary
440 * page; not in place) and written out to the lower file
442 * Encrypt an eCryptfs page. This is done on a per-extent basis. Note
443 * that eCryptfs pages may straddle the lower pages -- for instance,
444 * if the file was created on a machine with an 8K page size
445 * (resulting in an 8K header), and then the file is copied onto a
446 * host with a 32K page size, then when reading page 0 of the eCryptfs
447 * file, 24K of page 0 of the lower file will be read and decrypted,
448 * and then 8K of page 1 of the lower file will be read and decrypted.
450 * Returns zero on success; negative on error
452 int ecryptfs_encrypt_page(struct page *page)
454 struct inode *ecryptfs_inode;
455 struct ecryptfs_crypt_stat *crypt_stat;
456 char *enc_extent_virt;
457 struct page *enc_extent_page = NULL;
458 loff_t extent_offset;
462 ecryptfs_inode = page->mapping->host;
464 &(ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat);
465 BUG_ON(!(crypt_stat->flags & ECRYPTFS_ENCRYPTED));
466 enc_extent_page = alloc_page(GFP_USER);
467 if (!enc_extent_page) {
469 ecryptfs_printk(KERN_ERR, "Error allocating memory for "
470 "encrypted extent\n");
474 for (extent_offset = 0;
475 extent_offset < (PAGE_SIZE / crypt_stat->extent_size);
477 rc = crypt_extent(crypt_stat, enc_extent_page, page,
478 extent_offset, ENCRYPT);
480 printk(KERN_ERR "%s: Error encrypting extent; "
481 "rc = [%d]\n", __func__, rc);
486 lower_offset = lower_offset_for_page(crypt_stat, page);
487 enc_extent_virt = kmap(enc_extent_page);
488 rc = ecryptfs_write_lower(ecryptfs_inode, enc_extent_virt, lower_offset,
490 kunmap(enc_extent_page);
492 ecryptfs_printk(KERN_ERR,
493 "Error attempting to write lower page; rc = [%d]\n",
499 if (enc_extent_page) {
500 __free_page(enc_extent_page);
506 * ecryptfs_decrypt_page
507 * @page: Page mapped from the eCryptfs inode for the file; data read
508 * and decrypted from the lower file will be written into this
511 * Decrypt an eCryptfs page. This is done on a per-extent basis. Note
512 * that eCryptfs pages may straddle the lower pages -- for instance,
513 * if the file was created on a machine with an 8K page size
514 * (resulting in an 8K header), and then the file is copied onto a
515 * host with a 32K page size, then when reading page 0 of the eCryptfs
516 * file, 24K of page 0 of the lower file will be read and decrypted,
517 * and then 8K of page 1 of the lower file will be read and decrypted.
519 * Returns zero on success; negative on error
521 int ecryptfs_decrypt_page(struct page *page)
523 struct inode *ecryptfs_inode;
524 struct ecryptfs_crypt_stat *crypt_stat;
526 unsigned long extent_offset;
530 ecryptfs_inode = page->mapping->host;
532 &(ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat);
533 BUG_ON(!(crypt_stat->flags & ECRYPTFS_ENCRYPTED));
535 lower_offset = lower_offset_for_page(crypt_stat, page);
536 page_virt = kmap(page);
537 rc = ecryptfs_read_lower(page_virt, lower_offset, PAGE_SIZE,
541 ecryptfs_printk(KERN_ERR,
542 "Error attempting to read lower page; rc = [%d]\n",
547 for (extent_offset = 0;
548 extent_offset < (PAGE_SIZE / crypt_stat->extent_size);
550 rc = crypt_extent(crypt_stat, page, page,
551 extent_offset, DECRYPT);
553 printk(KERN_ERR "%s: Error encrypting extent; "
554 "rc = [%d]\n", __func__, rc);
562 #define ECRYPTFS_MAX_SCATTERLIST_LEN 4
565 * ecryptfs_init_crypt_ctx
566 * @crypt_stat: Uninitialized crypt stats structure
568 * Initialize the crypto context.
570 * TODO: Performance: Keep a cache of initialized cipher contexts;
571 * only init if needed
573 int ecryptfs_init_crypt_ctx(struct ecryptfs_crypt_stat *crypt_stat)
578 ecryptfs_printk(KERN_DEBUG,
579 "Initializing cipher [%s]; strlen = [%d]; "
580 "key_size_bits = [%zd]\n",
581 crypt_stat->cipher, (int)strlen(crypt_stat->cipher),
582 crypt_stat->key_size << 3);
583 mutex_lock(&crypt_stat->cs_tfm_mutex);
584 if (crypt_stat->tfm) {
588 rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name,
589 crypt_stat->cipher, "cbc");
592 crypt_stat->tfm = crypto_alloc_skcipher(full_alg_name, 0, 0);
593 if (IS_ERR(crypt_stat->tfm)) {
594 rc = PTR_ERR(crypt_stat->tfm);
595 crypt_stat->tfm = NULL;
596 ecryptfs_printk(KERN_ERR, "cryptfs: init_crypt_ctx(): "
597 "Error initializing cipher [%s]\n",
601 crypto_skcipher_set_flags(crypt_stat->tfm,
602 CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
605 kfree(full_alg_name);
607 mutex_unlock(&crypt_stat->cs_tfm_mutex);
611 static void set_extent_mask_and_shift(struct ecryptfs_crypt_stat *crypt_stat)
615 crypt_stat->extent_mask = 0xFFFFFFFF;
616 crypt_stat->extent_shift = 0;
617 if (crypt_stat->extent_size == 0)
619 extent_size_tmp = crypt_stat->extent_size;
620 while ((extent_size_tmp & 0x01) == 0) {
621 extent_size_tmp >>= 1;
622 crypt_stat->extent_mask <<= 1;
623 crypt_stat->extent_shift++;
627 void ecryptfs_set_default_sizes(struct ecryptfs_crypt_stat *crypt_stat)
629 /* Default values; may be overwritten as we are parsing the
631 crypt_stat->extent_size = ECRYPTFS_DEFAULT_EXTENT_SIZE;
632 set_extent_mask_and_shift(crypt_stat);
633 crypt_stat->iv_bytes = ECRYPTFS_DEFAULT_IV_BYTES;
634 if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
635 crypt_stat->metadata_size = ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
637 if (PAGE_SIZE <= ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE)
638 crypt_stat->metadata_size =
639 ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
641 crypt_stat->metadata_size = PAGE_SIZE;
646 * ecryptfs_compute_root_iv
649 * On error, sets the root IV to all 0's.
651 int ecryptfs_compute_root_iv(struct ecryptfs_crypt_stat *crypt_stat)
654 char dst[MD5_DIGEST_SIZE];
656 BUG_ON(crypt_stat->iv_bytes > MD5_DIGEST_SIZE);
657 BUG_ON(crypt_stat->iv_bytes <= 0);
658 if (!(crypt_stat->flags & ECRYPTFS_KEY_VALID)) {
660 ecryptfs_printk(KERN_WARNING, "Session key not valid; "
661 "cannot generate root IV\n");
664 rc = ecryptfs_calculate_md5(dst, crypt_stat, crypt_stat->key,
665 crypt_stat->key_size);
667 ecryptfs_printk(KERN_WARNING, "Error attempting to compute "
668 "MD5 while generating root IV\n");
671 memcpy(crypt_stat->root_iv, dst, crypt_stat->iv_bytes);
674 memset(crypt_stat->root_iv, 0, crypt_stat->iv_bytes);
675 crypt_stat->flags |= ECRYPTFS_SECURITY_WARNING;
680 static void ecryptfs_generate_new_key(struct ecryptfs_crypt_stat *crypt_stat)
682 get_random_bytes(crypt_stat->key, crypt_stat->key_size);
683 crypt_stat->flags |= ECRYPTFS_KEY_VALID;
684 ecryptfs_compute_root_iv(crypt_stat);
685 if (unlikely(ecryptfs_verbosity > 0)) {
686 ecryptfs_printk(KERN_DEBUG, "Generated new session key:\n");
687 ecryptfs_dump_hex(crypt_stat->key,
688 crypt_stat->key_size);
693 * ecryptfs_copy_mount_wide_flags_to_inode_flags
694 * @crypt_stat: The inode's cryptographic context
695 * @mount_crypt_stat: The mount point's cryptographic context
697 * This function propagates the mount-wide flags to individual inode
700 static void ecryptfs_copy_mount_wide_flags_to_inode_flags(
701 struct ecryptfs_crypt_stat *crypt_stat,
702 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
704 if (mount_crypt_stat->flags & ECRYPTFS_XATTR_METADATA_ENABLED)
705 crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
706 if (mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED)
707 crypt_stat->flags |= ECRYPTFS_VIEW_AS_ENCRYPTED;
708 if (mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) {
709 crypt_stat->flags |= ECRYPTFS_ENCRYPT_FILENAMES;
710 if (mount_crypt_stat->flags
711 & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK)
712 crypt_stat->flags |= ECRYPTFS_ENCFN_USE_MOUNT_FNEK;
713 else if (mount_crypt_stat->flags
714 & ECRYPTFS_GLOBAL_ENCFN_USE_FEK)
715 crypt_stat->flags |= ECRYPTFS_ENCFN_USE_FEK;
719 static int ecryptfs_copy_mount_wide_sigs_to_inode_sigs(
720 struct ecryptfs_crypt_stat *crypt_stat,
721 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
723 struct ecryptfs_global_auth_tok *global_auth_tok;
726 mutex_lock(&crypt_stat->keysig_list_mutex);
727 mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
729 list_for_each_entry(global_auth_tok,
730 &mount_crypt_stat->global_auth_tok_list,
731 mount_crypt_stat_list) {
732 if (global_auth_tok->flags & ECRYPTFS_AUTH_TOK_FNEK)
734 rc = ecryptfs_add_keysig(crypt_stat, global_auth_tok->sig);
736 printk(KERN_ERR "Error adding keysig; rc = [%d]\n", rc);
742 mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
743 mutex_unlock(&crypt_stat->keysig_list_mutex);
748 * ecryptfs_set_default_crypt_stat_vals
749 * @crypt_stat: The inode's cryptographic context
750 * @mount_crypt_stat: The mount point's cryptographic context
752 * Default values in the event that policy does not override them.
754 static void ecryptfs_set_default_crypt_stat_vals(
755 struct ecryptfs_crypt_stat *crypt_stat,
756 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
758 ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
760 ecryptfs_set_default_sizes(crypt_stat);
761 strcpy(crypt_stat->cipher, ECRYPTFS_DEFAULT_CIPHER);
762 crypt_stat->key_size = ECRYPTFS_DEFAULT_KEY_BYTES;
763 crypt_stat->flags &= ~(ECRYPTFS_KEY_VALID);
764 crypt_stat->file_version = ECRYPTFS_FILE_VERSION;
765 crypt_stat->mount_crypt_stat = mount_crypt_stat;
769 * ecryptfs_new_file_context
770 * @ecryptfs_inode: The eCryptfs inode
772 * If the crypto context for the file has not yet been established,
773 * this is where we do that. Establishing a new crypto context
774 * involves the following decisions:
775 * - What cipher to use?
776 * - What set of authentication tokens to use?
777 * Here we just worry about getting enough information into the
778 * authentication tokens so that we know that they are available.
779 * We associate the available authentication tokens with the new file
780 * via the set of signatures in the crypt_stat struct. Later, when
781 * the headers are actually written out, we may again defer to
782 * userspace to perform the encryption of the session key; for the
783 * foreseeable future, this will be the case with public key packets.
785 * Returns zero on success; non-zero otherwise
787 int ecryptfs_new_file_context(struct inode *ecryptfs_inode)
789 struct ecryptfs_crypt_stat *crypt_stat =
790 &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
791 struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
792 &ecryptfs_superblock_to_private(
793 ecryptfs_inode->i_sb)->mount_crypt_stat;
797 ecryptfs_set_default_crypt_stat_vals(crypt_stat, mount_crypt_stat);
798 crypt_stat->flags |= (ECRYPTFS_ENCRYPTED | ECRYPTFS_KEY_VALID);
799 ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
801 rc = ecryptfs_copy_mount_wide_sigs_to_inode_sigs(crypt_stat,
804 printk(KERN_ERR "Error attempting to copy mount-wide key sigs "
805 "to the inode key sigs; rc = [%d]\n", rc);
809 strlen(mount_crypt_stat->global_default_cipher_name);
810 memcpy(crypt_stat->cipher,
811 mount_crypt_stat->global_default_cipher_name,
813 crypt_stat->cipher[cipher_name_len] = '\0';
814 crypt_stat->key_size =
815 mount_crypt_stat->global_default_cipher_key_size;
816 ecryptfs_generate_new_key(crypt_stat);
817 rc = ecryptfs_init_crypt_ctx(crypt_stat);
819 ecryptfs_printk(KERN_ERR, "Error initializing cryptographic "
820 "context for cipher [%s]: rc = [%d]\n",
821 crypt_stat->cipher, rc);
827 * ecryptfs_validate_marker - check for the ecryptfs marker
828 * @data: The data block in which to check
830 * Returns zero if marker found; -EINVAL if not found
832 static int ecryptfs_validate_marker(char *data)
836 m_1 = get_unaligned_be32(data);
837 m_2 = get_unaligned_be32(data + 4);
838 if ((m_1 ^ MAGIC_ECRYPTFS_MARKER) == m_2)
840 ecryptfs_printk(KERN_DEBUG, "m_1 = [0x%.8x]; m_2 = [0x%.8x]; "
841 "MAGIC_ECRYPTFS_MARKER = [0x%.8x]\n", m_1, m_2,
842 MAGIC_ECRYPTFS_MARKER);
843 ecryptfs_printk(KERN_DEBUG, "(m_1 ^ MAGIC_ECRYPTFS_MARKER) = "
844 "[0x%.8x]\n", (m_1 ^ MAGIC_ECRYPTFS_MARKER));
848 struct ecryptfs_flag_map_elem {
853 /* Add support for additional flags by adding elements here. */
854 static struct ecryptfs_flag_map_elem ecryptfs_flag_map[] = {
855 {0x00000001, ECRYPTFS_ENABLE_HMAC},
856 {0x00000002, ECRYPTFS_ENCRYPTED},
857 {0x00000004, ECRYPTFS_METADATA_IN_XATTR},
858 {0x00000008, ECRYPTFS_ENCRYPT_FILENAMES}
862 * ecryptfs_process_flags
863 * @crypt_stat: The cryptographic context
864 * @page_virt: Source data to be parsed
865 * @bytes_read: Updated with the number of bytes read
867 static void ecryptfs_process_flags(struct ecryptfs_crypt_stat *crypt_stat,
868 char *page_virt, int *bytes_read)
873 flags = get_unaligned_be32(page_virt);
874 for (i = 0; i < ARRAY_SIZE(ecryptfs_flag_map); i++)
875 if (flags & ecryptfs_flag_map[i].file_flag) {
876 crypt_stat->flags |= ecryptfs_flag_map[i].local_flag;
878 crypt_stat->flags &= ~(ecryptfs_flag_map[i].local_flag);
879 /* Version is in top 8 bits of the 32-bit flag vector */
880 crypt_stat->file_version = ((flags >> 24) & 0xFF);
885 * write_ecryptfs_marker
886 * @page_virt: The pointer to in a page to begin writing the marker
887 * @written: Number of bytes written
889 * Marker = 0x3c81b7f5
891 static void write_ecryptfs_marker(char *page_virt, size_t *written)
895 get_random_bytes(&m_1, (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
896 m_2 = (m_1 ^ MAGIC_ECRYPTFS_MARKER);
897 put_unaligned_be32(m_1, page_virt);
898 page_virt += (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2);
899 put_unaligned_be32(m_2, page_virt);
900 (*written) = MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
903 void ecryptfs_write_crypt_stat_flags(char *page_virt,
904 struct ecryptfs_crypt_stat *crypt_stat,
910 for (i = 0; i < ARRAY_SIZE(ecryptfs_flag_map); i++)
911 if (crypt_stat->flags & ecryptfs_flag_map[i].local_flag)
912 flags |= ecryptfs_flag_map[i].file_flag;
913 /* Version is in top 8 bits of the 32-bit flag vector */
914 flags |= ((((u8)crypt_stat->file_version) << 24) & 0xFF000000);
915 put_unaligned_be32(flags, page_virt);
919 struct ecryptfs_cipher_code_str_map_elem {
924 /* Add support for additional ciphers by adding elements here. The
925 * cipher_code is whatever OpenPGP applications use to identify the
926 * ciphers. List in order of probability. */
927 static struct ecryptfs_cipher_code_str_map_elem
928 ecryptfs_cipher_code_str_map[] = {
929 {"aes",RFC2440_CIPHER_AES_128 },
930 {"blowfish", RFC2440_CIPHER_BLOWFISH},
931 {"des3_ede", RFC2440_CIPHER_DES3_EDE},
932 {"cast5", RFC2440_CIPHER_CAST_5},
933 {"twofish", RFC2440_CIPHER_TWOFISH},
934 {"cast6", RFC2440_CIPHER_CAST_6},
935 {"aes", RFC2440_CIPHER_AES_192},
936 {"aes", RFC2440_CIPHER_AES_256}
940 * ecryptfs_code_for_cipher_string
941 * @cipher_name: The string alias for the cipher
942 * @key_bytes: Length of key in bytes; used for AES code selection
944 * Returns zero on no match, or the cipher code on match
946 u8 ecryptfs_code_for_cipher_string(char *cipher_name, size_t key_bytes)
950 struct ecryptfs_cipher_code_str_map_elem *map =
951 ecryptfs_cipher_code_str_map;
953 if (strcmp(cipher_name, "aes") == 0) {
956 code = RFC2440_CIPHER_AES_128;
959 code = RFC2440_CIPHER_AES_192;
962 code = RFC2440_CIPHER_AES_256;
965 for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
966 if (strcmp(cipher_name, map[i].cipher_str) == 0) {
967 code = map[i].cipher_code;
975 * ecryptfs_cipher_code_to_string
976 * @str: Destination to write out the cipher name
977 * @cipher_code: The code to convert to cipher name string
979 * Returns zero on success
981 int ecryptfs_cipher_code_to_string(char *str, u8 cipher_code)
987 for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
988 if (cipher_code == ecryptfs_cipher_code_str_map[i].cipher_code)
989 strcpy(str, ecryptfs_cipher_code_str_map[i].cipher_str);
990 if (str[0] == '\0') {
991 ecryptfs_printk(KERN_WARNING, "Cipher code not recognized: "
992 "[%d]\n", cipher_code);
998 int ecryptfs_read_and_validate_header_region(struct inode *inode)
1000 u8 file_size[ECRYPTFS_SIZE_AND_MARKER_BYTES];
1001 u8 *marker = file_size + ECRYPTFS_FILE_SIZE_BYTES;
1004 rc = ecryptfs_read_lower(file_size, 0, ECRYPTFS_SIZE_AND_MARKER_BYTES,
1008 else if (rc < ECRYPTFS_SIZE_AND_MARKER_BYTES)
1010 rc = ecryptfs_validate_marker(marker);
1012 ecryptfs_i_size_init(file_size, inode);
1017 ecryptfs_write_header_metadata(char *virt,
1018 struct ecryptfs_crypt_stat *crypt_stat,
1021 u32 header_extent_size;
1022 u16 num_header_extents_at_front;
1024 header_extent_size = (u32)crypt_stat->extent_size;
1025 num_header_extents_at_front =
1026 (u16)(crypt_stat->metadata_size / crypt_stat->extent_size);
1027 put_unaligned_be32(header_extent_size, virt);
1029 put_unaligned_be16(num_header_extents_at_front, virt);
1033 struct kmem_cache *ecryptfs_header_cache;
1036 * ecryptfs_write_headers_virt
1037 * @page_virt: The virtual address to write the headers to
1038 * @max: The size of memory allocated at page_virt
1039 * @size: Set to the number of bytes written by this function
1040 * @crypt_stat: The cryptographic context
1041 * @ecryptfs_dentry: The eCryptfs dentry
1046 * Octets 0-7: Unencrypted file size (big-endian)
1047 * Octets 8-15: eCryptfs special marker
1048 * Octets 16-19: Flags
1049 * Octet 16: File format version number (between 0 and 255)
1050 * Octets 17-18: Reserved
1051 * Octet 19: Bit 1 (lsb): Reserved
1053 * Bits 3-8: Reserved
1054 * Octets 20-23: Header extent size (big-endian)
1055 * Octets 24-25: Number of header extents at front of file
1057 * Octet 26: Begin RFC 2440 authentication token packet set
1059 * Lower data (CBC encrypted)
1061 * Lower data (CBC encrypted)
1064 * Returns zero on success
1066 static int ecryptfs_write_headers_virt(char *page_virt, size_t max,
1068 struct ecryptfs_crypt_stat *crypt_stat,
1069 struct dentry *ecryptfs_dentry)
1075 offset = ECRYPTFS_FILE_SIZE_BYTES;
1076 write_ecryptfs_marker((page_virt + offset), &written);
1078 ecryptfs_write_crypt_stat_flags((page_virt + offset), crypt_stat,
1081 ecryptfs_write_header_metadata((page_virt + offset), crypt_stat,
1084 rc = ecryptfs_generate_key_packet_set((page_virt + offset), crypt_stat,
1085 ecryptfs_dentry, &written,
1088 ecryptfs_printk(KERN_WARNING, "Error generating key packet "
1089 "set; rc = [%d]\n", rc);
1098 ecryptfs_write_metadata_to_contents(struct inode *ecryptfs_inode,
1099 char *virt, size_t virt_len)
1103 rc = ecryptfs_write_lower(ecryptfs_inode, virt,
1106 printk(KERN_ERR "%s: Error attempting to write header "
1107 "information to lower file; rc = [%d]\n", __func__, rc);
1114 ecryptfs_write_metadata_to_xattr(struct dentry *ecryptfs_dentry,
1115 struct inode *ecryptfs_inode,
1116 char *page_virt, size_t size)
1119 struct dentry *lower_dentry = ecryptfs_dentry_to_lower(ecryptfs_dentry);
1120 struct inode *lower_inode = d_inode(lower_dentry);
1122 if (!(lower_inode->i_opflags & IOP_XATTR)) {
1127 inode_lock(lower_inode);
1128 rc = __vfs_setxattr(lower_dentry, lower_inode, ECRYPTFS_XATTR_NAME,
1129 page_virt, size, 0);
1130 if (!rc && ecryptfs_inode)
1131 fsstack_copy_attr_all(ecryptfs_inode, lower_inode);
1132 inode_unlock(lower_inode);
1137 static unsigned long ecryptfs_get_zeroed_pages(gfp_t gfp_mask,
1142 page = alloc_pages(gfp_mask | __GFP_ZERO, order);
1144 return (unsigned long) page_address(page);
1149 * ecryptfs_write_metadata
1150 * @ecryptfs_dentry: The eCryptfs dentry, which should be negative
1151 * @ecryptfs_inode: The newly created eCryptfs inode
1153 * Write the file headers out. This will likely involve a userspace
1154 * callout, in which the session key is encrypted with one or more
1155 * public keys and/or the passphrase necessary to do the encryption is
1156 * retrieved via a prompt. Exactly what happens at this point should
1157 * be policy-dependent.
1159 * Returns zero on success; non-zero on error
1161 int ecryptfs_write_metadata(struct dentry *ecryptfs_dentry,
1162 struct inode *ecryptfs_inode)
1164 struct ecryptfs_crypt_stat *crypt_stat =
1165 &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
1172 if (likely(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
1173 if (!(crypt_stat->flags & ECRYPTFS_KEY_VALID)) {
1174 printk(KERN_ERR "Key is invalid; bailing out\n");
1179 printk(KERN_WARNING "%s: Encrypted flag not set\n",
1184 virt_len = crypt_stat->metadata_size;
1185 order = get_order(virt_len);
1186 /* Released in this function */
1187 virt = (char *)ecryptfs_get_zeroed_pages(GFP_KERNEL, order);
1189 printk(KERN_ERR "%s: Out of memory\n", __func__);
1193 /* Zeroed page ensures the in-header unencrypted i_size is set to 0 */
1194 rc = ecryptfs_write_headers_virt(virt, virt_len, &size, crypt_stat,
1197 printk(KERN_ERR "%s: Error whilst writing headers; rc = [%d]\n",
1201 if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
1202 rc = ecryptfs_write_metadata_to_xattr(ecryptfs_dentry, ecryptfs_inode,
1205 rc = ecryptfs_write_metadata_to_contents(ecryptfs_inode, virt,
1208 printk(KERN_ERR "%s: Error writing metadata out to lower file; "
1209 "rc = [%d]\n", __func__, rc);
1213 free_pages((unsigned long)virt, order);
1218 #define ECRYPTFS_DONT_VALIDATE_HEADER_SIZE 0
1219 #define ECRYPTFS_VALIDATE_HEADER_SIZE 1
1220 static int parse_header_metadata(struct ecryptfs_crypt_stat *crypt_stat,
1221 char *virt, int *bytes_read,
1222 int validate_header_size)
1225 u32 header_extent_size;
1226 u16 num_header_extents_at_front;
1228 header_extent_size = get_unaligned_be32(virt);
1229 virt += sizeof(__be32);
1230 num_header_extents_at_front = get_unaligned_be16(virt);
1231 crypt_stat->metadata_size = (((size_t)num_header_extents_at_front
1232 * (size_t)header_extent_size));
1233 (*bytes_read) = (sizeof(__be32) + sizeof(__be16));
1234 if ((validate_header_size == ECRYPTFS_VALIDATE_HEADER_SIZE)
1235 && (crypt_stat->metadata_size
1236 < ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE)) {
1238 printk(KERN_WARNING "Invalid header size: [%zd]\n",
1239 crypt_stat->metadata_size);
1245 * set_default_header_data
1246 * @crypt_stat: The cryptographic context
1248 * For version 0 file format; this function is only for backwards
1249 * compatibility for files created with the prior versions of
1252 static void set_default_header_data(struct ecryptfs_crypt_stat *crypt_stat)
1254 crypt_stat->metadata_size = ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
1257 void ecryptfs_i_size_init(const char *page_virt, struct inode *inode)
1259 struct ecryptfs_mount_crypt_stat *mount_crypt_stat;
1260 struct ecryptfs_crypt_stat *crypt_stat;
1263 crypt_stat = &ecryptfs_inode_to_private(inode)->crypt_stat;
1265 &ecryptfs_superblock_to_private(inode->i_sb)->mount_crypt_stat;
1266 if (mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED) {
1267 file_size = i_size_read(ecryptfs_inode_to_lower(inode));
1268 if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
1269 file_size += crypt_stat->metadata_size;
1271 file_size = get_unaligned_be64(page_virt);
1272 i_size_write(inode, (loff_t)file_size);
1273 crypt_stat->flags |= ECRYPTFS_I_SIZE_INITIALIZED;
1277 * ecryptfs_read_headers_virt
1278 * @page_virt: The virtual address into which to read the headers
1279 * @crypt_stat: The cryptographic context
1280 * @ecryptfs_dentry: The eCryptfs dentry
1281 * @validate_header_size: Whether to validate the header size while reading
1283 * Read/parse the header data. The header format is detailed in the
1284 * comment block for the ecryptfs_write_headers_virt() function.
1286 * Returns zero on success
1288 static int ecryptfs_read_headers_virt(char *page_virt,
1289 struct ecryptfs_crypt_stat *crypt_stat,
1290 struct dentry *ecryptfs_dentry,
1291 int validate_header_size)
1297 ecryptfs_set_default_sizes(crypt_stat);
1298 crypt_stat->mount_crypt_stat = &ecryptfs_superblock_to_private(
1299 ecryptfs_dentry->d_sb)->mount_crypt_stat;
1300 offset = ECRYPTFS_FILE_SIZE_BYTES;
1301 rc = ecryptfs_validate_marker(page_virt + offset);
1304 if (!(crypt_stat->flags & ECRYPTFS_I_SIZE_INITIALIZED))
1305 ecryptfs_i_size_init(page_virt, d_inode(ecryptfs_dentry));
1306 offset += MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
1307 ecryptfs_process_flags(crypt_stat, (page_virt + offset), &bytes_read);
1308 if (crypt_stat->file_version > ECRYPTFS_SUPPORTED_FILE_VERSION) {
1309 ecryptfs_printk(KERN_WARNING, "File version is [%d]; only "
1310 "file version [%d] is supported by this "
1311 "version of eCryptfs\n",
1312 crypt_stat->file_version,
1313 ECRYPTFS_SUPPORTED_FILE_VERSION);
1317 offset += bytes_read;
1318 if (crypt_stat->file_version >= 1) {
1319 rc = parse_header_metadata(crypt_stat, (page_virt + offset),
1320 &bytes_read, validate_header_size);
1322 ecryptfs_printk(KERN_WARNING, "Error reading header "
1323 "metadata; rc = [%d]\n", rc);
1325 offset += bytes_read;
1327 set_default_header_data(crypt_stat);
1328 rc = ecryptfs_parse_packet_set(crypt_stat, (page_virt + offset),
1335 * ecryptfs_read_xattr_region
1336 * @page_virt: The vitual address into which to read the xattr data
1337 * @ecryptfs_inode: The eCryptfs inode
1339 * Attempts to read the crypto metadata from the extended attribute
1340 * region of the lower file.
1342 * Returns zero on success; non-zero on error
1344 int ecryptfs_read_xattr_region(char *page_virt, struct inode *ecryptfs_inode)
1346 struct dentry *lower_dentry =
1347 ecryptfs_inode_to_private(ecryptfs_inode)->lower_file->f_path.dentry;
1351 size = ecryptfs_getxattr_lower(lower_dentry,
1352 ecryptfs_inode_to_lower(ecryptfs_inode),
1353 ECRYPTFS_XATTR_NAME,
1354 page_virt, ECRYPTFS_DEFAULT_EXTENT_SIZE);
1356 if (unlikely(ecryptfs_verbosity > 0))
1357 printk(KERN_INFO "Error attempting to read the [%s] "
1358 "xattr from the lower file; return value = "
1359 "[%zd]\n", ECRYPTFS_XATTR_NAME, size);
1367 int ecryptfs_read_and_validate_xattr_region(struct dentry *dentry,
1368 struct inode *inode)
1370 u8 file_size[ECRYPTFS_SIZE_AND_MARKER_BYTES];
1371 u8 *marker = file_size + ECRYPTFS_FILE_SIZE_BYTES;
1374 rc = ecryptfs_getxattr_lower(ecryptfs_dentry_to_lower(dentry),
1375 ecryptfs_inode_to_lower(inode),
1376 ECRYPTFS_XATTR_NAME, file_size,
1377 ECRYPTFS_SIZE_AND_MARKER_BYTES);
1380 else if (rc < ECRYPTFS_SIZE_AND_MARKER_BYTES)
1382 rc = ecryptfs_validate_marker(marker);
1384 ecryptfs_i_size_init(file_size, inode);
1389 * ecryptfs_read_metadata
1391 * Common entry point for reading file metadata. From here, we could
1392 * retrieve the header information from the header region of the file,
1393 * the xattr region of the file, or some other repository that is
1394 * stored separately from the file itself. The current implementation
1395 * supports retrieving the metadata information from the file contents
1396 * and from the xattr region.
1398 * Returns zero if valid headers found and parsed; non-zero otherwise
1400 int ecryptfs_read_metadata(struct dentry *ecryptfs_dentry)
1404 struct inode *ecryptfs_inode = d_inode(ecryptfs_dentry);
1405 struct ecryptfs_crypt_stat *crypt_stat =
1406 &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
1407 struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1408 &ecryptfs_superblock_to_private(
1409 ecryptfs_dentry->d_sb)->mount_crypt_stat;
1411 ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
1413 /* Read the first page from the underlying file */
1414 page_virt = kmem_cache_alloc(ecryptfs_header_cache, GFP_USER);
1419 rc = ecryptfs_read_lower(page_virt, 0, crypt_stat->extent_size,
1422 rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
1424 ECRYPTFS_VALIDATE_HEADER_SIZE);
1426 /* metadata is not in the file header, so try xattrs */
1427 memset(page_virt, 0, PAGE_SIZE);
1428 rc = ecryptfs_read_xattr_region(page_virt, ecryptfs_inode);
1430 printk(KERN_DEBUG "Valid eCryptfs headers not found in "
1431 "file header region or xattr region, inode %lu\n",
1432 ecryptfs_inode->i_ino);
1436 rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
1438 ECRYPTFS_DONT_VALIDATE_HEADER_SIZE);
1440 printk(KERN_DEBUG "Valid eCryptfs headers not found in "
1441 "file xattr region either, inode %lu\n",
1442 ecryptfs_inode->i_ino);
1445 if (crypt_stat->mount_crypt_stat->flags
1446 & ECRYPTFS_XATTR_METADATA_ENABLED) {
1447 crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
1449 printk(KERN_WARNING "Attempt to access file with "
1450 "crypto metadata only in the extended attribute "
1451 "region, but eCryptfs was mounted without "
1452 "xattr support enabled. eCryptfs will not treat "
1453 "this like an encrypted file, inode %lu\n",
1454 ecryptfs_inode->i_ino);
1460 memset(page_virt, 0, PAGE_SIZE);
1461 kmem_cache_free(ecryptfs_header_cache, page_virt);
1467 * ecryptfs_encrypt_filename - encrypt filename
1469 * CBC-encrypts the filename. We do not want to encrypt the same
1470 * filename with the same key and IV, which may happen with hard
1471 * links, so we prepend random bits to each filename.
1473 * Returns zero on success; non-zero otherwise
1476 ecryptfs_encrypt_filename(struct ecryptfs_filename *filename,
1477 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
1481 filename->encrypted_filename = NULL;
1482 filename->encrypted_filename_size = 0;
1483 if (mount_crypt_stat && (mount_crypt_stat->flags
1484 & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK)) {
1486 size_t remaining_bytes;
1488 rc = ecryptfs_write_tag_70_packet(
1490 &filename->encrypted_filename_size,
1491 mount_crypt_stat, NULL,
1492 filename->filename_size);
1494 printk(KERN_ERR "%s: Error attempting to get packet "
1495 "size for tag 72; rc = [%d]\n", __func__,
1497 filename->encrypted_filename_size = 0;
1500 filename->encrypted_filename =
1501 kmalloc(filename->encrypted_filename_size, GFP_KERNEL);
1502 if (!filename->encrypted_filename) {
1506 remaining_bytes = filename->encrypted_filename_size;
1507 rc = ecryptfs_write_tag_70_packet(filename->encrypted_filename,
1512 filename->filename_size);
1514 printk(KERN_ERR "%s: Error attempting to generate "
1515 "tag 70 packet; rc = [%d]\n", __func__,
1517 kfree(filename->encrypted_filename);
1518 filename->encrypted_filename = NULL;
1519 filename->encrypted_filename_size = 0;
1522 filename->encrypted_filename_size = packet_size;
1524 printk(KERN_ERR "%s: No support for requested filename "
1525 "encryption method in this release\n", __func__);
1533 static int ecryptfs_copy_filename(char **copied_name, size_t *copied_name_size,
1534 const char *name, size_t name_size)
1538 (*copied_name) = kmalloc((name_size + 1), GFP_KERNEL);
1539 if (!(*copied_name)) {
1543 memcpy((void *)(*copied_name), (void *)name, name_size);
1544 (*copied_name)[(name_size)] = '\0'; /* Only for convenience
1545 * in printing out the
1548 (*copied_name_size) = name_size;
1554 * ecryptfs_process_key_cipher - Perform key cipher initialization.
1555 * @key_tfm: Crypto context for key material, set by this function
1556 * @cipher_name: Name of the cipher
1557 * @key_size: Size of the key in bytes
1559 * Returns zero on success. Any crypto_tfm structs allocated here
1560 * should be released by other functions, such as on a superblock put
1561 * event, regardless of whether this function succeeds for fails.
1564 ecryptfs_process_key_cipher(struct crypto_skcipher **key_tfm,
1565 char *cipher_name, size_t *key_size)
1567 char dummy_key[ECRYPTFS_MAX_KEY_BYTES];
1568 char *full_alg_name = NULL;
1572 if (*key_size > ECRYPTFS_MAX_KEY_BYTES) {
1574 printk(KERN_ERR "Requested key size is [%zd] bytes; maximum "
1575 "allowable is [%d]\n", *key_size, ECRYPTFS_MAX_KEY_BYTES);
1578 rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name, cipher_name,
1582 *key_tfm = crypto_alloc_skcipher(full_alg_name, 0, CRYPTO_ALG_ASYNC);
1583 if (IS_ERR(*key_tfm)) {
1584 rc = PTR_ERR(*key_tfm);
1585 printk(KERN_ERR "Unable to allocate crypto cipher with name "
1586 "[%s]; rc = [%d]\n", full_alg_name, rc);
1589 crypto_skcipher_set_flags(*key_tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
1591 *key_size = crypto_skcipher_max_keysize(*key_tfm);
1592 get_random_bytes(dummy_key, *key_size);
1593 rc = crypto_skcipher_setkey(*key_tfm, dummy_key, *key_size);
1595 printk(KERN_ERR "Error attempting to set key of size [%zd] for "
1596 "cipher [%s]; rc = [%d]\n", *key_size, full_alg_name,
1602 kfree(full_alg_name);
1606 struct kmem_cache *ecryptfs_key_tfm_cache;
1607 static struct list_head key_tfm_list;
1608 struct mutex key_tfm_list_mutex;
1610 int __init ecryptfs_init_crypto(void)
1612 mutex_init(&key_tfm_list_mutex);
1613 INIT_LIST_HEAD(&key_tfm_list);
1618 * ecryptfs_destroy_crypto - free all cached key_tfms on key_tfm_list
1620 * Called only at module unload time
1622 int ecryptfs_destroy_crypto(void)
1624 struct ecryptfs_key_tfm *key_tfm, *key_tfm_tmp;
1626 mutex_lock(&key_tfm_list_mutex);
1627 list_for_each_entry_safe(key_tfm, key_tfm_tmp, &key_tfm_list,
1629 list_del(&key_tfm->key_tfm_list);
1630 crypto_free_skcipher(key_tfm->key_tfm);
1631 kmem_cache_free(ecryptfs_key_tfm_cache, key_tfm);
1633 mutex_unlock(&key_tfm_list_mutex);
1638 ecryptfs_add_new_key_tfm(struct ecryptfs_key_tfm **key_tfm, char *cipher_name,
1641 struct ecryptfs_key_tfm *tmp_tfm;
1644 BUG_ON(!mutex_is_locked(&key_tfm_list_mutex));
1646 tmp_tfm = kmem_cache_alloc(ecryptfs_key_tfm_cache, GFP_KERNEL);
1648 (*key_tfm) = tmp_tfm;
1653 mutex_init(&tmp_tfm->key_tfm_mutex);
1654 strncpy(tmp_tfm->cipher_name, cipher_name,
1655 ECRYPTFS_MAX_CIPHER_NAME_SIZE);
1656 tmp_tfm->cipher_name[ECRYPTFS_MAX_CIPHER_NAME_SIZE] = '\0';
1657 tmp_tfm->key_size = key_size;
1658 rc = ecryptfs_process_key_cipher(&tmp_tfm->key_tfm,
1659 tmp_tfm->cipher_name,
1660 &tmp_tfm->key_size);
1662 printk(KERN_ERR "Error attempting to initialize key TFM "
1663 "cipher with name = [%s]; rc = [%d]\n",
1664 tmp_tfm->cipher_name, rc);
1665 kmem_cache_free(ecryptfs_key_tfm_cache, tmp_tfm);
1670 list_add(&tmp_tfm->key_tfm_list, &key_tfm_list);
1676 * ecryptfs_tfm_exists - Search for existing tfm for cipher_name.
1677 * @cipher_name: the name of the cipher to search for
1678 * @key_tfm: set to corresponding tfm if found
1680 * Searches for cached key_tfm matching @cipher_name
1681 * Must be called with &key_tfm_list_mutex held
1682 * Returns 1 if found, with @key_tfm set
1683 * Returns 0 if not found, with @key_tfm set to NULL
1685 int ecryptfs_tfm_exists(char *cipher_name, struct ecryptfs_key_tfm **key_tfm)
1687 struct ecryptfs_key_tfm *tmp_key_tfm;
1689 BUG_ON(!mutex_is_locked(&key_tfm_list_mutex));
1691 list_for_each_entry(tmp_key_tfm, &key_tfm_list, key_tfm_list) {
1692 if (strcmp(tmp_key_tfm->cipher_name, cipher_name) == 0) {
1694 (*key_tfm) = tmp_key_tfm;
1704 * ecryptfs_get_tfm_and_mutex_for_cipher_name
1706 * @tfm: set to cached tfm found, or new tfm created
1707 * @tfm_mutex: set to mutex for cached tfm found, or new tfm created
1708 * @cipher_name: the name of the cipher to search for and/or add
1710 * Sets pointers to @tfm & @tfm_mutex matching @cipher_name.
1711 * Searches for cached item first, and creates new if not found.
1712 * Returns 0 on success, non-zero if adding new cipher failed
1714 int ecryptfs_get_tfm_and_mutex_for_cipher_name(struct crypto_skcipher **tfm,
1715 struct mutex **tfm_mutex,
1718 struct ecryptfs_key_tfm *key_tfm;
1722 (*tfm_mutex) = NULL;
1724 mutex_lock(&key_tfm_list_mutex);
1725 if (!ecryptfs_tfm_exists(cipher_name, &key_tfm)) {
1726 rc = ecryptfs_add_new_key_tfm(&key_tfm, cipher_name, 0);
1728 printk(KERN_ERR "Error adding new key_tfm to list; "
1733 (*tfm) = key_tfm->key_tfm;
1734 (*tfm_mutex) = &key_tfm->key_tfm_mutex;
1736 mutex_unlock(&key_tfm_list_mutex);
1740 /* 64 characters forming a 6-bit target field */
1741 static unsigned char *portable_filename_chars = ("-.0123456789ABCD"
1744 "klmnopqrstuvwxyz");
1746 /* We could either offset on every reverse map or just pad some 0x00's
1747 * at the front here */
1748 static const unsigned char filename_rev_map[256] = {
1749 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 7 */
1750 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 15 */
1751 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 23 */
1752 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 31 */
1753 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 39 */
1754 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, /* 47 */
1755 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, /* 55 */
1756 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 63 */
1757 0x00, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, /* 71 */
1758 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, /* 79 */
1759 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, /* 87 */
1760 0x23, 0x24, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, /* 95 */
1761 0x00, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, /* 103 */
1762 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, /* 111 */
1763 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, /* 119 */
1764 0x3D, 0x3E, 0x3F /* 123 - 255 initialized to 0x00 */
1768 * ecryptfs_encode_for_filename
1769 * @dst: Destination location for encoded filename
1770 * @dst_size: Size of the encoded filename in bytes
1771 * @src: Source location for the filename to encode
1772 * @src_size: Size of the source in bytes
1774 static void ecryptfs_encode_for_filename(unsigned char *dst, size_t *dst_size,
1775 unsigned char *src, size_t src_size)
1778 size_t block_num = 0;
1779 size_t dst_offset = 0;
1780 unsigned char last_block[3];
1782 if (src_size == 0) {
1786 num_blocks = (src_size / 3);
1787 if ((src_size % 3) == 0) {
1788 memcpy(last_block, (&src[src_size - 3]), 3);
1791 last_block[2] = 0x00;
1792 switch (src_size % 3) {
1794 last_block[0] = src[src_size - 1];
1795 last_block[1] = 0x00;
1798 last_block[0] = src[src_size - 2];
1799 last_block[1] = src[src_size - 1];
1802 (*dst_size) = (num_blocks * 4);
1805 while (block_num < num_blocks) {
1806 unsigned char *src_block;
1807 unsigned char dst_block[4];
1809 if (block_num == (num_blocks - 1))
1810 src_block = last_block;
1812 src_block = &src[block_num * 3];
1813 dst_block[0] = ((src_block[0] >> 2) & 0x3F);
1814 dst_block[1] = (((src_block[0] << 4) & 0x30)
1815 | ((src_block[1] >> 4) & 0x0F));
1816 dst_block[2] = (((src_block[1] << 2) & 0x3C)
1817 | ((src_block[2] >> 6) & 0x03));
1818 dst_block[3] = (src_block[2] & 0x3F);
1819 dst[dst_offset++] = portable_filename_chars[dst_block[0]];
1820 dst[dst_offset++] = portable_filename_chars[dst_block[1]];
1821 dst[dst_offset++] = portable_filename_chars[dst_block[2]];
1822 dst[dst_offset++] = portable_filename_chars[dst_block[3]];
1829 static size_t ecryptfs_max_decoded_size(size_t encoded_size)
1831 /* Not exact; conservatively long. Every block of 4
1832 * encoded characters decodes into a block of 3
1833 * decoded characters. This segment of code provides
1834 * the caller with the maximum amount of allocated
1835 * space that @dst will need to point to in a
1836 * subsequent call. */
1837 return ((encoded_size + 1) * 3) / 4;
1841 * ecryptfs_decode_from_filename
1842 * @dst: If NULL, this function only sets @dst_size and returns. If
1843 * non-NULL, this function decodes the encoded octets in @src
1844 * into the memory that @dst points to.
1845 * @dst_size: Set to the size of the decoded string.
1846 * @src: The encoded set of octets to decode.
1847 * @src_size: The size of the encoded set of octets to decode.
1850 ecryptfs_decode_from_filename(unsigned char *dst, size_t *dst_size,
1851 const unsigned char *src, size_t src_size)
1853 u8 current_bit_offset = 0;
1854 size_t src_byte_offset = 0;
1855 size_t dst_byte_offset = 0;
1858 (*dst_size) = ecryptfs_max_decoded_size(src_size);
1861 while (src_byte_offset < src_size) {
1862 unsigned char src_byte =
1863 filename_rev_map[(int)src[src_byte_offset]];
1865 switch (current_bit_offset) {
1867 dst[dst_byte_offset] = (src_byte << 2);
1868 current_bit_offset = 6;
1871 dst[dst_byte_offset++] |= (src_byte >> 4);
1872 dst[dst_byte_offset] = ((src_byte & 0xF)
1874 current_bit_offset = 4;
1877 dst[dst_byte_offset++] |= (src_byte >> 2);
1878 dst[dst_byte_offset] = (src_byte << 6);
1879 current_bit_offset = 2;
1882 dst[dst_byte_offset++] |= (src_byte);
1883 current_bit_offset = 0;
1888 (*dst_size) = dst_byte_offset;
1894 * ecryptfs_encrypt_and_encode_filename - converts a plaintext file name to cipher text
1895 * @crypt_stat: The crypt_stat struct associated with the file anem to encode
1896 * @name: The plaintext name
1897 * @length: The length of the plaintext
1898 * @encoded_name: The encypted name
1900 * Encrypts and encodes a filename into something that constitutes a
1901 * valid filename for a filesystem, with printable characters.
1903 * We assume that we have a properly initialized crypto context,
1904 * pointed to by crypt_stat->tfm.
1906 * Returns zero on success; non-zero on otherwise
1908 int ecryptfs_encrypt_and_encode_filename(
1909 char **encoded_name,
1910 size_t *encoded_name_size,
1911 struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
1912 const char *name, size_t name_size)
1914 size_t encoded_name_no_prefix_size;
1917 (*encoded_name) = NULL;
1918 (*encoded_name_size) = 0;
1919 if (mount_crypt_stat && (mount_crypt_stat->flags
1920 & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)) {
1921 struct ecryptfs_filename *filename;
1923 filename = kzalloc(sizeof(*filename), GFP_KERNEL);
1928 filename->filename = (char *)name;
1929 filename->filename_size = name_size;
1930 rc = ecryptfs_encrypt_filename(filename, mount_crypt_stat);
1932 printk(KERN_ERR "%s: Error attempting to encrypt "
1933 "filename; rc = [%d]\n", __func__, rc);
1937 ecryptfs_encode_for_filename(
1938 NULL, &encoded_name_no_prefix_size,
1939 filename->encrypted_filename,
1940 filename->encrypted_filename_size);
1941 if (mount_crypt_stat
1942 && (mount_crypt_stat->flags
1943 & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK))
1944 (*encoded_name_size) =
1945 (ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE
1946 + encoded_name_no_prefix_size);
1948 (*encoded_name_size) =
1949 (ECRYPTFS_FEK_ENCRYPTED_FILENAME_PREFIX_SIZE
1950 + encoded_name_no_prefix_size);
1951 (*encoded_name) = kmalloc((*encoded_name_size) + 1, GFP_KERNEL);
1952 if (!(*encoded_name)) {
1954 kfree(filename->encrypted_filename);
1958 if (mount_crypt_stat
1959 && (mount_crypt_stat->flags
1960 & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK)) {
1961 memcpy((*encoded_name),
1962 ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX,
1963 ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE);
1964 ecryptfs_encode_for_filename(
1966 + ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE),
1967 &encoded_name_no_prefix_size,
1968 filename->encrypted_filename,
1969 filename->encrypted_filename_size);
1970 (*encoded_name_size) =
1971 (ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE
1972 + encoded_name_no_prefix_size);
1973 (*encoded_name)[(*encoded_name_size)] = '\0';
1978 printk(KERN_ERR "%s: Error attempting to encode "
1979 "encrypted filename; rc = [%d]\n", __func__,
1981 kfree((*encoded_name));
1982 (*encoded_name) = NULL;
1983 (*encoded_name_size) = 0;
1985 kfree(filename->encrypted_filename);
1988 rc = ecryptfs_copy_filename(encoded_name,
1996 static bool is_dot_dotdot(const char *name, size_t name_size)
1998 if (name_size == 1 && name[0] == '.')
2000 else if (name_size == 2 && name[0] == '.' && name[1] == '.')
2007 * ecryptfs_decode_and_decrypt_filename - converts the encoded cipher text name to decoded plaintext
2008 * @plaintext_name: The plaintext name
2009 * @plaintext_name_size: The plaintext name size
2010 * @ecryptfs_dir_dentry: eCryptfs directory dentry
2011 * @name: The filename in cipher text
2012 * @name_size: The cipher text name size
2014 * Decrypts and decodes the filename.
2016 * Returns zero on error; non-zero otherwise
2018 int ecryptfs_decode_and_decrypt_filename(char **plaintext_name,
2019 size_t *plaintext_name_size,
2020 struct super_block *sb,
2021 const char *name, size_t name_size)
2023 struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
2024 &ecryptfs_superblock_to_private(sb)->mount_crypt_stat;
2026 size_t decoded_name_size;
2030 if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) &&
2031 !(mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED)) {
2032 if (is_dot_dotdot(name, name_size)) {
2033 rc = ecryptfs_copy_filename(plaintext_name,
2034 plaintext_name_size,
2039 if (name_size <= ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE ||
2040 strncmp(name, ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX,
2041 ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE)) {
2046 name += ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE;
2047 name_size -= ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE;
2048 ecryptfs_decode_from_filename(NULL, &decoded_name_size,
2050 decoded_name = kmalloc(decoded_name_size, GFP_KERNEL);
2051 if (!decoded_name) {
2055 ecryptfs_decode_from_filename(decoded_name, &decoded_name_size,
2057 rc = ecryptfs_parse_tag_70_packet(plaintext_name,
2058 plaintext_name_size,
2064 ecryptfs_printk(KERN_DEBUG,
2065 "%s: Could not parse tag 70 packet from filename\n",
2070 rc = ecryptfs_copy_filename(plaintext_name,
2071 plaintext_name_size,
2076 kfree(decoded_name);
2081 #define ENC_NAME_MAX_BLOCKLEN_8_OR_16 143
2083 int ecryptfs_set_f_namelen(long *namelen, long lower_namelen,
2084 struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
2086 struct crypto_skcipher *tfm;
2087 struct mutex *tfm_mutex;
2088 size_t cipher_blocksize;
2091 if (!(mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)) {
2092 (*namelen) = lower_namelen;
2096 rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&tfm, &tfm_mutex,
2097 mount_crypt_stat->global_default_fn_cipher_name);
2103 mutex_lock(tfm_mutex);
2104 cipher_blocksize = crypto_skcipher_blocksize(tfm);
2105 mutex_unlock(tfm_mutex);
2107 /* Return an exact amount for the common cases */
2108 if (lower_namelen == NAME_MAX
2109 && (cipher_blocksize == 8 || cipher_blocksize == 16)) {
2110 (*namelen) = ENC_NAME_MAX_BLOCKLEN_8_OR_16;
2114 /* Return a safe estimate for the uncommon cases */
2115 (*namelen) = lower_namelen;
2116 (*namelen) -= ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE;
2117 /* Since this is the max decoded size, subtract 1 "decoded block" len */
2118 (*namelen) = ecryptfs_max_decoded_size(*namelen) - 3;
2119 (*namelen) -= ECRYPTFS_TAG_70_MAX_METADATA_SIZE;
2120 (*namelen) -= ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES;
2121 /* Worst case is that the filename is padded nearly a full block size */
2122 (*namelen) -= cipher_blocksize - 1;