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