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