682b1b2482c26a062cefeaf924787242f89612d1
[pandora-kernel.git] / fs / ecryptfs / keystore.c
1 /**
2  * eCryptfs: Linux filesystem encryption layer
3  * In-kernel key management code.  Includes functions to parse and
4  * write authentication token-related packets with the underlying
5  * file.
6  *
7  * Copyright (C) 2004-2006 International Business Machines Corp.
8  *   Author(s): Michael A. Halcrow <mhalcrow@us.ibm.com>
9  *              Michael C. Thompson <mcthomps@us.ibm.com>
10  *              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 static 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; non-zero on error
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 length. Must
110  *        have at least 5 bytes allocated.
111  * @size: The length to write.
112  * @packet_size_length: The number of bytes used to encode the packet
113  *                      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, u8 *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, u8 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 static int
400 ecryptfs_get_auth_tok_sig(char **sig, struct ecryptfs_auth_tok *auth_tok)
401 {
402         int rc = 0;
403
404         (*sig) = NULL;
405         switch (auth_tok->token_type) {
406         case ECRYPTFS_PASSWORD:
407                 (*sig) = auth_tok->token.password.signature;
408                 break;
409         case ECRYPTFS_PRIVATE_KEY:
410                 (*sig) = auth_tok->token.private_key.signature;
411                 break;
412         default:
413                 printk(KERN_ERR "Cannot get sig for auth_tok of type [%d]\n",
414                        auth_tok->token_type);
415                 rc = -EINVAL;
416         }
417         return rc;
418 }
419
420 /**
421  * decrypt_pki_encrypted_session_key - Decrypt the session key with the given auth_tok.
422  * @auth_tok: The key authentication token used to decrypt the session key
423  * @crypt_stat: The cryptographic context
424  *
425  * Returns zero on success; non-zero error otherwise.
426  */
427 static int
428 decrypt_pki_encrypted_session_key(struct ecryptfs_auth_tok *auth_tok,
429                                   struct ecryptfs_crypt_stat *crypt_stat)
430 {
431         u8 cipher_code = 0;
432         struct ecryptfs_msg_ctx *msg_ctx;
433         struct ecryptfs_message *msg = NULL;
434         char *auth_tok_sig;
435         char *netlink_message;
436         size_t netlink_message_length;
437         int rc;
438
439         rc = ecryptfs_get_auth_tok_sig(&auth_tok_sig, auth_tok);
440         if (rc) {
441                 printk(KERN_ERR "Unrecognized auth tok type: [%d]\n",
442                        auth_tok->token_type);
443                 goto out;
444         }
445         rc = write_tag_64_packet(auth_tok_sig, &(auth_tok->session_key),
446                                  &netlink_message, &netlink_message_length);
447         if (rc) {
448                 ecryptfs_printk(KERN_ERR, "Failed to write tag 64 packet");
449                 goto out;
450         }
451         rc = ecryptfs_send_message(ecryptfs_transport, netlink_message,
452                                    netlink_message_length, &msg_ctx);
453         if (rc) {
454                 ecryptfs_printk(KERN_ERR, "Error sending netlink message\n");
455                 goto out;
456         }
457         rc = ecryptfs_wait_for_response(msg_ctx, &msg);
458         if (rc) {
459                 ecryptfs_printk(KERN_ERR, "Failed to receive tag 65 packet "
460                                 "from the user space daemon\n");
461                 rc = -EIO;
462                 goto out;
463         }
464         rc = parse_tag_65_packet(&(auth_tok->session_key),
465                                  &cipher_code, msg);
466         if (rc) {
467                 printk(KERN_ERR "Failed to parse tag 65 packet; rc = [%d]\n",
468                        rc);
469                 goto out;
470         }
471         auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
472         memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
473                auth_tok->session_key.decrypted_key_size);
474         crypt_stat->key_size = auth_tok->session_key.decrypted_key_size;
475         rc = ecryptfs_cipher_code_to_string(crypt_stat->cipher, cipher_code);
476         if (rc) {
477                 ecryptfs_printk(KERN_ERR, "Cipher code [%d] is invalid\n",
478                                 cipher_code)
479                 goto out;
480         }
481         crypt_stat->flags |= ECRYPTFS_KEY_VALID;
482         if (ecryptfs_verbosity > 0) {
483                 ecryptfs_printk(KERN_DEBUG, "Decrypted session key:\n");
484                 ecryptfs_dump_hex(crypt_stat->key,
485                                   crypt_stat->key_size);
486         }
487 out:
488         if (msg)
489                 kfree(msg);
490         return rc;
491 }
492
493 static void wipe_auth_tok_list(struct list_head *auth_tok_list_head)
494 {
495         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
496         struct ecryptfs_auth_tok_list_item *auth_tok_list_item_tmp;
497
498         list_for_each_entry_safe(auth_tok_list_item, auth_tok_list_item_tmp,
499                                  auth_tok_list_head, list) {
500                 list_del(&auth_tok_list_item->list);
501                 kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
502                                 auth_tok_list_item);
503         }
504 }
505
506 struct kmem_cache *ecryptfs_auth_tok_list_item_cache;
507
508 /**
509  * parse_tag_1_packet
510  * @crypt_stat: The cryptographic context to modify based on packet contents
511  * @data: The raw bytes of the packet.
512  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
513  *                 a new authentication token will be placed at the
514  *                 end of this list for this packet.
515  * @new_auth_tok: Pointer to a pointer to memory that this function
516  *                allocates; sets the memory address of the pointer to
517  *                NULL on error. This object is added to the
518  *                auth_tok_list.
519  * @packet_size: This function writes the size of the parsed packet
520  *               into this memory location; zero on error.
521  * @max_packet_size: The maximum allowable packet size
522  *
523  * Returns zero on success; non-zero on error.
524  */
525 static int
526 parse_tag_1_packet(struct ecryptfs_crypt_stat *crypt_stat,
527                    unsigned char *data, struct list_head *auth_tok_list,
528                    struct ecryptfs_auth_tok **new_auth_tok,
529                    size_t *packet_size, size_t max_packet_size)
530 {
531         size_t body_size;
532         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
533         size_t length_size;
534         int rc = 0;
535
536         (*packet_size) = 0;
537         (*new_auth_tok) = NULL;
538         /**
539          * This format is inspired by OpenPGP; see RFC 2440
540          * packet tag 1
541          *
542          * Tag 1 identifier (1 byte)
543          * Max Tag 1 packet size (max 3 bytes)
544          * Version (1 byte)
545          * Key identifier (8 bytes; ECRYPTFS_SIG_SIZE)
546          * Cipher identifier (1 byte)
547          * Encrypted key size (arbitrary)
548          *
549          * 12 bytes minimum packet size
550          */
551         if (unlikely(max_packet_size < 12)) {
552                 printk(KERN_ERR "Invalid max packet size; must be >=12\n");
553                 rc = -EINVAL;
554                 goto out;
555         }
556         if (data[(*packet_size)++] != ECRYPTFS_TAG_1_PACKET_TYPE) {
557                 printk(KERN_ERR "Enter w/ first byte != 0x%.2x\n",
558                        ECRYPTFS_TAG_1_PACKET_TYPE);
559                 rc = -EINVAL;
560                 goto out;
561         }
562         /* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
563          * at end of function upon failure */
564         auth_tok_list_item =
565                 kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache,
566                                   GFP_KERNEL);
567         if (!auth_tok_list_item) {
568                 printk(KERN_ERR "Unable to allocate memory\n");
569                 rc = -ENOMEM;
570                 goto out;
571         }
572         (*new_auth_tok) = &auth_tok_list_item->auth_tok;
573         rc = parse_packet_length(&data[(*packet_size)], &body_size,
574                                  &length_size);
575         if (rc) {
576                 printk(KERN_WARNING "Error parsing packet length; "
577                        "rc = [%d]\n", rc);
578                 goto out_free;
579         }
580         if (unlikely(body_size < (ECRYPTFS_SIG_SIZE + 2))) {
581                 printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
582                 rc = -EINVAL;
583                 goto out_free;
584         }
585         (*packet_size) += length_size;
586         if (unlikely((*packet_size) + body_size > max_packet_size)) {
587                 printk(KERN_WARNING "Packet size exceeds max\n");
588                 rc = -EINVAL;
589                 goto out_free;
590         }
591         if (unlikely(data[(*packet_size)++] != 0x03)) {
592                 printk(KERN_WARNING "Unknown version number [%d]\n",
593                        data[(*packet_size) - 1]);
594                 rc = -EINVAL;
595                 goto out_free;
596         }
597         ecryptfs_to_hex((*new_auth_tok)->token.private_key.signature,
598                         &data[(*packet_size)], ECRYPTFS_SIG_SIZE);
599         *packet_size += ECRYPTFS_SIG_SIZE;
600         /* This byte is skipped because the kernel does not need to
601          * know which public key encryption algorithm was used */
602         (*packet_size)++;
603         (*new_auth_tok)->session_key.encrypted_key_size =
604                 body_size - (ECRYPTFS_SIG_SIZE + 2);
605         if ((*new_auth_tok)->session_key.encrypted_key_size
606             > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
607                 printk(KERN_WARNING "Tag 1 packet contains key larger "
608                        "than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES");
609                 rc = -EINVAL;
610                 goto out;
611         }
612         memcpy((*new_auth_tok)->session_key.encrypted_key,
613                &data[(*packet_size)], (body_size - (ECRYPTFS_SIG_SIZE + 2)));
614         (*packet_size) += (*new_auth_tok)->session_key.encrypted_key_size;
615         (*new_auth_tok)->session_key.flags &=
616                 ~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
617         (*new_auth_tok)->session_key.flags |=
618                 ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
619         (*new_auth_tok)->token_type = ECRYPTFS_PRIVATE_KEY;
620         (*new_auth_tok)->flags = 0;
621         (*new_auth_tok)->session_key.flags &=
622                 ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
623         (*new_auth_tok)->session_key.flags &=
624                 ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
625         list_add(&auth_tok_list_item->list, auth_tok_list);
626         goto out;
627 out_free:
628         (*new_auth_tok) = NULL;
629         memset(auth_tok_list_item, 0,
630                sizeof(struct ecryptfs_auth_tok_list_item));
631         kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
632                         auth_tok_list_item);
633 out:
634         if (rc)
635                 (*packet_size) = 0;
636         return rc;
637 }
638
639 /**
640  * parse_tag_3_packet
641  * @crypt_stat: The cryptographic context to modify based on packet
642  *              contents.
643  * @data: The raw bytes of the packet.
644  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
645  *                 a new authentication token will be placed at the end
646  *                 of this list for this packet.
647  * @new_auth_tok: Pointer to a pointer to memory that this function
648  *                allocates; sets the memory address of the pointer to
649  *                NULL on error. This object is added to the
650  *                auth_tok_list.
651  * @packet_size: This function writes the size of the parsed packet
652  *               into this memory location; zero on error.
653  * @max_packet_size: maximum number of bytes to parse
654  *
655  * Returns zero on success; non-zero on error.
656  */
657 static int
658 parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat,
659                    unsigned char *data, struct list_head *auth_tok_list,
660                    struct ecryptfs_auth_tok **new_auth_tok,
661                    size_t *packet_size, size_t max_packet_size)
662 {
663         size_t body_size;
664         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
665         size_t length_size;
666         int rc = 0;
667
668         (*packet_size) = 0;
669         (*new_auth_tok) = NULL;
670         /**
671          *This format is inspired by OpenPGP; see RFC 2440
672          * packet tag 3
673          *
674          * Tag 3 identifier (1 byte)
675          * Max Tag 3 packet size (max 3 bytes)
676          * Version (1 byte)
677          * Cipher code (1 byte)
678          * S2K specifier (1 byte)
679          * Hash identifier (1 byte)
680          * Salt (ECRYPTFS_SALT_SIZE)
681          * Hash iterations (1 byte)
682          * Encrypted key (arbitrary)
683          *
684          * (ECRYPTFS_SALT_SIZE + 7) minimum packet size
685          */
686         if (max_packet_size < (ECRYPTFS_SALT_SIZE + 7)) {
687                 printk(KERN_ERR "Max packet size too large\n");
688                 rc = -EINVAL;
689                 goto out;
690         }
691         if (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) {
692                 printk(KERN_ERR "First byte != 0x%.2x; invalid packet\n",
693                        ECRYPTFS_TAG_3_PACKET_TYPE);
694                 rc = -EINVAL;
695                 goto out;
696         }
697         /* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
698          * at end of function upon failure */
699         auth_tok_list_item =
700             kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL);
701         if (!auth_tok_list_item) {
702                 printk(KERN_ERR "Unable to allocate memory\n");
703                 rc = -ENOMEM;
704                 goto out;
705         }
706         (*new_auth_tok) = &auth_tok_list_item->auth_tok;
707         rc = parse_packet_length(&data[(*packet_size)], &body_size,
708                                  &length_size);
709         if (rc) {
710                 printk(KERN_WARNING "Error parsing packet length; rc = [%d]\n",
711                        rc);
712                 goto out_free;
713         }
714         if (unlikely(body_size < (ECRYPTFS_SALT_SIZE + 5))) {
715                 printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
716                 rc = -EINVAL;
717                 goto out_free;
718         }
719         (*packet_size) += length_size;
720         if (unlikely((*packet_size) + body_size > max_packet_size)) {
721                 printk(KERN_ERR "Packet size exceeds max\n");
722                 rc = -EINVAL;
723                 goto out_free;
724         }
725         (*new_auth_tok)->session_key.encrypted_key_size =
726                 (body_size - (ECRYPTFS_SALT_SIZE + 5));
727         if (unlikely(data[(*packet_size)++] != 0x04)) {
728                 printk(KERN_WARNING "Unknown version number [%d]\n",
729                        data[(*packet_size) - 1]);
730                 rc = -EINVAL;
731                 goto out_free;
732         }
733         ecryptfs_cipher_code_to_string(crypt_stat->cipher,
734                                        (u16)data[(*packet_size)]);
735         /* A little extra work to differentiate among the AES key
736          * sizes; see RFC2440 */
737         switch(data[(*packet_size)++]) {
738         case RFC2440_CIPHER_AES_192:
739                 crypt_stat->key_size = 24;
740                 break;
741         default:
742                 crypt_stat->key_size =
743                         (*new_auth_tok)->session_key.encrypted_key_size;
744         }
745         ecryptfs_init_crypt_ctx(crypt_stat);
746         if (unlikely(data[(*packet_size)++] != 0x03)) {
747                 printk(KERN_WARNING "Only S2K ID 3 is currently supported\n");
748                 rc = -ENOSYS;
749                 goto out_free;
750         }
751         /* TODO: finish the hash mapping */
752         switch (data[(*packet_size)++]) {
753         case 0x01: /* See RFC2440 for these numbers and their mappings */
754                 /* Choose MD5 */
755                 memcpy((*new_auth_tok)->token.password.salt,
756                        &data[(*packet_size)], ECRYPTFS_SALT_SIZE);
757                 (*packet_size) += ECRYPTFS_SALT_SIZE;
758                 /* This conversion was taken straight from RFC2440 */
759                 (*new_auth_tok)->token.password.hash_iterations =
760                         ((u32) 16 + (data[(*packet_size)] & 15))
761                                 << ((data[(*packet_size)] >> 4) + 6);
762                 (*packet_size)++;
763                 /* Friendly reminder:
764                  * (*new_auth_tok)->session_key.encrypted_key_size =
765                  *         (body_size - (ECRYPTFS_SALT_SIZE + 5)); */
766                 memcpy((*new_auth_tok)->session_key.encrypted_key,
767                        &data[(*packet_size)],
768                        (*new_auth_tok)->session_key.encrypted_key_size);
769                 (*packet_size) +=
770                         (*new_auth_tok)->session_key.encrypted_key_size;
771                 (*new_auth_tok)->session_key.flags &=
772                         ~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
773                 (*new_auth_tok)->session_key.flags |=
774                         ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
775                 (*new_auth_tok)->token.password.hash_algo = 0x01; /* MD5 */
776                 break;
777         default:
778                 ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: "
779                                 "[%d]\n", data[(*packet_size) - 1]);
780                 rc = -ENOSYS;
781                 goto out_free;
782         }
783         (*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;
784         /* TODO: Parametarize; we might actually want userspace to
785          * decrypt the session key. */
786         (*new_auth_tok)->session_key.flags &=
787                             ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
788         (*new_auth_tok)->session_key.flags &=
789                             ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
790         list_add(&auth_tok_list_item->list, auth_tok_list);
791         goto out;
792 out_free:
793         (*new_auth_tok) = NULL;
794         memset(auth_tok_list_item, 0,
795                sizeof(struct ecryptfs_auth_tok_list_item));
796         kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
797                         auth_tok_list_item);
798 out:
799         if (rc)
800                 (*packet_size) = 0;
801         return rc;
802 }
803
804 /**
805  * parse_tag_11_packet
806  * @data: The raw bytes of the packet
807  * @contents: This function writes the data contents of the literal
808  *            packet into this memory location
809  * @max_contents_bytes: The maximum number of bytes that this function
810  *                      is allowed to write into contents
811  * @tag_11_contents_size: This function writes the size of the parsed
812  *                        contents into this memory location; zero on
813  *                        error
814  * @packet_size: This function writes the size of the parsed packet
815  *               into this memory location; zero on error
816  * @max_packet_size: maximum number of bytes to parse
817  *
818  * Returns zero on success; non-zero on error.
819  */
820 static int
821 parse_tag_11_packet(unsigned char *data, unsigned char *contents,
822                     size_t max_contents_bytes, size_t *tag_11_contents_size,
823                     size_t *packet_size, size_t max_packet_size)
824 {
825         size_t body_size;
826         size_t length_size;
827         int rc = 0;
828
829         (*packet_size) = 0;
830         (*tag_11_contents_size) = 0;
831         /* This format is inspired by OpenPGP; see RFC 2440
832          * packet tag 11
833          *
834          * Tag 11 identifier (1 byte)
835          * Max Tag 11 packet size (max 3 bytes)
836          * Binary format specifier (1 byte)
837          * Filename length (1 byte)
838          * Filename ("_CONSOLE") (8 bytes)
839          * Modification date (4 bytes)
840          * Literal data (arbitrary)
841          *
842          * We need at least 16 bytes of data for the packet to even be
843          * valid.
844          */
845         if (max_packet_size < 16) {
846                 printk(KERN_ERR "Maximum packet size too small\n");
847                 rc = -EINVAL;
848                 goto out;
849         }
850         if (data[(*packet_size)++] != ECRYPTFS_TAG_11_PACKET_TYPE) {
851                 printk(KERN_WARNING "Invalid tag 11 packet format\n");
852                 rc = -EINVAL;
853                 goto out;
854         }
855         rc = parse_packet_length(&data[(*packet_size)], &body_size,
856                                  &length_size);
857         if (rc) {
858                 printk(KERN_WARNING "Invalid tag 11 packet format\n");
859                 goto out;
860         }
861         if (body_size < 14) {
862                 printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
863                 rc = -EINVAL;
864                 goto out;
865         }
866         (*packet_size) += length_size;
867         (*tag_11_contents_size) = (body_size - 14);
868         if (unlikely((*packet_size) + body_size + 1 > max_packet_size)) {
869                 printk(KERN_ERR "Packet size exceeds max\n");
870                 rc = -EINVAL;
871                 goto out;
872         }
873         if (data[(*packet_size)++] != 0x62) {
874                 printk(KERN_WARNING "Unrecognizable packet\n");
875                 rc = -EINVAL;
876                 goto out;
877         }
878         if (data[(*packet_size)++] != 0x08) {
879                 printk(KERN_WARNING "Unrecognizable packet\n");
880                 rc = -EINVAL;
881                 goto out;
882         }
883         (*packet_size) += 12; /* Ignore filename and modification date */
884         memcpy(contents, &data[(*packet_size)], (*tag_11_contents_size));
885         (*packet_size) += (*tag_11_contents_size);
886 out:
887         if (rc) {
888                 (*packet_size) = 0;
889                 (*tag_11_contents_size) = 0;
890         }
891         return rc;
892 }
893
894 static int
895 ecryptfs_find_global_auth_tok_for_sig(
896         struct ecryptfs_global_auth_tok **global_auth_tok,
897         struct ecryptfs_mount_crypt_stat *mount_crypt_stat, char *sig)
898 {
899         struct ecryptfs_global_auth_tok *walker;
900         int rc = 0;
901
902         (*global_auth_tok) = NULL;
903         mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
904         list_for_each_entry(walker,
905                             &mount_crypt_stat->global_auth_tok_list,
906                             mount_crypt_stat_list) {
907                 if (memcmp(walker->sig, sig, ECRYPTFS_SIG_SIZE_HEX) == 0) {
908                         (*global_auth_tok) = walker;
909                         goto out;
910                 }
911         }
912         rc = -EINVAL;
913 out:
914         mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
915         return rc;
916 }
917
918 /**
919  * ecryptfs_verify_version
920  * @version: The version number to confirm
921  *
922  * Returns zero on good version; non-zero otherwise
923  */
924 static int ecryptfs_verify_version(u16 version)
925 {
926         int rc = 0;
927         unsigned char major;
928         unsigned char minor;
929
930         major = ((version >> 8) & 0xFF);
931         minor = (version & 0xFF);
932         if (major != ECRYPTFS_VERSION_MAJOR) {
933                 ecryptfs_printk(KERN_ERR, "Major version number mismatch. "
934                                 "Expected [%d]; got [%d]\n",
935                                 ECRYPTFS_VERSION_MAJOR, major);
936                 rc = -EINVAL;
937                 goto out;
938         }
939         if (minor != ECRYPTFS_VERSION_MINOR) {
940                 ecryptfs_printk(KERN_ERR, "Minor version number mismatch. "
941                                 "Expected [%d]; got [%d]\n",
942                                 ECRYPTFS_VERSION_MINOR, minor);
943                 rc = -EINVAL;
944                 goto out;
945         }
946 out:
947         return rc;
948 }
949
950 int ecryptfs_keyring_auth_tok_for_sig(struct key **auth_tok_key,
951                                       struct ecryptfs_auth_tok **auth_tok,
952                                       char *sig)
953 {
954         int rc = 0;
955
956         (*auth_tok_key) = request_key(&key_type_user, sig, NULL);
957         if (!(*auth_tok_key) || IS_ERR(*auth_tok_key)) {
958                 printk(KERN_ERR "Could not find key with description: [%s]\n",
959                        sig);
960                 process_request_key_err(PTR_ERR(*auth_tok_key));
961                 rc = -EINVAL;
962                 goto out;
963         }
964         (*auth_tok) = ecryptfs_get_key_payload_data(*auth_tok_key);
965         if (ecryptfs_verify_version((*auth_tok)->version)) {
966                 printk(KERN_ERR
967                        "Data structure version mismatch. "
968                        "Userspace tools must match eCryptfs "
969                        "kernel module with major version [%d] "
970                        "and minor version [%d]\n",
971                        ECRYPTFS_VERSION_MAJOR,
972                        ECRYPTFS_VERSION_MINOR);
973                 rc = -EINVAL;
974                 goto out;
975         }
976         if ((*auth_tok)->token_type != ECRYPTFS_PASSWORD
977             && (*auth_tok)->token_type != ECRYPTFS_PRIVATE_KEY) {
978                 printk(KERN_ERR "Invalid auth_tok structure "
979                        "returned from key query\n");
980                 rc = -EINVAL;
981                 goto out;
982         }
983 out:
984         return rc;
985 }
986
987 /**
988  * ecryptfs_find_auth_tok_for_sig
989  * @auth_tok: Set to the matching auth_tok; NULL if not found
990  * @crypt_stat: inode crypt_stat crypto context
991  * @sig: Sig of auth_tok to find
992  *
993  * For now, this function simply looks at the registered auth_tok's
994  * linked off the mount_crypt_stat, so all the auth_toks that can be
995  * used must be registered at mount time. This function could
996  * potentially try a lot harder to find auth_tok's (e.g., by calling
997  * out to ecryptfsd to dynamically retrieve an auth_tok object) so
998  * that static registration of auth_tok's will no longer be necessary.
999  *
1000  * Returns zero on no error; non-zero on error
1001  */
1002 static int
1003 ecryptfs_find_auth_tok_for_sig(
1004         struct ecryptfs_auth_tok **auth_tok,
1005         struct ecryptfs_crypt_stat *crypt_stat, char *sig)
1006 {
1007         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1008                 crypt_stat->mount_crypt_stat;
1009         struct ecryptfs_global_auth_tok *global_auth_tok;
1010         int rc = 0;
1011
1012         (*auth_tok) = NULL;
1013         if (ecryptfs_find_global_auth_tok_for_sig(&global_auth_tok,
1014                                                   mount_crypt_stat, sig)) {
1015                 struct key *auth_tok_key;
1016
1017                 rc = ecryptfs_keyring_auth_tok_for_sig(&auth_tok_key, auth_tok,
1018                                                        sig);
1019         } else
1020                 (*auth_tok) = global_auth_tok->global_auth_tok;
1021         return rc;
1022 }
1023
1024 /**
1025  * decrypt_passphrase_encrypted_session_key - Decrypt the session key with the given auth_tok.
1026  * @auth_tok: The passphrase authentication token to use to encrypt the FEK
1027  * @crypt_stat: The cryptographic context
1028  *
1029  * Returns zero on success; non-zero error otherwise
1030  */
1031 static int
1032 decrypt_passphrase_encrypted_session_key(struct ecryptfs_auth_tok *auth_tok,
1033                                          struct ecryptfs_crypt_stat *crypt_stat)
1034 {
1035         struct scatterlist dst_sg;
1036         struct scatterlist src_sg;
1037         struct mutex *tfm_mutex;
1038         struct blkcipher_desc desc = {
1039                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
1040         };
1041         int rc = 0;
1042
1043         sg_init_table(&dst_sg, 1);
1044         sg_init_table(&src_sg, 1);
1045
1046         if (unlikely(ecryptfs_verbosity > 0)) {
1047                 ecryptfs_printk(
1048                         KERN_DEBUG, "Session key encryption key (size [%d]):\n",
1049                         auth_tok->token.password.session_key_encryption_key_bytes);
1050                 ecryptfs_dump_hex(
1051                         auth_tok->token.password.session_key_encryption_key,
1052                         auth_tok->token.password.session_key_encryption_key_bytes);
1053         }
1054         rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&desc.tfm, &tfm_mutex,
1055                                                         crypt_stat->cipher);
1056         if (unlikely(rc)) {
1057                 printk(KERN_ERR "Internal error whilst attempting to get "
1058                        "tfm and mutex for cipher name [%s]; rc = [%d]\n",
1059                        crypt_stat->cipher, rc);
1060                 goto out;
1061         }
1062         rc = virt_to_scatterlist(auth_tok->session_key.encrypted_key,
1063                                  auth_tok->session_key.encrypted_key_size,
1064                                  &src_sg, 1);
1065         if (rc != 1) {
1066                 printk(KERN_ERR "Internal error whilst attempting to convert "
1067                         "auth_tok->session_key.encrypted_key to scatterlist; "
1068                         "expected rc = 1; got rc = [%d]. "
1069                        "auth_tok->session_key.encrypted_key_size = [%d]\n", rc,
1070                         auth_tok->session_key.encrypted_key_size);
1071                 goto out;
1072         }
1073         auth_tok->session_key.decrypted_key_size =
1074                 auth_tok->session_key.encrypted_key_size;
1075         rc = virt_to_scatterlist(auth_tok->session_key.decrypted_key,
1076                                  auth_tok->session_key.decrypted_key_size,
1077                                  &dst_sg, 1);
1078         if (rc != 1) {
1079                 printk(KERN_ERR "Internal error whilst attempting to convert "
1080                         "auth_tok->session_key.decrypted_key to scatterlist; "
1081                         "expected rc = 1; got rc = [%d]\n", rc);
1082                 goto out;
1083         }
1084         mutex_lock(tfm_mutex);
1085         rc = crypto_blkcipher_setkey(
1086                 desc.tfm, auth_tok->token.password.session_key_encryption_key,
1087                 crypt_stat->key_size);
1088         if (unlikely(rc < 0)) {
1089                 mutex_unlock(tfm_mutex);
1090                 printk(KERN_ERR "Error setting key for crypto context\n");
1091                 rc = -EINVAL;
1092                 goto out;
1093         }
1094         rc = crypto_blkcipher_decrypt(&desc, &dst_sg, &src_sg,
1095                                       auth_tok->session_key.encrypted_key_size);
1096         mutex_unlock(tfm_mutex);
1097         if (unlikely(rc)) {
1098                 printk(KERN_ERR "Error decrypting; rc = [%d]\n", rc);
1099                 goto out;
1100         }
1101         auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1102         memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
1103                auth_tok->session_key.decrypted_key_size);
1104         crypt_stat->flags |= ECRYPTFS_KEY_VALID;
1105         if (unlikely(ecryptfs_verbosity > 0)) {
1106                 ecryptfs_printk(KERN_DEBUG, "FEK of size [%d]:\n",
1107                                 crypt_stat->key_size);
1108                 ecryptfs_dump_hex(crypt_stat->key,
1109                                   crypt_stat->key_size);
1110         }
1111 out:
1112         return rc;
1113 }
1114
1115 /**
1116  * ecryptfs_parse_packet_set
1117  * @crypt_stat: The cryptographic context
1118  * @src: Virtual address of region of memory containing the packets
1119  * @ecryptfs_dentry: The eCryptfs dentry associated with the packet set
1120  *
1121  * Get crypt_stat to have the file's session key if the requisite key
1122  * is available to decrypt the session key.
1123  *
1124  * Returns Zero if a valid authentication token was retrieved and
1125  * processed; negative value for file not encrypted or for error
1126  * conditions.
1127  */
1128 int ecryptfs_parse_packet_set(struct ecryptfs_crypt_stat *crypt_stat,
1129                               unsigned char *src,
1130                               struct dentry *ecryptfs_dentry)
1131 {
1132         size_t i = 0;
1133         size_t found_auth_tok;
1134         size_t next_packet_is_auth_tok_packet;
1135         struct list_head auth_tok_list;
1136         struct ecryptfs_auth_tok *matching_auth_tok;
1137         struct ecryptfs_auth_tok *candidate_auth_tok;
1138         char *candidate_auth_tok_sig;
1139         size_t packet_size;
1140         struct ecryptfs_auth_tok *new_auth_tok;
1141         unsigned char sig_tmp_space[ECRYPTFS_SIG_SIZE];
1142         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1143         size_t tag_11_contents_size;
1144         size_t tag_11_packet_size;
1145         int rc = 0;
1146
1147         INIT_LIST_HEAD(&auth_tok_list);
1148         /* Parse the header to find as many packets as we can; these will be
1149          * added the our &auth_tok_list */
1150         next_packet_is_auth_tok_packet = 1;
1151         while (next_packet_is_auth_tok_packet) {
1152                 size_t max_packet_size = ((PAGE_CACHE_SIZE - 8) - i);
1153
1154                 switch (src[i]) {
1155                 case ECRYPTFS_TAG_3_PACKET_TYPE:
1156                         rc = parse_tag_3_packet(crypt_stat,
1157                                                 (unsigned char *)&src[i],
1158                                                 &auth_tok_list, &new_auth_tok,
1159                                                 &packet_size, max_packet_size);
1160                         if (rc) {
1161                                 ecryptfs_printk(KERN_ERR, "Error parsing "
1162                                                 "tag 3 packet\n");
1163                                 rc = -EIO;
1164                                 goto out_wipe_list;
1165                         }
1166                         i += packet_size;
1167                         rc = parse_tag_11_packet((unsigned char *)&src[i],
1168                                                  sig_tmp_space,
1169                                                  ECRYPTFS_SIG_SIZE,
1170                                                  &tag_11_contents_size,
1171                                                  &tag_11_packet_size,
1172                                                  max_packet_size);
1173                         if (rc) {
1174                                 ecryptfs_printk(KERN_ERR, "No valid "
1175                                                 "(ecryptfs-specific) literal "
1176                                                 "packet containing "
1177                                                 "authentication token "
1178                                                 "signature found after "
1179                                                 "tag 3 packet\n");
1180                                 rc = -EIO;
1181                                 goto out_wipe_list;
1182                         }
1183                         i += tag_11_packet_size;
1184                         if (ECRYPTFS_SIG_SIZE != tag_11_contents_size) {
1185                                 ecryptfs_printk(KERN_ERR, "Expected "
1186                                                 "signature of size [%d]; "
1187                                                 "read size [%d]\n",
1188                                                 ECRYPTFS_SIG_SIZE,
1189                                                 tag_11_contents_size);
1190                                 rc = -EIO;
1191                                 goto out_wipe_list;
1192                         }
1193                         ecryptfs_to_hex(new_auth_tok->token.password.signature,
1194                                         sig_tmp_space, tag_11_contents_size);
1195                         new_auth_tok->token.password.signature[
1196                                 ECRYPTFS_PASSWORD_SIG_SIZE] = '\0';
1197                         crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1198                         break;
1199                 case ECRYPTFS_TAG_1_PACKET_TYPE:
1200                         rc = parse_tag_1_packet(crypt_stat,
1201                                                 (unsigned char *)&src[i],
1202                                                 &auth_tok_list, &new_auth_tok,
1203                                                 &packet_size, max_packet_size);
1204                         if (rc) {
1205                                 ecryptfs_printk(KERN_ERR, "Error parsing "
1206                                                 "tag 1 packet\n");
1207                                 rc = -EIO;
1208                                 goto out_wipe_list;
1209                         }
1210                         i += packet_size;
1211                         crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1212                         break;
1213                 case ECRYPTFS_TAG_11_PACKET_TYPE:
1214                         ecryptfs_printk(KERN_WARNING, "Invalid packet set "
1215                                         "(Tag 11 not allowed by itself)\n");
1216                         rc = -EIO;
1217                         goto out_wipe_list;
1218                         break;
1219                 default:
1220                         ecryptfs_printk(KERN_DEBUG, "No packet at offset "
1221                                         "[%d] of the file header; hex value of "
1222                                         "character is [0x%.2x]\n", i, src[i]);
1223                         next_packet_is_auth_tok_packet = 0;
1224                 }
1225         }
1226         if (list_empty(&auth_tok_list)) {
1227                 printk(KERN_ERR "The lower file appears to be a non-encrypted "
1228                        "eCryptfs file; this is not supported in this version "
1229                        "of the eCryptfs kernel module\n");
1230                 rc = -EINVAL;
1231                 goto out;
1232         }
1233         /* auth_tok_list contains the set of authentication tokens
1234          * parsed from the metadata. We need to find a matching
1235          * authentication token that has the secret component(s)
1236          * necessary to decrypt the EFEK in the auth_tok parsed from
1237          * the metadata. There may be several potential matches, but
1238          * just one will be sufficient to decrypt to get the FEK. */
1239 find_next_matching_auth_tok:
1240         found_auth_tok = 0;
1241         list_for_each_entry(auth_tok_list_item, &auth_tok_list, list) {
1242                 candidate_auth_tok = &auth_tok_list_item->auth_tok;
1243                 if (unlikely(ecryptfs_verbosity > 0)) {
1244                         ecryptfs_printk(KERN_DEBUG,
1245                                         "Considering cadidate auth tok:\n");
1246                         ecryptfs_dump_auth_tok(candidate_auth_tok);
1247                 }
1248                 rc = ecryptfs_get_auth_tok_sig(&candidate_auth_tok_sig,
1249                                                candidate_auth_tok);
1250                 if (rc) {
1251                         printk(KERN_ERR
1252                                "Unrecognized candidate auth tok type: [%d]\n",
1253                                candidate_auth_tok->token_type);
1254                         rc = -EINVAL;
1255                         goto out_wipe_list;
1256                 }
1257                 ecryptfs_find_auth_tok_for_sig(&matching_auth_tok, crypt_stat,
1258                                                candidate_auth_tok_sig);
1259                 if (matching_auth_tok) {
1260                         found_auth_tok = 1;
1261                         goto found_matching_auth_tok;
1262                 }
1263         }
1264         if (!found_auth_tok) {
1265                 ecryptfs_printk(KERN_ERR, "Could not find a usable "
1266                                 "authentication token\n");
1267                 rc = -EIO;
1268                 goto out_wipe_list;
1269         }
1270 found_matching_auth_tok:
1271         if (candidate_auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
1272                 memcpy(&(candidate_auth_tok->token.private_key),
1273                        &(matching_auth_tok->token.private_key),
1274                        sizeof(struct ecryptfs_private_key));
1275                 rc = decrypt_pki_encrypted_session_key(candidate_auth_tok,
1276                                                        crypt_stat);
1277         } else if (candidate_auth_tok->token_type == ECRYPTFS_PASSWORD) {
1278                 memcpy(&(candidate_auth_tok->token.password),
1279                        &(matching_auth_tok->token.password),
1280                        sizeof(struct ecryptfs_password));
1281                 rc = decrypt_passphrase_encrypted_session_key(
1282                         candidate_auth_tok, crypt_stat);
1283         }
1284         if (rc) {
1285                 struct ecryptfs_auth_tok_list_item *auth_tok_list_item_tmp;
1286
1287                 ecryptfs_printk(KERN_WARNING, "Error decrypting the "
1288                                 "session key for authentication token with sig "
1289                                 "[%.*s]; rc = [%d]. Removing auth tok "
1290                                 "candidate from the list and searching for "
1291                                 "the next match.\n", candidate_auth_tok_sig,
1292                                 ECRYPTFS_SIG_SIZE_HEX, rc);
1293                 list_for_each_entry_safe(auth_tok_list_item,
1294                                          auth_tok_list_item_tmp,
1295                                          &auth_tok_list, list) {
1296                         if (candidate_auth_tok
1297                             == &auth_tok_list_item->auth_tok) {
1298                                 list_del(&auth_tok_list_item->list);
1299                                 kmem_cache_free(
1300                                         ecryptfs_auth_tok_list_item_cache,
1301                                         auth_tok_list_item);
1302                                 goto find_next_matching_auth_tok;
1303                         }
1304                 }
1305                 BUG();
1306         }
1307         rc = ecryptfs_compute_root_iv(crypt_stat);
1308         if (rc) {
1309                 ecryptfs_printk(KERN_ERR, "Error computing "
1310                                 "the root IV\n");
1311                 goto out_wipe_list;
1312         }
1313         rc = ecryptfs_init_crypt_ctx(crypt_stat);
1314         if (rc) {
1315                 ecryptfs_printk(KERN_ERR, "Error initializing crypto "
1316                                 "context for cipher [%s]; rc = [%d]\n",
1317                                 crypt_stat->cipher, rc);
1318         }
1319 out_wipe_list:
1320         wipe_auth_tok_list(&auth_tok_list);
1321 out:
1322         return rc;
1323 }
1324
1325 static int
1326 pki_encrypt_session_key(struct ecryptfs_auth_tok *auth_tok,
1327                         struct ecryptfs_crypt_stat *crypt_stat,
1328                         struct ecryptfs_key_record *key_rec)
1329 {
1330         struct ecryptfs_msg_ctx *msg_ctx = NULL;
1331         char *netlink_payload;
1332         size_t netlink_payload_length;
1333         struct ecryptfs_message *msg;
1334         int rc;
1335
1336         rc = write_tag_66_packet(auth_tok->token.private_key.signature,
1337                                  ecryptfs_code_for_cipher_string(crypt_stat),
1338                                  crypt_stat, &netlink_payload,
1339                                  &netlink_payload_length);
1340         if (rc) {
1341                 ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet\n");
1342                 goto out;
1343         }
1344         rc = ecryptfs_send_message(ecryptfs_transport, netlink_payload,
1345                                    netlink_payload_length, &msg_ctx);
1346         if (rc) {
1347                 ecryptfs_printk(KERN_ERR, "Error sending netlink message\n");
1348                 goto out;
1349         }
1350         rc = ecryptfs_wait_for_response(msg_ctx, &msg);
1351         if (rc) {
1352                 ecryptfs_printk(KERN_ERR, "Failed to receive tag 67 packet "
1353                                 "from the user space daemon\n");
1354                 rc = -EIO;
1355                 goto out;
1356         }
1357         rc = parse_tag_67_packet(key_rec, msg);
1358         if (rc)
1359                 ecryptfs_printk(KERN_ERR, "Error parsing tag 67 packet\n");
1360         kfree(msg);
1361 out:
1362         if (netlink_payload)
1363                 kfree(netlink_payload);
1364         return rc;
1365 }
1366 /**
1367  * write_tag_1_packet - Write an RFC2440-compatible tag 1 (public key) packet
1368  * @dest: Buffer into which to write the packet
1369  * @remaining_bytes: Maximum number of bytes that can be writtn
1370  * @auth_tok: The authentication token used for generating the tag 1 packet
1371  * @crypt_stat: The cryptographic context
1372  * @key_rec: The key record struct for the tag 1 packet
1373  * @packet_size: This function will write the number of bytes that end
1374  *               up constituting the packet; set to zero on error
1375  *
1376  * Returns zero on success; non-zero on error.
1377  */
1378 static int
1379 write_tag_1_packet(char *dest, size_t *remaining_bytes,
1380                    struct ecryptfs_auth_tok *auth_tok,
1381                    struct ecryptfs_crypt_stat *crypt_stat,
1382                    struct ecryptfs_key_record *key_rec, size_t *packet_size)
1383 {
1384         size_t i;
1385         size_t encrypted_session_key_valid = 0;
1386         size_t packet_size_length;
1387         size_t max_packet_size;
1388         int rc = 0;
1389
1390         (*packet_size) = 0;
1391         ecryptfs_from_hex(key_rec->sig, auth_tok->token.private_key.signature,
1392                           ECRYPTFS_SIG_SIZE);
1393         encrypted_session_key_valid = 0;
1394         for (i = 0; i < crypt_stat->key_size; i++)
1395                 encrypted_session_key_valid |=
1396                         auth_tok->session_key.encrypted_key[i];
1397         if (encrypted_session_key_valid) {
1398                 memcpy(key_rec->enc_key,
1399                        auth_tok->session_key.encrypted_key,
1400                        auth_tok->session_key.encrypted_key_size);
1401                 goto encrypted_session_key_set;
1402         }
1403         if (auth_tok->session_key.encrypted_key_size == 0)
1404                 auth_tok->session_key.encrypted_key_size =
1405                         auth_tok->token.private_key.key_size;
1406         rc = pki_encrypt_session_key(auth_tok, crypt_stat, key_rec);
1407         if (rc) {
1408                 ecryptfs_printk(KERN_ERR, "Failed to encrypt session key "
1409                                 "via a pki");
1410                 goto out;
1411         }
1412         if (ecryptfs_verbosity > 0) {
1413                 ecryptfs_printk(KERN_DEBUG, "Encrypted key:\n");
1414                 ecryptfs_dump_hex(key_rec->enc_key, key_rec->enc_key_size);
1415         }
1416 encrypted_session_key_set:
1417         /* This format is inspired by OpenPGP; see RFC 2440
1418          * packet tag 1 */
1419         max_packet_size = (1                         /* Tag 1 identifier */
1420                            + 3                       /* Max Tag 1 packet size */
1421                            + 1                       /* Version */
1422                            + ECRYPTFS_SIG_SIZE       /* Key identifier */
1423                            + 1                       /* Cipher identifier */
1424                            + key_rec->enc_key_size); /* Encrypted key size */
1425         if (max_packet_size > (*remaining_bytes)) {
1426                 printk(KERN_ERR "Packet length larger than maximum allowable; "
1427                        "need up to [%td] bytes, but there are only [%td] "
1428                        "available\n", max_packet_size, (*remaining_bytes));
1429                 rc = -EINVAL;
1430                 goto out;
1431         }
1432         dest[(*packet_size)++] = ECRYPTFS_TAG_1_PACKET_TYPE;
1433         rc = write_packet_length(&dest[(*packet_size)], (max_packet_size - 4),
1434                                  &packet_size_length);
1435         if (rc) {
1436                 ecryptfs_printk(KERN_ERR, "Error generating tag 1 packet "
1437                                 "header; cannot generate packet length\n");
1438                 goto out;
1439         }
1440         (*packet_size) += packet_size_length;
1441         dest[(*packet_size)++] = 0x03; /* version 3 */
1442         memcpy(&dest[(*packet_size)], key_rec->sig, ECRYPTFS_SIG_SIZE);
1443         (*packet_size) += ECRYPTFS_SIG_SIZE;
1444         dest[(*packet_size)++] = RFC2440_CIPHER_RSA;
1445         memcpy(&dest[(*packet_size)], key_rec->enc_key,
1446                key_rec->enc_key_size);
1447         (*packet_size) += key_rec->enc_key_size;
1448 out:
1449         if (rc)
1450                 (*packet_size) = 0;
1451         else
1452                 (*remaining_bytes) -= (*packet_size);
1453         return rc;
1454 }
1455
1456 /**
1457  * write_tag_11_packet
1458  * @dest: Target into which Tag 11 packet is to be written
1459  * @remaining_bytes: Maximum packet length
1460  * @contents: Byte array of contents to copy in
1461  * @contents_length: Number of bytes in contents
1462  * @packet_length: Length of the Tag 11 packet written; zero on error
1463  *
1464  * Returns zero on success; non-zero on error.
1465  */
1466 static int
1467 write_tag_11_packet(char *dest, size_t *remaining_bytes, char *contents,
1468                     size_t contents_length, size_t *packet_length)
1469 {
1470         size_t packet_size_length;
1471         size_t max_packet_size;
1472         int rc = 0;
1473
1474         (*packet_length) = 0;
1475         /* This format is inspired by OpenPGP; see RFC 2440
1476          * packet tag 11 */
1477         max_packet_size = (1                   /* Tag 11 identifier */
1478                            + 3                 /* Max Tag 11 packet size */
1479                            + 1                 /* Binary format specifier */
1480                            + 1                 /* Filename length */
1481                            + 8                 /* Filename ("_CONSOLE") */
1482                            + 4                 /* Modification date */
1483                            + contents_length); /* Literal data */
1484         if (max_packet_size > (*remaining_bytes)) {
1485                 printk(KERN_ERR "Packet length larger than maximum allowable; "
1486                        "need up to [%td] bytes, but there are only [%td] "
1487                        "available\n", max_packet_size, (*remaining_bytes));
1488                 rc = -EINVAL;
1489                 goto out;
1490         }
1491         dest[(*packet_length)++] = ECRYPTFS_TAG_11_PACKET_TYPE;
1492         rc = write_packet_length(&dest[(*packet_length)],
1493                                  (max_packet_size - 4), &packet_size_length);
1494         if (rc) {
1495                 printk(KERN_ERR "Error generating tag 11 packet header; cannot "
1496                        "generate packet length. rc = [%d]\n", rc);
1497                 goto out;
1498         }
1499         (*packet_length) += packet_size_length;
1500         dest[(*packet_length)++] = 0x62; /* binary data format specifier */
1501         dest[(*packet_length)++] = 8;
1502         memcpy(&dest[(*packet_length)], "_CONSOLE", 8);
1503         (*packet_length) += 8;
1504         memset(&dest[(*packet_length)], 0x00, 4);
1505         (*packet_length) += 4;
1506         memcpy(&dest[(*packet_length)], contents, contents_length);
1507         (*packet_length) += contents_length;
1508  out:
1509         if (rc)
1510                 (*packet_length) = 0;
1511         else
1512                 (*remaining_bytes) -= (*packet_length);
1513         return rc;
1514 }
1515
1516 /**
1517  * write_tag_3_packet
1518  * @dest: Buffer into which to write the packet
1519  * @remaining_bytes: Maximum number of bytes that can be written
1520  * @auth_tok: Authentication token
1521  * @crypt_stat: The cryptographic context
1522  * @key_rec: encrypted key
1523  * @packet_size: This function will write the number of bytes that end
1524  *               up constituting the packet; set to zero on error
1525  *
1526  * Returns zero on success; non-zero on error.
1527  */
1528 static int
1529 write_tag_3_packet(char *dest, size_t *remaining_bytes,
1530                    struct ecryptfs_auth_tok *auth_tok,
1531                    struct ecryptfs_crypt_stat *crypt_stat,
1532                    struct ecryptfs_key_record *key_rec, size_t *packet_size)
1533 {
1534         size_t i;
1535         size_t encrypted_session_key_valid = 0;
1536         char session_key_encryption_key[ECRYPTFS_MAX_KEY_BYTES];
1537         struct scatterlist dst_sg;
1538         struct scatterlist src_sg;
1539         struct mutex *tfm_mutex = NULL;
1540         u8 cipher_code;
1541         size_t packet_size_length;
1542         size_t max_packet_size;
1543         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1544                 crypt_stat->mount_crypt_stat;
1545         struct blkcipher_desc desc = {
1546                 .tfm = NULL,
1547                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
1548         };
1549         int rc = 0;
1550
1551         (*packet_size) = 0;
1552         ecryptfs_from_hex(key_rec->sig, auth_tok->token.password.signature,
1553                           ECRYPTFS_SIG_SIZE);
1554         rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&desc.tfm, &tfm_mutex,
1555                                                         crypt_stat->cipher);
1556         if (unlikely(rc)) {
1557                 printk(KERN_ERR "Internal error whilst attempting to get "
1558                        "tfm and mutex for cipher name [%s]; rc = [%d]\n",
1559                        crypt_stat->cipher, rc);
1560                 goto out;
1561         }
1562         if (mount_crypt_stat->global_default_cipher_key_size == 0) {
1563                 struct blkcipher_alg *alg = crypto_blkcipher_alg(desc.tfm);
1564
1565                 printk(KERN_WARNING "No key size specified at mount; "
1566                        "defaulting to [%d]\n", alg->max_keysize);
1567                 mount_crypt_stat->global_default_cipher_key_size =
1568                         alg->max_keysize;
1569         }
1570         if (crypt_stat->key_size == 0)
1571                 crypt_stat->key_size =
1572                         mount_crypt_stat->global_default_cipher_key_size;
1573         if (auth_tok->session_key.encrypted_key_size == 0)
1574                 auth_tok->session_key.encrypted_key_size =
1575                         crypt_stat->key_size;
1576         if (crypt_stat->key_size == 24
1577             && strcmp("aes", crypt_stat->cipher) == 0) {
1578                 memset((crypt_stat->key + 24), 0, 8);
1579                 auth_tok->session_key.encrypted_key_size = 32;
1580         } else
1581                 auth_tok->session_key.encrypted_key_size = crypt_stat->key_size;
1582         key_rec->enc_key_size =
1583                 auth_tok->session_key.encrypted_key_size;
1584         encrypted_session_key_valid = 0;
1585         for (i = 0; i < auth_tok->session_key.encrypted_key_size; i++)
1586                 encrypted_session_key_valid |=
1587                         auth_tok->session_key.encrypted_key[i];
1588         if (encrypted_session_key_valid) {
1589                 ecryptfs_printk(KERN_DEBUG, "encrypted_session_key_valid != 0; "
1590                                 "using auth_tok->session_key.encrypted_key, "
1591                                 "where key_rec->enc_key_size = [%d]\n",
1592                                 key_rec->enc_key_size);
1593                 memcpy(key_rec->enc_key,
1594                        auth_tok->session_key.encrypted_key,
1595                        key_rec->enc_key_size);
1596                 goto encrypted_session_key_set;
1597         }
1598         if (auth_tok->token.password.flags &
1599             ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET) {
1600                 ecryptfs_printk(KERN_DEBUG, "Using previously generated "
1601                                 "session key encryption key of size [%d]\n",
1602                                 auth_tok->token.password.
1603                                 session_key_encryption_key_bytes);
1604                 memcpy(session_key_encryption_key,
1605                        auth_tok->token.password.session_key_encryption_key,
1606                        crypt_stat->key_size);
1607                 ecryptfs_printk(KERN_DEBUG,
1608                                 "Cached session key " "encryption key: \n");
1609                 if (ecryptfs_verbosity > 0)
1610                         ecryptfs_dump_hex(session_key_encryption_key, 16);
1611         }
1612         if (unlikely(ecryptfs_verbosity > 0)) {
1613                 ecryptfs_printk(KERN_DEBUG, "Session key encryption key:\n");
1614                 ecryptfs_dump_hex(session_key_encryption_key, 16);
1615         }
1616         rc = virt_to_scatterlist(crypt_stat->key, key_rec->enc_key_size,
1617                                  &src_sg, 1);
1618         if (rc != 1) {
1619                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
1620                                 "for crypt_stat session key; expected rc = 1; "
1621                                 "got rc = [%d]. key_rec->enc_key_size = [%d]\n",
1622                                 rc, key_rec->enc_key_size);
1623                 rc = -ENOMEM;
1624                 goto out;
1625         }
1626         rc = virt_to_scatterlist(key_rec->enc_key, key_rec->enc_key_size,
1627                                  &dst_sg, 1);
1628         if (rc != 1) {
1629                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
1630                                 "for crypt_stat encrypted session key; "
1631                                 "expected rc = 1; got rc = [%d]. "
1632                                 "key_rec->enc_key_size = [%d]\n", rc,
1633                                 key_rec->enc_key_size);
1634                 rc = -ENOMEM;
1635                 goto out;
1636         }
1637         mutex_lock(tfm_mutex);
1638         rc = crypto_blkcipher_setkey(desc.tfm, session_key_encryption_key,
1639                                      crypt_stat->key_size);
1640         if (rc < 0) {
1641                 mutex_unlock(tfm_mutex);
1642                 ecryptfs_printk(KERN_ERR, "Error setting key for crypto "
1643                                 "context; rc = [%d]\n", rc);
1644                 goto out;
1645         }
1646         rc = 0;
1647         ecryptfs_printk(KERN_DEBUG, "Encrypting [%d] bytes of the key\n",
1648                         crypt_stat->key_size);
1649         rc = crypto_blkcipher_encrypt(&desc, &dst_sg, &src_sg,
1650                                       (*key_rec).enc_key_size);
1651         mutex_unlock(tfm_mutex);
1652         if (rc) {
1653                 printk(KERN_ERR "Error encrypting; rc = [%d]\n", rc);
1654                 goto out;
1655         }
1656         ecryptfs_printk(KERN_DEBUG, "This should be the encrypted key:\n");
1657         if (ecryptfs_verbosity > 0) {
1658                 ecryptfs_printk(KERN_DEBUG, "EFEK of size [%d]:\n",
1659                                 key_rec->enc_key_size);
1660                 ecryptfs_dump_hex(key_rec->enc_key,
1661                                   key_rec->enc_key_size);
1662         }
1663 encrypted_session_key_set:
1664         /* This format is inspired by OpenPGP; see RFC 2440
1665          * packet tag 3 */
1666         max_packet_size = (1                         /* Tag 3 identifier */
1667                            + 3                       /* Max Tag 3 packet size */
1668                            + 1                       /* Version */
1669                            + 1                       /* Cipher code */
1670                            + 1                       /* S2K specifier */
1671                            + 1                       /* Hash identifier */
1672                            + ECRYPTFS_SALT_SIZE      /* Salt */
1673                            + 1                       /* Hash iterations */
1674                            + key_rec->enc_key_size); /* Encrypted key size */
1675         if (max_packet_size > (*remaining_bytes)) {
1676                 printk(KERN_ERR "Packet too large; need up to [%td] bytes, but "
1677                        "there are only [%td] available\n", max_packet_size,
1678                        (*remaining_bytes));
1679                 rc = -EINVAL;
1680                 goto out;
1681         }
1682         dest[(*packet_size)++] = ECRYPTFS_TAG_3_PACKET_TYPE;
1683         /* Chop off the Tag 3 identifier(1) and Tag 3 packet size(3)
1684          * to get the number of octets in the actual Tag 3 packet */
1685         rc = write_packet_length(&dest[(*packet_size)], (max_packet_size - 4),
1686                                  &packet_size_length);
1687         if (rc) {
1688                 printk(KERN_ERR "Error generating tag 3 packet header; cannot "
1689                        "generate packet length. rc = [%d]\n", rc);
1690                 goto out;
1691         }
1692         (*packet_size) += packet_size_length;
1693         dest[(*packet_size)++] = 0x04; /* version 4 */
1694         /* TODO: Break from RFC2440 so that arbitrary ciphers can be
1695          * specified with strings */
1696         cipher_code = ecryptfs_code_for_cipher_string(crypt_stat);
1697         if (cipher_code == 0) {
1698                 ecryptfs_printk(KERN_WARNING, "Unable to generate code for "
1699                                 "cipher [%s]\n", crypt_stat->cipher);
1700                 rc = -EINVAL;
1701                 goto out;
1702         }
1703         dest[(*packet_size)++] = cipher_code;
1704         dest[(*packet_size)++] = 0x03;  /* S2K */
1705         dest[(*packet_size)++] = 0x01;  /* MD5 (TODO: parameterize) */
1706         memcpy(&dest[(*packet_size)], auth_tok->token.password.salt,
1707                ECRYPTFS_SALT_SIZE);
1708         (*packet_size) += ECRYPTFS_SALT_SIZE;   /* salt */
1709         dest[(*packet_size)++] = 0x60;  /* hash iterations (65536) */
1710         memcpy(&dest[(*packet_size)], key_rec->enc_key,
1711                key_rec->enc_key_size);
1712         (*packet_size) += key_rec->enc_key_size;
1713 out:
1714         if (rc)
1715                 (*packet_size) = 0;
1716         else
1717                 (*remaining_bytes) -= (*packet_size);
1718         return rc;
1719 }
1720
1721 struct kmem_cache *ecryptfs_key_record_cache;
1722
1723 /**
1724  * ecryptfs_generate_key_packet_set
1725  * @dest_base: Virtual address from which to write the key record set
1726  * @crypt_stat: The cryptographic context from which the
1727  *              authentication tokens will be retrieved
1728  * @ecryptfs_dentry: The dentry, used to retrieve the mount crypt stat
1729  *                   for the global parameters
1730  * @len: The amount written
1731  * @max: The maximum amount of data allowed to be written
1732  *
1733  * Generates a key packet set and writes it to the virtual address
1734  * passed in.
1735  *
1736  * Returns zero on success; non-zero on error.
1737  */
1738 int
1739 ecryptfs_generate_key_packet_set(char *dest_base,
1740                                  struct ecryptfs_crypt_stat *crypt_stat,
1741                                  struct dentry *ecryptfs_dentry, size_t *len,
1742                                  size_t max)
1743 {
1744         struct ecryptfs_auth_tok *auth_tok;
1745         struct ecryptfs_global_auth_tok *global_auth_tok;
1746         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
1747                 &ecryptfs_superblock_to_private(
1748                         ecryptfs_dentry->d_sb)->mount_crypt_stat;
1749         size_t written;
1750         struct ecryptfs_key_record *key_rec;
1751         struct ecryptfs_key_sig *key_sig;
1752         int rc = 0;
1753
1754         (*len) = 0;
1755         mutex_lock(&crypt_stat->keysig_list_mutex);
1756         key_rec = kmem_cache_alloc(ecryptfs_key_record_cache, GFP_KERNEL);
1757         if (!key_rec) {
1758                 rc = -ENOMEM;
1759                 goto out;
1760         }
1761         list_for_each_entry(key_sig, &crypt_stat->keysig_list,
1762                             crypt_stat_list) {
1763                 memset(key_rec, 0, sizeof(*key_rec));
1764                 rc = ecryptfs_find_global_auth_tok_for_sig(&global_auth_tok,
1765                                                            mount_crypt_stat,
1766                                                            key_sig->keysig);
1767                 if (rc) {
1768                         printk(KERN_ERR "Error attempting to get the global "
1769                                "auth_tok; rc = [%d]\n", rc);
1770                         goto out_free;
1771                 }
1772                 if (global_auth_tok->flags & ECRYPTFS_AUTH_TOK_INVALID) {
1773                         printk(KERN_WARNING
1774                                "Skipping invalid auth tok with sig = [%s]\n",
1775                                global_auth_tok->sig);
1776                         continue;
1777                 }
1778                 auth_tok = global_auth_tok->global_auth_tok;
1779                 if (auth_tok->token_type == ECRYPTFS_PASSWORD) {
1780                         rc = write_tag_3_packet((dest_base + (*len)),
1781                                                 &max, auth_tok,
1782                                                 crypt_stat, key_rec,
1783                                                 &written);
1784                         if (rc) {
1785                                 ecryptfs_printk(KERN_WARNING, "Error "
1786                                                 "writing tag 3 packet\n");
1787                                 goto out_free;
1788                         }
1789                         (*len) += written;
1790                         /* Write auth tok signature packet */
1791                         rc = write_tag_11_packet((dest_base + (*len)), &max,
1792                                                  key_rec->sig,
1793                                                  ECRYPTFS_SIG_SIZE, &written);
1794                         if (rc) {
1795                                 ecryptfs_printk(KERN_ERR, "Error writing "
1796                                                 "auth tok signature packet\n");
1797                                 goto out_free;
1798                         }
1799                         (*len) += written;
1800                 } else if (auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
1801                         rc = write_tag_1_packet(dest_base + (*len),
1802                                                 &max, auth_tok,
1803                                                 crypt_stat, key_rec, &written);
1804                         if (rc) {
1805                                 ecryptfs_printk(KERN_WARNING, "Error "
1806                                                 "writing tag 1 packet\n");
1807                                 goto out_free;
1808                         }
1809                         (*len) += written;
1810                 } else {
1811                         ecryptfs_printk(KERN_WARNING, "Unsupported "
1812                                         "authentication token type\n");
1813                         rc = -EINVAL;
1814                         goto out_free;
1815                 }
1816         }
1817         if (likely(max > 0)) {
1818                 dest_base[(*len)] = 0x00;
1819         } else {
1820                 ecryptfs_printk(KERN_ERR, "Error writing boundary byte\n");
1821                 rc = -EIO;
1822         }
1823 out_free:
1824         kmem_cache_free(ecryptfs_key_record_cache, key_rec);
1825 out:
1826         if (rc)
1827                 (*len) = 0;
1828         mutex_unlock(&crypt_stat->keysig_list_mutex);
1829         return rc;
1830 }
1831
1832 struct kmem_cache *ecryptfs_key_sig_cache;
1833
1834 int ecryptfs_add_keysig(struct ecryptfs_crypt_stat *crypt_stat, char *sig)
1835 {
1836         struct ecryptfs_key_sig *new_key_sig;
1837         int rc = 0;
1838
1839         new_key_sig = kmem_cache_alloc(ecryptfs_key_sig_cache, GFP_KERNEL);
1840         if (!new_key_sig) {
1841                 rc = -ENOMEM;
1842                 printk(KERN_ERR
1843                        "Error allocating from ecryptfs_key_sig_cache\n");
1844                 goto out;
1845         }
1846         memcpy(new_key_sig->keysig, sig, ECRYPTFS_SIG_SIZE_HEX);
1847         mutex_lock(&crypt_stat->keysig_list_mutex);
1848         list_add(&new_key_sig->crypt_stat_list, &crypt_stat->keysig_list);
1849         mutex_unlock(&crypt_stat->keysig_list_mutex);
1850 out:
1851         return rc;
1852 }
1853
1854 struct kmem_cache *ecryptfs_global_auth_tok_cache;
1855
1856 int
1857 ecryptfs_add_global_auth_tok(struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
1858                              char *sig)
1859 {
1860         struct ecryptfs_global_auth_tok *new_auth_tok;
1861         int rc = 0;
1862
1863         new_auth_tok = kmem_cache_zalloc(ecryptfs_global_auth_tok_cache,
1864                                         GFP_KERNEL);
1865         if (!new_auth_tok) {
1866                 rc = -ENOMEM;
1867                 printk(KERN_ERR "Error allocating from "
1868                        "ecryptfs_global_auth_tok_cache\n");
1869                 goto out;
1870         }
1871         memcpy(new_auth_tok->sig, sig, ECRYPTFS_SIG_SIZE_HEX);
1872         new_auth_tok->sig[ECRYPTFS_SIG_SIZE_HEX] = '\0';
1873         mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
1874         list_add(&new_auth_tok->mount_crypt_stat_list,
1875                  &mount_crypt_stat->global_auth_tok_list);
1876         mount_crypt_stat->num_global_auth_toks++;
1877         mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
1878 out:
1879         return rc;
1880 }
1881