Merge branch 'master' of git://blackhole.kfki.hu/nf-next
[linux-2.6-microblaze.git] / security / keys / trusted.c
1 /*
2  * Copyright (C) 2010 IBM Corporation
3  *
4  * Author:
5  * David Safford <safford@us.ibm.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, version 2 of the License.
10  *
11  * See Documentation/security/keys/trusted-encrypted.rst
12  */
13
14 #include <crypto/hash_info.h>
15 #include <linux/uaccess.h>
16 #include <linux/module.h>
17 #include <linux/init.h>
18 #include <linux/slab.h>
19 #include <linux/parser.h>
20 #include <linux/string.h>
21 #include <linux/err.h>
22 #include <keys/user-type.h>
23 #include <keys/trusted-type.h>
24 #include <linux/key-type.h>
25 #include <linux/rcupdate.h>
26 #include <linux/crypto.h>
27 #include <crypto/hash.h>
28 #include <crypto/sha.h>
29 #include <linux/capability.h>
30 #include <linux/tpm.h>
31 #include <linux/tpm_command.h>
32
33 #include <keys/trusted.h>
34
35 static const char hmac_alg[] = "hmac(sha1)";
36 static const char hash_alg[] = "sha1";
37
38 struct sdesc {
39         struct shash_desc shash;
40         char ctx[];
41 };
42
43 static struct crypto_shash *hashalg;
44 static struct crypto_shash *hmacalg;
45
46 static struct sdesc *init_sdesc(struct crypto_shash *alg)
47 {
48         struct sdesc *sdesc;
49         int size;
50
51         size = sizeof(struct shash_desc) + crypto_shash_descsize(alg);
52         sdesc = kmalloc(size, GFP_KERNEL);
53         if (!sdesc)
54                 return ERR_PTR(-ENOMEM);
55         sdesc->shash.tfm = alg;
56         sdesc->shash.flags = 0x0;
57         return sdesc;
58 }
59
60 static int TSS_sha1(const unsigned char *data, unsigned int datalen,
61                     unsigned char *digest)
62 {
63         struct sdesc *sdesc;
64         int ret;
65
66         sdesc = init_sdesc(hashalg);
67         if (IS_ERR(sdesc)) {
68                 pr_info("trusted_key: can't alloc %s\n", hash_alg);
69                 return PTR_ERR(sdesc);
70         }
71
72         ret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);
73         kzfree(sdesc);
74         return ret;
75 }
76
77 static int TSS_rawhmac(unsigned char *digest, const unsigned char *key,
78                        unsigned int keylen, ...)
79 {
80         struct sdesc *sdesc;
81         va_list argp;
82         unsigned int dlen;
83         unsigned char *data;
84         int ret;
85
86         sdesc = init_sdesc(hmacalg);
87         if (IS_ERR(sdesc)) {
88                 pr_info("trusted_key: can't alloc %s\n", hmac_alg);
89                 return PTR_ERR(sdesc);
90         }
91
92         ret = crypto_shash_setkey(hmacalg, key, keylen);
93         if (ret < 0)
94                 goto out;
95         ret = crypto_shash_init(&sdesc->shash);
96         if (ret < 0)
97                 goto out;
98
99         va_start(argp, keylen);
100         for (;;) {
101                 dlen = va_arg(argp, unsigned int);
102                 if (dlen == 0)
103                         break;
104                 data = va_arg(argp, unsigned char *);
105                 if (data == NULL) {
106                         ret = -EINVAL;
107                         break;
108                 }
109                 ret = crypto_shash_update(&sdesc->shash, data, dlen);
110                 if (ret < 0)
111                         break;
112         }
113         va_end(argp);
114         if (!ret)
115                 ret = crypto_shash_final(&sdesc->shash, digest);
116 out:
117         kzfree(sdesc);
118         return ret;
119 }
120
121 /*
122  * calculate authorization info fields to send to TPM
123  */
124 int TSS_authhmac(unsigned char *digest, const unsigned char *key,
125                         unsigned int keylen, unsigned char *h1,
126                         unsigned char *h2, unsigned char h3, ...)
127 {
128         unsigned char paramdigest[SHA1_DIGEST_SIZE];
129         struct sdesc *sdesc;
130         unsigned int dlen;
131         unsigned char *data;
132         unsigned char c;
133         int ret;
134         va_list argp;
135
136         sdesc = init_sdesc(hashalg);
137         if (IS_ERR(sdesc)) {
138                 pr_info("trusted_key: can't alloc %s\n", hash_alg);
139                 return PTR_ERR(sdesc);
140         }
141
142         c = h3;
143         ret = crypto_shash_init(&sdesc->shash);
144         if (ret < 0)
145                 goto out;
146         va_start(argp, h3);
147         for (;;) {
148                 dlen = va_arg(argp, unsigned int);
149                 if (dlen == 0)
150                         break;
151                 data = va_arg(argp, unsigned char *);
152                 if (!data) {
153                         ret = -EINVAL;
154                         break;
155                 }
156                 ret = crypto_shash_update(&sdesc->shash, data, dlen);
157                 if (ret < 0)
158                         break;
159         }
160         va_end(argp);
161         if (!ret)
162                 ret = crypto_shash_final(&sdesc->shash, paramdigest);
163         if (!ret)
164                 ret = TSS_rawhmac(digest, key, keylen, SHA1_DIGEST_SIZE,
165                                   paramdigest, TPM_NONCE_SIZE, h1,
166                                   TPM_NONCE_SIZE, h2, 1, &c, 0, 0);
167 out:
168         kzfree(sdesc);
169         return ret;
170 }
171 EXPORT_SYMBOL_GPL(TSS_authhmac);
172
173 /*
174  * verify the AUTH1_COMMAND (Seal) result from TPM
175  */
176 int TSS_checkhmac1(unsigned char *buffer,
177                           const uint32_t command,
178                           const unsigned char *ononce,
179                           const unsigned char *key,
180                           unsigned int keylen, ...)
181 {
182         uint32_t bufsize;
183         uint16_t tag;
184         uint32_t ordinal;
185         uint32_t result;
186         unsigned char *enonce;
187         unsigned char *continueflag;
188         unsigned char *authdata;
189         unsigned char testhmac[SHA1_DIGEST_SIZE];
190         unsigned char paramdigest[SHA1_DIGEST_SIZE];
191         struct sdesc *sdesc;
192         unsigned int dlen;
193         unsigned int dpos;
194         va_list argp;
195         int ret;
196
197         bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
198         tag = LOAD16(buffer, 0);
199         ordinal = command;
200         result = LOAD32N(buffer, TPM_RETURN_OFFSET);
201         if (tag == TPM_TAG_RSP_COMMAND)
202                 return 0;
203         if (tag != TPM_TAG_RSP_AUTH1_COMMAND)
204                 return -EINVAL;
205         authdata = buffer + bufsize - SHA1_DIGEST_SIZE;
206         continueflag = authdata - 1;
207         enonce = continueflag - TPM_NONCE_SIZE;
208
209         sdesc = init_sdesc(hashalg);
210         if (IS_ERR(sdesc)) {
211                 pr_info("trusted_key: can't alloc %s\n", hash_alg);
212                 return PTR_ERR(sdesc);
213         }
214         ret = crypto_shash_init(&sdesc->shash);
215         if (ret < 0)
216                 goto out;
217         ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
218                                   sizeof result);
219         if (ret < 0)
220                 goto out;
221         ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
222                                   sizeof ordinal);
223         if (ret < 0)
224                 goto out;
225         va_start(argp, keylen);
226         for (;;) {
227                 dlen = va_arg(argp, unsigned int);
228                 if (dlen == 0)
229                         break;
230                 dpos = va_arg(argp, unsigned int);
231                 ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
232                 if (ret < 0)
233                         break;
234         }
235         va_end(argp);
236         if (!ret)
237                 ret = crypto_shash_final(&sdesc->shash, paramdigest);
238         if (ret < 0)
239                 goto out;
240
241         ret = TSS_rawhmac(testhmac, key, keylen, SHA1_DIGEST_SIZE, paramdigest,
242                           TPM_NONCE_SIZE, enonce, TPM_NONCE_SIZE, ononce,
243                           1, continueflag, 0, 0);
244         if (ret < 0)
245                 goto out;
246
247         if (memcmp(testhmac, authdata, SHA1_DIGEST_SIZE))
248                 ret = -EINVAL;
249 out:
250         kzfree(sdesc);
251         return ret;
252 }
253 EXPORT_SYMBOL_GPL(TSS_checkhmac1);
254
255 /*
256  * verify the AUTH2_COMMAND (unseal) result from TPM
257  */
258 static int TSS_checkhmac2(unsigned char *buffer,
259                           const uint32_t command,
260                           const unsigned char *ononce,
261                           const unsigned char *key1,
262                           unsigned int keylen1,
263                           const unsigned char *key2,
264                           unsigned int keylen2, ...)
265 {
266         uint32_t bufsize;
267         uint16_t tag;
268         uint32_t ordinal;
269         uint32_t result;
270         unsigned char *enonce1;
271         unsigned char *continueflag1;
272         unsigned char *authdata1;
273         unsigned char *enonce2;
274         unsigned char *continueflag2;
275         unsigned char *authdata2;
276         unsigned char testhmac1[SHA1_DIGEST_SIZE];
277         unsigned char testhmac2[SHA1_DIGEST_SIZE];
278         unsigned char paramdigest[SHA1_DIGEST_SIZE];
279         struct sdesc *sdesc;
280         unsigned int dlen;
281         unsigned int dpos;
282         va_list argp;
283         int ret;
284
285         bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
286         tag = LOAD16(buffer, 0);
287         ordinal = command;
288         result = LOAD32N(buffer, TPM_RETURN_OFFSET);
289
290         if (tag == TPM_TAG_RSP_COMMAND)
291                 return 0;
292         if (tag != TPM_TAG_RSP_AUTH2_COMMAND)
293                 return -EINVAL;
294         authdata1 = buffer + bufsize - (SHA1_DIGEST_SIZE + 1
295                         + SHA1_DIGEST_SIZE + SHA1_DIGEST_SIZE);
296         authdata2 = buffer + bufsize - (SHA1_DIGEST_SIZE);
297         continueflag1 = authdata1 - 1;
298         continueflag2 = authdata2 - 1;
299         enonce1 = continueflag1 - TPM_NONCE_SIZE;
300         enonce2 = continueflag2 - TPM_NONCE_SIZE;
301
302         sdesc = init_sdesc(hashalg);
303         if (IS_ERR(sdesc)) {
304                 pr_info("trusted_key: can't alloc %s\n", hash_alg);
305                 return PTR_ERR(sdesc);
306         }
307         ret = crypto_shash_init(&sdesc->shash);
308         if (ret < 0)
309                 goto out;
310         ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
311                                   sizeof result);
312         if (ret < 0)
313                 goto out;
314         ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
315                                   sizeof ordinal);
316         if (ret < 0)
317                 goto out;
318
319         va_start(argp, keylen2);
320         for (;;) {
321                 dlen = va_arg(argp, unsigned int);
322                 if (dlen == 0)
323                         break;
324                 dpos = va_arg(argp, unsigned int);
325                 ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
326                 if (ret < 0)
327                         break;
328         }
329         va_end(argp);
330         if (!ret)
331                 ret = crypto_shash_final(&sdesc->shash, paramdigest);
332         if (ret < 0)
333                 goto out;
334
335         ret = TSS_rawhmac(testhmac1, key1, keylen1, SHA1_DIGEST_SIZE,
336                           paramdigest, TPM_NONCE_SIZE, enonce1,
337                           TPM_NONCE_SIZE, ononce, 1, continueflag1, 0, 0);
338         if (ret < 0)
339                 goto out;
340         if (memcmp(testhmac1, authdata1, SHA1_DIGEST_SIZE)) {
341                 ret = -EINVAL;
342                 goto out;
343         }
344         ret = TSS_rawhmac(testhmac2, key2, keylen2, SHA1_DIGEST_SIZE,
345                           paramdigest, TPM_NONCE_SIZE, enonce2,
346                           TPM_NONCE_SIZE, ononce, 1, continueflag2, 0, 0);
347         if (ret < 0)
348                 goto out;
349         if (memcmp(testhmac2, authdata2, SHA1_DIGEST_SIZE))
350                 ret = -EINVAL;
351 out:
352         kzfree(sdesc);
353         return ret;
354 }
355
356 /*
357  * For key specific tpm requests, we will generate and send our
358  * own TPM command packets using the drivers send function.
359  */
360 int trusted_tpm_send(unsigned char *cmd, size_t buflen)
361 {
362         int rc;
363
364         dump_tpm_buf(cmd);
365         rc = tpm_send(NULL, cmd, buflen);
366         dump_tpm_buf(cmd);
367         if (rc > 0)
368                 /* Can't return positive return codes values to keyctl */
369                 rc = -EPERM;
370         return rc;
371 }
372 EXPORT_SYMBOL_GPL(trusted_tpm_send);
373
374 /*
375  * Lock a trusted key, by extending a selected PCR.
376  *
377  * Prevents a trusted key that is sealed to PCRs from being accessed.
378  * This uses the tpm driver's extend function.
379  */
380 static int pcrlock(const int pcrnum)
381 {
382         unsigned char hash[SHA1_DIGEST_SIZE];
383         int ret;
384
385         if (!capable(CAP_SYS_ADMIN))
386                 return -EPERM;
387         ret = tpm_get_random(NULL, hash, SHA1_DIGEST_SIZE);
388         if (ret != SHA1_DIGEST_SIZE)
389                 return ret;
390         return tpm_pcr_extend(NULL, pcrnum, hash) ? -EINVAL : 0;
391 }
392
393 /*
394  * Create an object specific authorisation protocol (OSAP) session
395  */
396 static int osap(struct tpm_buf *tb, struct osapsess *s,
397                 const unsigned char *key, uint16_t type, uint32_t handle)
398 {
399         unsigned char enonce[TPM_NONCE_SIZE];
400         unsigned char ononce[TPM_NONCE_SIZE];
401         int ret;
402
403         ret = tpm_get_random(NULL, ononce, TPM_NONCE_SIZE);
404         if (ret != TPM_NONCE_SIZE)
405                 return ret;
406
407         INIT_BUF(tb);
408         store16(tb, TPM_TAG_RQU_COMMAND);
409         store32(tb, TPM_OSAP_SIZE);
410         store32(tb, TPM_ORD_OSAP);
411         store16(tb, type);
412         store32(tb, handle);
413         storebytes(tb, ononce, TPM_NONCE_SIZE);
414
415         ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
416         if (ret < 0)
417                 return ret;
418
419         s->handle = LOAD32(tb->data, TPM_DATA_OFFSET);
420         memcpy(s->enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)]),
421                TPM_NONCE_SIZE);
422         memcpy(enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t) +
423                                   TPM_NONCE_SIZE]), TPM_NONCE_SIZE);
424         return TSS_rawhmac(s->secret, key, SHA1_DIGEST_SIZE, TPM_NONCE_SIZE,
425                            enonce, TPM_NONCE_SIZE, ononce, 0, 0);
426 }
427
428 /*
429  * Create an object independent authorisation protocol (oiap) session
430  */
431 int oiap(struct tpm_buf *tb, uint32_t *handle, unsigned char *nonce)
432 {
433         int ret;
434
435         INIT_BUF(tb);
436         store16(tb, TPM_TAG_RQU_COMMAND);
437         store32(tb, TPM_OIAP_SIZE);
438         store32(tb, TPM_ORD_OIAP);
439         ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
440         if (ret < 0)
441                 return ret;
442
443         *handle = LOAD32(tb->data, TPM_DATA_OFFSET);
444         memcpy(nonce, &tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)],
445                TPM_NONCE_SIZE);
446         return 0;
447 }
448 EXPORT_SYMBOL_GPL(oiap);
449
450 struct tpm_digests {
451         unsigned char encauth[SHA1_DIGEST_SIZE];
452         unsigned char pubauth[SHA1_DIGEST_SIZE];
453         unsigned char xorwork[SHA1_DIGEST_SIZE * 2];
454         unsigned char xorhash[SHA1_DIGEST_SIZE];
455         unsigned char nonceodd[TPM_NONCE_SIZE];
456 };
457
458 /*
459  * Have the TPM seal(encrypt) the trusted key, possibly based on
460  * Platform Configuration Registers (PCRs). AUTH1 for sealing key.
461  */
462 static int tpm_seal(struct tpm_buf *tb, uint16_t keytype,
463                     uint32_t keyhandle, const unsigned char *keyauth,
464                     const unsigned char *data, uint32_t datalen,
465                     unsigned char *blob, uint32_t *bloblen,
466                     const unsigned char *blobauth,
467                     const unsigned char *pcrinfo, uint32_t pcrinfosize)
468 {
469         struct osapsess sess;
470         struct tpm_digests *td;
471         unsigned char cont;
472         uint32_t ordinal;
473         uint32_t pcrsize;
474         uint32_t datsize;
475         int sealinfosize;
476         int encdatasize;
477         int storedsize;
478         int ret;
479         int i;
480
481         /* alloc some work space for all the hashes */
482         td = kmalloc(sizeof *td, GFP_KERNEL);
483         if (!td)
484                 return -ENOMEM;
485
486         /* get session for sealing key */
487         ret = osap(tb, &sess, keyauth, keytype, keyhandle);
488         if (ret < 0)
489                 goto out;
490         dump_sess(&sess);
491
492         /* calculate encrypted authorization value */
493         memcpy(td->xorwork, sess.secret, SHA1_DIGEST_SIZE);
494         memcpy(td->xorwork + SHA1_DIGEST_SIZE, sess.enonce, SHA1_DIGEST_SIZE);
495         ret = TSS_sha1(td->xorwork, SHA1_DIGEST_SIZE * 2, td->xorhash);
496         if (ret < 0)
497                 goto out;
498
499         ret = tpm_get_random(NULL, td->nonceodd, TPM_NONCE_SIZE);
500         if (ret != TPM_NONCE_SIZE)
501                 goto out;
502         ordinal = htonl(TPM_ORD_SEAL);
503         datsize = htonl(datalen);
504         pcrsize = htonl(pcrinfosize);
505         cont = 0;
506
507         /* encrypt data authorization key */
508         for (i = 0; i < SHA1_DIGEST_SIZE; ++i)
509                 td->encauth[i] = td->xorhash[i] ^ blobauth[i];
510
511         /* calculate authorization HMAC value */
512         if (pcrinfosize == 0) {
513                 /* no pcr info specified */
514                 ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
515                                    sess.enonce, td->nonceodd, cont,
516                                    sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
517                                    td->encauth, sizeof(uint32_t), &pcrsize,
518                                    sizeof(uint32_t), &datsize, datalen, data, 0,
519                                    0);
520         } else {
521                 /* pcr info specified */
522                 ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
523                                    sess.enonce, td->nonceodd, cont,
524                                    sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
525                                    td->encauth, sizeof(uint32_t), &pcrsize,
526                                    pcrinfosize, pcrinfo, sizeof(uint32_t),
527                                    &datsize, datalen, data, 0, 0);
528         }
529         if (ret < 0)
530                 goto out;
531
532         /* build and send the TPM request packet */
533         INIT_BUF(tb);
534         store16(tb, TPM_TAG_RQU_AUTH1_COMMAND);
535         store32(tb, TPM_SEAL_SIZE + pcrinfosize + datalen);
536         store32(tb, TPM_ORD_SEAL);
537         store32(tb, keyhandle);
538         storebytes(tb, td->encauth, SHA1_DIGEST_SIZE);
539         store32(tb, pcrinfosize);
540         storebytes(tb, pcrinfo, pcrinfosize);
541         store32(tb, datalen);
542         storebytes(tb, data, datalen);
543         store32(tb, sess.handle);
544         storebytes(tb, td->nonceodd, TPM_NONCE_SIZE);
545         store8(tb, cont);
546         storebytes(tb, td->pubauth, SHA1_DIGEST_SIZE);
547
548         ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
549         if (ret < 0)
550                 goto out;
551
552         /* calculate the size of the returned Blob */
553         sealinfosize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t));
554         encdatasize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t) +
555                              sizeof(uint32_t) + sealinfosize);
556         storedsize = sizeof(uint32_t) + sizeof(uint32_t) + sealinfosize +
557             sizeof(uint32_t) + encdatasize;
558
559         /* check the HMAC in the response */
560         ret = TSS_checkhmac1(tb->data, ordinal, td->nonceodd, sess.secret,
561                              SHA1_DIGEST_SIZE, storedsize, TPM_DATA_OFFSET, 0,
562                              0);
563
564         /* copy the returned blob to caller */
565         if (!ret) {
566                 memcpy(blob, tb->data + TPM_DATA_OFFSET, storedsize);
567                 *bloblen = storedsize;
568         }
569 out:
570         kzfree(td);
571         return ret;
572 }
573
574 /*
575  * use the AUTH2_COMMAND form of unseal, to authorize both key and blob
576  */
577 static int tpm_unseal(struct tpm_buf *tb,
578                       uint32_t keyhandle, const unsigned char *keyauth,
579                       const unsigned char *blob, int bloblen,
580                       const unsigned char *blobauth,
581                       unsigned char *data, unsigned int *datalen)
582 {
583         unsigned char nonceodd[TPM_NONCE_SIZE];
584         unsigned char enonce1[TPM_NONCE_SIZE];
585         unsigned char enonce2[TPM_NONCE_SIZE];
586         unsigned char authdata1[SHA1_DIGEST_SIZE];
587         unsigned char authdata2[SHA1_DIGEST_SIZE];
588         uint32_t authhandle1 = 0;
589         uint32_t authhandle2 = 0;
590         unsigned char cont = 0;
591         uint32_t ordinal;
592         uint32_t keyhndl;
593         int ret;
594
595         /* sessions for unsealing key and data */
596         ret = oiap(tb, &authhandle1, enonce1);
597         if (ret < 0) {
598                 pr_info("trusted_key: oiap failed (%d)\n", ret);
599                 return ret;
600         }
601         ret = oiap(tb, &authhandle2, enonce2);
602         if (ret < 0) {
603                 pr_info("trusted_key: oiap failed (%d)\n", ret);
604                 return ret;
605         }
606
607         ordinal = htonl(TPM_ORD_UNSEAL);
608         keyhndl = htonl(SRKHANDLE);
609         ret = tpm_get_random(NULL, nonceodd, TPM_NONCE_SIZE);
610         if (ret != TPM_NONCE_SIZE) {
611                 pr_info("trusted_key: tpm_get_random failed (%d)\n", ret);
612                 return ret;
613         }
614         ret = TSS_authhmac(authdata1, keyauth, TPM_NONCE_SIZE,
615                            enonce1, nonceodd, cont, sizeof(uint32_t),
616                            &ordinal, bloblen, blob, 0, 0);
617         if (ret < 0)
618                 return ret;
619         ret = TSS_authhmac(authdata2, blobauth, TPM_NONCE_SIZE,
620                            enonce2, nonceodd, cont, sizeof(uint32_t),
621                            &ordinal, bloblen, blob, 0, 0);
622         if (ret < 0)
623                 return ret;
624
625         /* build and send TPM request packet */
626         INIT_BUF(tb);
627         store16(tb, TPM_TAG_RQU_AUTH2_COMMAND);
628         store32(tb, TPM_UNSEAL_SIZE + bloblen);
629         store32(tb, TPM_ORD_UNSEAL);
630         store32(tb, keyhandle);
631         storebytes(tb, blob, bloblen);
632         store32(tb, authhandle1);
633         storebytes(tb, nonceodd, TPM_NONCE_SIZE);
634         store8(tb, cont);
635         storebytes(tb, authdata1, SHA1_DIGEST_SIZE);
636         store32(tb, authhandle2);
637         storebytes(tb, nonceodd, TPM_NONCE_SIZE);
638         store8(tb, cont);
639         storebytes(tb, authdata2, SHA1_DIGEST_SIZE);
640
641         ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
642         if (ret < 0) {
643                 pr_info("trusted_key: authhmac failed (%d)\n", ret);
644                 return ret;
645         }
646
647         *datalen = LOAD32(tb->data, TPM_DATA_OFFSET);
648         ret = TSS_checkhmac2(tb->data, ordinal, nonceodd,
649                              keyauth, SHA1_DIGEST_SIZE,
650                              blobauth, SHA1_DIGEST_SIZE,
651                              sizeof(uint32_t), TPM_DATA_OFFSET,
652                              *datalen, TPM_DATA_OFFSET + sizeof(uint32_t), 0,
653                              0);
654         if (ret < 0) {
655                 pr_info("trusted_key: TSS_checkhmac2 failed (%d)\n", ret);
656                 return ret;
657         }
658         memcpy(data, tb->data + TPM_DATA_OFFSET + sizeof(uint32_t), *datalen);
659         return 0;
660 }
661
662 /*
663  * Have the TPM seal(encrypt) the symmetric key
664  */
665 static int key_seal(struct trusted_key_payload *p,
666                     struct trusted_key_options *o)
667 {
668         struct tpm_buf *tb;
669         int ret;
670
671         tb = kzalloc(sizeof *tb, GFP_KERNEL);
672         if (!tb)
673                 return -ENOMEM;
674
675         /* include migratable flag at end of sealed key */
676         p->key[p->key_len] = p->migratable;
677
678         ret = tpm_seal(tb, o->keytype, o->keyhandle, o->keyauth,
679                        p->key, p->key_len + 1, p->blob, &p->blob_len,
680                        o->blobauth, o->pcrinfo, o->pcrinfo_len);
681         if (ret < 0)
682                 pr_info("trusted_key: srkseal failed (%d)\n", ret);
683
684         kzfree(tb);
685         return ret;
686 }
687
688 /*
689  * Have the TPM unseal(decrypt) the symmetric key
690  */
691 static int key_unseal(struct trusted_key_payload *p,
692                       struct trusted_key_options *o)
693 {
694         struct tpm_buf *tb;
695         int ret;
696
697         tb = kzalloc(sizeof *tb, GFP_KERNEL);
698         if (!tb)
699                 return -ENOMEM;
700
701         ret = tpm_unseal(tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
702                          o->blobauth, p->key, &p->key_len);
703         if (ret < 0)
704                 pr_info("trusted_key: srkunseal failed (%d)\n", ret);
705         else
706                 /* pull migratable flag out of sealed key */
707                 p->migratable = p->key[--p->key_len];
708
709         kzfree(tb);
710         return ret;
711 }
712
713 enum {
714         Opt_err = -1,
715         Opt_new, Opt_load, Opt_update,
716         Opt_keyhandle, Opt_keyauth, Opt_blobauth,
717         Opt_pcrinfo, Opt_pcrlock, Opt_migratable,
718         Opt_hash,
719         Opt_policydigest,
720         Opt_policyhandle,
721 };
722
723 static const match_table_t key_tokens = {
724         {Opt_new, "new"},
725         {Opt_load, "load"},
726         {Opt_update, "update"},
727         {Opt_keyhandle, "keyhandle=%s"},
728         {Opt_keyauth, "keyauth=%s"},
729         {Opt_blobauth, "blobauth=%s"},
730         {Opt_pcrinfo, "pcrinfo=%s"},
731         {Opt_pcrlock, "pcrlock=%s"},
732         {Opt_migratable, "migratable=%s"},
733         {Opt_hash, "hash=%s"},
734         {Opt_policydigest, "policydigest=%s"},
735         {Opt_policyhandle, "policyhandle=%s"},
736         {Opt_err, NULL}
737 };
738
739 /* can have zero or more token= options */
740 static int getoptions(char *c, struct trusted_key_payload *pay,
741                       struct trusted_key_options *opt)
742 {
743         substring_t args[MAX_OPT_ARGS];
744         char *p = c;
745         int token;
746         int res;
747         unsigned long handle;
748         unsigned long lock;
749         unsigned long token_mask = 0;
750         unsigned int digest_len;
751         int i;
752         int tpm2;
753
754         tpm2 = tpm_is_tpm2(NULL);
755         if (tpm2 < 0)
756                 return tpm2;
757
758         opt->hash = tpm2 ? HASH_ALGO_SHA256 : HASH_ALGO_SHA1;
759
760         while ((p = strsep(&c, " \t"))) {
761                 if (*p == '\0' || *p == ' ' || *p == '\t')
762                         continue;
763                 token = match_token(p, key_tokens, args);
764                 if (test_and_set_bit(token, &token_mask))
765                         return -EINVAL;
766
767                 switch (token) {
768                 case Opt_pcrinfo:
769                         opt->pcrinfo_len = strlen(args[0].from) / 2;
770                         if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
771                                 return -EINVAL;
772                         res = hex2bin(opt->pcrinfo, args[0].from,
773                                       opt->pcrinfo_len);
774                         if (res < 0)
775                                 return -EINVAL;
776                         break;
777                 case Opt_keyhandle:
778                         res = kstrtoul(args[0].from, 16, &handle);
779                         if (res < 0)
780                                 return -EINVAL;
781                         opt->keytype = SEAL_keytype;
782                         opt->keyhandle = handle;
783                         break;
784                 case Opt_keyauth:
785                         if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
786                                 return -EINVAL;
787                         res = hex2bin(opt->keyauth, args[0].from,
788                                       SHA1_DIGEST_SIZE);
789                         if (res < 0)
790                                 return -EINVAL;
791                         break;
792                 case Opt_blobauth:
793                         if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
794                                 return -EINVAL;
795                         res = hex2bin(opt->blobauth, args[0].from,
796                                       SHA1_DIGEST_SIZE);
797                         if (res < 0)
798                                 return -EINVAL;
799                         break;
800                 case Opt_migratable:
801                         if (*args[0].from == '0')
802                                 pay->migratable = 0;
803                         else
804                                 return -EINVAL;
805                         break;
806                 case Opt_pcrlock:
807                         res = kstrtoul(args[0].from, 10, &lock);
808                         if (res < 0)
809                                 return -EINVAL;
810                         opt->pcrlock = lock;
811                         break;
812                 case Opt_hash:
813                         if (test_bit(Opt_policydigest, &token_mask))
814                                 return -EINVAL;
815                         for (i = 0; i < HASH_ALGO__LAST; i++) {
816                                 if (!strcmp(args[0].from, hash_algo_name[i])) {
817                                         opt->hash = i;
818                                         break;
819                                 }
820                         }
821                         if (i == HASH_ALGO__LAST)
822                                 return -EINVAL;
823                         if  (!tpm2 && i != HASH_ALGO_SHA1) {
824                                 pr_info("trusted_key: TPM 1.x only supports SHA-1.\n");
825                                 return -EINVAL;
826                         }
827                         break;
828                 case Opt_policydigest:
829                         digest_len = hash_digest_size[opt->hash];
830                         if (!tpm2 || strlen(args[0].from) != (2 * digest_len))
831                                 return -EINVAL;
832                         res = hex2bin(opt->policydigest, args[0].from,
833                                       digest_len);
834                         if (res < 0)
835                                 return -EINVAL;
836                         opt->policydigest_len = digest_len;
837                         break;
838                 case Opt_policyhandle:
839                         if (!tpm2)
840                                 return -EINVAL;
841                         res = kstrtoul(args[0].from, 16, &handle);
842                         if (res < 0)
843                                 return -EINVAL;
844                         opt->policyhandle = handle;
845                         break;
846                 default:
847                         return -EINVAL;
848                 }
849         }
850         return 0;
851 }
852
853 /*
854  * datablob_parse - parse the keyctl data and fill in the
855  *                  payload and options structures
856  *
857  * On success returns 0, otherwise -EINVAL.
858  */
859 static int datablob_parse(char *datablob, struct trusted_key_payload *p,
860                           struct trusted_key_options *o)
861 {
862         substring_t args[MAX_OPT_ARGS];
863         long keylen;
864         int ret = -EINVAL;
865         int key_cmd;
866         char *c;
867
868         /* main command */
869         c = strsep(&datablob, " \t");
870         if (!c)
871                 return -EINVAL;
872         key_cmd = match_token(c, key_tokens, args);
873         switch (key_cmd) {
874         case Opt_new:
875                 /* first argument is key size */
876                 c = strsep(&datablob, " \t");
877                 if (!c)
878                         return -EINVAL;
879                 ret = kstrtol(c, 10, &keylen);
880                 if (ret < 0 || keylen < MIN_KEY_SIZE || keylen > MAX_KEY_SIZE)
881                         return -EINVAL;
882                 p->key_len = keylen;
883                 ret = getoptions(datablob, p, o);
884                 if (ret < 0)
885                         return ret;
886                 ret = Opt_new;
887                 break;
888         case Opt_load:
889                 /* first argument is sealed blob */
890                 c = strsep(&datablob, " \t");
891                 if (!c)
892                         return -EINVAL;
893                 p->blob_len = strlen(c) / 2;
894                 if (p->blob_len > MAX_BLOB_SIZE)
895                         return -EINVAL;
896                 ret = hex2bin(p->blob, c, p->blob_len);
897                 if (ret < 0)
898                         return -EINVAL;
899                 ret = getoptions(datablob, p, o);
900                 if (ret < 0)
901                         return ret;
902                 ret = Opt_load;
903                 break;
904         case Opt_update:
905                 /* all arguments are options */
906                 ret = getoptions(datablob, p, o);
907                 if (ret < 0)
908                         return ret;
909                 ret = Opt_update;
910                 break;
911         case Opt_err:
912                 return -EINVAL;
913                 break;
914         }
915         return ret;
916 }
917
918 static struct trusted_key_options *trusted_options_alloc(void)
919 {
920         struct trusted_key_options *options;
921         int tpm2;
922
923         tpm2 = tpm_is_tpm2(NULL);
924         if (tpm2 < 0)
925                 return NULL;
926
927         options = kzalloc(sizeof *options, GFP_KERNEL);
928         if (options) {
929                 /* set any non-zero defaults */
930                 options->keytype = SRK_keytype;
931
932                 if (!tpm2)
933                         options->keyhandle = SRKHANDLE;
934         }
935         return options;
936 }
937
938 static struct trusted_key_payload *trusted_payload_alloc(struct key *key)
939 {
940         struct trusted_key_payload *p = NULL;
941         int ret;
942
943         ret = key_payload_reserve(key, sizeof *p);
944         if (ret < 0)
945                 return p;
946         p = kzalloc(sizeof *p, GFP_KERNEL);
947         if (p)
948                 p->migratable = 1; /* migratable by default */
949         return p;
950 }
951
952 /*
953  * trusted_instantiate - create a new trusted key
954  *
955  * Unseal an existing trusted blob or, for a new key, get a
956  * random key, then seal and create a trusted key-type key,
957  * adding it to the specified keyring.
958  *
959  * On success, return 0. Otherwise return errno.
960  */
961 static int trusted_instantiate(struct key *key,
962                                struct key_preparsed_payload *prep)
963 {
964         struct trusted_key_payload *payload = NULL;
965         struct trusted_key_options *options = NULL;
966         size_t datalen = prep->datalen;
967         char *datablob;
968         int ret = 0;
969         int key_cmd;
970         size_t key_len;
971         int tpm2;
972
973         tpm2 = tpm_is_tpm2(NULL);
974         if (tpm2 < 0)
975                 return tpm2;
976
977         if (datalen <= 0 || datalen > 32767 || !prep->data)
978                 return -EINVAL;
979
980         datablob = kmalloc(datalen + 1, GFP_KERNEL);
981         if (!datablob)
982                 return -ENOMEM;
983         memcpy(datablob, prep->data, datalen);
984         datablob[datalen] = '\0';
985
986         options = trusted_options_alloc();
987         if (!options) {
988                 ret = -ENOMEM;
989                 goto out;
990         }
991         payload = trusted_payload_alloc(key);
992         if (!payload) {
993                 ret = -ENOMEM;
994                 goto out;
995         }
996
997         key_cmd = datablob_parse(datablob, payload, options);
998         if (key_cmd < 0) {
999                 ret = key_cmd;
1000                 goto out;
1001         }
1002
1003         if (!options->keyhandle) {
1004                 ret = -EINVAL;
1005                 goto out;
1006         }
1007
1008         dump_payload(payload);
1009         dump_options(options);
1010
1011         switch (key_cmd) {
1012         case Opt_load:
1013                 if (tpm2)
1014                         ret = tpm_unseal_trusted(NULL, payload, options);
1015                 else
1016                         ret = key_unseal(payload, options);
1017                 dump_payload(payload);
1018                 dump_options(options);
1019                 if (ret < 0)
1020                         pr_info("trusted_key: key_unseal failed (%d)\n", ret);
1021                 break;
1022         case Opt_new:
1023                 key_len = payload->key_len;
1024                 ret = tpm_get_random(NULL, payload->key, key_len);
1025                 if (ret != key_len) {
1026                         pr_info("trusted_key: key_create failed (%d)\n", ret);
1027                         goto out;
1028                 }
1029                 if (tpm2)
1030                         ret = tpm_seal_trusted(NULL, payload, options);
1031                 else
1032                         ret = key_seal(payload, options);
1033                 if (ret < 0)
1034                         pr_info("trusted_key: key_seal failed (%d)\n", ret);
1035                 break;
1036         default:
1037                 ret = -EINVAL;
1038                 goto out;
1039         }
1040         if (!ret && options->pcrlock)
1041                 ret = pcrlock(options->pcrlock);
1042 out:
1043         kzfree(datablob);
1044         kzfree(options);
1045         if (!ret)
1046                 rcu_assign_keypointer(key, payload);
1047         else
1048                 kzfree(payload);
1049         return ret;
1050 }
1051
1052 static void trusted_rcu_free(struct rcu_head *rcu)
1053 {
1054         struct trusted_key_payload *p;
1055
1056         p = container_of(rcu, struct trusted_key_payload, rcu);
1057         kzfree(p);
1058 }
1059
1060 /*
1061  * trusted_update - reseal an existing key with new PCR values
1062  */
1063 static int trusted_update(struct key *key, struct key_preparsed_payload *prep)
1064 {
1065         struct trusted_key_payload *p;
1066         struct trusted_key_payload *new_p;
1067         struct trusted_key_options *new_o;
1068         size_t datalen = prep->datalen;
1069         char *datablob;
1070         int ret = 0;
1071
1072         if (key_is_negative(key))
1073                 return -ENOKEY;
1074         p = key->payload.data[0];
1075         if (!p->migratable)
1076                 return -EPERM;
1077         if (datalen <= 0 || datalen > 32767 || !prep->data)
1078                 return -EINVAL;
1079
1080         datablob = kmalloc(datalen + 1, GFP_KERNEL);
1081         if (!datablob)
1082                 return -ENOMEM;
1083         new_o = trusted_options_alloc();
1084         if (!new_o) {
1085                 ret = -ENOMEM;
1086                 goto out;
1087         }
1088         new_p = trusted_payload_alloc(key);
1089         if (!new_p) {
1090                 ret = -ENOMEM;
1091                 goto out;
1092         }
1093
1094         memcpy(datablob, prep->data, datalen);
1095         datablob[datalen] = '\0';
1096         ret = datablob_parse(datablob, new_p, new_o);
1097         if (ret != Opt_update) {
1098                 ret = -EINVAL;
1099                 kzfree(new_p);
1100                 goto out;
1101         }
1102
1103         if (!new_o->keyhandle) {
1104                 ret = -EINVAL;
1105                 kzfree(new_p);
1106                 goto out;
1107         }
1108
1109         /* copy old key values, and reseal with new pcrs */
1110         new_p->migratable = p->migratable;
1111         new_p->key_len = p->key_len;
1112         memcpy(new_p->key, p->key, p->key_len);
1113         dump_payload(p);
1114         dump_payload(new_p);
1115
1116         ret = key_seal(new_p, new_o);
1117         if (ret < 0) {
1118                 pr_info("trusted_key: key_seal failed (%d)\n", ret);
1119                 kzfree(new_p);
1120                 goto out;
1121         }
1122         if (new_o->pcrlock) {
1123                 ret = pcrlock(new_o->pcrlock);
1124                 if (ret < 0) {
1125                         pr_info("trusted_key: pcrlock failed (%d)\n", ret);
1126                         kzfree(new_p);
1127                         goto out;
1128                 }
1129         }
1130         rcu_assign_keypointer(key, new_p);
1131         call_rcu(&p->rcu, trusted_rcu_free);
1132 out:
1133         kzfree(datablob);
1134         kzfree(new_o);
1135         return ret;
1136 }
1137
1138 /*
1139  * trusted_read - copy the sealed blob data to userspace in hex.
1140  * On success, return to userspace the trusted key datablob size.
1141  */
1142 static long trusted_read(const struct key *key, char __user *buffer,
1143                          size_t buflen)
1144 {
1145         const struct trusted_key_payload *p;
1146         char *ascii_buf;
1147         char *bufp;
1148         int i;
1149
1150         p = dereference_key_locked(key);
1151         if (!p)
1152                 return -EINVAL;
1153
1154         if (buffer && buflen >= 2 * p->blob_len) {
1155                 ascii_buf = kmalloc_array(2, p->blob_len, GFP_KERNEL);
1156                 if (!ascii_buf)
1157                         return -ENOMEM;
1158
1159                 bufp = ascii_buf;
1160                 for (i = 0; i < p->blob_len; i++)
1161                         bufp = hex_byte_pack(bufp, p->blob[i]);
1162                 if (copy_to_user(buffer, ascii_buf, 2 * p->blob_len) != 0) {
1163                         kzfree(ascii_buf);
1164                         return -EFAULT;
1165                 }
1166                 kzfree(ascii_buf);
1167         }
1168         return 2 * p->blob_len;
1169 }
1170
1171 /*
1172  * trusted_destroy - clear and free the key's payload
1173  */
1174 static void trusted_destroy(struct key *key)
1175 {
1176         kzfree(key->payload.data[0]);
1177 }
1178
1179 struct key_type key_type_trusted = {
1180         .name = "trusted",
1181         .instantiate = trusted_instantiate,
1182         .update = trusted_update,
1183         .destroy = trusted_destroy,
1184         .describe = user_describe,
1185         .read = trusted_read,
1186 };
1187
1188 EXPORT_SYMBOL_GPL(key_type_trusted);
1189
1190 static void trusted_shash_release(void)
1191 {
1192         if (hashalg)
1193                 crypto_free_shash(hashalg);
1194         if (hmacalg)
1195                 crypto_free_shash(hmacalg);
1196 }
1197
1198 static int __init trusted_shash_alloc(void)
1199 {
1200         int ret;
1201
1202         hmacalg = crypto_alloc_shash(hmac_alg, 0, CRYPTO_ALG_ASYNC);
1203         if (IS_ERR(hmacalg)) {
1204                 pr_info("trusted_key: could not allocate crypto %s\n",
1205                         hmac_alg);
1206                 return PTR_ERR(hmacalg);
1207         }
1208
1209         hashalg = crypto_alloc_shash(hash_alg, 0, CRYPTO_ALG_ASYNC);
1210         if (IS_ERR(hashalg)) {
1211                 pr_info("trusted_key: could not allocate crypto %s\n",
1212                         hash_alg);
1213                 ret = PTR_ERR(hashalg);
1214                 goto hashalg_fail;
1215         }
1216
1217         return 0;
1218
1219 hashalg_fail:
1220         crypto_free_shash(hmacalg);
1221         return ret;
1222 }
1223
1224 static int __init init_trusted(void)
1225 {
1226         int ret;
1227
1228         ret = trusted_shash_alloc();
1229         if (ret < 0)
1230                 return ret;
1231         ret = register_key_type(&key_type_trusted);
1232         if (ret < 0)
1233                 trusted_shash_release();
1234         return ret;
1235 }
1236
1237 static void __exit cleanup_trusted(void)
1238 {
1239         trusted_shash_release();
1240         unregister_key_type(&key_type_trusted);
1241 }
1242
1243 late_initcall(init_trusted);
1244 module_exit(cleanup_trusted);
1245
1246 MODULE_LICENSE("GPL");