Merge tag 'v2021.01-rc5' into next
[platform/kernel/u-boot.git] / lib / crypto / pkcs7_verify.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Verify the signature on a PKCS#7 message.
3  *
4  * Imported from crypto/asymmetric_keys/pkcs7_verify.c of linux 5.7
5  * with modification marked as __UBOOT__.
6  *
7  * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
8  * Written by David Howells (dhowells@redhat.com)
9  */
10
11 #define pr_fmt(fmt) "PKCS7: "fmt
12 #ifdef __UBOOT__
13 #include <image.h>
14 #include <string.h>
15 #include <linux/bitops.h>
16 #include <linux/compat.h>
17 #include <linux/asn1.h>
18 #include <u-boot/rsa-checksum.h>
19 #include <crypto/public_key.h>
20 #include <crypto/pkcs7_parser.h>
21 #else
22 #include <linux/kernel.h>
23 #include <linux/export.h>
24 #include <linux/slab.h>
25 #include <linux/err.h>
26 #include <linux/asn1.h>
27 #include <crypto/hash.h>
28 #include <crypto/hash_info.h>
29 #include <crypto/public_key.h>
30 #include "pkcs7_parser.h"
31 #endif
32
33 /*
34  * pkcs7_digest - Digest the relevant parts of the PKCS#7 data
35  * @pkcs7:      PKCS7 Signed Data
36  * @sinfo:      PKCS7 Signed Info
37  *
38  * Digest the relevant parts of the PKCS#7 data, @pkcs7, using signature
39  * information in @sinfo. But if there are authentication attributes,
40  * i.e. signed image case, the digest must be calculated against
41  * the authentication attributes.
42  *
43  * Return:      0 - on success, non-zero error code - otherwise
44  */
45 #ifdef __UBOOT__
46 static int pkcs7_digest(struct pkcs7_message *pkcs7,
47                         struct pkcs7_signed_info *sinfo)
48 {
49         struct public_key_signature *sig = sinfo->sig;
50         struct image_region regions[2];
51         int ret = 0;
52
53         /*
54          * [RFC2315 9.3]
55          * If the authenticated attributes are present,
56          * the message-digest is calculated on the
57          * attributes present in the
58          * authenticatedAttributes field and not just
59          * the contents field
60          */
61         if (!sinfo->authattrs && sig->digest)
62                 return 0;
63
64         if (!sinfo->sig->hash_algo)
65                 return -ENOPKG;
66         if (!strcmp(sinfo->sig->hash_algo, "sha256"))
67                 sig->digest_size = SHA256_SUM_LEN;
68         else if (!strcmp(sinfo->sig->hash_algo, "sha1"))
69                 sig->digest_size = SHA1_SUM_LEN;
70         else
71                 return -ENOPKG;
72
73         /*
74          * Calculate the hash only if the data is present.
75          * In case of authenticated variable and capsule,
76          * the hash has already been calculated on the
77          * efi_image_regions and populated
78          */
79         if (pkcs7->data) {
80                 sig->digest = calloc(1, sig->digest_size);
81                 if (!sig->digest) {
82                         pr_warn("Sig %u: Out of memory\n", sinfo->index);
83                         return -ENOMEM;
84                 }
85
86                 regions[0].data = pkcs7->data;
87                 regions[0].size = pkcs7->data_len;
88
89                 /* Digest the message [RFC2315 9.3] */
90                 hash_calculate(sinfo->sig->hash_algo, regions, 1, sig->digest);
91         }
92
93         /* However, if there are authenticated attributes, there must be a
94          * message digest attribute amongst them which corresponds to the
95          * digest we just calculated.
96          */
97         if (sinfo->authattrs) {
98                 u8 tag;
99
100                 if (!sinfo->msgdigest) {
101                         pr_warn("Sig %u: No messageDigest\n", sinfo->index);
102                         ret = -EKEYREJECTED;
103                         goto error;
104                 }
105
106                 if (sinfo->msgdigest_len != sig->digest_size) {
107                         pr_debug("Sig %u: Invalid digest size (%u)\n",
108                                  sinfo->index, sinfo->msgdigest_len);
109                         ret = -EBADMSG;
110                         goto error;
111                 }
112
113                 if (memcmp(sig->digest, sinfo->msgdigest,
114                            sinfo->msgdigest_len) != 0) {
115                         pr_debug("Sig %u: Message digest doesn't match\n",
116                                  sinfo->index);
117                         ret = -EKEYREJECTED;
118                         goto error;
119                 }
120
121                 /* We then calculate anew, using the authenticated attributes
122                  * as the contents of the digest instead.  Note that we need to
123                  * convert the attributes from a CONT.0 into a SET before we
124                  * hash it.
125                  */
126                 memset(sig->digest, 0, sig->digest_size);
127
128                 tag = 0x31;
129                 regions[0].data = &tag;
130                 regions[0].size = 1;
131                 regions[1].data = sinfo->authattrs;
132                 regions[1].size = sinfo->authattrs_len;
133
134                 hash_calculate(sinfo->sig->hash_algo, regions, 2, sig->digest);
135
136                 ret = 0;
137         }
138 error:
139         return ret;
140 }
141 #else /* !__UBOOT__ */
142 static int pkcs7_digest(struct pkcs7_message *pkcs7,
143                         struct pkcs7_signed_info *sinfo)
144 {
145         struct public_key_signature *sig = sinfo->sig;
146         struct crypto_shash *tfm;
147         struct shash_desc *desc;
148         size_t desc_size;
149         int ret;
150
151         kenter(",%u,%s", sinfo->index, sinfo->sig->hash_algo);
152
153         /* The digest was calculated already. */
154         if (sig->digest)
155                 return 0;
156
157         if (!sinfo->sig->hash_algo)
158                 return -ENOPKG;
159
160         /* Allocate the hashing algorithm we're going to need and find out how
161          * big the hash operational data will be.
162          */
163         tfm = crypto_alloc_shash(sinfo->sig->hash_algo, 0, 0);
164         if (IS_ERR(tfm))
165                 return (PTR_ERR(tfm) == -ENOENT) ? -ENOPKG : PTR_ERR(tfm);
166
167         desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
168         sig->digest_size = crypto_shash_digestsize(tfm);
169
170         ret = -ENOMEM;
171         sig->digest = kmalloc(sig->digest_size, GFP_KERNEL);
172         if (!sig->digest)
173                 goto error_no_desc;
174
175         desc = kzalloc(desc_size, GFP_KERNEL);
176         if (!desc)
177                 goto error_no_desc;
178
179         desc->tfm   = tfm;
180
181         /* Digest the message [RFC2315 9.3] */
182         ret = crypto_shash_digest(desc, pkcs7->data, pkcs7->data_len,
183                                   sig->digest);
184         if (ret < 0)
185                 goto error;
186         pr_devel("MsgDigest = [%*ph]\n", 8, sig->digest);
187
188         /* However, if there are authenticated attributes, there must be a
189          * message digest attribute amongst them which corresponds to the
190          * digest we just calculated.
191          */
192         if (sinfo->authattrs) {
193                 u8 tag;
194
195                 if (!sinfo->msgdigest) {
196                         pr_warn("Sig %u: No messageDigest\n", sinfo->index);
197                         ret = -EKEYREJECTED;
198                         goto error;
199                 }
200
201                 if (sinfo->msgdigest_len != sig->digest_size) {
202                         pr_debug("Sig %u: Invalid digest size (%u)\n",
203                                  sinfo->index, sinfo->msgdigest_len);
204                         ret = -EBADMSG;
205                         goto error;
206                 }
207
208                 if (memcmp(sig->digest, sinfo->msgdigest,
209                            sinfo->msgdigest_len) != 0) {
210                         pr_debug("Sig %u: Message digest doesn't match\n",
211                                  sinfo->index);
212                         ret = -EKEYREJECTED;
213                         goto error;
214                 }
215
216                 /* We then calculate anew, using the authenticated attributes
217                  * as the contents of the digest instead.  Note that we need to
218                  * convert the attributes from a CONT.0 into a SET before we
219                  * hash it.
220                  */
221                 memset(sig->digest, 0, sig->digest_size);
222
223                 ret = crypto_shash_init(desc);
224                 if (ret < 0)
225                         goto error;
226                 tag = ASN1_CONS_BIT | ASN1_SET;
227                 ret = crypto_shash_update(desc, &tag, 1);
228                 if (ret < 0)
229                         goto error;
230                 ret = crypto_shash_finup(desc, sinfo->authattrs,
231                                          sinfo->authattrs_len, sig->digest);
232                 if (ret < 0)
233                         goto error;
234                 pr_devel("AADigest = [%*ph]\n", 8, sig->digest);
235         }
236
237 error:
238         kfree(desc);
239 error_no_desc:
240         crypto_free_shash(tfm);
241         kleave(" = %d", ret);
242         return ret;
243 }
244
245 int pkcs7_get_digest(struct pkcs7_message *pkcs7, const u8 **buf, u32 *len,
246                      enum hash_algo *hash_algo)
247 {
248         struct pkcs7_signed_info *sinfo = pkcs7->signed_infos;
249         int i, ret;
250
251         /*
252          * This function doesn't support messages with more than one signature.
253          */
254         if (sinfo == NULL || sinfo->next != NULL)
255                 return -EBADMSG;
256
257         ret = pkcs7_digest(pkcs7, sinfo);
258         if (ret)
259                 return ret;
260
261         *buf = sinfo->sig->digest;
262         *len = sinfo->sig->digest_size;
263
264         for (i = 0; i < HASH_ALGO__LAST; i++)
265                 if (!strcmp(hash_algo_name[i], sinfo->sig->hash_algo)) {
266                         *hash_algo = i;
267                         break;
268                 }
269
270         return 0;
271 }
272 #endif /* !__UBOOT__ */
273
274 /*
275  * Find the key (X.509 certificate) to use to verify a PKCS#7 message.  PKCS#7
276  * uses the issuer's name and the issuing certificate serial number for
277  * matching purposes.  These must match the certificate issuer's name (not
278  * subject's name) and the certificate serial number [RFC 2315 6.7].
279  */
280 static int pkcs7_find_key(struct pkcs7_message *pkcs7,
281                           struct pkcs7_signed_info *sinfo)
282 {
283         struct x509_certificate *x509;
284         unsigned certix = 1;
285
286         kenter("%u", sinfo->index);
287
288         for (x509 = pkcs7->certs; x509; x509 = x509->next, certix++) {
289                 /* I'm _assuming_ that the generator of the PKCS#7 message will
290                  * encode the fields from the X.509 cert in the same way in the
291                  * PKCS#7 message - but I can't be 100% sure of that.  It's
292                  * possible this will need element-by-element comparison.
293                  */
294                 if (!asymmetric_key_id_same(x509->id, sinfo->sig->auth_ids[0]))
295                         continue;
296                 pr_devel("Sig %u: Found cert serial match X.509[%u]\n",
297                          sinfo->index, certix);
298
299                 if (strcmp(x509->pub->pkey_algo, sinfo->sig->pkey_algo) != 0) {
300                         pr_warn("Sig %u: X.509 algo and PKCS#7 sig algo don't match\n",
301                                 sinfo->index);
302                         continue;
303                 }
304
305                 sinfo->signer = x509;
306                 return 0;
307         }
308
309         /* The relevant X.509 cert isn't found here, but it might be found in
310          * the trust keyring.
311          */
312         pr_debug("Sig %u: Issuing X.509 cert not found (#%*phN)\n",
313                  sinfo->index,
314                  sinfo->sig->auth_ids[0]->len, sinfo->sig->auth_ids[0]->data);
315         return 0;
316 }
317
318 /*
319  * pkcs7_verify_sig_chain - Verify the internal certificate chain as best
320  *                          as we can.
321  * @pkcs7:      PKCS7 Signed Data
322  * @sinfo:      PKCS7 Signed Info
323  * @signer:     Singer's certificate
324  *
325  * Build up and verify the internal certificate chain against a signature
326  * in @sinfo, using certificates contained in @pkcs7 as best as we can.
327  * If the chain reaches the end, the last certificate will be returned
328  * in @signer.
329  *
330  * Return:      0 - on success, non-zero error code - otherwise
331  */
332 #ifdef __UBOOT__
333 static int pkcs7_verify_sig_chain(struct pkcs7_message *pkcs7,
334                                   struct pkcs7_signed_info *sinfo,
335                                   struct x509_certificate **signer)
336 #else
337 static int pkcs7_verify_sig_chain(struct pkcs7_message *pkcs7,
338                                   struct pkcs7_signed_info *sinfo)
339 #endif
340 {
341         struct public_key_signature *sig;
342         struct x509_certificate *x509 = sinfo->signer, *p;
343         struct asymmetric_key_id *auth;
344         int ret;
345
346         kenter("");
347
348         *signer = NULL;
349
350         for (p = pkcs7->certs; p; p = p->next)
351                 p->seen = false;
352
353         for (;;) {
354                 pr_debug("verify %s: %*phN\n",
355                          x509->subject,
356                          x509->raw_serial_size, x509->raw_serial);
357                 x509->seen = true;
358
359                 if (x509->blacklisted) {
360                         /* If this cert is blacklisted, then mark everything
361                          * that depends on this as blacklisted too.
362                          */
363                         sinfo->blacklisted = true;
364                         for (p = sinfo->signer; p != x509; p = p->signer)
365                                 p->blacklisted = true;
366                         pr_debug("- blacklisted\n");
367 #ifdef __UBOOT__
368                         *signer = x509;
369 #endif
370                         return 0;
371                 }
372
373                 if (x509->unsupported_key)
374                         goto unsupported_crypto_in_x509;
375
376                 pr_debug("- issuer %s\n", x509->issuer);
377                 sig = x509->sig;
378                 if (sig->auth_ids[0])
379                         pr_debug("- authkeyid.id %*phN\n",
380                                  sig->auth_ids[0]->len, sig->auth_ids[0]->data);
381                 if (sig->auth_ids[1])
382                         pr_debug("- authkeyid.skid %*phN\n",
383                                  sig->auth_ids[1]->len, sig->auth_ids[1]->data);
384
385                 if (x509->self_signed) {
386                         /* If there's no authority certificate specified, then
387                          * the certificate must be self-signed and is the root
388                          * of the chain.  Likewise if the cert is its own
389                          * authority.
390                          */
391                         if (x509->unsupported_sig)
392                                 goto unsupported_crypto_in_x509;
393                         x509->signer = x509;
394                         pr_debug("- self-signed\n");
395 #ifdef __UBOOT__
396                         *signer = x509;
397 #endif
398                         return 0;
399                 }
400
401                 /* Look through the X.509 certificates in the PKCS#7 message's
402                  * list to see if the next one is there.
403                  */
404                 auth = sig->auth_ids[0];
405                 if (auth) {
406                         pr_debug("- want %*phN\n", auth->len, auth->data);
407                         for (p = pkcs7->certs; p; p = p->next) {
408                                 pr_debug("- cmp [%u] %*phN\n",
409                                          p->index, p->id->len, p->id->data);
410                                 if (asymmetric_key_id_same(p->id, auth))
411                                         goto found_issuer_check_skid;
412                         }
413                 } else if (sig->auth_ids[1]) {
414                         auth = sig->auth_ids[1];
415                         pr_debug("- want %*phN\n", auth->len, auth->data);
416                         for (p = pkcs7->certs; p; p = p->next) {
417                                 if (!p->skid)
418                                         continue;
419                                 pr_debug("- cmp [%u] %*phN\n",
420                                          p->index, p->skid->len, p->skid->data);
421                                 if (asymmetric_key_id_same(p->skid, auth))
422                                         goto found_issuer;
423                         }
424                 }
425
426                 /* We didn't find the root of this chain */
427                 pr_debug("- top\n");
428 #ifdef __UBOOT__
429                 *signer = x509;
430 #endif
431                 return 0;
432
433         found_issuer_check_skid:
434                 /* We matched issuer + serialNumber, but if there's an
435                  * authKeyId.keyId, that must match the CA subjKeyId also.
436                  */
437                 if (sig->auth_ids[1] &&
438                     !asymmetric_key_id_same(p->skid, sig->auth_ids[1])) {
439                         pr_warn("Sig %u: X.509 chain contains auth-skid nonmatch (%u->%u)\n",
440                                 sinfo->index, x509->index, p->index);
441                         return -EKEYREJECTED;
442                 }
443         found_issuer:
444                 pr_debug("- subject %s\n", p->subject);
445                 if (p->seen) {
446                         pr_warn("Sig %u: X.509 chain contains loop\n",
447                                 sinfo->index);
448 #ifdef __UBOOT__
449                         *signer = p;
450 #endif
451                         return 0;
452                 }
453                 ret = public_key_verify_signature(p->pub, x509->sig);
454                 if (ret < 0)
455                         return ret;
456                 x509->signer = p;
457                 if (x509 == p) {
458                         pr_debug("- self-signed\n");
459 #ifdef __UBOOT__
460                         *signer = p;
461 #endif
462                         return 0;
463                 }
464                 x509 = p;
465 #ifndef __UBOOT__
466                 might_sleep();
467 #endif
468         }
469
470 unsupported_crypto_in_x509:
471         /* Just prune the certificate chain at this point if we lack some
472          * crypto module to go further.  Note, however, we don't want to set
473          * sinfo->unsupported_crypto as the signed info block may still be
474          * validatable against an X.509 cert lower in the chain that we have a
475          * trusted copy of.
476          */
477         return 0;
478 }
479
480 /*
481  * pkcs7_verify_one - Verify one signed information block from a PKCS#7
482  *                    message.
483  * @pkcs7:      PKCS7 Signed Data
484  * @sinfo:      PKCS7 Signed Info
485  * @signer:     Signer's certificate
486  *
487  * Verify one signature in @sinfo and follow the certificate chain.
488  * If the chain reaches the end, the last certificate will be returned
489  * in @signer.
490  *
491  * Return:      0 - on success, non-zero error code - otherwise
492  */
493 #ifdef __UBOOT__
494 int pkcs7_verify_one(struct pkcs7_message *pkcs7,
495                      struct pkcs7_signed_info *sinfo,
496                      struct x509_certificate **signer)
497 #else
498 static int pkcs7_verify_one(struct pkcs7_message *pkcs7,
499                             struct pkcs7_signed_info *sinfo)
500 #endif
501 {
502         int ret;
503
504         kenter(",%u", sinfo->index);
505
506         /* First of all, digest the data in the PKCS#7 message and the
507          * signed information block
508          */
509         ret = pkcs7_digest(pkcs7, sinfo);
510         if (ret < 0)
511                 return ret;
512
513         /* Find the key for the signature if there is one */
514         ret = pkcs7_find_key(pkcs7, sinfo);
515         if (ret < 0)
516                 return ret;
517
518         if (!sinfo->signer)
519                 return 0;
520
521         pr_devel("Using X.509[%u] for sig %u\n",
522                  sinfo->signer->index, sinfo->index);
523
524         /* Check that the PKCS#7 signing time is valid according to the X.509
525          * certificate.  We can't, however, check against the system clock
526          * since that may not have been set yet and may be wrong.
527          */
528         if (test_bit(sinfo_has_signing_time, &sinfo->aa_set)) {
529                 if (sinfo->signing_time < sinfo->signer->valid_from ||
530                     sinfo->signing_time > sinfo->signer->valid_to) {
531                         pr_warn("Message signed outside of X.509 validity window\n");
532                         return -EKEYREJECTED;
533                 }
534         }
535
536         /* Verify the PKCS#7 binary against the key */
537         ret = public_key_verify_signature(sinfo->signer->pub, sinfo->sig);
538         if (ret < 0)
539                 return ret;
540
541         pr_devel("Verified signature %u\n", sinfo->index);
542
543         /* Verify the internal certificate chain */
544         return pkcs7_verify_sig_chain(pkcs7, sinfo, signer);
545 }
546
547 #ifndef __UBOOT__
548 /**
549  * pkcs7_verify - Verify a PKCS#7 message
550  * @pkcs7: The PKCS#7 message to be verified
551  * @usage: The use to which the key is being put
552  *
553  * Verify a PKCS#7 message is internally consistent - that is, the data digest
554  * matches the digest in the AuthAttrs and any signature in the message or one
555  * of the X.509 certificates it carries that matches another X.509 cert in the
556  * message can be verified.
557  *
558  * This does not look to match the contents of the PKCS#7 message against any
559  * external public keys.
560  *
561  * Returns, in order of descending priority:
562  *
563  *  (*) -EKEYREJECTED if a key was selected that had a usage restriction at
564  *      odds with the specified usage, or:
565  *
566  *  (*) -EKEYREJECTED if a signature failed to match for which we found an
567  *      appropriate X.509 certificate, or:
568  *
569  *  (*) -EBADMSG if some part of the message was invalid, or:
570  *
571  *  (*) 0 if a signature chain passed verification, or:
572  *
573  *  (*) -EKEYREJECTED if a blacklisted key was encountered, or:
574  *
575  *  (*) -ENOPKG if none of the signature chains are verifiable because suitable
576  *      crypto modules couldn't be found.
577  */
578 int pkcs7_verify(struct pkcs7_message *pkcs7,
579                  enum key_being_used_for usage)
580 {
581         struct pkcs7_signed_info *sinfo;
582         int actual_ret = -ENOPKG;
583         int ret;
584
585         kenter("");
586
587         switch (usage) {
588         case VERIFYING_MODULE_SIGNATURE:
589                 if (pkcs7->data_type != OID_data) {
590                         pr_warn("Invalid module sig (not pkcs7-data)\n");
591                         return -EKEYREJECTED;
592                 }
593                 if (pkcs7->have_authattrs) {
594                         pr_warn("Invalid module sig (has authattrs)\n");
595                         return -EKEYREJECTED;
596                 }
597                 break;
598         case VERIFYING_FIRMWARE_SIGNATURE:
599                 if (pkcs7->data_type != OID_data) {
600                         pr_warn("Invalid firmware sig (not pkcs7-data)\n");
601                         return -EKEYREJECTED;
602                 }
603                 if (!pkcs7->have_authattrs) {
604                         pr_warn("Invalid firmware sig (missing authattrs)\n");
605                         return -EKEYREJECTED;
606                 }
607                 break;
608         case VERIFYING_KEXEC_PE_SIGNATURE:
609                 if (pkcs7->data_type != OID_msIndirectData) {
610                         pr_warn("Invalid kexec sig (not Authenticode)\n");
611                         return -EKEYREJECTED;
612                 }
613                 /* Authattr presence checked in parser */
614                 break;
615         case VERIFYING_UNSPECIFIED_SIGNATURE:
616                 if (pkcs7->data_type != OID_data) {
617                         pr_warn("Invalid unspecified sig (not pkcs7-data)\n");
618                         return -EKEYREJECTED;
619                 }
620                 break;
621         default:
622                 return -EINVAL;
623         }
624
625         for (sinfo = pkcs7->signed_infos; sinfo; sinfo = sinfo->next) {
626                 ret = pkcs7_verify_one(pkcs7, sinfo);
627                 if (sinfo->blacklisted) {
628                         if (actual_ret == -ENOPKG)
629                                 actual_ret = -EKEYREJECTED;
630                         continue;
631                 }
632                 if (ret < 0) {
633                         if (ret == -ENOPKG) {
634                                 sinfo->unsupported_crypto = true;
635                                 continue;
636                         }
637                         kleave(" = %d", ret);
638                         return ret;
639                 }
640                 actual_ret = 0;
641         }
642
643         kleave(" = %d", actual_ret);
644         return actual_ret;
645 }
646 EXPORT_SYMBOL_GPL(pkcs7_verify);
647
648 /**
649  * pkcs7_supply_detached_data - Supply the data needed to verify a PKCS#7 message
650  * @pkcs7: The PKCS#7 message
651  * @data: The data to be verified
652  * @datalen: The amount of data
653  *
654  * Supply the detached data needed to verify a PKCS#7 message.  Note that no
655  * attempt to retain/pin the data is made.  That is left to the caller.  The
656  * data will not be modified by pkcs7_verify() and will not be freed when the
657  * PKCS#7 message is freed.
658  *
659  * Returns -EINVAL if data is already supplied in the message, 0 otherwise.
660  */
661 int pkcs7_supply_detached_data(struct pkcs7_message *pkcs7,
662                                const void *data, size_t datalen)
663 {
664         if (pkcs7->data) {
665                 pr_debug("Data already supplied\n");
666                 return -EINVAL;
667         }
668         pkcs7->data = data;
669         pkcs7->data_len = datalen;
670         return 0;
671 }
672 #endif /* __UBOOT__ */