bc706d33559a3e80cdf52c7144d72675c416197b
[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_alloc(ecryptfs_auth_tok_list_item_cache, SLAB_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         memset(auth_tok_list_item, 0,
217                sizeof(struct ecryptfs_auth_tok_list_item));
218         (*new_auth_tok) = &auth_tok_list_item->auth_tok;
219
220         /* check for body size - one to two bytes */
221         rc = parse_packet_length(&data[(*packet_size)], &body_size,
222                                  &length_size);
223         if (rc) {
224                 ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
225                                 "rc = [%d]\n", rc);
226                 goto out_free;
227         }
228         if (unlikely(body_size < (0x05 + ECRYPTFS_SALT_SIZE))) {
229                 ecryptfs_printk(KERN_WARNING, "Invalid body size ([%d])\n",
230                                 body_size);
231                 rc = -EINVAL;
232                 goto out_free;
233         }
234         (*packet_size) += length_size;
235
236         /* now we know the length of the remainting Tag 3 packet size:
237          *   5 fix bytes for: version string, cipher, S2K ID, hash algo,
238          *                    number of hash iterations
239          *   ECRYPTFS_SALT_SIZE bytes for salt
240          *   body_size bytes minus the stuff above is the encrypted key size
241          */
242         if (unlikely((*packet_size) + body_size > max_packet_size)) {
243                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
244                 rc = -EINVAL;
245                 goto out_free;
246         }
247
248         /* There are 5 characters of additional information in the
249          * packet */
250         (*new_auth_tok)->session_key.encrypted_key_size =
251                 body_size - (0x05 + ECRYPTFS_SALT_SIZE);
252         ecryptfs_printk(KERN_DEBUG, "Encrypted key size = [%d]\n",
253                         (*new_auth_tok)->session_key.encrypted_key_size);
254
255         /* Version 4 (from RFC2440) - one byte */
256         if (unlikely(data[(*packet_size)++] != 0x04)) {
257                 ecryptfs_printk(KERN_DEBUG, "Unknown version number "
258                                 "[%d]\n", data[(*packet_size) - 1]);
259                 rc = -EINVAL;
260                 goto out_free;
261         }
262
263         /* cipher - one byte */
264         ecryptfs_cipher_code_to_string(crypt_stat->cipher,
265                                        (u16)data[(*packet_size)]);
266         /* A little extra work to differentiate among the AES key
267          * sizes; see RFC2440 */
268         switch(data[(*packet_size)++]) {
269         case RFC2440_CIPHER_AES_192:
270                 crypt_stat->key_size = 24;
271                 break;
272         default:
273                 crypt_stat->key_size =
274                         (*new_auth_tok)->session_key.encrypted_key_size;
275         }
276         ecryptfs_init_crypt_ctx(crypt_stat);
277         /* S2K identifier 3 (from RFC2440) */
278         if (unlikely(data[(*packet_size)++] != 0x03)) {
279                 ecryptfs_printk(KERN_ERR, "Only S2K ID 3 is currently "
280                                 "supported\n");
281                 rc = -ENOSYS;
282                 goto out_free;
283         }
284
285         /* TODO: finish the hash mapping */
286         /* hash algorithm - one byte */
287         switch (data[(*packet_size)++]) {
288         case 0x01: /* See RFC2440 for these numbers and their mappings */
289                 /* Choose MD5 */
290                 /* salt - ECRYPTFS_SALT_SIZE bytes */
291                 memcpy((*new_auth_tok)->token.password.salt,
292                        &data[(*packet_size)], ECRYPTFS_SALT_SIZE);
293                 (*packet_size) += ECRYPTFS_SALT_SIZE;
294
295                 /* This conversion was taken straight from RFC2440 */
296                 /* number of hash iterations - one byte */
297                 (*new_auth_tok)->token.password.hash_iterations =
298                         ((u32) 16 + (data[(*packet_size)] & 15))
299                                 << ((data[(*packet_size)] >> 4) + 6);
300                 (*packet_size)++;
301
302                 /* encrypted session key -
303                  *   (body_size-5-ECRYPTFS_SALT_SIZE) bytes */
304                 memcpy((*new_auth_tok)->session_key.encrypted_key,
305                        &data[(*packet_size)],
306                        (*new_auth_tok)->session_key.encrypted_key_size);
307                 (*packet_size) +=
308                         (*new_auth_tok)->session_key.encrypted_key_size;
309                 (*new_auth_tok)->session_key.flags &=
310                         ~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
311                 (*new_auth_tok)->session_key.flags |=
312                         ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
313                 (*new_auth_tok)->token.password.hash_algo = 0x01;
314                 break;
315         default:
316                 ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: "
317                                 "[%d]\n", data[(*packet_size) - 1]);
318                 rc = -ENOSYS;
319                 goto out_free;
320         }
321         (*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;
322         /* TODO: Parametarize; we might actually want userspace to
323          * decrypt the session key. */
324         ECRYPTFS_CLEAR_FLAG((*new_auth_tok)->session_key.flags,
325                             ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
326         ECRYPTFS_CLEAR_FLAG((*new_auth_tok)->session_key.flags,
327                             ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
328         list_add(&auth_tok_list_item->list, auth_tok_list);
329         goto out;
330 out_free:
331         (*new_auth_tok) = NULL;
332         memset(auth_tok_list_item, 0,
333                sizeof(struct ecryptfs_auth_tok_list_item));
334         kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
335                         auth_tok_list_item);
336 out:
337         if (rc)
338                 (*packet_size) = 0;
339         return rc;
340 }
341
342 /**
343  * parse_tag_11_packet
344  * @data: The raw bytes of the packet
345  * @contents: This function writes the data contents of the literal
346  *            packet into this memory location
347  * @max_contents_bytes: The maximum number of bytes that this function
348  *                      is allowed to write into contents
349  * @tag_11_contents_size: This function writes the size of the parsed
350  *                        contents into this memory location; zero on
351  *                        error
352  * @packet_size: This function writes the size of the parsed packet
353  *               into this memory location; zero on error
354  * @max_packet_size: maximum number of bytes to parse
355  *
356  * Returns zero on success; non-zero on error.
357  */
358 static int
359 parse_tag_11_packet(unsigned char *data, unsigned char *contents,
360                     size_t max_contents_bytes, size_t *tag_11_contents_size,
361                     size_t *packet_size, size_t max_packet_size)
362 {
363         int rc = 0;
364         size_t body_size;
365         size_t length_size;
366
367         (*packet_size) = 0;
368         (*tag_11_contents_size) = 0;
369
370         /* check that:
371          *   one byte for the Tag 11 ID flag
372          *   two bytes for the Tag 11 length
373          * do not exceed the maximum_packet_size
374          */
375         if (unlikely((*packet_size) + 3 > max_packet_size)) {
376                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
377                 rc = -EINVAL;
378                 goto out;
379         }
380
381         /* check for Tag 11 identifyer - one byte */
382         if (data[(*packet_size)++] != ECRYPTFS_TAG_11_PACKET_TYPE) {
383                 ecryptfs_printk(KERN_WARNING,
384                                 "Invalid tag 11 packet format\n");
385                 rc = -EINVAL;
386                 goto out;
387         }
388
389         /* get Tag 11 content length - one or two bytes */
390         rc = parse_packet_length(&data[(*packet_size)], &body_size,
391                                  &length_size);
392         if (rc) {
393                 ecryptfs_printk(KERN_WARNING,
394                                 "Invalid tag 11 packet format\n");
395                 goto out;
396         }
397         (*packet_size) += length_size;
398
399         if (body_size < 13) {
400                 ecryptfs_printk(KERN_WARNING, "Invalid body size ([%d])\n",
401                                 body_size);
402                 rc = -EINVAL;
403                 goto out;
404         }
405         /* We have 13 bytes of surrounding packet values */
406         (*tag_11_contents_size) = (body_size - 13);
407
408         /* now we know the length of the remainting Tag 11 packet size:
409          *   14 fix bytes for: special flag one, special flag two,
410          *                     12 skipped bytes
411          *   body_size bytes minus the stuff above is the Tag 11 content
412          */
413         /* FIXME why is the body size one byte smaller than the actual
414          * size of the body?
415          * this seems to be an error here as well as in
416          * write_tag_11_packet() */
417         if (unlikely((*packet_size) + body_size + 1 > max_packet_size)) {
418                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
419                 rc = -EINVAL;
420                 goto out;
421         }
422
423         /* special flag one - one byte */
424         if (data[(*packet_size)++] != 0x62) {
425                 ecryptfs_printk(KERN_WARNING, "Unrecognizable packet\n");
426                 rc = -EINVAL;
427                 goto out;
428         }
429
430         /* special flag two - one byte */
431         if (data[(*packet_size)++] != 0x08) {
432                 ecryptfs_printk(KERN_WARNING, "Unrecognizable packet\n");
433                 rc = -EINVAL;
434                 goto out;
435         }
436
437         /* skip the next 12 bytes */
438         (*packet_size) += 12; /* We don't care about the filename or
439                                * the timestamp */
440
441         /* get the Tag 11 contents - tag_11_contents_size bytes */
442         memcpy(contents, &data[(*packet_size)], (*tag_11_contents_size));
443         (*packet_size) += (*tag_11_contents_size);
444
445 out:
446         if (rc) {
447                 (*packet_size) = 0;
448                 (*tag_11_contents_size) = 0;
449         }
450         return rc;
451 }
452
453 /**
454  * decrypt_session_key - Decrypt the session key with the given auth_tok.
455  *
456  * Returns Zero on success; non-zero error otherwise.
457  */
458 static int decrypt_session_key(struct ecryptfs_auth_tok *auth_tok,
459                                struct ecryptfs_crypt_stat *crypt_stat)
460 {
461         int rc = 0;
462         struct ecryptfs_password *password_s_ptr;
463         struct crypto_tfm *tfm = NULL;
464         struct scatterlist src_sg[2], dst_sg[2];
465         struct mutex *tfm_mutex = NULL;
466         /* TODO: Use virt_to_scatterlist for these */
467         char *encrypted_session_key;
468         char *session_key;
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                 tfm = crypt_stat->mount_crypt_stat->global_key_tfm;
486                 tfm_mutex = &crypt_stat->mount_crypt_stat->global_key_tfm_mutex;
487         } else {
488                 tfm = crypto_alloc_tfm(crypt_stat->cipher,
489                                        CRYPTO_TFM_REQ_WEAK_KEY);
490                 if (!tfm) {
491                         printk(KERN_ERR "Error allocating crypto context\n");
492                         rc = -ENOMEM;
493                         goto out;
494                 }
495         }
496         if (tfm_mutex)
497                 mutex_lock(tfm_mutex);
498         rc = crypto_cipher_setkey(tfm,
499                                   password_s_ptr->session_key_encryption_key,
500                                   crypt_stat->key_size);
501         if (rc < 0) {
502                 printk(KERN_ERR "Error setting key for crypto context\n");
503                 rc = -EINVAL;
504                 goto out_free_tfm;
505         }
506         /* TODO: virt_to_scatterlist */
507         encrypted_session_key = (char *)__get_free_page(GFP_KERNEL);
508         if (!encrypted_session_key) {
509                 ecryptfs_printk(KERN_ERR, "Out of memory\n");
510                 rc = -ENOMEM;
511                 goto out_free_tfm;
512         }
513         session_key = (char *)__get_free_page(GFP_KERNEL);
514         if (!session_key) {
515                 kfree(encrypted_session_key);
516                 ecryptfs_printk(KERN_ERR, "Out of memory\n");
517                 rc = -ENOMEM;
518                 goto out_free_tfm;
519         }
520         memcpy(encrypted_session_key, auth_tok->session_key.encrypted_key,
521                auth_tok->session_key.encrypted_key_size);
522         src_sg[0].page = virt_to_page(encrypted_session_key);
523         src_sg[0].offset = 0;
524         BUG_ON(auth_tok->session_key.encrypted_key_size > PAGE_CACHE_SIZE);
525         src_sg[0].length = auth_tok->session_key.encrypted_key_size;
526         dst_sg[0].page = virt_to_page(session_key);
527         dst_sg[0].offset = 0;
528         auth_tok->session_key.decrypted_key_size =
529             auth_tok->session_key.encrypted_key_size;
530         dst_sg[0].length = auth_tok->session_key.encrypted_key_size;
531         /* TODO: Handle error condition */
532         crypto_cipher_decrypt(tfm, dst_sg, src_sg,
533                               auth_tok->session_key.encrypted_key_size);
534         auth_tok->session_key.decrypted_key_size =
535             auth_tok->session_key.encrypted_key_size;
536         memcpy(auth_tok->session_key.decrypted_key, session_key,
537                auth_tok->session_key.decrypted_key_size);
538         auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
539         memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
540                auth_tok->session_key.decrypted_key_size);
541         ECRYPTFS_SET_FLAG(crypt_stat->flags, ECRYPTFS_KEY_VALID);
542         ecryptfs_printk(KERN_DEBUG, "Decrypted session key:\n");
543         if (ecryptfs_verbosity > 0)
544                 ecryptfs_dump_hex(crypt_stat->key,
545                                   crypt_stat->key_size);
546         memset(encrypted_session_key, 0, PAGE_CACHE_SIZE);
547         free_page((unsigned long)encrypted_session_key);
548         memset(session_key, 0, PAGE_CACHE_SIZE);
549         free_page((unsigned long)session_key);
550 out_free_tfm:
551         if (tfm_mutex)
552                 mutex_unlock(tfm_mutex);
553         else
554                 crypto_free_tfm(tfm);
555 out:
556         return rc;
557 }
558
559 /**
560  * ecryptfs_parse_packet_set
561  * @dest: The header page in memory
562  * @version: Version of file format, to guide parsing behavior
563  *
564  * Get crypt_stat to have the file's session key if the requisite key
565  * is available to decrypt the session key.
566  *
567  * Returns Zero if a valid authentication token was retrieved and
568  * processed; negative value for file not encrypted or for error
569  * conditions.
570  */
571 int ecryptfs_parse_packet_set(struct ecryptfs_crypt_stat *crypt_stat,
572                               unsigned char *src,
573                               struct dentry *ecryptfs_dentry)
574 {
575         size_t i = 0;
576         int rc = 0;
577         size_t found_auth_tok = 0;
578         size_t next_packet_is_auth_tok_packet;
579         char sig[ECRYPTFS_SIG_SIZE_HEX];
580         struct list_head auth_tok_list;
581         struct list_head *walker;
582         struct ecryptfs_auth_tok *chosen_auth_tok = NULL;
583         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
584                 &ecryptfs_superblock_to_private(
585                         ecryptfs_dentry->d_sb)->mount_crypt_stat;
586         struct ecryptfs_auth_tok *candidate_auth_tok = NULL;
587         size_t packet_size;
588         struct ecryptfs_auth_tok *new_auth_tok;
589         unsigned char sig_tmp_space[ECRYPTFS_SIG_SIZE];
590         size_t tag_11_contents_size;
591         size_t tag_11_packet_size;
592
593         INIT_LIST_HEAD(&auth_tok_list);
594         /* Parse the header to find as many packets as we can, these will be
595          * added the our &auth_tok_list */
596         next_packet_is_auth_tok_packet = 1;
597         while (next_packet_is_auth_tok_packet) {
598                 size_t max_packet_size = ((PAGE_CACHE_SIZE - 8) - i);
599
600                 switch (src[i]) {
601                 case ECRYPTFS_TAG_3_PACKET_TYPE:
602                         rc = parse_tag_3_packet(crypt_stat,
603                                                 (unsigned char *)&src[i],
604                                                 &auth_tok_list, &new_auth_tok,
605                                                 &packet_size, max_packet_size);
606                         if (rc) {
607                                 ecryptfs_printk(KERN_ERR, "Error parsing "
608                                                 "tag 3 packet\n");
609                                 rc = -EIO;
610                                 goto out_wipe_list;
611                         }
612                         i += packet_size;
613                         rc = parse_tag_11_packet((unsigned char *)&src[i],
614                                                  sig_tmp_space,
615                                                  ECRYPTFS_SIG_SIZE,
616                                                  &tag_11_contents_size,
617                                                  &tag_11_packet_size,
618                                                  max_packet_size);
619                         if (rc) {
620                                 ecryptfs_printk(KERN_ERR, "No valid "
621                                                 "(ecryptfs-specific) literal "
622                                                 "packet containing "
623                                                 "authentication token "
624                                                 "signature found after "
625                                                 "tag 3 packet\n");
626                                 rc = -EIO;
627                                 goto out_wipe_list;
628                         }
629                         i += tag_11_packet_size;
630                         if (ECRYPTFS_SIG_SIZE != tag_11_contents_size) {
631                                 ecryptfs_printk(KERN_ERR, "Expected "
632                                                 "signature of size [%d]; "
633                                                 "read size [%d]\n",
634                                                 ECRYPTFS_SIG_SIZE,
635                                                 tag_11_contents_size);
636                                 rc = -EIO;
637                                 goto out_wipe_list;
638                         }
639                         ecryptfs_to_hex(new_auth_tok->token.password.signature,
640                                         sig_tmp_space, tag_11_contents_size);
641                         new_auth_tok->token.password.signature[
642                                 ECRYPTFS_PASSWORD_SIG_SIZE] = '\0';
643                         ECRYPTFS_SET_FLAG(crypt_stat->flags,
644                                           ECRYPTFS_ENCRYPTED);
645                         break;
646                 case ECRYPTFS_TAG_11_PACKET_TYPE:
647                         ecryptfs_printk(KERN_WARNING, "Invalid packet set "
648                                         "(Tag 11 not allowed by itself)\n");
649                         rc = -EIO;
650                         goto out_wipe_list;
651                         break;
652                 default:
653                         ecryptfs_printk(KERN_DEBUG, "No packet at offset "
654                                         "[%d] of the file header; hex value of "
655                                         "character is [0x%.2x]\n", i, src[i]);
656                         next_packet_is_auth_tok_packet = 0;
657                 }
658         }
659         if (list_empty(&auth_tok_list)) {
660                 rc = -EINVAL; /* Do not support non-encrypted files in
661                                * the 0.1 release */
662                 goto out;
663         }
664         /* If we have a global auth tok, then we should try to use
665          * it */
666         if (mount_crypt_stat->global_auth_tok) {
667                 memcpy(sig, mount_crypt_stat->global_auth_tok_sig,
668                        ECRYPTFS_SIG_SIZE_HEX);
669                 chosen_auth_tok = mount_crypt_stat->global_auth_tok;
670         } else
671                 BUG(); /* We should always have a global auth tok in
672                         * the 0.1 release */
673         /* Scan list to see if our chosen_auth_tok works */
674         list_for_each(walker, &auth_tok_list) {
675                 struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
676                 auth_tok_list_item =
677                     list_entry(walker, struct ecryptfs_auth_tok_list_item,
678                                list);
679                 candidate_auth_tok = &auth_tok_list_item->auth_tok;
680                 if (unlikely(ecryptfs_verbosity > 0)) {
681                         ecryptfs_printk(KERN_DEBUG,
682                                         "Considering cadidate auth tok:\n");
683                         ecryptfs_dump_auth_tok(candidate_auth_tok);
684                 }
685                 /* TODO: Replace ECRYPTFS_SIG_SIZE_HEX w/ dynamic value */
686                 if (candidate_auth_tok->token_type == ECRYPTFS_PASSWORD
687                     && !strncmp(candidate_auth_tok->token.password.signature,
688                                 sig, ECRYPTFS_SIG_SIZE_HEX)) {
689                         found_auth_tok = 1;
690                         goto leave_list;
691                         /* TODO: Transfer the common salt into the
692                          * crypt_stat salt */
693                 }
694         }
695 leave_list:
696         if (!found_auth_tok) {
697                 ecryptfs_printk(KERN_ERR, "Could not find authentication "
698                                 "token on temporary list for sig [%.*s]\n",
699                                 ECRYPTFS_SIG_SIZE_HEX, sig);
700                 rc = -EIO;
701                 goto out_wipe_list;
702         } else {
703                 memcpy(&(candidate_auth_tok->token.password),
704                        &(chosen_auth_tok->token.password),
705                        sizeof(struct ecryptfs_password));
706                 rc = decrypt_session_key(candidate_auth_tok, crypt_stat);
707                 if (rc) {
708                         ecryptfs_printk(KERN_ERR, "Error decrypting the "
709                                         "session key\n");
710                         goto out_wipe_list;
711                 }
712                 rc = ecryptfs_compute_root_iv(crypt_stat);
713                 if (rc) {
714                         ecryptfs_printk(KERN_ERR, "Error computing "
715                                         "the root IV\n");
716                         goto out_wipe_list;
717                 }
718         }
719         rc = ecryptfs_init_crypt_ctx(crypt_stat);
720         if (rc) {
721                 ecryptfs_printk(KERN_ERR, "Error initializing crypto "
722                                 "context for cipher [%s]; rc = [%d]\n",
723                                 crypt_stat->cipher, rc);
724         }
725 out_wipe_list:
726         wipe_auth_tok_list(&auth_tok_list);
727 out:
728         return rc;
729 }
730
731 /**
732  * write_tag_11_packet
733  * @dest: Target into which Tag 11 packet is to be written
734  * @max: Maximum packet length
735  * @contents: Byte array of contents to copy in
736  * @contents_length: Number of bytes in contents
737  * @packet_length: Length of the Tag 11 packet written; zero on error
738  *
739  * Returns zero on success; non-zero on error.
740  */
741 static int
742 write_tag_11_packet(char *dest, int max, char *contents, size_t contents_length,
743                     size_t *packet_length)
744 {
745         int rc = 0;
746         size_t packet_size_length;
747
748         (*packet_length) = 0;
749         if ((13 + contents_length) > max) {
750                 rc = -EINVAL;
751                 ecryptfs_printk(KERN_ERR, "Packet length larger than "
752                                 "maximum allowable\n");
753                 goto out;
754         }
755         /* General packet header */
756         /* Packet tag */
757         dest[(*packet_length)++] = ECRYPTFS_TAG_11_PACKET_TYPE;
758         /* Packet length */
759         rc = write_packet_length(&dest[(*packet_length)],
760                                  (13 + contents_length), &packet_size_length);
761         if (rc) {
762                 ecryptfs_printk(KERN_ERR, "Error generating tag 11 packet "
763                                 "header; cannot generate packet length\n");
764                 goto out;
765         }
766         (*packet_length) += packet_size_length;
767         /* Tag 11 specific */
768         /* One-octet field that describes how the data is formatted */
769         dest[(*packet_length)++] = 0x62; /* binary data */
770         /* One-octet filename length followed by filename */
771         dest[(*packet_length)++] = 8;
772         memcpy(&dest[(*packet_length)], "_CONSOLE", 8);
773         (*packet_length) += 8;
774         /* Four-octet number indicating modification date */
775         memset(&dest[(*packet_length)], 0x00, 4);
776         (*packet_length) += 4;
777         /* Remainder is literal data */
778         memcpy(&dest[(*packet_length)], contents, contents_length);
779         (*packet_length) += contents_length;
780  out:
781         if (rc)
782                 (*packet_length) = 0;
783         return rc;
784 }
785
786 /**
787  * write_tag_3_packet
788  * @dest: Buffer into which to write the packet
789  * @max: Maximum number of bytes that can be written
790  * @auth_tok: Authentication token
791  * @crypt_stat: The cryptographic context
792  * @key_rec: encrypted key
793  * @packet_size: This function will write the number of bytes that end
794  *               up constituting the packet; set to zero on error
795  *
796  * Returns zero on success; non-zero on error.
797  */
798 static int
799 write_tag_3_packet(char *dest, size_t max, struct ecryptfs_auth_tok *auth_tok,
800                    struct ecryptfs_crypt_stat *crypt_stat,
801                    struct ecryptfs_key_record *key_rec, size_t *packet_size)
802 {
803         int rc = 0;
804
805         size_t i;
806         size_t signature_is_valid = 0;
807         size_t encrypted_session_key_valid = 0;
808         char session_key_encryption_key[ECRYPTFS_MAX_KEY_BYTES];
809         struct scatterlist dest_sg[2];
810         struct scatterlist src_sg[2];
811         struct crypto_tfm *tfm = NULL;
812         struct mutex *tfm_mutex = NULL;
813         size_t key_rec_size;
814         size_t packet_size_length;
815         size_t cipher_code;
816
817         (*packet_size) = 0;
818         /* Check for a valid signature on the auth_tok */
819         for (i = 0; i < ECRYPTFS_SIG_SIZE_HEX; i++)
820                 signature_is_valid |= auth_tok->token.password.signature[i];
821         if (!signature_is_valid)
822                 BUG();
823         ecryptfs_from_hex((*key_rec).sig, auth_tok->token.password.signature,
824                           ECRYPTFS_SIG_SIZE);
825         encrypted_session_key_valid = 0;
826         for (i = 0; i < crypt_stat->key_size; i++)
827                 encrypted_session_key_valid |=
828                         auth_tok->session_key.encrypted_key[i];
829         if (encrypted_session_key_valid) {
830                 memcpy((*key_rec).enc_key,
831                        auth_tok->session_key.encrypted_key,
832                        auth_tok->session_key.encrypted_key_size);
833                 goto encrypted_session_key_set;
834         }
835         if (auth_tok->session_key.encrypted_key_size == 0)
836                 auth_tok->session_key.encrypted_key_size =
837                         crypt_stat->key_size;
838         if (crypt_stat->key_size == 24
839             && strcmp("aes", crypt_stat->cipher) == 0) {
840                 memset((crypt_stat->key + 24), 0, 8);
841                 auth_tok->session_key.encrypted_key_size = 32;
842         }
843         (*key_rec).enc_key_size =
844                 auth_tok->session_key.encrypted_key_size;
845         if (ECRYPTFS_CHECK_FLAG(auth_tok->token.password.flags,
846                                 ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET)) {
847                 ecryptfs_printk(KERN_DEBUG, "Using previously generated "
848                                 "session key encryption key of size [%d]\n",
849                                 auth_tok->token.password.
850                                 session_key_encryption_key_bytes);
851                 memcpy(session_key_encryption_key,
852                        auth_tok->token.password.session_key_encryption_key,
853                        crypt_stat->key_size);
854                 ecryptfs_printk(KERN_DEBUG,
855                                 "Cached session key " "encryption key: \n");
856                 if (ecryptfs_verbosity > 0)
857                         ecryptfs_dump_hex(session_key_encryption_key, 16);
858         }
859         if (unlikely(ecryptfs_verbosity > 0)) {
860                 ecryptfs_printk(KERN_DEBUG, "Session key encryption key:\n");
861                 ecryptfs_dump_hex(session_key_encryption_key, 16);
862         }
863         rc = virt_to_scatterlist(crypt_stat->key,
864                                  (*key_rec).enc_key_size, src_sg, 2);
865         if (!rc) {
866                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
867                                 "for crypt_stat session key\n");
868                 rc = -ENOMEM;
869                 goto out;
870         }
871         rc = virt_to_scatterlist((*key_rec).enc_key,
872                                  (*key_rec).enc_key_size, dest_sg, 2);
873         if (!rc) {
874                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
875                                 "for crypt_stat encrypted session key\n");
876                 rc = -ENOMEM;
877                 goto out;
878         }
879         if (!strcmp(crypt_stat->cipher,
880                     crypt_stat->mount_crypt_stat->global_default_cipher_name)
881             && crypt_stat->mount_crypt_stat->global_key_tfm) {
882                 tfm = crypt_stat->mount_crypt_stat->global_key_tfm;
883                 tfm_mutex = &crypt_stat->mount_crypt_stat->global_key_tfm_mutex;
884         } else
885                 tfm = crypto_alloc_tfm(crypt_stat->cipher, 0);
886         if (!tfm) {
887                 ecryptfs_printk(KERN_ERR, "Could not initialize crypto "
888                                 "context for cipher [%s]\n",
889                                 crypt_stat->cipher);
890                 rc = -EINVAL;
891                 goto out;
892         }
893         if (tfm_mutex)
894                 mutex_lock(tfm_mutex);
895         rc = crypto_cipher_setkey(tfm, session_key_encryption_key,
896                                   crypt_stat->key_size);
897         if (rc < 0) {
898                 if (tfm_mutex)
899                         mutex_unlock(tfm_mutex);
900                 ecryptfs_printk(KERN_ERR, "Error setting key for crypto "
901                                 "context\n");
902                 goto out;
903         }
904         rc = 0;
905         ecryptfs_printk(KERN_DEBUG, "Encrypting [%d] bytes of the key\n",
906                         crypt_stat->key_size);
907         crypto_cipher_encrypt(tfm, dest_sg, src_sg,
908                               (*key_rec).enc_key_size);
909         if (tfm_mutex)
910                 mutex_unlock(tfm_mutex);
911         ecryptfs_printk(KERN_DEBUG, "This should be the encrypted key:\n");
912         if (ecryptfs_verbosity > 0)
913                 ecryptfs_dump_hex((*key_rec).enc_key,
914                                   (*key_rec).enc_key_size);
915 encrypted_session_key_set:
916         /* Now we have a valid key_rec.  Append it to the
917          * key_rec set. */
918         key_rec_size = (sizeof(struct ecryptfs_key_record)
919                         - ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES
920                         + ((*key_rec).enc_key_size));
921         /* TODO: Include a packet size limit as a parameter to this
922          * function once we have multi-packet headers (for versions
923          * later than 0.1 */
924         if (key_rec_size >= ECRYPTFS_MAX_KEYSET_SIZE) {
925                 ecryptfs_printk(KERN_ERR, "Keyset too large\n");
926                 rc = -EINVAL;
927                 goto out;
928         }
929         /* TODO: Packet size limit */
930         /* We have 5 bytes of surrounding packet data */
931         if ((0x05 + ECRYPTFS_SALT_SIZE
932              + (*key_rec).enc_key_size) >= max) {
933                 ecryptfs_printk(KERN_ERR, "Authentication token is too "
934                                 "large\n");
935                 rc = -EINVAL;
936                 goto out;
937         }
938         /* This format is inspired by OpenPGP; see RFC 2440
939          * packet tag 3 */
940         dest[(*packet_size)++] = ECRYPTFS_TAG_3_PACKET_TYPE;
941         /* ver+cipher+s2k+hash+salt+iter+enc_key */
942         rc = write_packet_length(&dest[(*packet_size)],
943                                  (0x05 + ECRYPTFS_SALT_SIZE
944                                   + (*key_rec).enc_key_size),
945                                  &packet_size_length);
946         if (rc) {
947                 ecryptfs_printk(KERN_ERR, "Error generating tag 3 packet "
948                                 "header; cannot generate packet length\n");
949                 goto out;
950         }
951         (*packet_size) += packet_size_length;
952         dest[(*packet_size)++] = 0x04; /* version 4 */
953         cipher_code = ecryptfs_code_for_cipher_string(crypt_stat);
954         if (cipher_code == 0) {
955                 ecryptfs_printk(KERN_WARNING, "Unable to generate code for "
956                                 "cipher [%s]\n", crypt_stat->cipher);
957                 rc = -EINVAL;
958                 goto out;
959         }
960         dest[(*packet_size)++] = cipher_code;
961         dest[(*packet_size)++] = 0x03;  /* S2K */
962         dest[(*packet_size)++] = 0x01;  /* MD5 (TODO: parameterize) */
963         memcpy(&dest[(*packet_size)], auth_tok->token.password.salt,
964                ECRYPTFS_SALT_SIZE);
965         (*packet_size) += ECRYPTFS_SALT_SIZE;   /* salt */
966         dest[(*packet_size)++] = 0x60;  /* hash iterations (65536) */
967         memcpy(&dest[(*packet_size)], (*key_rec).enc_key,
968                (*key_rec).enc_key_size);
969         (*packet_size) += (*key_rec).enc_key_size;
970 out:
971         if (tfm && !tfm_mutex)
972                 crypto_free_tfm(tfm);
973         if (rc)
974                 (*packet_size) = 0;
975         return rc;
976 }
977
978 /**
979  * ecryptfs_generate_key_packet_set
980  * @dest: Virtual address from which to write the key record set
981  * @crypt_stat: The cryptographic context from which the
982  *              authentication tokens will be retrieved
983  * @ecryptfs_dentry: The dentry, used to retrieve the mount crypt stat
984  *                   for the global parameters
985  * @len: The amount written
986  * @max: The maximum amount of data allowed to be written
987  *
988  * Generates a key packet set and writes it to the virtual address
989  * passed in.
990  *
991  * Returns zero on success; non-zero on error.
992  */
993 int
994 ecryptfs_generate_key_packet_set(char *dest_base,
995                                  struct ecryptfs_crypt_stat *crypt_stat,
996                                  struct dentry *ecryptfs_dentry, size_t *len,
997                                  size_t max)
998 {
999         int rc = 0;
1000         struct ecryptfs_auth_tok *auth_tok;
1001         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1002                 &ecryptfs_superblock_to_private(
1003                         ecryptfs_dentry->d_sb)->mount_crypt_stat;
1004         size_t written;
1005         struct ecryptfs_key_record key_rec;
1006
1007         (*len) = 0;
1008         if (mount_crypt_stat->global_auth_tok) {
1009                 auth_tok = mount_crypt_stat->global_auth_tok;
1010                 if (auth_tok->token_type == ECRYPTFS_PASSWORD) {
1011                         rc = write_tag_3_packet((dest_base + (*len)),
1012                                                 max, auth_tok,
1013                                                 crypt_stat, &key_rec,
1014                                                 &written);
1015                         if (rc) {
1016                                 ecryptfs_printk(KERN_WARNING, "Error "
1017                                                 "writing tag 3 packet\n");
1018                                 goto out;
1019                         }
1020                         (*len) += written;
1021                         /* Write auth tok signature packet */
1022                         rc = write_tag_11_packet(
1023                                 (dest_base + (*len)),
1024                                 (max - (*len)),
1025                                 key_rec.sig, ECRYPTFS_SIG_SIZE, &written);
1026                         if (rc) {
1027                                 ecryptfs_printk(KERN_ERR, "Error writing "
1028                                                 "auth tok signature packet\n");
1029                                 goto out;
1030                         }
1031                         (*len) += written;
1032                 } else {
1033                         ecryptfs_printk(KERN_WARNING, "Unsupported "
1034                                         "authentication token type\n");
1035                         rc = -EINVAL;
1036                         goto out;
1037                 }
1038                 if (rc) {
1039                         ecryptfs_printk(KERN_WARNING, "Error writing "
1040                                         "authentication token packet with sig "
1041                                         "= [%s]\n",
1042                                         mount_crypt_stat->global_auth_tok_sig);
1043                         rc = -EIO;
1044                         goto out;
1045                 }
1046         } else
1047                 BUG();
1048         if (likely((max - (*len)) > 0)) {
1049                 dest_base[(*len)] = 0x00;
1050         } else {
1051                 ecryptfs_printk(KERN_ERR, "Error writing boundary byte\n");
1052                 rc = -EIO;
1053         }
1054 out:
1055         if (rc)
1056                 (*len) = 0;
1057         return rc;
1058 }