80bccd5ff8e6671908b528e408aa9427b2c7fbf4
[linux-2.6.git] / fs / ecryptfs / keystore.c
1 /**
2  * eCryptfs: Linux filesystem encryption layer
3  * In-kernel key management code.  Includes functions to parse and
4  * write authentication token-related packets with the underlying
5  * file.
6  *
7  * Copyright (C) 2004-2006 International Business Machines Corp.
8  *   Author(s): Michael A. Halcrow <mhalcrow@us.ibm.com>
9  *              Michael C. Thompson <mcthomps@us.ibm.com>
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License as
13  * published by the Free Software Foundation; either version 2 of the
14  * License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful, but
17  * WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24  * 02111-1307, USA.
25  */
26
27 #include <linux/string.h>
28 #include <linux/sched.h>
29 #include <linux/syscalls.h>
30 #include <linux/pagemap.h>
31 #include <linux/key.h>
32 #include <linux/random.h>
33 #include <linux/crypto.h>
34 #include <linux/scatterlist.h>
35 #include "ecryptfs_kernel.h"
36
37 /**
38  * request_key returned an error instead of a valid key address;
39  * determine the type of error, make appropriate log entries, and
40  * return an error code.
41  */
42 int process_request_key_err(long err_code)
43 {
44         int rc = 0;
45
46         switch (err_code) {
47         case ENOKEY:
48                 ecryptfs_printk(KERN_WARNING, "No key\n");
49                 rc = -ENOENT;
50                 break;
51         case EKEYEXPIRED:
52                 ecryptfs_printk(KERN_WARNING, "Key expired\n");
53                 rc = -ETIME;
54                 break;
55         case EKEYREVOKED:
56                 ecryptfs_printk(KERN_WARNING, "Key revoked\n");
57                 rc = -EINVAL;
58                 break;
59         default:
60                 ecryptfs_printk(KERN_WARNING, "Unknown error code: "
61                                 "[0x%.16x]\n", err_code);
62                 rc = -EINVAL;
63         }
64         return rc;
65 }
66
67 static void wipe_auth_tok_list(struct list_head *auth_tok_list_head)
68 {
69         struct list_head *walker;
70         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
71
72         walker = auth_tok_list_head->next;
73         while (walker != auth_tok_list_head) {
74                 auth_tok_list_item =
75                     list_entry(walker, struct ecryptfs_auth_tok_list_item,
76                                list);
77                 walker = auth_tok_list_item->list.next;
78                 memset(auth_tok_list_item, 0,
79                        sizeof(struct ecryptfs_auth_tok_list_item));
80                 kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
81                                 auth_tok_list_item);
82         }
83 }
84
85 struct kmem_cache *ecryptfs_auth_tok_list_item_cache;
86
87 /**
88  * parse_packet_length
89  * @data: Pointer to memory containing length at offset
90  * @size: This function writes the decoded size to this memory
91  *        address; zero on error
92  * @length_size: The number of bytes occupied by the encoded length
93  *
94  * Returns Zero on success
95  */
96 static int parse_packet_length(unsigned char *data, size_t *size,
97                                size_t *length_size)
98 {
99         int rc = 0;
100
101         (*length_size) = 0;
102         (*size) = 0;
103         if (data[0] < 192) {
104                 /* One-byte length */
105                 (*size) = data[0];
106                 (*length_size) = 1;
107         } else if (data[0] < 224) {
108                 /* Two-byte length */
109                 (*size) = ((data[0] - 192) * 256);
110                 (*size) += (data[1] + 192);
111                 (*length_size) = 2;
112         } else if (data[0] == 255) {
113                 /* Five-byte length; we're not supposed to see this */
114                 ecryptfs_printk(KERN_ERR, "Five-byte packet length not "
115                                 "supported\n");
116                 rc = -EINVAL;
117                 goto out;
118         } else {
119                 ecryptfs_printk(KERN_ERR, "Error parsing packet length\n");
120                 rc = -EINVAL;
121                 goto out;
122         }
123 out:
124         return rc;
125 }
126
127 /**
128  * write_packet_length
129  * @dest: The byte array target into which to write the
130  *       length. Must have at least 5 bytes allocated.
131  * @size: The length to write.
132  * @packet_size_length: The number of bytes used to encode the
133  *                      packet length is written to this address.
134  *
135  * Returns zero on success; non-zero on error.
136  */
137 static int write_packet_length(char *dest, size_t size,
138                                size_t *packet_size_length)
139 {
140         int rc = 0;
141
142         if (size < 192) {
143                 dest[0] = size;
144                 (*packet_size_length) = 1;
145         } else if (size < 65536) {
146                 dest[0] = (((size - 192) / 256) + 192);
147                 dest[1] = ((size - 192) % 256);
148                 (*packet_size_length) = 2;
149         } else {
150                 rc = -EINVAL;
151                 ecryptfs_printk(KERN_WARNING,
152                                 "Unsupported packet size: [%d]\n", size);
153         }
154         return rc;
155 }
156
157 /**
158  * parse_tag_3_packet
159  * @crypt_stat: The cryptographic context to modify based on packet
160  *              contents.
161  * @data: The raw bytes of the packet.
162  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
163  *                 a new authentication token will be placed at the end
164  *                 of this list for this packet.
165  * @new_auth_tok: Pointer to a pointer to memory that this function
166  *                allocates; sets the memory address of the pointer to
167  *                NULL on error. This object is added to the
168  *                auth_tok_list.
169  * @packet_size: This function writes the size of the parsed packet
170  *               into this memory location; zero on error.
171  * @max_packet_size: maximum number of bytes to parse
172  *
173  * Returns zero on success; non-zero on error.
174  */
175 static int
176 parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat,
177                    unsigned char *data, struct list_head *auth_tok_list,
178                    struct ecryptfs_auth_tok **new_auth_tok,
179                    size_t *packet_size, size_t max_packet_size)
180 {
181         int rc = 0;
182         size_t body_size;
183         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
184         size_t length_size;
185
186         (*packet_size) = 0;
187         (*new_auth_tok) = NULL;
188
189         /* we check that:
190          *   one byte for the Tag 3 ID flag
191          *   two bytes for the body size
192          * do not exceed the maximum_packet_size
193          */
194         if (unlikely((*packet_size) + 3 > max_packet_size)) {
195                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
196                 rc = -EINVAL;
197                 goto out;
198         }
199
200         /* check for Tag 3 identifyer - one byte */
201         if (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) {
202                 ecryptfs_printk(KERN_ERR, "Enter w/ first byte != 0x%.2x\n",
203                                 ECRYPTFS_TAG_3_PACKET_TYPE);
204                 rc = -EINVAL;
205                 goto out;
206         }
207         /* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
208          * at end of function upon failure */
209         auth_tok_list_item =
210             kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL);
211         if (!auth_tok_list_item) {
212                 ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
213                 rc = -ENOMEM;
214                 goto out;
215         }
216         (*new_auth_tok) = &auth_tok_list_item->auth_tok;
217
218         /* check for body size - one to two bytes */
219         rc = parse_packet_length(&data[(*packet_size)], &body_size,
220                                  &length_size);
221         if (rc) {
222                 ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
223                                 "rc = [%d]\n", rc);
224                 goto out_free;
225         }
226         if (unlikely(body_size < (0x05 + ECRYPTFS_SALT_SIZE))) {
227                 ecryptfs_printk(KERN_WARNING, "Invalid body size ([%d])\n",
228                                 body_size);
229                 rc = -EINVAL;
230                 goto out_free;
231         }
232         (*packet_size) += length_size;
233
234         /* now we know the length of the remainting Tag 3 packet size:
235          *   5 fix bytes for: version string, cipher, S2K ID, hash algo,
236          *                    number of hash iterations
237          *   ECRYPTFS_SALT_SIZE bytes for salt
238          *   body_size bytes minus the stuff above is the encrypted key size
239          */
240         if (unlikely((*packet_size) + body_size > max_packet_size)) {
241                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
242                 rc = -EINVAL;
243                 goto out_free;
244         }
245
246         /* There are 5 characters of additional information in the
247          * packet */
248         (*new_auth_tok)->session_key.encrypted_key_size =
249                 body_size - (0x05 + ECRYPTFS_SALT_SIZE);
250         ecryptfs_printk(KERN_DEBUG, "Encrypted key size = [%d]\n",
251                         (*new_auth_tok)->session_key.encrypted_key_size);
252
253         /* Version 4 (from RFC2440) - one byte */
254         if (unlikely(data[(*packet_size)++] != 0x04)) {
255                 ecryptfs_printk(KERN_DEBUG, "Unknown version number "
256                                 "[%d]\n", data[(*packet_size) - 1]);
257                 rc = -EINVAL;
258                 goto out_free;
259         }
260
261         /* cipher - one byte */
262         ecryptfs_cipher_code_to_string(crypt_stat->cipher,
263                                        (u16)data[(*packet_size)]);
264         /* A little extra work to differentiate among the AES key
265          * sizes; see RFC2440 */
266         switch(data[(*packet_size)++]) {
267         case RFC2440_CIPHER_AES_192:
268                 crypt_stat->key_size = 24;
269                 break;
270         default:
271                 crypt_stat->key_size =
272                         (*new_auth_tok)->session_key.encrypted_key_size;
273         }
274         ecryptfs_init_crypt_ctx(crypt_stat);
275         /* S2K identifier 3 (from RFC2440) */
276         if (unlikely(data[(*packet_size)++] != 0x03)) {
277                 ecryptfs_printk(KERN_ERR, "Only S2K ID 3 is currently "
278                                 "supported\n");
279                 rc = -ENOSYS;
280                 goto out_free;
281         }
282
283         /* TODO: finish the hash mapping */
284         /* hash algorithm - one byte */
285         switch (data[(*packet_size)++]) {
286         case 0x01: /* See RFC2440 for these numbers and their mappings */
287                 /* Choose MD5 */
288                 /* salt - ECRYPTFS_SALT_SIZE bytes */
289                 memcpy((*new_auth_tok)->token.password.salt,
290                        &data[(*packet_size)], ECRYPTFS_SALT_SIZE);
291                 (*packet_size) += ECRYPTFS_SALT_SIZE;
292
293                 /* This conversion was taken straight from RFC2440 */
294                 /* number of hash iterations - one byte */
295                 (*new_auth_tok)->token.password.hash_iterations =
296                         ((u32) 16 + (data[(*packet_size)] & 15))
297                                 << ((data[(*packet_size)] >> 4) + 6);
298                 (*packet_size)++;
299
300                 /* encrypted session key -
301                  *   (body_size-5-ECRYPTFS_SALT_SIZE) bytes */
302                 memcpy((*new_auth_tok)->session_key.encrypted_key,
303                        &data[(*packet_size)],
304                        (*new_auth_tok)->session_key.encrypted_key_size);
305                 (*packet_size) +=
306                         (*new_auth_tok)->session_key.encrypted_key_size;
307                 (*new_auth_tok)->session_key.flags &=
308                         ~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
309                 (*new_auth_tok)->session_key.flags |=
310                         ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
311                 (*new_auth_tok)->token.password.hash_algo = 0x01;
312                 break;
313         default:
314                 ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: "
315                                 "[%d]\n", data[(*packet_size) - 1]);
316                 rc = -ENOSYS;
317                 goto out_free;
318         }
319         (*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;
320         /* TODO: Parametarize; we might actually want userspace to
321          * decrypt the session key. */
322         ECRYPTFS_CLEAR_FLAG((*new_auth_tok)->session_key.flags,
323                             ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
324         ECRYPTFS_CLEAR_FLAG((*new_auth_tok)->session_key.flags,
325                             ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
326         list_add(&auth_tok_list_item->list, auth_tok_list);
327         goto out;
328 out_free:
329         (*new_auth_tok) = NULL;
330         memset(auth_tok_list_item, 0,
331                sizeof(struct ecryptfs_auth_tok_list_item));
332         kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
333                         auth_tok_list_item);
334 out:
335         if (rc)
336                 (*packet_size) = 0;
337         return rc;
338 }
339
340 /**
341  * parse_tag_11_packet
342  * @data: The raw bytes of the packet
343  * @contents: This function writes the data contents of the literal
344  *            packet into this memory location
345  * @max_contents_bytes: The maximum number of bytes that this function
346  *                      is allowed to write into contents
347  * @tag_11_contents_size: This function writes the size of the parsed
348  *                        contents into this memory location; zero on
349  *                        error
350  * @packet_size: This function writes the size of the parsed packet
351  *               into this memory location; zero on error
352  * @max_packet_size: maximum number of bytes to parse
353  *
354  * Returns zero on success; non-zero on error.
355  */
356 static int
357 parse_tag_11_packet(unsigned char *data, unsigned char *contents,
358                     size_t max_contents_bytes, size_t *tag_11_contents_size,
359                     size_t *packet_size, size_t max_packet_size)
360 {
361         int rc = 0;
362         size_t body_size;
363         size_t length_size;
364
365         (*packet_size) = 0;
366         (*tag_11_contents_size) = 0;
367
368         /* check that:
369          *   one byte for the Tag 11 ID flag
370          *   two bytes for the Tag 11 length
371          * do not exceed the maximum_packet_size
372          */
373         if (unlikely((*packet_size) + 3 > max_packet_size)) {
374                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
375                 rc = -EINVAL;
376                 goto out;
377         }
378
379         /* check for Tag 11 identifyer - one byte */
380         if (data[(*packet_size)++] != ECRYPTFS_TAG_11_PACKET_TYPE) {
381                 ecryptfs_printk(KERN_WARNING,
382                                 "Invalid tag 11 packet format\n");
383                 rc = -EINVAL;
384                 goto out;
385         }
386
387         /* get Tag 11 content length - one or two bytes */
388         rc = parse_packet_length(&data[(*packet_size)], &body_size,
389                                  &length_size);
390         if (rc) {
391                 ecryptfs_printk(KERN_WARNING,
392                                 "Invalid tag 11 packet format\n");
393                 goto out;
394         }
395         (*packet_size) += length_size;
396
397         if (body_size < 13) {
398                 ecryptfs_printk(KERN_WARNING, "Invalid body size ([%d])\n",
399                                 body_size);
400                 rc = -EINVAL;
401                 goto out;
402         }
403         /* We have 13 bytes of surrounding packet values */
404         (*tag_11_contents_size) = (body_size - 13);
405
406         /* now we know the length of the remainting Tag 11 packet size:
407          *   14 fix bytes for: special flag one, special flag two,
408          *                     12 skipped bytes
409          *   body_size bytes minus the stuff above is the Tag 11 content
410          */
411         /* FIXME why is the body size one byte smaller than the actual
412          * size of the body?
413          * this seems to be an error here as well as in
414          * write_tag_11_packet() */
415         if (unlikely((*packet_size) + body_size + 1 > max_packet_size)) {
416                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
417                 rc = -EINVAL;
418                 goto out;
419         }
420
421         /* special flag one - one byte */
422         if (data[(*packet_size)++] != 0x62) {
423                 ecryptfs_printk(KERN_WARNING, "Unrecognizable packet\n");
424                 rc = -EINVAL;
425                 goto out;
426         }
427
428         /* special flag two - one byte */
429         if (data[(*packet_size)++] != 0x08) {
430                 ecryptfs_printk(KERN_WARNING, "Unrecognizable packet\n");
431                 rc = -EINVAL;
432                 goto out;
433         }
434
435         /* skip the next 12 bytes */
436         (*packet_size) += 12; /* We don't care about the filename or
437                                * the timestamp */
438
439         /* get the Tag 11 contents - tag_11_contents_size bytes */
440         memcpy(contents, &data[(*packet_size)], (*tag_11_contents_size));
441         (*packet_size) += (*tag_11_contents_size);
442
443 out:
444         if (rc) {
445                 (*packet_size) = 0;
446                 (*tag_11_contents_size) = 0;
447         }
448         return rc;
449 }
450
451 /**
452  * decrypt_session_key - Decrypt the session key with the given auth_tok.
453  *
454  * Returns Zero on success; non-zero error otherwise.
455  */
456 static int decrypt_session_key(struct ecryptfs_auth_tok *auth_tok,
457                                struct ecryptfs_crypt_stat *crypt_stat)
458 {
459         struct ecryptfs_password *password_s_ptr;
460         struct scatterlist src_sg[2], dst_sg[2];
461         struct mutex *tfm_mutex = NULL;
462         /* TODO: Use virt_to_scatterlist for these */
463         char *encrypted_session_key;
464         char *session_key;
465         struct blkcipher_desc desc = {
466                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
467         };
468         int rc = 0;
469
470         password_s_ptr = &auth_tok->token.password;
471         if (ECRYPTFS_CHECK_FLAG(password_s_ptr->flags,
472                                 ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET))
473                 ecryptfs_printk(KERN_DEBUG, "Session key encryption key "
474                                 "set; skipping key generation\n");
475         ecryptfs_printk(KERN_DEBUG, "Session key encryption key (size [%d])"
476                         ":\n",
477                         password_s_ptr->session_key_encryption_key_bytes);
478         if (ecryptfs_verbosity > 0)
479                 ecryptfs_dump_hex(password_s_ptr->session_key_encryption_key,
480                                   password_s_ptr->
481                                   session_key_encryption_key_bytes);
482         if (!strcmp(crypt_stat->cipher,
483                     crypt_stat->mount_crypt_stat->global_default_cipher_name)
484             && crypt_stat->mount_crypt_stat->global_key_tfm) {
485                 desc.tfm = crypt_stat->mount_crypt_stat->global_key_tfm;
486                 tfm_mutex = &crypt_stat->mount_crypt_stat->global_key_tfm_mutex;
487         } else {
488                 char *full_alg_name;
489
490                 rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name,
491                                                             crypt_stat->cipher,
492                                                             "ecb");
493                 if (rc)
494                         goto out;
495                 desc.tfm = crypto_alloc_blkcipher(full_alg_name, 0,
496                                                   CRYPTO_ALG_ASYNC);
497                 kfree(full_alg_name);
498                 if (IS_ERR(desc.tfm)) {
499                         rc = PTR_ERR(desc.tfm);
500                         printk(KERN_ERR "Error allocating crypto context; "
501                                "rc = [%d]\n", rc);
502                         goto out;
503                 }
504                 crypto_blkcipher_set_flags(desc.tfm, CRYPTO_TFM_REQ_WEAK_KEY);
505         }
506         if (tfm_mutex)
507                 mutex_lock(tfm_mutex);
508         rc = crypto_blkcipher_setkey(desc.tfm,
509                                      password_s_ptr->session_key_encryption_key,
510                                      crypt_stat->key_size);
511         if (rc < 0) {
512                 printk(KERN_ERR "Error setting key for crypto context\n");
513                 rc = -EINVAL;
514                 goto out_free_tfm;
515         }
516         /* TODO: virt_to_scatterlist */
517         encrypted_session_key = (char *)__get_free_page(GFP_KERNEL);
518         if (!encrypted_session_key) {
519                 ecryptfs_printk(KERN_ERR, "Out of memory\n");
520                 rc = -ENOMEM;
521                 goto out_free_tfm;
522         }
523         session_key = (char *)__get_free_page(GFP_KERNEL);
524         if (!session_key) {
525                 kfree(encrypted_session_key);
526                 ecryptfs_printk(KERN_ERR, "Out of memory\n");
527                 rc = -ENOMEM;
528                 goto out_free_tfm;
529         }
530         memcpy(encrypted_session_key, auth_tok->session_key.encrypted_key,
531                auth_tok->session_key.encrypted_key_size);
532         src_sg[0].page = virt_to_page(encrypted_session_key);
533         src_sg[0].offset = 0;
534         BUG_ON(auth_tok->session_key.encrypted_key_size > PAGE_CACHE_SIZE);
535         src_sg[0].length = auth_tok->session_key.encrypted_key_size;
536         dst_sg[0].page = virt_to_page(session_key);
537         dst_sg[0].offset = 0;
538         auth_tok->session_key.decrypted_key_size =
539             auth_tok->session_key.encrypted_key_size;
540         dst_sg[0].length = auth_tok->session_key.encrypted_key_size;
541         rc = crypto_blkcipher_decrypt(&desc, dst_sg, src_sg,
542                                       auth_tok->session_key.encrypted_key_size);
543         if (rc) {
544                 printk(KERN_ERR "Error decrypting; rc = [%d]\n", rc);
545                 goto out_free_memory;
546         }
547         auth_tok->session_key.decrypted_key_size =
548             auth_tok->session_key.encrypted_key_size;
549         memcpy(auth_tok->session_key.decrypted_key, session_key,
550                auth_tok->session_key.decrypted_key_size);
551         auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
552         memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
553                auth_tok->session_key.decrypted_key_size);
554         ECRYPTFS_SET_FLAG(crypt_stat->flags, ECRYPTFS_KEY_VALID);
555         ecryptfs_printk(KERN_DEBUG, "Decrypted session key:\n");
556         if (ecryptfs_verbosity > 0)
557                 ecryptfs_dump_hex(crypt_stat->key,
558                                   crypt_stat->key_size);
559 out_free_memory:
560         memset(encrypted_session_key, 0, PAGE_CACHE_SIZE);
561         free_page((unsigned long)encrypted_session_key);
562         memset(session_key, 0, PAGE_CACHE_SIZE);
563         free_page((unsigned long)session_key);
564 out_free_tfm:
565         if (tfm_mutex)
566                 mutex_unlock(tfm_mutex);
567         else
568                 crypto_free_blkcipher(desc.tfm);
569 out:
570         return rc;
571 }
572
573 /**
574  * ecryptfs_parse_packet_set
575  * @dest: The header page in memory
576  * @version: Version of file format, to guide parsing behavior
577  *
578  * Get crypt_stat to have the file's session key if the requisite key
579  * is available to decrypt the session key.
580  *
581  * Returns Zero if a valid authentication token was retrieved and
582  * processed; negative value for file not encrypted or for error
583  * conditions.
584  */
585 int ecryptfs_parse_packet_set(struct ecryptfs_crypt_stat *crypt_stat,
586                               unsigned char *src,
587                               struct dentry *ecryptfs_dentry)
588 {
589         size_t i = 0;
590         int rc = 0;
591         size_t found_auth_tok = 0;
592         size_t next_packet_is_auth_tok_packet;
593         char sig[ECRYPTFS_SIG_SIZE_HEX];
594         struct list_head auth_tok_list;
595         struct list_head *walker;
596         struct ecryptfs_auth_tok *chosen_auth_tok = NULL;
597         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
598                 &ecryptfs_superblock_to_private(
599                         ecryptfs_dentry->d_sb)->mount_crypt_stat;
600         struct ecryptfs_auth_tok *candidate_auth_tok = NULL;
601         size_t packet_size;
602         struct ecryptfs_auth_tok *new_auth_tok;
603         unsigned char sig_tmp_space[ECRYPTFS_SIG_SIZE];
604         size_t tag_11_contents_size;
605         size_t tag_11_packet_size;
606
607         INIT_LIST_HEAD(&auth_tok_list);
608         /* Parse the header to find as many packets as we can, these will be
609          * added the our &auth_tok_list */
610         next_packet_is_auth_tok_packet = 1;
611         while (next_packet_is_auth_tok_packet) {
612                 size_t max_packet_size = ((PAGE_CACHE_SIZE - 8) - i);
613
614                 switch (src[i]) {
615                 case ECRYPTFS_TAG_3_PACKET_TYPE:
616                         rc = parse_tag_3_packet(crypt_stat,
617                                                 (unsigned char *)&src[i],
618                                                 &auth_tok_list, &new_auth_tok,
619                                                 &packet_size, max_packet_size);
620                         if (rc) {
621                                 ecryptfs_printk(KERN_ERR, "Error parsing "
622                                                 "tag 3 packet\n");
623                                 rc = -EIO;
624                                 goto out_wipe_list;
625                         }
626                         i += packet_size;
627                         rc = parse_tag_11_packet((unsigned char *)&src[i],
628                                                  sig_tmp_space,
629                                                  ECRYPTFS_SIG_SIZE,
630                                                  &tag_11_contents_size,
631                                                  &tag_11_packet_size,
632                                                  max_packet_size);
633                         if (rc) {
634                                 ecryptfs_printk(KERN_ERR, "No valid "
635                                                 "(ecryptfs-specific) literal "
636                                                 "packet containing "
637                                                 "authentication token "
638                                                 "signature found after "
639                                                 "tag 3 packet\n");
640                                 rc = -EIO;
641                                 goto out_wipe_list;
642                         }
643                         i += tag_11_packet_size;
644                         if (ECRYPTFS_SIG_SIZE != tag_11_contents_size) {
645                                 ecryptfs_printk(KERN_ERR, "Expected "
646                                                 "signature of size [%d]; "
647                                                 "read size [%d]\n",
648                                                 ECRYPTFS_SIG_SIZE,
649                                                 tag_11_contents_size);
650                                 rc = -EIO;
651                                 goto out_wipe_list;
652                         }
653                         ecryptfs_to_hex(new_auth_tok->token.password.signature,
654                                         sig_tmp_space, tag_11_contents_size);
655                         new_auth_tok->token.password.signature[
656                                 ECRYPTFS_PASSWORD_SIG_SIZE] = '\0';
657                         ECRYPTFS_SET_FLAG(crypt_stat->flags,
658                                           ECRYPTFS_ENCRYPTED);
659                         break;
660                 case ECRYPTFS_TAG_11_PACKET_TYPE:
661                         ecryptfs_printk(KERN_WARNING, "Invalid packet set "
662                                         "(Tag 11 not allowed by itself)\n");
663                         rc = -EIO;
664                         goto out_wipe_list;
665                         break;
666                 default:
667                         ecryptfs_printk(KERN_DEBUG, "No packet at offset "
668                                         "[%d] of the file header; hex value of "
669                                         "character is [0x%.2x]\n", i, src[i]);
670                         next_packet_is_auth_tok_packet = 0;
671                 }
672         }
673         if (list_empty(&auth_tok_list)) {
674                 rc = -EINVAL; /* Do not support non-encrypted files in
675                                * the 0.1 release */
676                 goto out;
677         }
678         /* If we have a global auth tok, then we should try to use
679          * it */
680         if (mount_crypt_stat->global_auth_tok) {
681                 memcpy(sig, mount_crypt_stat->global_auth_tok_sig,
682                        ECRYPTFS_SIG_SIZE_HEX);
683                 chosen_auth_tok = mount_crypt_stat->global_auth_tok;
684         } else
685                 BUG(); /* We should always have a global auth tok in
686                         * the 0.1 release */
687         /* Scan list to see if our chosen_auth_tok works */
688         list_for_each(walker, &auth_tok_list) {
689                 struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
690                 auth_tok_list_item =
691                     list_entry(walker, struct ecryptfs_auth_tok_list_item,
692                                list);
693                 candidate_auth_tok = &auth_tok_list_item->auth_tok;
694                 if (unlikely(ecryptfs_verbosity > 0)) {
695                         ecryptfs_printk(KERN_DEBUG,
696                                         "Considering cadidate auth tok:\n");
697                         ecryptfs_dump_auth_tok(candidate_auth_tok);
698                 }
699                 /* TODO: Replace ECRYPTFS_SIG_SIZE_HEX w/ dynamic value */
700                 if (candidate_auth_tok->token_type == ECRYPTFS_PASSWORD
701                     && !strncmp(candidate_auth_tok->token.password.signature,
702                                 sig, ECRYPTFS_SIG_SIZE_HEX)) {
703                         found_auth_tok = 1;
704                         goto leave_list;
705                         /* TODO: Transfer the common salt into the
706                          * crypt_stat salt */
707                 }
708         }
709 leave_list:
710         if (!found_auth_tok) {
711                 ecryptfs_printk(KERN_ERR, "Could not find authentication "
712                                 "token on temporary list for sig [%.*s]\n",
713                                 ECRYPTFS_SIG_SIZE_HEX, sig);
714                 rc = -EIO;
715                 goto out_wipe_list;
716         } else {
717                 memcpy(&(candidate_auth_tok->token.password),
718                        &(chosen_auth_tok->token.password),
719                        sizeof(struct ecryptfs_password));
720                 rc = decrypt_session_key(candidate_auth_tok, crypt_stat);
721                 if (rc) {
722                         ecryptfs_printk(KERN_ERR, "Error decrypting the "
723                                         "session key\n");
724                         goto out_wipe_list;
725                 }
726                 rc = ecryptfs_compute_root_iv(crypt_stat);
727                 if (rc) {
728                         ecryptfs_printk(KERN_ERR, "Error computing "
729                                         "the root IV\n");
730                         goto out_wipe_list;
731                 }
732         }
733         rc = ecryptfs_init_crypt_ctx(crypt_stat);
734         if (rc) {
735                 ecryptfs_printk(KERN_ERR, "Error initializing crypto "
736                                 "context for cipher [%s]; rc = [%d]\n",
737                                 crypt_stat->cipher, rc);
738         }
739 out_wipe_list:
740         wipe_auth_tok_list(&auth_tok_list);
741 out:
742         return rc;
743 }
744
745 /**
746  * write_tag_11_packet
747  * @dest: Target into which Tag 11 packet is to be written
748  * @max: Maximum packet length
749  * @contents: Byte array of contents to copy in
750  * @contents_length: Number of bytes in contents
751  * @packet_length: Length of the Tag 11 packet written; zero on error
752  *
753  * Returns zero on success; non-zero on error.
754  */
755 static int
756 write_tag_11_packet(char *dest, int max, char *contents, size_t contents_length,
757                     size_t *packet_length)
758 {
759         int rc = 0;
760         size_t packet_size_length;
761
762         (*packet_length) = 0;
763         if ((13 + contents_length) > max) {
764                 rc = -EINVAL;
765                 ecryptfs_printk(KERN_ERR, "Packet length larger than "
766                                 "maximum allowable\n");
767                 goto out;
768         }
769         /* General packet header */
770         /* Packet tag */
771         dest[(*packet_length)++] = ECRYPTFS_TAG_11_PACKET_TYPE;
772         /* Packet length */
773         rc = write_packet_length(&dest[(*packet_length)],
774                                  (13 + contents_length), &packet_size_length);
775         if (rc) {
776                 ecryptfs_printk(KERN_ERR, "Error generating tag 11 packet "
777                                 "header; cannot generate packet length\n");
778                 goto out;
779         }
780         (*packet_length) += packet_size_length;
781         /* Tag 11 specific */
782         /* One-octet field that describes how the data is formatted */
783         dest[(*packet_length)++] = 0x62; /* binary data */
784         /* One-octet filename length followed by filename */
785         dest[(*packet_length)++] = 8;
786         memcpy(&dest[(*packet_length)], "_CONSOLE", 8);
787         (*packet_length) += 8;
788         /* Four-octet number indicating modification date */
789         memset(&dest[(*packet_length)], 0x00, 4);
790         (*packet_length) += 4;
791         /* Remainder is literal data */
792         memcpy(&dest[(*packet_length)], contents, contents_length);
793         (*packet_length) += contents_length;
794  out:
795         if (rc)
796                 (*packet_length) = 0;
797         return rc;
798 }
799
800 /**
801  * write_tag_3_packet
802  * @dest: Buffer into which to write the packet
803  * @max: Maximum number of bytes that can be written
804  * @auth_tok: Authentication token
805  * @crypt_stat: The cryptographic context
806  * @key_rec: encrypted key
807  * @packet_size: This function will write the number of bytes that end
808  *               up constituting the packet; set to zero on error
809  *
810  * Returns zero on success; non-zero on error.
811  */
812 static int
813 write_tag_3_packet(char *dest, size_t max, struct ecryptfs_auth_tok *auth_tok,
814                    struct ecryptfs_crypt_stat *crypt_stat,
815                    struct ecryptfs_key_record *key_rec, size_t *packet_size)
816 {
817         size_t i;
818         size_t signature_is_valid = 0;
819         size_t encrypted_session_key_valid = 0;
820         char session_key_encryption_key[ECRYPTFS_MAX_KEY_BYTES];
821         struct scatterlist dest_sg[2];
822         struct scatterlist src_sg[2];
823         struct mutex *tfm_mutex = NULL;
824         size_t key_rec_size;
825         size_t packet_size_length;
826         size_t cipher_code;
827         struct blkcipher_desc desc = {
828                 .tfm = NULL,
829                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
830         };
831         int rc = 0;
832
833         (*packet_size) = 0;
834         /* Check for a valid signature on the auth_tok */
835         for (i = 0; i < ECRYPTFS_SIG_SIZE_HEX; i++)
836                 signature_is_valid |= auth_tok->token.password.signature[i];
837         if (!signature_is_valid)
838                 BUG();
839         ecryptfs_from_hex((*key_rec).sig, auth_tok->token.password.signature,
840                           ECRYPTFS_SIG_SIZE);
841         encrypted_session_key_valid = 0;
842         for (i = 0; i < crypt_stat->key_size; i++)
843                 encrypted_session_key_valid |=
844                         auth_tok->session_key.encrypted_key[i];
845         if (encrypted_session_key_valid) {
846                 memcpy((*key_rec).enc_key,
847                        auth_tok->session_key.encrypted_key,
848                        auth_tok->session_key.encrypted_key_size);
849                 goto encrypted_session_key_set;
850         }
851         if (auth_tok->session_key.encrypted_key_size == 0)
852                 auth_tok->session_key.encrypted_key_size =
853                         crypt_stat->key_size;
854         if (crypt_stat->key_size == 24
855             && strcmp("aes", crypt_stat->cipher) == 0) {
856                 memset((crypt_stat->key + 24), 0, 8);
857                 auth_tok->session_key.encrypted_key_size = 32;
858         }
859         (*key_rec).enc_key_size =
860                 auth_tok->session_key.encrypted_key_size;
861         if (ECRYPTFS_CHECK_FLAG(auth_tok->token.password.flags,
862                                 ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET)) {
863                 ecryptfs_printk(KERN_DEBUG, "Using previously generated "
864                                 "session key encryption key of size [%d]\n",
865                                 auth_tok->token.password.
866                                 session_key_encryption_key_bytes);
867                 memcpy(session_key_encryption_key,
868                        auth_tok->token.password.session_key_encryption_key,
869                        crypt_stat->key_size);
870                 ecryptfs_printk(KERN_DEBUG,
871                                 "Cached session key " "encryption key: \n");
872                 if (ecryptfs_verbosity > 0)
873                         ecryptfs_dump_hex(session_key_encryption_key, 16);
874         }
875         if (unlikely(ecryptfs_verbosity > 0)) {
876                 ecryptfs_printk(KERN_DEBUG, "Session key encryption key:\n");
877                 ecryptfs_dump_hex(session_key_encryption_key, 16);
878         }
879         rc = virt_to_scatterlist(crypt_stat->key,
880                                  (*key_rec).enc_key_size, src_sg, 2);
881         if (!rc) {
882                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
883                                 "for crypt_stat session key\n");
884                 rc = -ENOMEM;
885                 goto out;
886         }
887         rc = virt_to_scatterlist((*key_rec).enc_key,
888                                  (*key_rec).enc_key_size, dest_sg, 2);
889         if (!rc) {
890                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
891                                 "for crypt_stat encrypted session key\n");
892                 rc = -ENOMEM;
893                 goto out;
894         }
895         if (!strcmp(crypt_stat->cipher,
896                     crypt_stat->mount_crypt_stat->global_default_cipher_name)
897             && crypt_stat->mount_crypt_stat->global_key_tfm) {
898                 desc.tfm = crypt_stat->mount_crypt_stat->global_key_tfm;
899                 tfm_mutex = &crypt_stat->mount_crypt_stat->global_key_tfm_mutex;
900         } else {
901                 char *full_alg_name;
902
903                 rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name,
904                                                             crypt_stat->cipher,
905                                                             "ecb");
906                 if (rc)
907                         goto out;
908                 desc.tfm = crypto_alloc_blkcipher(full_alg_name, 0,
909                                                   CRYPTO_ALG_ASYNC);
910                 kfree(full_alg_name);
911                 if (IS_ERR(desc.tfm)) {
912                         rc = PTR_ERR(desc.tfm);
913                         ecryptfs_printk(KERN_ERR, "Could not initialize crypto "
914                                         "context for cipher [%s]; rc = [%d]\n",
915                                         crypt_stat->cipher, rc);
916                         goto out;
917                 }
918                 crypto_blkcipher_set_flags(desc.tfm, CRYPTO_TFM_REQ_WEAK_KEY);
919         }
920         if (tfm_mutex)
921                 mutex_lock(tfm_mutex);
922         rc = crypto_blkcipher_setkey(desc.tfm, session_key_encryption_key,
923                                      crypt_stat->key_size);
924         if (rc < 0) {
925                 if (tfm_mutex)
926                         mutex_unlock(tfm_mutex);
927                 ecryptfs_printk(KERN_ERR, "Error setting key for crypto "
928                                 "context; rc = [%d]\n", rc);
929                 goto out;
930         }
931         rc = 0;
932         ecryptfs_printk(KERN_DEBUG, "Encrypting [%d] bytes of the key\n",
933                         crypt_stat->key_size);
934         rc = crypto_blkcipher_encrypt(&desc, dest_sg, src_sg,
935                                       (*key_rec).enc_key_size);
936         if (rc) {
937                 printk(KERN_ERR "Error encrypting; rc = [%d]\n", rc);
938                 goto out;
939         }
940         if (tfm_mutex)
941                 mutex_unlock(tfm_mutex);
942         ecryptfs_printk(KERN_DEBUG, "This should be the encrypted key:\n");
943         if (ecryptfs_verbosity > 0)
944                 ecryptfs_dump_hex((*key_rec).enc_key,
945                                   (*key_rec).enc_key_size);
946 encrypted_session_key_set:
947         /* Now we have a valid key_rec.  Append it to the
948          * key_rec set. */
949         key_rec_size = (sizeof(struct ecryptfs_key_record)
950                         - ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES
951                         + ((*key_rec).enc_key_size));
952         /* TODO: Include a packet size limit as a parameter to this
953          * function once we have multi-packet headers (for versions
954          * later than 0.1 */
955         if (key_rec_size >= ECRYPTFS_MAX_KEYSET_SIZE) {
956                 ecryptfs_printk(KERN_ERR, "Keyset too large\n");
957                 rc = -EINVAL;
958                 goto out;
959         }
960         /* TODO: Packet size limit */
961         /* We have 5 bytes of surrounding packet data */
962         if ((0x05 + ECRYPTFS_SALT_SIZE
963              + (*key_rec).enc_key_size) >= max) {
964                 ecryptfs_printk(KERN_ERR, "Authentication token is too "
965                                 "large\n");
966                 rc = -EINVAL;
967                 goto out;
968         }
969         /* This format is inspired by OpenPGP; see RFC 2440
970          * packet tag 3 */
971         dest[(*packet_size)++] = ECRYPTFS_TAG_3_PACKET_TYPE;
972         /* ver+cipher+s2k+hash+salt+iter+enc_key */
973         rc = write_packet_length(&dest[(*packet_size)],
974                                  (0x05 + ECRYPTFS_SALT_SIZE
975                                   + (*key_rec).enc_key_size),
976                                  &packet_size_length);
977         if (rc) {
978                 ecryptfs_printk(KERN_ERR, "Error generating tag 3 packet "
979                                 "header; cannot generate packet length\n");
980                 goto out;
981         }
982         (*packet_size) += packet_size_length;
983         dest[(*packet_size)++] = 0x04; /* version 4 */
984         cipher_code = ecryptfs_code_for_cipher_string(crypt_stat);
985         if (cipher_code == 0) {
986                 ecryptfs_printk(KERN_WARNING, "Unable to generate code for "
987                                 "cipher [%s]\n", crypt_stat->cipher);
988                 rc = -EINVAL;
989                 goto out;
990         }
991         dest[(*packet_size)++] = cipher_code;
992         dest[(*packet_size)++] = 0x03;  /* S2K */
993         dest[(*packet_size)++] = 0x01;  /* MD5 (TODO: parameterize) */
994         memcpy(&dest[(*packet_size)], auth_tok->token.password.salt,
995                ECRYPTFS_SALT_SIZE);
996         (*packet_size) += ECRYPTFS_SALT_SIZE;   /* salt */
997         dest[(*packet_size)++] = 0x60;  /* hash iterations (65536) */
998         memcpy(&dest[(*packet_size)], (*key_rec).enc_key,
999                (*key_rec).enc_key_size);
1000         (*packet_size) += (*key_rec).enc_key_size;
1001 out:
1002         if (desc.tfm && !tfm_mutex)
1003                 crypto_free_blkcipher(desc.tfm);
1004         if (rc)
1005                 (*packet_size) = 0;
1006         return rc;
1007 }
1008
1009 /**
1010  * ecryptfs_generate_key_packet_set
1011  * @dest: Virtual address from which to write the key record set
1012  * @crypt_stat: The cryptographic context from which the
1013  *              authentication tokens will be retrieved
1014  * @ecryptfs_dentry: The dentry, used to retrieve the mount crypt stat
1015  *                   for the global parameters
1016  * @len: The amount written
1017  * @max: The maximum amount of data allowed to be written
1018  *
1019  * Generates a key packet set and writes it to the virtual address
1020  * passed in.
1021  *
1022  * Returns zero on success; non-zero on error.
1023  */
1024 int
1025 ecryptfs_generate_key_packet_set(char *dest_base,
1026                                  struct ecryptfs_crypt_stat *crypt_stat,
1027                                  struct dentry *ecryptfs_dentry, size_t *len,
1028                                  size_t max)
1029 {
1030         int rc = 0;
1031         struct ecryptfs_auth_tok *auth_tok;
1032         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1033                 &ecryptfs_superblock_to_private(
1034                         ecryptfs_dentry->d_sb)->mount_crypt_stat;
1035         size_t written;
1036         struct ecryptfs_key_record key_rec;
1037
1038         (*len) = 0;
1039         if (mount_crypt_stat->global_auth_tok) {
1040                 auth_tok = mount_crypt_stat->global_auth_tok;
1041                 if (auth_tok->token_type == ECRYPTFS_PASSWORD) {
1042                         rc = write_tag_3_packet((dest_base + (*len)),
1043                                                 max, auth_tok,
1044                                                 crypt_stat, &key_rec,
1045                                                 &written);
1046                         if (rc) {
1047                                 ecryptfs_printk(KERN_WARNING, "Error "
1048                                                 "writing tag 3 packet\n");
1049                                 goto out;
1050                         }
1051                         (*len) += written;
1052                         /* Write auth tok signature packet */
1053                         rc = write_tag_11_packet(
1054                                 (dest_base + (*len)),
1055                                 (max - (*len)),
1056                                 key_rec.sig, ECRYPTFS_SIG_SIZE, &written);
1057                         if (rc) {
1058                                 ecryptfs_printk(KERN_ERR, "Error writing "
1059                                                 "auth tok signature packet\n");
1060                                 goto out;
1061                         }
1062                         (*len) += written;
1063                 } else {
1064                         ecryptfs_printk(KERN_WARNING, "Unsupported "
1065                                         "authentication token type\n");
1066                         rc = -EINVAL;
1067                         goto out;
1068                 }
1069                 if (rc) {
1070                         ecryptfs_printk(KERN_WARNING, "Error writing "
1071                                         "authentication token packet with sig "
1072                                         "= [%s]\n",
1073                                         mount_crypt_stat->global_auth_tok_sig);
1074                         rc = -EIO;
1075                         goto out;
1076                 }
1077         } else
1078                 BUG();
1079         if (likely((max - (*len)) > 0)) {
1080                 dest_base[(*len)] = 0x00;
1081         } else {
1082                 ecryptfs_printk(KERN_ERR, "Error writing boundary byte\n");
1083                 rc = -EIO;
1084         }
1085 out:
1086         if (rc)
1087                 (*len) = 0;
1088         return rc;
1089 }