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