eCryptfs: Filename Encryption: Tag 70 packets
[safe/jmp/linux-2.6] / fs / ecryptfs / keystore.c
1 /**
2  * eCryptfs: Linux filesystem encryption layer
3  * In-kernel key management code.  Includes functions to parse and
4  * write authentication token-related packets with the underlying
5  * file.
6  *
7  * Copyright (C) 2004-2006 International Business Machines Corp.
8  *   Author(s): Michael A. Halcrow <mhalcrow@us.ibm.com>
9  *              Michael C. Thompson <mcthomps@us.ibm.com>
10  *              Trevor S. Highland <trevor.highland@gmail.com>
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25  * 02111-1307, USA.
26  */
27
28 #include <linux/string.h>
29 #include <linux/syscalls.h>
30 #include <linux/pagemap.h>
31 #include <linux/key.h>
32 #include <linux/random.h>
33 #include <linux/crypto.h>
34 #include <linux/scatterlist.h>
35 #include "ecryptfs_kernel.h"
36
37 /**
38  * request_key returned an error instead of a valid key address;
39  * determine the type of error, make appropriate log entries, and
40  * return an error code.
41  */
42 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 message received from ecryptfsd "
238                                 "is 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_find_global_auth_tok_for_sig(
407         struct ecryptfs_global_auth_tok **global_auth_tok,
408         struct ecryptfs_mount_crypt_stat *mount_crypt_stat, char *sig)
409 {
410         struct ecryptfs_global_auth_tok *walker;
411         int rc = 0;
412
413         (*global_auth_tok) = NULL;
414         mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
415         list_for_each_entry(walker,
416                             &mount_crypt_stat->global_auth_tok_list,
417                             mount_crypt_stat_list) {
418                 if (memcmp(walker->sig, sig, ECRYPTFS_SIG_SIZE_HEX) == 0) {
419                         (*global_auth_tok) = walker;
420                         goto out;
421                 }
422         }
423         rc = -EINVAL;
424 out:
425         mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
426         return rc;
427 }
428
429 /**
430  * ecryptfs_find_auth_tok_for_sig
431  * @auth_tok: Set to the matching auth_tok; NULL if not found
432  * @crypt_stat: inode crypt_stat crypto context
433  * @sig: Sig of auth_tok to find
434  *
435  * For now, this function simply looks at the registered auth_tok's
436  * linked off the mount_crypt_stat, so all the auth_toks that can be
437  * used must be registered at mount time. This function could
438  * potentially try a lot harder to find auth_tok's (e.g., by calling
439  * out to ecryptfsd to dynamically retrieve an auth_tok object) so
440  * that static registration of auth_tok's will no longer be necessary.
441  *
442  * Returns zero on no error; non-zero on error
443  */
444 static int
445 ecryptfs_find_auth_tok_for_sig(
446         struct ecryptfs_auth_tok **auth_tok,
447         struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
448         char *sig)
449 {
450         struct ecryptfs_global_auth_tok *global_auth_tok;
451         int rc = 0;
452
453         (*auth_tok) = NULL;
454         if (ecryptfs_find_global_auth_tok_for_sig(&global_auth_tok,
455                                                   mount_crypt_stat, sig)) {
456                 struct key *auth_tok_key;
457
458                 rc = ecryptfs_keyring_auth_tok_for_sig(&auth_tok_key, auth_tok,
459                                                        sig);
460         } else
461                 (*auth_tok) = global_auth_tok->global_auth_tok;
462         return rc;
463 }
464
465 /**
466  * write_tag_70_packet can gobble a lot of stack space. We stuff most
467  * of the function's parameters in a kmalloc'd struct to help reduce
468  * eCryptfs' overall stack usage.
469  */
470 struct ecryptfs_write_tag_70_packet_silly_stack {
471         u8 cipher_code;
472         size_t max_packet_size;
473         size_t packet_size_len;
474         size_t block_aligned_filename_size;
475         size_t block_size;
476         size_t i;
477         size_t j;
478         size_t num_rand_bytes;
479         struct mutex *tfm_mutex;
480         char *block_aligned_filename;
481         struct ecryptfs_auth_tok *auth_tok;
482         struct scatterlist src_sg;
483         struct scatterlist dst_sg;
484         struct blkcipher_desc desc;
485         char iv[ECRYPTFS_MAX_IV_BYTES];
486         char hash[ECRYPTFS_TAG_70_DIGEST_SIZE];
487         char tmp_hash[ECRYPTFS_TAG_70_DIGEST_SIZE];
488         struct hash_desc hash_desc;
489         struct scatterlist hash_sg;
490 };
491
492 /**
493  * write_tag_70_packet - Write encrypted filename (EFN) packet against FNEK
494  * @filename: NULL-terminated filename string
495  *
496  * This is the simplest mechanism for achieving filename encryption in
497  * eCryptfs. It encrypts the given filename with the mount-wide
498  * filename encryption key (FNEK) and stores it in a packet to @dest,
499  * which the callee will encode and write directly into the dentry
500  * name.
501  */
502 int
503 ecryptfs_write_tag_70_packet(char *dest, size_t *remaining_bytes,
504                              size_t *packet_size,
505                              struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
506                              char *filename, size_t filename_size)
507 {
508         struct ecryptfs_write_tag_70_packet_silly_stack *s;
509         int rc = 0;
510
511         s = kmalloc(sizeof(*s), GFP_KERNEL);
512         if (!s) {
513                 printk(KERN_ERR "%s: Out of memory whilst trying to kmalloc "
514                        "[%d] bytes of kernel memory\n", __func__, sizeof(*s));
515                 goto out;
516         }
517         s->desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
518         (*packet_size) = 0;
519         rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(
520                 &s->desc.tfm,
521                 &s->tfm_mutex, mount_crypt_stat->global_default_fn_cipher_name);
522         if (unlikely(rc)) {
523                 printk(KERN_ERR "Internal error whilst attempting to get "
524                        "tfm and mutex for cipher name [%s]; rc = [%d]\n",
525                        mount_crypt_stat->global_default_fn_cipher_name, rc);
526                 goto out;
527         }
528         mutex_lock(s->tfm_mutex);
529         s->block_size = crypto_blkcipher_blocksize(s->desc.tfm);
530         /* Plus one for the \0 separator between the random prefix
531          * and the plaintext filename */
532         s->num_rand_bytes = (ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES + 1);
533         s->block_aligned_filename_size = (s->num_rand_bytes + filename_size);
534         if ((s->block_aligned_filename_size % s->block_size) != 0) {
535                 s->num_rand_bytes += (s->block_size
536                                       - (s->block_aligned_filename_size
537                                          % s->block_size));
538                 s->block_aligned_filename_size = (s->num_rand_bytes
539                                                   + filename_size);
540         }
541         /* Octet 0: Tag 70 identifier
542          * Octets 1-N1: Tag 70 packet size (includes cipher identifier
543          *              and block-aligned encrypted filename size)
544          * Octets N1-N2: FNEK sig (ECRYPTFS_SIG_SIZE)
545          * Octet N2-N3: Cipher identifier (1 octet)
546          * Octets N3-N4: Block-aligned encrypted filename
547          *  - Consists of a minimum number of random characters, a \0
548          *    separator, and then the filename */
549         s->max_packet_size = (1                   /* Tag 70 identifier */
550                               + 3                 /* Max Tag 70 packet size */
551                               + ECRYPTFS_SIG_SIZE /* FNEK sig */
552                               + 1                 /* Cipher identifier */
553                               + s->block_aligned_filename_size);
554         if (dest == NULL) {
555                 (*packet_size) = s->max_packet_size;
556                 goto out_unlock;
557         }
558         if (s->max_packet_size > (*remaining_bytes)) {
559                 printk(KERN_WARNING "%s: Require [%d] bytes to write; only "
560                        "[%d] available\n", __func__, s->max_packet_size,
561                        (*remaining_bytes));
562                 rc = -EINVAL;
563                 goto out_unlock;
564         }
565         s->block_aligned_filename = kzalloc(s->block_aligned_filename_size,
566                                             GFP_KERNEL);
567         if (!s->block_aligned_filename) {
568                 printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
569                        "kzalloc [%Zd] bytes\n", __func__,
570                        s->block_aligned_filename_size);
571                 rc = -ENOMEM;
572                 goto out_unlock;
573         }
574         s->i = 0;
575         dest[s->i++] = ECRYPTFS_TAG_70_PACKET_TYPE;
576         rc = ecryptfs_write_packet_length(&dest[s->i],
577                                           (ECRYPTFS_SIG_SIZE
578                                            + 1 /* Cipher code */
579                                            + s->block_aligned_filename_size),
580                                           &s->packet_size_len);
581         if (rc) {
582                 printk(KERN_ERR "%s: Error generating tag 70 packet "
583                        "header; cannot generate packet length; rc = [%d]\n",
584                        __func__, rc);
585                 goto out_free_unlock;
586         }
587         s->i += s->packet_size_len;
588         ecryptfs_from_hex(&dest[s->i],
589                           mount_crypt_stat->global_default_fnek_sig,
590                           ECRYPTFS_SIG_SIZE);
591         s->i += ECRYPTFS_SIG_SIZE;
592         s->cipher_code = ecryptfs_code_for_cipher_string(
593                 mount_crypt_stat->global_default_fn_cipher_name,
594                 mount_crypt_stat->global_default_fn_cipher_key_bytes);
595         if (s->cipher_code == 0) {
596                 printk(KERN_WARNING "%s: Unable to generate code for "
597                        "cipher [%s] with key bytes [%d]\n", __func__,
598                        mount_crypt_stat->global_default_fn_cipher_name,
599                        mount_crypt_stat->global_default_fn_cipher_key_bytes);
600                 rc = -EINVAL;
601                 goto out_free_unlock;
602         }
603         dest[s->i++] = s->cipher_code;
604         rc = ecryptfs_find_auth_tok_for_sig(
605                 &s->auth_tok, mount_crypt_stat,
606                 mount_crypt_stat->global_default_fnek_sig);
607         if (rc) {
608                 printk(KERN_ERR "%s: Error attempting to find auth tok for "
609                        "fnek sig [%s]; rc = [%d]\n", __func__,
610                        mount_crypt_stat->global_default_fnek_sig, rc);
611                 goto out_free_unlock;
612         }
613         /* TODO: Support other key modules than passphrase for
614          * filename encryption */
615         BUG_ON(s->auth_tok->token_type != ECRYPTFS_PASSWORD);
616         sg_init_one(
617                 &s->hash_sg,
618                 (u8 *)s->auth_tok->token.password.session_key_encryption_key,
619                 s->auth_tok->token.password.session_key_encryption_key_bytes);
620         s->hash_desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
621         s->hash_desc.tfm = crypto_alloc_hash(ECRYPTFS_TAG_70_DIGEST, 0,
622                                              CRYPTO_ALG_ASYNC);
623         if (IS_ERR(s->hash_desc.tfm)) {
624                         rc = PTR_ERR(s->hash_desc.tfm);
625                         printk(KERN_ERR "%s: Error attempting to "
626                                "allocate hash crypto context; rc = [%d]\n",
627                                __func__, rc);
628                         goto out_free_unlock;
629         }
630         rc = crypto_hash_init(&s->hash_desc);
631         if (rc) {
632                 printk(KERN_ERR
633                        "%s: Error initializing crypto hash; rc = [%d]\n",
634                        __func__, rc);
635                 goto out_release_free_unlock;
636         }
637         rc = crypto_hash_update(
638                 &s->hash_desc, &s->hash_sg,
639                 s->auth_tok->token.password.session_key_encryption_key_bytes);
640         if (rc) {
641                 printk(KERN_ERR
642                        "%s: Error updating crypto hash; rc = [%d]\n",
643                        __func__, rc);
644                 goto out_release_free_unlock;
645         }
646         rc = crypto_hash_final(&s->hash_desc, s->hash);
647         if (rc) {
648                 printk(KERN_ERR
649                        "%s: Error finalizing crypto hash; rc = [%d]\n",
650                        __func__, rc);
651                 goto out_release_free_unlock;
652         }
653         for (s->j = 0; s->j < (s->num_rand_bytes - 1); s->j++) {
654                 s->block_aligned_filename[s->j] =
655                         s->hash[(s->j % ECRYPTFS_TAG_70_DIGEST_SIZE)];
656                 if ((s->j % ECRYPTFS_TAG_70_DIGEST_SIZE)
657                     == (ECRYPTFS_TAG_70_DIGEST_SIZE - 1)) {
658                         sg_init_one(&s->hash_sg, (u8 *)s->hash,
659                                     ECRYPTFS_TAG_70_DIGEST_SIZE);
660                         rc = crypto_hash_init(&s->hash_desc);
661                         if (rc) {
662                                 printk(KERN_ERR
663                                        "%s: Error initializing crypto hash; "
664                                        "rc = [%d]\n", __func__, rc);
665                                 goto out_release_free_unlock;
666                         }
667                         rc = crypto_hash_update(&s->hash_desc, &s->hash_sg,
668                                                 ECRYPTFS_TAG_70_DIGEST_SIZE);
669                         if (rc) {
670                                 printk(KERN_ERR
671                                        "%s: Error updating crypto hash; "
672                                        "rc = [%d]\n", __func__, rc);
673                                 goto out_release_free_unlock;
674                         }
675                         rc = crypto_hash_final(&s->hash_desc, s->tmp_hash);
676                         if (rc) {
677                                 printk(KERN_ERR
678                                        "%s: Error finalizing crypto hash; "
679                                        "rc = [%d]\n", __func__, rc);
680                                 goto out_release_free_unlock;
681                         }
682                         memcpy(s->hash, s->tmp_hash,
683                                ECRYPTFS_TAG_70_DIGEST_SIZE);
684                 }
685                 if (s->block_aligned_filename[s->j] == '\0')
686                         s->block_aligned_filename[s->j] = ECRYPTFS_NON_NULL;
687         }
688         memcpy(&s->block_aligned_filename[s->num_rand_bytes], filename,
689                filename_size);
690         rc = virt_to_scatterlist(s->block_aligned_filename,
691                                  s->block_aligned_filename_size, &s->src_sg, 1);
692         if (rc != 1) {
693                 printk(KERN_ERR "%s: Internal error whilst attempting to "
694                        "convert filename memory to scatterlist; "
695                        "expected rc = 1; got rc = [%d]. "
696                        "block_aligned_filename_size = [%d]\n", __func__, rc,
697                        s->block_aligned_filename_size);
698                 goto out_release_free_unlock;
699         }
700         rc = virt_to_scatterlist(&dest[s->i], s->block_aligned_filename_size,
701                                  &s->dst_sg, 1);
702         if (rc != 1) {
703                 printk(KERN_ERR "%s: Internal error whilst attempting to "
704                        "convert encrypted filename memory to scatterlist; "
705                        "expected rc = 1; got rc = [%d]. "
706                        "block_aligned_filename_size = [%d]\n", __func__, rc,
707                        s->block_aligned_filename_size);
708                 goto out_release_free_unlock;
709         }
710         /* The characters in the first block effectively do the job
711          * of the IV here, so we just use 0's for the IV. Note the
712          * constraint that ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES
713          * >= ECRYPTFS_MAX_IV_BYTES. */
714         memset(s->iv, 0, ECRYPTFS_MAX_IV_BYTES);
715         s->desc.info = s->iv;
716         rc = crypto_blkcipher_setkey(
717                 s->desc.tfm,
718                 s->auth_tok->token.password.session_key_encryption_key,
719                 mount_crypt_stat->global_default_fn_cipher_key_bytes);
720         if (rc < 0) {
721                 printk(KERN_ERR "%s: Error setting key for crypto context; "
722                        "rc = [%d]. s->auth_tok->token.password.session_key_"
723                        "encryption_key = [0x%p]; mount_crypt_stat->"
724                        "global_default_fn_cipher_key_bytes = [%Zd]\n", __func__,
725                        rc,
726                        s->auth_tok->token.password.session_key_encryption_key,
727                        mount_crypt_stat->global_default_fn_cipher_key_bytes);
728                 goto out_release_free_unlock;
729         }
730         rc = crypto_blkcipher_encrypt_iv(&s->desc, &s->dst_sg, &s->src_sg,
731                                          s->block_aligned_filename_size);
732         if (rc) {
733                 printk(KERN_ERR "%s: Error attempting to encrypt filename; "
734                        "rc = [%d]\n", __func__, rc);
735                 goto out_release_free_unlock;
736         }
737         s->i += s->block_aligned_filename_size;
738         (*packet_size) = s->i;
739         (*remaining_bytes) -= (*packet_size);
740 out_release_free_unlock:
741         crypto_free_hash(s->hash_desc.tfm);
742 out_free_unlock:
743         memset(s->block_aligned_filename, 0, s->block_aligned_filename_size);
744         kfree(s->block_aligned_filename);
745 out_unlock:
746         mutex_unlock(s->tfm_mutex);
747 out:
748         kfree(s);
749         return rc;
750 }
751
752 struct ecryptfs_parse_tag_70_packet_silly_stack {
753         u8 cipher_code;
754         size_t max_packet_size;
755         size_t packet_size_len;
756         size_t parsed_tag_70_packet_size;
757         size_t block_aligned_filename_size;
758         size_t block_size;
759         size_t i;
760         struct mutex *tfm_mutex;
761         char *decrypted_filename;
762         struct ecryptfs_auth_tok *auth_tok;
763         struct scatterlist src_sg;
764         struct scatterlist dst_sg;
765         struct blkcipher_desc desc;
766         char fnek_sig_hex[ECRYPTFS_SIG_SIZE_HEX + 1];
767         char iv[ECRYPTFS_MAX_IV_BYTES];
768         char cipher_string[ECRYPTFS_MAX_CIPHER_NAME_SIZE];
769 };
770
771 /**
772  * parse_tag_70_packet - Parse and process FNEK-encrypted passphrase packet
773  * @filename: This function kmalloc's the memory for the filename
774  */
775 int
776 ecryptfs_parse_tag_70_packet(char **filename, size_t *filename_size,
777                              size_t *packet_size,
778                              struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
779                              char *data, size_t max_packet_size)
780 {
781         struct ecryptfs_parse_tag_70_packet_silly_stack *s;
782         int rc = 0;
783
784         (*packet_size) = 0;
785         (*filename_size) = 0;
786         (*filename) = NULL;
787         s = kmalloc(sizeof(*s), GFP_KERNEL);
788         if (!s) {
789                 printk(KERN_ERR "%s: Out of memory whilst trying to kmalloc "
790                        "[%d] bytes of kernel memory\n", __func__, sizeof(*s));
791                 goto out;
792         }
793         s->desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
794         if (max_packet_size < (1 + 1 + ECRYPTFS_SIG_SIZE + 1 + 1)) {
795                 printk(KERN_WARNING "%s: max_packet_size is [%Zd]; it must be "
796                        "at least [%d]\n", __func__, max_packet_size,
797                         (1 + 1 + ECRYPTFS_SIG_SIZE + 1 + 1));
798                 rc = -EINVAL;
799                 goto out;
800         }
801         /* Octet 0: Tag 70 identifier
802          * Octets 1-N1: Tag 70 packet size (includes cipher identifier
803          *              and block-aligned encrypted filename size)
804          * Octets N1-N2: FNEK sig (ECRYPTFS_SIG_SIZE)
805          * Octet N2-N3: Cipher identifier (1 octet)
806          * Octets N3-N4: Block-aligned encrypted filename
807          *  - Consists of a minimum number of random numbers, a \0
808          *    separator, and then the filename */
809         if (data[(*packet_size)++] != ECRYPTFS_TAG_70_PACKET_TYPE) {
810                 printk(KERN_WARNING "%s: Invalid packet tag [0x%.2x]; must be "
811                        "tag [0x%.2x]\n", __func__,
812                        data[((*packet_size) - 1)], ECRYPTFS_TAG_70_PACKET_TYPE);
813                 rc = -EINVAL;
814                 goto out;
815         }
816         rc = ecryptfs_parse_packet_length(&data[(*packet_size)],
817                                           &s->parsed_tag_70_packet_size,
818                                           &s->packet_size_len);
819         if (rc) {
820                 printk(KERN_WARNING "%s: Error parsing packet length; "
821                        "rc = [%d]\n", __func__, rc);
822                 goto out;
823         }
824         s->block_aligned_filename_size = (s->parsed_tag_70_packet_size
825                                           - ECRYPTFS_SIG_SIZE - 1);
826         if ((1 + s->packet_size_len + s->parsed_tag_70_packet_size)
827             > max_packet_size) {
828                 printk(KERN_WARNING "%s: max_packet_size is [%d]; real packet "
829                        "size is [%d]\n", __func__, max_packet_size,
830                        (1 + s->packet_size_len + 1
831                         + s->block_aligned_filename_size));
832                 rc = -EINVAL;
833                 goto out;
834         }
835         (*packet_size) += s->packet_size_len;
836         ecryptfs_to_hex(s->fnek_sig_hex, &data[(*packet_size)],
837                         ECRYPTFS_SIG_SIZE);
838         s->fnek_sig_hex[ECRYPTFS_SIG_SIZE_HEX] = '\0';
839         (*packet_size) += ECRYPTFS_SIG_SIZE;
840         s->cipher_code = data[(*packet_size)++];
841         rc = ecryptfs_cipher_code_to_string(s->cipher_string, s->cipher_code);
842         if (rc) {
843                 printk(KERN_WARNING "%s: Cipher code [%d] is invalid\n",
844                        __func__, s->cipher_code);
845                 goto out;
846         }
847         rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&s->desc.tfm,
848                                                         &s->tfm_mutex,
849                                                         s->cipher_string);
850         if (unlikely(rc)) {
851                 printk(KERN_ERR "Internal error whilst attempting to get "
852                        "tfm and mutex for cipher name [%s]; rc = [%d]\n",
853                        s->cipher_string, rc);
854                 goto out;
855         }
856         mutex_lock(s->tfm_mutex);
857         rc = virt_to_scatterlist(&data[(*packet_size)],
858                                  s->block_aligned_filename_size, &s->src_sg, 1);
859         if (rc != 1) {
860                 printk(KERN_ERR "%s: Internal error whilst attempting to "
861                        "convert encrypted filename memory to scatterlist; "
862                        "expected rc = 1; got rc = [%d]. "
863                        "block_aligned_filename_size = [%d]\n", __func__, rc,
864                        s->block_aligned_filename_size);
865                 goto out_unlock;
866         }
867         (*packet_size) += s->block_aligned_filename_size;
868         s->decrypted_filename = kmalloc(s->block_aligned_filename_size,
869                                         GFP_KERNEL);
870         if (!s->decrypted_filename) {
871                 printk(KERN_ERR "%s: Out of memory whilst attempting to "
872                        "kmalloc [%d] bytes\n", __func__,
873                        s->block_aligned_filename_size);
874                 rc = -ENOMEM;
875                 goto out_unlock;
876         }
877         rc = virt_to_scatterlist(s->decrypted_filename,
878                                  s->block_aligned_filename_size, &s->dst_sg, 1);
879         if (rc != 1) {
880                 printk(KERN_ERR "%s: Internal error whilst attempting to "
881                        "convert decrypted filename memory to scatterlist; "
882                        "expected rc = 1; got rc = [%d]. "
883                        "block_aligned_filename_size = [%d]\n", __func__, rc,
884                        s->block_aligned_filename_size);
885                 goto out_free_unlock;
886         }
887         /* The characters in the first block effectively do the job of
888          * the IV here, so we just use 0's for the IV. Note the
889          * constraint that ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES
890          * >= ECRYPTFS_MAX_IV_BYTES. */
891         memset(s->iv, 0, ECRYPTFS_MAX_IV_BYTES);
892         s->desc.info = s->iv;
893         rc = ecryptfs_find_auth_tok_for_sig(&s->auth_tok, mount_crypt_stat,
894                                             s->fnek_sig_hex);
895         if (rc) {
896                 printk(KERN_ERR "%s: Error attempting to find auth tok for "
897                        "fnek sig [%s]; rc = [%d]\n", __func__, s->fnek_sig_hex,
898                        rc);
899                 goto out_free_unlock;
900         }
901         /* TODO: Support other key modules than passphrase for
902          * filename encryption */
903         BUG_ON(s->auth_tok->token_type != ECRYPTFS_PASSWORD);
904         rc = crypto_blkcipher_setkey(
905                 s->desc.tfm,
906                 s->auth_tok->token.password.session_key_encryption_key,
907                 mount_crypt_stat->global_default_fn_cipher_key_bytes);
908         if (rc < 0) {
909                 printk(KERN_ERR "%s: Error setting key for crypto context; "
910                        "rc = [%d]. s->auth_tok->token.password.session_key_"
911                        "encryption_key = [0x%p]; mount_crypt_stat->"
912                        "global_default_fn_cipher_key_bytes = [%Zd]\n", __func__,
913                        rc,
914                        s->auth_tok->token.password.session_key_encryption_key,
915                        mount_crypt_stat->global_default_fn_cipher_key_bytes);
916                 goto out_free_unlock;
917         }
918         rc = crypto_blkcipher_decrypt_iv(&s->desc, &s->dst_sg, &s->src_sg,
919                                          s->block_aligned_filename_size);
920         if (rc) {
921                 printk(KERN_ERR "%s: Error attempting to decrypt filename; "
922                        "rc = [%d]\n", __func__, rc);
923                 goto out_free_unlock;
924         }
925         s->i = 0;
926         while (s->decrypted_filename[s->i] != '\0'
927                && s->i < s->block_aligned_filename_size)
928                 s->i++;
929         if (s->i == s->block_aligned_filename_size) {
930                 printk(KERN_WARNING "%s: Invalid tag 70 packet; could not "
931                        "find valid separator between random characters and "
932                        "the filename\n", __func__);
933                 rc = -EINVAL;
934                 goto out_free_unlock;
935         }
936         s->i++;
937         (*filename_size) = (s->block_aligned_filename_size - s->i);
938         if (!((*filename_size) > 0 && (*filename_size < PATH_MAX))) {
939                 printk(KERN_WARNING "%s: Filename size is [%Zd], which is "
940                        "invalid\n", __func__, (*filename_size));
941                 rc = -EINVAL;
942                 goto out_free_unlock;
943         }
944         (*filename) = kmalloc(((*filename_size) + 1), GFP_KERNEL);
945         if (!(*filename)) {
946                 printk(KERN_ERR "%s: Out of memory whilst attempting to "
947                        "kmalloc [%d] bytes\n", __func__,
948                        ((*filename_size) + 1));
949                 rc = -ENOMEM;
950                 goto out_free_unlock;
951         }
952         memcpy((*filename), &s->decrypted_filename[s->i], (*filename_size));
953         (*filename)[(*filename_size)] = '\0';
954 out_free_unlock:
955         kfree(s->decrypted_filename);
956 out_unlock:
957         mutex_unlock(s->tfm_mutex);
958 out:
959         if (rc) {
960                 (*packet_size) = 0;
961                 (*filename_size) = 0;
962                 (*filename) = NULL;
963         }
964         kfree(s);
965         return rc;
966 }
967
968 static int
969 ecryptfs_get_auth_tok_sig(char **sig, struct ecryptfs_auth_tok *auth_tok)
970 {
971         int rc = 0;
972
973         (*sig) = NULL;
974         switch (auth_tok->token_type) {
975         case ECRYPTFS_PASSWORD:
976                 (*sig) = auth_tok->token.password.signature;
977                 break;
978         case ECRYPTFS_PRIVATE_KEY:
979                 (*sig) = auth_tok->token.private_key.signature;
980                 break;
981         default:
982                 printk(KERN_ERR "Cannot get sig for auth_tok of type [%d]\n",
983                        auth_tok->token_type);
984                 rc = -EINVAL;
985         }
986         return rc;
987 }
988
989 /**
990  * decrypt_pki_encrypted_session_key - Decrypt the session key with the given auth_tok.
991  * @auth_tok: The key authentication token used to decrypt the session key
992  * @crypt_stat: The cryptographic context
993  *
994  * Returns zero on success; non-zero error otherwise.
995  */
996 static int
997 decrypt_pki_encrypted_session_key(struct ecryptfs_auth_tok *auth_tok,
998                                   struct ecryptfs_crypt_stat *crypt_stat)
999 {
1000         u8 cipher_code = 0;
1001         struct ecryptfs_msg_ctx *msg_ctx;
1002         struct ecryptfs_message *msg = NULL;
1003         char *auth_tok_sig;
1004         char *payload;
1005         size_t payload_len;
1006         int rc;
1007
1008         rc = ecryptfs_get_auth_tok_sig(&auth_tok_sig, auth_tok);
1009         if (rc) {
1010                 printk(KERN_ERR "Unrecognized auth tok type: [%d]\n",
1011                        auth_tok->token_type);
1012                 goto out;
1013         }
1014         rc = write_tag_64_packet(auth_tok_sig, &(auth_tok->session_key),
1015                                  &payload, &payload_len);
1016         if (rc) {
1017                 ecryptfs_printk(KERN_ERR, "Failed to write tag 64 packet\n");
1018                 goto out;
1019         }
1020         rc = ecryptfs_send_message(payload, payload_len, &msg_ctx);
1021         if (rc) {
1022                 ecryptfs_printk(KERN_ERR, "Error sending message to "
1023                                 "ecryptfsd\n");
1024                 goto out;
1025         }
1026         rc = ecryptfs_wait_for_response(msg_ctx, &msg);
1027         if (rc) {
1028                 ecryptfs_printk(KERN_ERR, "Failed to receive tag 65 packet "
1029                                 "from the user space daemon\n");
1030                 rc = -EIO;
1031                 goto out;
1032         }
1033         rc = parse_tag_65_packet(&(auth_tok->session_key),
1034                                  &cipher_code, msg);
1035         if (rc) {
1036                 printk(KERN_ERR "Failed to parse tag 65 packet; rc = [%d]\n",
1037                        rc);
1038                 goto out;
1039         }
1040         auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1041         memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
1042                auth_tok->session_key.decrypted_key_size);
1043         crypt_stat->key_size = auth_tok->session_key.decrypted_key_size;
1044         rc = ecryptfs_cipher_code_to_string(crypt_stat->cipher, cipher_code);
1045         if (rc) {
1046                 ecryptfs_printk(KERN_ERR, "Cipher code [%d] is invalid\n",
1047                                 cipher_code)
1048                 goto out;
1049         }
1050         crypt_stat->flags |= ECRYPTFS_KEY_VALID;
1051         if (ecryptfs_verbosity > 0) {
1052                 ecryptfs_printk(KERN_DEBUG, "Decrypted session key:\n");
1053                 ecryptfs_dump_hex(crypt_stat->key,
1054                                   crypt_stat->key_size);
1055         }
1056 out:
1057         if (msg)
1058                 kfree(msg);
1059         return rc;
1060 }
1061
1062 static void wipe_auth_tok_list(struct list_head *auth_tok_list_head)
1063 {
1064         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1065         struct ecryptfs_auth_tok_list_item *auth_tok_list_item_tmp;
1066
1067         list_for_each_entry_safe(auth_tok_list_item, auth_tok_list_item_tmp,
1068                                  auth_tok_list_head, list) {
1069                 list_del(&auth_tok_list_item->list);
1070                 kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1071                                 auth_tok_list_item);
1072         }
1073 }
1074
1075 struct kmem_cache *ecryptfs_auth_tok_list_item_cache;
1076
1077 /**
1078  * parse_tag_1_packet
1079  * @crypt_stat: The cryptographic context to modify based on packet contents
1080  * @data: The raw bytes of the packet.
1081  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
1082  *                 a new authentication token will be placed at the
1083  *                 end of this list for this packet.
1084  * @new_auth_tok: Pointer to a pointer to memory that this function
1085  *                allocates; sets the memory address of the pointer to
1086  *                NULL on error. This object is added to the
1087  *                auth_tok_list.
1088  * @packet_size: This function writes the size of the parsed packet
1089  *               into this memory location; zero on error.
1090  * @max_packet_size: The maximum allowable packet size
1091  *
1092  * Returns zero on success; non-zero on error.
1093  */
1094 static int
1095 parse_tag_1_packet(struct ecryptfs_crypt_stat *crypt_stat,
1096                    unsigned char *data, struct list_head *auth_tok_list,
1097                    struct ecryptfs_auth_tok **new_auth_tok,
1098                    size_t *packet_size, size_t max_packet_size)
1099 {
1100         size_t body_size;
1101         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1102         size_t length_size;
1103         int rc = 0;
1104
1105         (*packet_size) = 0;
1106         (*new_auth_tok) = NULL;
1107         /**
1108          * This format is inspired by OpenPGP; see RFC 2440
1109          * packet tag 1
1110          *
1111          * Tag 1 identifier (1 byte)
1112          * Max Tag 1 packet size (max 3 bytes)
1113          * Version (1 byte)
1114          * Key identifier (8 bytes; ECRYPTFS_SIG_SIZE)
1115          * Cipher identifier (1 byte)
1116          * Encrypted key size (arbitrary)
1117          *
1118          * 12 bytes minimum packet size
1119          */
1120         if (unlikely(max_packet_size < 12)) {
1121                 printk(KERN_ERR "Invalid max packet size; must be >=12\n");
1122                 rc = -EINVAL;
1123                 goto out;
1124         }
1125         if (data[(*packet_size)++] != ECRYPTFS_TAG_1_PACKET_TYPE) {
1126                 printk(KERN_ERR "Enter w/ first byte != 0x%.2x\n",
1127                        ECRYPTFS_TAG_1_PACKET_TYPE);
1128                 rc = -EINVAL;
1129                 goto out;
1130         }
1131         /* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
1132          * at end of function upon failure */
1133         auth_tok_list_item =
1134                 kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache,
1135                                   GFP_KERNEL);
1136         if (!auth_tok_list_item) {
1137                 printk(KERN_ERR "Unable to allocate memory\n");
1138                 rc = -ENOMEM;
1139                 goto out;
1140         }
1141         (*new_auth_tok) = &auth_tok_list_item->auth_tok;
1142         rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1143                                           &length_size);
1144         if (rc) {
1145                 printk(KERN_WARNING "Error parsing packet length; "
1146                        "rc = [%d]\n", rc);
1147                 goto out_free;
1148         }
1149         if (unlikely(body_size < (ECRYPTFS_SIG_SIZE + 2))) {
1150                 printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1151                 rc = -EINVAL;
1152                 goto out_free;
1153         }
1154         (*packet_size) += length_size;
1155         if (unlikely((*packet_size) + body_size > max_packet_size)) {
1156                 printk(KERN_WARNING "Packet size exceeds max\n");
1157                 rc = -EINVAL;
1158                 goto out_free;
1159         }
1160         if (unlikely(data[(*packet_size)++] != 0x03)) {
1161                 printk(KERN_WARNING "Unknown version number [%d]\n",
1162                        data[(*packet_size) - 1]);
1163                 rc = -EINVAL;
1164                 goto out_free;
1165         }
1166         ecryptfs_to_hex((*new_auth_tok)->token.private_key.signature,
1167                         &data[(*packet_size)], ECRYPTFS_SIG_SIZE);
1168         *packet_size += ECRYPTFS_SIG_SIZE;
1169         /* This byte is skipped because the kernel does not need to
1170          * know which public key encryption algorithm was used */
1171         (*packet_size)++;
1172         (*new_auth_tok)->session_key.encrypted_key_size =
1173                 body_size - (ECRYPTFS_SIG_SIZE + 2);
1174         if ((*new_auth_tok)->session_key.encrypted_key_size
1175             > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
1176                 printk(KERN_WARNING "Tag 1 packet contains key larger "
1177                        "than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES");
1178                 rc = -EINVAL;
1179                 goto out;
1180         }
1181         memcpy((*new_auth_tok)->session_key.encrypted_key,
1182                &data[(*packet_size)], (body_size - (ECRYPTFS_SIG_SIZE + 2)));
1183         (*packet_size) += (*new_auth_tok)->session_key.encrypted_key_size;
1184         (*new_auth_tok)->session_key.flags &=
1185                 ~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1186         (*new_auth_tok)->session_key.flags |=
1187                 ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
1188         (*new_auth_tok)->token_type = ECRYPTFS_PRIVATE_KEY;
1189         (*new_auth_tok)->flags = 0;
1190         (*new_auth_tok)->session_key.flags &=
1191                 ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
1192         (*new_auth_tok)->session_key.flags &=
1193                 ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
1194         list_add(&auth_tok_list_item->list, auth_tok_list);
1195         goto out;
1196 out_free:
1197         (*new_auth_tok) = NULL;
1198         memset(auth_tok_list_item, 0,
1199                sizeof(struct ecryptfs_auth_tok_list_item));
1200         kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1201                         auth_tok_list_item);
1202 out:
1203         if (rc)
1204                 (*packet_size) = 0;
1205         return rc;
1206 }
1207
1208 /**
1209  * parse_tag_3_packet
1210  * @crypt_stat: The cryptographic context to modify based on packet
1211  *              contents.
1212  * @data: The raw bytes of the packet.
1213  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
1214  *                 a new authentication token will be placed at the end
1215  *                 of this list for this packet.
1216  * @new_auth_tok: Pointer to a pointer to memory that this function
1217  *                allocates; sets the memory address of the pointer to
1218  *                NULL on error. This object is added to the
1219  *                auth_tok_list.
1220  * @packet_size: This function writes the size of the parsed packet
1221  *               into this memory location; zero on error.
1222  * @max_packet_size: maximum number of bytes to parse
1223  *
1224  * Returns zero on success; non-zero on error.
1225  */
1226 static int
1227 parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat,
1228                    unsigned char *data, struct list_head *auth_tok_list,
1229                    struct ecryptfs_auth_tok **new_auth_tok,
1230                    size_t *packet_size, size_t max_packet_size)
1231 {
1232         size_t body_size;
1233         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1234         size_t length_size;
1235         int rc = 0;
1236
1237         (*packet_size) = 0;
1238         (*new_auth_tok) = NULL;
1239         /**
1240          *This format is inspired by OpenPGP; see RFC 2440
1241          * packet tag 3
1242          *
1243          * Tag 3 identifier (1 byte)
1244          * Max Tag 3 packet size (max 3 bytes)
1245          * Version (1 byte)
1246          * Cipher code (1 byte)
1247          * S2K specifier (1 byte)
1248          * Hash identifier (1 byte)
1249          * Salt (ECRYPTFS_SALT_SIZE)
1250          * Hash iterations (1 byte)
1251          * Encrypted key (arbitrary)
1252          *
1253          * (ECRYPTFS_SALT_SIZE + 7) minimum packet size
1254          */
1255         if (max_packet_size < (ECRYPTFS_SALT_SIZE + 7)) {
1256                 printk(KERN_ERR "Max packet size too large\n");
1257                 rc = -EINVAL;
1258                 goto out;
1259         }
1260         if (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) {
1261                 printk(KERN_ERR "First byte != 0x%.2x; invalid packet\n",
1262                        ECRYPTFS_TAG_3_PACKET_TYPE);
1263                 rc = -EINVAL;
1264                 goto out;
1265         }
1266         /* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
1267          * at end of function upon failure */
1268         auth_tok_list_item =
1269             kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL);
1270         if (!auth_tok_list_item) {
1271                 printk(KERN_ERR "Unable to allocate memory\n");
1272                 rc = -ENOMEM;
1273                 goto out;
1274         }
1275         (*new_auth_tok) = &auth_tok_list_item->auth_tok;
1276         rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1277                                           &length_size);
1278         if (rc) {
1279                 printk(KERN_WARNING "Error parsing packet length; rc = [%d]\n",
1280                        rc);
1281                 goto out_free;
1282         }
1283         if (unlikely(body_size < (ECRYPTFS_SALT_SIZE + 5))) {
1284                 printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1285                 rc = -EINVAL;
1286                 goto out_free;
1287         }
1288         (*packet_size) += length_size;
1289         if (unlikely((*packet_size) + body_size > max_packet_size)) {
1290                 printk(KERN_ERR "Packet size exceeds max\n");
1291                 rc = -EINVAL;
1292                 goto out_free;
1293         }
1294         (*new_auth_tok)->session_key.encrypted_key_size =
1295                 (body_size - (ECRYPTFS_SALT_SIZE + 5));
1296         if (unlikely(data[(*packet_size)++] != 0x04)) {
1297                 printk(KERN_WARNING "Unknown version number [%d]\n",
1298                        data[(*packet_size) - 1]);
1299                 rc = -EINVAL;
1300                 goto out_free;
1301         }
1302         ecryptfs_cipher_code_to_string(crypt_stat->cipher,
1303                                        (u16)data[(*packet_size)]);
1304         /* A little extra work to differentiate among the AES key
1305          * sizes; see RFC2440 */
1306         switch(data[(*packet_size)++]) {
1307         case RFC2440_CIPHER_AES_192:
1308                 crypt_stat->key_size = 24;
1309                 break;
1310         default:
1311                 crypt_stat->key_size =
1312                         (*new_auth_tok)->session_key.encrypted_key_size;
1313         }
1314         ecryptfs_init_crypt_ctx(crypt_stat);
1315         if (unlikely(data[(*packet_size)++] != 0x03)) {
1316                 printk(KERN_WARNING "Only S2K ID 3 is currently supported\n");
1317                 rc = -ENOSYS;
1318                 goto out_free;
1319         }
1320         /* TODO: finish the hash mapping */
1321         switch (data[(*packet_size)++]) {
1322         case 0x01: /* See RFC2440 for these numbers and their mappings */
1323                 /* Choose MD5 */
1324                 memcpy((*new_auth_tok)->token.password.salt,
1325                        &data[(*packet_size)], ECRYPTFS_SALT_SIZE);
1326                 (*packet_size) += ECRYPTFS_SALT_SIZE;
1327                 /* This conversion was taken straight from RFC2440 */
1328                 (*new_auth_tok)->token.password.hash_iterations =
1329                         ((u32) 16 + (data[(*packet_size)] & 15))
1330                                 << ((data[(*packet_size)] >> 4) + 6);
1331                 (*packet_size)++;
1332                 /* Friendly reminder:
1333                  * (*new_auth_tok)->session_key.encrypted_key_size =
1334                  *         (body_size - (ECRYPTFS_SALT_SIZE + 5)); */
1335                 memcpy((*new_auth_tok)->session_key.encrypted_key,
1336                        &data[(*packet_size)],
1337                        (*new_auth_tok)->session_key.encrypted_key_size);
1338                 (*packet_size) +=
1339                         (*new_auth_tok)->session_key.encrypted_key_size;
1340                 (*new_auth_tok)->session_key.flags &=
1341                         ~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1342                 (*new_auth_tok)->session_key.flags |=
1343                         ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
1344                 (*new_auth_tok)->token.password.hash_algo = 0x01; /* MD5 */
1345                 break;
1346         default:
1347                 ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: "
1348                                 "[%d]\n", data[(*packet_size) - 1]);
1349                 rc = -ENOSYS;
1350                 goto out_free;
1351         }
1352         (*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;
1353         /* TODO: Parametarize; we might actually want userspace to
1354          * decrypt the session key. */
1355         (*new_auth_tok)->session_key.flags &=
1356                             ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
1357         (*new_auth_tok)->session_key.flags &=
1358                             ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
1359         list_add(&auth_tok_list_item->list, auth_tok_list);
1360         goto out;
1361 out_free:
1362         (*new_auth_tok) = NULL;
1363         memset(auth_tok_list_item, 0,
1364                sizeof(struct ecryptfs_auth_tok_list_item));
1365         kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1366                         auth_tok_list_item);
1367 out:
1368         if (rc)
1369                 (*packet_size) = 0;
1370         return rc;
1371 }
1372
1373 /**
1374  * parse_tag_11_packet
1375  * @data: The raw bytes of the packet
1376  * @contents: This function writes the data contents of the literal
1377  *            packet into this memory location
1378  * @max_contents_bytes: The maximum number of bytes that this function
1379  *                      is allowed to write into contents
1380  * @tag_11_contents_size: This function writes the size of the parsed
1381  *                        contents into this memory location; zero on
1382  *                        error
1383  * @packet_size: This function writes the size of the parsed packet
1384  *               into this memory location; zero on error
1385  * @max_packet_size: maximum number of bytes to parse
1386  *
1387  * Returns zero on success; non-zero on error.
1388  */
1389 static int
1390 parse_tag_11_packet(unsigned char *data, unsigned char *contents,
1391                     size_t max_contents_bytes, size_t *tag_11_contents_size,
1392                     size_t *packet_size, size_t max_packet_size)
1393 {
1394         size_t body_size;
1395         size_t length_size;
1396         int rc = 0;
1397
1398         (*packet_size) = 0;
1399         (*tag_11_contents_size) = 0;
1400         /* This format is inspired by OpenPGP; see RFC 2440
1401          * packet tag 11
1402          *
1403          * Tag 11 identifier (1 byte)
1404          * Max Tag 11 packet size (max 3 bytes)
1405          * Binary format specifier (1 byte)
1406          * Filename length (1 byte)
1407          * Filename ("_CONSOLE") (8 bytes)
1408          * Modification date (4 bytes)
1409          * Literal data (arbitrary)
1410          *
1411          * We need at least 16 bytes of data for the packet to even be
1412          * valid.
1413          */
1414         if (max_packet_size < 16) {
1415                 printk(KERN_ERR "Maximum packet size too small\n");
1416                 rc = -EINVAL;
1417                 goto out;
1418         }
1419         if (data[(*packet_size)++] != ECRYPTFS_TAG_11_PACKET_TYPE) {
1420                 printk(KERN_WARNING "Invalid tag 11 packet format\n");
1421                 rc = -EINVAL;
1422                 goto out;
1423         }
1424         rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1425                                           &length_size);
1426         if (rc) {
1427                 printk(KERN_WARNING "Invalid tag 11 packet format\n");
1428                 goto out;
1429         }
1430         if (body_size < 14) {
1431                 printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1432                 rc = -EINVAL;
1433                 goto out;
1434         }
1435         (*packet_size) += length_size;
1436         (*tag_11_contents_size) = (body_size - 14);
1437         if (unlikely((*packet_size) + body_size + 1 > max_packet_size)) {
1438                 printk(KERN_ERR "Packet size exceeds max\n");
1439                 rc = -EINVAL;
1440                 goto out;
1441         }
1442         if (data[(*packet_size)++] != 0x62) {
1443                 printk(KERN_WARNING "Unrecognizable packet\n");
1444                 rc = -EINVAL;
1445                 goto out;
1446         }
1447         if (data[(*packet_size)++] != 0x08) {
1448                 printk(KERN_WARNING "Unrecognizable packet\n");
1449                 rc = -EINVAL;
1450                 goto out;
1451         }
1452         (*packet_size) += 12; /* Ignore filename and modification date */
1453         memcpy(contents, &data[(*packet_size)], (*tag_11_contents_size));
1454         (*packet_size) += (*tag_11_contents_size);
1455 out:
1456         if (rc) {
1457                 (*packet_size) = 0;
1458                 (*tag_11_contents_size) = 0;
1459         }
1460         return rc;
1461 }
1462
1463 /**
1464  * ecryptfs_verify_version
1465  * @version: The version number to confirm
1466  *
1467  * Returns zero on good version; non-zero otherwise
1468  */
1469 static int ecryptfs_verify_version(u16 version)
1470 {
1471         int rc = 0;
1472         unsigned char major;
1473         unsigned char minor;
1474
1475         major = ((version >> 8) & 0xFF);
1476         minor = (version & 0xFF);
1477         if (major != ECRYPTFS_VERSION_MAJOR) {
1478                 ecryptfs_printk(KERN_ERR, "Major version number mismatch. "
1479                                 "Expected [%d]; got [%d]\n",
1480                                 ECRYPTFS_VERSION_MAJOR, major);
1481                 rc = -EINVAL;
1482                 goto out;
1483         }
1484         if (minor != ECRYPTFS_VERSION_MINOR) {
1485                 ecryptfs_printk(KERN_ERR, "Minor version number mismatch. "
1486                                 "Expected [%d]; got [%d]\n",
1487                                 ECRYPTFS_VERSION_MINOR, minor);
1488                 rc = -EINVAL;
1489                 goto out;
1490         }
1491 out:
1492         return rc;
1493 }
1494
1495 int ecryptfs_keyring_auth_tok_for_sig(struct key **auth_tok_key,
1496                                       struct ecryptfs_auth_tok **auth_tok,
1497                                       char *sig)
1498 {
1499         int rc = 0;
1500
1501         (*auth_tok_key) = request_key(&key_type_user, sig, NULL);
1502         if (!(*auth_tok_key) || IS_ERR(*auth_tok_key)) {
1503                 printk(KERN_ERR "Could not find key with description: [%s]\n",
1504                        sig);
1505                 rc = process_request_key_err(PTR_ERR(*auth_tok_key));
1506                 goto out;
1507         }
1508         (*auth_tok) = ecryptfs_get_key_payload_data(*auth_tok_key);
1509         if (ecryptfs_verify_version((*auth_tok)->version)) {
1510                 printk(KERN_ERR
1511                        "Data structure version mismatch. "
1512                        "Userspace tools must match eCryptfs "
1513                        "kernel module with major version [%d] "
1514                        "and minor version [%d]\n",
1515                        ECRYPTFS_VERSION_MAJOR,
1516                        ECRYPTFS_VERSION_MINOR);
1517                 rc = -EINVAL;
1518                 goto out;
1519         }
1520         if ((*auth_tok)->token_type != ECRYPTFS_PASSWORD
1521             && (*auth_tok)->token_type != ECRYPTFS_PRIVATE_KEY) {
1522                 printk(KERN_ERR "Invalid auth_tok structure "
1523                        "returned from key query\n");
1524                 rc = -EINVAL;
1525                 goto out;
1526         }
1527 out:
1528         return rc;
1529 }
1530
1531 /**
1532  * decrypt_passphrase_encrypted_session_key - Decrypt the session key with the given auth_tok.
1533  * @auth_tok: The passphrase authentication token to use to encrypt the FEK
1534  * @crypt_stat: The cryptographic context
1535  *
1536  * Returns zero on success; non-zero error otherwise
1537  */
1538 static int
1539 decrypt_passphrase_encrypted_session_key(struct ecryptfs_auth_tok *auth_tok,
1540                                          struct ecryptfs_crypt_stat *crypt_stat)
1541 {
1542         struct scatterlist dst_sg[2];
1543         struct scatterlist src_sg[2];
1544         struct mutex *tfm_mutex;
1545         struct blkcipher_desc desc = {
1546                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
1547         };
1548         int rc = 0;
1549
1550         if (unlikely(ecryptfs_verbosity > 0)) {
1551                 ecryptfs_printk(
1552                         KERN_DEBUG, "Session key encryption key (size [%d]):\n",
1553                         auth_tok->token.password.session_key_encryption_key_bytes);
1554                 ecryptfs_dump_hex(
1555                         auth_tok->token.password.session_key_encryption_key,
1556                         auth_tok->token.password.session_key_encryption_key_bytes);
1557         }
1558         rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&desc.tfm, &tfm_mutex,
1559                                                         crypt_stat->cipher);
1560         if (unlikely(rc)) {
1561                 printk(KERN_ERR "Internal error whilst attempting to get "
1562                        "tfm and mutex for cipher name [%s]; rc = [%d]\n",
1563                        crypt_stat->cipher, rc);
1564                 goto out;
1565         }
1566         rc = virt_to_scatterlist(auth_tok->session_key.encrypted_key,
1567                                  auth_tok->session_key.encrypted_key_size,
1568                                  src_sg, 2);
1569         if (rc < 1 || rc > 2) {
1570                 printk(KERN_ERR "Internal error whilst attempting to convert "
1571                         "auth_tok->session_key.encrypted_key to scatterlist; "
1572                         "expected rc = 1; got rc = [%d]. "
1573                        "auth_tok->session_key.encrypted_key_size = [%d]\n", rc,
1574                         auth_tok->session_key.encrypted_key_size);
1575                 goto out;
1576         }
1577         auth_tok->session_key.decrypted_key_size =
1578                 auth_tok->session_key.encrypted_key_size;
1579         rc = virt_to_scatterlist(auth_tok->session_key.decrypted_key,
1580                                  auth_tok->session_key.decrypted_key_size,
1581                                  dst_sg, 2);
1582         if (rc < 1 || rc > 2) {
1583                 printk(KERN_ERR "Internal error whilst attempting to convert "
1584                         "auth_tok->session_key.decrypted_key to scatterlist; "
1585                         "expected rc = 1; got rc = [%d]\n", rc);
1586                 goto out;
1587         }
1588         mutex_lock(tfm_mutex);
1589         rc = crypto_blkcipher_setkey(
1590                 desc.tfm, auth_tok->token.password.session_key_encryption_key,
1591                 crypt_stat->key_size);
1592         if (unlikely(rc < 0)) {
1593                 mutex_unlock(tfm_mutex);
1594                 printk(KERN_ERR "Error setting key for crypto context\n");
1595                 rc = -EINVAL;
1596                 goto out;
1597         }
1598         rc = crypto_blkcipher_decrypt(&desc, dst_sg, src_sg,
1599                                       auth_tok->session_key.encrypted_key_size);
1600         mutex_unlock(tfm_mutex);
1601         if (unlikely(rc)) {
1602                 printk(KERN_ERR "Error decrypting; rc = [%d]\n", rc);
1603                 goto out;
1604         }
1605         auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1606         memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
1607                auth_tok->session_key.decrypted_key_size);
1608         crypt_stat->flags |= ECRYPTFS_KEY_VALID;
1609         if (unlikely(ecryptfs_verbosity > 0)) {
1610                 ecryptfs_printk(KERN_DEBUG, "FEK of size [%d]:\n",
1611                                 crypt_stat->key_size);
1612                 ecryptfs_dump_hex(crypt_stat->key,
1613                                   crypt_stat->key_size);
1614         }
1615 out:
1616         return rc;
1617 }
1618
1619 /**
1620  * ecryptfs_parse_packet_set
1621  * @crypt_stat: The cryptographic context
1622  * @src: Virtual address of region of memory containing the packets
1623  * @ecryptfs_dentry: The eCryptfs dentry associated with the packet set
1624  *
1625  * Get crypt_stat to have the file's session key if the requisite key
1626  * is available to decrypt the session key.
1627  *
1628  * Returns Zero if a valid authentication token was retrieved and
1629  * processed; negative value for file not encrypted or for error
1630  * conditions.
1631  */
1632 int ecryptfs_parse_packet_set(struct ecryptfs_crypt_stat *crypt_stat,
1633                               unsigned char *src,
1634                               struct dentry *ecryptfs_dentry)
1635 {
1636         size_t i = 0;
1637         size_t found_auth_tok;
1638         size_t next_packet_is_auth_tok_packet;
1639         struct list_head auth_tok_list;
1640         struct ecryptfs_auth_tok *matching_auth_tok;
1641         struct ecryptfs_auth_tok *candidate_auth_tok;
1642         char *candidate_auth_tok_sig;
1643         size_t packet_size;
1644         struct ecryptfs_auth_tok *new_auth_tok;
1645         unsigned char sig_tmp_space[ECRYPTFS_SIG_SIZE];
1646         struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1647         size_t tag_11_contents_size;
1648         size_t tag_11_packet_size;
1649         int rc = 0;
1650
1651         INIT_LIST_HEAD(&auth_tok_list);
1652         /* Parse the header to find as many packets as we can; these will be
1653          * added the our &auth_tok_list */
1654         next_packet_is_auth_tok_packet = 1;
1655         while (next_packet_is_auth_tok_packet) {
1656                 size_t max_packet_size = ((PAGE_CACHE_SIZE - 8) - i);
1657
1658                 switch (src[i]) {
1659                 case ECRYPTFS_TAG_3_PACKET_TYPE:
1660                         rc = parse_tag_3_packet(crypt_stat,
1661                                                 (unsigned char *)&src[i],
1662                                                 &auth_tok_list, &new_auth_tok,
1663                                                 &packet_size, max_packet_size);
1664                         if (rc) {
1665                                 ecryptfs_printk(KERN_ERR, "Error parsing "
1666                                                 "tag 3 packet\n");
1667                                 rc = -EIO;
1668                                 goto out_wipe_list;
1669                         }
1670                         i += packet_size;
1671                         rc = parse_tag_11_packet((unsigned char *)&src[i],
1672                                                  sig_tmp_space,
1673                                                  ECRYPTFS_SIG_SIZE,
1674                                                  &tag_11_contents_size,
1675                                                  &tag_11_packet_size,
1676                                                  max_packet_size);
1677                         if (rc) {
1678                                 ecryptfs_printk(KERN_ERR, "No valid "
1679                                                 "(ecryptfs-specific) literal "
1680                                                 "packet containing "
1681                                                 "authentication token "
1682                                                 "signature found after "
1683                                                 "tag 3 packet\n");
1684                                 rc = -EIO;
1685                                 goto out_wipe_list;
1686                         }
1687                         i += tag_11_packet_size;
1688                         if (ECRYPTFS_SIG_SIZE != tag_11_contents_size) {
1689                                 ecryptfs_printk(KERN_ERR, "Expected "
1690                                                 "signature of size [%d]; "
1691                                                 "read size [%d]\n",
1692                                                 ECRYPTFS_SIG_SIZE,
1693                                                 tag_11_contents_size);
1694                                 rc = -EIO;
1695                                 goto out_wipe_list;
1696                         }
1697                         ecryptfs_to_hex(new_auth_tok->token.password.signature,
1698                                         sig_tmp_space, tag_11_contents_size);
1699                         new_auth_tok->token.password.signature[
1700                                 ECRYPTFS_PASSWORD_SIG_SIZE] = '\0';
1701                         crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1702                         break;
1703                 case ECRYPTFS_TAG_1_PACKET_TYPE:
1704                         rc = parse_tag_1_packet(crypt_stat,
1705                                                 (unsigned char *)&src[i],
1706                                                 &auth_tok_list, &new_auth_tok,
1707                                                 &packet_size, max_packet_size);
1708                         if (rc) {
1709                                 ecryptfs_printk(KERN_ERR, "Error parsing "
1710                                                 "tag 1 packet\n");
1711                                 rc = -EIO;
1712                                 goto out_wipe_list;
1713                         }
1714                         i += packet_size;
1715                         crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1716                         break;
1717                 case ECRYPTFS_TAG_11_PACKET_TYPE:
1718                         ecryptfs_printk(KERN_WARNING, "Invalid packet set "
1719                                         "(Tag 11 not allowed by itself)\n");
1720                         rc = -EIO;
1721                         goto out_wipe_list;
1722                         break;
1723                 default:
1724                         ecryptfs_printk(KERN_DEBUG, "No packet at offset "
1725                                         "[%d] of the file header; hex value of "
1726                                         "character is [0x%.2x]\n", i, src[i]);
1727                         next_packet_is_auth_tok_packet = 0;
1728                 }
1729         }
1730         if (list_empty(&auth_tok_list)) {
1731                 printk(KERN_ERR "The lower file appears to be a non-encrypted "
1732                        "eCryptfs file; this is not supported in this version "
1733                        "of the eCryptfs kernel module\n");
1734                 rc = -EINVAL;
1735                 goto out;
1736         }
1737         /* auth_tok_list contains the set of authentication tokens
1738          * parsed from the metadata. We need to find a matching
1739          * authentication token that has the secret component(s)
1740          * necessary to decrypt the EFEK in the auth_tok parsed from
1741          * the metadata. There may be several potential matches, but
1742          * just one will be sufficient to decrypt to get the FEK. */
1743 find_next_matching_auth_tok:
1744         found_auth_tok = 0;
1745         list_for_each_entry(auth_tok_list_item, &auth_tok_list, list) {
1746                 candidate_auth_tok = &auth_tok_list_item->auth_tok;
1747                 if (unlikely(ecryptfs_verbosity > 0)) {
1748                         ecryptfs_printk(KERN_DEBUG,
1749                                         "Considering cadidate auth tok:\n");
1750                         ecryptfs_dump_auth_tok(candidate_auth_tok);
1751                 }
1752                 rc = ecryptfs_get_auth_tok_sig(&candidate_auth_tok_sig,
1753                                                candidate_auth_tok);
1754                 if (rc) {
1755                         printk(KERN_ERR
1756                                "Unrecognized candidate auth tok type: [%d]\n",
1757                                candidate_auth_tok->token_type);
1758                         rc = -EINVAL;
1759                         goto out_wipe_list;
1760                 }
1761                 ecryptfs_find_auth_tok_for_sig(&matching_auth_tok,
1762                                                crypt_stat->mount_crypt_stat,
1763                                                candidate_auth_tok_sig);
1764                 if (matching_auth_tok) {
1765                         found_auth_tok = 1;
1766                         goto found_matching_auth_tok;
1767                 }
1768         }
1769         if (!found_auth_tok) {
1770                 ecryptfs_printk(KERN_ERR, "Could not find a usable "
1771                                 "authentication token\n");
1772                 rc = -EIO;
1773                 goto out_wipe_list;
1774         }
1775 found_matching_auth_tok:
1776         if (candidate_auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
1777                 memcpy(&(candidate_auth_tok->token.private_key),
1778                        &(matching_auth_tok->token.private_key),
1779                        sizeof(struct ecryptfs_private_key));
1780                 rc = decrypt_pki_encrypted_session_key(candidate_auth_tok,
1781                                                        crypt_stat);
1782         } else if (candidate_auth_tok->token_type == ECRYPTFS_PASSWORD) {
1783                 memcpy(&(candidate_auth_tok->token.password),
1784                        &(matching_auth_tok->token.password),
1785                        sizeof(struct ecryptfs_password));
1786                 rc = decrypt_passphrase_encrypted_session_key(
1787                         candidate_auth_tok, crypt_stat);
1788         }
1789         if (rc) {
1790                 struct ecryptfs_auth_tok_list_item *auth_tok_list_item_tmp;
1791
1792                 ecryptfs_printk(KERN_WARNING, "Error decrypting the "
1793                                 "session key for authentication token with sig "
1794                                 "[%.*s]; rc = [%d]. Removing auth tok "
1795                                 "candidate from the list and searching for "
1796                                 "the next match.\n", candidate_auth_tok_sig,
1797                                 ECRYPTFS_SIG_SIZE_HEX, rc);
1798                 list_for_each_entry_safe(auth_tok_list_item,
1799                                          auth_tok_list_item_tmp,
1800                                          &auth_tok_list, list) {
1801                         if (candidate_auth_tok
1802                             == &auth_tok_list_item->auth_tok) {
1803                                 list_del(&auth_tok_list_item->list);
1804                                 kmem_cache_free(
1805                                         ecryptfs_auth_tok_list_item_cache,
1806                                         auth_tok_list_item);
1807                                 goto find_next_matching_auth_tok;
1808                         }
1809                 }
1810                 BUG();
1811         }
1812         rc = ecryptfs_compute_root_iv(crypt_stat);
1813         if (rc) {
1814                 ecryptfs_printk(KERN_ERR, "Error computing "
1815                                 "the root IV\n");
1816                 goto out_wipe_list;
1817         }
1818         rc = ecryptfs_init_crypt_ctx(crypt_stat);
1819         if (rc) {
1820                 ecryptfs_printk(KERN_ERR, "Error initializing crypto "
1821                                 "context for cipher [%s]; rc = [%d]\n",
1822                                 crypt_stat->cipher, rc);
1823         }
1824 out_wipe_list:
1825         wipe_auth_tok_list(&auth_tok_list);
1826 out:
1827         return rc;
1828 }
1829
1830 static int
1831 pki_encrypt_session_key(struct ecryptfs_auth_tok *auth_tok,
1832                         struct ecryptfs_crypt_stat *crypt_stat,
1833                         struct ecryptfs_key_record *key_rec)
1834 {
1835         struct ecryptfs_msg_ctx *msg_ctx = NULL;
1836         char *payload = NULL;
1837         size_t payload_len;
1838         struct ecryptfs_message *msg;
1839         int rc;
1840
1841         rc = write_tag_66_packet(auth_tok->token.private_key.signature,
1842                                  ecryptfs_code_for_cipher_string(
1843                                          crypt_stat->cipher,
1844                                          crypt_stat->key_size),
1845                                  crypt_stat, &payload, &payload_len);
1846         if (rc) {
1847                 ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet\n");
1848                 goto out;
1849         }
1850         rc = ecryptfs_send_message(payload, payload_len, &msg_ctx);
1851         if (rc) {
1852                 ecryptfs_printk(KERN_ERR, "Error sending message to "
1853                                 "ecryptfsd\n");
1854                 goto out;
1855         }
1856         rc = ecryptfs_wait_for_response(msg_ctx, &msg);
1857         if (rc) {
1858                 ecryptfs_printk(KERN_ERR, "Failed to receive tag 67 packet "
1859                                 "from the user space daemon\n");
1860                 rc = -EIO;
1861                 goto out;
1862         }
1863         rc = parse_tag_67_packet(key_rec, msg);
1864         if (rc)
1865                 ecryptfs_printk(KERN_ERR, "Error parsing tag 67 packet\n");
1866         kfree(msg);
1867 out:
1868         kfree(payload);
1869         return rc;
1870 }
1871 /**
1872  * write_tag_1_packet - Write an RFC2440-compatible tag 1 (public key) packet
1873  * @dest: Buffer into which to write the packet
1874  * @remaining_bytes: Maximum number of bytes that can be writtn
1875  * @auth_tok: The authentication token used for generating the tag 1 packet
1876  * @crypt_stat: The cryptographic context
1877  * @key_rec: The key record struct for the tag 1 packet
1878  * @packet_size: This function will write the number of bytes that end
1879  *               up constituting the packet; set to zero on error
1880  *
1881  * Returns zero on success; non-zero on error.
1882  */
1883 static int
1884 write_tag_1_packet(char *dest, size_t *remaining_bytes,
1885                    struct ecryptfs_auth_tok *auth_tok,
1886                    struct ecryptfs_crypt_stat *crypt_stat,
1887                    struct ecryptfs_key_record *key_rec, size_t *packet_size)
1888 {
1889         size_t i;
1890         size_t encrypted_session_key_valid = 0;
1891         size_t packet_size_length;
1892         size_t max_packet_size;
1893         int rc = 0;
1894
1895         (*packet_size) = 0;
1896         ecryptfs_from_hex(key_rec->sig, auth_tok->token.private_key.signature,
1897                           ECRYPTFS_SIG_SIZE);
1898         encrypted_session_key_valid = 0;
1899         for (i = 0; i < crypt_stat->key_size; i++)
1900                 encrypted_session_key_valid |=
1901                         auth_tok->session_key.encrypted_key[i];
1902         if (encrypted_session_key_valid) {
1903                 memcpy(key_rec->enc_key,
1904                        auth_tok->session_key.encrypted_key,
1905                        auth_tok->session_key.encrypted_key_size);
1906                 goto encrypted_session_key_set;
1907         }
1908         if (auth_tok->session_key.encrypted_key_size == 0)
1909                 auth_tok->session_key.encrypted_key_size =
1910                         auth_tok->token.private_key.key_size;
1911         rc = pki_encrypt_session_key(auth_tok, crypt_stat, key_rec);
1912         if (rc) {
1913                 printk(KERN_ERR "Failed to encrypt session key via a key "
1914                        "module; rc = [%d]\n", rc);
1915                 goto out;
1916         }
1917         if (ecryptfs_verbosity > 0) {
1918                 ecryptfs_printk(KERN_DEBUG, "Encrypted key:\n");
1919                 ecryptfs_dump_hex(key_rec->enc_key, key_rec->enc_key_size);
1920         }
1921 encrypted_session_key_set:
1922         /* This format is inspired by OpenPGP; see RFC 2440
1923          * packet tag 1 */
1924         max_packet_size = (1                         /* Tag 1 identifier */
1925                            + 3                       /* Max Tag 1 packet size */
1926                            + 1                       /* Version */
1927                            + ECRYPTFS_SIG_SIZE       /* Key identifier */
1928                            + 1                       /* Cipher identifier */
1929                            + key_rec->enc_key_size); /* Encrypted key size */
1930         if (max_packet_size > (*remaining_bytes)) {
1931                 printk(KERN_ERR "Packet length larger than maximum allowable; "
1932                        "need up to [%td] bytes, but there are only [%td] "
1933                        "available\n", max_packet_size, (*remaining_bytes));
1934                 rc = -EINVAL;
1935                 goto out;
1936         }
1937         dest[(*packet_size)++] = ECRYPTFS_TAG_1_PACKET_TYPE;
1938         rc = ecryptfs_write_packet_length(&dest[(*packet_size)],
1939                                           (max_packet_size - 4),
1940                                           &packet_size_length);
1941         if (rc) {
1942                 ecryptfs_printk(KERN_ERR, "Error generating tag 1 packet "
1943                                 "header; cannot generate packet length\n");
1944                 goto out;
1945         }
1946         (*packet_size) += packet_size_length;
1947         dest[(*packet_size)++] = 0x03; /* version 3 */
1948         memcpy(&dest[(*packet_size)], key_rec->sig, ECRYPTFS_SIG_SIZE);
1949         (*packet_size) += ECRYPTFS_SIG_SIZE;
1950         dest[(*packet_size)++] = RFC2440_CIPHER_RSA;
1951         memcpy(&dest[(*packet_size)], key_rec->enc_key,
1952                key_rec->enc_key_size);
1953         (*packet_size) += key_rec->enc_key_size;
1954 out:
1955         if (rc)
1956                 (*packet_size) = 0;
1957         else
1958                 (*remaining_bytes) -= (*packet_size);
1959         return rc;
1960 }
1961
1962 /**
1963  * write_tag_11_packet
1964  * @dest: Target into which Tag 11 packet is to be written
1965  * @remaining_bytes: Maximum packet length
1966  * @contents: Byte array of contents to copy in
1967  * @contents_length: Number of bytes in contents
1968  * @packet_length: Length of the Tag 11 packet written; zero on error
1969  *
1970  * Returns zero on success; non-zero on error.
1971  */
1972 static int
1973 write_tag_11_packet(char *dest, size_t *remaining_bytes, char *contents,
1974                     size_t contents_length, size_t *packet_length)
1975 {
1976         size_t packet_size_length;
1977         size_t max_packet_size;
1978         int rc = 0;
1979
1980         (*packet_length) = 0;
1981         /* This format is inspired by OpenPGP; see RFC 2440
1982          * packet tag 11 */
1983         max_packet_size = (1                   /* Tag 11 identifier */
1984                            + 3                 /* Max Tag 11 packet size */
1985                            + 1                 /* Binary format specifier */
1986                            + 1                 /* Filename length */
1987                            + 8                 /* Filename ("_CONSOLE") */
1988                            + 4                 /* Modification date */
1989                            + contents_length); /* Literal data */
1990         if (max_packet_size > (*remaining_bytes)) {
1991                 printk(KERN_ERR "Packet length larger than maximum allowable; "
1992                        "need up to [%td] bytes, but there are only [%td] "
1993                        "available\n", max_packet_size, (*remaining_bytes));
1994                 rc = -EINVAL;
1995                 goto out;
1996         }
1997         dest[(*packet_length)++] = ECRYPTFS_TAG_11_PACKET_TYPE;
1998         rc = ecryptfs_write_packet_length(&dest[(*packet_length)],
1999                                           (max_packet_size - 4),
2000                                           &packet_size_length);
2001         if (rc) {
2002                 printk(KERN_ERR "Error generating tag 11 packet header; cannot "
2003                        "generate packet length. rc = [%d]\n", rc);
2004                 goto out;
2005         }
2006         (*packet_length) += packet_size_length;
2007         dest[(*packet_length)++] = 0x62; /* binary data format specifier */
2008         dest[(*packet_length)++] = 8;
2009         memcpy(&dest[(*packet_length)], "_CONSOLE", 8);
2010         (*packet_length) += 8;
2011         memset(&dest[(*packet_length)], 0x00, 4);
2012         (*packet_length) += 4;
2013         memcpy(&dest[(*packet_length)], contents, contents_length);
2014         (*packet_length) += contents_length;
2015  out:
2016         if (rc)
2017                 (*packet_length) = 0;
2018         else
2019                 (*remaining_bytes) -= (*packet_length);
2020         return rc;
2021 }
2022
2023 /**
2024  * write_tag_3_packet
2025  * @dest: Buffer into which to write the packet
2026  * @remaining_bytes: Maximum number of bytes that can be written
2027  * @auth_tok: Authentication token
2028  * @crypt_stat: The cryptographic context
2029  * @key_rec: encrypted key
2030  * @packet_size: This function will write the number of bytes that end
2031  *               up constituting the packet; set to zero on error
2032  *
2033  * Returns zero on success; non-zero on error.
2034  */
2035 static int
2036 write_tag_3_packet(char *dest, size_t *remaining_bytes,
2037                    struct ecryptfs_auth_tok *auth_tok,
2038                    struct ecryptfs_crypt_stat *crypt_stat,
2039                    struct ecryptfs_key_record *key_rec, size_t *packet_size)
2040 {
2041         size_t i;
2042         size_t encrypted_session_key_valid = 0;
2043         char session_key_encryption_key[ECRYPTFS_MAX_KEY_BYTES];
2044         struct scatterlist dst_sg[2];
2045         struct scatterlist src_sg[2];
2046         struct mutex *tfm_mutex = NULL;
2047         u8 cipher_code;
2048         size_t packet_size_length;
2049         size_t max_packet_size;
2050         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
2051                 crypt_stat->mount_crypt_stat;
2052         struct blkcipher_desc desc = {
2053                 .tfm = NULL,
2054                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP
2055         };
2056         int rc = 0;
2057
2058         (*packet_size) = 0;
2059         ecryptfs_from_hex(key_rec->sig, auth_tok->token.password.signature,
2060                           ECRYPTFS_SIG_SIZE);
2061         rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&desc.tfm, &tfm_mutex,
2062                                                         crypt_stat->cipher);
2063         if (unlikely(rc)) {
2064                 printk(KERN_ERR "Internal error whilst attempting to get "
2065                        "tfm and mutex for cipher name [%s]; rc = [%d]\n",
2066                        crypt_stat->cipher, rc);
2067                 goto out;
2068         }
2069         if (mount_crypt_stat->global_default_cipher_key_size == 0) {
2070                 struct blkcipher_alg *alg = crypto_blkcipher_alg(desc.tfm);
2071
2072                 printk(KERN_WARNING "No key size specified at mount; "
2073                        "defaulting to [%d]\n", alg->max_keysize);
2074                 mount_crypt_stat->global_default_cipher_key_size =
2075                         alg->max_keysize;
2076         }
2077         if (crypt_stat->key_size == 0)
2078                 crypt_stat->key_size =
2079                         mount_crypt_stat->global_default_cipher_key_size;
2080         if (auth_tok->session_key.encrypted_key_size == 0)
2081                 auth_tok->session_key.encrypted_key_size =
2082                         crypt_stat->key_size;
2083         if (crypt_stat->key_size == 24
2084             && strcmp("aes", crypt_stat->cipher) == 0) {
2085                 memset((crypt_stat->key + 24), 0, 8);
2086                 auth_tok->session_key.encrypted_key_size = 32;
2087         } else
2088                 auth_tok->session_key.encrypted_key_size = crypt_stat->key_size;
2089         key_rec->enc_key_size =
2090                 auth_tok->session_key.encrypted_key_size;
2091         encrypted_session_key_valid = 0;
2092         for (i = 0; i < auth_tok->session_key.encrypted_key_size; i++)
2093                 encrypted_session_key_valid |=
2094                         auth_tok->session_key.encrypted_key[i];
2095         if (encrypted_session_key_valid) {
2096                 ecryptfs_printk(KERN_DEBUG, "encrypted_session_key_valid != 0; "
2097                                 "using auth_tok->session_key.encrypted_key, "
2098                                 "where key_rec->enc_key_size = [%d]\n",
2099                                 key_rec->enc_key_size);
2100                 memcpy(key_rec->enc_key,
2101                        auth_tok->session_key.encrypted_key,
2102                        key_rec->enc_key_size);
2103                 goto encrypted_session_key_set;
2104         }
2105         if (auth_tok->token.password.flags &
2106             ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET) {
2107                 ecryptfs_printk(KERN_DEBUG, "Using previously generated "
2108                                 "session key encryption key of size [%d]\n",
2109                                 auth_tok->token.password.
2110                                 session_key_encryption_key_bytes);
2111                 memcpy(session_key_encryption_key,
2112                        auth_tok->token.password.session_key_encryption_key,
2113                        crypt_stat->key_size);
2114                 ecryptfs_printk(KERN_DEBUG,
2115                                 "Cached session key " "encryption key: \n");
2116                 if (ecryptfs_verbosity > 0)
2117                         ecryptfs_dump_hex(session_key_encryption_key, 16);
2118         }
2119         if (unlikely(ecryptfs_verbosity > 0)) {
2120                 ecryptfs_printk(KERN_DEBUG, "Session key encryption key:\n");
2121                 ecryptfs_dump_hex(session_key_encryption_key, 16);
2122         }
2123         rc = virt_to_scatterlist(crypt_stat->key, key_rec->enc_key_size,
2124                                  src_sg, 2);
2125         if (rc < 1 || rc > 2) {
2126                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
2127                                 "for crypt_stat session key; expected rc = 1; "
2128                                 "got rc = [%d]. key_rec->enc_key_size = [%d]\n",
2129                                 rc, key_rec->enc_key_size);
2130                 rc = -ENOMEM;
2131                 goto out;
2132         }
2133         rc = virt_to_scatterlist(key_rec->enc_key, key_rec->enc_key_size,
2134                                  dst_sg, 2);
2135         if (rc < 1 || rc > 2) {
2136                 ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
2137                                 "for crypt_stat encrypted session key; "
2138                                 "expected rc = 1; got rc = [%d]. "
2139                                 "key_rec->enc_key_size = [%d]\n", rc,
2140                                 key_rec->enc_key_size);
2141                 rc = -ENOMEM;
2142                 goto out;
2143         }
2144         mutex_lock(tfm_mutex);
2145         rc = crypto_blkcipher_setkey(desc.tfm, session_key_encryption_key,
2146                                      crypt_stat->key_size);
2147         if (rc < 0) {
2148                 mutex_unlock(tfm_mutex);
2149                 ecryptfs_printk(KERN_ERR, "Error setting key for crypto "
2150                                 "context; rc = [%d]\n", rc);
2151                 goto out;
2152         }
2153         rc = 0;
2154         ecryptfs_printk(KERN_DEBUG, "Encrypting [%d] bytes of the key\n",
2155                         crypt_stat->key_size);
2156         rc = crypto_blkcipher_encrypt(&desc, dst_sg, src_sg,
2157                                       (*key_rec).enc_key_size);
2158         mutex_unlock(tfm_mutex);
2159         if (rc) {
2160                 printk(KERN_ERR "Error encrypting; rc = [%d]\n", rc);
2161                 goto out;
2162         }
2163         ecryptfs_printk(KERN_DEBUG, "This should be the encrypted key:\n");
2164         if (ecryptfs_verbosity > 0) {
2165                 ecryptfs_printk(KERN_DEBUG, "EFEK of size [%d]:\n",
2166                                 key_rec->enc_key_size);
2167                 ecryptfs_dump_hex(key_rec->enc_key,
2168                                   key_rec->enc_key_size);
2169         }
2170 encrypted_session_key_set:
2171         /* This format is inspired by OpenPGP; see RFC 2440
2172          * packet tag 3 */
2173         max_packet_size = (1                         /* Tag 3 identifier */
2174                            + 3                       /* Max Tag 3 packet size */
2175                            + 1                       /* Version */
2176                            + 1                       /* Cipher code */
2177                            + 1                       /* S2K specifier */
2178                            + 1                       /* Hash identifier */
2179                            + ECRYPTFS_SALT_SIZE      /* Salt */
2180                            + 1                       /* Hash iterations */
2181                            + key_rec->enc_key_size); /* Encrypted key size */
2182         if (max_packet_size > (*remaining_bytes)) {
2183                 printk(KERN_ERR "Packet too large; need up to [%td] bytes, but "
2184                        "there are only [%td] available\n", max_packet_size,
2185                        (*remaining_bytes));
2186                 rc = -EINVAL;
2187                 goto out;
2188         }
2189         dest[(*packet_size)++] = ECRYPTFS_TAG_3_PACKET_TYPE;
2190         /* Chop off the Tag 3 identifier(1) and Tag 3 packet size(3)
2191          * to get the number of octets in the actual Tag 3 packet */
2192         rc = ecryptfs_write_packet_length(&dest[(*packet_size)],
2193                                           (max_packet_size - 4),
2194                                           &packet_size_length);
2195         if (rc) {
2196                 printk(KERN_ERR "Error generating tag 3 packet header; cannot "
2197                        "generate packet length. rc = [%d]\n", rc);
2198                 goto out;
2199         }
2200         (*packet_size) += packet_size_length;
2201         dest[(*packet_size)++] = 0x04; /* version 4 */
2202         /* TODO: Break from RFC2440 so that arbitrary ciphers can be
2203          * specified with strings */
2204         cipher_code = ecryptfs_code_for_cipher_string(crypt_stat->cipher,
2205                                                       crypt_stat->key_size);
2206         if (cipher_code == 0) {
2207                 ecryptfs_printk(KERN_WARNING, "Unable to generate code for "
2208                                 "cipher [%s]\n", crypt_stat->cipher);
2209                 rc = -EINVAL;
2210                 goto out;
2211         }
2212         dest[(*packet_size)++] = cipher_code;
2213         dest[(*packet_size)++] = 0x03;  /* S2K */
2214         dest[(*packet_size)++] = 0x01;  /* MD5 (TODO: parameterize) */
2215         memcpy(&dest[(*packet_size)], auth_tok->token.password.salt,
2216                ECRYPTFS_SALT_SIZE);
2217         (*packet_size) += ECRYPTFS_SALT_SIZE;   /* salt */
2218         dest[(*packet_size)++] = 0x60;  /* hash iterations (65536) */
2219         memcpy(&dest[(*packet_size)], key_rec->enc_key,
2220                key_rec->enc_key_size);
2221         (*packet_size) += key_rec->enc_key_size;
2222 out:
2223         if (rc)
2224                 (*packet_size) = 0;
2225         else
2226                 (*remaining_bytes) -= (*packet_size);
2227         return rc;
2228 }
2229
2230 struct kmem_cache *ecryptfs_key_record_cache;
2231
2232 /**
2233  * ecryptfs_generate_key_packet_set
2234  * @dest_base: Virtual address from which to write the key record set
2235  * @crypt_stat: The cryptographic context from which the
2236  *              authentication tokens will be retrieved
2237  * @ecryptfs_dentry: The dentry, used to retrieve the mount crypt stat
2238  *                   for the global parameters
2239  * @len: The amount written
2240  * @max: The maximum amount of data allowed to be written
2241  *
2242  * Generates a key packet set and writes it to the virtual address
2243  * passed in.
2244  *
2245  * Returns zero on success; non-zero on error.
2246  */
2247 int
2248 ecryptfs_generate_key_packet_set(char *dest_base,
2249                                  struct ecryptfs_crypt_stat *crypt_stat,
2250                                  struct dentry *ecryptfs_dentry, size_t *len,
2251                                  size_t max)
2252 {
2253         struct ecryptfs_auth_tok *auth_tok;
2254         struct ecryptfs_global_auth_tok *global_auth_tok;
2255         struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
2256                 &ecryptfs_superblock_to_private(
2257                         ecryptfs_dentry->d_sb)->mount_crypt_stat;
2258         size_t written;
2259         struct ecryptfs_key_record *key_rec;
2260         struct ecryptfs_key_sig *key_sig;
2261         int rc = 0;
2262
2263         (*len) = 0;
2264         mutex_lock(&crypt_stat->keysig_list_mutex);
2265         key_rec = kmem_cache_alloc(ecryptfs_key_record_cache, GFP_KERNEL);
2266         if (!key_rec) {
2267                 rc = -ENOMEM;
2268                 goto out;
2269         }
2270         list_for_each_entry(key_sig, &crypt_stat->keysig_list,
2271                             crypt_stat_list) {
2272                 memset(key_rec, 0, sizeof(*key_rec));
2273                 rc = ecryptfs_find_global_auth_tok_for_sig(&global_auth_tok,
2274                                                            mount_crypt_stat,
2275                                                            key_sig->keysig);
2276                 if (rc) {
2277                         printk(KERN_ERR "Error attempting to get the global "
2278                                "auth_tok; rc = [%d]\n", rc);
2279                         goto out_free;
2280                 }
2281                 if (global_auth_tok->flags & ECRYPTFS_AUTH_TOK_INVALID) {
2282                         printk(KERN_WARNING
2283                                "Skipping invalid auth tok with sig = [%s]\n",
2284                                global_auth_tok->sig);
2285                         continue;
2286                 }
2287                 auth_tok = global_auth_tok->global_auth_tok;
2288                 if (auth_tok->token_type == ECRYPTFS_PASSWORD) {
2289                         rc = write_tag_3_packet((dest_base + (*len)),
2290                                                 &max, auth_tok,
2291                                                 crypt_stat, key_rec,
2292                                                 &written);
2293                         if (rc) {
2294                                 ecryptfs_printk(KERN_WARNING, "Error "
2295                                                 "writing tag 3 packet\n");
2296                                 goto out_free;
2297                         }
2298                         (*len) += written;
2299                         /* Write auth tok signature packet */
2300                         rc = write_tag_11_packet((dest_base + (*len)), &max,
2301                                                  key_rec->sig,
2302                                                  ECRYPTFS_SIG_SIZE, &written);
2303                         if (rc) {
2304                                 ecryptfs_printk(KERN_ERR, "Error writing "
2305                                                 "auth tok signature packet\n");
2306                                 goto out_free;
2307                         }
2308                         (*len) += written;
2309                 } else if (auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
2310                         rc = write_tag_1_packet(dest_base + (*len),
2311                                                 &max, auth_tok,
2312                                                 crypt_stat, key_rec, &written);
2313                         if (rc) {
2314                                 ecryptfs_printk(KERN_WARNING, "Error "
2315                                                 "writing tag 1 packet\n");
2316                                 goto out_free;
2317                         }
2318                         (*len) += written;
2319                 } else {
2320                         ecryptfs_printk(KERN_WARNING, "Unsupported "
2321                                         "authentication token type\n");
2322                         rc = -EINVAL;
2323                         goto out_free;
2324                 }
2325         }
2326         if (likely(max > 0)) {
2327                 dest_base[(*len)] = 0x00;
2328         } else {
2329                 ecryptfs_printk(KERN_ERR, "Error writing boundary byte\n");
2330                 rc = -EIO;
2331         }
2332 out_free:
2333         kmem_cache_free(ecryptfs_key_record_cache, key_rec);
2334 out:
2335         if (rc)
2336                 (*len) = 0;
2337         mutex_unlock(&crypt_stat->keysig_list_mutex);
2338         return rc;
2339 }
2340
2341 struct kmem_cache *ecryptfs_key_sig_cache;
2342
2343 int ecryptfs_add_keysig(struct ecryptfs_crypt_stat *crypt_stat, char *sig)
2344 {
2345         struct ecryptfs_key_sig *new_key_sig;
2346         int rc = 0;
2347
2348         new_key_sig = kmem_cache_alloc(ecryptfs_key_sig_cache, GFP_KERNEL);
2349         if (!new_key_sig) {
2350                 rc = -ENOMEM;
2351                 printk(KERN_ERR
2352                        "Error allocating from ecryptfs_key_sig_cache\n");
2353                 goto out;
2354         }
2355         memcpy(new_key_sig->keysig, sig, ECRYPTFS_SIG_SIZE_HEX);
2356         mutex_lock(&crypt_stat->keysig_list_mutex);
2357         list_add(&new_key_sig->crypt_stat_list, &crypt_stat->keysig_list);
2358         mutex_unlock(&crypt_stat->keysig_list_mutex);
2359 out:
2360         return rc;
2361 }
2362
2363 struct kmem_cache *ecryptfs_global_auth_tok_cache;
2364
2365 int
2366 ecryptfs_add_global_auth_tok(struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
2367                              char *sig)
2368 {
2369         struct ecryptfs_global_auth_tok *new_auth_tok;
2370         int rc = 0;
2371
2372         new_auth_tok = kmem_cache_zalloc(ecryptfs_global_auth_tok_cache,
2373                                         GFP_KERNEL);
2374         if (!new_auth_tok) {
2375                 rc = -ENOMEM;
2376                 printk(KERN_ERR "Error allocating from "
2377                        "ecryptfs_global_auth_tok_cache\n");
2378                 goto out;
2379         }
2380         memcpy(new_auth_tok->sig, sig, ECRYPTFS_SIG_SIZE_HEX);
2381         new_auth_tok->sig[ECRYPTFS_SIG_SIZE_HEX] = '\0';
2382         mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
2383         list_add(&new_auth_tok->mount_crypt_stat_list,
2384                  &mount_crypt_stat->global_auth_tok_list);
2385         mount_crypt_stat->num_global_auth_toks++;
2386         mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
2387 out:
2388         return rc;
2389 }
2390