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