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