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