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