xref: /openbmc/linux/fs/ecryptfs/keystore.c (revision 6aa7de05)
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 <crypto/hash.h>
29 #include <crypto/skcipher.h>
30 #include <linux/string.h>
31 #include <linux/pagemap.h>
32 #include <linux/key.h>
33 #include <linux/random.h>
34 #include <linux/scatterlist.h>
35 #include <linux/slab.h>
36 #include "ecryptfs_kernel.h"
37 
38 /**
39  * request_key returned an error instead of a valid key address;
40  * determine the type of error, make appropriate log entries, and
41  * return an error code.
42  */
43 static int process_request_key_err(long err_code)
44 {
45 	int rc = 0;
46 
47 	switch (err_code) {
48 	case -ENOKEY:
49 		ecryptfs_printk(KERN_WARNING, "No key\n");
50 		rc = -ENOENT;
51 		break;
52 	case -EKEYEXPIRED:
53 		ecryptfs_printk(KERN_WARNING, "Key expired\n");
54 		rc = -ETIME;
55 		break;
56 	case -EKEYREVOKED:
57 		ecryptfs_printk(KERN_WARNING, "Key revoked\n");
58 		rc = -EINVAL;
59 		break;
60 	default:
61 		ecryptfs_printk(KERN_WARNING, "Unknown error code: "
62 				"[0x%.16lx]\n", err_code);
63 		rc = -EINVAL;
64 	}
65 	return rc;
66 }
67 
68 static int process_find_global_auth_tok_for_sig_err(int err_code)
69 {
70 	int rc = err_code;
71 
72 	switch (err_code) {
73 	case -ENOENT:
74 		ecryptfs_printk(KERN_WARNING, "Missing auth tok\n");
75 		break;
76 	case -EINVAL:
77 		ecryptfs_printk(KERN_WARNING, "Invalid auth tok\n");
78 		break;
79 	default:
80 		rc = process_request_key_err(err_code);
81 		break;
82 	}
83 	return rc;
84 }
85 
86 /**
87  * ecryptfs_parse_packet_length
88  * @data: Pointer to memory containing length at offset
89  * @size: This function writes the decoded size to this memory
90  *        address; zero on error
91  * @length_size: The number of bytes occupied by the encoded length
92  *
93  * Returns zero on success; non-zero on error
94  */
95 int ecryptfs_parse_packet_length(unsigned char *data, size_t *size,
96 				 size_t *length_size)
97 {
98 	int rc = 0;
99 
100 	(*length_size) = 0;
101 	(*size) = 0;
102 	if (data[0] < 192) {
103 		/* One-byte length */
104 		(*size) = data[0];
105 		(*length_size) = 1;
106 	} else if (data[0] < 224) {
107 		/* Two-byte length */
108 		(*size) = (data[0] - 192) * 256;
109 		(*size) += data[1] + 192;
110 		(*length_size) = 2;
111 	} else if (data[0] == 255) {
112 		/* If support is added, adjust ECRYPTFS_MAX_PKT_LEN_SIZE */
113 		ecryptfs_printk(KERN_ERR, "Five-byte packet length not "
114 				"supported\n");
115 		rc = -EINVAL;
116 		goto out;
117 	} else {
118 		ecryptfs_printk(KERN_ERR, "Error parsing packet length\n");
119 		rc = -EINVAL;
120 		goto out;
121 	}
122 out:
123 	return rc;
124 }
125 
126 /**
127  * ecryptfs_write_packet_length
128  * @dest: The byte array target into which to write the length. Must
129  *        have at least ECRYPTFS_MAX_PKT_LEN_SIZE bytes allocated.
130  * @size: The length to write.
131  * @packet_size_length: The number of bytes used to encode the packet
132  *                      length is written to this address.
133  *
134  * Returns zero on success; non-zero on error.
135  */
136 int ecryptfs_write_packet_length(char *dest, size_t size,
137 				 size_t *packet_size_length)
138 {
139 	int rc = 0;
140 
141 	if (size < 192) {
142 		dest[0] = size;
143 		(*packet_size_length) = 1;
144 	} else if (size < 65536) {
145 		dest[0] = (((size - 192) / 256) + 192);
146 		dest[1] = ((size - 192) % 256);
147 		(*packet_size_length) = 2;
148 	} else {
149 		/* If support is added, adjust ECRYPTFS_MAX_PKT_LEN_SIZE */
150 		rc = -EINVAL;
151 		ecryptfs_printk(KERN_WARNING,
152 				"Unsupported packet size: [%zd]\n", size);
153 	}
154 	return rc;
155 }
156 
157 static int
158 write_tag_64_packet(char *signature, struct ecryptfs_session_key *session_key,
159 		    char **packet, size_t *packet_len)
160 {
161 	size_t i = 0;
162 	size_t data_len;
163 	size_t packet_size_len;
164 	char *message;
165 	int rc;
166 
167 	/*
168 	 *              ***** TAG 64 Packet Format *****
169 	 *    | Content Type                       | 1 byte       |
170 	 *    | Key Identifier Size                | 1 or 2 bytes |
171 	 *    | Key Identifier                     | arbitrary    |
172 	 *    | Encrypted File Encryption Key Size | 1 or 2 bytes |
173 	 *    | Encrypted File Encryption Key      | arbitrary    |
174 	 */
175 	data_len = (5 + ECRYPTFS_SIG_SIZE_HEX
176 		    + session_key->encrypted_key_size);
177 	*packet = kmalloc(data_len, GFP_KERNEL);
178 	message = *packet;
179 	if (!message) {
180 		ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
181 		rc = -ENOMEM;
182 		goto out;
183 	}
184 	message[i++] = ECRYPTFS_TAG_64_PACKET_TYPE;
185 	rc = ecryptfs_write_packet_length(&message[i], ECRYPTFS_SIG_SIZE_HEX,
186 					  &packet_size_len);
187 	if (rc) {
188 		ecryptfs_printk(KERN_ERR, "Error generating tag 64 packet "
189 				"header; cannot generate packet length\n");
190 		goto out;
191 	}
192 	i += packet_size_len;
193 	memcpy(&message[i], signature, ECRYPTFS_SIG_SIZE_HEX);
194 	i += ECRYPTFS_SIG_SIZE_HEX;
195 	rc = ecryptfs_write_packet_length(&message[i],
196 					  session_key->encrypted_key_size,
197 					  &packet_size_len);
198 	if (rc) {
199 		ecryptfs_printk(KERN_ERR, "Error generating tag 64 packet "
200 				"header; cannot generate packet length\n");
201 		goto out;
202 	}
203 	i += packet_size_len;
204 	memcpy(&message[i], session_key->encrypted_key,
205 	       session_key->encrypted_key_size);
206 	i += session_key->encrypted_key_size;
207 	*packet_len = i;
208 out:
209 	return rc;
210 }
211 
212 static int
213 parse_tag_65_packet(struct ecryptfs_session_key *session_key, u8 *cipher_code,
214 		    struct ecryptfs_message *msg)
215 {
216 	size_t i = 0;
217 	char *data;
218 	size_t data_len;
219 	size_t m_size;
220 	size_t message_len;
221 	u16 checksum = 0;
222 	u16 expected_checksum = 0;
223 	int rc;
224 
225 	/*
226 	 *              ***** TAG 65 Packet Format *****
227 	 *         | Content Type             | 1 byte       |
228 	 *         | Status Indicator         | 1 byte       |
229 	 *         | File Encryption Key Size | 1 or 2 bytes |
230 	 *         | File Encryption Key      | arbitrary    |
231 	 */
232 	message_len = msg->data_len;
233 	data = msg->data;
234 	if (message_len < 4) {
235 		rc = -EIO;
236 		goto out;
237 	}
238 	if (data[i++] != ECRYPTFS_TAG_65_PACKET_TYPE) {
239 		ecryptfs_printk(KERN_ERR, "Type should be ECRYPTFS_TAG_65\n");
240 		rc = -EIO;
241 		goto out;
242 	}
243 	if (data[i++]) {
244 		ecryptfs_printk(KERN_ERR, "Status indicator has non-zero value "
245 				"[%d]\n", data[i-1]);
246 		rc = -EIO;
247 		goto out;
248 	}
249 	rc = ecryptfs_parse_packet_length(&data[i], &m_size, &data_len);
250 	if (rc) {
251 		ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
252 				"rc = [%d]\n", rc);
253 		goto out;
254 	}
255 	i += data_len;
256 	if (message_len < (i + m_size)) {
257 		ecryptfs_printk(KERN_ERR, "The message received from ecryptfsd "
258 				"is shorter than expected\n");
259 		rc = -EIO;
260 		goto out;
261 	}
262 	if (m_size < 3) {
263 		ecryptfs_printk(KERN_ERR,
264 				"The decrypted key is not long enough to "
265 				"include a cipher code and checksum\n");
266 		rc = -EIO;
267 		goto out;
268 	}
269 	*cipher_code = data[i++];
270 	/* The decrypted key includes 1 byte cipher code and 2 byte checksum */
271 	session_key->decrypted_key_size = m_size - 3;
272 	if (session_key->decrypted_key_size > ECRYPTFS_MAX_KEY_BYTES) {
273 		ecryptfs_printk(KERN_ERR, "key_size [%d] larger than "
274 				"the maximum key size [%d]\n",
275 				session_key->decrypted_key_size,
276 				ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES);
277 		rc = -EIO;
278 		goto out;
279 	}
280 	memcpy(session_key->decrypted_key, &data[i],
281 	       session_key->decrypted_key_size);
282 	i += session_key->decrypted_key_size;
283 	expected_checksum += (unsigned char)(data[i++]) << 8;
284 	expected_checksum += (unsigned char)(data[i++]);
285 	for (i = 0; i < session_key->decrypted_key_size; i++)
286 		checksum += session_key->decrypted_key[i];
287 	if (expected_checksum != checksum) {
288 		ecryptfs_printk(KERN_ERR, "Invalid checksum for file "
289 				"encryption  key; expected [%x]; calculated "
290 				"[%x]\n", expected_checksum, checksum);
291 		rc = -EIO;
292 	}
293 out:
294 	return rc;
295 }
296 
297 
298 static int
299 write_tag_66_packet(char *signature, u8 cipher_code,
300 		    struct ecryptfs_crypt_stat *crypt_stat, char **packet,
301 		    size_t *packet_len)
302 {
303 	size_t i = 0;
304 	size_t j;
305 	size_t data_len;
306 	size_t checksum = 0;
307 	size_t packet_size_len;
308 	char *message;
309 	int rc;
310 
311 	/*
312 	 *              ***** TAG 66 Packet Format *****
313 	 *         | Content Type             | 1 byte       |
314 	 *         | Key Identifier Size      | 1 or 2 bytes |
315 	 *         | Key Identifier           | arbitrary    |
316 	 *         | File Encryption Key Size | 1 or 2 bytes |
317 	 *         | File Encryption Key      | arbitrary    |
318 	 */
319 	data_len = (5 + ECRYPTFS_SIG_SIZE_HEX + crypt_stat->key_size);
320 	*packet = kmalloc(data_len, GFP_KERNEL);
321 	message = *packet;
322 	if (!message) {
323 		ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
324 		rc = -ENOMEM;
325 		goto out;
326 	}
327 	message[i++] = ECRYPTFS_TAG_66_PACKET_TYPE;
328 	rc = ecryptfs_write_packet_length(&message[i], ECRYPTFS_SIG_SIZE_HEX,
329 					  &packet_size_len);
330 	if (rc) {
331 		ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet "
332 				"header; cannot generate packet length\n");
333 		goto out;
334 	}
335 	i += packet_size_len;
336 	memcpy(&message[i], signature, ECRYPTFS_SIG_SIZE_HEX);
337 	i += ECRYPTFS_SIG_SIZE_HEX;
338 	/* The encrypted key includes 1 byte cipher code and 2 byte checksum */
339 	rc = ecryptfs_write_packet_length(&message[i], crypt_stat->key_size + 3,
340 					  &packet_size_len);
341 	if (rc) {
342 		ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet "
343 				"header; cannot generate packet length\n");
344 		goto out;
345 	}
346 	i += packet_size_len;
347 	message[i++] = cipher_code;
348 	memcpy(&message[i], crypt_stat->key, crypt_stat->key_size);
349 	i += crypt_stat->key_size;
350 	for (j = 0; j < crypt_stat->key_size; j++)
351 		checksum += crypt_stat->key[j];
352 	message[i++] = (checksum / 256) % 256;
353 	message[i++] = (checksum % 256);
354 	*packet_len = i;
355 out:
356 	return rc;
357 }
358 
359 static int
360 parse_tag_67_packet(struct ecryptfs_key_record *key_rec,
361 		    struct ecryptfs_message *msg)
362 {
363 	size_t i = 0;
364 	char *data;
365 	size_t data_len;
366 	size_t message_len;
367 	int rc;
368 
369 	/*
370 	 *              ***** TAG 65 Packet Format *****
371 	 *    | Content Type                       | 1 byte       |
372 	 *    | Status Indicator                   | 1 byte       |
373 	 *    | Encrypted File Encryption Key Size | 1 or 2 bytes |
374 	 *    | Encrypted File Encryption Key      | arbitrary    |
375 	 */
376 	message_len = msg->data_len;
377 	data = msg->data;
378 	/* verify that everything through the encrypted FEK size is present */
379 	if (message_len < 4) {
380 		rc = -EIO;
381 		printk(KERN_ERR "%s: message_len is [%zd]; minimum acceptable "
382 		       "message length is [%d]\n", __func__, message_len, 4);
383 		goto out;
384 	}
385 	if (data[i++] != ECRYPTFS_TAG_67_PACKET_TYPE) {
386 		rc = -EIO;
387 		printk(KERN_ERR "%s: Type should be ECRYPTFS_TAG_67\n",
388 		       __func__);
389 		goto out;
390 	}
391 	if (data[i++]) {
392 		rc = -EIO;
393 		printk(KERN_ERR "%s: Status indicator has non zero "
394 		       "value [%d]\n", __func__, data[i-1]);
395 
396 		goto out;
397 	}
398 	rc = ecryptfs_parse_packet_length(&data[i], &key_rec->enc_key_size,
399 					  &data_len);
400 	if (rc) {
401 		ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
402 				"rc = [%d]\n", rc);
403 		goto out;
404 	}
405 	i += data_len;
406 	if (message_len < (i + key_rec->enc_key_size)) {
407 		rc = -EIO;
408 		printk(KERN_ERR "%s: message_len [%zd]; max len is [%zd]\n",
409 		       __func__, message_len, (i + key_rec->enc_key_size));
410 		goto out;
411 	}
412 	if (key_rec->enc_key_size > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
413 		rc = -EIO;
414 		printk(KERN_ERR "%s: Encrypted key_size [%zd] larger than "
415 		       "the maximum key size [%d]\n", __func__,
416 		       key_rec->enc_key_size,
417 		       ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES);
418 		goto out;
419 	}
420 	memcpy(key_rec->enc_key, &data[i], key_rec->enc_key_size);
421 out:
422 	return rc;
423 }
424 
425 /**
426  * ecryptfs_verify_version
427  * @version: The version number to confirm
428  *
429  * Returns zero on good version; non-zero otherwise
430  */
431 static int ecryptfs_verify_version(u16 version)
432 {
433 	int rc = 0;
434 	unsigned char major;
435 	unsigned char minor;
436 
437 	major = ((version >> 8) & 0xFF);
438 	minor = (version & 0xFF);
439 	if (major != ECRYPTFS_VERSION_MAJOR) {
440 		ecryptfs_printk(KERN_ERR, "Major version number mismatch. "
441 				"Expected [%d]; got [%d]\n",
442 				ECRYPTFS_VERSION_MAJOR, major);
443 		rc = -EINVAL;
444 		goto out;
445 	}
446 	if (minor != ECRYPTFS_VERSION_MINOR) {
447 		ecryptfs_printk(KERN_ERR, "Minor version number mismatch. "
448 				"Expected [%d]; got [%d]\n",
449 				ECRYPTFS_VERSION_MINOR, minor);
450 		rc = -EINVAL;
451 		goto out;
452 	}
453 out:
454 	return rc;
455 }
456 
457 /**
458  * ecryptfs_verify_auth_tok_from_key
459  * @auth_tok_key: key containing the authentication token
460  * @auth_tok: authentication token
461  *
462  * Returns zero on valid auth tok; -EINVAL if the payload is invalid; or
463  * -EKEYREVOKED if the key was revoked before we acquired its semaphore.
464  */
465 static int
466 ecryptfs_verify_auth_tok_from_key(struct key *auth_tok_key,
467 				  struct ecryptfs_auth_tok **auth_tok)
468 {
469 	int rc = 0;
470 
471 	(*auth_tok) = ecryptfs_get_key_payload_data(auth_tok_key);
472 	if (IS_ERR(*auth_tok)) {
473 		rc = PTR_ERR(*auth_tok);
474 		*auth_tok = NULL;
475 		goto out;
476 	}
477 
478 	if (ecryptfs_verify_version((*auth_tok)->version)) {
479 		printk(KERN_ERR "Data structure version mismatch. Userspace "
480 		       "tools must match eCryptfs kernel module with major "
481 		       "version [%d] and minor version [%d]\n",
482 		       ECRYPTFS_VERSION_MAJOR, ECRYPTFS_VERSION_MINOR);
483 		rc = -EINVAL;
484 		goto out;
485 	}
486 	if ((*auth_tok)->token_type != ECRYPTFS_PASSWORD
487 	    && (*auth_tok)->token_type != ECRYPTFS_PRIVATE_KEY) {
488 		printk(KERN_ERR "Invalid auth_tok structure "
489 		       "returned from key query\n");
490 		rc = -EINVAL;
491 		goto out;
492 	}
493 out:
494 	return rc;
495 }
496 
497 static int
498 ecryptfs_find_global_auth_tok_for_sig(
499 	struct key **auth_tok_key,
500 	struct ecryptfs_auth_tok **auth_tok,
501 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat, char *sig)
502 {
503 	struct ecryptfs_global_auth_tok *walker;
504 	int rc = 0;
505 
506 	(*auth_tok_key) = NULL;
507 	(*auth_tok) = NULL;
508 	mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
509 	list_for_each_entry(walker,
510 			    &mount_crypt_stat->global_auth_tok_list,
511 			    mount_crypt_stat_list) {
512 		if (memcmp(walker->sig, sig, ECRYPTFS_SIG_SIZE_HEX))
513 			continue;
514 
515 		if (walker->flags & ECRYPTFS_AUTH_TOK_INVALID) {
516 			rc = -EINVAL;
517 			goto out;
518 		}
519 
520 		rc = key_validate(walker->global_auth_tok_key);
521 		if (rc) {
522 			if (rc == -EKEYEXPIRED)
523 				goto out;
524 			goto out_invalid_auth_tok;
525 		}
526 
527 		down_write(&(walker->global_auth_tok_key->sem));
528 		rc = ecryptfs_verify_auth_tok_from_key(
529 				walker->global_auth_tok_key, auth_tok);
530 		if (rc)
531 			goto out_invalid_auth_tok_unlock;
532 
533 		(*auth_tok_key) = walker->global_auth_tok_key;
534 		key_get(*auth_tok_key);
535 		goto out;
536 	}
537 	rc = -ENOENT;
538 	goto out;
539 out_invalid_auth_tok_unlock:
540 	up_write(&(walker->global_auth_tok_key->sem));
541 out_invalid_auth_tok:
542 	printk(KERN_WARNING "Invalidating auth tok with sig = [%s]\n", sig);
543 	walker->flags |= ECRYPTFS_AUTH_TOK_INVALID;
544 	key_put(walker->global_auth_tok_key);
545 	walker->global_auth_tok_key = NULL;
546 out:
547 	mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
548 	return rc;
549 }
550 
551 /**
552  * ecryptfs_find_auth_tok_for_sig
553  * @auth_tok: Set to the matching auth_tok; NULL if not found
554  * @crypt_stat: inode crypt_stat crypto context
555  * @sig: Sig of auth_tok to find
556  *
557  * For now, this function simply looks at the registered auth_tok's
558  * linked off the mount_crypt_stat, so all the auth_toks that can be
559  * used must be registered at mount time. This function could
560  * potentially try a lot harder to find auth_tok's (e.g., by calling
561  * out to ecryptfsd to dynamically retrieve an auth_tok object) so
562  * that static registration of auth_tok's will no longer be necessary.
563  *
564  * Returns zero on no error; non-zero on error
565  */
566 static int
567 ecryptfs_find_auth_tok_for_sig(
568 	struct key **auth_tok_key,
569 	struct ecryptfs_auth_tok **auth_tok,
570 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
571 	char *sig)
572 {
573 	int rc = 0;
574 
575 	rc = ecryptfs_find_global_auth_tok_for_sig(auth_tok_key, auth_tok,
576 						   mount_crypt_stat, sig);
577 	if (rc == -ENOENT) {
578 		/* if the flag ECRYPTFS_GLOBAL_MOUNT_AUTH_TOK_ONLY is set in the
579 		 * mount_crypt_stat structure, we prevent to use auth toks that
580 		 * are not inserted through the ecryptfs_add_global_auth_tok
581 		 * function.
582 		 */
583 		if (mount_crypt_stat->flags
584 				& ECRYPTFS_GLOBAL_MOUNT_AUTH_TOK_ONLY)
585 			return -EINVAL;
586 
587 		rc = ecryptfs_keyring_auth_tok_for_sig(auth_tok_key, auth_tok,
588 						       sig);
589 	}
590 	return rc;
591 }
592 
593 /**
594  * write_tag_70_packet can gobble a lot of stack space. We stuff most
595  * of the function's parameters in a kmalloc'd struct to help reduce
596  * eCryptfs' overall stack usage.
597  */
598 struct ecryptfs_write_tag_70_packet_silly_stack {
599 	u8 cipher_code;
600 	size_t max_packet_size;
601 	size_t packet_size_len;
602 	size_t block_aligned_filename_size;
603 	size_t block_size;
604 	size_t i;
605 	size_t j;
606 	size_t num_rand_bytes;
607 	struct mutex *tfm_mutex;
608 	char *block_aligned_filename;
609 	struct ecryptfs_auth_tok *auth_tok;
610 	struct scatterlist src_sg[2];
611 	struct scatterlist dst_sg[2];
612 	struct crypto_skcipher *skcipher_tfm;
613 	struct skcipher_request *skcipher_req;
614 	char iv[ECRYPTFS_MAX_IV_BYTES];
615 	char hash[ECRYPTFS_TAG_70_DIGEST_SIZE];
616 	char tmp_hash[ECRYPTFS_TAG_70_DIGEST_SIZE];
617 	struct crypto_shash *hash_tfm;
618 	struct shash_desc *hash_desc;
619 };
620 
621 /**
622  * write_tag_70_packet - Write encrypted filename (EFN) packet against FNEK
623  * @filename: NULL-terminated filename string
624  *
625  * This is the simplest mechanism for achieving filename encryption in
626  * eCryptfs. It encrypts the given filename with the mount-wide
627  * filename encryption key (FNEK) and stores it in a packet to @dest,
628  * which the callee will encode and write directly into the dentry
629  * name.
630  */
631 int
632 ecryptfs_write_tag_70_packet(char *dest, size_t *remaining_bytes,
633 			     size_t *packet_size,
634 			     struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
635 			     char *filename, size_t filename_size)
636 {
637 	struct ecryptfs_write_tag_70_packet_silly_stack *s;
638 	struct key *auth_tok_key = NULL;
639 	int rc = 0;
640 
641 	s = kzalloc(sizeof(*s), GFP_KERNEL);
642 	if (!s) {
643 		printk(KERN_ERR "%s: Out of memory whilst trying to kmalloc "
644 		       "[%zd] bytes of kernel memory\n", __func__, sizeof(*s));
645 		return -ENOMEM;
646 	}
647 	(*packet_size) = 0;
648 	rc = ecryptfs_find_auth_tok_for_sig(
649 		&auth_tok_key,
650 		&s->auth_tok, mount_crypt_stat,
651 		mount_crypt_stat->global_default_fnek_sig);
652 	if (rc) {
653 		printk(KERN_ERR "%s: Error attempting to find auth tok for "
654 		       "fnek sig [%s]; rc = [%d]\n", __func__,
655 		       mount_crypt_stat->global_default_fnek_sig, rc);
656 		goto out;
657 	}
658 	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(
659 		&s->skcipher_tfm,
660 		&s->tfm_mutex, mount_crypt_stat->global_default_fn_cipher_name);
661 	if (unlikely(rc)) {
662 		printk(KERN_ERR "Internal error whilst attempting to get "
663 		       "tfm and mutex for cipher name [%s]; rc = [%d]\n",
664 		       mount_crypt_stat->global_default_fn_cipher_name, rc);
665 		goto out;
666 	}
667 	mutex_lock(s->tfm_mutex);
668 	s->block_size = crypto_skcipher_blocksize(s->skcipher_tfm);
669 	/* Plus one for the \0 separator between the random prefix
670 	 * and the plaintext filename */
671 	s->num_rand_bytes = (ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES + 1);
672 	s->block_aligned_filename_size = (s->num_rand_bytes + filename_size);
673 	if ((s->block_aligned_filename_size % s->block_size) != 0) {
674 		s->num_rand_bytes += (s->block_size
675 				      - (s->block_aligned_filename_size
676 					 % s->block_size));
677 		s->block_aligned_filename_size = (s->num_rand_bytes
678 						  + filename_size);
679 	}
680 	/* Octet 0: Tag 70 identifier
681 	 * Octets 1-N1: Tag 70 packet size (includes cipher identifier
682 	 *              and block-aligned encrypted filename size)
683 	 * Octets N1-N2: FNEK sig (ECRYPTFS_SIG_SIZE)
684 	 * Octet N2-N3: Cipher identifier (1 octet)
685 	 * Octets N3-N4: Block-aligned encrypted filename
686 	 *  - Consists of a minimum number of random characters, a \0
687 	 *    separator, and then the filename */
688 	s->max_packet_size = (ECRYPTFS_TAG_70_MAX_METADATA_SIZE
689 			      + s->block_aligned_filename_size);
690 	if (dest == NULL) {
691 		(*packet_size) = s->max_packet_size;
692 		goto out_unlock;
693 	}
694 	if (s->max_packet_size > (*remaining_bytes)) {
695 		printk(KERN_WARNING "%s: Require [%zd] bytes to write; only "
696 		       "[%zd] available\n", __func__, s->max_packet_size,
697 		       (*remaining_bytes));
698 		rc = -EINVAL;
699 		goto out_unlock;
700 	}
701 
702 	s->skcipher_req = skcipher_request_alloc(s->skcipher_tfm, GFP_KERNEL);
703 	if (!s->skcipher_req) {
704 		printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
705 		       "skcipher_request_alloc for %s\n", __func__,
706 		       crypto_skcipher_driver_name(s->skcipher_tfm));
707 		rc = -ENOMEM;
708 		goto out_unlock;
709 	}
710 
711 	skcipher_request_set_callback(s->skcipher_req,
712 				      CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
713 
714 	s->block_aligned_filename = kzalloc(s->block_aligned_filename_size,
715 					    GFP_KERNEL);
716 	if (!s->block_aligned_filename) {
717 		printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
718 		       "kzalloc [%zd] bytes\n", __func__,
719 		       s->block_aligned_filename_size);
720 		rc = -ENOMEM;
721 		goto out_unlock;
722 	}
723 	dest[s->i++] = ECRYPTFS_TAG_70_PACKET_TYPE;
724 	rc = ecryptfs_write_packet_length(&dest[s->i],
725 					  (ECRYPTFS_SIG_SIZE
726 					   + 1 /* Cipher code */
727 					   + s->block_aligned_filename_size),
728 					  &s->packet_size_len);
729 	if (rc) {
730 		printk(KERN_ERR "%s: Error generating tag 70 packet "
731 		       "header; cannot generate packet length; rc = [%d]\n",
732 		       __func__, rc);
733 		goto out_free_unlock;
734 	}
735 	s->i += s->packet_size_len;
736 	ecryptfs_from_hex(&dest[s->i],
737 			  mount_crypt_stat->global_default_fnek_sig,
738 			  ECRYPTFS_SIG_SIZE);
739 	s->i += ECRYPTFS_SIG_SIZE;
740 	s->cipher_code = ecryptfs_code_for_cipher_string(
741 		mount_crypt_stat->global_default_fn_cipher_name,
742 		mount_crypt_stat->global_default_fn_cipher_key_bytes);
743 	if (s->cipher_code == 0) {
744 		printk(KERN_WARNING "%s: Unable to generate code for "
745 		       "cipher [%s] with key bytes [%zd]\n", __func__,
746 		       mount_crypt_stat->global_default_fn_cipher_name,
747 		       mount_crypt_stat->global_default_fn_cipher_key_bytes);
748 		rc = -EINVAL;
749 		goto out_free_unlock;
750 	}
751 	dest[s->i++] = s->cipher_code;
752 	/* TODO: Support other key modules than passphrase for
753 	 * filename encryption */
754 	if (s->auth_tok->token_type != ECRYPTFS_PASSWORD) {
755 		rc = -EOPNOTSUPP;
756 		printk(KERN_INFO "%s: Filename encryption only supports "
757 		       "password tokens\n", __func__);
758 		goto out_free_unlock;
759 	}
760 	s->hash_tfm = crypto_alloc_shash(ECRYPTFS_TAG_70_DIGEST, 0, 0);
761 	if (IS_ERR(s->hash_tfm)) {
762 			rc = PTR_ERR(s->hash_tfm);
763 			printk(KERN_ERR "%s: Error attempting to "
764 			       "allocate hash crypto context; rc = [%d]\n",
765 			       __func__, rc);
766 			goto out_free_unlock;
767 	}
768 
769 	s->hash_desc = kmalloc(sizeof(*s->hash_desc) +
770 			       crypto_shash_descsize(s->hash_tfm), GFP_KERNEL);
771 	if (!s->hash_desc) {
772 		printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
773 		       "kmalloc [%zd] bytes\n", __func__,
774 		       sizeof(*s->hash_desc) +
775 		       crypto_shash_descsize(s->hash_tfm));
776 		rc = -ENOMEM;
777 		goto out_release_free_unlock;
778 	}
779 
780 	s->hash_desc->tfm = s->hash_tfm;
781 	s->hash_desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
782 
783 	rc = crypto_shash_digest(s->hash_desc,
784 				 (u8 *)s->auth_tok->token.password.session_key_encryption_key,
785 				 s->auth_tok->token.password.session_key_encryption_key_bytes,
786 				 s->hash);
787 	if (rc) {
788 		printk(KERN_ERR
789 		       "%s: Error computing crypto hash; rc = [%d]\n",
790 		       __func__, rc);
791 		goto out_release_free_unlock;
792 	}
793 	for (s->j = 0; s->j < (s->num_rand_bytes - 1); s->j++) {
794 		s->block_aligned_filename[s->j] =
795 			s->hash[(s->j % ECRYPTFS_TAG_70_DIGEST_SIZE)];
796 		if ((s->j % ECRYPTFS_TAG_70_DIGEST_SIZE)
797 		    == (ECRYPTFS_TAG_70_DIGEST_SIZE - 1)) {
798 			rc = crypto_shash_digest(s->hash_desc, (u8 *)s->hash,
799 						ECRYPTFS_TAG_70_DIGEST_SIZE,
800 						s->tmp_hash);
801 			if (rc) {
802 				printk(KERN_ERR
803 				       "%s: Error computing crypto hash; "
804 				       "rc = [%d]\n", __func__, rc);
805 				goto out_release_free_unlock;
806 			}
807 			memcpy(s->hash, s->tmp_hash,
808 			       ECRYPTFS_TAG_70_DIGEST_SIZE);
809 		}
810 		if (s->block_aligned_filename[s->j] == '\0')
811 			s->block_aligned_filename[s->j] = ECRYPTFS_NON_NULL;
812 	}
813 	memcpy(&s->block_aligned_filename[s->num_rand_bytes], filename,
814 	       filename_size);
815 	rc = virt_to_scatterlist(s->block_aligned_filename,
816 				 s->block_aligned_filename_size, s->src_sg, 2);
817 	if (rc < 1) {
818 		printk(KERN_ERR "%s: Internal error whilst attempting to "
819 		       "convert filename memory to scatterlist; rc = [%d]. "
820 		       "block_aligned_filename_size = [%zd]\n", __func__, rc,
821 		       s->block_aligned_filename_size);
822 		goto out_release_free_unlock;
823 	}
824 	rc = virt_to_scatterlist(&dest[s->i], s->block_aligned_filename_size,
825 				 s->dst_sg, 2);
826 	if (rc < 1) {
827 		printk(KERN_ERR "%s: Internal error whilst attempting to "
828 		       "convert encrypted filename memory to scatterlist; "
829 		       "rc = [%d]. block_aligned_filename_size = [%zd]\n",
830 		       __func__, rc, s->block_aligned_filename_size);
831 		goto out_release_free_unlock;
832 	}
833 	/* The characters in the first block effectively do the job
834 	 * of the IV here, so we just use 0's for the IV. Note the
835 	 * constraint that ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES
836 	 * >= ECRYPTFS_MAX_IV_BYTES. */
837 	rc = crypto_skcipher_setkey(
838 		s->skcipher_tfm,
839 		s->auth_tok->token.password.session_key_encryption_key,
840 		mount_crypt_stat->global_default_fn_cipher_key_bytes);
841 	if (rc < 0) {
842 		printk(KERN_ERR "%s: Error setting key for crypto context; "
843 		       "rc = [%d]. s->auth_tok->token.password.session_key_"
844 		       "encryption_key = [0x%p]; mount_crypt_stat->"
845 		       "global_default_fn_cipher_key_bytes = [%zd]\n", __func__,
846 		       rc,
847 		       s->auth_tok->token.password.session_key_encryption_key,
848 		       mount_crypt_stat->global_default_fn_cipher_key_bytes);
849 		goto out_release_free_unlock;
850 	}
851 	skcipher_request_set_crypt(s->skcipher_req, s->src_sg, s->dst_sg,
852 				   s->block_aligned_filename_size, s->iv);
853 	rc = crypto_skcipher_encrypt(s->skcipher_req);
854 	if (rc) {
855 		printk(KERN_ERR "%s: Error attempting to encrypt filename; "
856 		       "rc = [%d]\n", __func__, rc);
857 		goto out_release_free_unlock;
858 	}
859 	s->i += s->block_aligned_filename_size;
860 	(*packet_size) = s->i;
861 	(*remaining_bytes) -= (*packet_size);
862 out_release_free_unlock:
863 	crypto_free_shash(s->hash_tfm);
864 out_free_unlock:
865 	kzfree(s->block_aligned_filename);
866 out_unlock:
867 	mutex_unlock(s->tfm_mutex);
868 out:
869 	if (auth_tok_key) {
870 		up_write(&(auth_tok_key->sem));
871 		key_put(auth_tok_key);
872 	}
873 	skcipher_request_free(s->skcipher_req);
874 	kzfree(s->hash_desc);
875 	kfree(s);
876 	return rc;
877 }
878 
879 struct ecryptfs_parse_tag_70_packet_silly_stack {
880 	u8 cipher_code;
881 	size_t max_packet_size;
882 	size_t packet_size_len;
883 	size_t parsed_tag_70_packet_size;
884 	size_t block_aligned_filename_size;
885 	size_t block_size;
886 	size_t i;
887 	struct mutex *tfm_mutex;
888 	char *decrypted_filename;
889 	struct ecryptfs_auth_tok *auth_tok;
890 	struct scatterlist src_sg[2];
891 	struct scatterlist dst_sg[2];
892 	struct crypto_skcipher *skcipher_tfm;
893 	struct skcipher_request *skcipher_req;
894 	char fnek_sig_hex[ECRYPTFS_SIG_SIZE_HEX + 1];
895 	char iv[ECRYPTFS_MAX_IV_BYTES];
896 	char cipher_string[ECRYPTFS_MAX_CIPHER_NAME_SIZE + 1];
897 };
898 
899 /**
900  * parse_tag_70_packet - Parse and process FNEK-encrypted passphrase packet
901  * @filename: This function kmalloc's the memory for the filename
902  * @filename_size: This function sets this to the amount of memory
903  *                 kmalloc'd for the filename
904  * @packet_size: This function sets this to the the number of octets
905  *               in the packet parsed
906  * @mount_crypt_stat: The mount-wide cryptographic context
907  * @data: The memory location containing the start of the tag 70
908  *        packet
909  * @max_packet_size: The maximum legal size of the packet to be parsed
910  *                   from @data
911  *
912  * Returns zero on success; non-zero otherwise
913  */
914 int
915 ecryptfs_parse_tag_70_packet(char **filename, size_t *filename_size,
916 			     size_t *packet_size,
917 			     struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
918 			     char *data, size_t max_packet_size)
919 {
920 	struct ecryptfs_parse_tag_70_packet_silly_stack *s;
921 	struct key *auth_tok_key = NULL;
922 	int rc = 0;
923 
924 	(*packet_size) = 0;
925 	(*filename_size) = 0;
926 	(*filename) = NULL;
927 	s = kzalloc(sizeof(*s), GFP_KERNEL);
928 	if (!s) {
929 		printk(KERN_ERR "%s: Out of memory whilst trying to kmalloc "
930 		       "[%zd] bytes of kernel memory\n", __func__, sizeof(*s));
931 		return -ENOMEM;
932 	}
933 	if (max_packet_size < ECRYPTFS_TAG_70_MIN_METADATA_SIZE) {
934 		printk(KERN_WARNING "%s: max_packet_size is [%zd]; it must be "
935 		       "at least [%d]\n", __func__, max_packet_size,
936 		       ECRYPTFS_TAG_70_MIN_METADATA_SIZE);
937 		rc = -EINVAL;
938 		goto out;
939 	}
940 	/* Octet 0: Tag 70 identifier
941 	 * Octets 1-N1: Tag 70 packet size (includes cipher identifier
942 	 *              and block-aligned encrypted filename size)
943 	 * Octets N1-N2: FNEK sig (ECRYPTFS_SIG_SIZE)
944 	 * Octet N2-N3: Cipher identifier (1 octet)
945 	 * Octets N3-N4: Block-aligned encrypted filename
946 	 *  - Consists of a minimum number of random numbers, a \0
947 	 *    separator, and then the filename */
948 	if (data[(*packet_size)++] != ECRYPTFS_TAG_70_PACKET_TYPE) {
949 		printk(KERN_WARNING "%s: Invalid packet tag [0x%.2x]; must be "
950 		       "tag [0x%.2x]\n", __func__,
951 		       data[((*packet_size) - 1)], ECRYPTFS_TAG_70_PACKET_TYPE);
952 		rc = -EINVAL;
953 		goto out;
954 	}
955 	rc = ecryptfs_parse_packet_length(&data[(*packet_size)],
956 					  &s->parsed_tag_70_packet_size,
957 					  &s->packet_size_len);
958 	if (rc) {
959 		printk(KERN_WARNING "%s: Error parsing packet length; "
960 		       "rc = [%d]\n", __func__, rc);
961 		goto out;
962 	}
963 	s->block_aligned_filename_size = (s->parsed_tag_70_packet_size
964 					  - ECRYPTFS_SIG_SIZE - 1);
965 	if ((1 + s->packet_size_len + s->parsed_tag_70_packet_size)
966 	    > max_packet_size) {
967 		printk(KERN_WARNING "%s: max_packet_size is [%zd]; real packet "
968 		       "size is [%zd]\n", __func__, max_packet_size,
969 		       (1 + s->packet_size_len + 1
970 			+ s->block_aligned_filename_size));
971 		rc = -EINVAL;
972 		goto out;
973 	}
974 	(*packet_size) += s->packet_size_len;
975 	ecryptfs_to_hex(s->fnek_sig_hex, &data[(*packet_size)],
976 			ECRYPTFS_SIG_SIZE);
977 	s->fnek_sig_hex[ECRYPTFS_SIG_SIZE_HEX] = '\0';
978 	(*packet_size) += ECRYPTFS_SIG_SIZE;
979 	s->cipher_code = data[(*packet_size)++];
980 	rc = ecryptfs_cipher_code_to_string(s->cipher_string, s->cipher_code);
981 	if (rc) {
982 		printk(KERN_WARNING "%s: Cipher code [%d] is invalid\n",
983 		       __func__, s->cipher_code);
984 		goto out;
985 	}
986 	rc = ecryptfs_find_auth_tok_for_sig(&auth_tok_key,
987 					    &s->auth_tok, mount_crypt_stat,
988 					    s->fnek_sig_hex);
989 	if (rc) {
990 		printk(KERN_ERR "%s: Error attempting to find auth tok for "
991 		       "fnek sig [%s]; rc = [%d]\n", __func__, s->fnek_sig_hex,
992 		       rc);
993 		goto out;
994 	}
995 	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&s->skcipher_tfm,
996 							&s->tfm_mutex,
997 							s->cipher_string);
998 	if (unlikely(rc)) {
999 		printk(KERN_ERR "Internal error whilst attempting to get "
1000 		       "tfm and mutex for cipher name [%s]; rc = [%d]\n",
1001 		       s->cipher_string, rc);
1002 		goto out;
1003 	}
1004 	mutex_lock(s->tfm_mutex);
1005 	rc = virt_to_scatterlist(&data[(*packet_size)],
1006 				 s->block_aligned_filename_size, s->src_sg, 2);
1007 	if (rc < 1) {
1008 		printk(KERN_ERR "%s: Internal error whilst attempting to "
1009 		       "convert encrypted filename memory to scatterlist; "
1010 		       "rc = [%d]. block_aligned_filename_size = [%zd]\n",
1011 		       __func__, rc, s->block_aligned_filename_size);
1012 		goto out_unlock;
1013 	}
1014 	(*packet_size) += s->block_aligned_filename_size;
1015 	s->decrypted_filename = kmalloc(s->block_aligned_filename_size,
1016 					GFP_KERNEL);
1017 	if (!s->decrypted_filename) {
1018 		printk(KERN_ERR "%s: Out of memory whilst attempting to "
1019 		       "kmalloc [%zd] bytes\n", __func__,
1020 		       s->block_aligned_filename_size);
1021 		rc = -ENOMEM;
1022 		goto out_unlock;
1023 	}
1024 	rc = virt_to_scatterlist(s->decrypted_filename,
1025 				 s->block_aligned_filename_size, s->dst_sg, 2);
1026 	if (rc < 1) {
1027 		printk(KERN_ERR "%s: Internal error whilst attempting to "
1028 		       "convert decrypted filename memory to scatterlist; "
1029 		       "rc = [%d]. block_aligned_filename_size = [%zd]\n",
1030 		       __func__, rc, s->block_aligned_filename_size);
1031 		goto out_free_unlock;
1032 	}
1033 
1034 	s->skcipher_req = skcipher_request_alloc(s->skcipher_tfm, GFP_KERNEL);
1035 	if (!s->skcipher_req) {
1036 		printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
1037 		       "skcipher_request_alloc for %s\n", __func__,
1038 		       crypto_skcipher_driver_name(s->skcipher_tfm));
1039 		rc = -ENOMEM;
1040 		goto out_free_unlock;
1041 	}
1042 
1043 	skcipher_request_set_callback(s->skcipher_req,
1044 				      CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
1045 
1046 	/* The characters in the first block effectively do the job of
1047 	 * the IV here, so we just use 0's for the IV. Note the
1048 	 * constraint that ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES
1049 	 * >= ECRYPTFS_MAX_IV_BYTES. */
1050 	/* TODO: Support other key modules than passphrase for
1051 	 * filename encryption */
1052 	if (s->auth_tok->token_type != ECRYPTFS_PASSWORD) {
1053 		rc = -EOPNOTSUPP;
1054 		printk(KERN_INFO "%s: Filename encryption only supports "
1055 		       "password tokens\n", __func__);
1056 		goto out_free_unlock;
1057 	}
1058 	rc = crypto_skcipher_setkey(
1059 		s->skcipher_tfm,
1060 		s->auth_tok->token.password.session_key_encryption_key,
1061 		mount_crypt_stat->global_default_fn_cipher_key_bytes);
1062 	if (rc < 0) {
1063 		printk(KERN_ERR "%s: Error setting key for crypto context; "
1064 		       "rc = [%d]. s->auth_tok->token.password.session_key_"
1065 		       "encryption_key = [0x%p]; mount_crypt_stat->"
1066 		       "global_default_fn_cipher_key_bytes = [%zd]\n", __func__,
1067 		       rc,
1068 		       s->auth_tok->token.password.session_key_encryption_key,
1069 		       mount_crypt_stat->global_default_fn_cipher_key_bytes);
1070 		goto out_free_unlock;
1071 	}
1072 	skcipher_request_set_crypt(s->skcipher_req, s->src_sg, s->dst_sg,
1073 				   s->block_aligned_filename_size, s->iv);
1074 	rc = crypto_skcipher_decrypt(s->skcipher_req);
1075 	if (rc) {
1076 		printk(KERN_ERR "%s: Error attempting to decrypt filename; "
1077 		       "rc = [%d]\n", __func__, rc);
1078 		goto out_free_unlock;
1079 	}
1080 	while (s->decrypted_filename[s->i] != '\0'
1081 	       && s->i < s->block_aligned_filename_size)
1082 		s->i++;
1083 	if (s->i == s->block_aligned_filename_size) {
1084 		printk(KERN_WARNING "%s: Invalid tag 70 packet; could not "
1085 		       "find valid separator between random characters and "
1086 		       "the filename\n", __func__);
1087 		rc = -EINVAL;
1088 		goto out_free_unlock;
1089 	}
1090 	s->i++;
1091 	(*filename_size) = (s->block_aligned_filename_size - s->i);
1092 	if (!((*filename_size) > 0 && (*filename_size < PATH_MAX))) {
1093 		printk(KERN_WARNING "%s: Filename size is [%zd], which is "
1094 		       "invalid\n", __func__, (*filename_size));
1095 		rc = -EINVAL;
1096 		goto out_free_unlock;
1097 	}
1098 	(*filename) = kmalloc(((*filename_size) + 1), GFP_KERNEL);
1099 	if (!(*filename)) {
1100 		printk(KERN_ERR "%s: Out of memory whilst attempting to "
1101 		       "kmalloc [%zd] bytes\n", __func__,
1102 		       ((*filename_size) + 1));
1103 		rc = -ENOMEM;
1104 		goto out_free_unlock;
1105 	}
1106 	memcpy((*filename), &s->decrypted_filename[s->i], (*filename_size));
1107 	(*filename)[(*filename_size)] = '\0';
1108 out_free_unlock:
1109 	kfree(s->decrypted_filename);
1110 out_unlock:
1111 	mutex_unlock(s->tfm_mutex);
1112 out:
1113 	if (rc) {
1114 		(*packet_size) = 0;
1115 		(*filename_size) = 0;
1116 		(*filename) = NULL;
1117 	}
1118 	if (auth_tok_key) {
1119 		up_write(&(auth_tok_key->sem));
1120 		key_put(auth_tok_key);
1121 	}
1122 	skcipher_request_free(s->skcipher_req);
1123 	kfree(s);
1124 	return rc;
1125 }
1126 
1127 static int
1128 ecryptfs_get_auth_tok_sig(char **sig, struct ecryptfs_auth_tok *auth_tok)
1129 {
1130 	int rc = 0;
1131 
1132 	(*sig) = NULL;
1133 	switch (auth_tok->token_type) {
1134 	case ECRYPTFS_PASSWORD:
1135 		(*sig) = auth_tok->token.password.signature;
1136 		break;
1137 	case ECRYPTFS_PRIVATE_KEY:
1138 		(*sig) = auth_tok->token.private_key.signature;
1139 		break;
1140 	default:
1141 		printk(KERN_ERR "Cannot get sig for auth_tok of type [%d]\n",
1142 		       auth_tok->token_type);
1143 		rc = -EINVAL;
1144 	}
1145 	return rc;
1146 }
1147 
1148 /**
1149  * decrypt_pki_encrypted_session_key - Decrypt the session key with the given auth_tok.
1150  * @auth_tok: The key authentication token used to decrypt the session key
1151  * @crypt_stat: The cryptographic context
1152  *
1153  * Returns zero on success; non-zero error otherwise.
1154  */
1155 static int
1156 decrypt_pki_encrypted_session_key(struct ecryptfs_auth_tok *auth_tok,
1157 				  struct ecryptfs_crypt_stat *crypt_stat)
1158 {
1159 	u8 cipher_code = 0;
1160 	struct ecryptfs_msg_ctx *msg_ctx;
1161 	struct ecryptfs_message *msg = NULL;
1162 	char *auth_tok_sig;
1163 	char *payload = NULL;
1164 	size_t payload_len = 0;
1165 	int rc;
1166 
1167 	rc = ecryptfs_get_auth_tok_sig(&auth_tok_sig, auth_tok);
1168 	if (rc) {
1169 		printk(KERN_ERR "Unrecognized auth tok type: [%d]\n",
1170 		       auth_tok->token_type);
1171 		goto out;
1172 	}
1173 	rc = write_tag_64_packet(auth_tok_sig, &(auth_tok->session_key),
1174 				 &payload, &payload_len);
1175 	if (rc) {
1176 		ecryptfs_printk(KERN_ERR, "Failed to write tag 64 packet\n");
1177 		goto out;
1178 	}
1179 	rc = ecryptfs_send_message(payload, payload_len, &msg_ctx);
1180 	if (rc) {
1181 		ecryptfs_printk(KERN_ERR, "Error sending message to "
1182 				"ecryptfsd: %d\n", rc);
1183 		goto out;
1184 	}
1185 	rc = ecryptfs_wait_for_response(msg_ctx, &msg);
1186 	if (rc) {
1187 		ecryptfs_printk(KERN_ERR, "Failed to receive tag 65 packet "
1188 				"from the user space daemon\n");
1189 		rc = -EIO;
1190 		goto out;
1191 	}
1192 	rc = parse_tag_65_packet(&(auth_tok->session_key),
1193 				 &cipher_code, msg);
1194 	if (rc) {
1195 		printk(KERN_ERR "Failed to parse tag 65 packet; rc = [%d]\n",
1196 		       rc);
1197 		goto out;
1198 	}
1199 	auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1200 	memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
1201 	       auth_tok->session_key.decrypted_key_size);
1202 	crypt_stat->key_size = auth_tok->session_key.decrypted_key_size;
1203 	rc = ecryptfs_cipher_code_to_string(crypt_stat->cipher, cipher_code);
1204 	if (rc) {
1205 		ecryptfs_printk(KERN_ERR, "Cipher code [%d] is invalid\n",
1206 				cipher_code)
1207 		goto out;
1208 	}
1209 	crypt_stat->flags |= ECRYPTFS_KEY_VALID;
1210 	if (ecryptfs_verbosity > 0) {
1211 		ecryptfs_printk(KERN_DEBUG, "Decrypted session key:\n");
1212 		ecryptfs_dump_hex(crypt_stat->key,
1213 				  crypt_stat->key_size);
1214 	}
1215 out:
1216 	kfree(msg);
1217 	kfree(payload);
1218 	return rc;
1219 }
1220 
1221 static void wipe_auth_tok_list(struct list_head *auth_tok_list_head)
1222 {
1223 	struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1224 	struct ecryptfs_auth_tok_list_item *auth_tok_list_item_tmp;
1225 
1226 	list_for_each_entry_safe(auth_tok_list_item, auth_tok_list_item_tmp,
1227 				 auth_tok_list_head, list) {
1228 		list_del(&auth_tok_list_item->list);
1229 		kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1230 				auth_tok_list_item);
1231 	}
1232 }
1233 
1234 struct kmem_cache *ecryptfs_auth_tok_list_item_cache;
1235 
1236 /**
1237  * parse_tag_1_packet
1238  * @crypt_stat: The cryptographic context to modify based on packet contents
1239  * @data: The raw bytes of the packet.
1240  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
1241  *                 a new authentication token will be placed at the
1242  *                 end of this list for this packet.
1243  * @new_auth_tok: Pointer to a pointer to memory that this function
1244  *                allocates; sets the memory address of the pointer to
1245  *                NULL on error. This object is added to the
1246  *                auth_tok_list.
1247  * @packet_size: This function writes the size of the parsed packet
1248  *               into this memory location; zero on error.
1249  * @max_packet_size: The maximum allowable packet size
1250  *
1251  * Returns zero on success; non-zero on error.
1252  */
1253 static int
1254 parse_tag_1_packet(struct ecryptfs_crypt_stat *crypt_stat,
1255 		   unsigned char *data, struct list_head *auth_tok_list,
1256 		   struct ecryptfs_auth_tok **new_auth_tok,
1257 		   size_t *packet_size, size_t max_packet_size)
1258 {
1259 	size_t body_size;
1260 	struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1261 	size_t length_size;
1262 	int rc = 0;
1263 
1264 	(*packet_size) = 0;
1265 	(*new_auth_tok) = NULL;
1266 	/**
1267 	 * This format is inspired by OpenPGP; see RFC 2440
1268 	 * packet tag 1
1269 	 *
1270 	 * Tag 1 identifier (1 byte)
1271 	 * Max Tag 1 packet size (max 3 bytes)
1272 	 * Version (1 byte)
1273 	 * Key identifier (8 bytes; ECRYPTFS_SIG_SIZE)
1274 	 * Cipher identifier (1 byte)
1275 	 * Encrypted key size (arbitrary)
1276 	 *
1277 	 * 12 bytes minimum packet size
1278 	 */
1279 	if (unlikely(max_packet_size < 12)) {
1280 		printk(KERN_ERR "Invalid max packet size; must be >=12\n");
1281 		rc = -EINVAL;
1282 		goto out;
1283 	}
1284 	if (data[(*packet_size)++] != ECRYPTFS_TAG_1_PACKET_TYPE) {
1285 		printk(KERN_ERR "Enter w/ first byte != 0x%.2x\n",
1286 		       ECRYPTFS_TAG_1_PACKET_TYPE);
1287 		rc = -EINVAL;
1288 		goto out;
1289 	}
1290 	/* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
1291 	 * at end of function upon failure */
1292 	auth_tok_list_item =
1293 		kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache,
1294 				  GFP_KERNEL);
1295 	if (!auth_tok_list_item) {
1296 		printk(KERN_ERR "Unable to allocate memory\n");
1297 		rc = -ENOMEM;
1298 		goto out;
1299 	}
1300 	(*new_auth_tok) = &auth_tok_list_item->auth_tok;
1301 	rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1302 					  &length_size);
1303 	if (rc) {
1304 		printk(KERN_WARNING "Error parsing packet length; "
1305 		       "rc = [%d]\n", rc);
1306 		goto out_free;
1307 	}
1308 	if (unlikely(body_size < (ECRYPTFS_SIG_SIZE + 2))) {
1309 		printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1310 		rc = -EINVAL;
1311 		goto out_free;
1312 	}
1313 	(*packet_size) += length_size;
1314 	if (unlikely((*packet_size) + body_size > max_packet_size)) {
1315 		printk(KERN_WARNING "Packet size exceeds max\n");
1316 		rc = -EINVAL;
1317 		goto out_free;
1318 	}
1319 	if (unlikely(data[(*packet_size)++] != 0x03)) {
1320 		printk(KERN_WARNING "Unknown version number [%d]\n",
1321 		       data[(*packet_size) - 1]);
1322 		rc = -EINVAL;
1323 		goto out_free;
1324 	}
1325 	ecryptfs_to_hex((*new_auth_tok)->token.private_key.signature,
1326 			&data[(*packet_size)], ECRYPTFS_SIG_SIZE);
1327 	*packet_size += ECRYPTFS_SIG_SIZE;
1328 	/* This byte is skipped because the kernel does not need to
1329 	 * know which public key encryption algorithm was used */
1330 	(*packet_size)++;
1331 	(*new_auth_tok)->session_key.encrypted_key_size =
1332 		body_size - (ECRYPTFS_SIG_SIZE + 2);
1333 	if ((*new_auth_tok)->session_key.encrypted_key_size
1334 	    > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
1335 		printk(KERN_WARNING "Tag 1 packet contains key larger "
1336 		       "than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES");
1337 		rc = -EINVAL;
1338 		goto out;
1339 	}
1340 	memcpy((*new_auth_tok)->session_key.encrypted_key,
1341 	       &data[(*packet_size)], (body_size - (ECRYPTFS_SIG_SIZE + 2)));
1342 	(*packet_size) += (*new_auth_tok)->session_key.encrypted_key_size;
1343 	(*new_auth_tok)->session_key.flags &=
1344 		~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1345 	(*new_auth_tok)->session_key.flags |=
1346 		ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
1347 	(*new_auth_tok)->token_type = ECRYPTFS_PRIVATE_KEY;
1348 	(*new_auth_tok)->flags = 0;
1349 	(*new_auth_tok)->session_key.flags &=
1350 		~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
1351 	(*new_auth_tok)->session_key.flags &=
1352 		~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
1353 	list_add(&auth_tok_list_item->list, auth_tok_list);
1354 	goto out;
1355 out_free:
1356 	(*new_auth_tok) = NULL;
1357 	memset(auth_tok_list_item, 0,
1358 	       sizeof(struct ecryptfs_auth_tok_list_item));
1359 	kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1360 			auth_tok_list_item);
1361 out:
1362 	if (rc)
1363 		(*packet_size) = 0;
1364 	return rc;
1365 }
1366 
1367 /**
1368  * parse_tag_3_packet
1369  * @crypt_stat: The cryptographic context to modify based on packet
1370  *              contents.
1371  * @data: The raw bytes of the packet.
1372  * @auth_tok_list: eCryptfs parses packets into authentication tokens;
1373  *                 a new authentication token will be placed at the end
1374  *                 of this list for this packet.
1375  * @new_auth_tok: Pointer to a pointer to memory that this function
1376  *                allocates; sets the memory address of the pointer to
1377  *                NULL on error. This object is added to the
1378  *                auth_tok_list.
1379  * @packet_size: This function writes the size of the parsed packet
1380  *               into this memory location; zero on error.
1381  * @max_packet_size: maximum number of bytes to parse
1382  *
1383  * Returns zero on success; non-zero on error.
1384  */
1385 static int
1386 parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat,
1387 		   unsigned char *data, struct list_head *auth_tok_list,
1388 		   struct ecryptfs_auth_tok **new_auth_tok,
1389 		   size_t *packet_size, size_t max_packet_size)
1390 {
1391 	size_t body_size;
1392 	struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1393 	size_t length_size;
1394 	int rc = 0;
1395 
1396 	(*packet_size) = 0;
1397 	(*new_auth_tok) = NULL;
1398 	/**
1399 	 *This format is inspired by OpenPGP; see RFC 2440
1400 	 * packet tag 3
1401 	 *
1402 	 * Tag 3 identifier (1 byte)
1403 	 * Max Tag 3 packet size (max 3 bytes)
1404 	 * Version (1 byte)
1405 	 * Cipher code (1 byte)
1406 	 * S2K specifier (1 byte)
1407 	 * Hash identifier (1 byte)
1408 	 * Salt (ECRYPTFS_SALT_SIZE)
1409 	 * Hash iterations (1 byte)
1410 	 * Encrypted key (arbitrary)
1411 	 *
1412 	 * (ECRYPTFS_SALT_SIZE + 7) minimum packet size
1413 	 */
1414 	if (max_packet_size < (ECRYPTFS_SALT_SIZE + 7)) {
1415 		printk(KERN_ERR "Max packet size too large\n");
1416 		rc = -EINVAL;
1417 		goto out;
1418 	}
1419 	if (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) {
1420 		printk(KERN_ERR "First byte != 0x%.2x; invalid packet\n",
1421 		       ECRYPTFS_TAG_3_PACKET_TYPE);
1422 		rc = -EINVAL;
1423 		goto out;
1424 	}
1425 	/* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
1426 	 * at end of function upon failure */
1427 	auth_tok_list_item =
1428 	    kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL);
1429 	if (!auth_tok_list_item) {
1430 		printk(KERN_ERR "Unable to allocate memory\n");
1431 		rc = -ENOMEM;
1432 		goto out;
1433 	}
1434 	(*new_auth_tok) = &auth_tok_list_item->auth_tok;
1435 	rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1436 					  &length_size);
1437 	if (rc) {
1438 		printk(KERN_WARNING "Error parsing packet length; rc = [%d]\n",
1439 		       rc);
1440 		goto out_free;
1441 	}
1442 	if (unlikely(body_size < (ECRYPTFS_SALT_SIZE + 5))) {
1443 		printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1444 		rc = -EINVAL;
1445 		goto out_free;
1446 	}
1447 	(*packet_size) += length_size;
1448 	if (unlikely((*packet_size) + body_size > max_packet_size)) {
1449 		printk(KERN_ERR "Packet size exceeds max\n");
1450 		rc = -EINVAL;
1451 		goto out_free;
1452 	}
1453 	(*new_auth_tok)->session_key.encrypted_key_size =
1454 		(body_size - (ECRYPTFS_SALT_SIZE + 5));
1455 	if ((*new_auth_tok)->session_key.encrypted_key_size
1456 	    > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
1457 		printk(KERN_WARNING "Tag 3 packet contains key larger "
1458 		       "than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES\n");
1459 		rc = -EINVAL;
1460 		goto out_free;
1461 	}
1462 	if (unlikely(data[(*packet_size)++] != 0x04)) {
1463 		printk(KERN_WARNING "Unknown version number [%d]\n",
1464 		       data[(*packet_size) - 1]);
1465 		rc = -EINVAL;
1466 		goto out_free;
1467 	}
1468 	rc = ecryptfs_cipher_code_to_string(crypt_stat->cipher,
1469 					    (u16)data[(*packet_size)]);
1470 	if (rc)
1471 		goto out_free;
1472 	/* A little extra work to differentiate among the AES key
1473 	 * sizes; see RFC2440 */
1474 	switch(data[(*packet_size)++]) {
1475 	case RFC2440_CIPHER_AES_192:
1476 		crypt_stat->key_size = 24;
1477 		break;
1478 	default:
1479 		crypt_stat->key_size =
1480 			(*new_auth_tok)->session_key.encrypted_key_size;
1481 	}
1482 	rc = ecryptfs_init_crypt_ctx(crypt_stat);
1483 	if (rc)
1484 		goto out_free;
1485 	if (unlikely(data[(*packet_size)++] != 0x03)) {
1486 		printk(KERN_WARNING "Only S2K ID 3 is currently supported\n");
1487 		rc = -ENOSYS;
1488 		goto out_free;
1489 	}
1490 	/* TODO: finish the hash mapping */
1491 	switch (data[(*packet_size)++]) {
1492 	case 0x01: /* See RFC2440 for these numbers and their mappings */
1493 		/* Choose MD5 */
1494 		memcpy((*new_auth_tok)->token.password.salt,
1495 		       &data[(*packet_size)], ECRYPTFS_SALT_SIZE);
1496 		(*packet_size) += ECRYPTFS_SALT_SIZE;
1497 		/* This conversion was taken straight from RFC2440 */
1498 		(*new_auth_tok)->token.password.hash_iterations =
1499 			((u32) 16 + (data[(*packet_size)] & 15))
1500 				<< ((data[(*packet_size)] >> 4) + 6);
1501 		(*packet_size)++;
1502 		/* Friendly reminder:
1503 		 * (*new_auth_tok)->session_key.encrypted_key_size =
1504 		 *         (body_size - (ECRYPTFS_SALT_SIZE + 5)); */
1505 		memcpy((*new_auth_tok)->session_key.encrypted_key,
1506 		       &data[(*packet_size)],
1507 		       (*new_auth_tok)->session_key.encrypted_key_size);
1508 		(*packet_size) +=
1509 			(*new_auth_tok)->session_key.encrypted_key_size;
1510 		(*new_auth_tok)->session_key.flags &=
1511 			~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1512 		(*new_auth_tok)->session_key.flags |=
1513 			ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
1514 		(*new_auth_tok)->token.password.hash_algo = 0x01; /* MD5 */
1515 		break;
1516 	default:
1517 		ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: "
1518 				"[%d]\n", data[(*packet_size) - 1]);
1519 		rc = -ENOSYS;
1520 		goto out_free;
1521 	}
1522 	(*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;
1523 	/* TODO: Parametarize; we might actually want userspace to
1524 	 * decrypt the session key. */
1525 	(*new_auth_tok)->session_key.flags &=
1526 			    ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
1527 	(*new_auth_tok)->session_key.flags &=
1528 			    ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
1529 	list_add(&auth_tok_list_item->list, auth_tok_list);
1530 	goto out;
1531 out_free:
1532 	(*new_auth_tok) = NULL;
1533 	memset(auth_tok_list_item, 0,
1534 	       sizeof(struct ecryptfs_auth_tok_list_item));
1535 	kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1536 			auth_tok_list_item);
1537 out:
1538 	if (rc)
1539 		(*packet_size) = 0;
1540 	return rc;
1541 }
1542 
1543 /**
1544  * parse_tag_11_packet
1545  * @data: The raw bytes of the packet
1546  * @contents: This function writes the data contents of the literal
1547  *            packet into this memory location
1548  * @max_contents_bytes: The maximum number of bytes that this function
1549  *                      is allowed to write into contents
1550  * @tag_11_contents_size: This function writes the size of the parsed
1551  *                        contents into this memory location; zero on
1552  *                        error
1553  * @packet_size: This function writes the size of the parsed packet
1554  *               into this memory location; zero on error
1555  * @max_packet_size: maximum number of bytes to parse
1556  *
1557  * Returns zero on success; non-zero on error.
1558  */
1559 static int
1560 parse_tag_11_packet(unsigned char *data, unsigned char *contents,
1561 		    size_t max_contents_bytes, size_t *tag_11_contents_size,
1562 		    size_t *packet_size, size_t max_packet_size)
1563 {
1564 	size_t body_size;
1565 	size_t length_size;
1566 	int rc = 0;
1567 
1568 	(*packet_size) = 0;
1569 	(*tag_11_contents_size) = 0;
1570 	/* This format is inspired by OpenPGP; see RFC 2440
1571 	 * packet tag 11
1572 	 *
1573 	 * Tag 11 identifier (1 byte)
1574 	 * Max Tag 11 packet size (max 3 bytes)
1575 	 * Binary format specifier (1 byte)
1576 	 * Filename length (1 byte)
1577 	 * Filename ("_CONSOLE") (8 bytes)
1578 	 * Modification date (4 bytes)
1579 	 * Literal data (arbitrary)
1580 	 *
1581 	 * We need at least 16 bytes of data for the packet to even be
1582 	 * valid.
1583 	 */
1584 	if (max_packet_size < 16) {
1585 		printk(KERN_ERR "Maximum packet size too small\n");
1586 		rc = -EINVAL;
1587 		goto out;
1588 	}
1589 	if (data[(*packet_size)++] != ECRYPTFS_TAG_11_PACKET_TYPE) {
1590 		printk(KERN_WARNING "Invalid tag 11 packet format\n");
1591 		rc = -EINVAL;
1592 		goto out;
1593 	}
1594 	rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1595 					  &length_size);
1596 	if (rc) {
1597 		printk(KERN_WARNING "Invalid tag 11 packet format\n");
1598 		goto out;
1599 	}
1600 	if (body_size < 14) {
1601 		printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1602 		rc = -EINVAL;
1603 		goto out;
1604 	}
1605 	(*packet_size) += length_size;
1606 	(*tag_11_contents_size) = (body_size - 14);
1607 	if (unlikely((*packet_size) + body_size + 1 > max_packet_size)) {
1608 		printk(KERN_ERR "Packet size exceeds max\n");
1609 		rc = -EINVAL;
1610 		goto out;
1611 	}
1612 	if (unlikely((*tag_11_contents_size) > max_contents_bytes)) {
1613 		printk(KERN_ERR "Literal data section in tag 11 packet exceeds "
1614 		       "expected size\n");
1615 		rc = -EINVAL;
1616 		goto out;
1617 	}
1618 	if (data[(*packet_size)++] != 0x62) {
1619 		printk(KERN_WARNING "Unrecognizable packet\n");
1620 		rc = -EINVAL;
1621 		goto out;
1622 	}
1623 	if (data[(*packet_size)++] != 0x08) {
1624 		printk(KERN_WARNING "Unrecognizable packet\n");
1625 		rc = -EINVAL;
1626 		goto out;
1627 	}
1628 	(*packet_size) += 12; /* Ignore filename and modification date */
1629 	memcpy(contents, &data[(*packet_size)], (*tag_11_contents_size));
1630 	(*packet_size) += (*tag_11_contents_size);
1631 out:
1632 	if (rc) {
1633 		(*packet_size) = 0;
1634 		(*tag_11_contents_size) = 0;
1635 	}
1636 	return rc;
1637 }
1638 
1639 int ecryptfs_keyring_auth_tok_for_sig(struct key **auth_tok_key,
1640 				      struct ecryptfs_auth_tok **auth_tok,
1641 				      char *sig)
1642 {
1643 	int rc = 0;
1644 
1645 	(*auth_tok_key) = request_key(&key_type_user, sig, NULL);
1646 	if (!(*auth_tok_key) || IS_ERR(*auth_tok_key)) {
1647 		(*auth_tok_key) = ecryptfs_get_encrypted_key(sig);
1648 		if (!(*auth_tok_key) || IS_ERR(*auth_tok_key)) {
1649 			printk(KERN_ERR "Could not find key with description: [%s]\n",
1650 			      sig);
1651 			rc = process_request_key_err(PTR_ERR(*auth_tok_key));
1652 			(*auth_tok_key) = NULL;
1653 			goto out;
1654 		}
1655 	}
1656 	down_write(&(*auth_tok_key)->sem);
1657 	rc = ecryptfs_verify_auth_tok_from_key(*auth_tok_key, auth_tok);
1658 	if (rc) {
1659 		up_write(&(*auth_tok_key)->sem);
1660 		key_put(*auth_tok_key);
1661 		(*auth_tok_key) = NULL;
1662 		goto out;
1663 	}
1664 out:
1665 	return rc;
1666 }
1667 
1668 /**
1669  * decrypt_passphrase_encrypted_session_key - Decrypt the session key with the given auth_tok.
1670  * @auth_tok: The passphrase authentication token to use to encrypt the FEK
1671  * @crypt_stat: The cryptographic context
1672  *
1673  * Returns zero on success; non-zero error otherwise
1674  */
1675 static int
1676 decrypt_passphrase_encrypted_session_key(struct ecryptfs_auth_tok *auth_tok,
1677 					 struct ecryptfs_crypt_stat *crypt_stat)
1678 {
1679 	struct scatterlist dst_sg[2];
1680 	struct scatterlist src_sg[2];
1681 	struct mutex *tfm_mutex;
1682 	struct crypto_skcipher *tfm;
1683 	struct skcipher_request *req = NULL;
1684 	int rc = 0;
1685 
1686 	if (unlikely(ecryptfs_verbosity > 0)) {
1687 		ecryptfs_printk(
1688 			KERN_DEBUG, "Session key encryption key (size [%d]):\n",
1689 			auth_tok->token.password.session_key_encryption_key_bytes);
1690 		ecryptfs_dump_hex(
1691 			auth_tok->token.password.session_key_encryption_key,
1692 			auth_tok->token.password.session_key_encryption_key_bytes);
1693 	}
1694 	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&tfm, &tfm_mutex,
1695 							crypt_stat->cipher);
1696 	if (unlikely(rc)) {
1697 		printk(KERN_ERR "Internal error whilst attempting to get "
1698 		       "tfm and mutex for cipher name [%s]; rc = [%d]\n",
1699 		       crypt_stat->cipher, rc);
1700 		goto out;
1701 	}
1702 	rc = virt_to_scatterlist(auth_tok->session_key.encrypted_key,
1703 				 auth_tok->session_key.encrypted_key_size,
1704 				 src_sg, 2);
1705 	if (rc < 1 || rc > 2) {
1706 		printk(KERN_ERR "Internal error whilst attempting to convert "
1707 			"auth_tok->session_key.encrypted_key to scatterlist; "
1708 			"expected rc = 1; got rc = [%d]. "
1709 		       "auth_tok->session_key.encrypted_key_size = [%d]\n", rc,
1710 			auth_tok->session_key.encrypted_key_size);
1711 		goto out;
1712 	}
1713 	auth_tok->session_key.decrypted_key_size =
1714 		auth_tok->session_key.encrypted_key_size;
1715 	rc = virt_to_scatterlist(auth_tok->session_key.decrypted_key,
1716 				 auth_tok->session_key.decrypted_key_size,
1717 				 dst_sg, 2);
1718 	if (rc < 1 || rc > 2) {
1719 		printk(KERN_ERR "Internal error whilst attempting to convert "
1720 			"auth_tok->session_key.decrypted_key to scatterlist; "
1721 			"expected rc = 1; got rc = [%d]\n", rc);
1722 		goto out;
1723 	}
1724 	mutex_lock(tfm_mutex);
1725 	req = skcipher_request_alloc(tfm, GFP_KERNEL);
1726 	if (!req) {
1727 		mutex_unlock(tfm_mutex);
1728 		printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
1729 		       "skcipher_request_alloc for %s\n", __func__,
1730 		       crypto_skcipher_driver_name(tfm));
1731 		rc = -ENOMEM;
1732 		goto out;
1733 	}
1734 
1735 	skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP,
1736 				      NULL, NULL);
1737 	rc = crypto_skcipher_setkey(
1738 		tfm, auth_tok->token.password.session_key_encryption_key,
1739 		crypt_stat->key_size);
1740 	if (unlikely(rc < 0)) {
1741 		mutex_unlock(tfm_mutex);
1742 		printk(KERN_ERR "Error setting key for crypto context\n");
1743 		rc = -EINVAL;
1744 		goto out;
1745 	}
1746 	skcipher_request_set_crypt(req, src_sg, dst_sg,
1747 				   auth_tok->session_key.encrypted_key_size,
1748 				   NULL);
1749 	rc = crypto_skcipher_decrypt(req);
1750 	mutex_unlock(tfm_mutex);
1751 	if (unlikely(rc)) {
1752 		printk(KERN_ERR "Error decrypting; rc = [%d]\n", rc);
1753 		goto out;
1754 	}
1755 	auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1756 	memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
1757 	       auth_tok->session_key.decrypted_key_size);
1758 	crypt_stat->flags |= ECRYPTFS_KEY_VALID;
1759 	if (unlikely(ecryptfs_verbosity > 0)) {
1760 		ecryptfs_printk(KERN_DEBUG, "FEK of size [%zd]:\n",
1761 				crypt_stat->key_size);
1762 		ecryptfs_dump_hex(crypt_stat->key,
1763 				  crypt_stat->key_size);
1764 	}
1765 out:
1766 	skcipher_request_free(req);
1767 	return rc;
1768 }
1769 
1770 /**
1771  * ecryptfs_parse_packet_set
1772  * @crypt_stat: The cryptographic context
1773  * @src: Virtual address of region of memory containing the packets
1774  * @ecryptfs_dentry: The eCryptfs dentry associated with the packet set
1775  *
1776  * Get crypt_stat to have the file's session key if the requisite key
1777  * is available to decrypt the session key.
1778  *
1779  * Returns Zero if a valid authentication token was retrieved and
1780  * processed; negative value for file not encrypted or for error
1781  * conditions.
1782  */
1783 int ecryptfs_parse_packet_set(struct ecryptfs_crypt_stat *crypt_stat,
1784 			      unsigned char *src,
1785 			      struct dentry *ecryptfs_dentry)
1786 {
1787 	size_t i = 0;
1788 	size_t found_auth_tok;
1789 	size_t next_packet_is_auth_tok_packet;
1790 	struct list_head auth_tok_list;
1791 	struct ecryptfs_auth_tok *matching_auth_tok;
1792 	struct ecryptfs_auth_tok *candidate_auth_tok;
1793 	char *candidate_auth_tok_sig;
1794 	size_t packet_size;
1795 	struct ecryptfs_auth_tok *new_auth_tok;
1796 	unsigned char sig_tmp_space[ECRYPTFS_SIG_SIZE];
1797 	struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1798 	size_t tag_11_contents_size;
1799 	size_t tag_11_packet_size;
1800 	struct key *auth_tok_key = NULL;
1801 	int rc = 0;
1802 
1803 	INIT_LIST_HEAD(&auth_tok_list);
1804 	/* Parse the header to find as many packets as we can; these will be
1805 	 * added the our &auth_tok_list */
1806 	next_packet_is_auth_tok_packet = 1;
1807 	while (next_packet_is_auth_tok_packet) {
1808 		size_t max_packet_size = ((PAGE_SIZE - 8) - i);
1809 
1810 		switch (src[i]) {
1811 		case ECRYPTFS_TAG_3_PACKET_TYPE:
1812 			rc = parse_tag_3_packet(crypt_stat,
1813 						(unsigned char *)&src[i],
1814 						&auth_tok_list, &new_auth_tok,
1815 						&packet_size, max_packet_size);
1816 			if (rc) {
1817 				ecryptfs_printk(KERN_ERR, "Error parsing "
1818 						"tag 3 packet\n");
1819 				rc = -EIO;
1820 				goto out_wipe_list;
1821 			}
1822 			i += packet_size;
1823 			rc = parse_tag_11_packet((unsigned char *)&src[i],
1824 						 sig_tmp_space,
1825 						 ECRYPTFS_SIG_SIZE,
1826 						 &tag_11_contents_size,
1827 						 &tag_11_packet_size,
1828 						 max_packet_size);
1829 			if (rc) {
1830 				ecryptfs_printk(KERN_ERR, "No valid "
1831 						"(ecryptfs-specific) literal "
1832 						"packet containing "
1833 						"authentication token "
1834 						"signature found after "
1835 						"tag 3 packet\n");
1836 				rc = -EIO;
1837 				goto out_wipe_list;
1838 			}
1839 			i += tag_11_packet_size;
1840 			if (ECRYPTFS_SIG_SIZE != tag_11_contents_size) {
1841 				ecryptfs_printk(KERN_ERR, "Expected "
1842 						"signature of size [%d]; "
1843 						"read size [%zd]\n",
1844 						ECRYPTFS_SIG_SIZE,
1845 						tag_11_contents_size);
1846 				rc = -EIO;
1847 				goto out_wipe_list;
1848 			}
1849 			ecryptfs_to_hex(new_auth_tok->token.password.signature,
1850 					sig_tmp_space, tag_11_contents_size);
1851 			new_auth_tok->token.password.signature[
1852 				ECRYPTFS_PASSWORD_SIG_SIZE] = '\0';
1853 			crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1854 			break;
1855 		case ECRYPTFS_TAG_1_PACKET_TYPE:
1856 			rc = parse_tag_1_packet(crypt_stat,
1857 						(unsigned char *)&src[i],
1858 						&auth_tok_list, &new_auth_tok,
1859 						&packet_size, max_packet_size);
1860 			if (rc) {
1861 				ecryptfs_printk(KERN_ERR, "Error parsing "
1862 						"tag 1 packet\n");
1863 				rc = -EIO;
1864 				goto out_wipe_list;
1865 			}
1866 			i += packet_size;
1867 			crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1868 			break;
1869 		case ECRYPTFS_TAG_11_PACKET_TYPE:
1870 			ecryptfs_printk(KERN_WARNING, "Invalid packet set "
1871 					"(Tag 11 not allowed by itself)\n");
1872 			rc = -EIO;
1873 			goto out_wipe_list;
1874 		default:
1875 			ecryptfs_printk(KERN_DEBUG, "No packet at offset [%zd] "
1876 					"of the file header; hex value of "
1877 					"character is [0x%.2x]\n", i, src[i]);
1878 			next_packet_is_auth_tok_packet = 0;
1879 		}
1880 	}
1881 	if (list_empty(&auth_tok_list)) {
1882 		printk(KERN_ERR "The lower file appears to be a non-encrypted "
1883 		       "eCryptfs file; this is not supported in this version "
1884 		       "of the eCryptfs kernel module\n");
1885 		rc = -EINVAL;
1886 		goto out;
1887 	}
1888 	/* auth_tok_list contains the set of authentication tokens
1889 	 * parsed from the metadata. We need to find a matching
1890 	 * authentication token that has the secret component(s)
1891 	 * necessary to decrypt the EFEK in the auth_tok parsed from
1892 	 * the metadata. There may be several potential matches, but
1893 	 * just one will be sufficient to decrypt to get the FEK. */
1894 find_next_matching_auth_tok:
1895 	found_auth_tok = 0;
1896 	list_for_each_entry(auth_tok_list_item, &auth_tok_list, list) {
1897 		candidate_auth_tok = &auth_tok_list_item->auth_tok;
1898 		if (unlikely(ecryptfs_verbosity > 0)) {
1899 			ecryptfs_printk(KERN_DEBUG,
1900 					"Considering cadidate auth tok:\n");
1901 			ecryptfs_dump_auth_tok(candidate_auth_tok);
1902 		}
1903 		rc = ecryptfs_get_auth_tok_sig(&candidate_auth_tok_sig,
1904 					       candidate_auth_tok);
1905 		if (rc) {
1906 			printk(KERN_ERR
1907 			       "Unrecognized candidate auth tok type: [%d]\n",
1908 			       candidate_auth_tok->token_type);
1909 			rc = -EINVAL;
1910 			goto out_wipe_list;
1911 		}
1912 		rc = ecryptfs_find_auth_tok_for_sig(&auth_tok_key,
1913 					       &matching_auth_tok,
1914 					       crypt_stat->mount_crypt_stat,
1915 					       candidate_auth_tok_sig);
1916 		if (!rc) {
1917 			found_auth_tok = 1;
1918 			goto found_matching_auth_tok;
1919 		}
1920 	}
1921 	if (!found_auth_tok) {
1922 		ecryptfs_printk(KERN_ERR, "Could not find a usable "
1923 				"authentication token\n");
1924 		rc = -EIO;
1925 		goto out_wipe_list;
1926 	}
1927 found_matching_auth_tok:
1928 	if (candidate_auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
1929 		memcpy(&(candidate_auth_tok->token.private_key),
1930 		       &(matching_auth_tok->token.private_key),
1931 		       sizeof(struct ecryptfs_private_key));
1932 		up_write(&(auth_tok_key->sem));
1933 		key_put(auth_tok_key);
1934 		rc = decrypt_pki_encrypted_session_key(candidate_auth_tok,
1935 						       crypt_stat);
1936 	} else if (candidate_auth_tok->token_type == ECRYPTFS_PASSWORD) {
1937 		memcpy(&(candidate_auth_tok->token.password),
1938 		       &(matching_auth_tok->token.password),
1939 		       sizeof(struct ecryptfs_password));
1940 		up_write(&(auth_tok_key->sem));
1941 		key_put(auth_tok_key);
1942 		rc = decrypt_passphrase_encrypted_session_key(
1943 			candidate_auth_tok, crypt_stat);
1944 	} else {
1945 		up_write(&(auth_tok_key->sem));
1946 		key_put(auth_tok_key);
1947 		rc = -EINVAL;
1948 	}
1949 	if (rc) {
1950 		struct ecryptfs_auth_tok_list_item *auth_tok_list_item_tmp;
1951 
1952 		ecryptfs_printk(KERN_WARNING, "Error decrypting the "
1953 				"session key for authentication token with sig "
1954 				"[%.*s]; rc = [%d]. Removing auth tok "
1955 				"candidate from the list and searching for "
1956 				"the next match.\n", ECRYPTFS_SIG_SIZE_HEX,
1957 				candidate_auth_tok_sig,	rc);
1958 		list_for_each_entry_safe(auth_tok_list_item,
1959 					 auth_tok_list_item_tmp,
1960 					 &auth_tok_list, list) {
1961 			if (candidate_auth_tok
1962 			    == &auth_tok_list_item->auth_tok) {
1963 				list_del(&auth_tok_list_item->list);
1964 				kmem_cache_free(
1965 					ecryptfs_auth_tok_list_item_cache,
1966 					auth_tok_list_item);
1967 				goto find_next_matching_auth_tok;
1968 			}
1969 		}
1970 		BUG();
1971 	}
1972 	rc = ecryptfs_compute_root_iv(crypt_stat);
1973 	if (rc) {
1974 		ecryptfs_printk(KERN_ERR, "Error computing "
1975 				"the root IV\n");
1976 		goto out_wipe_list;
1977 	}
1978 	rc = ecryptfs_init_crypt_ctx(crypt_stat);
1979 	if (rc) {
1980 		ecryptfs_printk(KERN_ERR, "Error initializing crypto "
1981 				"context for cipher [%s]; rc = [%d]\n",
1982 				crypt_stat->cipher, rc);
1983 	}
1984 out_wipe_list:
1985 	wipe_auth_tok_list(&auth_tok_list);
1986 out:
1987 	return rc;
1988 }
1989 
1990 static int
1991 pki_encrypt_session_key(struct key *auth_tok_key,
1992 			struct ecryptfs_auth_tok *auth_tok,
1993 			struct ecryptfs_crypt_stat *crypt_stat,
1994 			struct ecryptfs_key_record *key_rec)
1995 {
1996 	struct ecryptfs_msg_ctx *msg_ctx = NULL;
1997 	char *payload = NULL;
1998 	size_t payload_len = 0;
1999 	struct ecryptfs_message *msg;
2000 	int rc;
2001 
2002 	rc = write_tag_66_packet(auth_tok->token.private_key.signature,
2003 				 ecryptfs_code_for_cipher_string(
2004 					 crypt_stat->cipher,
2005 					 crypt_stat->key_size),
2006 				 crypt_stat, &payload, &payload_len);
2007 	up_write(&(auth_tok_key->sem));
2008 	key_put(auth_tok_key);
2009 	if (rc) {
2010 		ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet\n");
2011 		goto out;
2012 	}
2013 	rc = ecryptfs_send_message(payload, payload_len, &msg_ctx);
2014 	if (rc) {
2015 		ecryptfs_printk(KERN_ERR, "Error sending message to "
2016 				"ecryptfsd: %d\n", rc);
2017 		goto out;
2018 	}
2019 	rc = ecryptfs_wait_for_response(msg_ctx, &msg);
2020 	if (rc) {
2021 		ecryptfs_printk(KERN_ERR, "Failed to receive tag 67 packet "
2022 				"from the user space daemon\n");
2023 		rc = -EIO;
2024 		goto out;
2025 	}
2026 	rc = parse_tag_67_packet(key_rec, msg);
2027 	if (rc)
2028 		ecryptfs_printk(KERN_ERR, "Error parsing tag 67 packet\n");
2029 	kfree(msg);
2030 out:
2031 	kfree(payload);
2032 	return rc;
2033 }
2034 /**
2035  * write_tag_1_packet - Write an RFC2440-compatible tag 1 (public key) packet
2036  * @dest: Buffer into which to write the packet
2037  * @remaining_bytes: Maximum number of bytes that can be writtn
2038  * @auth_tok_key: The authentication token key to unlock and put when done with
2039  *                @auth_tok
2040  * @auth_tok: The authentication token used for generating the tag 1 packet
2041  * @crypt_stat: The cryptographic context
2042  * @key_rec: The key record struct for the tag 1 packet
2043  * @packet_size: This function will write the number of bytes that end
2044  *               up constituting the packet; set to zero on error
2045  *
2046  * Returns zero on success; non-zero on error.
2047  */
2048 static int
2049 write_tag_1_packet(char *dest, size_t *remaining_bytes,
2050 		   struct key *auth_tok_key, struct ecryptfs_auth_tok *auth_tok,
2051 		   struct ecryptfs_crypt_stat *crypt_stat,
2052 		   struct ecryptfs_key_record *key_rec, size_t *packet_size)
2053 {
2054 	size_t i;
2055 	size_t encrypted_session_key_valid = 0;
2056 	size_t packet_size_length;
2057 	size_t max_packet_size;
2058 	int rc = 0;
2059 
2060 	(*packet_size) = 0;
2061 	ecryptfs_from_hex(key_rec->sig, auth_tok->token.private_key.signature,
2062 			  ECRYPTFS_SIG_SIZE);
2063 	encrypted_session_key_valid = 0;
2064 	for (i = 0; i < crypt_stat->key_size; i++)
2065 		encrypted_session_key_valid |=
2066 			auth_tok->session_key.encrypted_key[i];
2067 	if (encrypted_session_key_valid) {
2068 		memcpy(key_rec->enc_key,
2069 		       auth_tok->session_key.encrypted_key,
2070 		       auth_tok->session_key.encrypted_key_size);
2071 		up_write(&(auth_tok_key->sem));
2072 		key_put(auth_tok_key);
2073 		goto encrypted_session_key_set;
2074 	}
2075 	if (auth_tok->session_key.encrypted_key_size == 0)
2076 		auth_tok->session_key.encrypted_key_size =
2077 			auth_tok->token.private_key.key_size;
2078 	rc = pki_encrypt_session_key(auth_tok_key, auth_tok, crypt_stat,
2079 				     key_rec);
2080 	if (rc) {
2081 		printk(KERN_ERR "Failed to encrypt session key via a key "
2082 		       "module; rc = [%d]\n", rc);
2083 		goto out;
2084 	}
2085 	if (ecryptfs_verbosity > 0) {
2086 		ecryptfs_printk(KERN_DEBUG, "Encrypted key:\n");
2087 		ecryptfs_dump_hex(key_rec->enc_key, key_rec->enc_key_size);
2088 	}
2089 encrypted_session_key_set:
2090 	/* This format is inspired by OpenPGP; see RFC 2440
2091 	 * packet tag 1 */
2092 	max_packet_size = (1                         /* Tag 1 identifier */
2093 			   + 3                       /* Max Tag 1 packet size */
2094 			   + 1                       /* Version */
2095 			   + ECRYPTFS_SIG_SIZE       /* Key identifier */
2096 			   + 1                       /* Cipher identifier */
2097 			   + key_rec->enc_key_size); /* Encrypted key size */
2098 	if (max_packet_size > (*remaining_bytes)) {
2099 		printk(KERN_ERR "Packet length larger than maximum allowable; "
2100 		       "need up to [%td] bytes, but there are only [%td] "
2101 		       "available\n", max_packet_size, (*remaining_bytes));
2102 		rc = -EINVAL;
2103 		goto out;
2104 	}
2105 	dest[(*packet_size)++] = ECRYPTFS_TAG_1_PACKET_TYPE;
2106 	rc = ecryptfs_write_packet_length(&dest[(*packet_size)],
2107 					  (max_packet_size - 4),
2108 					  &packet_size_length);
2109 	if (rc) {
2110 		ecryptfs_printk(KERN_ERR, "Error generating tag 1 packet "
2111 				"header; cannot generate packet length\n");
2112 		goto out;
2113 	}
2114 	(*packet_size) += packet_size_length;
2115 	dest[(*packet_size)++] = 0x03; /* version 3 */
2116 	memcpy(&dest[(*packet_size)], key_rec->sig, ECRYPTFS_SIG_SIZE);
2117 	(*packet_size) += ECRYPTFS_SIG_SIZE;
2118 	dest[(*packet_size)++] = RFC2440_CIPHER_RSA;
2119 	memcpy(&dest[(*packet_size)], key_rec->enc_key,
2120 	       key_rec->enc_key_size);
2121 	(*packet_size) += key_rec->enc_key_size;
2122 out:
2123 	if (rc)
2124 		(*packet_size) = 0;
2125 	else
2126 		(*remaining_bytes) -= (*packet_size);
2127 	return rc;
2128 }
2129 
2130 /**
2131  * write_tag_11_packet
2132  * @dest: Target into which Tag 11 packet is to be written
2133  * @remaining_bytes: Maximum packet length
2134  * @contents: Byte array of contents to copy in
2135  * @contents_length: Number of bytes in contents
2136  * @packet_length: Length of the Tag 11 packet written; zero on error
2137  *
2138  * Returns zero on success; non-zero on error.
2139  */
2140 static int
2141 write_tag_11_packet(char *dest, size_t *remaining_bytes, char *contents,
2142 		    size_t contents_length, size_t *packet_length)
2143 {
2144 	size_t packet_size_length;
2145 	size_t max_packet_size;
2146 	int rc = 0;
2147 
2148 	(*packet_length) = 0;
2149 	/* This format is inspired by OpenPGP; see RFC 2440
2150 	 * packet tag 11 */
2151 	max_packet_size = (1                   /* Tag 11 identifier */
2152 			   + 3                 /* Max Tag 11 packet size */
2153 			   + 1                 /* Binary format specifier */
2154 			   + 1                 /* Filename length */
2155 			   + 8                 /* Filename ("_CONSOLE") */
2156 			   + 4                 /* Modification date */
2157 			   + contents_length); /* Literal data */
2158 	if (max_packet_size > (*remaining_bytes)) {
2159 		printk(KERN_ERR "Packet length larger than maximum allowable; "
2160 		       "need up to [%td] bytes, but there are only [%td] "
2161 		       "available\n", max_packet_size, (*remaining_bytes));
2162 		rc = -EINVAL;
2163 		goto out;
2164 	}
2165 	dest[(*packet_length)++] = ECRYPTFS_TAG_11_PACKET_TYPE;
2166 	rc = ecryptfs_write_packet_length(&dest[(*packet_length)],
2167 					  (max_packet_size - 4),
2168 					  &packet_size_length);
2169 	if (rc) {
2170 		printk(KERN_ERR "Error generating tag 11 packet header; cannot "
2171 		       "generate packet length. rc = [%d]\n", rc);
2172 		goto out;
2173 	}
2174 	(*packet_length) += packet_size_length;
2175 	dest[(*packet_length)++] = 0x62; /* binary data format specifier */
2176 	dest[(*packet_length)++] = 8;
2177 	memcpy(&dest[(*packet_length)], "_CONSOLE", 8);
2178 	(*packet_length) += 8;
2179 	memset(&dest[(*packet_length)], 0x00, 4);
2180 	(*packet_length) += 4;
2181 	memcpy(&dest[(*packet_length)], contents, contents_length);
2182 	(*packet_length) += contents_length;
2183  out:
2184 	if (rc)
2185 		(*packet_length) = 0;
2186 	else
2187 		(*remaining_bytes) -= (*packet_length);
2188 	return rc;
2189 }
2190 
2191 /**
2192  * write_tag_3_packet
2193  * @dest: Buffer into which to write the packet
2194  * @remaining_bytes: Maximum number of bytes that can be written
2195  * @auth_tok: Authentication token
2196  * @crypt_stat: The cryptographic context
2197  * @key_rec: encrypted key
2198  * @packet_size: This function will write the number of bytes that end
2199  *               up constituting the packet; set to zero on error
2200  *
2201  * Returns zero on success; non-zero on error.
2202  */
2203 static int
2204 write_tag_3_packet(char *dest, size_t *remaining_bytes,
2205 		   struct ecryptfs_auth_tok *auth_tok,
2206 		   struct ecryptfs_crypt_stat *crypt_stat,
2207 		   struct ecryptfs_key_record *key_rec, size_t *packet_size)
2208 {
2209 	size_t i;
2210 	size_t encrypted_session_key_valid = 0;
2211 	char session_key_encryption_key[ECRYPTFS_MAX_KEY_BYTES];
2212 	struct scatterlist dst_sg[2];
2213 	struct scatterlist src_sg[2];
2214 	struct mutex *tfm_mutex = NULL;
2215 	u8 cipher_code;
2216 	size_t packet_size_length;
2217 	size_t max_packet_size;
2218 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
2219 		crypt_stat->mount_crypt_stat;
2220 	struct crypto_skcipher *tfm;
2221 	struct skcipher_request *req;
2222 	int rc = 0;
2223 
2224 	(*packet_size) = 0;
2225 	ecryptfs_from_hex(key_rec->sig, auth_tok->token.password.signature,
2226 			  ECRYPTFS_SIG_SIZE);
2227 	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&tfm, &tfm_mutex,
2228 							crypt_stat->cipher);
2229 	if (unlikely(rc)) {
2230 		printk(KERN_ERR "Internal error whilst attempting to get "
2231 		       "tfm and mutex for cipher name [%s]; rc = [%d]\n",
2232 		       crypt_stat->cipher, rc);
2233 		goto out;
2234 	}
2235 	if (mount_crypt_stat->global_default_cipher_key_size == 0) {
2236 		printk(KERN_WARNING "No key size specified at mount; "
2237 		       "defaulting to [%d]\n",
2238 		       crypto_skcipher_default_keysize(tfm));
2239 		mount_crypt_stat->global_default_cipher_key_size =
2240 			crypto_skcipher_default_keysize(tfm);
2241 	}
2242 	if (crypt_stat->key_size == 0)
2243 		crypt_stat->key_size =
2244 			mount_crypt_stat->global_default_cipher_key_size;
2245 	if (auth_tok->session_key.encrypted_key_size == 0)
2246 		auth_tok->session_key.encrypted_key_size =
2247 			crypt_stat->key_size;
2248 	if (crypt_stat->key_size == 24
2249 	    && strcmp("aes", crypt_stat->cipher) == 0) {
2250 		memset((crypt_stat->key + 24), 0, 8);
2251 		auth_tok->session_key.encrypted_key_size = 32;
2252 	} else
2253 		auth_tok->session_key.encrypted_key_size = crypt_stat->key_size;
2254 	key_rec->enc_key_size =
2255 		auth_tok->session_key.encrypted_key_size;
2256 	encrypted_session_key_valid = 0;
2257 	for (i = 0; i < auth_tok->session_key.encrypted_key_size; i++)
2258 		encrypted_session_key_valid |=
2259 			auth_tok->session_key.encrypted_key[i];
2260 	if (encrypted_session_key_valid) {
2261 		ecryptfs_printk(KERN_DEBUG, "encrypted_session_key_valid != 0; "
2262 				"using auth_tok->session_key.encrypted_key, "
2263 				"where key_rec->enc_key_size = [%zd]\n",
2264 				key_rec->enc_key_size);
2265 		memcpy(key_rec->enc_key,
2266 		       auth_tok->session_key.encrypted_key,
2267 		       key_rec->enc_key_size);
2268 		goto encrypted_session_key_set;
2269 	}
2270 	if (auth_tok->token.password.flags &
2271 	    ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET) {
2272 		ecryptfs_printk(KERN_DEBUG, "Using previously generated "
2273 				"session key encryption key of size [%d]\n",
2274 				auth_tok->token.password.
2275 				session_key_encryption_key_bytes);
2276 		memcpy(session_key_encryption_key,
2277 		       auth_tok->token.password.session_key_encryption_key,
2278 		       crypt_stat->key_size);
2279 		ecryptfs_printk(KERN_DEBUG,
2280 				"Cached session key encryption key:\n");
2281 		if (ecryptfs_verbosity > 0)
2282 			ecryptfs_dump_hex(session_key_encryption_key, 16);
2283 	}
2284 	if (unlikely(ecryptfs_verbosity > 0)) {
2285 		ecryptfs_printk(KERN_DEBUG, "Session key encryption key:\n");
2286 		ecryptfs_dump_hex(session_key_encryption_key, 16);
2287 	}
2288 	rc = virt_to_scatterlist(crypt_stat->key, key_rec->enc_key_size,
2289 				 src_sg, 2);
2290 	if (rc < 1 || rc > 2) {
2291 		ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
2292 				"for crypt_stat session key; expected rc = 1; "
2293 				"got rc = [%d]. key_rec->enc_key_size = [%zd]\n",
2294 				rc, key_rec->enc_key_size);
2295 		rc = -ENOMEM;
2296 		goto out;
2297 	}
2298 	rc = virt_to_scatterlist(key_rec->enc_key, key_rec->enc_key_size,
2299 				 dst_sg, 2);
2300 	if (rc < 1 || rc > 2) {
2301 		ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
2302 				"for crypt_stat encrypted session key; "
2303 				"expected rc = 1; got rc = [%d]. "
2304 				"key_rec->enc_key_size = [%zd]\n", rc,
2305 				key_rec->enc_key_size);
2306 		rc = -ENOMEM;
2307 		goto out;
2308 	}
2309 	mutex_lock(tfm_mutex);
2310 	rc = crypto_skcipher_setkey(tfm, session_key_encryption_key,
2311 				    crypt_stat->key_size);
2312 	if (rc < 0) {
2313 		mutex_unlock(tfm_mutex);
2314 		ecryptfs_printk(KERN_ERR, "Error setting key for crypto "
2315 				"context; rc = [%d]\n", rc);
2316 		goto out;
2317 	}
2318 
2319 	req = skcipher_request_alloc(tfm, GFP_KERNEL);
2320 	if (!req) {
2321 		mutex_unlock(tfm_mutex);
2322 		ecryptfs_printk(KERN_ERR, "Out of kernel memory whilst "
2323 				"attempting to skcipher_request_alloc for "
2324 				"%s\n", crypto_skcipher_driver_name(tfm));
2325 		rc = -ENOMEM;
2326 		goto out;
2327 	}
2328 
2329 	skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP,
2330 				      NULL, NULL);
2331 
2332 	rc = 0;
2333 	ecryptfs_printk(KERN_DEBUG, "Encrypting [%zd] bytes of the key\n",
2334 			crypt_stat->key_size);
2335 	skcipher_request_set_crypt(req, src_sg, dst_sg,
2336 				   (*key_rec).enc_key_size, NULL);
2337 	rc = crypto_skcipher_encrypt(req);
2338 	mutex_unlock(tfm_mutex);
2339 	skcipher_request_free(req);
2340 	if (rc) {
2341 		printk(KERN_ERR "Error encrypting; rc = [%d]\n", rc);
2342 		goto out;
2343 	}
2344 	ecryptfs_printk(KERN_DEBUG, "This should be the encrypted key:\n");
2345 	if (ecryptfs_verbosity > 0) {
2346 		ecryptfs_printk(KERN_DEBUG, "EFEK of size [%zd]:\n",
2347 				key_rec->enc_key_size);
2348 		ecryptfs_dump_hex(key_rec->enc_key,
2349 				  key_rec->enc_key_size);
2350 	}
2351 encrypted_session_key_set:
2352 	/* This format is inspired by OpenPGP; see RFC 2440
2353 	 * packet tag 3 */
2354 	max_packet_size = (1                         /* Tag 3 identifier */
2355 			   + 3                       /* Max Tag 3 packet size */
2356 			   + 1                       /* Version */
2357 			   + 1                       /* Cipher code */
2358 			   + 1                       /* S2K specifier */
2359 			   + 1                       /* Hash identifier */
2360 			   + ECRYPTFS_SALT_SIZE      /* Salt */
2361 			   + 1                       /* Hash iterations */
2362 			   + key_rec->enc_key_size); /* Encrypted key size */
2363 	if (max_packet_size > (*remaining_bytes)) {
2364 		printk(KERN_ERR "Packet too large; need up to [%td] bytes, but "
2365 		       "there are only [%td] available\n", max_packet_size,
2366 		       (*remaining_bytes));
2367 		rc = -EINVAL;
2368 		goto out;
2369 	}
2370 	dest[(*packet_size)++] = ECRYPTFS_TAG_3_PACKET_TYPE;
2371 	/* Chop off the Tag 3 identifier(1) and Tag 3 packet size(3)
2372 	 * to get the number of octets in the actual Tag 3 packet */
2373 	rc = ecryptfs_write_packet_length(&dest[(*packet_size)],
2374 					  (max_packet_size - 4),
2375 					  &packet_size_length);
2376 	if (rc) {
2377 		printk(KERN_ERR "Error generating tag 3 packet header; cannot "
2378 		       "generate packet length. rc = [%d]\n", rc);
2379 		goto out;
2380 	}
2381 	(*packet_size) += packet_size_length;
2382 	dest[(*packet_size)++] = 0x04; /* version 4 */
2383 	/* TODO: Break from RFC2440 so that arbitrary ciphers can be
2384 	 * specified with strings */
2385 	cipher_code = ecryptfs_code_for_cipher_string(crypt_stat->cipher,
2386 						      crypt_stat->key_size);
2387 	if (cipher_code == 0) {
2388 		ecryptfs_printk(KERN_WARNING, "Unable to generate code for "
2389 				"cipher [%s]\n", crypt_stat->cipher);
2390 		rc = -EINVAL;
2391 		goto out;
2392 	}
2393 	dest[(*packet_size)++] = cipher_code;
2394 	dest[(*packet_size)++] = 0x03;	/* S2K */
2395 	dest[(*packet_size)++] = 0x01;	/* MD5 (TODO: parameterize) */
2396 	memcpy(&dest[(*packet_size)], auth_tok->token.password.salt,
2397 	       ECRYPTFS_SALT_SIZE);
2398 	(*packet_size) += ECRYPTFS_SALT_SIZE;	/* salt */
2399 	dest[(*packet_size)++] = 0x60;	/* hash iterations (65536) */
2400 	memcpy(&dest[(*packet_size)], key_rec->enc_key,
2401 	       key_rec->enc_key_size);
2402 	(*packet_size) += key_rec->enc_key_size;
2403 out:
2404 	if (rc)
2405 		(*packet_size) = 0;
2406 	else
2407 		(*remaining_bytes) -= (*packet_size);
2408 	return rc;
2409 }
2410 
2411 struct kmem_cache *ecryptfs_key_record_cache;
2412 
2413 /**
2414  * ecryptfs_generate_key_packet_set
2415  * @dest_base: Virtual address from which to write the key record set
2416  * @crypt_stat: The cryptographic context from which the
2417  *              authentication tokens will be retrieved
2418  * @ecryptfs_dentry: The dentry, used to retrieve the mount crypt stat
2419  *                   for the global parameters
2420  * @len: The amount written
2421  * @max: The maximum amount of data allowed to be written
2422  *
2423  * Generates a key packet set and writes it to the virtual address
2424  * passed in.
2425  *
2426  * Returns zero on success; non-zero on error.
2427  */
2428 int
2429 ecryptfs_generate_key_packet_set(char *dest_base,
2430 				 struct ecryptfs_crypt_stat *crypt_stat,
2431 				 struct dentry *ecryptfs_dentry, size_t *len,
2432 				 size_t max)
2433 {
2434 	struct ecryptfs_auth_tok *auth_tok;
2435 	struct key *auth_tok_key = NULL;
2436 	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
2437 		&ecryptfs_superblock_to_private(
2438 			ecryptfs_dentry->d_sb)->mount_crypt_stat;
2439 	size_t written;
2440 	struct ecryptfs_key_record *key_rec;
2441 	struct ecryptfs_key_sig *key_sig;
2442 	int rc = 0;
2443 
2444 	(*len) = 0;
2445 	mutex_lock(&crypt_stat->keysig_list_mutex);
2446 	key_rec = kmem_cache_alloc(ecryptfs_key_record_cache, GFP_KERNEL);
2447 	if (!key_rec) {
2448 		rc = -ENOMEM;
2449 		goto out;
2450 	}
2451 	list_for_each_entry(key_sig, &crypt_stat->keysig_list,
2452 			    crypt_stat_list) {
2453 		memset(key_rec, 0, sizeof(*key_rec));
2454 		rc = ecryptfs_find_global_auth_tok_for_sig(&auth_tok_key,
2455 							   &auth_tok,
2456 							   mount_crypt_stat,
2457 							   key_sig->keysig);
2458 		if (rc) {
2459 			printk(KERN_WARNING "Unable to retrieve auth tok with "
2460 			       "sig = [%s]\n", key_sig->keysig);
2461 			rc = process_find_global_auth_tok_for_sig_err(rc);
2462 			goto out_free;
2463 		}
2464 		if (auth_tok->token_type == ECRYPTFS_PASSWORD) {
2465 			rc = write_tag_3_packet((dest_base + (*len)),
2466 						&max, auth_tok,
2467 						crypt_stat, key_rec,
2468 						&written);
2469 			up_write(&(auth_tok_key->sem));
2470 			key_put(auth_tok_key);
2471 			if (rc) {
2472 				ecryptfs_printk(KERN_WARNING, "Error "
2473 						"writing tag 3 packet\n");
2474 				goto out_free;
2475 			}
2476 			(*len) += written;
2477 			/* Write auth tok signature packet */
2478 			rc = write_tag_11_packet((dest_base + (*len)), &max,
2479 						 key_rec->sig,
2480 						 ECRYPTFS_SIG_SIZE, &written);
2481 			if (rc) {
2482 				ecryptfs_printk(KERN_ERR, "Error writing "
2483 						"auth tok signature packet\n");
2484 				goto out_free;
2485 			}
2486 			(*len) += written;
2487 		} else if (auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
2488 			rc = write_tag_1_packet(dest_base + (*len), &max,
2489 						auth_tok_key, auth_tok,
2490 						crypt_stat, key_rec, &written);
2491 			if (rc) {
2492 				ecryptfs_printk(KERN_WARNING, "Error "
2493 						"writing tag 1 packet\n");
2494 				goto out_free;
2495 			}
2496 			(*len) += written;
2497 		} else {
2498 			up_write(&(auth_tok_key->sem));
2499 			key_put(auth_tok_key);
2500 			ecryptfs_printk(KERN_WARNING, "Unsupported "
2501 					"authentication token type\n");
2502 			rc = -EINVAL;
2503 			goto out_free;
2504 		}
2505 	}
2506 	if (likely(max > 0)) {
2507 		dest_base[(*len)] = 0x00;
2508 	} else {
2509 		ecryptfs_printk(KERN_ERR, "Error writing boundary byte\n");
2510 		rc = -EIO;
2511 	}
2512 out_free:
2513 	kmem_cache_free(ecryptfs_key_record_cache, key_rec);
2514 out:
2515 	if (rc)
2516 		(*len) = 0;
2517 	mutex_unlock(&crypt_stat->keysig_list_mutex);
2518 	return rc;
2519 }
2520 
2521 struct kmem_cache *ecryptfs_key_sig_cache;
2522 
2523 int ecryptfs_add_keysig(struct ecryptfs_crypt_stat *crypt_stat, char *sig)
2524 {
2525 	struct ecryptfs_key_sig *new_key_sig;
2526 
2527 	new_key_sig = kmem_cache_alloc(ecryptfs_key_sig_cache, GFP_KERNEL);
2528 	if (!new_key_sig) {
2529 		printk(KERN_ERR
2530 		       "Error allocating from ecryptfs_key_sig_cache\n");
2531 		return -ENOMEM;
2532 	}
2533 	memcpy(new_key_sig->keysig, sig, ECRYPTFS_SIG_SIZE_HEX);
2534 	new_key_sig->keysig[ECRYPTFS_SIG_SIZE_HEX] = '\0';
2535 	/* Caller must hold keysig_list_mutex */
2536 	list_add(&new_key_sig->crypt_stat_list, &crypt_stat->keysig_list);
2537 
2538 	return 0;
2539 }
2540 
2541 struct kmem_cache *ecryptfs_global_auth_tok_cache;
2542 
2543 int
2544 ecryptfs_add_global_auth_tok(struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
2545 			     char *sig, u32 global_auth_tok_flags)
2546 {
2547 	struct ecryptfs_global_auth_tok *new_auth_tok;
2548 	int rc = 0;
2549 
2550 	new_auth_tok = kmem_cache_zalloc(ecryptfs_global_auth_tok_cache,
2551 					GFP_KERNEL);
2552 	if (!new_auth_tok) {
2553 		rc = -ENOMEM;
2554 		printk(KERN_ERR "Error allocating from "
2555 		       "ecryptfs_global_auth_tok_cache\n");
2556 		goto out;
2557 	}
2558 	memcpy(new_auth_tok->sig, sig, ECRYPTFS_SIG_SIZE_HEX);
2559 	new_auth_tok->flags = global_auth_tok_flags;
2560 	new_auth_tok->sig[ECRYPTFS_SIG_SIZE_HEX] = '\0';
2561 	mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
2562 	list_add(&new_auth_tok->mount_crypt_stat_list,
2563 		 &mount_crypt_stat->global_auth_tok_list);
2564 	mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
2565 out:
2566 	return rc;
2567 }
2568 
2569