]> Git Repo - u-boot.git/blob - lib/rsa/rsa-verify.c
Merge branch 'master' of https://source.denx.de/u-boot/custodians/u-boot-sh
[u-boot.git] / lib / rsa / rsa-verify.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2013, Google Inc.
4  */
5
6 #ifndef USE_HOSTCC
7 #include <fdtdec.h>
8 #include <log.h>
9 #include <malloc.h>
10 #include <asm/types.h>
11 #include <asm/byteorder.h>
12 #include <linux/errno.h>
13 #include <asm/types.h>
14 #include <asm/unaligned.h>
15 #include <dm.h>
16 #else
17 #include "fdt_host.h"
18 #include "mkimage.h"
19 #include <linux/kconfig.h>
20 #include <fdt_support.h>
21 #endif
22 #include <u-boot/rsa-mod-exp.h>
23 #include <u-boot/rsa.h>
24
25 /* Default public exponent for backward compatibility */
26 #define RSA_DEFAULT_PUBEXP      65537
27
28 /**
29  * rsa_verify_padding() - Verify RSA message padding is valid
30  *
31  * Verify a RSA message's padding is consistent with PKCS1.5
32  * padding as described in the RSA PKCS#1 v2.1 standard.
33  *
34  * @msg:        Padded message
35  * @pad_len:    Number of expected padding bytes
36  * @algo:       Checksum algo structure having information on DER encoding etc.
37  * Return: 0 on success, != 0 on failure
38  */
39 static int rsa_verify_padding(const uint8_t *msg, const int pad_len,
40                               struct checksum_algo *algo)
41 {
42         int ff_len;
43         int ret;
44
45         /* first byte must be 0x00 */
46         ret = *msg++;
47         /* second byte must be 0x01 */
48         ret |= *msg++ ^ 0x01;
49         /* next ff_len bytes must be 0xff */
50         ff_len = pad_len - algo->der_len - 3;
51         ret |= *msg ^ 0xff;
52         ret |= memcmp(msg, msg+1, ff_len-1);
53         msg += ff_len;
54         /* next byte must be 0x00 */
55         ret |= *msg++;
56         /* next der_len bytes must match der_prefix */
57         ret |= memcmp(msg, algo->der_prefix, algo->der_len);
58
59         return ret;
60 }
61
62 int padding_pkcs_15_verify(struct image_sign_info *info,
63                            const uint8_t *msg, int msg_len,
64                            const uint8_t *hash, int hash_len)
65 {
66         struct checksum_algo *checksum = info->checksum;
67         int ret, pad_len = msg_len - checksum->checksum_len;
68
69         /* Check pkcs1.5 padding bytes */
70         ret = rsa_verify_padding(msg, pad_len, checksum);
71         if (ret) {
72                 debug("In RSAVerify(): Padding check failed!\n");
73                 return -EINVAL;
74         }
75
76         /* Check hash */
77         if (memcmp((uint8_t *)msg + pad_len, hash, msg_len - pad_len)) {
78                 debug("In RSAVerify(): Hash check failed!\n");
79                 return -EACCES;
80         }
81
82         return 0;
83 }
84
85 #ifndef USE_HOSTCC
86 U_BOOT_PADDING_ALGO(pkcs_15) = {
87         .name = "pkcs-1.5",
88         .verify = padding_pkcs_15_verify,
89 };
90 #endif
91
92 #if CONFIG_IS_ENABLED(FIT_RSASSA_PSS)
93 static void u32_i2osp(uint32_t val, uint8_t *buf)
94 {
95         buf[0] = (uint8_t)((val >> 24) & 0xff);
96         buf[1] = (uint8_t)((val >> 16) & 0xff);
97         buf[2] = (uint8_t)((val >>  8) & 0xff);
98         buf[3] = (uint8_t)((val >>  0) & 0xff);
99 }
100
101 /**
102  * mask_generation_function1() - generate an octet string
103  *
104  * Generate an octet string used to check rsa signature.
105  * It use an input octet string and a hash function.
106  *
107  * @checksum:   A Hash function
108  * @seed:       Specifies an input variable octet string
109  * @seed_len:   Size of the input octet string
110  * @output:     Specifies the output octet string
111  * @output_len: Size of the output octet string
112  * Return: 0 if the octet string was correctly generated, others on error
113  */
114 static int mask_generation_function1(struct checksum_algo *checksum,
115                                      const uint8_t *seed, int seed_len,
116                                      uint8_t *output, int output_len)
117 {
118         struct image_region region[2];
119         int ret = 0, i, i_output = 0, region_count = 2;
120         uint32_t counter = 0;
121         uint8_t buf_counter[4], *tmp;
122         int hash_len = checksum->checksum_len;
123
124         memset(output, 0, output_len);
125
126         region[0].data = seed;
127         region[0].size = seed_len;
128         region[1].data = &buf_counter[0];
129         region[1].size = 4;
130
131         tmp = malloc(hash_len);
132         if (!tmp) {
133                 debug("%s: can't allocate array tmp\n", __func__);
134                 ret = -ENOMEM;
135                 goto out;
136         }
137
138         while (i_output < output_len) {
139                 u32_i2osp(counter, &buf_counter[0]);
140
141                 ret = checksum->calculate(checksum->name,
142                                           region, region_count,
143                                           tmp);
144                 if (ret < 0) {
145                         debug("%s: Error in checksum calculation\n", __func__);
146                         goto out;
147                 }
148
149                 i = 0;
150                 while ((i_output < output_len) && (i < hash_len)) {
151                         output[i_output] = tmp[i];
152                         i_output++;
153                         i++;
154                 }
155
156                 counter++;
157         }
158
159 out:
160         free(tmp);
161
162         return ret;
163 }
164
165 static int compute_hash_prime(struct checksum_algo *checksum,
166                               const uint8_t *pad, int pad_len,
167                               const uint8_t *hash, int hash_len,
168                               const uint8_t *salt, int salt_len,
169                               uint8_t *hprime)
170 {
171         struct image_region region[3];
172         int ret, region_count = 3;
173
174         region[0].data = pad;
175         region[0].size = pad_len;
176         region[1].data = hash;
177         region[1].size = hash_len;
178         region[2].data = salt;
179         region[2].size = salt_len;
180
181         ret = checksum->calculate(checksum->name, region, region_count, hprime);
182         if (ret < 0) {
183                 debug("%s: Error in checksum calculation\n", __func__);
184                 goto out;
185         }
186
187 out:
188         return ret;
189 }
190
191 /*
192  * padding_pss_verify() - verify the pss padding of a signature
193  *
194  * Works with any salt length
195  *
196  * msg is a concatenation of : masked_db + h + 0xbc
197  * Once unmasked, db is a concatenation of : [0x00]* + 0x01 + salt
198  * Length of 0-padding at begin of db depends on salt length.
199  *
200  * @info:       Specifies key and FIT information
201  * @msg:        byte array of message, len equal to msg_len
202  * @msg_len:    Message length
203  * @hash:       Pointer to the expected hash
204  * @hash_len:   Length of the hash
205  *
206  * Return:      0 if padding is correct, non-zero otherwise
207  */
208 int padding_pss_verify(struct image_sign_info *info,
209                        const uint8_t *msg, int msg_len,
210                        const uint8_t *hash, int hash_len)
211 {
212         const uint8_t *masked_db = NULL;
213         uint8_t *db_mask = NULL;
214         uint8_t *db = NULL;
215         int db_len = msg_len - hash_len - 1;
216         const uint8_t *h = NULL;
217         uint8_t *hprime = NULL;
218         int h_len = hash_len;
219         uint8_t *db_nopad = NULL, *salt = NULL;
220         int db_padlen, salt_len;
221         uint8_t pad_zero[8] = { 0 };
222         int ret, i, leftmost_bits = 1;
223         uint8_t leftmost_mask;
224         struct checksum_algo *checksum = info->checksum;
225
226         if (db_len <= 0)
227                 return -EINVAL;
228
229         /* first, allocate everything */
230         db_mask = malloc(db_len);
231         db = malloc(db_len);
232         hprime = malloc(hash_len);
233         if (!db_mask || !db || !hprime) {
234                 printf("%s: can't allocate some buffer\n", __func__);
235                 ret = -ENOMEM;
236                 goto out;
237         }
238
239         /* step 4: check if the last byte is 0xbc */
240         if (msg[msg_len - 1] != 0xbc) {
241                 printf("%s: invalid pss padding (0xbc is missing)\n", __func__);
242                 ret = -EINVAL;
243                 goto out;
244         }
245
246         /* step 5 */
247         masked_db = &msg[0];
248         h = &msg[db_len];
249
250         /* step 6 */
251         leftmost_mask = (0xff >> (8 - leftmost_bits)) << (8 - leftmost_bits);
252         if (masked_db[0] & leftmost_mask) {
253                 printf("%s: invalid pss padding ", __func__);
254                 printf("(leftmost bit of maskedDB not zero)\n");
255                 ret = -EINVAL;
256                 goto out;
257         }
258
259         /* step 7 */
260         mask_generation_function1(checksum, h, h_len, db_mask, db_len);
261
262         /* step 8 */
263         for (i = 0; i < db_len; i++)
264                 db[i] = masked_db[i] ^ db_mask[i];
265
266         /* step 9 */
267         db[0] &= 0xff >> leftmost_bits;
268
269         /* step 10 */
270         db_padlen = 0;
271         while (db[db_padlen] == 0x00 && db_padlen < (db_len - 1))
272                 db_padlen++;
273         db_nopad = &db[db_padlen];
274         if (db_nopad[0] != 0x01) {
275                 printf("%s: invalid pss padding ", __func__);
276                 printf("(leftmost byte of db after 0-padding isn't 0x01)\n");
277                 ret = EINVAL;
278                 goto out;
279         }
280
281         /* step 11 */
282         salt_len = db_len - db_padlen - 1;
283         salt = &db_nopad[1];
284
285         /* step 12 & 13 */
286         compute_hash_prime(checksum, pad_zero, 8,
287                            hash, hash_len,
288                            salt, salt_len, hprime);
289
290         /* step 14 */
291         ret = memcmp(h, hprime, hash_len);
292
293 out:
294         free(hprime);
295         free(db);
296         free(db_mask);
297
298         return ret;
299 }
300
301 #ifndef USE_HOSTCC
302 U_BOOT_PADDING_ALGO(pss) = {
303         .name = "pss",
304         .verify = padding_pss_verify,
305 };
306 #endif
307
308 #endif
309
310 /**
311  * rsa_verify_key() - Verify a signature against some data using RSA Key
312  *
313  * Verify a RSA PKCS1.5 signature against an expected hash using
314  * the RSA Key properties in prop structure.
315  *
316  * @info:       Specifies key and FIT information
317  * @prop:       Specifies key
318  * @sig:        Signature
319  * @sig_len:    Number of bytes in signature
320  * @hash:       Pointer to the expected hash
321  * @key_len:    Number of bytes in rsa key
322  * Return: 0 if verified, -ve on error
323  */
324 static int rsa_verify_key(struct image_sign_info *info,
325                           struct key_prop *prop, const uint8_t *sig,
326                           const uint32_t sig_len, const uint8_t *hash,
327                           const uint32_t key_len)
328 {
329         int ret;
330 #if !defined(USE_HOSTCC)
331         struct udevice *mod_exp_dev;
332 #endif
333         struct checksum_algo *checksum = info->checksum;
334         struct padding_algo *padding = info->padding;
335         int hash_len;
336
337         if (!prop || !sig || !hash || !checksum || !padding)
338                 return -EIO;
339
340         if (sig_len != (prop->num_bits / 8)) {
341                 debug("Signature is of incorrect length %d\n", sig_len);
342                 return -EINVAL;
343         }
344
345         debug("Checksum algorithm: %s\n", checksum->name);
346
347         /* Sanity check for stack size */
348         if (sig_len > RSA_MAX_SIG_BITS / 8) {
349                 debug("Signature length %u exceeds maximum %d\n", sig_len,
350                       RSA_MAX_SIG_BITS / 8);
351                 return -EINVAL;
352         }
353
354         uint8_t buf[sig_len];
355         hash_len = checksum->checksum_len;
356
357 #if !defined(USE_HOSTCC)
358         ret = uclass_get_device(UCLASS_MOD_EXP, 0, &mod_exp_dev);
359         if (ret) {
360                 printf("RSA: Can't find Modular Exp implementation\n");
361                 return -EINVAL;
362         }
363
364         ret = rsa_mod_exp(mod_exp_dev, sig, sig_len, prop, buf);
365 #else
366         ret = rsa_mod_exp_sw(sig, sig_len, prop, buf);
367 #endif
368         if (ret) {
369                 debug("Error in Modular exponentation\n");
370                 return ret;
371         }
372
373         ret = padding->verify(info, buf, key_len, hash, hash_len);
374         if (ret) {
375                 debug("In RSAVerify(): padding check failed!\n");
376                 return ret;
377         }
378
379         return 0;
380 }
381
382 /**
383  * rsa_verify_with_pkey() - Verify a signature against some data using
384  * only modulus and exponent as RSA key properties.
385  * @info:       Specifies key information
386  * @hash:       Pointer to the expected hash
387  * @sig:        Signature
388  * @sig_len:    Number of bytes in signature
389  *
390  * Parse a RSA public key blob in DER format pointed to in @info and fill
391  * a key_prop structure with properties of the key. Then verify a RSA PKCS1.5
392  * signature against an expected hash using the calculated properties.
393  *
394  * Return       0 if verified, -ve on error
395  */
396 int rsa_verify_with_pkey(struct image_sign_info *info,
397                          const void *hash, uint8_t *sig, uint sig_len)
398 {
399         struct key_prop *prop;
400         int ret;
401
402         if (!CONFIG_IS_ENABLED(RSA_VERIFY_WITH_PKEY))
403                 return -EACCES;
404
405         /* Public key is self-described to fill key_prop */
406         ret = rsa_gen_key_prop(info->key, info->keylen, &prop);
407         if (ret) {
408                 debug("Generating necessary parameter for decoding failed\n");
409                 return ret;
410         }
411
412         ret = rsa_verify_key(info, prop, sig, sig_len, hash,
413                              info->crypto->key_len);
414
415         rsa_free_key_prop(prop);
416
417         return ret;
418 }
419
420 #if CONFIG_IS_ENABLED(FIT_SIGNATURE)
421 /**
422  * rsa_verify_with_keynode() - Verify a signature against some data using
423  * information in node with prperties of RSA Key like modulus, exponent etc.
424  *
425  * Parse sign-node and fill a key_prop structure with properties of the
426  * key.  Verify a RSA PKCS1.5 signature against an expected hash using
427  * the properties parsed
428  *
429  * @info:       Specifies key and FIT information
430  * @hash:       Pointer to the expected hash
431  * @sig:        Signature
432  * @sig_len:    Number of bytes in signature
433  * @node:       Node having the RSA Key properties
434  * Return: 0 if verified, -ve on error
435  */
436 static int rsa_verify_with_keynode(struct image_sign_info *info,
437                                    const void *hash, uint8_t *sig,
438                                    uint sig_len, int node)
439 {
440         const void *blob = info->fdt_blob;
441         struct key_prop prop;
442         int length;
443         int ret = 0;
444         const char *algo;
445
446         if (node < 0) {
447                 debug("%s: Skipping invalid node\n", __func__);
448                 return -EBADF;
449         }
450
451         algo = fdt_getprop(blob, node, "algo", NULL);
452         if (strcmp(info->name, algo)) {
453                 debug("%s: Wrong algo: have %s, expected %s\n", __func__,
454                       info->name, algo);
455                 return -EFAULT;
456         }
457
458         prop.num_bits = fdtdec_get_int(blob, node, "rsa,num-bits", 0);
459
460         prop.n0inv = fdtdec_get_int(blob, node, "rsa,n0-inverse", 0);
461
462         prop.public_exponent = fdt_getprop(blob, node, "rsa,exponent", &length);
463         if (!prop.public_exponent || length < sizeof(uint64_t))
464                 prop.public_exponent = NULL;
465
466         prop.exp_len = sizeof(uint64_t);
467
468         prop.modulus = fdt_getprop(blob, node, "rsa,modulus", NULL);
469
470         prop.rr = fdt_getprop(blob, node, "rsa,r-squared", NULL);
471
472         if (!prop.num_bits || !prop.modulus || !prop.rr) {
473                 debug("%s: Missing RSA key info\n", __func__);
474                 return -EFAULT;
475         }
476
477         ret = rsa_verify_key(info, &prop, sig, sig_len, hash,
478                              info->crypto->key_len);
479
480         return ret;
481 }
482 #else
483 static int rsa_verify_with_keynode(struct image_sign_info *info,
484                                    const void *hash, uint8_t *sig,
485                                    uint sig_len, int node)
486 {
487         return -EACCES;
488 }
489 #endif
490
491 int rsa_verify_hash(struct image_sign_info *info,
492                     const uint8_t *hash, uint8_t *sig, uint sig_len)
493 {
494         int ret = -EACCES;
495
496         /*
497          * Since host tools, like mkimage, make use of openssl library for
498          * RSA encryption, rsa_verify_with_pkey()/rsa_gen_key_prop() are
499          * of no use and should not be compiled in.
500          */
501         if (!tools_build() && CONFIG_IS_ENABLED(RSA_VERIFY_WITH_PKEY) &&
502                         !info->fdt_blob) {
503                 /* don't rely on fdt properties */
504                 ret = rsa_verify_with_pkey(info, hash, sig, sig_len);
505                 if (ret)
506                         debug("%s: rsa_verify_with_pkey() failed\n", __func__);
507                 return ret;
508         }
509
510         if (CONFIG_IS_ENABLED(FIT_SIGNATURE)) {
511                 const void *blob = info->fdt_blob;
512                 int ndepth, noffset;
513                 int sig_node, node;
514                 char name[100];
515
516                 sig_node = fdt_subnode_offset(blob, 0, FIT_SIG_NODENAME);
517                 if (sig_node < 0) {
518                         debug("%s: No signature node found\n", __func__);
519                         return -ENOENT;
520                 }
521
522                 /* See if we must use a particular key */
523                 if (info->required_keynode != -1) {
524                         ret = rsa_verify_with_keynode(info, hash, sig, sig_len,
525                                                       info->required_keynode);
526                         if (ret)
527                                 debug("%s: Failed to verify required_keynode\n",
528                                       __func__);
529                         return ret;
530                 }
531
532                 /* Look for a key that matches our hint */
533                 snprintf(name, sizeof(name), "key-%s", info->keyname);
534                 node = fdt_subnode_offset(blob, sig_node, name);
535                 ret = rsa_verify_with_keynode(info, hash, sig, sig_len, node);
536                 if (!ret)
537                         return ret;
538                 debug("%s: Could not verify key '%s', trying all\n", __func__,
539                       name);
540
541                 /* No luck, so try each of the keys in turn */
542                 for (ndepth = 0, noffset = fdt_next_node(blob, sig_node,
543                                                          &ndepth);
544                      (noffset >= 0) && (ndepth > 0);
545                      noffset = fdt_next_node(blob, noffset, &ndepth)) {
546                         if (ndepth == 1 && noffset != node) {
547                                 ret = rsa_verify_with_keynode(info, hash,
548                                                               sig, sig_len,
549                                                               noffset);
550                                 if (!ret)
551                                         break;
552                         }
553                 }
554         }
555         debug("%s: Failed to verify by any means\n", __func__);
556
557         return ret;
558 }
559
560 int rsa_verify(struct image_sign_info *info,
561                const struct image_region region[], int region_count,
562                uint8_t *sig, uint sig_len)
563 {
564         /* Reserve memory for maximum checksum-length */
565         uint8_t hash[info->crypto->key_len];
566         int ret;
567
568         /*
569          * Verify that the checksum-length does not exceed the
570          * rsa-signature-length
571          */
572         if (info->checksum->checksum_len >
573             info->crypto->key_len) {
574                 debug("%s: invalid checksum-algorithm %s for %s\n",
575                       __func__, info->checksum->name, info->crypto->name);
576                 return -EINVAL;
577         }
578
579         /* Calculate checksum with checksum-algorithm */
580         ret = info->checksum->calculate(info->checksum->name,
581                                         region, region_count, hash);
582         if (ret < 0) {
583                 debug("%s: Error in checksum calculation\n", __func__);
584                 return -EINVAL;
585         }
586
587         return rsa_verify_hash(info, hash, sig, sig_len);
588 }
589
590 #ifndef USE_HOSTCC
591
592 U_BOOT_CRYPTO_ALGO(rsa2048) = {
593         .name = "rsa2048",
594         .key_len = RSA2048_BYTES,
595         .verify = rsa_verify,
596 };
597
598 U_BOOT_CRYPTO_ALGO(rsa3072) = {
599         .name = "rsa3072",
600         .key_len = RSA3072_BYTES,
601         .verify = rsa_verify,
602 };
603
604 U_BOOT_CRYPTO_ALGO(rsa4096) = {
605         .name = "rsa4096",
606         .key_len = RSA4096_BYTES,
607         .verify = rsa_verify,
608 };
609
610 #endif
This page took 0.069093 seconds and 4 git commands to generate.