Prepare v2023.10
[platform/kernel/u-boot.git] / lib / crypto / asymmetric_type.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Asymmetric public-key cryptography key type
3  *
4  * See Documentation/crypto/asymmetric-keys.txt
5  *
6  * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
7  * Written by David Howells (dhowells@redhat.com)
8  */
9 #ifndef __UBOOT__
10 #include <log.h>
11 #include <dm/devres.h>
12 #include <keys/asymmetric-subtype.h>
13 #include <keys/asymmetric-parser.h>
14 #endif
15 #include <crypto/public_key.h>
16 #ifdef __UBOOT__
17 #include <linux/bug.h>
18 #include <linux/compat.h>
19 #include <linux/ctype.h>
20 #include <linux/err.h>
21 #include <linux/string.h>
22 #else
23 #include <linux/seq_file.h>
24 #include <linux/module.h>
25 #include <linux/slab.h>
26 #include <linux/ctype.h>
27 #endif
28 #ifdef __UBOOT__
29 #include <keys/asymmetric-type.h>
30 #else
31 #include <keys/system_keyring.h>
32 #include <keys/user-type.h>
33 #include "asymmetric_keys.h"
34 #endif
35
36 MODULE_LICENSE("GPL");
37
38 #ifndef __UBOOT__
39 const char *const key_being_used_for[NR__KEY_BEING_USED_FOR] = {
40         [VERIFYING_MODULE_SIGNATURE]            = "mod sig",
41         [VERIFYING_FIRMWARE_SIGNATURE]          = "firmware sig",
42         [VERIFYING_KEXEC_PE_SIGNATURE]          = "kexec PE sig",
43         [VERIFYING_KEY_SIGNATURE]               = "key sig",
44         [VERIFYING_KEY_SELF_SIGNATURE]          = "key self sig",
45         [VERIFYING_UNSPECIFIED_SIGNATURE]       = "unspec sig",
46 };
47 EXPORT_SYMBOL_GPL(key_being_used_for);
48
49 static LIST_HEAD(asymmetric_key_parsers);
50 static DECLARE_RWSEM(asymmetric_key_parsers_sem);
51
52 /**
53  * find_asymmetric_key - Find a key by ID.
54  * @keyring: The keys to search.
55  * @id_0: The first ID to look for or NULL.
56  * @id_1: The second ID to look for or NULL.
57  * @partial: Use partial match if true, exact if false.
58  *
59  * Find a key in the given keyring by identifier.  The preferred identifier is
60  * the id_0 and the fallback identifier is the id_1.  If both are given, the
61  * lookup is by the former, but the latter must also match.
62  */
63 struct key *find_asymmetric_key(struct key *keyring,
64                                 const struct asymmetric_key_id *id_0,
65                                 const struct asymmetric_key_id *id_1,
66                                 bool partial)
67 {
68         struct key *key;
69         key_ref_t ref;
70         const char *lookup;
71         char *req, *p;
72         int len;
73
74         BUG_ON(!id_0 && !id_1);
75
76         if (id_0) {
77                 lookup = id_0->data;
78                 len = id_0->len;
79         } else {
80                 lookup = id_1->data;
81                 len = id_1->len;
82         }
83
84         /* Construct an identifier "id:<keyid>". */
85         p = req = kmalloc(2 + 1 + len * 2 + 1, GFP_KERNEL);
86         if (!req)
87                 return ERR_PTR(-ENOMEM);
88
89         if (partial) {
90                 *p++ = 'i';
91                 *p++ = 'd';
92         } else {
93                 *p++ = 'e';
94                 *p++ = 'x';
95         }
96         *p++ = ':';
97         p = bin2hex(p, lookup, len);
98         *p = 0;
99
100         pr_debug("Look up: \"%s\"\n", req);
101
102         ref = keyring_search(make_key_ref(keyring, 1),
103                              &key_type_asymmetric, req, true);
104         if (IS_ERR(ref))
105                 pr_debug("Request for key '%s' err %ld\n", req, PTR_ERR(ref));
106         kfree(req);
107
108         if (IS_ERR(ref)) {
109                 switch (PTR_ERR(ref)) {
110                         /* Hide some search errors */
111                 case -EACCES:
112                 case -ENOTDIR:
113                 case -EAGAIN:
114                         return ERR_PTR(-ENOKEY);
115                 default:
116                         return ERR_CAST(ref);
117                 }
118         }
119
120         key = key_ref_to_ptr(ref);
121         if (id_0 && id_1) {
122                 const struct asymmetric_key_ids *kids = asymmetric_key_ids(key);
123
124                 if (!kids->id[1]) {
125                         pr_debug("First ID matches, but second is missing\n");
126                         goto reject;
127                 }
128                 if (!asymmetric_key_id_same(id_1, kids->id[1])) {
129                         pr_debug("First ID matches, but second does not\n");
130                         goto reject;
131                 }
132         }
133
134         pr_devel("<==%s() = 0 [%x]\n", __func__, key_serial(key));
135         return key;
136
137 reject:
138         key_put(key);
139         return ERR_PTR(-EKEYREJECTED);
140 }
141 EXPORT_SYMBOL_GPL(find_asymmetric_key);
142 #endif /* !__UBOOT__ */
143
144 /**
145  * asymmetric_key_generate_id: Construct an asymmetric key ID
146  * @val_1: First binary blob
147  * @len_1: Length of first binary blob
148  * @val_2: Second binary blob
149  * @len_2: Length of second binary blob
150  *
151  * Construct an asymmetric key ID from a pair of binary blobs.
152  */
153 struct asymmetric_key_id *asymmetric_key_generate_id(const void *val_1,
154                                                      size_t len_1,
155                                                      const void *val_2,
156                                                      size_t len_2)
157 {
158         struct asymmetric_key_id *kid;
159
160         kid = kmalloc(sizeof(struct asymmetric_key_id) + len_1 + len_2,
161                       GFP_KERNEL);
162         if (!kid)
163                 return ERR_PTR(-ENOMEM);
164         kid->len = len_1 + len_2;
165         memcpy(kid->data, val_1, len_1);
166         memcpy(kid->data + len_1, val_2, len_2);
167         return kid;
168 }
169 EXPORT_SYMBOL_GPL(asymmetric_key_generate_id);
170
171 /**
172  * asymmetric_key_id_same - Return true if two asymmetric keys IDs are the same.
173  * @kid_1, @kid_2: The key IDs to compare
174  */
175 bool asymmetric_key_id_same(const struct asymmetric_key_id *kid1,
176                             const struct asymmetric_key_id *kid2)
177 {
178         if (!kid1 || !kid2)
179                 return false;
180         if (kid1->len != kid2->len)
181                 return false;
182         return memcmp(kid1->data, kid2->data, kid1->len) == 0;
183 }
184 EXPORT_SYMBOL_GPL(asymmetric_key_id_same);
185
186 /**
187  * asymmetric_key_id_partial - Return true if two asymmetric keys IDs
188  * partially match
189  * @kid_1, @kid_2: The key IDs to compare
190  */
191 bool asymmetric_key_id_partial(const struct asymmetric_key_id *kid1,
192                                const struct asymmetric_key_id *kid2)
193 {
194         if (!kid1 || !kid2)
195                 return false;
196         if (kid1->len < kid2->len)
197                 return false;
198         return memcmp(kid1->data + (kid1->len - kid2->len),
199                       kid2->data, kid2->len) == 0;
200 }
201 EXPORT_SYMBOL_GPL(asymmetric_key_id_partial);
202
203 #ifndef __UBOOT__
204 /**
205  * asymmetric_match_key_ids - Search asymmetric key IDs
206  * @kids: The list of key IDs to check
207  * @match_id: The key ID we're looking for
208  * @match: The match function to use
209  */
210 static bool asymmetric_match_key_ids(
211         const struct asymmetric_key_ids *kids,
212         const struct asymmetric_key_id *match_id,
213         bool (*match)(const struct asymmetric_key_id *kid1,
214                       const struct asymmetric_key_id *kid2))
215 {
216         int i;
217
218         if (!kids || !match_id)
219                 return false;
220         for (i = 0; i < ARRAY_SIZE(kids->id); i++)
221                 if (match(kids->id[i], match_id))
222                         return true;
223         return false;
224 }
225
226 /* helper function can be called directly with pre-allocated memory */
227 inline int __asymmetric_key_hex_to_key_id(const char *id,
228                                    struct asymmetric_key_id *match_id,
229                                    size_t hexlen)
230 {
231         match_id->len = hexlen;
232         return hex2bin(match_id->data, id, hexlen);
233 }
234
235 /**
236  * asymmetric_key_hex_to_key_id - Convert a hex string into a key ID.
237  * @id: The ID as a hex string.
238  */
239 struct asymmetric_key_id *asymmetric_key_hex_to_key_id(const char *id)
240 {
241         struct asymmetric_key_id *match_id;
242         size_t asciihexlen;
243         int ret;
244
245         if (!*id)
246                 return ERR_PTR(-EINVAL);
247         asciihexlen = strlen(id);
248         if (asciihexlen & 1)
249                 return ERR_PTR(-EINVAL);
250
251         match_id = kmalloc(sizeof(struct asymmetric_key_id) + asciihexlen / 2,
252                            GFP_KERNEL);
253         if (!match_id)
254                 return ERR_PTR(-ENOMEM);
255         ret = __asymmetric_key_hex_to_key_id(id, match_id, asciihexlen / 2);
256         if (ret < 0) {
257                 kfree(match_id);
258                 return ERR_PTR(-EINVAL);
259         }
260         return match_id;
261 }
262
263 /*
264  * Match asymmetric keys by an exact match on an ID.
265  */
266 static bool asymmetric_key_cmp(const struct key *key,
267                                const struct key_match_data *match_data)
268 {
269         const struct asymmetric_key_ids *kids = asymmetric_key_ids(key);
270         const struct asymmetric_key_id *match_id = match_data->preparsed;
271
272         return asymmetric_match_key_ids(kids, match_id,
273                                         asymmetric_key_id_same);
274 }
275
276 /*
277  * Match asymmetric keys by a partial match on an IDs.
278  */
279 static bool asymmetric_key_cmp_partial(const struct key *key,
280                                        const struct key_match_data *match_data)
281 {
282         const struct asymmetric_key_ids *kids = asymmetric_key_ids(key);
283         const struct asymmetric_key_id *match_id = match_data->preparsed;
284
285         return asymmetric_match_key_ids(kids, match_id,
286                                         asymmetric_key_id_partial);
287 }
288
289 /*
290  * Preparse the match criterion.  If we don't set lookup_type and cmp,
291  * the default will be an exact match on the key description.
292  *
293  * There are some specifiers for matching key IDs rather than by the key
294  * description:
295  *
296  *      "id:<id>" - find a key by partial match on any available ID
297  *      "ex:<id>" - find a key by exact match on any available ID
298  *
299  * These have to be searched by iteration rather than by direct lookup because
300  * the key is hashed according to its description.
301  */
302 static int asymmetric_key_match_preparse(struct key_match_data *match_data)
303 {
304         struct asymmetric_key_id *match_id;
305         const char *spec = match_data->raw_data;
306         const char *id;
307         bool (*cmp)(const struct key *, const struct key_match_data *) =
308                 asymmetric_key_cmp;
309
310         if (!spec || !*spec)
311                 return -EINVAL;
312         if (spec[0] == 'i' &&
313             spec[1] == 'd' &&
314             spec[2] == ':') {
315                 id = spec + 3;
316                 cmp = asymmetric_key_cmp_partial;
317         } else if (spec[0] == 'e' &&
318                    spec[1] == 'x' &&
319                    spec[2] == ':') {
320                 id = spec + 3;
321         } else {
322                 goto default_match;
323         }
324
325         match_id = asymmetric_key_hex_to_key_id(id);
326         if (IS_ERR(match_id))
327                 return PTR_ERR(match_id);
328
329         match_data->preparsed = match_id;
330         match_data->cmp = cmp;
331         match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE;
332         return 0;
333
334 default_match:
335         return 0;
336 }
337
338 /*
339  * Free the preparsed the match criterion.
340  */
341 static void asymmetric_key_match_free(struct key_match_data *match_data)
342 {
343         kfree(match_data->preparsed);
344 }
345
346 /*
347  * Describe the asymmetric key
348  */
349 static void asymmetric_key_describe(const struct key *key, struct seq_file *m)
350 {
351         const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
352         const struct asymmetric_key_ids *kids = asymmetric_key_ids(key);
353         const struct asymmetric_key_id *kid;
354         const unsigned char *p;
355         int n;
356
357         seq_puts(m, key->description);
358
359         if (subtype) {
360                 seq_puts(m, ": ");
361                 subtype->describe(key, m);
362
363                 if (kids && kids->id[1]) {
364                         kid = kids->id[1];
365                         seq_putc(m, ' ');
366                         n = kid->len;
367                         p = kid->data;
368                         if (n > 4) {
369                                 p += n - 4;
370                                 n = 4;
371                         }
372                         seq_printf(m, "%*phN", n, p);
373                 }
374
375                 seq_puts(m, " [");
376                 /* put something here to indicate the key's capabilities */
377                 seq_putc(m, ']');
378         }
379 }
380
381 /*
382  * Preparse a asymmetric payload to get format the contents appropriately for the
383  * internal payload to cut down on the number of scans of the data performed.
384  *
385  * We also generate a proposed description from the contents of the key that
386  * can be used to name the key if the user doesn't want to provide one.
387  */
388 static int asymmetric_key_preparse(struct key_preparsed_payload *prep)
389 {
390         struct asymmetric_key_parser *parser;
391         int ret;
392
393         pr_devel("==>%s()\n", __func__);
394
395         if (prep->datalen == 0)
396                 return -EINVAL;
397
398         down_read(&asymmetric_key_parsers_sem);
399
400         ret = -EBADMSG;
401         list_for_each_entry(parser, &asymmetric_key_parsers, link) {
402                 pr_debug("Trying parser '%s'\n", parser->name);
403
404                 ret = parser->parse(prep);
405                 if (ret != -EBADMSG) {
406                         pr_debug("Parser recognised the format (ret %d)\n",
407                                  ret);
408                         break;
409                 }
410         }
411
412         up_read(&asymmetric_key_parsers_sem);
413         pr_devel("<==%s() = %d\n", __func__, ret);
414         return ret;
415 }
416
417 /*
418  * Clean up the key ID list
419  */
420 static void asymmetric_key_free_kids(struct asymmetric_key_ids *kids)
421 {
422         int i;
423
424         if (kids) {
425                 for (i = 0; i < ARRAY_SIZE(kids->id); i++)
426                         kfree(kids->id[i]);
427                 kfree(kids);
428         }
429 }
430
431 /*
432  * Clean up the preparse data
433  */
434 static void asymmetric_key_free_preparse(struct key_preparsed_payload *prep)
435 {
436         struct asymmetric_key_subtype *subtype = prep->payload.data[asym_subtype];
437         struct asymmetric_key_ids *kids = prep->payload.data[asym_key_ids];
438
439         pr_devel("==>%s()\n", __func__);
440
441         if (subtype) {
442                 subtype->destroy(prep->payload.data[asym_crypto],
443                                  prep->payload.data[asym_auth]);
444                 module_put(subtype->owner);
445         }
446         asymmetric_key_free_kids(kids);
447         kfree(prep->description);
448 }
449
450 /*
451  * dispose of the data dangling from the corpse of a asymmetric key
452  */
453 static void asymmetric_key_destroy(struct key *key)
454 {
455         struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
456         struct asymmetric_key_ids *kids = key->payload.data[asym_key_ids];
457         void *data = key->payload.data[asym_crypto];
458         void *auth = key->payload.data[asym_auth];
459
460         key->payload.data[asym_crypto] = NULL;
461         key->payload.data[asym_subtype] = NULL;
462         key->payload.data[asym_key_ids] = NULL;
463         key->payload.data[asym_auth] = NULL;
464
465         if (subtype) {
466                 subtype->destroy(data, auth);
467                 module_put(subtype->owner);
468         }
469
470         asymmetric_key_free_kids(kids);
471 }
472
473 static struct key_restriction *asymmetric_restriction_alloc(
474         key_restrict_link_func_t check,
475         struct key *key)
476 {
477         struct key_restriction *keyres =
478                 kzalloc(sizeof(struct key_restriction), GFP_KERNEL);
479
480         if (!keyres)
481                 return ERR_PTR(-ENOMEM);
482
483         keyres->check = check;
484         keyres->key = key;
485         keyres->keytype = &key_type_asymmetric;
486
487         return keyres;
488 }
489
490 /*
491  * look up keyring restrict functions for asymmetric keys
492  */
493 static struct key_restriction *asymmetric_lookup_restriction(
494         const char *restriction)
495 {
496         char *restrict_method;
497         char *parse_buf;
498         char *next;
499         struct key_restriction *ret = ERR_PTR(-EINVAL);
500
501         if (strcmp("builtin_trusted", restriction) == 0)
502                 return asymmetric_restriction_alloc(
503                         restrict_link_by_builtin_trusted, NULL);
504
505         if (strcmp("builtin_and_secondary_trusted", restriction) == 0)
506                 return asymmetric_restriction_alloc(
507                         restrict_link_by_builtin_and_secondary_trusted, NULL);
508
509         parse_buf = kstrndup(restriction, PAGE_SIZE, GFP_KERNEL);
510         if (!parse_buf)
511                 return ERR_PTR(-ENOMEM);
512
513         next = parse_buf;
514         restrict_method = strsep(&next, ":");
515
516         if ((strcmp(restrict_method, "key_or_keyring") == 0) && next) {
517                 char *key_text;
518                 key_serial_t serial;
519                 struct key *key;
520                 key_restrict_link_func_t link_fn =
521                         restrict_link_by_key_or_keyring;
522                 bool allow_null_key = false;
523
524                 key_text = strsep(&next, ":");
525
526                 if (next) {
527                         if (strcmp(next, "chain") != 0)
528                                 goto out;
529
530                         link_fn = restrict_link_by_key_or_keyring_chain;
531                         allow_null_key = true;
532                 }
533
534                 if (kstrtos32(key_text, 0, &serial) < 0)
535                         goto out;
536
537                 if ((serial == 0) && allow_null_key) {
538                         key = NULL;
539                 } else {
540                         key = key_lookup(serial);
541                         if (IS_ERR(key)) {
542                                 ret = ERR_CAST(key);
543                                 goto out;
544                         }
545                 }
546
547                 ret = asymmetric_restriction_alloc(link_fn, key);
548                 if (IS_ERR(ret))
549                         key_put(key);
550         }
551
552 out:
553         kfree(parse_buf);
554         return ret;
555 }
556
557 int asymmetric_key_eds_op(struct kernel_pkey_params *params,
558                           const void *in, void *out)
559 {
560         const struct asymmetric_key_subtype *subtype;
561         struct key *key = params->key;
562         int ret;
563
564         pr_devel("==>%s()\n", __func__);
565
566         if (key->type != &key_type_asymmetric)
567                 return -EINVAL;
568         subtype = asymmetric_key_subtype(key);
569         if (!subtype ||
570             !key->payload.data[0])
571                 return -EINVAL;
572         if (!subtype->eds_op)
573                 return -ENOTSUPP;
574
575         ret = subtype->eds_op(params, in, out);
576
577         pr_devel("<==%s() = %d\n", __func__, ret);
578         return ret;
579 }
580
581 static int asymmetric_key_verify_signature(struct kernel_pkey_params *params,
582                                            const void *in, const void *in2)
583 {
584         struct public_key_signature sig = {
585                 .s_size         = params->in2_len,
586                 .digest_size    = params->in_len,
587                 .encoding       = params->encoding,
588                 .hash_algo      = params->hash_algo,
589                 .digest         = (void *)in,
590                 .s              = (void *)in2,
591         };
592
593         return verify_signature(params->key, &sig);
594 }
595
596 struct key_type key_type_asymmetric = {
597         .name                   = "asymmetric",
598         .preparse               = asymmetric_key_preparse,
599         .free_preparse          = asymmetric_key_free_preparse,
600         .instantiate            = generic_key_instantiate,
601         .match_preparse         = asymmetric_key_match_preparse,
602         .match_free             = asymmetric_key_match_free,
603         .destroy                = asymmetric_key_destroy,
604         .describe               = asymmetric_key_describe,
605         .lookup_restriction     = asymmetric_lookup_restriction,
606         .asym_query             = query_asymmetric_key,
607         .asym_eds_op            = asymmetric_key_eds_op,
608         .asym_verify_signature  = asymmetric_key_verify_signature,
609 };
610 EXPORT_SYMBOL_GPL(key_type_asymmetric);
611
612 /**
613  * register_asymmetric_key_parser - Register a asymmetric key blob parser
614  * @parser: The parser to register
615  */
616 int register_asymmetric_key_parser(struct asymmetric_key_parser *parser)
617 {
618         struct asymmetric_key_parser *cursor;
619         int ret;
620
621         down_write(&asymmetric_key_parsers_sem);
622
623         list_for_each_entry(cursor, &asymmetric_key_parsers, link) {
624                 if (strcmp(cursor->name, parser->name) == 0) {
625                         pr_err("Asymmetric key parser '%s' already registered\n",
626                                parser->name);
627                         ret = -EEXIST;
628                         goto out;
629                 }
630         }
631
632         list_add_tail(&parser->link, &asymmetric_key_parsers);
633
634         pr_notice("Asymmetric key parser '%s' registered\n", parser->name);
635         ret = 0;
636
637 out:
638         up_write(&asymmetric_key_parsers_sem);
639         return ret;
640 }
641 EXPORT_SYMBOL_GPL(register_asymmetric_key_parser);
642
643 /**
644  * unregister_asymmetric_key_parser - Unregister a asymmetric key blob parser
645  * @parser: The parser to unregister
646  */
647 void unregister_asymmetric_key_parser(struct asymmetric_key_parser *parser)
648 {
649         down_write(&asymmetric_key_parsers_sem);
650         list_del(&parser->link);
651         up_write(&asymmetric_key_parsers_sem);
652
653         pr_notice("Asymmetric key parser '%s' unregistered\n", parser->name);
654 }
655 EXPORT_SYMBOL_GPL(unregister_asymmetric_key_parser);
656
657 /*
658  * Module stuff
659  */
660 static int __init asymmetric_key_init(void)
661 {
662         return register_key_type(&key_type_asymmetric);
663 }
664
665 static void __exit asymmetric_key_cleanup(void)
666 {
667         unregister_key_type(&key_type_asymmetric);
668 }
669
670 module_init(asymmetric_key_init);
671 module_exit(asymmetric_key_cleanup);
672 #endif /* !__UBOOT__ */