1 /*
2  * Copyright (C) 2010 IBM Corporation
3  * Copyright (C) 2010 Politecnico di Torino, Italy
4  *                    TORSEC group -- http://security.polito.it
5  *
6  * Authors:
7  * Mimi Zohar <zohar@us.ibm.com>
8  * Roberto Sassu <roberto.sassu@polito.it>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, version 2 of the License.
13  *
14  * See Documentation/security/keys/trusted-encrypted.rst
15  */
16 
17 #include <linux/uaccess.h>
18 #include <linux/module.h>
19 #include <linux/init.h>
20 #include <linux/slab.h>
21 #include <linux/parser.h>
22 #include <linux/string.h>
23 #include <linux/err.h>
24 #include <keys/user-type.h>
25 #include <keys/trusted-type.h>
26 #include <keys/encrypted-type.h>
27 #include <linux/key-type.h>
28 #include <linux/random.h>
29 #include <linux/rcupdate.h>
30 #include <linux/scatterlist.h>
31 #include <linux/ctype.h>
32 #include <crypto/aes.h>
33 #include <crypto/algapi.h>
34 #include <crypto/hash.h>
35 #include <crypto/sha.h>
36 #include <crypto/skcipher.h>
37 
38 #include "encrypted.h"
39 #include "ecryptfs_format.h"
40 
41 static const char KEY_TRUSTED_PREFIX[] = "trusted:";
42 static const char KEY_USER_PREFIX[] = "user:";
43 static const char hash_alg[] = "sha256";
44 static const char hmac_alg[] = "hmac(sha256)";
45 static const char blkcipher_alg[] = "cbc(aes)";
46 static const char key_format_default[] = "default";
47 static const char key_format_ecryptfs[] = "ecryptfs";
48 static const char key_format_enc32[] = "enc32";
49 static unsigned int ivsize;
50 static int blksize;
51 
52 #define KEY_TRUSTED_PREFIX_LEN (sizeof (KEY_TRUSTED_PREFIX) - 1)
53 #define KEY_USER_PREFIX_LEN (sizeof (KEY_USER_PREFIX) - 1)
54 #define KEY_ECRYPTFS_DESC_LEN 16
55 #define HASH_SIZE SHA256_DIGEST_SIZE
56 #define MAX_DATA_SIZE 4096
57 #define MIN_DATA_SIZE  20
58 #define KEY_ENC32_PAYLOAD_LEN 32
59 
60 static struct crypto_shash *hash_tfm;
61 
62 enum {
63 	Opt_new, Opt_load, Opt_update, Opt_err
64 };
65 
66 enum {
67 	Opt_default, Opt_ecryptfs, Opt_enc32, Opt_error
68 };
69 
70 static const match_table_t key_format_tokens = {
71 	{Opt_default, "default"},
72 	{Opt_ecryptfs, "ecryptfs"},
73 	{Opt_enc32, "enc32"},
74 	{Opt_error, NULL}
75 };
76 
77 static const match_table_t key_tokens = {
78 	{Opt_new, "new"},
79 	{Opt_load, "load"},
80 	{Opt_update, "update"},
81 	{Opt_err, NULL}
82 };
83 
84 static int aes_get_sizes(void)
85 {
86 	struct crypto_skcipher *tfm;
87 
88 	tfm = crypto_alloc_skcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC);
89 	if (IS_ERR(tfm)) {
90 		pr_err("encrypted_key: failed to alloc_cipher (%ld)\n",
91 		       PTR_ERR(tfm));
92 		return PTR_ERR(tfm);
93 	}
94 	ivsize = crypto_skcipher_ivsize(tfm);
95 	blksize = crypto_skcipher_blocksize(tfm);
96 	crypto_free_skcipher(tfm);
97 	return 0;
98 }
99 
100 /*
101  * valid_ecryptfs_desc - verify the description of a new/loaded encrypted key
102  *
103  * The description of a encrypted key with format 'ecryptfs' must contain
104  * exactly 16 hexadecimal characters.
105  *
106  */
107 static int valid_ecryptfs_desc(const char *ecryptfs_desc)
108 {
109 	int i;
110 
111 	if (strlen(ecryptfs_desc) != KEY_ECRYPTFS_DESC_LEN) {
112 		pr_err("encrypted_key: key description must be %d hexadecimal "
113 		       "characters long\n", KEY_ECRYPTFS_DESC_LEN);
114 		return -EINVAL;
115 	}
116 
117 	for (i = 0; i < KEY_ECRYPTFS_DESC_LEN; i++) {
118 		if (!isxdigit(ecryptfs_desc[i])) {
119 			pr_err("encrypted_key: key description must contain "
120 			       "only hexadecimal characters\n");
121 			return -EINVAL;
122 		}
123 	}
124 
125 	return 0;
126 }
127 
128 /*
129  * valid_master_desc - verify the 'key-type:desc' of a new/updated master-key
130  *
131  * key-type:= "trusted:" | "user:"
132  * desc:= master-key description
133  *
134  * Verify that 'key-type' is valid and that 'desc' exists. On key update,
135  * only the master key description is permitted to change, not the key-type.
136  * The key-type remains constant.
137  *
138  * On success returns 0, otherwise -EINVAL.
139  */
140 static int valid_master_desc(const char *new_desc, const char *orig_desc)
141 {
142 	int prefix_len;
143 
144 	if (!strncmp(new_desc, KEY_TRUSTED_PREFIX, KEY_TRUSTED_PREFIX_LEN))
145 		prefix_len = KEY_TRUSTED_PREFIX_LEN;
146 	else if (!strncmp(new_desc, KEY_USER_PREFIX, KEY_USER_PREFIX_LEN))
147 		prefix_len = KEY_USER_PREFIX_LEN;
148 	else
149 		return -EINVAL;
150 
151 	if (!new_desc[prefix_len])
152 		return -EINVAL;
153 
154 	if (orig_desc && strncmp(new_desc, orig_desc, prefix_len))
155 		return -EINVAL;
156 
157 	return 0;
158 }
159 
160 /*
161  * datablob_parse - parse the keyctl data
162  *
163  * datablob format:
164  * new [<format>] <master-key name> <decrypted data length>
165  * load [<format>] <master-key name> <decrypted data length>
166  *     <encrypted iv + data>
167  * update <new-master-key name>
168  *
169  * Tokenizes a copy of the keyctl data, returning a pointer to each token,
170  * which is null terminated.
171  *
172  * On success returns 0, otherwise -EINVAL.
173  */
174 static int datablob_parse(char *datablob, const char **format,
175 			  char **master_desc, char **decrypted_datalen,
176 			  char **hex_encoded_iv)
177 {
178 	substring_t args[MAX_OPT_ARGS];
179 	int ret = -EINVAL;
180 	int key_cmd;
181 	int key_format;
182 	char *p, *keyword;
183 
184 	keyword = strsep(&datablob, " \t");
185 	if (!keyword) {
186 		pr_info("encrypted_key: insufficient parameters specified\n");
187 		return ret;
188 	}
189 	key_cmd = match_token(keyword, key_tokens, args);
190 
191 	/* Get optional format: default | ecryptfs */
192 	p = strsep(&datablob, " \t");
193 	if (!p) {
194 		pr_err("encrypted_key: insufficient parameters specified\n");
195 		return ret;
196 	}
197 
198 	key_format = match_token(p, key_format_tokens, args);
199 	switch (key_format) {
200 	case Opt_ecryptfs:
201 	case Opt_enc32:
202 	case Opt_default:
203 		*format = p;
204 		*master_desc = strsep(&datablob, " \t");
205 		break;
206 	case Opt_error:
207 		*master_desc = p;
208 		break;
209 	}
210 
211 	if (!*master_desc) {
212 		pr_info("encrypted_key: master key parameter is missing\n");
213 		goto out;
214 	}
215 
216 	if (valid_master_desc(*master_desc, NULL) < 0) {
217 		pr_info("encrypted_key: master key parameter \'%s\' "
218 			"is invalid\n", *master_desc);
219 		goto out;
220 	}
221 
222 	if (decrypted_datalen) {
223 		*decrypted_datalen = strsep(&datablob, " \t");
224 		if (!*decrypted_datalen) {
225 			pr_info("encrypted_key: keylen parameter is missing\n");
226 			goto out;
227 		}
228 	}
229 
230 	switch (key_cmd) {
231 	case Opt_new:
232 		if (!decrypted_datalen) {
233 			pr_info("encrypted_key: keyword \'%s\' not allowed "
234 				"when called from .update method\n", keyword);
235 			break;
236 		}
237 		ret = 0;
238 		break;
239 	case Opt_load:
240 		if (!decrypted_datalen) {
241 			pr_info("encrypted_key: keyword \'%s\' not allowed "
242 				"when called from .update method\n", keyword);
243 			break;
244 		}
245 		*hex_encoded_iv = strsep(&datablob, " \t");
246 		if (!*hex_encoded_iv) {
247 			pr_info("encrypted_key: hex blob is missing\n");
248 			break;
249 		}
250 		ret = 0;
251 		break;
252 	case Opt_update:
253 		if (decrypted_datalen) {
254 			pr_info("encrypted_key: keyword \'%s\' not allowed "
255 				"when called from .instantiate method\n",
256 				keyword);
257 			break;
258 		}
259 		ret = 0;
260 		break;
261 	case Opt_err:
262 		pr_info("encrypted_key: keyword \'%s\' not recognized\n",
263 			keyword);
264 		break;
265 	}
266 out:
267 	return ret;
268 }
269 
270 /*
271  * datablob_format - format as an ascii string, before copying to userspace
272  */
273 static char *datablob_format(struct encrypted_key_payload *epayload,
274 			     size_t asciiblob_len)
275 {
276 	char *ascii_buf, *bufp;
277 	u8 *iv = epayload->iv;
278 	int len;
279 	int i;
280 
281 	ascii_buf = kmalloc(asciiblob_len + 1, GFP_KERNEL);
282 	if (!ascii_buf)
283 		goto out;
284 
285 	ascii_buf[asciiblob_len] = '\0';
286 
287 	/* copy datablob master_desc and datalen strings */
288 	len = sprintf(ascii_buf, "%s %s %s ", epayload->format,
289 		      epayload->master_desc, epayload->datalen);
290 
291 	/* convert the hex encoded iv, encrypted-data and HMAC to ascii */
292 	bufp = &ascii_buf[len];
293 	for (i = 0; i < (asciiblob_len - len) / 2; i++)
294 		bufp = hex_byte_pack(bufp, iv[i]);
295 out:
296 	return ascii_buf;
297 }
298 
299 /*
300  * request_user_key - request the user key
301  *
302  * Use a user provided key to encrypt/decrypt an encrypted-key.
303  */
304 static struct key *request_user_key(const char *master_desc, const u8 **master_key,
305 				    size_t *master_keylen)
306 {
307 	const struct user_key_payload *upayload;
308 	struct key *ukey;
309 
310 	ukey = request_key(&key_type_user, master_desc, NULL);
311 	if (IS_ERR(ukey))
312 		goto error;
313 
314 	down_read(&ukey->sem);
315 	upayload = user_key_payload_locked(ukey);
316 	if (!upayload) {
317 		/* key was revoked before we acquired its semaphore */
318 		up_read(&ukey->sem);
319 		key_put(ukey);
320 		ukey = ERR_PTR(-EKEYREVOKED);
321 		goto error;
322 	}
323 	*master_key = upayload->data;
324 	*master_keylen = upayload->datalen;
325 error:
326 	return ukey;
327 }
328 
329 static int calc_hash(struct crypto_shash *tfm, u8 *digest,
330 		     const u8 *buf, unsigned int buflen)
331 {
332 	SHASH_DESC_ON_STACK(desc, tfm);
333 	int err;
334 
335 	desc->tfm = tfm;
336 
337 	err = crypto_shash_digest(desc, buf, buflen, digest);
338 	shash_desc_zero(desc);
339 	return err;
340 }
341 
342 static int calc_hmac(u8 *digest, const u8 *key, unsigned int keylen,
343 		     const u8 *buf, unsigned int buflen)
344 {
345 	struct crypto_shash *tfm;
346 	int err;
347 
348 	tfm = crypto_alloc_shash(hmac_alg, 0, 0);
349 	if (IS_ERR(tfm)) {
350 		pr_err("encrypted_key: can't alloc %s transform: %ld\n",
351 		       hmac_alg, PTR_ERR(tfm));
352 		return PTR_ERR(tfm);
353 	}
354 
355 	err = crypto_shash_setkey(tfm, key, keylen);
356 	if (!err)
357 		err = calc_hash(tfm, digest, buf, buflen);
358 	crypto_free_shash(tfm);
359 	return err;
360 }
361 
362 enum derived_key_type { ENC_KEY, AUTH_KEY };
363 
364 /* Derive authentication/encryption key from trusted key */
365 static int get_derived_key(u8 *derived_key, enum derived_key_type key_type,
366 			   const u8 *master_key, size_t master_keylen)
367 {
368 	u8 *derived_buf;
369 	unsigned int derived_buf_len;
370 	int ret;
371 
372 	derived_buf_len = strlen("AUTH_KEY") + 1 + master_keylen;
373 	if (derived_buf_len < HASH_SIZE)
374 		derived_buf_len = HASH_SIZE;
375 
376 	derived_buf = kzalloc(derived_buf_len, GFP_KERNEL);
377 	if (!derived_buf)
378 		return -ENOMEM;
379 
380 	if (key_type)
381 		strcpy(derived_buf, "AUTH_KEY");
382 	else
383 		strcpy(derived_buf, "ENC_KEY");
384 
385 	memcpy(derived_buf + strlen(derived_buf) + 1, master_key,
386 	       master_keylen);
387 	ret = calc_hash(hash_tfm, derived_key, derived_buf, derived_buf_len);
388 	kzfree(derived_buf);
389 	return ret;
390 }
391 
392 static struct skcipher_request *init_skcipher_req(const u8 *key,
393 						  unsigned int key_len)
394 {
395 	struct skcipher_request *req;
396 	struct crypto_skcipher *tfm;
397 	int ret;
398 
399 	tfm = crypto_alloc_skcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC);
400 	if (IS_ERR(tfm)) {
401 		pr_err("encrypted_key: failed to load %s transform (%ld)\n",
402 		       blkcipher_alg, PTR_ERR(tfm));
403 		return ERR_CAST(tfm);
404 	}
405 
406 	ret = crypto_skcipher_setkey(tfm, key, key_len);
407 	if (ret < 0) {
408 		pr_err("encrypted_key: failed to setkey (%d)\n", ret);
409 		crypto_free_skcipher(tfm);
410 		return ERR_PTR(ret);
411 	}
412 
413 	req = skcipher_request_alloc(tfm, GFP_KERNEL);
414 	if (!req) {
415 		pr_err("encrypted_key: failed to allocate request for %s\n",
416 		       blkcipher_alg);
417 		crypto_free_skcipher(tfm);
418 		return ERR_PTR(-ENOMEM);
419 	}
420 
421 	skcipher_request_set_callback(req, 0, NULL, NULL);
422 	return req;
423 }
424 
425 static struct key *request_master_key(struct encrypted_key_payload *epayload,
426 				      const u8 **master_key, size_t *master_keylen)
427 {
428 	struct key *mkey = ERR_PTR(-EINVAL);
429 
430 	if (!strncmp(epayload->master_desc, KEY_TRUSTED_PREFIX,
431 		     KEY_TRUSTED_PREFIX_LEN)) {
432 		mkey = request_trusted_key(epayload->master_desc +
433 					   KEY_TRUSTED_PREFIX_LEN,
434 					   master_key, master_keylen);
435 	} else if (!strncmp(epayload->master_desc, KEY_USER_PREFIX,
436 			    KEY_USER_PREFIX_LEN)) {
437 		mkey = request_user_key(epayload->master_desc +
438 					KEY_USER_PREFIX_LEN,
439 					master_key, master_keylen);
440 	} else
441 		goto out;
442 
443 	if (IS_ERR(mkey)) {
444 		int ret = PTR_ERR(mkey);
445 
446 		if (ret == -ENOTSUPP)
447 			pr_info("encrypted_key: key %s not supported",
448 				epayload->master_desc);
449 		else
450 			pr_info("encrypted_key: key %s not found",
451 				epayload->master_desc);
452 		goto out;
453 	}
454 
455 	dump_master_key(*master_key, *master_keylen);
456 out:
457 	return mkey;
458 }
459 
460 /* Before returning data to userspace, encrypt decrypted data. */
461 static int derived_key_encrypt(struct encrypted_key_payload *epayload,
462 			       const u8 *derived_key,
463 			       unsigned int derived_keylen)
464 {
465 	struct scatterlist sg_in[2];
466 	struct scatterlist sg_out[1];
467 	struct crypto_skcipher *tfm;
468 	struct skcipher_request *req;
469 	unsigned int encrypted_datalen;
470 	u8 iv[AES_BLOCK_SIZE];
471 	int ret;
472 
473 	encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
474 
475 	req = init_skcipher_req(derived_key, derived_keylen);
476 	ret = PTR_ERR(req);
477 	if (IS_ERR(req))
478 		goto out;
479 	dump_decrypted_data(epayload);
480 
481 	sg_init_table(sg_in, 2);
482 	sg_set_buf(&sg_in[0], epayload->decrypted_data,
483 		   epayload->decrypted_datalen);
484 	sg_set_page(&sg_in[1], ZERO_PAGE(0), AES_BLOCK_SIZE, 0);
485 
486 	sg_init_table(sg_out, 1);
487 	sg_set_buf(sg_out, epayload->encrypted_data, encrypted_datalen);
488 
489 	memcpy(iv, epayload->iv, sizeof(iv));
490 	skcipher_request_set_crypt(req, sg_in, sg_out, encrypted_datalen, iv);
491 	ret = crypto_skcipher_encrypt(req);
492 	tfm = crypto_skcipher_reqtfm(req);
493 	skcipher_request_free(req);
494 	crypto_free_skcipher(tfm);
495 	if (ret < 0)
496 		pr_err("encrypted_key: failed to encrypt (%d)\n", ret);
497 	else
498 		dump_encrypted_data(epayload, encrypted_datalen);
499 out:
500 	return ret;
501 }
502 
503 static int datablob_hmac_append(struct encrypted_key_payload *epayload,
504 				const u8 *master_key, size_t master_keylen)
505 {
506 	u8 derived_key[HASH_SIZE];
507 	u8 *digest;
508 	int ret;
509 
510 	ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen);
511 	if (ret < 0)
512 		goto out;
513 
514 	digest = epayload->format + epayload->datablob_len;
515 	ret = calc_hmac(digest, derived_key, sizeof derived_key,
516 			epayload->format, epayload->datablob_len);
517 	if (!ret)
518 		dump_hmac(NULL, digest, HASH_SIZE);
519 out:
520 	memzero_explicit(derived_key, sizeof(derived_key));
521 	return ret;
522 }
523 
524 /* verify HMAC before decrypting encrypted key */
525 static int datablob_hmac_verify(struct encrypted_key_payload *epayload,
526 				const u8 *format, const u8 *master_key,
527 				size_t master_keylen)
528 {
529 	u8 derived_key[HASH_SIZE];
530 	u8 digest[HASH_SIZE];
531 	int ret;
532 	char *p;
533 	unsigned short len;
534 
535 	ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen);
536 	if (ret < 0)
537 		goto out;
538 
539 	len = epayload->datablob_len;
540 	if (!format) {
541 		p = epayload->master_desc;
542 		len -= strlen(epayload->format) + 1;
543 	} else
544 		p = epayload->format;
545 
546 	ret = calc_hmac(digest, derived_key, sizeof derived_key, p, len);
547 	if (ret < 0)
548 		goto out;
549 	ret = crypto_memneq(digest, epayload->format + epayload->datablob_len,
550 			    sizeof(digest));
551 	if (ret) {
552 		ret = -EINVAL;
553 		dump_hmac("datablob",
554 			  epayload->format + epayload->datablob_len,
555 			  HASH_SIZE);
556 		dump_hmac("calc", digest, HASH_SIZE);
557 	}
558 out:
559 	memzero_explicit(derived_key, sizeof(derived_key));
560 	return ret;
561 }
562 
563 static int derived_key_decrypt(struct encrypted_key_payload *epayload,
564 			       const u8 *derived_key,
565 			       unsigned int derived_keylen)
566 {
567 	struct scatterlist sg_in[1];
568 	struct scatterlist sg_out[2];
569 	struct crypto_skcipher *tfm;
570 	struct skcipher_request *req;
571 	unsigned int encrypted_datalen;
572 	u8 iv[AES_BLOCK_SIZE];
573 	u8 *pad;
574 	int ret;
575 
576 	/* Throwaway buffer to hold the unused zero padding at the end */
577 	pad = kmalloc(AES_BLOCK_SIZE, GFP_KERNEL);
578 	if (!pad)
579 		return -ENOMEM;
580 
581 	encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
582 	req = init_skcipher_req(derived_key, derived_keylen);
583 	ret = PTR_ERR(req);
584 	if (IS_ERR(req))
585 		goto out;
586 	dump_encrypted_data(epayload, encrypted_datalen);
587 
588 	sg_init_table(sg_in, 1);
589 	sg_init_table(sg_out, 2);
590 	sg_set_buf(sg_in, epayload->encrypted_data, encrypted_datalen);
591 	sg_set_buf(&sg_out[0], epayload->decrypted_data,
592 		   epayload->decrypted_datalen);
593 	sg_set_buf(&sg_out[1], pad, AES_BLOCK_SIZE);
594 
595 	memcpy(iv, epayload->iv, sizeof(iv));
596 	skcipher_request_set_crypt(req, sg_in, sg_out, encrypted_datalen, iv);
597 	ret = crypto_skcipher_decrypt(req);
598 	tfm = crypto_skcipher_reqtfm(req);
599 	skcipher_request_free(req);
600 	crypto_free_skcipher(tfm);
601 	if (ret < 0)
602 		goto out;
603 	dump_decrypted_data(epayload);
604 out:
605 	kfree(pad);
606 	return ret;
607 }
608 
609 /* Allocate memory for decrypted key and datablob. */
610 static struct encrypted_key_payload *encrypted_key_alloc(struct key *key,
611 							 const char *format,
612 							 const char *master_desc,
613 							 const char *datalen)
614 {
615 	struct encrypted_key_payload *epayload = NULL;
616 	unsigned short datablob_len;
617 	unsigned short decrypted_datalen;
618 	unsigned short payload_datalen;
619 	unsigned int encrypted_datalen;
620 	unsigned int format_len;
621 	long dlen;
622 	int ret;
623 
624 	ret = kstrtol(datalen, 10, &dlen);
625 	if (ret < 0 || dlen < MIN_DATA_SIZE || dlen > MAX_DATA_SIZE)
626 		return ERR_PTR(-EINVAL);
627 
628 	format_len = (!format) ? strlen(key_format_default) : strlen(format);
629 	decrypted_datalen = dlen;
630 	payload_datalen = decrypted_datalen;
631 	if (format) {
632 		if (!strcmp(format, key_format_ecryptfs)) {
633 			if (dlen != ECRYPTFS_MAX_KEY_BYTES) {
634 				pr_err("encrypted_key: keylen for the ecryptfs format must be equal to %d bytes\n",
635 					ECRYPTFS_MAX_KEY_BYTES);
636 				return ERR_PTR(-EINVAL);
637 			}
638 			decrypted_datalen = ECRYPTFS_MAX_KEY_BYTES;
639 			payload_datalen = sizeof(struct ecryptfs_auth_tok);
640 		} else if (!strcmp(format, key_format_enc32)) {
641 			if (decrypted_datalen != KEY_ENC32_PAYLOAD_LEN) {
642 				pr_err("encrypted_key: enc32 key payload incorrect length: %d\n",
643 						decrypted_datalen);
644 				return ERR_PTR(-EINVAL);
645 			}
646 		}
647 	}
648 
649 	encrypted_datalen = roundup(decrypted_datalen, blksize);
650 
651 	datablob_len = format_len + 1 + strlen(master_desc) + 1
652 	    + strlen(datalen) + 1 + ivsize + 1 + encrypted_datalen;
653 
654 	ret = key_payload_reserve(key, payload_datalen + datablob_len
655 				  + HASH_SIZE + 1);
656 	if (ret < 0)
657 		return ERR_PTR(ret);
658 
659 	epayload = kzalloc(sizeof(*epayload) + payload_datalen +
660 			   datablob_len + HASH_SIZE + 1, GFP_KERNEL);
661 	if (!epayload)
662 		return ERR_PTR(-ENOMEM);
663 
664 	epayload->payload_datalen = payload_datalen;
665 	epayload->decrypted_datalen = decrypted_datalen;
666 	epayload->datablob_len = datablob_len;
667 	return epayload;
668 }
669 
670 static int encrypted_key_decrypt(struct encrypted_key_payload *epayload,
671 				 const char *format, const char *hex_encoded_iv)
672 {
673 	struct key *mkey;
674 	u8 derived_key[HASH_SIZE];
675 	const u8 *master_key;
676 	u8 *hmac;
677 	const char *hex_encoded_data;
678 	unsigned int encrypted_datalen;
679 	size_t master_keylen;
680 	size_t asciilen;
681 	int ret;
682 
683 	encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
684 	asciilen = (ivsize + 1 + encrypted_datalen + HASH_SIZE) * 2;
685 	if (strlen(hex_encoded_iv) != asciilen)
686 		return -EINVAL;
687 
688 	hex_encoded_data = hex_encoded_iv + (2 * ivsize) + 2;
689 	ret = hex2bin(epayload->iv, hex_encoded_iv, ivsize);
690 	if (ret < 0)
691 		return -EINVAL;
692 	ret = hex2bin(epayload->encrypted_data, hex_encoded_data,
693 		      encrypted_datalen);
694 	if (ret < 0)
695 		return -EINVAL;
696 
697 	hmac = epayload->format + epayload->datablob_len;
698 	ret = hex2bin(hmac, hex_encoded_data + (encrypted_datalen * 2),
699 		      HASH_SIZE);
700 	if (ret < 0)
701 		return -EINVAL;
702 
703 	mkey = request_master_key(epayload, &master_key, &master_keylen);
704 	if (IS_ERR(mkey))
705 		return PTR_ERR(mkey);
706 
707 	ret = datablob_hmac_verify(epayload, format, master_key, master_keylen);
708 	if (ret < 0) {
709 		pr_err("encrypted_key: bad hmac (%d)\n", ret);
710 		goto out;
711 	}
712 
713 	ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen);
714 	if (ret < 0)
715 		goto out;
716 
717 	ret = derived_key_decrypt(epayload, derived_key, sizeof derived_key);
718 	if (ret < 0)
719 		pr_err("encrypted_key: failed to decrypt key (%d)\n", ret);
720 out:
721 	up_read(&mkey->sem);
722 	key_put(mkey);
723 	memzero_explicit(derived_key, sizeof(derived_key));
724 	return ret;
725 }
726 
727 static void __ekey_init(struct encrypted_key_payload *epayload,
728 			const char *format, const char *master_desc,
729 			const char *datalen)
730 {
731 	unsigned int format_len;
732 
733 	format_len = (!format) ? strlen(key_format_default) : strlen(format);
734 	epayload->format = epayload->payload_data + epayload->payload_datalen;
735 	epayload->master_desc = epayload->format + format_len + 1;
736 	epayload->datalen = epayload->master_desc + strlen(master_desc) + 1;
737 	epayload->iv = epayload->datalen + strlen(datalen) + 1;
738 	epayload->encrypted_data = epayload->iv + ivsize + 1;
739 	epayload->decrypted_data = epayload->payload_data;
740 
741 	if (!format)
742 		memcpy(epayload->format, key_format_default, format_len);
743 	else {
744 		if (!strcmp(format, key_format_ecryptfs))
745 			epayload->decrypted_data =
746 				ecryptfs_get_auth_tok_key((struct ecryptfs_auth_tok *)epayload->payload_data);
747 
748 		memcpy(epayload->format, format, format_len);
749 	}
750 
751 	memcpy(epayload->master_desc, master_desc, strlen(master_desc));
752 	memcpy(epayload->datalen, datalen, strlen(datalen));
753 }
754 
755 /*
756  * encrypted_init - initialize an encrypted key
757  *
758  * For a new key, use a random number for both the iv and data
759  * itself.  For an old key, decrypt the hex encoded data.
760  */
761 static int encrypted_init(struct encrypted_key_payload *epayload,
762 			  const char *key_desc, const char *format,
763 			  const char *master_desc, const char *datalen,
764 			  const char *hex_encoded_iv)
765 {
766 	int ret = 0;
767 
768 	if (format && !strcmp(format, key_format_ecryptfs)) {
769 		ret = valid_ecryptfs_desc(key_desc);
770 		if (ret < 0)
771 			return ret;
772 
773 		ecryptfs_fill_auth_tok((struct ecryptfs_auth_tok *)epayload->payload_data,
774 				       key_desc);
775 	}
776 
777 	__ekey_init(epayload, format, master_desc, datalen);
778 	if (!hex_encoded_iv) {
779 		get_random_bytes(epayload->iv, ivsize);
780 
781 		get_random_bytes(epayload->decrypted_data,
782 				 epayload->decrypted_datalen);
783 	} else
784 		ret = encrypted_key_decrypt(epayload, format, hex_encoded_iv);
785 	return ret;
786 }
787 
788 /*
789  * encrypted_instantiate - instantiate an encrypted key
790  *
791  * Decrypt an existing encrypted datablob or create a new encrypted key
792  * based on a kernel random number.
793  *
794  * On success, return 0. Otherwise return errno.
795  */
796 static int encrypted_instantiate(struct key *key,
797 				 struct key_preparsed_payload *prep)
798 {
799 	struct encrypted_key_payload *epayload = NULL;
800 	char *datablob = NULL;
801 	const char *format = NULL;
802 	char *master_desc = NULL;
803 	char *decrypted_datalen = NULL;
804 	char *hex_encoded_iv = NULL;
805 	size_t datalen = prep->datalen;
806 	int ret;
807 
808 	if (datalen <= 0 || datalen > 32767 || !prep->data)
809 		return -EINVAL;
810 
811 	datablob = kmalloc(datalen + 1, GFP_KERNEL);
812 	if (!datablob)
813 		return -ENOMEM;
814 	datablob[datalen] = 0;
815 	memcpy(datablob, prep->data, datalen);
816 	ret = datablob_parse(datablob, &format, &master_desc,
817 			     &decrypted_datalen, &hex_encoded_iv);
818 	if (ret < 0)
819 		goto out;
820 
821 	epayload = encrypted_key_alloc(key, format, master_desc,
822 				       decrypted_datalen);
823 	if (IS_ERR(epayload)) {
824 		ret = PTR_ERR(epayload);
825 		goto out;
826 	}
827 	ret = encrypted_init(epayload, key->description, format, master_desc,
828 			     decrypted_datalen, hex_encoded_iv);
829 	if (ret < 0) {
830 		kzfree(epayload);
831 		goto out;
832 	}
833 
834 	rcu_assign_keypointer(key, epayload);
835 out:
836 	kzfree(datablob);
837 	return ret;
838 }
839 
840 static void encrypted_rcu_free(struct rcu_head *rcu)
841 {
842 	struct encrypted_key_payload *epayload;
843 
844 	epayload = container_of(rcu, struct encrypted_key_payload, rcu);
845 	kzfree(epayload);
846 }
847 
848 /*
849  * encrypted_update - update the master key description
850  *
851  * Change the master key description for an existing encrypted key.
852  * The next read will return an encrypted datablob using the new
853  * master key description.
854  *
855  * On success, return 0. Otherwise return errno.
856  */
857 static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)
858 {
859 	struct encrypted_key_payload *epayload = key->payload.data[0];
860 	struct encrypted_key_payload *new_epayload;
861 	char *buf;
862 	char *new_master_desc = NULL;
863 	const char *format = NULL;
864 	size_t datalen = prep->datalen;
865 	int ret = 0;
866 
867 	if (key_is_negative(key))
868 		return -ENOKEY;
869 	if (datalen <= 0 || datalen > 32767 || !prep->data)
870 		return -EINVAL;
871 
872 	buf = kmalloc(datalen + 1, GFP_KERNEL);
873 	if (!buf)
874 		return -ENOMEM;
875 
876 	buf[datalen] = 0;
877 	memcpy(buf, prep->data, datalen);
878 	ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);
879 	if (ret < 0)
880 		goto out;
881 
882 	ret = valid_master_desc(new_master_desc, epayload->master_desc);
883 	if (ret < 0)
884 		goto out;
885 
886 	new_epayload = encrypted_key_alloc(key, epayload->format,
887 					   new_master_desc, epayload->datalen);
888 	if (IS_ERR(new_epayload)) {
889 		ret = PTR_ERR(new_epayload);
890 		goto out;
891 	}
892 
893 	__ekey_init(new_epayload, epayload->format, new_master_desc,
894 		    epayload->datalen);
895 
896 	memcpy(new_epayload->iv, epayload->iv, ivsize);
897 	memcpy(new_epayload->payload_data, epayload->payload_data,
898 	       epayload->payload_datalen);
899 
900 	rcu_assign_keypointer(key, new_epayload);
901 	call_rcu(&epayload->rcu, encrypted_rcu_free);
902 out:
903 	kzfree(buf);
904 	return ret;
905 }
906 
907 /*
908  * encrypted_read - format and copy the encrypted data to userspace
909  *
910  * The resulting datablob format is:
911  * <master-key name> <decrypted data length> <encrypted iv> <encrypted data>
912  *
913  * On success, return to userspace the encrypted key datablob size.
914  */
915 static long encrypted_read(const struct key *key, char __user *buffer,
916 			   size_t buflen)
917 {
918 	struct encrypted_key_payload *epayload;
919 	struct key *mkey;
920 	const u8 *master_key;
921 	size_t master_keylen;
922 	char derived_key[HASH_SIZE];
923 	char *ascii_buf;
924 	size_t asciiblob_len;
925 	int ret;
926 
927 	epayload = dereference_key_locked(key);
928 
929 	/* returns the hex encoded iv, encrypted-data, and hmac as ascii */
930 	asciiblob_len = epayload->datablob_len + ivsize + 1
931 	    + roundup(epayload->decrypted_datalen, blksize)
932 	    + (HASH_SIZE * 2);
933 
934 	if (!buffer || buflen < asciiblob_len)
935 		return asciiblob_len;
936 
937 	mkey = request_master_key(epayload, &master_key, &master_keylen);
938 	if (IS_ERR(mkey))
939 		return PTR_ERR(mkey);
940 
941 	ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen);
942 	if (ret < 0)
943 		goto out;
944 
945 	ret = derived_key_encrypt(epayload, derived_key, sizeof derived_key);
946 	if (ret < 0)
947 		goto out;
948 
949 	ret = datablob_hmac_append(epayload, master_key, master_keylen);
950 	if (ret < 0)
951 		goto out;
952 
953 	ascii_buf = datablob_format(epayload, asciiblob_len);
954 	if (!ascii_buf) {
955 		ret = -ENOMEM;
956 		goto out;
957 	}
958 
959 	up_read(&mkey->sem);
960 	key_put(mkey);
961 	memzero_explicit(derived_key, sizeof(derived_key));
962 
963 	if (copy_to_user(buffer, ascii_buf, asciiblob_len) != 0)
964 		ret = -EFAULT;
965 	kzfree(ascii_buf);
966 
967 	return asciiblob_len;
968 out:
969 	up_read(&mkey->sem);
970 	key_put(mkey);
971 	memzero_explicit(derived_key, sizeof(derived_key));
972 	return ret;
973 }
974 
975 /*
976  * encrypted_destroy - clear and free the key's payload
977  */
978 static void encrypted_destroy(struct key *key)
979 {
980 	kzfree(key->payload.data[0]);
981 }
982 
983 struct key_type key_type_encrypted = {
984 	.name = "encrypted",
985 	.instantiate = encrypted_instantiate,
986 	.update = encrypted_update,
987 	.destroy = encrypted_destroy,
988 	.describe = user_describe,
989 	.read = encrypted_read,
990 };
991 EXPORT_SYMBOL_GPL(key_type_encrypted);
992 
993 static int __init init_encrypted(void)
994 {
995 	int ret;
996 
997 	hash_tfm = crypto_alloc_shash(hash_alg, 0, 0);
998 	if (IS_ERR(hash_tfm)) {
999 		pr_err("encrypted_key: can't allocate %s transform: %ld\n",
1000 		       hash_alg, PTR_ERR(hash_tfm));
1001 		return PTR_ERR(hash_tfm);
1002 	}
1003 
1004 	ret = aes_get_sizes();
1005 	if (ret < 0)
1006 		goto out;
1007 	ret = register_key_type(&key_type_encrypted);
1008 	if (ret < 0)
1009 		goto out;
1010 	return 0;
1011 out:
1012 	crypto_free_shash(hash_tfm);
1013 	return ret;
1014 
1015 }
1016 
1017 static void __exit cleanup_encrypted(void)
1018 {
1019 	crypto_free_shash(hash_tfm);
1020 	unregister_key_type(&key_type_encrypted);
1021 }
1022 
1023 late_initcall(init_encrypted);
1024 module_exit(cleanup_encrypted);
1025 
1026 MODULE_LICENSE("GPL");
1027