Linux-libre 5.3.12-gnu
[librecmc/linux-libre.git] / crypto / asymmetric_keys / asym_tpm.c
1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) "ASYM-TPM: "fmt
3 #include <linux/slab.h>
4 #include <linux/module.h>
5 #include <linux/export.h>
6 #include <linux/kernel.h>
7 #include <linux/seq_file.h>
8 #include <linux/scatterlist.h>
9 #include <linux/tpm.h>
10 #include <linux/tpm_command.h>
11 #include <crypto/akcipher.h>
12 #include <crypto/hash.h>
13 #include <crypto/sha.h>
14 #include <asm/unaligned.h>
15 #include <keys/asymmetric-subtype.h>
16 #include <keys/trusted.h>
17 #include <crypto/asym_tpm_subtype.h>
18 #include <crypto/public_key.h>
19
20 #define TPM_ORD_FLUSHSPECIFIC   186
21 #define TPM_ORD_LOADKEY2        65
22 #define TPM_ORD_UNBIND          30
23 #define TPM_ORD_SIGN            60
24 #define TPM_LOADKEY2_SIZE               59
25 #define TPM_FLUSHSPECIFIC_SIZE          18
26 #define TPM_UNBIND_SIZE                 63
27 #define TPM_SIGN_SIZE                   63
28
29 #define TPM_RT_KEY                      0x00000001
30
31 /*
32  * Load a TPM key from the blob provided by userspace
33  */
34 static int tpm_loadkey2(struct tpm_buf *tb,
35                         uint32_t keyhandle, unsigned char *keyauth,
36                         const unsigned char *keyblob, int keybloblen,
37                         uint32_t *newhandle)
38 {
39         unsigned char nonceodd[TPM_NONCE_SIZE];
40         unsigned char enonce[TPM_NONCE_SIZE];
41         unsigned char authdata[SHA1_DIGEST_SIZE];
42         uint32_t authhandle = 0;
43         unsigned char cont = 0;
44         uint32_t ordinal;
45         int ret;
46
47         ordinal = htonl(TPM_ORD_LOADKEY2);
48
49         /* session for loading the key */
50         ret = oiap(tb, &authhandle, enonce);
51         if (ret < 0) {
52                 pr_info("oiap failed (%d)\n", ret);
53                 return ret;
54         }
55
56         /* generate odd nonce */
57         ret = tpm_get_random(NULL, nonceodd, TPM_NONCE_SIZE);
58         if (ret < 0) {
59                 pr_info("tpm_get_random failed (%d)\n", ret);
60                 return ret;
61         }
62
63         /* calculate authorization HMAC value */
64         ret = TSS_authhmac(authdata, keyauth, SHA1_DIGEST_SIZE, enonce,
65                            nonceodd, cont, sizeof(uint32_t), &ordinal,
66                            keybloblen, keyblob, 0, 0);
67         if (ret < 0)
68                 return ret;
69
70         /* build the request buffer */
71         INIT_BUF(tb);
72         store16(tb, TPM_TAG_RQU_AUTH1_COMMAND);
73         store32(tb, TPM_LOADKEY2_SIZE + keybloblen);
74         store32(tb, TPM_ORD_LOADKEY2);
75         store32(tb, keyhandle);
76         storebytes(tb, keyblob, keybloblen);
77         store32(tb, authhandle);
78         storebytes(tb, nonceodd, TPM_NONCE_SIZE);
79         store8(tb, cont);
80         storebytes(tb, authdata, SHA1_DIGEST_SIZE);
81
82         ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
83         if (ret < 0) {
84                 pr_info("authhmac failed (%d)\n", ret);
85                 return ret;
86         }
87
88         ret = TSS_checkhmac1(tb->data, ordinal, nonceodd, keyauth,
89                              SHA1_DIGEST_SIZE, 0, 0);
90         if (ret < 0) {
91                 pr_info("TSS_checkhmac1 failed (%d)\n", ret);
92                 return ret;
93         }
94
95         *newhandle = LOAD32(tb->data, TPM_DATA_OFFSET);
96         return 0;
97 }
98
99 /*
100  * Execute the FlushSpecific TPM command
101  */
102 static int tpm_flushspecific(struct tpm_buf *tb, uint32_t handle)
103 {
104         INIT_BUF(tb);
105         store16(tb, TPM_TAG_RQU_COMMAND);
106         store32(tb, TPM_FLUSHSPECIFIC_SIZE);
107         store32(tb, TPM_ORD_FLUSHSPECIFIC);
108         store32(tb, handle);
109         store32(tb, TPM_RT_KEY);
110
111         return trusted_tpm_send(tb->data, MAX_BUF_SIZE);
112 }
113
114 /*
115  * Decrypt a blob provided by userspace using a specific key handle.
116  * The handle is a well known handle or previously loaded by e.g. LoadKey2
117  */
118 static int tpm_unbind(struct tpm_buf *tb,
119                         uint32_t keyhandle, unsigned char *keyauth,
120                         const unsigned char *blob, uint32_t bloblen,
121                         void *out, uint32_t outlen)
122 {
123         unsigned char nonceodd[TPM_NONCE_SIZE];
124         unsigned char enonce[TPM_NONCE_SIZE];
125         unsigned char authdata[SHA1_DIGEST_SIZE];
126         uint32_t authhandle = 0;
127         unsigned char cont = 0;
128         uint32_t ordinal;
129         uint32_t datalen;
130         int ret;
131
132         ordinal = htonl(TPM_ORD_UNBIND);
133         datalen = htonl(bloblen);
134
135         /* session for loading the key */
136         ret = oiap(tb, &authhandle, enonce);
137         if (ret < 0) {
138                 pr_info("oiap failed (%d)\n", ret);
139                 return ret;
140         }
141
142         /* generate odd nonce */
143         ret = tpm_get_random(NULL, nonceodd, TPM_NONCE_SIZE);
144         if (ret < 0) {
145                 pr_info("tpm_get_random failed (%d)\n", ret);
146                 return ret;
147         }
148
149         /* calculate authorization HMAC value */
150         ret = TSS_authhmac(authdata, keyauth, SHA1_DIGEST_SIZE, enonce,
151                            nonceodd, cont, sizeof(uint32_t), &ordinal,
152                            sizeof(uint32_t), &datalen,
153                            bloblen, blob, 0, 0);
154         if (ret < 0)
155                 return ret;
156
157         /* build the request buffer */
158         INIT_BUF(tb);
159         store16(tb, TPM_TAG_RQU_AUTH1_COMMAND);
160         store32(tb, TPM_UNBIND_SIZE + bloblen);
161         store32(tb, TPM_ORD_UNBIND);
162         store32(tb, keyhandle);
163         store32(tb, bloblen);
164         storebytes(tb, blob, bloblen);
165         store32(tb, authhandle);
166         storebytes(tb, nonceodd, TPM_NONCE_SIZE);
167         store8(tb, cont);
168         storebytes(tb, authdata, SHA1_DIGEST_SIZE);
169
170         ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
171         if (ret < 0) {
172                 pr_info("authhmac failed (%d)\n", ret);
173                 return ret;
174         }
175
176         datalen = LOAD32(tb->data, TPM_DATA_OFFSET);
177
178         ret = TSS_checkhmac1(tb->data, ordinal, nonceodd,
179                              keyauth, SHA1_DIGEST_SIZE,
180                              sizeof(uint32_t), TPM_DATA_OFFSET,
181                              datalen, TPM_DATA_OFFSET + sizeof(uint32_t),
182                              0, 0);
183         if (ret < 0) {
184                 pr_info("TSS_checkhmac1 failed (%d)\n", ret);
185                 return ret;
186         }
187
188         memcpy(out, tb->data + TPM_DATA_OFFSET + sizeof(uint32_t),
189                min(outlen, datalen));
190
191         return datalen;
192 }
193
194 /*
195  * Sign a blob provided by userspace (that has had the hash function applied)
196  * using a specific key handle.  The handle is assumed to have been previously
197  * loaded by e.g. LoadKey2.
198  *
199  * Note that the key signature scheme of the used key should be set to
200  * TPM_SS_RSASSAPKCS1v15_DER.  This allows the hashed input to be of any size
201  * up to key_length_in_bytes - 11 and not be limited to size 20 like the
202  * TPM_SS_RSASSAPKCS1v15_SHA1 signature scheme.
203  */
204 static int tpm_sign(struct tpm_buf *tb,
205                     uint32_t keyhandle, unsigned char *keyauth,
206                     const unsigned char *blob, uint32_t bloblen,
207                     void *out, uint32_t outlen)
208 {
209         unsigned char nonceodd[TPM_NONCE_SIZE];
210         unsigned char enonce[TPM_NONCE_SIZE];
211         unsigned char authdata[SHA1_DIGEST_SIZE];
212         uint32_t authhandle = 0;
213         unsigned char cont = 0;
214         uint32_t ordinal;
215         uint32_t datalen;
216         int ret;
217
218         ordinal = htonl(TPM_ORD_SIGN);
219         datalen = htonl(bloblen);
220
221         /* session for loading the key */
222         ret = oiap(tb, &authhandle, enonce);
223         if (ret < 0) {
224                 pr_info("oiap failed (%d)\n", ret);
225                 return ret;
226         }
227
228         /* generate odd nonce */
229         ret = tpm_get_random(NULL, nonceodd, TPM_NONCE_SIZE);
230         if (ret < 0) {
231                 pr_info("tpm_get_random failed (%d)\n", ret);
232                 return ret;
233         }
234
235         /* calculate authorization HMAC value */
236         ret = TSS_authhmac(authdata, keyauth, SHA1_DIGEST_SIZE, enonce,
237                            nonceodd, cont, sizeof(uint32_t), &ordinal,
238                            sizeof(uint32_t), &datalen,
239                            bloblen, blob, 0, 0);
240         if (ret < 0)
241                 return ret;
242
243         /* build the request buffer */
244         INIT_BUF(tb);
245         store16(tb, TPM_TAG_RQU_AUTH1_COMMAND);
246         store32(tb, TPM_SIGN_SIZE + bloblen);
247         store32(tb, TPM_ORD_SIGN);
248         store32(tb, keyhandle);
249         store32(tb, bloblen);
250         storebytes(tb, blob, bloblen);
251         store32(tb, authhandle);
252         storebytes(tb, nonceodd, TPM_NONCE_SIZE);
253         store8(tb, cont);
254         storebytes(tb, authdata, SHA1_DIGEST_SIZE);
255
256         ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
257         if (ret < 0) {
258                 pr_info("authhmac failed (%d)\n", ret);
259                 return ret;
260         }
261
262         datalen = LOAD32(tb->data, TPM_DATA_OFFSET);
263
264         ret = TSS_checkhmac1(tb->data, ordinal, nonceodd,
265                              keyauth, SHA1_DIGEST_SIZE,
266                              sizeof(uint32_t), TPM_DATA_OFFSET,
267                              datalen, TPM_DATA_OFFSET + sizeof(uint32_t),
268                              0, 0);
269         if (ret < 0) {
270                 pr_info("TSS_checkhmac1 failed (%d)\n", ret);
271                 return ret;
272         }
273
274         memcpy(out, tb->data + TPM_DATA_OFFSET + sizeof(uint32_t),
275                min(datalen, outlen));
276
277         return datalen;
278 }
279
280 /* Room to fit two u32 zeros for algo id and parameters length. */
281 #define SETKEY_PARAMS_SIZE (sizeof(u32) * 2)
282
283 /*
284  * Maximum buffer size for the BER/DER encoded public key.  The public key
285  * is of the form SEQUENCE { INTEGER n, INTEGER e } where n is a maximum 2048
286  * bit key and e is usually 65537
287  * The encoding overhead is:
288  * - max 4 bytes for SEQUENCE
289  *   - max 4 bytes for INTEGER n type/length
290  *     - 257 bytes of n
291  *   - max 2 bytes for INTEGER e type/length
292  *     - 3 bytes of e
293  * - 4+4 of zeros for set_pub_key parameters (SETKEY_PARAMS_SIZE)
294  */
295 #define PUB_KEY_BUF_SIZE (4 + 4 + 257 + 2 + 3 + SETKEY_PARAMS_SIZE)
296
297 /*
298  * Provide a part of a description of the key for /proc/keys.
299  */
300 static void asym_tpm_describe(const struct key *asymmetric_key,
301                               struct seq_file *m)
302 {
303         struct tpm_key *tk = asymmetric_key->payload.data[asym_crypto];
304
305         if (!tk)
306                 return;
307
308         seq_printf(m, "TPM1.2/Blob");
309 }
310
311 static void asym_tpm_destroy(void *payload0, void *payload3)
312 {
313         struct tpm_key *tk = payload0;
314
315         if (!tk)
316                 return;
317
318         kfree(tk->blob);
319         tk->blob_len = 0;
320
321         kfree(tk);
322 }
323
324 /* How many bytes will it take to encode the length */
325 static inline uint32_t definite_length(uint32_t len)
326 {
327         if (len <= 127)
328                 return 1;
329         if (len <= 255)
330                 return 2;
331         return 3;
332 }
333
334 static inline uint8_t *encode_tag_length(uint8_t *buf, uint8_t tag,
335                                          uint32_t len)
336 {
337         *buf++ = tag;
338
339         if (len <= 127) {
340                 buf[0] = len;
341                 return buf + 1;
342         }
343
344         if (len <= 255) {
345                 buf[0] = 0x81;
346                 buf[1] = len;
347                 return buf + 2;
348         }
349
350         buf[0] = 0x82;
351         put_unaligned_be16(len, buf + 1);
352         return buf + 3;
353 }
354
355 static uint32_t derive_pub_key(const void *pub_key, uint32_t len, uint8_t *buf)
356 {
357         uint8_t *cur = buf;
358         uint32_t n_len = definite_length(len) + 1 + len + 1;
359         uint32_t e_len = definite_length(3) + 1 + 3;
360         uint8_t e[3] = { 0x01, 0x00, 0x01 };
361
362         /* SEQUENCE */
363         cur = encode_tag_length(cur, 0x30, n_len + e_len);
364         /* INTEGER n */
365         cur = encode_tag_length(cur, 0x02, len + 1);
366         cur[0] = 0x00;
367         memcpy(cur + 1, pub_key, len);
368         cur += len + 1;
369         cur = encode_tag_length(cur, 0x02, sizeof(e));
370         memcpy(cur, e, sizeof(e));
371         cur += sizeof(e);
372         /* Zero parameters to satisfy set_pub_key ABI. */
373         memset(cur, 0, SETKEY_PARAMS_SIZE);
374
375         return cur - buf;
376 }
377
378 /*
379  * Determine the crypto algorithm name.
380  */
381 static int determine_akcipher(const char *encoding, const char *hash_algo,
382                               char alg_name[CRYPTO_MAX_ALG_NAME])
383 {
384         if (strcmp(encoding, "pkcs1") == 0) {
385                 if (!hash_algo) {
386                         strcpy(alg_name, "pkcs1pad(rsa)");
387                         return 0;
388                 }
389
390                 if (snprintf(alg_name, CRYPTO_MAX_ALG_NAME, "pkcs1pad(rsa,%s)",
391                              hash_algo) >= CRYPTO_MAX_ALG_NAME)
392                         return -EINVAL;
393
394                 return 0;
395         }
396
397         if (strcmp(encoding, "raw") == 0) {
398                 strcpy(alg_name, "rsa");
399                 return 0;
400         }
401
402         return -ENOPKG;
403 }
404
405 /*
406  * Query information about a key.
407  */
408 static int tpm_key_query(const struct kernel_pkey_params *params,
409                          struct kernel_pkey_query *info)
410 {
411         struct tpm_key *tk = params->key->payload.data[asym_crypto];
412         int ret;
413         char alg_name[CRYPTO_MAX_ALG_NAME];
414         struct crypto_akcipher *tfm;
415         uint8_t der_pub_key[PUB_KEY_BUF_SIZE];
416         uint32_t der_pub_key_len;
417         int len;
418
419         /* TPM only works on private keys, public keys still done in software */
420         ret = determine_akcipher(params->encoding, params->hash_algo, alg_name);
421         if (ret < 0)
422                 return ret;
423
424         tfm = crypto_alloc_akcipher(alg_name, 0, 0);
425         if (IS_ERR(tfm))
426                 return PTR_ERR(tfm);
427
428         der_pub_key_len = derive_pub_key(tk->pub_key, tk->pub_key_len,
429                                          der_pub_key);
430
431         ret = crypto_akcipher_set_pub_key(tfm, der_pub_key, der_pub_key_len);
432         if (ret < 0)
433                 goto error_free_tfm;
434
435         len = crypto_akcipher_maxsize(tfm);
436
437         info->key_size = tk->key_len;
438         info->max_data_size = tk->key_len / 8;
439         info->max_sig_size = len;
440         info->max_enc_size = len;
441         info->max_dec_size = tk->key_len / 8;
442
443         info->supported_ops = KEYCTL_SUPPORTS_ENCRYPT |
444                               KEYCTL_SUPPORTS_DECRYPT |
445                               KEYCTL_SUPPORTS_VERIFY |
446                               KEYCTL_SUPPORTS_SIGN;
447
448         ret = 0;
449 error_free_tfm:
450         crypto_free_akcipher(tfm);
451         pr_devel("<==%s() = %d\n", __func__, ret);
452         return ret;
453 }
454
455 /*
456  * Encryption operation is performed with the public key.  Hence it is done
457  * in software
458  */
459 static int tpm_key_encrypt(struct tpm_key *tk,
460                            struct kernel_pkey_params *params,
461                            const void *in, void *out)
462 {
463         char alg_name[CRYPTO_MAX_ALG_NAME];
464         struct crypto_akcipher *tfm;
465         struct akcipher_request *req;
466         struct crypto_wait cwait;
467         struct scatterlist in_sg, out_sg;
468         uint8_t der_pub_key[PUB_KEY_BUF_SIZE];
469         uint32_t der_pub_key_len;
470         int ret;
471
472         pr_devel("==>%s()\n", __func__);
473
474         ret = determine_akcipher(params->encoding, params->hash_algo, alg_name);
475         if (ret < 0)
476                 return ret;
477
478         tfm = crypto_alloc_akcipher(alg_name, 0, 0);
479         if (IS_ERR(tfm))
480                 return PTR_ERR(tfm);
481
482         der_pub_key_len = derive_pub_key(tk->pub_key, tk->pub_key_len,
483                                          der_pub_key);
484
485         ret = crypto_akcipher_set_pub_key(tfm, der_pub_key, der_pub_key_len);
486         if (ret < 0)
487                 goto error_free_tfm;
488
489         req = akcipher_request_alloc(tfm, GFP_KERNEL);
490         if (!req)
491                 goto error_free_tfm;
492
493         sg_init_one(&in_sg, in, params->in_len);
494         sg_init_one(&out_sg, out, params->out_len);
495         akcipher_request_set_crypt(req, &in_sg, &out_sg, params->in_len,
496                                    params->out_len);
497         crypto_init_wait(&cwait);
498         akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
499                                       CRYPTO_TFM_REQ_MAY_SLEEP,
500                                       crypto_req_done, &cwait);
501
502         ret = crypto_akcipher_encrypt(req);
503         ret = crypto_wait_req(ret, &cwait);
504
505         if (ret == 0)
506                 ret = req->dst_len;
507
508         akcipher_request_free(req);
509 error_free_tfm:
510         crypto_free_akcipher(tfm);
511         pr_devel("<==%s() = %d\n", __func__, ret);
512         return ret;
513 }
514
515 /*
516  * Decryption operation is performed with the private key in the TPM.
517  */
518 static int tpm_key_decrypt(struct tpm_key *tk,
519                            struct kernel_pkey_params *params,
520                            const void *in, void *out)
521 {
522         struct tpm_buf *tb;
523         uint32_t keyhandle;
524         uint8_t srkauth[SHA1_DIGEST_SIZE];
525         uint8_t keyauth[SHA1_DIGEST_SIZE];
526         int r;
527
528         pr_devel("==>%s()\n", __func__);
529
530         if (params->hash_algo)
531                 return -ENOPKG;
532
533         if (strcmp(params->encoding, "pkcs1"))
534                 return -ENOPKG;
535
536         tb = kzalloc(sizeof(*tb), GFP_KERNEL);
537         if (!tb)
538                 return -ENOMEM;
539
540         /* TODO: Handle a non-all zero SRK authorization */
541         memset(srkauth, 0, sizeof(srkauth));
542
543         r = tpm_loadkey2(tb, SRKHANDLE, srkauth,
544                                 tk->blob, tk->blob_len, &keyhandle);
545         if (r < 0) {
546                 pr_devel("loadkey2 failed (%d)\n", r);
547                 goto error;
548         }
549
550         /* TODO: Handle a non-all zero key authorization */
551         memset(keyauth, 0, sizeof(keyauth));
552
553         r = tpm_unbind(tb, keyhandle, keyauth,
554                        in, params->in_len, out, params->out_len);
555         if (r < 0)
556                 pr_devel("tpm_unbind failed (%d)\n", r);
557
558         if (tpm_flushspecific(tb, keyhandle) < 0)
559                 pr_devel("flushspecific failed (%d)\n", r);
560
561 error:
562         kzfree(tb);
563         pr_devel("<==%s() = %d\n", __func__, r);
564         return r;
565 }
566
567 /*
568  * Hash algorithm OIDs plus ASN.1 DER wrappings [RFC4880 sec 5.2.2].
569  */
570 static const u8 digest_info_md5[] = {
571         0x30, 0x20, 0x30, 0x0c, 0x06, 0x08,
572         0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, /* OID */
573         0x05, 0x00, 0x04, 0x10
574 };
575
576 static const u8 digest_info_sha1[] = {
577         0x30, 0x21, 0x30, 0x09, 0x06, 0x05,
578         0x2b, 0x0e, 0x03, 0x02, 0x1a,
579         0x05, 0x00, 0x04, 0x14
580 };
581
582 static const u8 digest_info_rmd160[] = {
583         0x30, 0x21, 0x30, 0x09, 0x06, 0x05,
584         0x2b, 0x24, 0x03, 0x02, 0x01,
585         0x05, 0x00, 0x04, 0x14
586 };
587
588 static const u8 digest_info_sha224[] = {
589         0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09,
590         0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04,
591         0x05, 0x00, 0x04, 0x1c
592 };
593
594 static const u8 digest_info_sha256[] = {
595         0x30, 0x31, 0x30, 0x0d, 0x06, 0x09,
596         0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
597         0x05, 0x00, 0x04, 0x20
598 };
599
600 static const u8 digest_info_sha384[] = {
601         0x30, 0x41, 0x30, 0x0d, 0x06, 0x09,
602         0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
603         0x05, 0x00, 0x04, 0x30
604 };
605
606 static const u8 digest_info_sha512[] = {
607         0x30, 0x51, 0x30, 0x0d, 0x06, 0x09,
608         0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
609         0x05, 0x00, 0x04, 0x40
610 };
611
612 static const struct asn1_template {
613         const char      *name;
614         const u8        *data;
615         size_t          size;
616 } asn1_templates[] = {
617 #define _(X) { #X, digest_info_##X, sizeof(digest_info_##X) }
618         _(md5),
619         _(sha1),
620         _(rmd160),
621         _(sha256),
622         _(sha384),
623         _(sha512),
624         _(sha224),
625         { NULL }
626 #undef _
627 };
628
629 static const struct asn1_template *lookup_asn1(const char *name)
630 {
631         const struct asn1_template *p;
632
633         for (p = asn1_templates; p->name; p++)
634                 if (strcmp(name, p->name) == 0)
635                         return p;
636         return NULL;
637 }
638
639 /*
640  * Sign operation is performed with the private key in the TPM.
641  */
642 static int tpm_key_sign(struct tpm_key *tk,
643                         struct kernel_pkey_params *params,
644                         const void *in, void *out)
645 {
646         struct tpm_buf *tb;
647         uint32_t keyhandle;
648         uint8_t srkauth[SHA1_DIGEST_SIZE];
649         uint8_t keyauth[SHA1_DIGEST_SIZE];
650         void *asn1_wrapped = NULL;
651         uint32_t in_len = params->in_len;
652         int r;
653
654         pr_devel("==>%s()\n", __func__);
655
656         if (strcmp(params->encoding, "pkcs1"))
657                 return -ENOPKG;
658
659         if (params->hash_algo) {
660                 const struct asn1_template *asn1 =
661                                                 lookup_asn1(params->hash_algo);
662
663                 if (!asn1)
664                         return -ENOPKG;
665
666                 /* request enough space for the ASN.1 template + input hash */
667                 asn1_wrapped = kzalloc(in_len + asn1->size, GFP_KERNEL);
668                 if (!asn1_wrapped)
669                         return -ENOMEM;
670
671                 /* Copy ASN.1 template, then the input */
672                 memcpy(asn1_wrapped, asn1->data, asn1->size);
673                 memcpy(asn1_wrapped + asn1->size, in, in_len);
674
675                 in = asn1_wrapped;
676                 in_len += asn1->size;
677         }
678
679         if (in_len > tk->key_len / 8 - 11) {
680                 r = -EOVERFLOW;
681                 goto error_free_asn1_wrapped;
682         }
683
684         r = -ENOMEM;
685         tb = kzalloc(sizeof(*tb), GFP_KERNEL);
686         if (!tb)
687                 goto error_free_asn1_wrapped;
688
689         /* TODO: Handle a non-all zero SRK authorization */
690         memset(srkauth, 0, sizeof(srkauth));
691
692         r = tpm_loadkey2(tb, SRKHANDLE, srkauth,
693                          tk->blob, tk->blob_len, &keyhandle);
694         if (r < 0) {
695                 pr_devel("loadkey2 failed (%d)\n", r);
696                 goto error_free_tb;
697         }
698
699         /* TODO: Handle a non-all zero key authorization */
700         memset(keyauth, 0, sizeof(keyauth));
701
702         r = tpm_sign(tb, keyhandle, keyauth, in, in_len, out, params->out_len);
703         if (r < 0)
704                 pr_devel("tpm_sign failed (%d)\n", r);
705
706         if (tpm_flushspecific(tb, keyhandle) < 0)
707                 pr_devel("flushspecific failed (%d)\n", r);
708
709 error_free_tb:
710         kzfree(tb);
711 error_free_asn1_wrapped:
712         kfree(asn1_wrapped);
713         pr_devel("<==%s() = %d\n", __func__, r);
714         return r;
715 }
716
717 /*
718  * Do encryption, decryption and signing ops.
719  */
720 static int tpm_key_eds_op(struct kernel_pkey_params *params,
721                           const void *in, void *out)
722 {
723         struct tpm_key *tk = params->key->payload.data[asym_crypto];
724         int ret = -EOPNOTSUPP;
725
726         /* Perform the encryption calculation. */
727         switch (params->op) {
728         case kernel_pkey_encrypt:
729                 ret = tpm_key_encrypt(tk, params, in, out);
730                 break;
731         case kernel_pkey_decrypt:
732                 ret = tpm_key_decrypt(tk, params, in, out);
733                 break;
734         case kernel_pkey_sign:
735                 ret = tpm_key_sign(tk, params, in, out);
736                 break;
737         default:
738                 BUG();
739         }
740
741         return ret;
742 }
743
744 /*
745  * Verify a signature using a public key.
746  */
747 static int tpm_key_verify_signature(const struct key *key,
748                                     const struct public_key_signature *sig)
749 {
750         const struct tpm_key *tk = key->payload.data[asym_crypto];
751         struct crypto_wait cwait;
752         struct crypto_akcipher *tfm;
753         struct akcipher_request *req;
754         struct scatterlist src_sg[2];
755         char alg_name[CRYPTO_MAX_ALG_NAME];
756         uint8_t der_pub_key[PUB_KEY_BUF_SIZE];
757         uint32_t der_pub_key_len;
758         int ret;
759
760         pr_devel("==>%s()\n", __func__);
761
762         BUG_ON(!tk);
763         BUG_ON(!sig);
764         BUG_ON(!sig->s);
765
766         if (!sig->digest)
767                 return -ENOPKG;
768
769         ret = determine_akcipher(sig->encoding, sig->hash_algo, alg_name);
770         if (ret < 0)
771                 return ret;
772
773         tfm = crypto_alloc_akcipher(alg_name, 0, 0);
774         if (IS_ERR(tfm))
775                 return PTR_ERR(tfm);
776
777         der_pub_key_len = derive_pub_key(tk->pub_key, tk->pub_key_len,
778                                          der_pub_key);
779
780         ret = crypto_akcipher_set_pub_key(tfm, der_pub_key, der_pub_key_len);
781         if (ret < 0)
782                 goto error_free_tfm;
783
784         ret = -ENOMEM;
785         req = akcipher_request_alloc(tfm, GFP_KERNEL);
786         if (!req)
787                 goto error_free_tfm;
788
789         sg_init_table(src_sg, 2);
790         sg_set_buf(&src_sg[0], sig->s, sig->s_size);
791         sg_set_buf(&src_sg[1], sig->digest, sig->digest_size);
792         akcipher_request_set_crypt(req, src_sg, NULL, sig->s_size,
793                                    sig->digest_size);
794         crypto_init_wait(&cwait);
795         akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
796                                       CRYPTO_TFM_REQ_MAY_SLEEP,
797                                       crypto_req_done, &cwait);
798         ret = crypto_wait_req(crypto_akcipher_verify(req), &cwait);
799
800         akcipher_request_free(req);
801 error_free_tfm:
802         crypto_free_akcipher(tfm);
803         pr_devel("<==%s() = %d\n", __func__, ret);
804         if (WARN_ON_ONCE(ret > 0))
805                 ret = -EINVAL;
806         return ret;
807 }
808
809 /*
810  * Parse enough information out of TPM_KEY structure:
811  * TPM_STRUCT_VER -> 4 bytes
812  * TPM_KEY_USAGE -> 2 bytes
813  * TPM_KEY_FLAGS -> 4 bytes
814  * TPM_AUTH_DATA_USAGE -> 1 byte
815  * TPM_KEY_PARMS -> variable
816  * UINT32 PCRInfoSize -> 4 bytes
817  * BYTE* -> PCRInfoSize bytes
818  * TPM_STORE_PUBKEY
819  * UINT32 encDataSize;
820  * BYTE* -> encDataSize;
821  *
822  * TPM_KEY_PARMS:
823  * TPM_ALGORITHM_ID -> 4 bytes
824  * TPM_ENC_SCHEME -> 2 bytes
825  * TPM_SIG_SCHEME -> 2 bytes
826  * UINT32 parmSize -> 4 bytes
827  * BYTE* -> variable
828  */
829 static int extract_key_parameters(struct tpm_key *tk)
830 {
831         const void *cur = tk->blob;
832         uint32_t len = tk->blob_len;
833         const void *pub_key;
834         uint32_t sz;
835         uint32_t key_len;
836
837         if (len < 11)
838                 return -EBADMSG;
839
840         /* Ensure this is a legacy key */
841         if (get_unaligned_be16(cur + 4) != 0x0015)
842                 return -EBADMSG;
843
844         /* Skip to TPM_KEY_PARMS */
845         cur += 11;
846         len -= 11;
847
848         if (len < 12)
849                 return -EBADMSG;
850
851         /* Make sure this is an RSA key */
852         if (get_unaligned_be32(cur) != 0x00000001)
853                 return -EBADMSG;
854
855         /* Make sure this is TPM_ES_RSAESPKCSv15 encoding scheme */
856         if (get_unaligned_be16(cur + 4) != 0x0002)
857                 return -EBADMSG;
858
859         /* Make sure this is TPM_SS_RSASSAPKCS1v15_DER signature scheme */
860         if (get_unaligned_be16(cur + 6) != 0x0003)
861                 return -EBADMSG;
862
863         sz = get_unaligned_be32(cur + 8);
864         if (len < sz + 12)
865                 return -EBADMSG;
866
867         /* Move to TPM_RSA_KEY_PARMS */
868         len -= 12;
869         cur += 12;
870
871         /* Grab the RSA key length */
872         key_len = get_unaligned_be32(cur);
873
874         switch (key_len) {
875         case 512:
876         case 1024:
877         case 1536:
878         case 2048:
879                 break;
880         default:
881                 return -EINVAL;
882         }
883
884         /* Move just past TPM_KEY_PARMS */
885         cur += sz;
886         len -= sz;
887
888         if (len < 4)
889                 return -EBADMSG;
890
891         sz = get_unaligned_be32(cur);
892         if (len < 4 + sz)
893                 return -EBADMSG;
894
895         /* Move to TPM_STORE_PUBKEY */
896         cur += 4 + sz;
897         len -= 4 + sz;
898
899         /* Grab the size of the public key, it should jive with the key size */
900         sz = get_unaligned_be32(cur);
901         if (sz > 256)
902                 return -EINVAL;
903
904         pub_key = cur + 4;
905
906         tk->key_len = key_len;
907         tk->pub_key = pub_key;
908         tk->pub_key_len = sz;
909
910         return 0;
911 }
912
913 /* Given the blob, parse it and load it into the TPM */
914 struct tpm_key *tpm_key_create(const void *blob, uint32_t blob_len)
915 {
916         int r;
917         struct tpm_key *tk;
918
919         r = tpm_is_tpm2(NULL);
920         if (r < 0)
921                 goto error;
922
923         /* We don't support TPM2 yet */
924         if (r > 0) {
925                 r = -ENODEV;
926                 goto error;
927         }
928
929         r = -ENOMEM;
930         tk = kzalloc(sizeof(struct tpm_key), GFP_KERNEL);
931         if (!tk)
932                 goto error;
933
934         tk->blob = kmemdup(blob, blob_len, GFP_KERNEL);
935         if (!tk->blob)
936                 goto error_memdup;
937
938         tk->blob_len = blob_len;
939
940         r = extract_key_parameters(tk);
941         if (r < 0)
942                 goto error_extract;
943
944         return tk;
945
946 error_extract:
947         kfree(tk->blob);
948         tk->blob_len = 0;
949 error_memdup:
950         kfree(tk);
951 error:
952         return ERR_PTR(r);
953 }
954 EXPORT_SYMBOL_GPL(tpm_key_create);
955
956 /*
957  * TPM-based asymmetric key subtype
958  */
959 struct asymmetric_key_subtype asym_tpm_subtype = {
960         .owner                  = THIS_MODULE,
961         .name                   = "asym_tpm",
962         .name_len               = sizeof("asym_tpm") - 1,
963         .describe               = asym_tpm_describe,
964         .destroy                = asym_tpm_destroy,
965         .query                  = tpm_key_query,
966         .eds_op                 = tpm_key_eds_op,
967         .verify_signature       = tpm_key_verify_signature,
968 };
969 EXPORT_SYMBOL_GPL(asym_tpm_subtype);
970
971 MODULE_DESCRIPTION("TPM based asymmetric key subtype");
972 MODULE_AUTHOR("Intel Corporation");
973 MODULE_LICENSE("GPL v2");