Blame view

fs/ecryptfs/crypto.c 67.5 KB
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1
2
3
4
5
  /**
   * eCryptfs: Linux filesystem encryption layer
   *
   * Copyright (C) 1997-2004 Erez Zadok
   * Copyright (C) 2001-2004 Stony Brook University
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
6
   * Copyright (C) 2004-2007 International Business Machines Corp.
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
   *   Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
   *   		Michael C. Thompson <mcthomps@us.ibm.com>
   *
   * This program is free software; you can redistribute it and/or
   * modify it under the terms of the GNU General Public License as
   * published by the Free Software Foundation; either version 2 of the
   * License, or (at your option) any later version.
   *
   * This program is distributed in the hope that it will be useful, but
   * WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
   * 02111-1307, USA.
   */
  
  #include <linux/fs.h>
  #include <linux/mount.h>
  #include <linux/pagemap.h>
  #include <linux/random.h>
  #include <linux/compiler.h>
  #include <linux/key.h>
  #include <linux/namei.h>
  #include <linux/crypto.h>
  #include <linux/file.h>
  #include <linux/scatterlist.h>
5a0e3ad6a   Tejun Heo   include cleanup: ...
36
  #include <linux/slab.h>
29335c6a4   Harvey Harrison   ecryptfs: crypto....
37
  #include <asm/unaligned.h>
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  #include "ecryptfs_kernel.h"
  
  static int
  ecryptfs_decrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
  			     struct page *dst_page, int dst_offset,
  			     struct page *src_page, int src_offset, int size,
  			     unsigned char *iv);
  static int
  ecryptfs_encrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
  			     struct page *dst_page, int dst_offset,
  			     struct page *src_page, int src_offset, int size,
  			     unsigned char *iv);
  
  /**
   * ecryptfs_to_hex
   * @dst: Buffer to take hex character representation of contents of
   *       src; must be at least of size (src_size * 2)
   * @src: Buffer to be converted to a hex string respresentation
   * @src_size: number of bytes to convert
   */
  void ecryptfs_to_hex(char *dst, char *src, size_t src_size)
  {
  	int x;
  
  	for (x = 0; x < src_size; x++)
  		sprintf(&dst[x * 2], "%.2x", (unsigned char)src[x]);
  }
  
  /**
   * ecryptfs_from_hex
   * @dst: Buffer to take the bytes from src hex; must be at least of
   *       size (src_size / 2)
   * @src: Buffer to be converted from a hex string respresentation to raw value
   * @dst_size: size of dst buffer, or number of hex characters pairs to convert
   */
  void ecryptfs_from_hex(char *dst, char *src, int dst_size)
  {
  	int x;
  	char tmp[3] = { 0, };
  
  	for (x = 0; x < dst_size; x++) {
  		tmp[0] = src[x * 2];
  		tmp[1] = src[x * 2 + 1];
  		dst[x] = (unsigned char)simple_strtol(tmp, NULL, 16);
  	}
  }
  
  /**
   * ecryptfs_calculate_md5 - calculates the md5 of @src
   * @dst: Pointer to 16 bytes of allocated memory
   * @crypt_stat: Pointer to crypt_stat struct for the current inode
   * @src: Data to be md5'd
   * @len: Length of @src
   *
   * Uses the allocated crypto context that crypt_stat references to
   * generate the MD5 sum of the contents of src.
   */
  static int ecryptfs_calculate_md5(char *dst,
  				  struct ecryptfs_crypt_stat *crypt_stat,
  				  char *src, int len)
  {
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
99
  	struct scatterlist sg;
565d9724b   Michael Halcrow   [PATCH] eCryptfs:...
100
101
102
103
104
  	struct hash_desc desc = {
  		.tfm = crypt_stat->hash_tfm,
  		.flags = CRYPTO_TFM_REQ_MAY_SLEEP
  	};
  	int rc = 0;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
105

565d9724b   Michael Halcrow   [PATCH] eCryptfs:...
106
  	mutex_lock(&crypt_stat->cs_hash_tfm_mutex);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
107
  	sg_init_one(&sg, (u8 *)src, len);
565d9724b   Michael Halcrow   [PATCH] eCryptfs:...
108
109
110
111
112
  	if (!desc.tfm) {
  		desc.tfm = crypto_alloc_hash(ECRYPTFS_DEFAULT_HASH, 0,
  					     CRYPTO_ALG_ASYNC);
  		if (IS_ERR(desc.tfm)) {
  			rc = PTR_ERR(desc.tfm);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
113
  			ecryptfs_printk(KERN_ERR, "Error attempting to "
565d9724b   Michael Halcrow   [PATCH] eCryptfs:...
114
115
116
  					"allocate crypto context; rc = [%d]
  ",
  					rc);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
117
118
  			goto out;
  		}
565d9724b   Michael Halcrow   [PATCH] eCryptfs:...
119
  		crypt_stat->hash_tfm = desc.tfm;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
120
  	}
8a29f2b02   Michael Halcrow   eCryptfs: release...
121
122
123
124
125
  	rc = crypto_hash_init(&desc);
  	if (rc) {
  		printk(KERN_ERR
  		       "%s: Error initializing crypto hash; rc = [%d]
  ",
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
126
  		       __func__, rc);
8a29f2b02   Michael Halcrow   eCryptfs: release...
127
128
129
130
131
132
133
  		goto out;
  	}
  	rc = crypto_hash_update(&desc, &sg, len);
  	if (rc) {
  		printk(KERN_ERR
  		       "%s: Error updating crypto hash; rc = [%d]
  ",
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
134
  		       __func__, rc);
8a29f2b02   Michael Halcrow   eCryptfs: release...
135
136
137
138
139
140
141
  		goto out;
  	}
  	rc = crypto_hash_final(&desc, dst);
  	if (rc) {
  		printk(KERN_ERR
  		       "%s: Error finalizing crypto hash; rc = [%d]
  ",
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
142
  		       __func__, rc);
8a29f2b02   Michael Halcrow   eCryptfs: release...
143
144
  		goto out;
  	}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
145
  out:
8a29f2b02   Michael Halcrow   eCryptfs: release...
146
  	mutex_unlock(&crypt_stat->cs_hash_tfm_mutex);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
147
148
  	return rc;
  }
cd9d67dfd   Michael Halcrow   eCryptfs: make ne...
149
150
151
  static int ecryptfs_crypto_api_algify_cipher_name(char **algified_name,
  						  char *cipher_name,
  						  char *chaining_modifier)
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
152
153
154
155
156
157
158
159
  {
  	int cipher_name_len = strlen(cipher_name);
  	int chaining_modifier_len = strlen(chaining_modifier);
  	int algified_name_len;
  	int rc;
  
  	algified_name_len = (chaining_modifier_len + cipher_name_len + 3);
  	(*algified_name) = kmalloc(algified_name_len, GFP_KERNEL);
7bd473fcc   Michael Halcrow   [PATCH] eCryptfs:...
160
  	if (!(*algified_name)) {
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
161
162
163
164
165
166
167
168
169
  		rc = -ENOMEM;
  		goto out;
  	}
  	snprintf((*algified_name), algified_name_len, "%s(%s)",
  		 chaining_modifier, cipher_name);
  	rc = 0;
  out:
  	return rc;
  }
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
170
171
172
173
  /**
   * ecryptfs_derive_iv
   * @iv: destination for the derived iv vale
   * @crypt_stat: Pointer to crypt_stat struct for the current inode
d6a13c171   Michael Halcrow   eCryptfs: fix dat...
174
   * @offset: Offset of the extent whose IV we are to derive
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
175
176
177
178
179
180
   *
   * Generate the initialization vector from the given root IV and page
   * offset.
   *
   * Returns zero on success; non-zero on error.
   */
