Merge branch 'hwmon-for-linus' of git://jdelvare.pck.nerim.net/jdelvare-2.6
[linux-2.6] / 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  *              Trevor S. Highland <trevor.highland@gmail.com>
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25  * 02111-1307, USA.
26  */
27
28 #include <linux/string.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 /**
68  * parse_packet_length
69  * @data: Pointer to memory containing length at offset
70  * @size: This function writes the decoded size to this memory
71  *        address; zero on error
72  * @length_size: The number of bytes occupied by the encoded length
73  *
74  * Returns Zero on success
75  */
76 static int parse_packet_length(unsigned char *data, size_t *size,
77                                size_t *length_size)
78 {
79         int rc = 0;
80
81         (*length_size) = 0;
82         (*size) = 0;
83         if (data[0] < 192) {
84                 /* One-byte length */
85                 (*size) = (unsigned char)data[0];
86                 (*length_size) = 1;
87         } else if (data[0] < 224) {
88                 /* Two-byte length */
89                 (*size) = (((unsigned char)(data[0]) - 192) * 256);
90                 (*size) += ((unsigned char)(data[1]) + 192);
91                 (*length_size) = 2;
92         } else if (data[0] == 255) {
93                 /* Five-byte length; we're not supposed to see this */
94                 ecryptfs_printk(KERN_ERR, "Five-byte packet length not "
95                                 "supported\n");
96                 rc = -EINVAL;
97                 goto out;
98         } else {
99                 ecryptfs_printk(KERN_ERR, "Error parsing packet length\n");
100                 rc = -EINVAL;
101                 goto out;
102         }
103 out:
104         return rc;
105 }
106
107 /**
108  * write_packet_length
109  * @dest: The byte array target into which to write the
110  *       length. Must have at least 5 bytes allocated.
111  * @size: The length to write.
112  * @packet_size_length: The number of bytes used to encode the
113  *                      packet length is written to this address.
114  *
115  * Returns zero on success; non-zero on error.
116  */
117 static int write_packet_length(char *dest, size_t size,
118                                size_t *packet_size_length)
119 {
120         int rc = 0;
121
122         if (size < 192) {
123                 dest[0] = size;
124                 (*packet_size_length) = 1;
125         } else if (size < 65536) {
126                 dest[0] = (((size - 192) / 256) + 192);
127                 dest[1] = ((size - 192) % 256);
128                 (*packet_size_length) = 2;
129         } else {
130                 rc = -EINVAL;
131                 ecryptfs_printk(KERN_WARNING,
132                                 "Unsupported packet size: [%d]\n", size);
133         }
134         return rc;
135 }
136
137 static int
138 write_tag_64_packet(char *signature, struct ecryptfs_session_key *session_key,
139                     char **packet, size_t *packet_len)
140 {
141         size_t i = 0;
142         size_t data_len;
143         size_t packet_size_len;
144         char *message;
145         int rc;
146
147         /*
148          *              ***** TAG 64 Packet Format *****
149          *    | Content Type                       | 1 byte       |
150          *    | Key Identifier Size                | 1 or 2 bytes |
151          *    | Key Identifier                     | arbitrary    |
152          *    | Encrypted File Encryption Key Size | 1 or 2 bytes |
153          *    | Encrypted File Encryption Key      | arbitrary    |
154          */
155         data_len = (5 + ECRYPTFS_SIG_SIZE_HEX
156                     + session_key->encrypted_key_size);
157         *packet = kmalloc(data_len, GFP_KERNEL);
158         message = *packet;
159         if (!message) {
160                 ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
161                 rc = -ENOMEM;
162                 goto out;
163         }
164         message[i++] = ECRYPTFS_TAG_64_PACKET_TYPE;
165         rc = write_packet_length(&message[i], ECRYPTFS_SIG_SIZE_HEX,
166                                  &packet_size_len);
167         if (rc) {
168                 ecryptfs_printk(KERN_ERR, "Error generating tag 64 packet "
169                                 "header; cannot generate packet length\n");
170                 goto out;
171         }
172         i += packet_size_len;
173         memcpy(&message[i], signature, ECRYPTFS_SIG_SIZE_HEX);
174         i += ECRYPTFS_SIG_SIZE_HEX;
175         rc = write_packet_length(&message[i], session_key->encrypted_key_size,
176                                  &packet_size_len);
177         if (rc) {
178                 ecryptfs_printk(KERN_ERR, "Error generating tag 64 packet "
179                                 "header; cannot generate packet length\n");
180                 goto out;
181         }
182         i += packet_size_len;
183         memcpy(&message[i], session_key->encrypted_key,
184                session_key->encrypted_key_size);
185         i += session_key->encrypted_key_size;
186         *packet_len = i;
187 out:
188         return rc;
189 }
190
191 static int
192 parse_tag_65_packet(struct ecryptfs_session_key *session_key, u16 *cipher_code,
193                     struct ecryptfs_message *msg)
194 {
195         size_t i = 0;
196         char *data;
197         size_t data_len;
198         size_t m_size;
199         size_t message_len;
200         u16 checksum = 0;
201         u16 expected_checksum = 0;
202         int rc;
203
204         /*
205          *              ***** TAG 65 Packet Format *****
206          *         | Content Type             | 1 byte       |
207          *         | Status Indicator         | 1 byte       |
208          *         | File Encryption Key Size | 1 or 2 bytes |
209          *         | File Encryption Key      | arbitrary    |
210          */
211         message_len = msg->data_len;
212         data = msg->data;
213         if (message_len < 4) {
214                 rc = -EIO;
215                 goto out;
216         }
217         if (data[i++] != ECRYPTFS_TAG_65_PACKET_TYPE) {
218                 ecryptfs_printk(KERN_ERR, "Type should be ECRYPTFS_TAG_65\n");
219                 rc = -EIO;
220                 goto out;
221         }
222         if (data[i++]) {
223                 ecryptfs_printk(KERN_ERR, "Status indicator has non-zero value "
224                                 "[%d]\n", data[i-1]);
225                 rc = -EIO;
226                 goto out;
227         }
228         rc = parse_packet_length(&data[i], &m_size, &data_len);
229         if (rc) {
230                 ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
231                                 "rc = [%d]\n", rc);
232                 goto out;
233         }
234         i += data_len;
235         if (message_len < (i + m_size)) {
236                 ecryptfs_printk(KERN_ERR, "The received netlink message is "
237                                 "shorter than expected\n");
238                 rc = -EIO;
239                 goto out;
240         }
241         if (m_size < 3) {
242                 ecryptfs_printk(KERN_ERR,
243                                 "The decrypted key is not long enough to "
244                                 "include a cipher code and checksum\n");
245                 rc = -EIO;
246                 goto out;
247         }
248         *cipher_code = data[i++];
249         /* The decrypted key includes 1 byte cipher code and 2 byte checksum */
250         session_key->decrypted_key_size = m_size - 3;
251         if (session_key->decrypted_key_size > ECRYPTFS_MAX_KEY_BYTES) {
252                 ecryptfs_printk(KERN_ERR, "key_size [%d] larger than "
253                                 "the maximum key size [%d]\n",
254                                 session_key->decrypted_key_size,
255                                 ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES);
256                 rc = -EIO;
257                 goto out;
258         }
259         memcpy(session_key->decrypted_key, &data[i],
260                session_key->decrypted_key_size);
261         i += session_key->decrypted_key_size;
262         expected_checksum += (unsigned char)(data[i++]) << 8;
263         expected_checksum += (unsigned char)(data[i++]);
264         for (i = 0; i < session_key->decrypted_key_size; i++)
265                 checksum += session_key->decrypted_key[i];
266         if (expected_checksum != checksum) {
267                 ecryptfs_printk(KERN_ERR, "Invalid checksum for file "
268                                 "encryption  key; expected [%x]; calculated "
269                                 "[%x]\n", expected_checksum, checksum);
270                 rc = -EIO;
271         }
272 out:
273         return rc;
274 }
275
276
277 static int
278 write_tag_66_packet(char *signature, size_t cipher_code,
279                     struct ecryptfs_crypt_stat *crypt_stat, char **packet,
280                     size_t *packet_len)
281 {
282         size_t i = 0;
283         size_t j;
284         size_t data_len;
285         size_t checksum = 0;
286         size_t packet_size_len;
287         char *message;
288         int rc;
289
290         /*
291          *              ***** TAG 66 Packet Format *****
292          *         | Content Type             | 1 byte       |
293          *         | Key Identifier Size      | 1 or 2 bytes |
294          *         | Key Identifier           | arbitrary    |
295          *         | File Encryption Key Size | 1 or 2 bytes |
296          *         | File Encryption Key      | arbitrary    |
297          */
298         data_len = (5 + ECRYPTFS_SIG_SIZE_HEX + crypt_stat->key_size);
299         *packet = kmalloc(data_len, GFP_KERNEL);
300         message = *packet;
301         if (!message) {
302                 ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
303                 rc = -ENOMEM;
304                 goto out;
305         }
306         message[i++] = ECRYPTFS_TAG_66_PACKET_TYPE;
307         rc = write_packet_length(&message[i], ECRYPTFS_SIG_SIZE_HEX,
308                                  &packet_size_len);
309         if (rc) {
310                 ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet "
311                                 "header; cannot generate packet length\n");
312                 goto out;
313         }
314         i += packet_size_len;
315         memcpy(&message[i], signature, ECRYPTFS_SIG_SIZE_HEX);
316         i += ECRYPTFS_SIG_SIZE_HEX;
317         /* The encrypted key includes 1 byte cipher code and 2 byte checksum */
318         rc = write_packet_length(&message[i], crypt_stat->key_size + 3,
319                                  &packet_size_len);
320         if (rc) {
321                 ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet "
322                                 "header; cannot generate packet length\n");
323                 goto out;
324         }
325         i += packet_size_len;
326         message[i++] = cipher_code;
327         memcpy(&message[i], crypt_stat->key, crypt_stat->key_size);
328         i += crypt_stat->key_size;
329         for (j = 0; j < crypt_stat->key_size; j++)
330                 checksum += crypt_stat->key[j];
331         message[i++] = (checksum / 256) % 256;
332         message[i++] = (checksum % 256);
333         *packet_len = i;
334 out:
335         return rc;
336 }
337
338 static int
339 parse_tag_67_packet(struct ecryptfs_key_record *key_rec,
340                     struct ecryptfs_message *msg)
341 {
342         size_t i = 0;
343         char *data;
344         size_t data_len;
345         size_t message_len;
346         int rc;
347
348         /*
349          *              ***** TAG 65 Packet Format *****
350          *    | Content Type                       | 1 byte       |
351          *    | Status Indicator                   | 1 byte       |
352          *    | Encrypted File Encryption Key Size | 1 or 2 bytes |
353          *    | Encrypted File Encryption Key      | arbitrary    |
354          */
355         message_len = msg->data_len;
356         data = msg->data;
357         /* verify that everything through the encrypted FEK size is present */
358         if (message_len < 4) {
359                 rc = -EIO;
360                 goto out;
361         }
362         if (data[i++] != ECRYPTFS_TAG_67_PACKET_TYPE) {
363                 ecryptfs_printk(KERN_ERR, "Type should be ECRYPTFS_TAG_67\n");
364                 rc = -EIO;
365                 goto out;
366         }
367         if (data[i++]) {
368                 ecryptfs_printk(KERN_ERR, "Status indicator has non zero value"
369                                 " [%d]\n", data[i-1]);
370                 rc = -EIO;
371                 goto out;
372         }
373         rc = parse_packet_length(&data[i], &key_rec->enc_key_size, &data_len);
374         if (rc) {
375                 ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
376                                 "rc = [%d]\n", rc);
377                 goto out;
378         }
379         i += data_len;
380         if (message_len < (i + key_rec->enc_key_size)) {
381                 ecryptfs_printk(KERN_ERR, "message_len [%d]; max len is [%d]\n",
382                                 message_len, (i + key_rec->enc_key_size));
383                 rc = -EIO;
384                 goto out;
385         }
386         if (key_rec->enc_key_size > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
387                 ecryptfs_printk(KERN_ERR, "Encrypted key_size [%d] larger than "
388                                 "the maximum key size [%d]\n",
389                                 key_rec->enc_key_size,
390                                 ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES);
391                 rc = -EIO;
392                 goto out;
393         }
394         memcpy(key_rec->enc_key, &data[i], key_rec->enc_key_size);
395 out:
396         return rc;
397 }
398
399 /**
400  * decrypt_pki_encrypted_session_key - Decrypt the session key with
401  * the given auth_tok.
402  *
403  * Returns Zero on success; non-zero error otherwise.
404  */
405 static int decrypt_pki_encrypted_session_key(
406         struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
407         struct ecryptfs_auth_tok *auth_tok,
408         struct ecryptfs_crypt_stat *crypt_stat)
409 {
410         u16 cipher_code = 0;
411         struct ecryptfs_msg_ctx *msg_ctx;
412         struct ecryptfs_message *msg = NULL;
413         char *netlink_message;
414         size_t netlink_message_length;
415         int rc;
416
417         rc = write_tag_64_packet(mount_crypt_stat->global_auth_tok_sig,
418                                  &(auth_tok->session_key),
419                                  &netlink_message, &netlink_message_length);
420         if (rc) {
421                 ecryptfs_printk(KERN_ERR, "Failed to write tag 64 packet");
422                 goto out;
423         }
424         rc = ecryptfs_send_message(ecryptfs_transport, netlink_message,
425                                    netlink_message_length, &msg_ctx);
426         if (rc) {
427                 ecryptfs_printk(KERN_ERR, "Error sending netlink message\n");
428                 goto out;
429         }
430         rc = ecryptfs_wait_for_response(msg_ctx, &msg);
431         if (rc) {
432                 ecryptfs_printk(KERN_ERR, "Failed to receive tag 65 packet "
433                                 "from the user space daemon\n");
434                 rc = -EIO;
435                 goto out;
436         }
437         rc = parse_tag_65_packet(&(auth_tok->session_key),
438                                  &cipher_code, msg);
439         if (rc) {
440                 printk(KERN_ERR "Failed to parse tag 65 packet; rc = [%d]\n",
441                        rc);
442                 goto out;
443         }
444         auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
445         memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
446                auth_tok->session_key.decrypted_key_size);
447         crypt_stat->key_size = auth_tok->session_key.decrypted_key_size;
448         rc = ecryptfs_cipher_code_to_string(crypt_stat->cipher, cipher_code);
449         if (rc) {
450                 ecryptfs_printk(KERN_ERR, "Cipher code [%d] is invalid\n",
451                                 cipher_code)
452                 goto out;
453         }
454         crypt_stat->flags |= ECRYPTFS_KEY_VALID;
455         if (ecryptfs_verbosity > 0) {
456                 ecryptfs_printk(KERN_DEBUG, "Decrypted session key:\n");
457                 ecryptfs_dump_hex(crypt_stat->key,
458                                   crypt_stat->key_size);
459         }
460 out:
461         if (msg)
462                 kfree(msg);
463         return rc;
464 }
465
466 static void wipe_auth_tok_list(struct list_head *auth_tok_list_head)
467 {
468         struct list_head *walker;
469         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
470
471         walker = auth_tok_list_head->next;
472         while (walker != auth_tok_list_head) {
473                 auth_tok_list_item =
474                     list_entry(walker, struct ecryptfs_auth_tok_list_item,
475                                list);
476                 walker = auth_tok_list_item->list.next;
477                 memset(auth_tok_list_item, 0,
478                        sizeof(struct ecryptfs_auth_tok_list_item));
479                 kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
480                                 auth_tok_list_item);
481         }
482         auth_tok_list_head->next = NULL;
483 }
484
485 struct kmem_cache *ecryptfs_auth_tok_list_item_cache;
486
487
488 /**
489  * parse_tag_1_packet
490  * @crypt_stat: The cryptographic context to modify based on packet
491  *              contents.
492  * @data: The raw bytes of the packet.
493  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
494  *                 a new authentication token will be placed at the end
495  *                 of this list for this packet.
496  * @new_auth_tok: Pointer to a pointer to memory that this function
497  *                allocates; sets the memory address of the pointer to
498  *                NULL on error. This object is added to the
499  *                auth_tok_list.
500  * @packet_size: This function writes the size of the parsed packet
501  *               into this memory location; zero on error.
502  *
503  * Returns zero on success; non-zero on error.
504  */
505 static int
506 parse_tag_1_packet(struct ecryptfs_crypt_stat *crypt_stat,
507                    unsigned char *data, struct list_head *auth_tok_list,
508                    struct ecryptfs_auth_tok **new_auth_tok,
509                    size_t *packet_size, size_t max_packet_size)
510 {
511         size_t body_size;
512         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
513         size_t length_size;
514         int rc = 0;
515
516         (*packet_size) = 0;
517         (*new_auth_tok) = NULL;
518
519         /* we check that:
520          *   one byte for the Tag 1 ID flag
521          *   two bytes for the body size
522          * do not exceed the maximum_packet_size
523          */
524         if (unlikely((*packet_size) + 3 > max_packet_size)) {
525                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
526                 rc = -EINVAL;
527                 goto out;
528         }
529         /* check for Tag 1 identifier - one byte */
530         if (data[(*packet_size)++] != ECRYPTFS_TAG_1_PACKET_TYPE) {
531                 ecryptfs_printk(KERN_ERR, "Enter w/ first byte != 0x%.2x\n",
532                                 ECRYPTFS_TAG_1_PACKET_TYPE);
533                 rc = -EINVAL;
534                 goto out;
535         }
536         /* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
537          * at end of function upon failure */
538         auth_tok_list_item =
539                 kmem_cache_alloc(ecryptfs_auth_tok_list_item_cache,
540                                  GFP_KERNEL);
541         if (!auth_tok_list_item) {
542                 ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
543                 rc = -ENOMEM;
544                 goto out;
545         }
546         memset(auth_tok_list_item, 0,
547                sizeof(struct ecryptfs_auth_tok_list_item));
548         (*new_auth_tok) = &auth_tok_list_item->auth_tok;
549         /* check for body size - one to two bytes
550          *
551          *              ***** TAG 1 Packet Format *****
552          *    | version number                     | 1 byte       |
553          *    | key ID                             | 8 bytes      |
554          *    | public key algorithm               | 1 byte       |
555          *    | encrypted session key              | arbitrary    |
556          */
557         rc = parse_packet_length(&data[(*packet_size)], &body_size,
558                                  &length_size);
559         if (rc) {
560                 ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
561                                 "rc = [%d]\n", rc);
562                 goto out_free;
563         }
564         if (unlikely(body_size < (0x02 + ECRYPTFS_SIG_SIZE))) {
565                 ecryptfs_printk(KERN_WARNING, "Invalid body size ([%d])\n",
566                                 body_size);
567                 rc = -EINVAL;
568                 goto out_free;
569         }
570         (*packet_size) += length_size;
571         if (unlikely((*packet_size) + body_size > max_packet_size)) {
572                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
573                 rc = -EINVAL;
574                 goto out_free;
575         }
576         /* Version 3 (from RFC2440) - one byte */
577         if (unlikely(data[(*packet_size)++] != 0x03)) {
578                 ecryptfs_printk(KERN_DEBUG, "Unknown version number "
579                                 "[%d]\n", data[(*packet_size) - 1]);
580                 rc = -EINVAL;
581                 goto out_free;
582         }
583         /* Read Signature */
584         ecryptfs_to_hex((*new_auth_tok)->token.private_key.signature,
585                         &data[(*packet_size)], ECRYPTFS_SIG_SIZE);
586         *packet_size += ECRYPTFS_SIG_SIZE;
587         /* This byte is skipped because the kernel does not need to
588          * know which public key encryption algorithm was used */
589         (*packet_size)++;
590         (*new_auth_tok)->session_key.encrypted_key_size =
591                 body_size - (0x02 + ECRYPTFS_SIG_SIZE);
592         if ((*new_auth_tok)->session_key.encrypted_key_size
593             > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
594                 ecryptfs_printk(KERN_ERR, "Tag 1 packet contains key larger "
595                                 "than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES");
596                 rc = -EINVAL;
597                 goto out;
598         }
599         ecryptfs_printk(KERN_DEBUG, "Encrypted key size = [%d]\n",
600                         (*new_auth_tok)->session_key.encrypted_key_size);
601         memcpy((*new_auth_tok)->session_key.encrypted_key,
602                &data[(*packet_size)], (body_size - 0x02 - ECRYPTFS_SIG_SIZE));
603         (*packet_size) += (*new_auth_tok)->session_key.encrypted_key_size;
604         (*new_auth_tok)->session_key.flags &=
605                 ~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
606         (*new_auth_tok)->session_key.flags |=
607                 ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
608         (*new_auth_tok)->token_type = ECRYPTFS_PRIVATE_KEY;
609         (*new_auth_tok)->flags |= ECRYPTFS_PRIVATE_KEY;
610         /* TODO: Why are we setting this flag here? Don't we want the
611          * userspace to decrypt the session key? */
612         (*new_auth_tok)->session_key.flags &=
613                 ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
614         (*new_auth_tok)->session_key.flags &=
615                 ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
616         list_add(&auth_tok_list_item->list, auth_tok_list);
617         goto out;
618 out_free:
619         (*new_auth_tok) = NULL;
620         memset(auth_tok_list_item, 0,
621                sizeof(struct ecryptfs_auth_tok_list_item));
622         kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
623                         auth_tok_list_item);
624 out:
625         if (rc)
626                 (*packet_size) = 0;
627         return rc;
628 }
629
630 /**
631  * parse_tag_3_packet
632  * @crypt_stat: The cryptographic context to modify based on packet
633  *              contents.
634  * @data: The raw bytes of the packet.
635  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
636  *                 a new authentication token will be placed at the end
637  *                 of this list for this packet.
638  * @new_auth_tok: Pointer to a pointer to memory that this function
639  *                allocates; sets the memory address of the pointer to
640  *                NULL on error. This object is added to the
641  *                auth_tok_list.
642  * @packet_size: This function writes the size of the parsed packet
643  *               into this memory location; zero on error.
644  * @max_packet_size: maximum number of bytes to parse
645  *
646  * Returns zero on success; non-zero on error.
647  */
648 static int
649 parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat,
650                    unsigned char *data, struct list_head *auth_tok_list,
651                    struct ecryptfs_auth_tok **new_auth_tok,
652                    size_t *packet_size, size_t max_packet_size)
653 {
654         size_t body_size;
655         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
656         size_t length_size;
657         int rc = 0;
658
659         (*packet_size) = 0;
660         (*new_auth_tok) = NULL;
661
662         /* we check that:
663          *   one byte for the Tag 3 ID flag
664          *   two bytes for the body size
665          * do not exceed the maximum_packet_size
666          */
667         if (unlikely((*packet_size) + 3 > max_packet_size)) {
668                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
669                 rc = -EINVAL;
670                 goto out;
671         }
672
673         /* check for Tag 3 identifyer - one byte */
674         if (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) {
675                 ecryptfs_printk(KERN_ERR, "Enter w/ first byte != 0x%.2x\n",
676                                 ECRYPTFS_TAG_3_PACKET_TYPE);
677                 rc = -EINVAL;
678                 goto out;
679         }
680         /* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
681          * at end of function upon failure */
682         auth_tok_list_item =
683             kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL);
684         if (!auth_tok_list_item) {
685                 ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
686                 rc = -ENOMEM;
687                 goto out;
688         }
689         (*new_auth_tok) = &auth_tok_list_item->auth_tok;
690
691         /* check for body size - one to two bytes */
692         rc = parse_packet_length(&data[(*packet_size)], &body_size,
693                                  &length_size);
694         if (rc) {
695                 ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
696                                 "rc = [%d]\n", rc);
697                 goto out_free;
698         }
699         if (unlikely(body_size < (0x05 + ECRYPTFS_SALT_SIZE))) {
700                 ecryptfs_printk(KERN_WARNING, "Invalid body size ([%d])\n",
701                                 body_size);
702                 rc = -EINVAL;
703                 goto out_free;
704         }
705         (*packet_size) += length_size;
706
707         /* now we know the length of the remainting Tag 3 packet size:
708          *   5 fix bytes for: version string, cipher, S2K ID, hash algo,
709          *                    number of hash iterations
710          *   ECRYPTFS_SALT_SIZE bytes for salt
711          *   body_size bytes minus the stuff above is the encrypted key size
712          */
713         if (unlikely((*packet_size) + body_size > max_packet_size)) {
714                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
715                 rc = -EINVAL;
716                 goto out_free;
717         }
718
719         /* There are 5 characters of additional information in the
720          * packet */
721         (*new_auth_tok)->session_key.encrypted_key_size =
722                 body_size - (0x05 + ECRYPTFS_SALT_SIZE);
723         ecryptfs_printk(KERN_DEBUG, "Encrypted key size = [%d]\n",
724                         (*new_auth_tok)->session_key.encrypted_key_size);
725
726         /* Version 4 (from RFC2440) - one byte */
727         if (unlikely(data[(*packet_size)++] != 0x04)) {
728                 ecryptfs_printk(KERN_DEBUG, "Unknown version number "
729                                 "[%d]\n", data[(*packet_size) - 1]);
730                 rc = -EINVAL;
731                 goto out_free;
732         }
733
734         /* cipher - one byte */
735         ecryptfs_cipher_code_to_string(crypt_stat->cipher,
736                                        (u16)data[(*packet_size)]);
737         /* A little extra work to differentiate among the AES key
738          * sizes; see RFC2440 */
739         switch(data[(*packet_size)++]) {
740         case RFC2440_CIPHER_AES_192:
741                 crypt_stat->key_size = 24;
742                 break;
743         default:
744                 crypt_stat->key_size =
745                         (*new_auth_tok)->session_key.encrypted_key_size;
746         }
747         ecryptfs_init_crypt_ctx(crypt_stat);
748         /* S2K identifier 3 (from RFC2440) */
749         if (unlikely(data[(*packet_size)++] != 0x03)) {
750                 ecryptfs_printk(KERN_ERR, "Only S2K ID 3 is currently "
751                                 "supported\n");
752                 rc = -ENOSYS;
753                 goto out_free;
754         }
755
756         /* TODO: finish the hash mapping */
757         /* hash algorithm - one byte */
758         switch (data[(*packet_size)++]) {
759         case 0x01: /* See RFC2440 for these numbers and their mappings */
760                 /* Choose MD5 */
761                 /* salt - ECRYPTFS_SALT_SIZE bytes */
762                 memcpy((*new_auth_tok)->token.password.salt,
763                        &data[(*packet_size)], ECRYPTFS_SALT_SIZE);
764                 (*packet_size) += ECRYPTFS_SALT_SIZE;
765
766                 /* This conversion was taken straight from RFC2440 */
767                 /* number of hash iterations - one byte */
768                 (*new_auth_tok)->token.password.hash_iterations =
769                         ((u32) 16 + (data[(*packet_size)] & 15))
770                                 << ((data[(*packet_size)] >> 4) + 6);
771                 (*packet_size)++;
772
773                 /* encrypted session key -
774                  *   (body_size-5-ECRYPTFS_SALT_SIZE) bytes */
775                 memcpy((*new_auth_tok)->session_key.encrypted_key,
776                        &data[(*packet_size)],
777                        (*new_auth_tok)->session_key.encrypted_key_size);
778                 (*packet_size) +=
779                         (*new_auth_tok)->session_key.encrypted_key_size;
780                 (*new_auth_tok)->session_key.flags &=
781                         ~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
782                 (*new_auth_tok)->session_key.flags |=
783                         ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
784                 (*new_auth_tok)->token.password.hash_algo = 0x01;
785                 break;
786         default:
787                 ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: "
788                                 "[%d]\n", data[(*packet_size) - 1]);
789                 rc = -ENOSYS;
790                 goto out_free;
791         }
792         (*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;
793         /* TODO: Parametarize; we might actually want userspace to
794          * decrypt the session key. */
795         (*new_auth_tok)->session_key.flags &=
796                             ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
797         (*new_auth_tok)->session_key.flags &=
798                             ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
799         list_add(&auth_tok_list_item->list, auth_tok_list);
800         goto out;
801 out_free:
802         (*new_auth_tok) = NULL;
803         memset(auth_tok_list_item, 0,
804                sizeof(struct ecryptfs_auth_tok_list_item));
805         kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
806                         auth_tok_list_item);
807 out:
808         if (rc)
809                 (*packet_size) = 0;
810         return rc;
811 }
812
813 /**
814  * parse_tag_11_packet
815  * @data: The raw bytes of the packet
816  * @contents: This function writes the data contents of the literal
817  *            packet into this memory location
818  * @max_contents_bytes: The maximum number of bytes that this function
819  *                      is allowed to write into contents
820  * @tag_11_contents_size: This function writes the size of the parsed
821  *                        contents into this memory location; zero on
822  *                        error
823  * @packet_size: This function writes the size of the parsed packet
824  *               into this memory location; zero on error
825  * @max_packet_size: maximum number of bytes to parse
826  *
827  * Returns zero on success; non-zero on error.
828  */
829 static int
830 parse_tag_11_packet(unsigned char *data, unsigned char *contents,
831                     size_t max_contents_bytes, size_t *tag_11_contents_size,
832                     size_t *packet_size, size_t max_packet_size)
833 {
834         size_t body_size;
835         size_t length_size;
836         int rc = 0;
837
838         (*packet_size) = 0;
839         (*tag_11_contents_size) = 0;
840
841         /* check that:
842          *   one byte for the Tag 11 ID flag
843          *   two bytes for the Tag 11 length
844          * do not exceed the maximum_packet_size
845          */
846         if (unlikely((*packet_size) + 3 > max_packet_size)) {
847                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
848                 rc = -EINVAL;
849                 goto out;
850         }
851
852         /* check for Tag 11 identifyer - one byte */
853         if (data[(*packet_size)++] != ECRYPTFS_TAG_11_PACKET_TYPE) {
854                 ecryptfs_printk(KERN_WARNING,
855                                 "Invalid tag 11 packet format\n");
856                 rc = -EINVAL;
857                 goto out;
858         }
859
860         /* get Tag 11 content length - one or two bytes */
861         rc = parse_packet_length(&data[(*packet_size)], &body_size,
862                                  &length_size);
863         if (rc) {
864                 ecryptfs_printk(KERN_WARNING,
865                                 "Invalid tag 11 packet format\n");
866                 goto out;
867         }
868         (*packet_size) += length_size;
869
870         if (body_size < 13) {
871                 ecryptfs_printk(KERN_WARNING, "Invalid body size ([%d])\n",
872                                 body_size);
873                 rc = -EINVAL;
874                 goto out;
875         }
876         /* We have 13 bytes of surrounding packet values */
877         (*tag_11_contents_size) = (body_size - 13);
878
879         /* now we know the length of the remainting Tag 11 packet size:
880          *   14 fix bytes for: special flag one, special flag two,
881          *                     12 skipped bytes
882          *   body_size bytes minus the stuff above is the Tag 11 content
883          */
884         /* FIXME why is the body size one byte smaller than the actual
885          * size of the body?
886          * this seems to be an error here as well as in
887          * write_tag_11_packet() */
888         if (unlikely((*packet_size) + body_size + 1 > max_packet_size)) {
889                 ecryptfs_printk(KERN_ERR, "Packet size exceeds max\n");
890                 rc = -EINVAL;
891                 goto out;
892         }
893
894         /* special flag one - one byte */
895         if (data[(*packet_size)++] != 0x62) {
896                 ecryptfs_printk(KERN_WARNING, "Unrecognizable packet\n");
897                 rc = -EINVAL;
898                 goto out;
899         }
900
901         /* special flag two - one byte */
902         if (data[(*packet_size)++] != 0x08) {
903                 ecryptfs_printk(KERN_WARNING, "Unrecognizable packet\n");
904                 rc = -EINVAL;
905                 goto out;
906         }
907
908         /* skip the next 12 bytes */
909         (*packet_size) += 12; /* We don't care about the filename or
910                                * the timestamp */
911
912         /* get the Tag 11 contents - tag_11_contents_size bytes */
913         memcpy(contents, &data[(*packet_size)], (*tag_11_contents_size));
914         (*packet_size) += (*tag_11_contents_size);
915
916 out:
917         if (rc) {
918                 (*packet_size) = 0;
919                 (*tag_11_contents_size) = 0;
920         }
921         return rc;
922 }
923
924 /**
925  * decrypt_session_key - Decrypt the session key with the given auth_tok.
926  *
927  * Returns Zero on success; non-zero error otherwise.
928  */
929 static int decrypt_session_key(struct ecryptfs_auth_tok *auth_tok,
930                                struct ecryptfs_crypt_stat *crypt_stat)
931 {
932         struct ecryptfs_password *password_s_ptr;
933         struct scatterlist src_sg[2], dst_sg[2];
934         struct mutex *tfm_mutex = NULL;
935         char *encrypted_session_key;
936         char *session_key;
937         struct blkcipher_desc desc = {
938                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
939         };
940         int rc = 0;
941
942         password_s_ptr = &auth_tok->token.password;
943         if (password_s_ptr->flags & ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET)
944                 ecryptfs_printk(KERN_DEBUG, "Session key encryption key "
945                                 "set; skipping key generation\n");
946         ecryptfs_printk(KERN_DEBUG, "Session key encryption key (size [%d])"
947                         ":\n",
948                         password_s_ptr->session_key_encryption_key_bytes);
949         if (ecryptfs_verbosity > 0)
950                 ecryptfs_dump_hex(password_s_ptr->session_key_encryption_key,
951                                   password_s_ptr->
952                                   session_key_encryption_key_bytes);
953         if (!strcmp(crypt_stat->cipher,
954                     crypt_stat->mount_crypt_stat->global_default_cipher_name)
955             && crypt_stat->mount_crypt_stat->global_key_tfm) {
956                 desc.tfm = crypt_stat->mount_crypt_stat->global_key_tfm;
957                 tfm_mutex = &crypt_stat->mount_crypt_stat->global_key_tfm_mutex;
958         } else {
959                 char *full_alg_name;
960
961                 rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name,
962                                                             crypt_stat->cipher,
963                                                             "ecb");
964                 if (rc)
965                         goto out;
966                 desc.tfm = crypto_alloc_blkcipher(full_alg_name, 0,
967                                                   CRYPTO_ALG_ASYNC);
968                 kfree(full_alg_name);
969                 if (IS_ERR(desc.tfm)) {
970                         rc = PTR_ERR(desc.tfm);
971                         printk(KERN_ERR "Error allocating crypto context; "
972                                "rc = [%d]\n", rc);
973                         goto out;
974                 }
975                 crypto_blkcipher_set_flags(desc.tfm, CRYPTO_TFM_REQ_WEAK_KEY);
976         }
977         if (tfm_mutex)
978                 mutex_lock(tfm_mutex);
979         rc = crypto_blkcipher_setkey(desc.tfm,
980                                      password_s_ptr->session_key_encryption_key,
981                                      crypt_stat->key_size);
982         if (rc < 0) {
983                 printk(KERN_ERR "Error setting key for crypto context\n");
984                 rc = -EINVAL;
985                 goto out_free_tfm;
986         }
987         /* TODO: virt_to_scatterlist */
988         encrypted_session_key = (char *)__get_free_page(GFP_KERNEL);
989         if (!encrypted_session_key) {
990                 ecryptfs_printk(KERN_ERR, "Out of memory\n");
991                 rc = -ENOMEM;
992                 goto out_free_tfm;
993         }
994         session_key = (char *)__get_free_page(GFP_KERNEL);
995         if (!session_key) {
996                 kfree(encrypted_session_key);
997                 ecryptfs_printk(KERN_ERR, "Out of memory\n");
998                 rc = -ENOMEM;
999                 goto out_free_tfm;
1000         }
1001         memcpy(encrypted_session_key, auth_tok->session_key.encrypted_key,
1002                auth_tok->session_key.encrypted_key_size);
1003         src_sg[0].page = virt_to_page(encrypted_session_key);
1004         src_sg[0].offset = 0;
1005         BUG_ON(auth_tok->session_key.encrypted_key_size > PAGE_CACHE_SIZE);
1006         src_sg[0].length = auth_tok->session_key.encrypted_key_size;
1007         dst_sg[0].page = virt_to_page(session_key);
1008         dst_sg[0].offset = 0;
1009         auth_tok->session_key.decrypted_key_size =
1010             auth_tok->session_key.encrypted_key_size;
1011         dst_sg[0].length = auth_tok->session_key.encrypted_key_size;
1012         rc = crypto_blkcipher_decrypt(&desc, dst_sg, src_sg,
1013                                       auth_tok->session_key.encrypted_key_size);
1014         if (rc) {
1015                 printk(KERN_ERR "Error decrypting; rc = [%d]\n", rc);
1016                 goto out_free_memory;
1017         }
1018         auth_tok->session_key.decrypted_key_size =
1019             auth_tok->session_key.encrypted_key_size;
1020         memcpy(auth_tok->session_key.decrypted_key, session_key,
1021                auth_tok->session_key.decrypted_key_size);
1022         auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1023         memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
1024                auth_tok->session_key.decrypted_key_size);
1025         crypt_stat->flags |= ECRYPTFS_KEY_VALID;
1026         ecryptfs_printk(KERN_DEBUG, "Decrypted session key:\n");
1027         if (ecryptfs_verbosity > 0)
1028                 ecryptfs_dump_hex(crypt_stat->key,
1029                                   crypt_stat->key_size);
1030 out_free_memory:
1031         memset(encrypted_session_key, 0, PAGE_CACHE_SIZE);
1032         free_page((unsigned long)encrypted_session_key);
1033         memset(session_key, 0, PAGE_CACHE_SIZE);
1034         free_page((unsigned long)session_key);
1035 out_free_tfm:
1036         if (tfm_mutex)
1037                 mutex_unlock(tfm_mutex);
1038         else
1039                 crypto_free_blkcipher(desc.tfm);
1040 out:
1041         return rc;
1042 }
1043
1044 /**
1045  * ecryptfs_parse_packet_set
1046  * @dest: The header page in memory
1047  * @version: Version of file format, to guide parsing behavior
1048  *
1049  * Get crypt_stat to have the file's session key if the requisite key
1050  * is available to decrypt the session key.
1051  *
1052  * Returns Zero if a valid authentication token was retrieved and
1053  * processed; negative value for file not encrypted or for error
1054  * conditions.
1055  */
1056 int ecryptfs_parse_packet_set(struct ecryptfs_crypt_stat *crypt_stat,
1057                               unsigned char *src,
1058                               struct dentry *ecryptfs_dentry)
1059 {
1060         size_t i = 0;
1061         size_t found_auth_tok = 0;
1062         size_t next_packet_is_auth_tok_packet;
1063         char sig[ECRYPTFS_SIG_SIZE_HEX];
1064         struct list_head auth_tok_list;
1065         struct list_head *walker;
1066         struct ecryptfs_auth_tok *chosen_auth_tok = NULL;
1067         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1068                 &ecryptfs_superblock_to_private(
1069                         ecryptfs_dentry->d_sb)->mount_crypt_stat;
1070         struct ecryptfs_auth_tok *candidate_auth_tok = NULL;
1071         size_t packet_size;
1072         struct ecryptfs_auth_tok *new_auth_tok;
1073         unsigned char sig_tmp_space[ECRYPTFS_SIG_SIZE];
1074         size_t tag_11_contents_size;
1075         size_t tag_11_packet_size;
1076         int rc = 0;
1077
1078         INIT_LIST_HEAD(&auth_tok_list);
1079         /* Parse the header to find as many packets as we can, these will be
1080          * added the our &auth_tok_list */
1081         next_packet_is_auth_tok_packet = 1;
1082         while (next_packet_is_auth_tok_packet) {
1083                 size_t max_packet_size = ((PAGE_CACHE_SIZE - 8) - i);
1084
1085                 switch (src[i]) {
1086                 case ECRYPTFS_TAG_3_PACKET_TYPE:
1087                         rc = parse_tag_3_packet(crypt_stat,
1088                                                 (unsigned char *)&src[i],
1089                                                 &auth_tok_list, &new_auth_tok,
1090                                                 &packet_size, max_packet_size);
1091                         if (rc) {
1092                                 ecryptfs_printk(KERN_ERR, "Error parsing "
1093                                                 "tag 3 packet\n");
1094                                 rc = -EIO;
1095                                 goto out_wipe_list;
1096                         }
1097                         i += packet_size;
1098                         rc = parse_tag_11_packet((unsigned char *)&src[i],
1099                                                  sig_tmp_space,
1100                                                  ECRYPTFS_SIG_SIZE,
1101                                                  &tag_11_contents_size,
1102                                                  &tag_11_packet_size,
1103                                                  max_packet_size);
1104                         if (rc) {
1105                                 ecryptfs_printk(KERN_ERR, "No valid "
1106                                                 "(ecryptfs-specific) literal "
1107                                                 "packet containing "
1108                                                 "authentication token "
1109                                                 "signature found after "
1110                                                 "tag 3 packet\n");
1111                                 rc = -EIO;
1112                                 goto out_wipe_list;
1113                         }
1114                         i += tag_11_packet_size;
1115                         if (ECRYPTFS_SIG_SIZE != tag_11_contents_size) {
1116                                 ecryptfs_printk(KERN_ERR, "Expected "
1117                                                 "signature of size [%d]; "
1118                                                 "read size [%d]\n",
1119                                                 ECRYPTFS_SIG_SIZE,
1120                                                 tag_11_contents_size);
1121                                 rc = -EIO;
1122                                 goto out_wipe_list;
1123                         }
1124                         ecryptfs_to_hex(new_auth_tok->token.password.signature,
1125                                         sig_tmp_space, tag_11_contents_size);
1126                         new_auth_tok->token.password.signature[
1127                                 ECRYPTFS_PASSWORD_SIG_SIZE] = '\0';
1128                         crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1129                         break;
1130                 case ECRYPTFS_TAG_1_PACKET_TYPE:
1131                         rc = parse_tag_1_packet(crypt_stat,
1132                                                 (unsigned char *)&src[i],
1133                                                 &auth_tok_list, &new_auth_tok,
1134                                                 &packet_size, max_packet_size);
1135                         if (rc) {
1136                                 ecryptfs_printk(KERN_ERR, "Error parsing "
1137                                                 "tag 1 packet\n");
1138                                 rc = -EIO;
1139                                 goto out_wipe_list;
1140                         }
1141                         i += packet_size;
1142                         crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1143                         break;
1144                 case ECRYPTFS_TAG_11_PACKET_TYPE:
1145                         ecryptfs_printk(KERN_WARNING, "Invalid packet set "
1146                                         "(Tag 11 not allowed by itself)\n");
1147                         rc = -EIO;
1148                         goto out_wipe_list;
1149                         break;
1150                 default:
1151                         ecryptfs_printk(KERN_DEBUG, "No packet at offset "
1152                                         "[%d] of the file header; hex value of "
1153                                         "character is [0x%.2x]\n", i, src[i]);
1154                         next_packet_is_auth_tok_packet = 0;
1155                 }
1156         }
1157         if (list_empty(&auth_tok_list)) {
1158                 rc = -EINVAL; /* Do not support non-encrypted files in
1159                                * the 0.1 release */
1160                 goto out;
1161         }
1162         /* If we have a global auth tok, then we should try to use
1163          * it */
1164         if (mount_crypt_stat->global_auth_tok) {
1165                 memcpy(sig, mount_crypt_stat->global_auth_tok_sig,
1166                        ECRYPTFS_SIG_SIZE_HEX);
1167                 chosen_auth_tok = mount_crypt_stat->global_auth_tok;
1168         } else
1169                 BUG(); /* We should always have a global auth tok in
1170                         * the 0.1 release */
1171         /* Scan list to see if our chosen_auth_tok works */
1172         list_for_each(walker, &auth_tok_list) {
1173                 struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1174                 auth_tok_list_item =
1175                     list_entry(walker, struct ecryptfs_auth_tok_list_item,
1176                                list);
1177                 candidate_auth_tok = &auth_tok_list_item->auth_tok;
1178                 if (unlikely(ecryptfs_verbosity > 0)) {
1179                         ecryptfs_printk(KERN_DEBUG,
1180                                         "Considering cadidate auth tok:\n");
1181                         ecryptfs_dump_auth_tok(candidate_auth_tok);
1182                 }
1183                 /* TODO: Replace ECRYPTFS_SIG_SIZE_HEX w/ dynamic value */
1184                 if (candidate_auth_tok->token_type == ECRYPTFS_PASSWORD
1185                     && !strncmp(candidate_auth_tok->token.password.signature,
1186                                 sig, ECRYPTFS_SIG_SIZE_HEX)) {
1187                         found_auth_tok = 1;
1188                         goto leave_list;
1189                         /* TODO: Transfer the common salt into the
1190                          * crypt_stat salt */
1191                 } else if ((candidate_auth_tok->token_type
1192                             == ECRYPTFS_PRIVATE_KEY)
1193                            && !strncmp(candidate_auth_tok->token.private_key.signature,
1194                                      sig, ECRYPTFS_SIG_SIZE_HEX)) {
1195                         found_auth_tok = 1;
1196                         goto leave_list;
1197                 }
1198         }
1199         if (!found_auth_tok) {
1200                 ecryptfs_printk(KERN_ERR, "Could not find authentication "
1201                                 "token on temporary list for sig [%.*s]\n",
1202                                 ECRYPTFS_SIG_SIZE_HEX, sig);
1203                 rc = -EIO;
1204                 goto out_wipe_list;
1205         }
1206 leave_list:
1207         rc = -ENOTSUPP;
1208         if (candidate_auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
1209                 memcpy(&(candidate_auth_tok->token.private_key),
1210                        &(chosen_auth_tok->token.private_key),
1211                        sizeof(struct ecryptfs_private_key));
1212                 rc = decrypt_pki_encrypted_session_key(mount_crypt_stat,
1213                                                        candidate_auth_tok,
1214                                                        crypt_stat);
1215         } else if (candidate_auth_tok->token_type == ECRYPTFS_PASSWORD) {
1216                 memcpy(&(candidate_auth_tok->token.password),
1217                        &(chosen_auth_tok->token.password),
1218                        sizeof(struct ecryptfs_password));
1219                 rc = decrypt_session_key(candidate_auth_tok, crypt_stat);
1220         }
1221         if (rc) {
1222                 ecryptfs_printk(KERN_ERR, "Error decrypting the "
1223                                 "session key; rc = [%d]\n", rc);
1224                 goto out_wipe_list;
1225         }
1226         rc = ecryptfs_compute_root_iv(crypt_stat);
1227         if (rc) {
1228                 ecryptfs_printk(KERN_ERR, "Error computing "
1229                                 "the root IV\n");
1230                 goto out_wipe_list;
1231         }
1232         rc = ecryptfs_init_crypt_ctx(crypt_stat);
1233         if (rc) {
1234                 ecryptfs_printk(KERN_ERR, "Error initializing crypto "
1235                                 "context for cipher [%s]; rc = [%d]\n",
1236                                 crypt_stat->cipher, rc);
1237         }
1238 out_wipe_list:
1239         wipe_auth_tok_list(&auth_tok_list);
1240 out:
1241         return rc;
1242 }
1243 static int
1244 pki_encrypt_session_key(struct ecryptfs_auth_tok *auth_tok,
1245                         struct ecryptfs_crypt_stat *crypt_stat,
1246                         struct ecryptfs_key_record *key_rec)
1247 {
1248         struct ecryptfs_msg_ctx *msg_ctx = NULL;
1249         char *netlink_payload;
1250         size_t netlink_payload_length;
1251         struct ecryptfs_message *msg;
1252         int rc;
1253
1254         rc = write_tag_66_packet(auth_tok->token.private_key.signature,
1255                                  ecryptfs_code_for_cipher_string(crypt_stat),
1256                                  crypt_stat, &netlink_payload,
1257                                  &netlink_payload_length);
1258         if (rc) {
1259                 ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet\n");
1260                 goto out;
1261         }
1262         rc = ecryptfs_send_message(ecryptfs_transport, netlink_payload,
1263                                    netlink_payload_length, &msg_ctx);
1264         if (rc) {
1265                 ecryptfs_printk(KERN_ERR, "Error sending netlink message\n");
1266                 goto out;
1267         }
1268         rc = ecryptfs_wait_for_response(msg_ctx, &msg);
1269         if (rc) {
1270                 ecryptfs_printk(KERN_ERR, "Failed to receive tag 67 packet "
1271                                 "from the user space daemon\n");
1272                 rc = -EIO;
1273                 goto out;
1274         }
1275         rc = parse_tag_67_packet(key_rec, msg);
1276         if (rc)
1277                 ecryptfs_printk(KERN_ERR, "Error parsing tag 67 packet\n");
1278         kfree(msg);
1279 out:
1280         if (netlink_payload)
1281                 kfree(netlink_payload);
1282         return rc;
1283 }
1284 /**
1285  * write_tag_1_packet - Write an RFC2440-compatible tag 1 (public key) packet
1286  * @dest: Buffer into which to write the packet
1287  * @max: Maximum number of bytes that can be writtn
1288  * @packet_size: This function will write the number of bytes that end
1289  *               up constituting the packet; set to zero on error
1290  *
1291  * Returns zero on success; non-zero on error.
1292  */
1293 static int
1294 write_tag_1_packet(char *dest, size_t max, struct ecryptfs_auth_tok *auth_tok,
1295                    struct ecryptfs_crypt_stat *crypt_stat,
1296                    struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
1297                    struct ecryptfs_key_record *key_rec, size_t *packet_size)
1298 {
1299         size_t i;
1300         size_t encrypted_session_key_valid = 0;
1301         size_t key_rec_size;
1302         size_t packet_size_length;
1303         int rc = 0;
1304
1305         (*packet_size) = 0;
1306         ecryptfs_from_hex(key_rec->sig, auth_tok->token.private_key.signature,
1307                           ECRYPTFS_SIG_SIZE);
1308         encrypted_session_key_valid = 0;
1309         for (i = 0; i < crypt_stat->key_size; i++)
1310                 encrypted_session_key_valid |=
1311                         auth_tok->session_key.encrypted_key[i];
1312         if (encrypted_session_key_valid) {
1313                 memcpy(key_rec->enc_key,
1314                        auth_tok->session_key.encrypted_key,
1315                        auth_tok->session_key.encrypted_key_size);
1316                 goto encrypted_session_key_set;
1317         }
1318         if (auth_tok->session_key.encrypted_key_size == 0)
1319                 auth_tok->session_key.encrypted_key_size =
1320                         auth_tok->token.private_key.key_size;
1321         rc = pki_encrypt_session_key(auth_tok, crypt_stat, key_rec);
1322         if (rc) {
1323                 ecryptfs_printk(KERN_ERR, "Failed to encrypt session key "
1324                                 "via a pki");
1325                 goto out;
1326         }
1327         if (ecryptfs_verbosity > 0) {
1328                 ecryptfs_printk(KERN_DEBUG, "Encrypted key:\n");
1329                 ecryptfs_dump_hex(key_rec->enc_key, key_rec->enc_key_size);
1330         }
1331 encrypted_session_key_set:
1332         /* Now we have a valid key_rec.  Append it to the
1333          * key_rec set. */
1334         key_rec_size = (sizeof(struct ecryptfs_key_record)
1335                         - ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES
1336                         + (key_rec->enc_key_size));
1337         /* TODO: Include a packet size limit as a parameter to this
1338          * function once we have multi-packet headers (for versions
1339          * later than 0.1 */
1340         if (key_rec_size >= ECRYPTFS_MAX_KEYSET_SIZE) {
1341                 ecryptfs_printk(KERN_ERR, "Keyset too large\n");
1342                 rc = -EINVAL;
1343                 goto out;
1344         }
1345         /*              ***** TAG 1 Packet Format *****
1346          *    | version number                     | 1 byte       |
1347          *    | key ID                             | 8 bytes      |
1348          *    | public key algorithm               | 1 byte       |
1349          *    | encrypted session key              | arbitrary    |
1350          */
1351         if ((0x02 + ECRYPTFS_SIG_SIZE + key_rec->enc_key_size) >= max) {
1352                 ecryptfs_printk(KERN_ERR,
1353                                 "Authentication token is too large\n");
1354                 rc = -EINVAL;
1355                 goto out;
1356         }
1357         dest[(*packet_size)++] = ECRYPTFS_TAG_1_PACKET_TYPE;
1358         /* This format is inspired by OpenPGP; see RFC 2440
1359          * packet tag 1 */
1360         rc = write_packet_length(&dest[(*packet_size)],
1361                                  (0x02 + ECRYPTFS_SIG_SIZE +
1362                                  key_rec->enc_key_size),
1363                                  &packet_size_length);
1364         if (rc) {
1365                 ecryptfs_printk(KERN_ERR, "Error generating tag 1 packet "
1366                                 "header; cannot generate packet length\n");
1367                 goto out;
1368         }
1369         (*packet_size) += packet_size_length;
1370         dest[(*packet_size)++] = 0x03; /* version 3 */
1371         memcpy(&dest[(*packet_size)], key_rec->sig, ECRYPTFS_SIG_SIZE);
1372         (*packet_size) += ECRYPTFS_SIG_SIZE;
1373         dest[(*packet_size)++] = RFC2440_CIPHER_RSA;
1374         memcpy(&dest[(*packet_size)], key_rec->enc_key,
1375                key_rec->enc_key_size);
1376         (*packet_size) += key_rec->enc_key_size;
1377 out:
1378         if (rc)
1379                 (*packet_size) = 0;
1380         return rc;
1381 }
1382
1383 /**
1384  * write_tag_11_packet
1385  * @dest: Target into which Tag 11 packet is to be written
1386  * @max: Maximum packet length
1387  * @contents: Byte array of contents to copy in
1388  * @contents_length: Number of bytes in contents
1389  * @packet_length: Length of the Tag 11 packet written; zero on error
1390  *
1391  * Returns zero on success; non-zero on error.
1392  */
1393 static int
1394 write_tag_11_packet(char *dest, int max, char *contents, size_t contents_length,
1395                     size_t *packet_length)
1396 {
1397         size_t packet_size_length;
1398         int rc = 0;
1399
1400         (*packet_length) = 0;
1401         if ((13 + contents_length) > max) {
1402                 rc = -EINVAL;
1403                 ecryptfs_printk(KERN_ERR, "Packet length larger than "
1404                                 "maximum allowable\n");
1405                 goto out;
1406         }
1407         /* General packet header */
1408         /* Packet tag */
1409         dest[(*packet_length)++] = ECRYPTFS_TAG_11_PACKET_TYPE;
1410         /* Packet length */
1411         rc = write_packet_length(&dest[(*packet_length)],
1412                                  (13 + contents_length), &packet_size_length);
1413         if (rc) {
1414                 ecryptfs_printk(KERN_ERR, "Error generating tag 11 packet "
1415                                 "header; cannot generate packet length\n");
1416                 goto out;
1417         }
1418         (*packet_length) += packet_size_length;
1419         /* Tag 11 specific */
1420         /* One-octet field that describes how the data is formatted */
1421         dest[(*packet_length)++] = 0x62; /* binary data */
1422         /* One-octet filename length followed by filename */
1423         dest[(*packet_length)++] = 8;
1424         memcpy(&dest[(*packet_length)], "_CONSOLE", 8);
1425         (*packet_length) += 8;
1426         /* Four-octet number indicating modification date */
1427         memset(&dest[(*packet_length)], 0x00, 4);
1428         (*packet_length) += 4;
1429         /* Remainder is literal data */
1430         memcpy(&dest[(*packet_length)], contents, contents_length);
1431         (*packet_length) += contents_length;
1432  out:
1433         if (rc)
1434                 (*packet_length) = 0;
1435         return rc;
1436 }
1437
1438 /**
1439  * write_tag_3_packet
1440  * @dest: Buffer into which to write the packet
1441  * @max: Maximum number of bytes that can be written
1442  * @auth_tok: Authentication token
1443  * @crypt_stat: The cryptographic context
1444  * @key_rec: encrypted key
1445  * @packet_size: This function will write the number of bytes that end
1446  *               up constituting the packet; set to zero on error
1447  *
1448  * Returns zero on success; non-zero on error.
1449  */
1450 static int
1451 write_tag_3_packet(char *dest, size_t max, struct ecryptfs_auth_tok *auth_tok,
1452                    struct ecryptfs_crypt_stat *crypt_stat,
1453                    struct ecryptfs_key_record *key_rec, size_t *packet_size)
1454 {
1455         size_t i;
1456         size_t encrypted_session_key_valid = 0;
1457         char session_key_encryption_key[ECRYPTFS_MAX_KEY_BYTES];
1458         struct scatterlist dest_sg[2];
1459         struct scatterlist src_sg[2];
1460         struct mutex *tfm_mutex = NULL;
1461         size_t key_rec_size;
1462         size_t packet_size_length;
1463         size_t cipher_code;
1464         struct blkcipher_desc desc = {
1465                 .tfm = NULL,
1466                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
1467         };
1468         int rc = 0;
1469
1470         (*packet_size) = 0;
1471         ecryptfs_from_hex(key_rec->sig, auth_tok->token.password.signature,
1472                           ECRYPTFS_SIG_SIZE);
1473         encrypted_session_key_valid = 0;
1474         for (i = 0; i < crypt_stat->key_size; i++)
1475                 encrypted_session_key_valid |=
1476                         auth_tok->session_key.encrypted_key[i];
1477         if (encrypted_session_key_valid) {
1478                 memcpy(key_rec->enc_key,
1479                        auth_tok->session_key.encrypted_key,
1480                        auth_tok->session_key.encrypted_key_size);
1481                 goto encrypted_session_key_set;
1482         }
1483         if (auth_tok->session_key.encrypted_key_size == 0)
1484                 auth_tok->session_key.encrypted_key_size =
1485                         crypt_stat->key_size;
1486         if (crypt_stat->key_size == 24
1487             && strcmp("aes", crypt_stat->cipher) == 0) {
1488                 memset((crypt_stat->key + 24), 0, 8);
1489                 auth_tok->session_key.encrypted_key_size = 32;
1490         }
1491         key_rec->enc_key_size =
1492                 auth_tok->session_key.encrypted_key_size;
1493         if (auth_tok->token.password.flags &
1494             ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET) {
1495                 ecryptfs_printk(KERN_DEBUG, "Using previously generated "
1496                                 "session key encryption key of size [%d]\n",
1497                                 auth_tok->token.password.
1498                                 session_key_encryption_key_bytes);
1499                 memcpy(session_key_encryption_key,
1500                        auth_tok->token.password.session_key_encryption_key,
1501                        crypt_stat->key_size);
1502                 ecryptfs_printk(KERN_DEBUG,
1503                                 "Cached session key " "encryption key: \n");
1504                 if (ecryptfs_verbosity > 0)
1505                         ecryptfs_dump_hex(session_key_encryption_key, 16);
1506         }
1507         if (unlikely(ecryptfs_verbosity > 0)) {
1508                 ecryptfs_printk(KERN_DEBUG, "Session key encryption key:\n");
1509                 ecryptfs_dump_hex(session_key_encryption_key, 16);
1510         }
1511         rc = virt_to_scatterlist(crypt_stat->key,
1512                                  key_rec->enc_key_size, src_sg, 2);
1513         if (!rc) {
1514                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
1515                                 "for crypt_stat session key\n");
1516                 rc = -ENOMEM;
1517                 goto out;
1518         }
1519         rc = virt_to_scatterlist(key_rec->enc_key,
1520                                  key_rec->enc_key_size, dest_sg, 2);
1521         if (!rc) {
1522                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
1523                                 "for crypt_stat encrypted session key\n");
1524                 rc = -ENOMEM;
1525                 goto out;
1526         }
1527         if (!strcmp(crypt_stat->cipher,
1528                     crypt_stat->mount_crypt_stat->global_default_cipher_name)
1529             && crypt_stat->mount_crypt_stat->global_key_tfm) {
1530                 desc.tfm = crypt_stat->mount_crypt_stat->global_key_tfm;
1531                 tfm_mutex = &crypt_stat->mount_crypt_stat->global_key_tfm_mutex;
1532         } else {
1533                 char *full_alg_name;
1534
1535                 rc = ecryptfs_crypto_api_algify_cipher_name(&full_alg_name,
1536                                                             crypt_stat->cipher,
1537                                                             "ecb");
1538                 if (rc)
1539                         goto out;
1540                 desc.tfm = crypto_alloc_blkcipher(full_alg_name, 0,
1541                                                   CRYPTO_ALG_ASYNC);
1542                 kfree(full_alg_name);
1543                 if (IS_ERR(desc.tfm)) {
1544                         rc = PTR_ERR(desc.tfm);
1545                         ecryptfs_printk(KERN_ERR, "Could not initialize crypto "
1546                                         "context for cipher [%s]; rc = [%d]\n",
1547                                         crypt_stat->cipher, rc);
1548                         goto out;
1549                 }
1550                 crypto_blkcipher_set_flags(desc.tfm, CRYPTO_TFM_REQ_WEAK_KEY);
1551         }
1552         if (tfm_mutex)
1553                 mutex_lock(tfm_mutex);
1554         rc = crypto_blkcipher_setkey(desc.tfm, session_key_encryption_key,
1555                                      crypt_stat->key_size);
1556         if (rc < 0) {
1557                 if (tfm_mutex)
1558                         mutex_unlock(tfm_mutex);
1559                 ecryptfs_printk(KERN_ERR, "Error setting key for crypto "
1560                                 "context; rc = [%d]\n", rc);
1561                 goto out;
1562         }
1563         rc = 0;
1564         ecryptfs_printk(KERN_DEBUG, "Encrypting [%d] bytes of the key\n",
1565                         crypt_stat->key_size);
1566         rc = crypto_blkcipher_encrypt(&desc, dest_sg, src_sg,
1567                                       (*key_rec).enc_key_size);
1568         if (rc) {
1569                 printk(KERN_ERR "Error encrypting; rc = [%d]\n", rc);
1570                 goto out;
1571         }
1572         if (tfm_mutex)
1573                 mutex_unlock(tfm_mutex);
1574         ecryptfs_printk(KERN_DEBUG, "This should be the encrypted key:\n");
1575         if (ecryptfs_verbosity > 0)
1576                 ecryptfs_dump_hex(key_rec->enc_key,
1577                                   key_rec->enc_key_size);
1578 encrypted_session_key_set:
1579         /* Now we have a valid key_rec.  Append it to the
1580          * key_rec set. */
1581         key_rec_size = (sizeof(struct ecryptfs_key_record)
1582                         - ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES
1583                         + (key_rec->enc_key_size));
1584         /* TODO: Include a packet size limit as a parameter to this
1585          * function once we have multi-packet headers (for versions
1586          * later than 0.1 */
1587         if (key_rec_size >= ECRYPTFS_MAX_KEYSET_SIZE) {
1588                 ecryptfs_printk(KERN_ERR, "Keyset too large\n");
1589                 rc = -EINVAL;
1590                 goto out;
1591         }
1592         /* TODO: Packet size limit */
1593         /* We have 5 bytes of surrounding packet data */
1594         if ((0x05 + ECRYPTFS_SALT_SIZE
1595              + key_rec->enc_key_size) >= max) {
1596                 ecryptfs_printk(KERN_ERR, "Authentication token is too "
1597                                 "large\n");
1598                 rc = -EINVAL;
1599                 goto out;
1600         }
1601         /* This format is inspired by OpenPGP; see RFC 2440
1602          * packet tag 3 */
1603         dest[(*packet_size)++] = ECRYPTFS_TAG_3_PACKET_TYPE;
1604         /* ver+cipher+s2k+hash+salt+iter+enc_key */
1605         rc = write_packet_length(&dest[(*packet_size)],
1606                                  (0x05 + ECRYPTFS_SALT_SIZE
1607                                   + key_rec->enc_key_size),
1608                                  &packet_size_length);
1609         if (rc) {
1610                 ecryptfs_printk(KERN_ERR, "Error generating tag 3 packet "
1611                                 "header; cannot generate packet length\n");
1612                 goto out;
1613         }
1614         (*packet_size) += packet_size_length;
1615         dest[(*packet_size)++] = 0x04; /* version 4 */
1616         cipher_code = ecryptfs_code_for_cipher_string(crypt_stat);
1617         if (cipher_code == 0) {
1618                 ecryptfs_printk(KERN_WARNING, "Unable to generate code for "
1619                                 "cipher [%s]\n", crypt_stat->cipher);
1620                 rc = -EINVAL;
1621                 goto out;
1622         }
1623         dest[(*packet_size)++] = cipher_code;
1624         dest[(*packet_size)++] = 0x03;  /* S2K */
1625         dest[(*packet_size)++] = 0x01;  /* MD5 (TODO: parameterize) */
1626         memcpy(&dest[(*packet_size)], auth_tok->token.password.salt,
1627                ECRYPTFS_SALT_SIZE);
1628         (*packet_size) += ECRYPTFS_SALT_SIZE;   /* salt */
1629         dest[(*packet_size)++] = 0x60;  /* hash iterations (65536) */
1630         memcpy(&dest[(*packet_size)], key_rec->enc_key,
1631                key_rec->enc_key_size);
1632         (*packet_size) += key_rec->enc_key_size;
1633 out:
1634         if (desc.tfm && !tfm_mutex)
1635                 crypto_free_blkcipher(desc.tfm);
1636         if (rc)
1637                 (*packet_size) = 0;
1638         return rc;
1639 }
1640
1641 struct kmem_cache *ecryptfs_key_record_cache;
1642
1643 /**
1644  * ecryptfs_generate_key_packet_set
1645  * @dest: Virtual address from which to write the key record set
1646  * @crypt_stat: The cryptographic context from which the
1647  *              authentication tokens will be retrieved
1648  * @ecryptfs_dentry: The dentry, used to retrieve the mount crypt stat
1649  *                   for the global parameters
1650  * @len: The amount written
1651  * @max: The maximum amount of data allowed to be written
1652  *
1653  * Generates a key packet set and writes it to the virtual address
1654  * passed in.
1655  *
1656  * Returns zero on success; non-zero on error.
1657  */
1658 int
1659 ecryptfs_generate_key_packet_set(char *dest_base,
1660                                  struct ecryptfs_crypt_stat *crypt_stat,
1661                                  struct dentry *ecryptfs_dentry, size_t *len,
1662                                  size_t max)
1663 {
1664         struct ecryptfs_auth_tok *auth_tok;
1665         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1666                 &ecryptfs_superblock_to_private(
1667                         ecryptfs_dentry->d_sb)->mount_crypt_stat;
1668         size_t written;
1669         struct ecryptfs_key_record *key_rec;
1670         int rc = 0;
1671
1672         (*len) = 0;
1673         key_rec = kmem_cache_alloc(ecryptfs_key_record_cache, GFP_KERNEL);
1674         if (!key_rec) {
1675                 rc = -ENOMEM;
1676                 goto out;
1677         }
1678         if (mount_crypt_stat->global_auth_tok) {
1679                 auth_tok = mount_crypt_stat->global_auth_tok;
1680                 if (auth_tok->token_type == ECRYPTFS_PASSWORD) {
1681                         rc = write_tag_3_packet((dest_base + (*len)),
1682                                                 max, auth_tok,
1683                                                 crypt_stat, key_rec,
1684                                                 &written);
1685                         if (rc) {
1686                                 ecryptfs_printk(KERN_WARNING, "Error "
1687                                                 "writing tag 3 packet\n");
1688                                 goto out_free;
1689                         }
1690                         (*len) += written;
1691                         /* Write auth tok signature packet */
1692                         rc = write_tag_11_packet(
1693                                 (dest_base + (*len)),
1694                                 (max - (*len)),
1695                                 key_rec->sig, ECRYPTFS_SIG_SIZE, &written);
1696                         if (rc) {
1697                                 ecryptfs_printk(KERN_ERR, "Error writing "
1698                                                 "auth tok signature packet\n");
1699                                 goto out_free;
1700                         }
1701                         (*len) += written;
1702                 } else if (auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
1703                         rc = write_tag_1_packet(dest_base + (*len),
1704                                                 max, auth_tok,
1705                                                 crypt_stat,mount_crypt_stat,
1706                                                 key_rec, &written);
1707                         if (rc) {
1708                                 ecryptfs_printk(KERN_WARNING, "Error "
1709                                                 "writing tag 1 packet\n");
1710                                 goto out_free;
1711                         }
1712                         (*len) += written;
1713                 } else {
1714                         ecryptfs_printk(KERN_WARNING, "Unsupported "
1715                                         "authentication token type\n");
1716                         rc = -EINVAL;
1717                         goto out_free;
1718                 }
1719         } else
1720                 BUG();
1721         if (likely((max - (*len)) > 0)) {
1722                 dest_base[(*len)] = 0x00;
1723         } else {
1724                 ecryptfs_printk(KERN_ERR, "Error writing boundary byte\n");
1725                 rc = -EIO;
1726         }
1727
1728 out_free:
1729         kmem_cache_free(ecryptfs_key_record_cache, key_rec);
1730 out:
1731         if (rc)
1732                 (*len) = 0;
1733         return rc;
1734 }