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