a34f60f74   Michael Halcrow   eCryptfs: Filenam...
181
182
  int ecryptfs_derive_iv(char *iv, struct ecryptfs_crypt_stat *crypt_stat,
  		       loff_t offset)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
  {
  	int rc = 0;
  	char dst[MD5_DIGEST_SIZE];
  	char src[ECRYPTFS_MAX_IV_BYTES + 16];
  
  	if (unlikely(ecryptfs_verbosity > 0)) {
  		ecryptfs_printk(KERN_DEBUG, "root iv:
  ");
  		ecryptfs_dump_hex(crypt_stat->root_iv, crypt_stat->iv_bytes);
  	}
  	/* TODO: It is probably secure to just cast the least
  	 * significant bits of the root IV into an unsigned long and
  	 * add the offset to that rather than go through all this
  	 * hashing business. -Halcrow */
  	memcpy(src, crypt_stat->root_iv, crypt_stat->iv_bytes);
  	memset((src + crypt_stat->iv_bytes), 0, 16);
d6a13c171   Michael Halcrow   eCryptfs: fix dat...
199
  	snprintf((src + crypt_stat->iv_bytes), 16, "%lld", offset);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
  	if (unlikely(ecryptfs_verbosity > 0)) {
  		ecryptfs_printk(KERN_DEBUG, "source:
  ");
  		ecryptfs_dump_hex(src, (crypt_stat->iv_bytes + 16));
  	}
  	rc = ecryptfs_calculate_md5(dst, crypt_stat, src,
  				    (crypt_stat->iv_bytes + 16));
  	if (rc) {
  		ecryptfs_printk(KERN_WARNING, "Error attempting to compute "
  				"MD5 while generating IV for a page
  ");
  		goto out;
  	}
  	memcpy(iv, dst, crypt_stat->iv_bytes);
  	if (unlikely(ecryptfs_verbosity > 0)) {
  		ecryptfs_printk(KERN_DEBUG, "derived iv:
  ");
  		ecryptfs_dump_hex(iv, crypt_stat->iv_bytes);
  	}
  out:
  	return rc;
  }
  
  /**
   * ecryptfs_init_crypt_stat
   * @crypt_stat: Pointer to the crypt_stat struct to initialize.
   *
   * Initialize the crypt_stat structure.
   */
  void
  ecryptfs_init_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
  {
  	memset((void *)crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
f4aad16ad   Michael Halcrow   eCryptfs: add key...
233
234
  	INIT_LIST_HEAD(&crypt_stat->keysig_list);
  	mutex_init(&crypt_stat->keysig_list_mutex);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
235
236
  	mutex_init(&crypt_stat->cs_mutex);
  	mutex_init(&crypt_stat->cs_tfm_mutex);
565d9724b   Michael Halcrow   [PATCH] eCryptfs:...
237
  	mutex_init(&crypt_stat->cs_hash_tfm_mutex);
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
238
  	crypt_stat->flags |= ECRYPTFS_STRUCT_INITIALIZED;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
239
240
241
  }
  
  /**
fcd128356   Michael Halcrow   eCryptfs: grammat...
242
   * ecryptfs_destroy_crypt_stat
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
243
244
245
246
   * @crypt_stat: Pointer to the crypt_stat struct to initialize.
   *
   * Releases all memory associated with a crypt_stat struct.
   */
fcd128356   Michael Halcrow   eCryptfs: grammat...
247
  void ecryptfs_destroy_crypt_stat(struct ecryptfs_crypt_stat *crypt_stat)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
248
  {
f4aad16ad   Michael Halcrow   eCryptfs: add key...
249
  	struct ecryptfs_key_sig *key_sig, *key_sig_tmp;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
250
  	if (crypt_stat->tfm)
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
251
  		crypto_free_blkcipher(crypt_stat->tfm);
565d9724b   Michael Halcrow   [PATCH] eCryptfs:...
252
253
  	if (crypt_stat->hash_tfm)
  		crypto_free_hash(crypt_stat->hash_tfm);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
254
255
256
257
258
  	list_for_each_entry_safe(key_sig, key_sig_tmp,
  				 &crypt_stat->keysig_list, crypt_stat_list) {
  		list_del(&key_sig->crypt_stat_list);
  		kmem_cache_free(ecryptfs_key_sig_cache, key_sig);
  	}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
259
260
  	memset(crypt_stat, 0, sizeof(struct ecryptfs_crypt_stat));
  }
fcd128356   Michael Halcrow   eCryptfs: grammat...
261
  void ecryptfs_destroy_mount_crypt_stat(
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
262
263
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
  {
f4aad16ad   Michael Halcrow   eCryptfs: add key...
264
265
266
267
268
269
270
271
272
  	struct ecryptfs_global_auth_tok *auth_tok, *auth_tok_tmp;
  
  	if (!(mount_crypt_stat->flags & ECRYPTFS_MOUNT_CRYPT_STAT_INITIALIZED))
  		return;
  	mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
  	list_for_each_entry_safe(auth_tok, auth_tok_tmp,
  				 &mount_crypt_stat->global_auth_tok_list,
  				 mount_crypt_stat_list) {
  		list_del(&auth_tok->mount_crypt_stat_list);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
273
274
275
276
277
278
  		if (auth_tok->global_auth_tok_key
  		    && !(auth_tok->flags & ECRYPTFS_AUTH_TOK_INVALID))
  			key_put(auth_tok->global_auth_tok_key);
  		kmem_cache_free(ecryptfs_global_auth_tok_cache, auth_tok);
  	}
  	mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
  	memset(mount_crypt_stat, 0, sizeof(struct ecryptfs_mount_crypt_stat));
  }
  
  /**
   * virt_to_scatterlist
   * @addr: Virtual address
   * @size: Size of data; should be an even multiple of the block size
   * @sg: Pointer to scatterlist array; set to NULL to obtain only
   *      the number of scatterlist structs required in array
   * @sg_size: Max array size
   *
   * Fills in a scatterlist array with page references for a passed
   * virtual address.
   *
   * Returns the number of scatterlist structs in array used
   */
  int virt_to_scatterlist(const void *addr, int size, struct scatterlist *sg,
  			int sg_size)
  {
  	int i = 0;
  	struct page *pg;
  	int offset;
  	int remainder_of_page;
68e3f5dd4   Herbert Xu   [CRYPTO] users: F...
302
  	sg_init_table(sg, sg_size);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
303
304
305
  	while (size > 0 && i < sg_size) {
  		pg = virt_to_page(addr);
  		offset = offset_in_page(addr);
642f14903   Jens Axboe   SG: Change sg_set...
306
307
  		if (sg)
  			sg_set_page(&sg[i], pg, 0, offset);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
  		remainder_of_page = PAGE_CACHE_SIZE - offset;
  		if (size >= remainder_of_page) {
  			if (sg)
  				sg[i].length = remainder_of_page;
  			addr += remainder_of_page;
  			size -= remainder_of_page;
  		} else {
  			if (sg)
  				sg[i].length = size;
  			addr += size;
  			size = 0;
  		}
  		i++;
  	}
  	if (size > 0)
  		return -ENOMEM;
  	return i;
  }
  
  /**
   * encrypt_scatterlist
   * @crypt_stat: Pointer to the crypt_stat struct to initialize.
   * @dest_sg: Destination of encrypted data
   * @src_sg: Data to be encrypted
   * @size: Length of data to be encrypted
   * @iv: iv to use during encryption
   *
   * Returns the number of bytes encrypted; negative value on error
   */
  static int encrypt_scatterlist(struct ecryptfs_crypt_stat *crypt_stat,
  			       struct scatterlist *dest_sg,
  			       struct scatterlist *src_sg, int size,
  			       unsigned char *iv)
  {
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
342
343
344
345
346
  	struct blkcipher_desc desc = {
  		.tfm = crypt_stat->tfm,
  		.info = iv,
  		.flags = CRYPTO_TFM_REQ_MAY_SLEEP
  	};
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
347
348
349
  	int rc = 0;
  
  	BUG_ON(!crypt_stat || !crypt_stat->tfm
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
350
  	       || !(crypt_stat->flags & ECRYPTFS_STRUCT_INITIALIZED));
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
351
  	if (unlikely(ecryptfs_verbosity > 0)) {
f24b38874   Tyler Hicks   ecryptfs: Fix ecr...
352
353
  		ecryptfs_printk(KERN_DEBUG, "Key size [%zd]; key:
  ",
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
354
355
356
357
358
359
  				crypt_stat->key_size);
  		ecryptfs_dump_hex(crypt_stat->key,
  				  crypt_stat->key_size);
  	}
  	/* Consider doing this once, when the file is opened */
  	mutex_lock(&crypt_stat->cs_tfm_mutex);
8e3a6f16b   Trevor Highland   eCryptfs: set ino...
360
361
362
363
364
  	if (!(crypt_stat->flags & ECRYPTFS_KEY_SET)) {
  		rc = crypto_blkcipher_setkey(crypt_stat->tfm, crypt_stat->key,
  					     crypt_stat->key_size);
  		crypt_stat->flags |= ECRYPTFS_KEY_SET;
  	}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
365
366
367
368
369
370
371
372
373
374
  	if (rc) {
  		ecryptfs_printk(KERN_ERR, "Error setting key; rc = [%d]
  ",
  				rc);
  		mutex_unlock(&crypt_stat->cs_tfm_mutex);
  		rc = -EINVAL;
  		goto out;
  	}
  	ecryptfs_printk(KERN_DEBUG, "Encrypting [%d] bytes.
  ", size);
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
375
  	crypto_blkcipher_encrypt_iv(&desc, dest_sg, src_sg, size);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
376
377
378
379
  	mutex_unlock(&crypt_stat->cs_tfm_mutex);
  out:
  	return rc;
  }
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
380
  /**
0216f7f79   Michael Halcrow   eCryptfs: replace...
381
382
383
384
   * ecryptfs_lower_offset_for_extent
   *
   * Convert an eCryptfs page index into a lower byte offset
   */
7896b6318   Adrian Bunk   fs/ecryptfs/: pos...
385
386
  static void ecryptfs_lower_offset_for_extent(loff_t *offset, loff_t extent_num,
  					     struct ecryptfs_crypt_stat *crypt_stat)
0216f7f79   Michael Halcrow   eCryptfs: replace...
387
  {
157f10713   Tyler Hicks   eCryptfs: Fix met...
388
389
  	(*offset) = ecryptfs_lower_header_size(crypt_stat)
  		    + (crypt_stat->extent_size * extent_num);
0216f7f79   Michael Halcrow   eCryptfs: replace...
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
  }
  
  /**
   * ecryptfs_encrypt_extent
   * @enc_extent_page: Allocated page into which to encrypt the data in
   *                   @page
   * @crypt_stat: crypt_stat containing cryptographic context for the
   *              encryption operation
   * @page: Page containing plaintext data extent to encrypt
   * @extent_offset: Page extent offset for use in generating IV
   *
   * Encrypts one extent of data.
   *
   * Return zero on success; non-zero otherwise
   */
  static int ecryptfs_encrypt_extent(struct page *enc_extent_page,
  				   struct ecryptfs_crypt_stat *crypt_stat,
  				   struct page *page,
  				   unsigned long extent_offset)
  {
d6a13c171   Michael Halcrow   eCryptfs: fix dat...
410
  	loff_t extent_base;
0216f7f79   Michael Halcrow   eCryptfs: replace...
411
412
  	char extent_iv[ECRYPTFS_MAX_IV_BYTES];
  	int rc;
d6a13c171   Michael Halcrow   eCryptfs: fix dat...
413
  	extent_base = (((loff_t)page->index)
0216f7f79   Michael Halcrow   eCryptfs: replace...
414
415
416
417
  		       * (PAGE_CACHE_SIZE / crypt_stat->extent_size));
  	rc = ecryptfs_derive_iv(extent_iv, crypt_stat,
  				(extent_base + extent_offset));
  	if (rc) {
888d57bbc   Joe Perches   fs/ecryptfs: Add ...
418
419
420
421
  		ecryptfs_printk(KERN_ERR, "Error attempting to derive IV for "
  			"extent [0x%.16llx]; rc = [%d]
  ",
  			(unsigned long long)(extent_base + extent_offset), rc);
0216f7f79   Michael Halcrow   eCryptfs: replace...
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
  		goto out;
  	}
  	if (unlikely(ecryptfs_verbosity > 0)) {
  		ecryptfs_printk(KERN_DEBUG, "Encrypting extent "
  				"with iv:
  ");
  		ecryptfs_dump_hex(extent_iv, crypt_stat->iv_bytes);
  		ecryptfs_printk(KERN_DEBUG, "First 8 bytes before "
  				"encryption:
  ");
  		ecryptfs_dump_hex((char *)
  				  (page_address(page)
  				   + (extent_offset * crypt_stat->extent_size)),
  				  8);
  	}
  	rc = ecryptfs_encrypt_page_offset(crypt_stat, enc_extent_page, 0,
  					  page, (extent_offset
  						 * crypt_stat->extent_size),
  					  crypt_stat->extent_size, extent_iv);
  	if (rc < 0) {
  		printk(KERN_ERR "%s: Error attempting to encrypt page with "
  		       "page->index = [%ld], extent_offset = [%ld]; "
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
444
445
  		       "rc = [%d]
  ", __func__, page->index, extent_offset,
0216f7f79   Michael Halcrow   eCryptfs: replace...
446
447
448
449
450
  		       rc);
  		goto out;
  	}
  	rc = 0;
  	if (unlikely(ecryptfs_verbosity > 0)) {
888d57bbc   Joe Perches   fs/ecryptfs: Add ...
451
452
453
454
  		ecryptfs_printk(KERN_DEBUG, "Encrypt extent [0x%.16llx]; "
  			"rc = [%d]
  ",
  			(unsigned long long)(extent_base + extent_offset), rc);
0216f7f79   Michael Halcrow   eCryptfs: replace...
455
456
457
458
459
460
461
462
463
464
  		ecryptfs_printk(KERN_DEBUG, "First 8 bytes after "
  				"encryption:
  ");
  		ecryptfs_dump_hex((char *)(page_address(enc_extent_page)), 8);
  	}
  out:
  	return rc;
  }
  
  /**
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
465
   * ecryptfs_encrypt_page
0216f7f79   Michael Halcrow   eCryptfs: replace...
466
467
468
   * @page: Page mapped from the eCryptfs inode for the file; contains
   *        decrypted content that needs to be encrypted (to a temporary
   *        page; not in place) and written out to the lower file
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
469
470
471
472
473
474
475
476
477
   *
   * Encrypt an eCryptfs page. This is done on a per-extent basis. Note
   * that eCryptfs pages may straddle the lower pages -- for instance,
   * if the file was created on a machine with an 8K page size
   * (resulting in an 8K header), and then the file is copied onto a
   * host with a 32K page size, then when reading page 0 of the eCryptfs
   * file, 24K of page 0 of the lower file will be read and decrypted,
   * and then 8K of page 1 of the lower file will be read and decrypted.
   *
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
478
479
   * Returns zero on success; negative on error
   */
0216f7f79   Michael Halcrow   eCryptfs: replace...
480
  int ecryptfs_encrypt_page(struct page *page)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
481
  {
0216f7f79   Michael Halcrow   eCryptfs: replace...
482
  	struct inode *ecryptfs_inode;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
483
  	struct ecryptfs_crypt_stat *crypt_stat;
7fcba0543   Eric Sandeen   eCryptfs: use pag...
484
485
  	char *enc_extent_virt;
  	struct page *enc_extent_page = NULL;
0216f7f79   Michael Halcrow   eCryptfs: replace...
486
  	loff_t extent_offset;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
487
  	int rc = 0;
0216f7f79   Michael Halcrow   eCryptfs: replace...
488
489
490
491
  
  	ecryptfs_inode = page->mapping->host;
  	crypt_stat =
  		&(ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat);
13a791b4e   Tyler Hicks   eCryptfs: Fix dat...
492
  	BUG_ON(!(crypt_stat->flags & ECRYPTFS_ENCRYPTED));
7fcba0543   Eric Sandeen   eCryptfs: use pag...
493
494
  	enc_extent_page = alloc_page(GFP_USER);
  	if (!enc_extent_page) {
0216f7f79   Michael Halcrow   eCryptfs: replace...
495
496
497
498
499
500
  		rc = -ENOMEM;
  		ecryptfs_printk(KERN_ERR, "Error allocating memory for "
  				"encrypted extent
  ");
  		goto out;
  	}
7fcba0543   Eric Sandeen   eCryptfs: use pag...
501
  	enc_extent_virt = kmap(enc_extent_page);
0216f7f79   Michael Halcrow   eCryptfs: replace...
502
503
504
505
506
507
508
  	for (extent_offset = 0;
  	     extent_offset < (PAGE_CACHE_SIZE / crypt_stat->extent_size);
  	     extent_offset++) {
  		loff_t offset;
  
  		rc = ecryptfs_encrypt_extent(enc_extent_page, crypt_stat, page,
  					     extent_offset);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
509
  		if (rc) {
0216f7f79   Michael Halcrow   eCryptfs: replace...
510
  			printk(KERN_ERR "%s: Error encrypting extent; "
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
511
512
  			       "rc = [%d]
  ", __func__, rc);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
513
514
  			goto out;
  		}
0216f7f79   Michael Halcrow   eCryptfs: replace...
515
  		ecryptfs_lower_offset_for_extent(
d6a13c171   Michael Halcrow   eCryptfs: fix dat...
516
517
518
  			&offset, ((((loff_t)page->index)
  				   * (PAGE_CACHE_SIZE
  				      / crypt_stat->extent_size))
0216f7f79   Michael Halcrow   eCryptfs: replace...
519
520
521
  				  + extent_offset), crypt_stat);
  		rc = ecryptfs_write_lower(ecryptfs_inode, enc_extent_virt,
  					  offset, crypt_stat->extent_size);
96a7b9c2f   Tyler Hicks   eCryptfs: Propaga...
522
  		if (rc < 0) {
0216f7f79   Michael Halcrow   eCryptfs: replace...
523
524
525
526
527
  			ecryptfs_printk(KERN_ERR, "Error attempting "
  					"to write lower page; rc = [%d]"
  					"
  ", rc);
  			goto out;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
528
  		}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
529
  	}
96a7b9c2f   Tyler Hicks   eCryptfs: Propaga...
530
  	rc = 0;
0216f7f79   Michael Halcrow   eCryptfs: replace...
531
  out:
7fcba0543   Eric Sandeen   eCryptfs: use pag...
532
533
534
535
  	if (enc_extent_page) {
  		kunmap(enc_extent_page);
  		__free_page(enc_extent_page);
  	}
0216f7f79   Michael Halcrow   eCryptfs: replace...
536
537
538
539
540
541
542
543
  	return rc;
  }
  
  static int ecryptfs_decrypt_extent(struct page *page,
  				   struct ecryptfs_crypt_stat *crypt_stat,
  				   struct page *enc_extent_page,
  				   unsigned long extent_offset)
  {
d6a13c171   Michael Halcrow   eCryptfs: fix dat...
544
  	loff_t extent_base;
0216f7f79   Michael Halcrow   eCryptfs: replace...
545
546
  	char extent_iv[ECRYPTFS_MAX_IV_BYTES];
  	int rc;
d6a13c171   Michael Halcrow   eCryptfs: fix dat...
547
  	extent_base = (((loff_t)page->index)
0216f7f79   Michael Halcrow   eCryptfs: replace...
548
549
550
  		       * (PAGE_CACHE_SIZE / crypt_stat->extent_size));
  	rc = ecryptfs_derive_iv(extent_iv, crypt_stat,
  				(extent_base + extent_offset));
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
551
  	if (rc) {
888d57bbc   Joe Perches   fs/ecryptfs: Add ...
552
553
554
555
  		ecryptfs_printk(KERN_ERR, "Error attempting to derive IV for "
  			"extent [0x%.16llx]; rc = [%d]
  ",
  			(unsigned long long)(extent_base + extent_offset), rc);
0216f7f79   Michael Halcrow   eCryptfs: replace...
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
  		goto out;
  	}
  	if (unlikely(ecryptfs_verbosity > 0)) {
  		ecryptfs_printk(KERN_DEBUG, "Decrypting extent "
  				"with iv:
  ");
  		ecryptfs_dump_hex(extent_iv, crypt_stat->iv_bytes);
  		ecryptfs_printk(KERN_DEBUG, "First 8 bytes before "
  				"decryption:
  ");
  		ecryptfs_dump_hex((char *)
  				  (page_address(enc_extent_page)
  				   + (extent_offset * crypt_stat->extent_size)),
  				  8);
  	}
  	rc = ecryptfs_decrypt_page_offset(crypt_stat, page,
  					  (extent_offset
  					   * crypt_stat->extent_size),
  					  enc_extent_page, 0,
  					  crypt_stat->extent_size, extent_iv);
  	if (rc < 0) {
  		printk(KERN_ERR "%s: Error attempting to decrypt to page with "
  		       "page->index = [%ld], extent_offset = [%ld]; "
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
579
580
  		       "rc = [%d]
  ", __func__, page->index, extent_offset,
0216f7f79   Michael Halcrow   eCryptfs: replace...
581
582
583
584
585
  		       rc);
  		goto out;
  	}
  	rc = 0;
  	if (unlikely(ecryptfs_verbosity > 0)) {
888d57bbc   Joe Perches   fs/ecryptfs: Add ...
586
587
588
589
  		ecryptfs_printk(KERN_DEBUG, "Decrypt extent [0x%.16llx]; "
  			"rc = [%d]
  ",
  			(unsigned long long)(extent_base + extent_offset), rc);
0216f7f79   Michael Halcrow   eCryptfs: replace...
590
591
592
593
594
595
  		ecryptfs_printk(KERN_DEBUG, "First 8 bytes after "
  				"decryption:
  ");
  		ecryptfs_dump_hex((char *)(page_address(page)
  					   + (extent_offset
  					      * crypt_stat->extent_size)), 8);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
596
597
598
599
600
601
602
  	}
  out:
  	return rc;
  }
  
  /**
   * ecryptfs_decrypt_page
0216f7f79   Michael Halcrow   eCryptfs: replace...
603
604
605
   * @page: Page mapped from the eCryptfs inode for the file; data read
   *        and decrypted from the lower file will be written into this
   *        page
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
606
607
608
609
610
611
612
613
614
615
616
   *
   * Decrypt an eCryptfs page. This is done on a per-extent basis. Note
   * that eCryptfs pages may straddle the lower pages -- for instance,
   * if the file was created on a machine with an 8K page size
   * (resulting in an 8K header), and then the file is copied onto a
   * host with a 32K page size, then when reading page 0 of the eCryptfs
   * file, 24K of page 0 of the lower file will be read and decrypted,
   * and then 8K of page 1 of the lower file will be read and decrypted.
   *
   * Returns zero on success; negative on error
   */
0216f7f79   Michael Halcrow   eCryptfs: replace...
617
  int ecryptfs_decrypt_page(struct page *page)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
618
  {
0216f7f79   Michael Halcrow   eCryptfs: replace...
619
  	struct inode *ecryptfs_inode;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
620
  	struct ecryptfs_crypt_stat *crypt_stat;
7fcba0543   Eric Sandeen   eCryptfs: use pag...
621
622
  	char *enc_extent_virt;
  	struct page *enc_extent_page = NULL;
0216f7f79   Michael Halcrow   eCryptfs: replace...
623
  	unsigned long extent_offset;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
624
  	int rc = 0;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
625

0216f7f79   Michael Halcrow   eCryptfs: replace...
626
627
628
  	ecryptfs_inode = page->mapping->host;
  	crypt_stat =
  		&(ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat);
13a791b4e   Tyler Hicks   eCryptfs: Fix dat...
629
  	BUG_ON(!(crypt_stat->flags & ECRYPTFS_ENCRYPTED));
7fcba0543   Eric Sandeen   eCryptfs: use pag...
630
631
  	enc_extent_page = alloc_page(GFP_USER);
  	if (!enc_extent_page) {
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
632
  		rc = -ENOMEM;
0216f7f79   Michael Halcrow   eCryptfs: replace...
633
634
635
  		ecryptfs_printk(KERN_ERR, "Error allocating memory for "
  				"encrypted extent
  ");
16a72c455   Michael Halcrow   ecryptfs: clean u...
636
  		goto out;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
637
  	}
7fcba0543   Eric Sandeen   eCryptfs: use pag...
638
  	enc_extent_virt = kmap(enc_extent_page);
0216f7f79   Michael Halcrow   eCryptfs: replace...
639
640
641
642
643
644
645
646
647
648
649
650
  	for (extent_offset = 0;
  	     extent_offset < (PAGE_CACHE_SIZE / crypt_stat->extent_size);
  	     extent_offset++) {
  		loff_t offset;
  
  		ecryptfs_lower_offset_for_extent(
  			&offset, ((page->index * (PAGE_CACHE_SIZE
  						  / crypt_stat->extent_size))
  				  + extent_offset), crypt_stat);
  		rc = ecryptfs_read_lower(enc_extent_virt, offset,
  					 crypt_stat->extent_size,
  					 ecryptfs_inode);
96a7b9c2f   Tyler Hicks   eCryptfs: Propaga...
651
  		if (rc < 0) {
0216f7f79   Michael Halcrow   eCryptfs: replace...
652
653
654
655
  			ecryptfs_printk(KERN_ERR, "Error attempting "
  					"to read lower page; rc = [%d]"
  					"
  ", rc);
16a72c455   Michael Halcrow   ecryptfs: clean u...
656
  			goto out;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
657
  		}
0216f7f79   Michael Halcrow   eCryptfs: replace...
658
659
660
661
  		rc = ecryptfs_decrypt_extent(page, crypt_stat, enc_extent_page,
  					     extent_offset);
  		if (rc) {
  			printk(KERN_ERR "%s: Error encrypting extent; "
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
662
663
  			       "rc = [%d]
  ", __func__, rc);
16a72c455   Michael Halcrow   ecryptfs: clean u...
664
  			goto out;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
665
  		}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
666
667
  	}
  out:
7fcba0543   Eric Sandeen   eCryptfs: use pag...
668
669
670
671
  	if (enc_extent_page) {
  		kunmap(enc_extent_page);
  		__free_page(enc_extent_page);
  	}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
672
673
674
675
676
  	return rc;
  }
  
  /**
   * decrypt_scatterlist
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
677
678
679
680
681
   * @crypt_stat: Cryptographic context
   * @dest_sg: The destination scatterlist to decrypt into
   * @src_sg: The source scatterlist to decrypt from
   * @size: The number of bytes to decrypt
   * @iv: The initialization vector to use for the decryption
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
682
683
684
685
686
687
688
689
   *
   * Returns the number of bytes decrypted; negative value on error
   */
  static int decrypt_scatterlist(struct ecryptfs_crypt_stat *crypt_stat,
  			       struct scatterlist *dest_sg,
  			       struct scatterlist *src_sg, int size,
  			       unsigned char *iv)
  {
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
690
691
692
693
694
  	struct blkcipher_desc desc = {
  		.tfm = crypt_stat->tfm,
  		.info = iv,
  		.flags = CRYPTO_TFM_REQ_MAY_SLEEP
  	};
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
695
696
697
698
  	int rc = 0;
  
  	/* Consider doing this once, when the file is opened */
  	mutex_lock(&crypt_stat->cs_tfm_mutex);
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
699
700
  	rc = crypto_blkcipher_setkey(crypt_stat->tfm, crypt_stat->key,
  				     crypt_stat->key_size);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
701
702
703
704
705
706
707
708
709
710
  	if (rc) {
  		ecryptfs_printk(KERN_ERR, "Error setting key; rc = [%d]
  ",
  				rc);
  		mutex_unlock(&crypt_stat->cs_tfm_mutex);
  		rc = -EINVAL;
  		goto out;
  	}
  	ecryptfs_printk(KERN_DEBUG, "Decrypting [%d] bytes.
  ", size);
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
711
  	rc = crypto_blkcipher_decrypt_iv(&desc, dest_sg, src_sg, size);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
712
713
714
715
716
717
718
719
720
721
722
723
724
725
  	mutex_unlock(&crypt_stat->cs_tfm_mutex);
  	if (rc) {
  		ecryptfs_printk(KERN_ERR, "Error decrypting; rc = [%d]
  ",
  				rc);
  		goto out;
  	}
  	rc = size;
  out:
  	return rc;
  }
  
  /**
   * ecryptfs_encrypt_page_offset
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
726
727
728
729
730
731
732
   * @crypt_stat: The cryptographic context
   * @dst_page: The page to encrypt into
   * @dst_offset: The offset in the page to encrypt into
   * @src_page: The page to encrypt from
   * @src_offset: The offset in the page to encrypt from
   * @size: The number of bytes to encrypt
   * @iv: The initialization vector to use for the encryption
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
733
734
735
736
737
738
739
740
741
742
   *
   * Returns the number of bytes encrypted
   */
  static int
  ecryptfs_encrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
  			     struct page *dst_page, int dst_offset,
  			     struct page *src_page, int src_offset, int size,
  			     unsigned char *iv)
  {
  	struct scatterlist src_sg, dst_sg;
60c74f819   Jens Axboe   Update fs/ to use...
743
744
  	sg_init_table(&src_sg, 1);
  	sg_init_table(&dst_sg, 1);
642f14903   Jens Axboe   SG: Change sg_set...
745
746
  	sg_set_page(&src_sg, src_page, size, src_offset);
  	sg_set_page(&dst_sg, dst_page, size, dst_offset);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
747
748
749
750
751
  	return encrypt_scatterlist(crypt_stat, &dst_sg, &src_sg, size, iv);
  }
  
  /**
   * ecryptfs_decrypt_page_offset
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
752
753
754
755
756
757
758
   * @crypt_stat: The cryptographic context
   * @dst_page: The page to decrypt into
   * @dst_offset: The offset in the page to decrypt into
   * @src_page: The page to decrypt from
   * @src_offset: The offset in the page to decrypt from
   * @size: The number of bytes to decrypt
   * @iv: The initialization vector to use for the decryption
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
759
760
761
762
763
764
765
766
767
768
   *
   * Returns the number of bytes decrypted
   */
  static int
  ecryptfs_decrypt_page_offset(struct ecryptfs_crypt_stat *crypt_stat,
  			     struct page *dst_page, int dst_offset,
  			     struct page *src_page, int src_offset, int size,
  			     unsigned char *iv)
  {
  	struct scatterlist src_sg, dst_sg;
60c74f819   Jens Axboe   Update fs/ to use...
769
  	sg_init_table(&src_sg, 1);
642f14903   Jens Axboe   SG: Change sg_set...
770
  	sg_set_page(&src_sg, src_page, size, src_offset);
60c74f819   Jens Axboe   Update fs/ to use...
771
  	sg_init_table(&dst_sg, 1);
642f14903   Jens Axboe   SG: Change sg_set...
772
  	sg_set_page(&dst_sg, dst_page, size, dst_offset);
60c74f819   Jens Axboe   Update fs/ to use...
773

237fead61   Michael Halcrow   [PATCH] ecryptfs:...
774
775
776
777
778
779
780
  	return decrypt_scatterlist(crypt_stat, &dst_sg, &src_sg, size, iv);
  }
  
  #define ECRYPTFS_MAX_SCATTERLIST_LEN 4
  
  /**
   * ecryptfs_init_crypt_ctx
421f91d21   Uwe Kleine-König   fix typos concern...
781
   * @crypt_stat: Uninitialized crypt stats structure
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
782
783
784
785
786
787
788
789
   *
   * Initialize the crypto context.
   *
   * TODO: Performance: Keep a cache of initialized cipher contexts;
   * only init if needed
   */
  int ecryptfs_init_crypt_ctx(struct ecryptfs_crypt_stat *crypt_stat)
  {
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
790
  	char *full_alg_name;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
791
792
793
794
795
796
797
798
799
  	int rc = -EINVAL;
  
  	if (!crypt_stat->cipher) {
  		ecryptfs_printk(KERN_ERR, "No cipher specified
  ");
  		goto out;
  	}
  	ecryptfs_printk(KERN_DEBUG,
  			"Initializing cipher [%s]; strlen = [%d]; "
f24b38874   Tyler Hicks   ecryptfs: Fix ecr...
800
801
  			"key_size_bits = [%zd]
  ",
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
802
803
804
805
806
807
808
  			crypt_stat->cipher, (int)strlen(crypt_stat->cipher),
  			crypt_stat->key_size << 3);
  	if (crypt_stat->tfm) {
  		rc = 0;
  		goto out;
  	}
  	mutex_lock(&crypt_stat->cs_tfm_mutex);
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
809
810
811
  	rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name,
  						    crypt_stat->cipher, "cbc");
  	if (rc)
c8161f64c   Eric Sandeen   ecryptfs: fix unl...
812
  		goto out_unlock;
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
813
814
815
  	crypt_stat->tfm = crypto_alloc_blkcipher(full_alg_name, 0,
  						 CRYPTO_ALG_ASYNC);
  	kfree(full_alg_name);
de88777e6   Akinobu Mita   [PATCH] ecryptfs:...
816
817
  	if (IS_ERR(crypt_stat->tfm)) {
  		rc = PTR_ERR(crypt_stat->tfm);
b0105eaef   Tyler Hicks   eCryptfs: Handle ...
818
  		crypt_stat->tfm = NULL;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
819
820
821
822
  		ecryptfs_printk(KERN_ERR, "cryptfs: init_crypt_ctx(): "
  				"Error initializing cipher [%s]
  ",
  				crypt_stat->cipher);
c8161f64c   Eric Sandeen   ecryptfs: fix unl...
823
  		goto out_unlock;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
824
  	}
f1ddcaf33   Herbert Xu   [CRYPTO] api: Rem...
825
  	crypto_blkcipher_set_flags(crypt_stat->tfm, CRYPTO_TFM_REQ_WEAK_KEY);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
826
  	rc = 0;
c8161f64c   Eric Sandeen   ecryptfs: fix unl...
827
828
  out_unlock:
  	mutex_unlock(&crypt_stat->cs_tfm_mutex);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
  out:
  	return rc;
  }
  
  static void set_extent_mask_and_shift(struct ecryptfs_crypt_stat *crypt_stat)
  {
  	int extent_size_tmp;
  
  	crypt_stat->extent_mask = 0xFFFFFFFF;
  	crypt_stat->extent_shift = 0;
  	if (crypt_stat->extent_size == 0)
  		return;
  	extent_size_tmp = crypt_stat->extent_size;
  	while ((extent_size_tmp & 0x01) == 0) {
  		extent_size_tmp >>= 1;
  		crypt_stat->extent_mask <<= 1;
  		crypt_stat->extent_shift++;
  	}
  }
  
  void ecryptfs_set_default_sizes(struct ecryptfs_crypt_stat *crypt_stat)
  {
  	/* Default values; may be overwritten as we are parsing the
  	 * packets. */
  	crypt_stat->extent_size = ECRYPTFS_DEFAULT_EXTENT_SIZE;
  	set_extent_mask_and_shift(crypt_stat);
  	crypt_stat->iv_bytes = ECRYPTFS_DEFAULT_IV_BYTES;
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
856
  	if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
857
  		crypt_stat->metadata_size = ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
45eaab796   Michael Halcrow   eCryptfs: remove ...
858
859
  	else {
  		if (PAGE_CACHE_SIZE <= ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE)
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
860
  			crypt_stat->metadata_size =
cc11beffd   Michael Halcrow   eCryptfs: track h...
861
  				ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
45eaab796   Michael Halcrow   eCryptfs: remove ...
862
  		else
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
863
  			crypt_stat->metadata_size = PAGE_CACHE_SIZE;
45eaab796   Michael Halcrow   eCryptfs: remove ...
864
  	}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
  }
  
  /**
   * ecryptfs_compute_root_iv
   * @crypt_stats
   *
   * On error, sets the root IV to all 0's.
   */
  int ecryptfs_compute_root_iv(struct ecryptfs_crypt_stat *crypt_stat)
  {
  	int rc = 0;
  	char dst[MD5_DIGEST_SIZE];
  
  	BUG_ON(crypt_stat->iv_bytes > MD5_DIGEST_SIZE);
  	BUG_ON(crypt_stat->iv_bytes <= 0);
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
880
  	if (!(crypt_stat->flags & ECRYPTFS_KEY_VALID)) {
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
  		rc = -EINVAL;
  		ecryptfs_printk(KERN_WARNING, "Session key not valid; "
  				"cannot generate root IV
  ");
  		goto out;
  	}
  	rc = ecryptfs_calculate_md5(dst, crypt_stat, crypt_stat->key,
  				    crypt_stat->key_size);
  	if (rc) {
  		ecryptfs_printk(KERN_WARNING, "Error attempting to compute "
  				"MD5 while generating root IV
  ");
  		goto out;
  	}
  	memcpy(crypt_stat->root_iv, dst, crypt_stat->iv_bytes);
  out:
  	if (rc) {
  		memset(crypt_stat->root_iv, 0, crypt_stat->iv_bytes);
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
899
  		crypt_stat->flags |= ECRYPTFS_SECURITY_WARNING;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
900
901
902
903
904
905
906
  	}
  	return rc;
  }
  
  static void ecryptfs_generate_new_key(struct ecryptfs_crypt_stat *crypt_stat)
  {
  	get_random_bytes(crypt_stat->key, crypt_stat->key_size);
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
907
  	crypt_stat->flags |= ECRYPTFS_KEY_VALID;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
908
909
910
911
912
913
914
915
916
917
  	ecryptfs_compute_root_iv(crypt_stat);
  	if (unlikely(ecryptfs_verbosity > 0)) {
  		ecryptfs_printk(KERN_DEBUG, "Generated new session key:
  ");
  		ecryptfs_dump_hex(crypt_stat->key,
  				  crypt_stat->key_size);
  	}
  }
  
  /**
17398957a   Michael Halcrow   [PATCH] eCryptfs:...
918
   * ecryptfs_copy_mount_wide_flags_to_inode_flags
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
919
920
   * @crypt_stat: The inode's cryptographic context
   * @mount_crypt_stat: The mount point's cryptographic context
17398957a   Michael Halcrow   [PATCH] eCryptfs:...
921
922
923
924
925
926
927
928
929
930
931
932
   *
   * This function propagates the mount-wide flags to individual inode
   * flags.
   */
  static void ecryptfs_copy_mount_wide_flags_to_inode_flags(
  	struct ecryptfs_crypt_stat *crypt_stat,
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
  {
  	if (mount_crypt_stat->flags & ECRYPTFS_XATTR_METADATA_ENABLED)
  		crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
  	if (mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED)
  		crypt_stat->flags |= ECRYPTFS_VIEW_AS_ENCRYPTED;
addd65ad8   Michael Halcrow   eCryptfs: Filenam...
933
934
935
936
937
938
939
940
941
  	if (mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) {
  		crypt_stat->flags |= ECRYPTFS_ENCRYPT_FILENAMES;
  		if (mount_crypt_stat->flags
  		    & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK)
  			crypt_stat->flags |= ECRYPTFS_ENCFN_USE_MOUNT_FNEK;
  		else if (mount_crypt_stat->flags
  			 & ECRYPTFS_GLOBAL_ENCFN_USE_FEK)
  			crypt_stat->flags |= ECRYPTFS_ENCFN_USE_FEK;
  	}
17398957a   Michael Halcrow   [PATCH] eCryptfs:...
942
  }
f4aad16ad   Michael Halcrow   eCryptfs: add key...
943
944
945
946
947
948
  static int ecryptfs_copy_mount_wide_sigs_to_inode_sigs(
  	struct ecryptfs_crypt_stat *crypt_stat,
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
  {
  	struct ecryptfs_global_auth_tok *global_auth_tok;
  	int rc = 0;
aa06117f1   Roland Dreier   eCryptfs: Fix loc...
949
  	mutex_lock(&crypt_stat->keysig_list_mutex);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
950
  	mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
aa06117f1   Roland Dreier   eCryptfs: Fix loc...
951

f4aad16ad   Michael Halcrow   eCryptfs: add key...
952
953
954
  	list_for_each_entry(global_auth_tok,
  			    &mount_crypt_stat->global_auth_tok_list,
  			    mount_crypt_stat_list) {
84814d642   Tyler Hicks   eCryptfs: don't e...
955
956
  		if (global_auth_tok->flags & ECRYPTFS_AUTH_TOK_FNEK)
  			continue;
f4aad16ad   Michael Halcrow   eCryptfs: add key...
957
958
959
960
  		rc = ecryptfs_add_keysig(crypt_stat, global_auth_tok->sig);
  		if (rc) {
  			printk(KERN_ERR "Error adding keysig; rc = [%d]
  ", rc);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
961
962
963
  			goto out;
  		}
  	}
aa06117f1   Roland Dreier   eCryptfs: Fix loc...
964

f4aad16ad   Michael Halcrow   eCryptfs: add key...
965
  out:
aa06117f1   Roland Dreier   eCryptfs: Fix loc...
966
967
  	mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
  	mutex_unlock(&crypt_stat->keysig_list_mutex);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
968
969
  	return rc;
  }
17398957a   Michael Halcrow   [PATCH] eCryptfs:...
970
  /**
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
971
   * ecryptfs_set_default_crypt_stat_vals
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
972
973
   * @crypt_stat: The inode's cryptographic context
   * @mount_crypt_stat: The mount point's cryptographic context
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
974
975
976
977
978
979
980
   *
   * Default values in the event that policy does not override them.
   */
  static void ecryptfs_set_default_crypt_stat_vals(
  	struct ecryptfs_crypt_stat *crypt_stat,
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
  {
17398957a   Michael Halcrow   [PATCH] eCryptfs:...
981
982
  	ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
  						      mount_crypt_stat);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
983
984
985
  	ecryptfs_set_default_sizes(crypt_stat);
  	strcpy(crypt_stat->cipher, ECRYPTFS_DEFAULT_CIPHER);
  	crypt_stat->key_size = ECRYPTFS_DEFAULT_KEY_BYTES;
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
986
  	crypt_stat->flags &= ~(ECRYPTFS_KEY_VALID);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
987
988
989
990
991
992
  	crypt_stat->file_version = ECRYPTFS_FILE_VERSION;
  	crypt_stat->mount_crypt_stat = mount_crypt_stat;
  }
  
  /**
   * ecryptfs_new_file_context
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
993
   * @ecryptfs_inode: The eCryptfs inode
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
   *
   * If the crypto context for the file has not yet been established,
   * this is where we do that.  Establishing a new crypto context
   * involves the following decisions:
   *  - What cipher to use?
   *  - What set of authentication tokens to use?
   * Here we just worry about getting enough information into the
   * authentication tokens so that we know that they are available.
   * We associate the available authentication tokens with the new file
   * via the set of signatures in the crypt_stat struct.  Later, when
   * the headers are actually written out, we may again defer to
   * userspace to perform the encryption of the session key; for the
   * foreseeable future, this will be the case with public key packets.
   *
   * Returns zero on success; non-zero otherwise
   */
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1010
  int ecryptfs_new_file_context(struct inode *ecryptfs_inode)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1011
  {
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1012
  	struct ecryptfs_crypt_stat *crypt_stat =
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1013
  	    &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1014
1015
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
  	    &ecryptfs_superblock_to_private(
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1016
  		    ecryptfs_inode->i_sb)->mount_crypt_stat;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1017
  	int cipher_name_len;
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1018
  	int rc = 0;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1019
1020
  
  	ecryptfs_set_default_crypt_stat_vals(crypt_stat, mount_crypt_stat);
af655dc6a   Michael Halcrow   eCryptfs: collaps...
1021
  	crypt_stat->flags |= (ECRYPTFS_ENCRYPTED | ECRYPTFS_KEY_VALID);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
  	ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
  						      mount_crypt_stat);
  	rc = ecryptfs_copy_mount_wide_sigs_to_inode_sigs(crypt_stat,
  							 mount_crypt_stat);
  	if (rc) {
  		printk(KERN_ERR "Error attempting to copy mount-wide key sigs "
  		       "to the inode key sigs; rc = [%d]
  ", rc);
  		goto out;
  	}
  	cipher_name_len =
  		strlen(mount_crypt_stat->global_default_cipher_name);
  	memcpy(crypt_stat->cipher,
  	       mount_crypt_stat->global_default_cipher_name,
  	       cipher_name_len);
  	crypt_stat->cipher[cipher_name_len] = '\0';
  	crypt_stat->key_size =
  		mount_crypt_stat->global_default_cipher_key_size;
  	ecryptfs_generate_new_key(crypt_stat);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1041
1042
1043
1044
1045
1046
  	rc = ecryptfs_init_crypt_ctx(crypt_stat);
  	if (rc)
  		ecryptfs_printk(KERN_ERR, "Error initializing cryptographic "
  				"context for cipher [%s]: rc = [%d]
  ",
  				crypt_stat->cipher, rc);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1047
  out:
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1048
1049
1050
1051
  	return rc;
  }
  
  /**
7a86617e5   Tyler Hicks   eCryptfs: Return ...
1052
   * ecryptfs_validate_marker - check for the ecryptfs marker
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1053
1054
   * @data: The data block in which to check
   *
7a86617e5   Tyler Hicks   eCryptfs: Return ...
1055
   * Returns zero if marker found; -EINVAL if not found
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1056
   */
7a86617e5   Tyler Hicks   eCryptfs: Return ...
1057
  static int ecryptfs_validate_marker(char *data)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1058
1059
  {
  	u32 m_1, m_2;
29335c6a4   Harvey Harrison   ecryptfs: crypto....
1060
1061
  	m_1 = get_unaligned_be32(data);
  	m_2 = get_unaligned_be32(data + 4);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1062
  	if ((m_1 ^ MAGIC_ECRYPTFS_MARKER) == m_2)
7a86617e5   Tyler Hicks   eCryptfs: Return ...
1063
  		return 0;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1064
1065
1066
1067
1068
1069
1070
  	ecryptfs_printk(KERN_DEBUG, "m_1 = [0x%.8x]; m_2 = [0x%.8x]; "
  			"MAGIC_ECRYPTFS_MARKER = [0x%.8x]
  ", m_1, m_2,
  			MAGIC_ECRYPTFS_MARKER);
  	ecryptfs_printk(KERN_DEBUG, "(m_1 ^ MAGIC_ECRYPTFS_MARKER) = "
  			"[0x%.8x]
  ", (m_1 ^ MAGIC_ECRYPTFS_MARKER));
7a86617e5   Tyler Hicks   eCryptfs: Return ...
1071
  	return -EINVAL;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
  }
  
  struct ecryptfs_flag_map_elem {
  	u32 file_flag;
  	u32 local_flag;
  };
  
  /* Add support for additional flags by adding elements here. */
  static struct ecryptfs_flag_map_elem ecryptfs_flag_map[] = {
  	{0x00000001, ECRYPTFS_ENABLE_HMAC},
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1082
  	{0x00000002, ECRYPTFS_ENCRYPTED},
addd65ad8   Michael Halcrow   eCryptfs: Filenam...
1083
1084
  	{0x00000004, ECRYPTFS_METADATA_IN_XATTR},
  	{0x00000008, ECRYPTFS_ENCRYPT_FILENAMES}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1085
1086
1087
1088
  };
  
  /**
   * ecryptfs_process_flags
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1089
   * @crypt_stat: The cryptographic context
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
   * @page_virt: Source data to be parsed
   * @bytes_read: Updated with the number of bytes read
   *
   * Returns zero on success; non-zero if the flag set is invalid
   */
  static int ecryptfs_process_flags(struct ecryptfs_crypt_stat *crypt_stat,
  				  char *page_virt, int *bytes_read)
  {
  	int rc = 0;
  	int i;
  	u32 flags;
29335c6a4   Harvey Harrison   ecryptfs: crypto....
1101
  	flags = get_unaligned_be32(page_virt);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1102
1103
1104
  	for (i = 0; i < ((sizeof(ecryptfs_flag_map)
  			  / sizeof(struct ecryptfs_flag_map_elem))); i++)
  		if (flags & ecryptfs_flag_map[i].file_flag) {
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
1105
  			crypt_stat->flags |= ecryptfs_flag_map[i].local_flag;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1106
  		} else
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
1107
  			crypt_stat->flags &= ~(ecryptfs_flag_map[i].local_flag);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
  	/* Version is in top 8 bits of the 32-bit flag vector */
  	crypt_stat->file_version = ((flags >> 24) & 0xFF);
  	(*bytes_read) = 4;
  	return rc;
  }
  
  /**
   * write_ecryptfs_marker
   * @page_virt: The pointer to in a page to begin writing the marker
   * @written: Number of bytes written
   *
   * Marker = 0x3c81b7f5
   */
  static void write_ecryptfs_marker(char *page_virt, size_t *written)
  {
  	u32 m_1, m_2;
  
  	get_random_bytes(&m_1, (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2));
  	m_2 = (m_1 ^ MAGIC_ECRYPTFS_MARKER);
29335c6a4   Harvey Harrison   ecryptfs: crypto....
1127
1128
1129
  	put_unaligned_be32(m_1, page_virt);
  	page_virt += (MAGIC_ECRYPTFS_MARKER_SIZE_BYTES / 2);
  	put_unaligned_be32(m_2, page_virt);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1130
1131
  	(*written) = MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
  }
f4e60e6b3   Tyler Hicks   eCryptfs: Strip m...
1132
1133
1134
  void ecryptfs_write_crypt_stat_flags(char *page_virt,
  				     struct ecryptfs_crypt_stat *crypt_stat,
  				     size_t *written)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1135
1136
1137
1138
1139
1140
  {
  	u32 flags = 0;
  	int i;
  
  	for (i = 0; i < ((sizeof(ecryptfs_flag_map)
  			  / sizeof(struct ecryptfs_flag_map_elem))); i++)
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
1141
  		if (crypt_stat->flags & ecryptfs_flag_map[i].local_flag)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1142
1143
1144
  			flags |= ecryptfs_flag_map[i].file_flag;
  	/* Version is in top 8 bits of the 32-bit flag vector */
  	flags |= ((((u8)crypt_stat->file_version) << 24) & 0xFF000000);
29335c6a4   Harvey Harrison   ecryptfs: crypto....
1145
  	put_unaligned_be32(flags, page_virt);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1146
1147
1148
1149
1150
  	(*written) = 4;
  }
  
  struct ecryptfs_cipher_code_str_map_elem {
  	char cipher_str[16];
19e66a67e   Trevor Highland   eCryptfs: change ...
1151
  	u8 cipher_code;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
  };
  
  /* Add support for additional ciphers by adding elements here. The
   * cipher_code is whatever OpenPGP applicatoins use to identify the
   * ciphers. List in order of probability. */
  static struct ecryptfs_cipher_code_str_map_elem
  ecryptfs_cipher_code_str_map[] = {
  	{"aes",RFC2440_CIPHER_AES_128 },
  	{"blowfish", RFC2440_CIPHER_BLOWFISH},
  	{"des3_ede", RFC2440_CIPHER_DES3_EDE},
  	{"cast5", RFC2440_CIPHER_CAST_5},
  	{"twofish", RFC2440_CIPHER_TWOFISH},
  	{"cast6", RFC2440_CIPHER_CAST_6},
  	{"aes", RFC2440_CIPHER_AES_192},
  	{"aes", RFC2440_CIPHER_AES_256}
  };
  
  /**
   * ecryptfs_code_for_cipher_string
9c79f34f7   Michael Halcrow   eCryptfs: Filenam...
1171
1172
   * @cipher_name: The string alias for the cipher
   * @key_bytes: Length of key in bytes; used for AES code selection
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1173
1174
1175
   *
   * Returns zero on no match, or the cipher code on match
   */
9c79f34f7   Michael Halcrow   eCryptfs: Filenam...
1176
  u8 ecryptfs_code_for_cipher_string(char *cipher_name, size_t key_bytes)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1177
1178
  {
  	int i;
19e66a67e   Trevor Highland   eCryptfs: change ...
1179
  	u8 code = 0;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1180
1181
  	struct ecryptfs_cipher_code_str_map_elem *map =
  		ecryptfs_cipher_code_str_map;
9c79f34f7   Michael Halcrow   eCryptfs: Filenam...
1182
1183
  	if (strcmp(cipher_name, "aes") == 0) {
  		switch (key_bytes) {
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
  		case 16:
  			code = RFC2440_CIPHER_AES_128;
  			break;
  		case 24:
  			code = RFC2440_CIPHER_AES_192;
  			break;
  		case 32:
  			code = RFC2440_CIPHER_AES_256;
  		}
  	} else {
  		for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
9c79f34f7   Michael Halcrow   eCryptfs: Filenam...
1195
  			if (strcmp(cipher_name, map[i].cipher_str) == 0) {
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
  				code = map[i].cipher_code;
  				break;
  			}
  	}
  	return code;
  }
  
  /**
   * ecryptfs_cipher_code_to_string
   * @str: Destination to write out the cipher name
   * @cipher_code: The code to convert to cipher name string
   *
   * Returns zero on success
   */
19e66a67e   Trevor Highland   eCryptfs: change ...
1210
  int ecryptfs_cipher_code_to_string(char *str, u8 cipher_code)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
  {
  	int rc = 0;
  	int i;
  
  	str[0] = '\0';
  	for (i = 0; i < ARRAY_SIZE(ecryptfs_cipher_code_str_map); i++)
  		if (cipher_code == ecryptfs_cipher_code_str_map[i].cipher_code)
  			strcpy(str, ecryptfs_cipher_code_str_map[i].cipher_str);
  	if (str[0] == '\0') {
  		ecryptfs_printk(KERN_WARNING, "Cipher code not recognized: "
  				"[%d]
  ", cipher_code);
  		rc = -EINVAL;
  	}
  	return rc;
  }
778aeb42a   Tyler Hicks   eCryptfs: Cleanup...
1227
  int ecryptfs_read_and_validate_header_region(struct inode *inode)
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1228
  {
778aeb42a   Tyler Hicks   eCryptfs: Cleanup...
1229
1230
  	u8 file_size[ECRYPTFS_SIZE_AND_MARKER_BYTES];
  	u8 *marker = file_size + ECRYPTFS_FILE_SIZE_BYTES;
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1231
  	int rc;
778aeb42a   Tyler Hicks   eCryptfs: Cleanup...
1232
1233
1234
1235
1236
1237
1238
  	rc = ecryptfs_read_lower(file_size, 0, ECRYPTFS_SIZE_AND_MARKER_BYTES,
  				 inode);
  	if (rc < ECRYPTFS_SIZE_AND_MARKER_BYTES)
  		return rc >= 0 ? -EINVAL : rc;
  	rc = ecryptfs_validate_marker(marker);
  	if (!rc)
  		ecryptfs_i_size_init(file_size, inode);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1239
1240
  	return rc;
  }
e77a56ddc   Michael Halcrow   [PATCH] eCryptfs:...
1241
1242
1243
1244
  void
  ecryptfs_write_header_metadata(char *virt,
  			       struct ecryptfs_crypt_stat *crypt_stat,
  			       size_t *written)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1245
1246
1247
  {
  	u32 header_extent_size;
  	u16 num_header_extents_at_front;
45eaab796   Michael Halcrow   eCryptfs: remove ...
1248
  	header_extent_size = (u32)crypt_stat->extent_size;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1249
  	num_header_extents_at_front =
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
1250
  		(u16)(crypt_stat->metadata_size / crypt_stat->extent_size);
29335c6a4   Harvey Harrison   ecryptfs: crypto....
1251
  	put_unaligned_be32(header_extent_size, virt);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1252
  	virt += 4;
29335c6a4   Harvey Harrison   ecryptfs: crypto....
1253
  	put_unaligned_be16(num_header_extents_at_front, virt);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1254
1255
  	(*written) = 6;
  }
306328705   Tyler Hicks   eCryptfs: Remove ...
1256
  struct kmem_cache *ecryptfs_header_cache;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1257
1258
1259
  
  /**
   * ecryptfs_write_headers_virt
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1260
   * @page_virt: The virtual address to write the headers to
87b811c3f   Eric Sandeen   ecryptfs: fix mem...
1261
   * @max: The size of memory allocated at page_virt
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1262
1263
1264
   * @size: Set to the number of bytes written by this function
   * @crypt_stat: The cryptographic context
   * @ecryptfs_dentry: The eCryptfs dentry
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
   *
   * Format version: 1
   *
   *   Header Extent:
   *     Octets 0-7:        Unencrypted file size (big-endian)
   *     Octets 8-15:       eCryptfs special marker
   *     Octets 16-19:      Flags
   *      Octet 16:         File format version number (between 0 and 255)
   *      Octets 17-18:     Reserved
   *      Octet 19:         Bit 1 (lsb): Reserved
   *                        Bit 2: Encrypted?
   *                        Bits 3-8: Reserved
   *     Octets 20-23:      Header extent size (big-endian)
   *     Octets 24-25:      Number of header extents at front of file
   *                        (big-endian)
   *     Octet  26:         Begin RFC 2440 authentication token packet set
   *   Data Extent 0:
   *     Lower data (CBC encrypted)
   *   Data Extent 1:
   *     Lower data (CBC encrypted)
   *   ...
   *
   * Returns zero on success
   */
87b811c3f   Eric Sandeen   ecryptfs: fix mem...
1289
1290
  static int ecryptfs_write_headers_virt(char *page_virt, size_t max,
  				       size_t *size,
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1291
1292
  				       struct ecryptfs_crypt_stat *crypt_stat,
  				       struct dentry *ecryptfs_dentry)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1293
1294
1295
1296
1297
1298
1299
1300
  {
  	int rc;
  	size_t written;
  	size_t offset;
  
  	offset = ECRYPTFS_FILE_SIZE_BYTES;
  	write_ecryptfs_marker((page_virt + offset), &written);
  	offset += written;
f4e60e6b3   Tyler Hicks   eCryptfs: Strip m...
1301
1302
  	ecryptfs_write_crypt_stat_flags((page_virt + offset), crypt_stat,
  					&written);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1303
  	offset += written;
e77a56ddc   Michael Halcrow   [PATCH] eCryptfs:...
1304
1305
  	ecryptfs_write_header_metadata((page_virt + offset), crypt_stat,
  				       &written);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1306
1307
1308
  	offset += written;
  	rc = ecryptfs_generate_key_packet_set((page_virt + offset), crypt_stat,
  					      ecryptfs_dentry, &written,
87b811c3f   Eric Sandeen   ecryptfs: fix mem...
1309
  					      max - offset);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1310
1311
1312
1313
  	if (rc)
  		ecryptfs_printk(KERN_WARNING, "Error generating key packet "
  				"set; rc = [%d]
  ", rc);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1314
1315
1316
1317
1318
1319
  	if (size) {
  		offset += written;
  		*size = offset;
  	}
  	return rc;
  }
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1320
  static int
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1321
  ecryptfs_write_metadata_to_contents(struct inode *ecryptfs_inode,
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1322
  				    char *virt, size_t virt_len)
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1323
  {
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1324
  	int rc;
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1325

b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1326
  	rc = ecryptfs_write_lower(ecryptfs_inode, virt,
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1327
  				  0, virt_len);
96a7b9c2f   Tyler Hicks   eCryptfs: Propaga...
1328
  	if (rc < 0)
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1329
  		printk(KERN_ERR "%s: Error attempting to write header "
96a7b9c2f   Tyler Hicks   eCryptfs: Propaga...
1330
1331
1332
1333
  		       "information to lower file; rc = [%d]
  ", __func__, rc);
  	else
  		rc = 0;
70456600f   Michael Halcrow   [PATCH] eCryptfs:...
1334
  	return rc;
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1335
  }
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1336
1337
  static int
  ecryptfs_write_metadata_to_xattr(struct dentry *ecryptfs_dentry,
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1338
  				 char *page_virt, size_t size)
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1339
1340
1341
1342
1343
  {
  	int rc;
  
  	rc = ecryptfs_setxattr(ecryptfs_dentry, ECRYPTFS_XATTR_NAME, page_virt,
  			       size, 0);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1344
1345
  	return rc;
  }
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
  static unsigned long ecryptfs_get_zeroed_pages(gfp_t gfp_mask,
  					       unsigned int order)
  {
  	struct page *page;
  
  	page = alloc_pages(gfp_mask | __GFP_ZERO, order);
  	if (page)
  		return (unsigned long) page_address(page);
  	return 0;
  }
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1356
  /**
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1357
   * ecryptfs_write_metadata
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1358
1359
   * @ecryptfs_dentry: The eCryptfs dentry, which should be negative
   * @ecryptfs_inode: The newly created eCryptfs inode
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1360
1361
1362
1363
1364
1365
1366
1367
1368
   *
   * Write the file headers out.  This will likely involve a userspace
   * callout, in which the session key is encrypted with one or more
   * public keys and/or the passphrase necessary to do the encryption is
   * retrieved via a prompt.  Exactly what happens at this point should
   * be policy-dependent.
   *
   * Returns zero on success; non-zero on error
   */
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1369
1370
  int ecryptfs_write_metadata(struct dentry *ecryptfs_dentry,
  			    struct inode *ecryptfs_inode)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1371
  {
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1372
  	struct ecryptfs_crypt_stat *crypt_stat =
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1373
  		&ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1374
  	unsigned int order;
cc11beffd   Michael Halcrow   eCryptfs: track h...
1375
  	char *virt;
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1376
  	size_t virt_len;
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1377
  	size_t size = 0;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1378
  	int rc = 0;
e2bd99ec5   Michael Halcrow   [PATCH] eCryptfs:...
1379
1380
  	if (likely(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
  		if (!(crypt_stat->flags & ECRYPTFS_KEY_VALID)) {
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1381
1382
  			printk(KERN_ERR "Key is invalid; bailing out
  ");
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1383
1384
1385
1386
  			rc = -EINVAL;
  			goto out;
  		}
  	} else {
cc11beffd   Michael Halcrow   eCryptfs: track h...
1387
1388
  		printk(KERN_WARNING "%s: Encrypted flag not set
  ",
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
1389
  		       __func__);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1390
  		rc = -EINVAL;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1391
1392
  		goto out;
  	}
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
1393
  	virt_len = crypt_stat->metadata_size;
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1394
  	order = get_order(virt_len);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1395
  	/* Released in this function */
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1396
  	virt = (char *)ecryptfs_get_zeroed_pages(GFP_KERNEL, order);
cc11beffd   Michael Halcrow   eCryptfs: track h...
1397
  	if (!virt) {
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
1398
1399
  		printk(KERN_ERR "%s: Out of memory
  ", __func__);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1400
1401
1402
  		rc = -ENOMEM;
  		goto out;
  	}
bd4f0fe8b   Tyler Hicks   eCryptfs: Remove ...
1403
  	/* Zeroed page ensures the in-header unencrypted i_size is set to 0 */
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1404
1405
  	rc = ecryptfs_write_headers_virt(virt, virt_len, &size, crypt_stat,
  					 ecryptfs_dentry);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1406
  	if (unlikely(rc)) {
cc11beffd   Michael Halcrow   eCryptfs: track h...
1407
1408
  		printk(KERN_ERR "%s: Error whilst writing headers; rc = [%d]
  ",
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
1409
  		       __func__, rc);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1410
1411
  		goto out_free;
  	}
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1412
  	if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1413
1414
  		rc = ecryptfs_write_metadata_to_xattr(ecryptfs_dentry, virt,
  						      size);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1415
  	else
b59db43ad   Tyler Hicks   eCryptfs: Prevent...
1416
  		rc = ecryptfs_write_metadata_to_contents(ecryptfs_inode, virt,
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1417
  							 virt_len);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1418
  	if (rc) {
cc11beffd   Michael Halcrow   eCryptfs: track h...
1419
  		printk(KERN_ERR "%s: Error writing metadata out to lower file; "
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
1420
1421
  		       "rc = [%d]
  ", __func__, rc);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1422
  		goto out_free;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1423
  	}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1424
  out_free:
8faece5f9   Tyler Hicks   eCryptfs: Allocat...
1425
  	free_pages((unsigned long)virt, order);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1426
1427
1428
  out:
  	return rc;
  }
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1429
1430
  #define ECRYPTFS_DONT_VALIDATE_HEADER_SIZE 0
  #define ECRYPTFS_VALIDATE_HEADER_SIZE 1
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1431
  static int parse_header_metadata(struct ecryptfs_crypt_stat *crypt_stat,
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1432
1433
  				 char *virt, int *bytes_read,
  				 int validate_header_size)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1434
1435
1436
1437
  {
  	int rc = 0;
  	u32 header_extent_size;
  	u16 num_header_extents_at_front;
29335c6a4   Harvey Harrison   ecryptfs: crypto....
1438
1439
1440
  	header_extent_size = get_unaligned_be32(virt);
  	virt += sizeof(__be32);
  	num_header_extents_at_front = get_unaligned_be16(virt);
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
1441
1442
  	crypt_stat->metadata_size = (((size_t)num_header_extents_at_front
  				     * (size_t)header_extent_size));
29335c6a4   Harvey Harrison   ecryptfs: crypto....
1443
  	(*bytes_read) = (sizeof(__be32) + sizeof(__be16));
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1444
  	if ((validate_header_size == ECRYPTFS_VALIDATE_HEADER_SIZE)
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
1445
  	    && (crypt_stat->metadata_size
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1446
  		< ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE)) {
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1447
  		rc = -EINVAL;
cc11beffd   Michael Halcrow   eCryptfs: track h...
1448
1449
  		printk(KERN_WARNING "Invalid header size: [%zd]
  ",
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
1450
  		       crypt_stat->metadata_size);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1451
1452
1453
1454
1455
1456
  	}
  	return rc;
  }
  
  /**
   * set_default_header_data
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1457
   * @crypt_stat: The cryptographic context
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1458
1459
1460
1461
1462
1463
1464
   *
   * For version 0 file format; this function is only for backwards
   * compatibility for files created with the prior versions of
   * eCryptfs.
   */
  static void set_default_header_data(struct ecryptfs_crypt_stat *crypt_stat)
  {
fa3ef1cb4   Tyler Hicks   eCryptfs: Rename ...
1465
  	crypt_stat->metadata_size = ECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1466
  }
3aeb86ea4   Tyler Hicks   eCryptfs: Handle ...
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
  void ecryptfs_i_size_init(const char *page_virt, struct inode *inode)
  {
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat;
  	struct ecryptfs_crypt_stat *crypt_stat;
  	u64 file_size;
  
  	crypt_stat = &ecryptfs_inode_to_private(inode)->crypt_stat;
  	mount_crypt_stat =
  		&ecryptfs_superblock_to_private(inode->i_sb)->mount_crypt_stat;
  	if (mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED) {
  		file_size = i_size_read(ecryptfs_inode_to_lower(inode));
  		if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
  			file_size += crypt_stat->metadata_size;
  	} else
  		file_size = get_unaligned_be64(page_virt);
  	i_size_write(inode, (loff_t)file_size);
  	crypt_stat->flags |= ECRYPTFS_I_SIZE_INITIALIZED;
  }
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1485
1486
  /**
   * ecryptfs_read_headers_virt
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1487
1488
1489
1490
   * @page_virt: The virtual address into which to read the headers
   * @crypt_stat: The cryptographic context
   * @ecryptfs_dentry: The eCryptfs dentry
   * @validate_header_size: Whether to validate the header size while reading
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1491
1492
1493
1494
1495
1496
1497
1498
   *
   * Read/parse the header data. The header format is detailed in the
   * comment block for the ecryptfs_write_headers_virt() function.
   *
   * Returns zero on success
   */
  static int ecryptfs_read_headers_virt(char *page_virt,
  				      struct ecryptfs_crypt_stat *crypt_stat,
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1499
1500
  				      struct dentry *ecryptfs_dentry,
  				      int validate_header_size)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1501
1502
1503
1504
1505
1506
1507
1508
1509
  {
  	int rc = 0;
  	int offset;
  	int bytes_read;
  
  	ecryptfs_set_default_sizes(crypt_stat);
  	crypt_stat->mount_crypt_stat = &ecryptfs_superblock_to_private(
  		ecryptfs_dentry->d_sb)->mount_crypt_stat;
  	offset = ECRYPTFS_FILE_SIZE_BYTES;
7a86617e5   Tyler Hicks   eCryptfs: Return ...
1510
1511
  	rc = ecryptfs_validate_marker(page_virt + offset);
  	if (rc)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1512
  		goto out;
3aeb86ea4   Tyler Hicks   eCryptfs: Handle ...
1513
1514
  	if (!(crypt_stat->flags & ECRYPTFS_I_SIZE_INITIALIZED))
  		ecryptfs_i_size_init(page_virt, ecryptfs_dentry->d_inode);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
  	offset += MAGIC_ECRYPTFS_MARKER_SIZE_BYTES;
  	rc = ecryptfs_process_flags(crypt_stat, (page_virt + offset),
  				    &bytes_read);
  	if (rc) {
  		ecryptfs_printk(KERN_WARNING, "Error processing flags
  ");
  		goto out;
  	}
  	if (crypt_stat->file_version > ECRYPTFS_SUPPORTED_FILE_VERSION) {
  		ecryptfs_printk(KERN_WARNING, "File version is [%d]; only "
  				"file version [%d] is supported by this "
  				"version of eCryptfs
  ",
  				crypt_stat->file_version,
  				ECRYPTFS_SUPPORTED_FILE_VERSION);
  		rc = -EINVAL;
  		goto out;
  	}
  	offset += bytes_read;
  	if (crypt_stat->file_version >= 1) {
  		rc = parse_header_metadata(crypt_stat, (page_virt + offset),
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1536
  					   &bytes_read, validate_header_size);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
  		if (rc) {
  			ecryptfs_printk(KERN_WARNING, "Error reading header "
  					"metadata; rc = [%d]
  ", rc);
  		}
  		offset += bytes_read;
  	} else
  		set_default_header_data(crypt_stat);
  	rc = ecryptfs_parse_packet_set(crypt_stat, (page_virt + offset),
  				       ecryptfs_dentry);
  out:
  	return rc;
  }
  
  /**
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1552
   * ecryptfs_read_xattr_region
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1553
   * @page_virt: The vitual address into which to read the xattr data
2ed92554a   Michael Halcrow   eCryptfs: make op...
1554
   * @ecryptfs_inode: The eCryptfs inode
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1555
1556
1557
   *
   * Attempts to read the crypto metadata from the extended attribute
   * region of the lower file.
22e78fafb   Michael Halcrow   eCryptfs: kerneld...
1558
1559
   *
   * Returns zero on success; non-zero on error
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1560
   */
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1561
  int ecryptfs_read_xattr_region(char *page_virt, struct inode *ecryptfs_inode)
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1562
  {
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1563
1564
  	struct dentry *lower_dentry =
  		ecryptfs_inode_to_private(ecryptfs_inode)->lower_file->f_dentry;
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1565
1566
  	ssize_t size;
  	int rc = 0;
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1567
1568
  	size = ecryptfs_getxattr_lower(lower_dentry, ECRYPTFS_XATTR_NAME,
  				       page_virt, ECRYPTFS_DEFAULT_EXTENT_SIZE);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1569
  	if (size < 0) {
25bd81740   Michael Halcrow   eCryptfs: Minor f...
1570
1571
1572
1573
1574
  		if (unlikely(ecryptfs_verbosity > 0))
  			printk(KERN_INFO "Error attempting to read the [%s] "
  			       "xattr from the lower file; return value = "
  			       "[%zd]
  ", ECRYPTFS_XATTR_NAME, size);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1575
1576
1577
1578
1579
1580
  		rc = -EINVAL;
  		goto out;
  	}
  out:
  	return rc;
  }
778aeb42a   Tyler Hicks   eCryptfs: Cleanup...
1581
  int ecryptfs_read_and_validate_xattr_region(struct dentry *dentry,
3b06b3ebf   Tyler Hicks   eCryptfs: Fix new...
1582
  					    struct inode *inode)
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1583
  {
778aeb42a   Tyler Hicks   eCryptfs: Cleanup...
1584
1585
  	u8 file_size[ECRYPTFS_SIZE_AND_MARKER_BYTES];
  	u8 *marker = file_size + ECRYPTFS_FILE_SIZE_BYTES;
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1586
  	int rc;
778aeb42a   Tyler Hicks   eCryptfs: Cleanup...
1587
1588
1589
1590
1591
1592
1593
1594
  	rc = ecryptfs_getxattr_lower(ecryptfs_dentry_to_lower(dentry),
  				     ECRYPTFS_XATTR_NAME, file_size,
  				     ECRYPTFS_SIZE_AND_MARKER_BYTES);
  	if (rc < ECRYPTFS_SIZE_AND_MARKER_BYTES)
  		return rc >= 0 ? -EINVAL : rc;
  	rc = ecryptfs_validate_marker(marker);
  	if (!rc)
  		ecryptfs_i_size_init(file_size, inode);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
  	return rc;
  }
  
  /**
   * ecryptfs_read_metadata
   *
   * Common entry point for reading file metadata. From here, we could
   * retrieve the header information from the header region of the file,
   * the xattr region of the file, or some other repostory that is
   * stored separately from the file itself. The current implementation
   * supports retrieving the metadata information from the file contents
   * and from the xattr region.
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1607
1608
1609
   *
   * Returns zero if valid headers found and parsed; non-zero otherwise
   */
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1610
  int ecryptfs_read_metadata(struct dentry *ecryptfs_dentry)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1611
1612
1613
  {
  	int rc = 0;
  	char *page_virt = NULL;
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1614
  	struct inode *ecryptfs_inode = ecryptfs_dentry->d_inode;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1615
  	struct ecryptfs_crypt_stat *crypt_stat =
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1616
  	    &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
e77a56ddc   Michael Halcrow   [PATCH] eCryptfs:...
1617
1618
1619
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
  		&ecryptfs_superblock_to_private(
  			ecryptfs_dentry->d_sb)->mount_crypt_stat;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1620

e77a56ddc   Michael Halcrow   [PATCH] eCryptfs:...
1621
1622
  	ecryptfs_copy_mount_wide_flags_to_inode_flags(crypt_stat,
  						      mount_crypt_stat);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1623
  	/* Read the first page from the underlying file */
306328705   Tyler Hicks   eCryptfs: Remove ...
1624
  	page_virt = kmem_cache_alloc(ecryptfs_header_cache, GFP_USER);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1625
1626
  	if (!page_virt) {
  		rc = -ENOMEM;
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1627
1628
  		printk(KERN_ERR "%s: Unable to allocate page_virt
  ",
18d1dbf1d   Harvey Harrison   ecryptfs: replace...
1629
  		       __func__);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1630
1631
  		goto out;
  	}
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1632
1633
  	rc = ecryptfs_read_lower(page_virt, 0, crypt_stat->extent_size,
  				 ecryptfs_inode);
96a7b9c2f   Tyler Hicks   eCryptfs: Propaga...
1634
  	if (rc >= 0)
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1635
1636
1637
  		rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
  						ecryptfs_dentry,
  						ECRYPTFS_VALIDATE_HEADER_SIZE);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1638
  	if (rc) {
1984c23f9   Tyler Hicks   eCryptfs: Clear b...
1639
  		memset(page_virt, 0, PAGE_CACHE_SIZE);
d7cdc5feb   Michael Halcrow   eCryptfs: update ...
1640
  		rc = ecryptfs_read_xattr_region(page_virt, ecryptfs_inode);
dd2a3b7ad   Michael Halcrow   [PATCH] eCryptfs:...
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
  		if (rc) {
  			printk(KERN_DEBUG "Valid eCryptfs headers not found in "
  			       "file header region or xattr region
  ");
  			rc = -EINVAL;
  			goto out;
  		}
  		rc = ecryptfs_read_headers_virt(page_virt, crypt_stat,
  						ecryptfs_dentry,
  						ECRYPTFS_DONT_VALIDATE_HEADER_SIZE);
  		if (rc) {
  			printk(KERN_DEBUG "Valid eCryptfs headers not found in "
  			       "file xattr region either
  ");
  			rc = -EINVAL;
  		}
  		if (crypt_stat->mount_crypt_stat->flags
  		    & ECRYPTFS_XATTR_METADATA_ENABLED) {
  			crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
  		} else {
  			printk(KERN_WARNING "Attempt to access file with "
  			       "crypto metadata only in the extended attribute "
  			       "region, but eCryptfs was mounted without "
  			       "xattr support enabled. eCryptfs will not treat "
  			       "this like an encrypted file.
  ");
  			rc = -EINVAL;
  		}
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1669
1670
1671
1672
  	}
  out:
  	if (page_virt) {
  		memset(page_virt, 0, PAGE_CACHE_SIZE);
306328705   Tyler Hicks   eCryptfs: Remove ...
1673
  		kmem_cache_free(ecryptfs_header_cache, page_virt);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1674
1675
1676
1677
1678
  	}
  	return rc;
  }
  
  /**
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
   * ecryptfs_encrypt_filename - encrypt filename
   *
   * CBC-encrypts the filename. We do not want to encrypt the same
   * filename with the same key and IV, which may happen with hard
   * links, so we prepend random bits to each filename.
   *
   * Returns zero on success; non-zero otherwise
   */
  static int
  ecryptfs_encrypt_filename(struct ecryptfs_filename *filename,
  			  struct ecryptfs_crypt_stat *crypt_stat,
  			  struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
  {
  	int rc = 0;
  
  	filename->encrypted_filename = NULL;
  	filename->encrypted_filename_size = 0;
  	if ((crypt_stat && (crypt_stat->flags & ECRYPTFS_ENCFN_USE_MOUNT_FNEK))
  	    || (mount_crypt_stat && (mount_crypt_stat->flags
  				     & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK))) {
  		size_t packet_size;
  		size_t remaining_bytes;
  
  		rc = ecryptfs_write_tag_70_packet(
  			NULL, NULL,
  			&filename->encrypted_filename_size,
  			mount_crypt_stat, NULL,
  			filename->filename_size);
  		if (rc) {
  			printk(KERN_ERR "%s: Error attempting to get packet "
  			       "size for tag 72; rc = [%d]
  ", __func__,
  			       rc);
  			filename->encrypted_filename_size = 0;
  			goto out;
  		}
  		filename->encrypted_filename =
  			kmalloc(filename->encrypted_filename_size, GFP_KERNEL);
  		if (!filename->encrypted_filename) {
  			printk(KERN_ERR "%s: Out of memory whilst attempting "
df261c52a   Michael Halcrow   eCryptfs: Replace...
1719
1720
  			       "to kmalloc [%zd] bytes
  ", __func__,
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
  			       filename->encrypted_filename_size);
  			rc = -ENOMEM;
  			goto out;
  		}
  		remaining_bytes = filename->encrypted_filename_size;
  		rc = ecryptfs_write_tag_70_packet(filename->encrypted_filename,
  						  &remaining_bytes,
  						  &packet_size,
  						  mount_crypt_stat,
  						  filename->filename,
  						  filename->filename_size);
  		if (rc) {
  			printk(KERN_ERR "%s: Error attempting to generate "
  			       "tag 70 packet; rc = [%d]
  ", __func__,
  			       rc);
  			kfree(filename->encrypted_filename);
  			filename->encrypted_filename = NULL;
  			filename->encrypted_filename_size = 0;
  			goto out;
  		}
  		filename->encrypted_filename_size = packet_size;
  	} else {
  		printk(KERN_ERR "%s: No support for requested filename "
  		       "encryption method in this release
  ", __func__);
df6ad33ba   Tyler Hicks   eCryptfs: Filenam...
1747
  		rc = -EOPNOTSUPP;
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
  		goto out;
  	}
  out:
  	return rc;
  }
  
  static int ecryptfs_copy_filename(char **copied_name, size_t *copied_name_size,
  				  const char *name, size_t name_size)
  {
  	int rc = 0;
fd9fc842b   Tyler Hicks   eCryptfs: Regress...
1758
  	(*copied_name) = kmalloc((name_size + 1), GFP_KERNEL);
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
1759
1760
1761
1762
1763
1764
1765
1766
1767
  	if (!(*copied_name)) {
  		rc = -ENOMEM;
  		goto out;
  	}
  	memcpy((void *)(*copied_name), (void *)name, name_size);
  	(*copied_name)[(name_size)] = '\0';	/* Only for convenience
  						 * in printing out the
  						 * string in debug
  						 * messages */
fd9fc842b   Tyler Hicks   eCryptfs: Regress...
1768
  	(*copied_name_size) = name_size;
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
1769
1770
1771
1772
1773
  out:
  	return rc;
  }
  
  /**
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1774
   * ecryptfs_process_key_cipher - Perform key cipher initialization.
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1775
   * @key_tfm: Crypto context for key material, set by this function
e5d9cbde6   Michael Halcrow   [PATCH] eCryptfs:...
1776
1777
   * @cipher_name: Name of the cipher
   * @key_size: Size of the key in bytes
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1778
1779
1780
1781
1782
   *
   * Returns zero on success. Any crypto_tfm structs allocated here
   * should be released by other functions, such as on a superblock put
   * event, regardless of whether this function succeeds for fails.
   */
cd9d67dfd   Michael Halcrow   eCryptfs: make ne...
1783
  static int
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1784
1785
  ecryptfs_process_key_cipher(struct crypto_blkcipher **key_tfm,
  			    char *cipher_name, size_t *key_size)
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1786
1787
  {
  	char dummy_key[ECRYPTFS_MAX_KEY_BYTES];
ece550f51   Dan Carpenter   ecryptfs: use aft...
1788
  	char *full_alg_name = NULL;
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1789
  	int rc;
e5d9cbde6   Michael Halcrow   [PATCH] eCryptfs:...
1790
1791
  	*key_tfm = NULL;
  	if (*key_size > ECRYPTFS_MAX_KEY_BYTES) {
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1792
  		rc = -EINVAL;
df261c52a   Michael Halcrow   eCryptfs: Replace...
1793
  		printk(KERN_ERR "Requested key size is [%zd] bytes; maximum "
e5d9cbde6   Michael Halcrow   [PATCH] eCryptfs:...
1794
1795
  		      "allowable is [%d]
  ", *key_size, ECRYPTFS_MAX_KEY_BYTES);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1796
1797
  		goto out;
  	}
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
1798
1799
1800
1801
1802
  	rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name, cipher_name,
  						    "ecb");
  	if (rc)
  		goto out;
  	*key_tfm = crypto_alloc_blkcipher(full_alg_name, 0, CRYPTO_ALG_ASYNC);
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
1803
1804
  	if (IS_ERR(*key_tfm)) {
  		rc = PTR_ERR(*key_tfm);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1805
  		printk(KERN_ERR "Unable to allocate crypto cipher with name "
382684984   Dave Hansen   ecryptfs: improve...
1806
1807
  		       "[%s]; rc = [%d]
  ", full_alg_name, rc);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1808
1809
  		goto out;
  	}
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
1810
1811
1812
1813
1814
1815
  	crypto_blkcipher_set_flags(*key_tfm, CRYPTO_TFM_REQ_WEAK_KEY);
  	if (*key_size == 0) {
  		struct blkcipher_alg *alg = crypto_blkcipher_alg(*key_tfm);
  
  		*key_size = alg->max_keysize;
  	}
e5d9cbde6   Michael Halcrow   [PATCH] eCryptfs:...
1816
  	get_random_bytes(dummy_key, *key_size);
8bba066f4   Michael Halcrow   [PATCH] eCryptfs:...
1817
  	rc = crypto_blkcipher_setkey(*key_tfm, dummy_key, *key_size);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1818
  	if (rc) {
df261c52a   Michael Halcrow   eCryptfs: Replace...
1819
  		printk(KERN_ERR "Error attempting to set key of size [%zd] for "
382684984   Dave Hansen   ecryptfs: improve...
1820
1821
1822
  		       "cipher [%s]; rc = [%d]
  ", *key_size, full_alg_name,
  		       rc);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1823
1824
1825
1826
  		rc = -EINVAL;
  		goto out;
  	}
  out:
ece550f51   Dan Carpenter   ecryptfs: use aft...
1827
  	kfree(full_alg_name);
237fead61   Michael Halcrow   [PATCH] ecryptfs:...
1828
1829
  	return rc;
  }
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1830
1831
  
  struct kmem_cache *ecryptfs_key_tfm_cache;
7896b6318   Adrian Bunk   fs/ecryptfs/: pos...
1832
  static struct list_head key_tfm_list;
af440f529   Eric Sandeen   ecryptfs: check f...
1833
  struct mutex key_tfm_list_mutex;
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1834

7371a3820   Jerome Marchand   ecryptfs: properl...
1835
  int __init ecryptfs_init_crypto(void)
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1836
1837
1838
1839
1840
  {
  	mutex_init(&key_tfm_list_mutex);
  	INIT_LIST_HEAD(&key_tfm_list);
  	return 0;
  }
af440f529   Eric Sandeen   ecryptfs: check f...
1841
1842
1843
1844
1845
  /**
   * ecryptfs_destroy_crypto - free all cached key_tfms on key_tfm_list
   *
   * Called only at module unload time
   */
fcd128356   Michael Halcrow   eCryptfs: grammat...
1846
  int ecryptfs_destroy_crypto(void)
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
  {
  	struct ecryptfs_key_tfm *key_tfm, *key_tfm_tmp;
  
  	mutex_lock(&key_tfm_list_mutex);
  	list_for_each_entry_safe(key_tfm, key_tfm_tmp, &key_tfm_list,
  				 key_tfm_list) {
  		list_del(&key_tfm->key_tfm_list);
  		if (key_tfm->key_tfm)
  			crypto_free_blkcipher(key_tfm->key_tfm);
  		kmem_cache_free(ecryptfs_key_tfm_cache, key_tfm);
  	}
  	mutex_unlock(&key_tfm_list_mutex);
  	return 0;
  }
  
  int
  ecryptfs_add_new_key_tfm(struct ecryptfs_key_tfm **key_tfm, char *cipher_name,
  			 size_t key_size)
  {
  	struct ecryptfs_key_tfm *tmp_tfm;
  	int rc = 0;
af440f529   Eric Sandeen   ecryptfs: check f...
1868
  	BUG_ON(!mutex_is_locked(&key_tfm_list_mutex));
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
  	tmp_tfm = kmem_cache_alloc(ecryptfs_key_tfm_cache, GFP_KERNEL);
  	if (key_tfm != NULL)
  		(*key_tfm) = tmp_tfm;
  	if (!tmp_tfm) {
  		rc = -ENOMEM;
  		printk(KERN_ERR "Error attempting to allocate from "
  		       "ecryptfs_key_tfm_cache
  ");
  		goto out;
  	}
  	mutex_init(&tmp_tfm->key_tfm_mutex);
  	strncpy(tmp_tfm->cipher_name, cipher_name,
  		ECRYPTFS_MAX_CIPHER_NAME_SIZE);
b88629060   Eric Sandeen   ecryptfs: fix str...
1882
  	tmp_tfm->cipher_name[ECRYPTFS_MAX_CIPHER_NAME_SIZE] = '\0';
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1883
  	tmp_tfm->key_size = key_size;
5dda6992a   Michael Halcrow   eCryptfs: remove ...
1884
1885
1886
1887
  	rc = ecryptfs_process_key_cipher(&tmp_tfm->key_tfm,
  					 tmp_tfm->cipher_name,
  					 &tmp_tfm->key_size);
  	if (rc) {
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1888
1889
1890
1891
1892
1893
1894
1895
1896
  		printk(KERN_ERR "Error attempting to initialize key TFM "
  		       "cipher with name = [%s]; rc = [%d]
  ",
  		       tmp_tfm->cipher_name, rc);
  		kmem_cache_free(ecryptfs_key_tfm_cache, tmp_tfm);
  		if (key_tfm != NULL)
  			(*key_tfm) = NULL;
  		goto out;
  	}
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1897
  	list_add(&tmp_tfm->key_tfm_list, &key_tfm_list);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1898
1899
1900
  out:
  	return rc;
  }
af440f529   Eric Sandeen   ecryptfs: check f...
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
  /**
   * ecryptfs_tfm_exists - Search for existing tfm for cipher_name.
   * @cipher_name: the name of the cipher to search for
   * @key_tfm: set to corresponding tfm if found
   *
   * Searches for cached key_tfm matching @cipher_name
   * Must be called with &key_tfm_list_mutex held
   * Returns 1 if found, with @key_tfm set
   * Returns 0 if not found, with @key_tfm set to NULL
   */
  int ecryptfs_tfm_exists(char *cipher_name, struct ecryptfs_key_tfm **key_tfm)
  {
  	struct ecryptfs_key_tfm *tmp_key_tfm;
  
  	BUG_ON(!mutex_is_locked(&key_tfm_list_mutex));
  
  	list_for_each_entry(tmp_key_tfm, &key_tfm_list, key_tfm_list) {
  		if (strcmp(tmp_key_tfm->cipher_name, cipher_name) == 0) {
  			if (key_tfm)
  				(*key_tfm) = tmp_key_tfm;
  			return 1;
  		}
  	}
  	if (key_tfm)
  		(*key_tfm) = NULL;
  	return 0;
  }
  
  /**
   * ecryptfs_get_tfm_and_mutex_for_cipher_name
   *
   * @tfm: set to cached tfm found, or new tfm created
   * @tfm_mutex: set to mutex for cached tfm found, or new tfm created
   * @cipher_name: the name of the cipher to search for and/or add
   *
   * Sets pointers to @tfm & @tfm_mutex matching @cipher_name.
   * Searches for cached item first, and creates new if not found.
   * Returns 0 on success, non-zero if adding new cipher failed
   */
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1940
1941
1942
1943
1944
1945
1946
1947
1948
  int ecryptfs_get_tfm_and_mutex_for_cipher_name(struct crypto_blkcipher **tfm,
  					       struct mutex **tfm_mutex,
  					       char *cipher_name)
  {
  	struct ecryptfs_key_tfm *key_tfm;
  	int rc = 0;
  
  	(*tfm) = NULL;
  	(*tfm_mutex) = NULL;
af440f529   Eric Sandeen   ecryptfs: check f...
1949

f4aad16ad   Michael Halcrow   eCryptfs: add key...
1950
  	mutex_lock(&key_tfm_list_mutex);
af440f529   Eric Sandeen   ecryptfs: check f...
1951
1952
1953
1954
1955
1956
  	if (!ecryptfs_tfm_exists(cipher_name, &key_tfm)) {
  		rc = ecryptfs_add_new_key_tfm(&key_tfm, cipher_name, 0);
  		if (rc) {
  			printk(KERN_ERR "Error adding new key_tfm to list; "
  					"rc = [%d]
  ", rc);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1957
1958
1959
  			goto out;
  		}
  	}
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1960
1961
1962
  	(*tfm) = key_tfm->key_tfm;
  	(*tfm_mutex) = &key_tfm->key_tfm_mutex;
  out:
71fd5179e   Cyrill Gorcunov   ecryptfs: fix mis...
1963
  	mutex_unlock(&key_tfm_list_mutex);
f4aad16ad   Michael Halcrow   eCryptfs: add key...
1964
1965
  	return rc;
  }
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
1966
1967
1968
1969
1970
1971
1972
1973
1974
  
  /* 64 characters forming a 6-bit target field */
  static unsigned char *portable_filename_chars = ("-.0123456789ABCD"
  						 "EFGHIJKLMNOPQRST"
  						 "UVWXYZabcdefghij"
  						 "klmnopqrstuvwxyz");
  
  /* We could either offset on every reverse map or just pad some 0x00's
   * at the front here */
0f751e641   Tyler Hicks   eCryptfs: Extend ...
1975
  static const unsigned char filename_rev_map[256] = {
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
  	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 7 */
  	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 15 */
  	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 23 */
  	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 31 */
  	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 39 */
  	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, /* 47 */
  	0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, /* 55 */
  	0x0A, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 63 */
  	0x00, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, /* 71 */
  	0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, /* 79 */
  	0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, /* 87 */
  	0x23, 0x24, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, /* 95 */
  	0x00, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, /* 103 */
  	0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, /* 111 */
  	0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, /* 119 */
0f751e641   Tyler Hicks   eCryptfs: Extend ...
1991
  	0x3D, 0x3E, 0x3F /* 123 - 255 initialized to 0x00 */
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
  };
  
  /**
   * ecryptfs_encode_for_filename
   * @dst: Destination location for encoded filename
   * @dst_size: Size of the encoded filename in bytes
   * @src: Source location for the filename to encode
   * @src_size: Size of the source in bytes
   */
  void ecryptfs_encode_for_filename(unsigned char *dst, size_t *dst_size,
  				  unsigned char *src, size_t src_size)
  {
  	size_t num_blocks;
  	size_t block_num = 0;
  	size_t dst_offset = 0;
  	unsigned char last_block[3];
  
  	if (src_size == 0) {
  		(*dst_size) = 0;
  		goto out;
  	}
  	num_blocks = (src_size / 3);
  	if ((src_size % 3) == 0) {
  		memcpy(last_block, (&src[src_size - 3]), 3);
  	} else {
  		num_blocks++;
  		last_block[2] = 0x00;
  		switch (src_size % 3) {
  		case 1:
  			last_block[0] = src[src_size - 1];
  			last_block[1] = 0x00;
  			break;
  		case 2:
  			last_block[0] = src[src_size - 2];
  			last_block[1] = src[src_size - 1];
  		}
  	}
  	(*dst_size) = (num_blocks * 4);
  	if (!dst)
  		goto out;
  	while (block_num < num_blocks) {
  		unsigned char *src_block;
  		unsigned char dst_block[4];
  
  		if (block_num == (num_blocks - 1))
  			src_block = last_block;
  		else
  			src_block = &src[block_num * 3];
  		dst_block[0] = ((src_block[0] >> 2) & 0x3F);
  		dst_block[1] = (((src_block[0] << 4) & 0x30)
  				| ((src_block[1] >> 4) & 0x0F));
  		dst_block[2] = (((src_block[1] << 2) & 0x3C)
  				| ((src_block[2] >> 6) & 0x03));
  		dst_block[3] = (src_block[2] & 0x3F);
  		dst[dst_offset++] = portable_filename_chars[dst_block[0]];
  		dst[dst_offset++] = portable_filename_chars[dst_block[1]];
  		dst[dst_offset++] = portable_filename_chars[dst_block[2]];
  		dst[dst_offset++] = portable_filename_chars[dst_block[3]];
  		block_num++;
  	}
  out:
  	return;
  }
71c11c378   Michael Halcrow   eCryptfs: Clean u...
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
  /**
   * ecryptfs_decode_from_filename
   * @dst: If NULL, this function only sets @dst_size and returns. If
   *       non-NULL, this function decodes the encoded octets in @src
   *       into the memory that @dst points to.
   * @dst_size: Set to the size of the decoded string.
   * @src: The encoded set of octets to decode.
   * @src_size: The size of the encoded set of octets to decode.
   */
  static void
  ecryptfs_decode_from_filename(unsigned char *dst, size_t *dst_size,
  			      const unsigned char *src, size_t src_size)
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2067
2068
2069
2070
  {
  	u8 current_bit_offset = 0;
  	size_t src_byte_offset = 0;
  	size_t dst_byte_offset = 0;
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2071
2072
  
  	if (dst == NULL) {
71c11c378   Michael Halcrow   eCryptfs: Clean u...
2073
2074
2075
2076
2077
2078
  		/* Not exact; conservatively long. Every block of 4
  		 * encoded characters decodes into a block of 3
  		 * decoded characters. This segment of code provides
  		 * the caller with the maximum amount of allocated
  		 * space that @dst will need to point to in a
  		 * subsequent call. */
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
  		(*dst_size) = (((src_size + 1) * 3) / 4);
  		goto out;
  	}
  	while (src_byte_offset < src_size) {
  		unsigned char src_byte =
  				filename_rev_map[(int)src[src_byte_offset]];
  
  		switch (current_bit_offset) {
  		case 0:
  			dst[dst_byte_offset] = (src_byte << 2);
  			current_bit_offset = 6;
  			break;
  		case 6:
  			dst[dst_byte_offset++] |= (src_byte >> 4);
  			dst[dst_byte_offset] = ((src_byte & 0xF)
  						 << 4);
  			current_bit_offset = 4;
  			break;
  		case 4:
  			dst[dst_byte_offset++] |= (src_byte >> 2);
  			dst[dst_byte_offset] = (src_byte << 6);
  			current_bit_offset = 2;
  			break;
  		case 2:
  			dst[dst_byte_offset++] |= (src_byte);
  			dst[dst_byte_offset] = 0;
  			current_bit_offset = 0;
  			break;
  		}
  		src_byte_offset++;
  	}
  	(*dst_size) = dst_byte_offset;
  out:
71c11c378   Michael Halcrow   eCryptfs: Clean u...
2112
  	return;
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
  }
  
  /**
   * ecryptfs_encrypt_and_encode_filename - converts a plaintext file name to cipher text
   * @crypt_stat: The crypt_stat struct associated with the file anem to encode
   * @name: The plaintext name
   * @length: The length of the plaintext
   * @encoded_name: The encypted name
   *
   * Encrypts and encodes a filename into something that constitutes a
   * valid filename for a filesystem, with printable characters.
   *
   * We assume that we have a properly initialized crypto context,
   * pointed to by crypt_stat->tfm.
   *
   * Returns zero on success; non-zero on otherwise
   */
  int ecryptfs_encrypt_and_encode_filename(
  	char **encoded_name,
  	size_t *encoded_name_size,
  	struct ecryptfs_crypt_stat *crypt_stat,
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
  	const char *name, size_t name_size)
  {
  	size_t encoded_name_no_prefix_size;
  	int rc = 0;
  
  	(*encoded_name) = NULL;
  	(*encoded_name_size) = 0;
  	if ((crypt_stat && (crypt_stat->flags & ECRYPTFS_ENCRYPT_FILENAMES))
  	    || (mount_crypt_stat && (mount_crypt_stat->flags
  				     & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES))) {
  		struct ecryptfs_filename *filename;
  
  		filename = kzalloc(sizeof(*filename), GFP_KERNEL);
  		if (!filename) {
  			printk(KERN_ERR "%s: Out of memory whilst attempting "
a8f12864c   Michael Halcrow   eCryptfs: Fix dat...
2150
2151
  			       "to kzalloc [%zd] bytes
  ", __func__,
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
  			       sizeof(*filename));
  			rc = -ENOMEM;
  			goto out;
  		}
  		filename->filename = (char *)name;
  		filename->filename_size = name_size;
  		rc = ecryptfs_encrypt_filename(filename, crypt_stat,
  					       mount_crypt_stat);
  		if (rc) {
  			printk(KERN_ERR "%s: Error attempting to encrypt "
  			       "filename; rc = [%d]
  ", __func__, rc);
  			kfree(filename);
  			goto out;
  		}
  		ecryptfs_encode_for_filename(
  			NULL, &encoded_name_no_prefix_size,
  			filename->encrypted_filename,
  			filename->encrypted_filename_size);
  		if ((crypt_stat && (crypt_stat->flags
  				    & ECRYPTFS_ENCFN_USE_MOUNT_FNEK))
  		    || (mount_crypt_stat
  			&& (mount_crypt_stat->flags
  			    & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK)))
  			(*encoded_name_size) =
  				(ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE
  				 + encoded_name_no_prefix_size);
  		else
  			(*encoded_name_size) =
  				(ECRYPTFS_FEK_ENCRYPTED_FILENAME_PREFIX_SIZE
  				 + encoded_name_no_prefix_size);
  		(*encoded_name) = kmalloc((*encoded_name_size) + 1, GFP_KERNEL);
  		if (!(*encoded_name)) {
  			printk(KERN_ERR "%s: Out of memory whilst attempting "
a8f12864c   Michael Halcrow   eCryptfs: Fix dat...
2186
2187
  			       "to kzalloc [%zd] bytes
  ", __func__,
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
  			       (*encoded_name_size));
  			rc = -ENOMEM;
  			kfree(filename->encrypted_filename);
  			kfree(filename);
  			goto out;
  		}
  		if ((crypt_stat && (crypt_stat->flags
  				    & ECRYPTFS_ENCFN_USE_MOUNT_FNEK))
  		    || (mount_crypt_stat
  			&& (mount_crypt_stat->flags
  			    & ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK))) {
  			memcpy((*encoded_name),
  			       ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX,
  			       ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE);
  			ecryptfs_encode_for_filename(
  			    ((*encoded_name)
  			     + ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE),
  			    &encoded_name_no_prefix_size,
  			    filename->encrypted_filename,
  			    filename->encrypted_filename_size);
  			(*encoded_name_size) =
  				(ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE
  				 + encoded_name_no_prefix_size);
  			(*encoded_name)[(*encoded_name_size)] = '\0';
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2212
  		} else {
df6ad33ba   Tyler Hicks   eCryptfs: Filenam...
2213
  			rc = -EOPNOTSUPP;
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
  		}
  		if (rc) {
  			printk(KERN_ERR "%s: Error attempting to encode "
  			       "encrypted filename; rc = [%d]
  ", __func__,
  			       rc);
  			kfree((*encoded_name));
  			(*encoded_name) = NULL;
  			(*encoded_name_size) = 0;
  		}
  		kfree(filename->encrypted_filename);
  		kfree(filename);
  	} else {
  		rc = ecryptfs_copy_filename(encoded_name,
  					    encoded_name_size,
  					    name, name_size);
  	}
  out:
  	return rc;
  }
  
  /**
   * ecryptfs_decode_and_decrypt_filename - converts the encoded cipher text name to decoded plaintext
   * @plaintext_name: The plaintext name
   * @plaintext_name_size: The plaintext name size
   * @ecryptfs_dir_dentry: eCryptfs directory dentry
   * @name: The filename in cipher text
   * @name_size: The cipher text name size
   *
   * Decrypts and decodes the filename.
   *
   * Returns zero on error; non-zero otherwise
   */
  int ecryptfs_decode_and_decrypt_filename(char **plaintext_name,
  					 size_t *plaintext_name_size,
  					 struct dentry *ecryptfs_dir_dentry,
  					 const char *name, size_t name_size)
  {
2aac0cf88   Tyler Hicks   eCryptfs: NULL cr...
2252
2253
2254
  	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
  		&ecryptfs_superblock_to_private(
  			ecryptfs_dir_dentry->d_sb)->mount_crypt_stat;
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2255
2256
2257
2258
  	char *decoded_name;
  	size_t decoded_name_size;
  	size_t packet_size;
  	int rc = 0;
2aac0cf88   Tyler Hicks   eCryptfs: NULL cr...
2259
2260
2261
  	if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)
  	    && !(mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED)
  	    && (name_size > ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE)
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2262
2263
  	    && (strncmp(name, ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX,
  			ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE) == 0)) {
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2264
2265
2266
2267
2268
  		const char *orig_name = name;
  		size_t orig_name_size = name_size;
  
  		name += ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE;
  		name_size -= ECRYPTFS_FNEK_ENCRYPTED_FILENAME_PREFIX_SIZE;
71c11c378   Michael Halcrow   eCryptfs: Clean u...
2269
2270
  		ecryptfs_decode_from_filename(NULL, &decoded_name_size,
  					      name, name_size);
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2271
2272
2273
  		decoded_name = kmalloc(decoded_name_size, GFP_KERNEL);
  		if (!decoded_name) {
  			printk(KERN_ERR "%s: Out of memory whilst attempting "
df261c52a   Michael Halcrow   eCryptfs: Replace...
2274
2275
  			       "to kmalloc [%zd] bytes
  ", __func__,
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2276
2277
2278
2279
  			       decoded_name_size);
  			rc = -ENOMEM;
  			goto out;
  		}
71c11c378   Michael Halcrow   eCryptfs: Clean u...
2280
2281
  		ecryptfs_decode_from_filename(decoded_name, &decoded_name_size,
  					      name, name_size);
51ca58dcc   Michael Halcrow   eCryptfs: Filenam...
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
  		rc = ecryptfs_parse_tag_70_packet(plaintext_name,
  						  plaintext_name_size,
  						  &packet_size,
  						  mount_crypt_stat,
  						  decoded_name,
  						  decoded_name_size);
  		if (rc) {
  			printk(KERN_INFO "%s: Could not parse tag 70 packet "
  			       "from filename; copying through filename "
  			       "as-is
  ", __func__);
  			rc = ecryptfs_copy_filename(plaintext_name,
  						    plaintext_name_size,
  						    orig_name, orig_name_size);
  			goto out_free;
  		}
  	} else {
  		rc = ecryptfs_copy_filename(plaintext_name,
  					    plaintext_name_size,
  					    name, name_size);
  		goto out;
  	}
  out_free:
  	kfree(decoded_name);
  out:
  	return rc;
  }