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