mmc: mediatek: add support for MediaTek MT7621 SoC
[platform/kernel/u-boot.git] / tools / sunxi_toc0.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2018 Arm Ltd.
4  * (C) Copyright 2020-2021 Samuel Holland <samuel@sholland.org>
5  */
6
7 #define OPENSSL_API_COMPAT 0x10101000L
8
9 #include <assert.h>
10 #include <stdint.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14
15 #include <openssl/asn1t.h>
16 #include <openssl/bn.h>
17 #include <openssl/pem.h>
18 #include <openssl/rsa.h>
19
20 #include <image.h>
21 #include <sunxi_image.h>
22
23 #include "imagetool.h"
24 #include "mkimage.h"
25
26 /*
27  * NAND requires 8K padding. For other devices, BROM requires only
28  * 512B padding, but let's use the larger padding to cover everything.
29  */
30 #define PAD_SIZE                8192
31
32 #define pr_fmt(fmt)             "mkimage (TOC0): %s: " fmt
33 #define pr_err(fmt, args...)    fprintf(stderr, pr_fmt(fmt), "error", ##args)
34 #define pr_warn(fmt, args...)   fprintf(stderr, pr_fmt(fmt), "warning", ##args)
35 #define pr_info(fmt, args...)   fprintf(stderr, pr_fmt(fmt), "info", ##args)
36
37 struct __packed toc0_key_item {
38         __le32  vendor_id;
39         __le32  key0_n_len;
40         __le32  key0_e_len;
41         __le32  key1_n_len;
42         __le32  key1_e_len;
43         __le32  sig_len;
44         uint8_t key0[512];
45         uint8_t key1[512];
46         uint8_t reserved[32];
47         uint8_t sig[256];
48 };
49
50 /*
51  * This looks somewhat like an X.509 certificate, but it is not valid BER.
52  *
53  * Some differences:
54  *  - Some X.509 certificate fields are missing or rearranged.
55  *  - Some sequences have the wrong tag.
56  *  - Zero-length sequences are accepted.
57  *  - Large strings and integers must be an even number of bytes long.
58  *  - Positive integers are not zero-extended to maintain their sign.
59  *
60  * See https://linux-sunxi.org/TOC0 for more information.
61  */
62 struct __packed toc0_small_tag {
63         uint8_t tag;
64         uint8_t length;
65 };
66
67 typedef struct toc0_small_tag toc0_small_int;
68 typedef struct toc0_small_tag toc0_small_oct;
69 typedef struct toc0_small_tag toc0_small_seq;
70 typedef struct toc0_small_tag toc0_small_exp;
71
72 #define TOC0_SMALL_INT(len) { 0x02, (len) }
73 #define TOC0_SMALL_SEQ(len) { 0x30, (len) }
74 #define TOC0_SMALL_EXP(tag, len) { 0xa0 | (tag), len }
75
76 struct __packed toc0_large_tag {
77         uint8_t tag;
78         uint8_t prefix;
79         uint8_t length_hi;
80         uint8_t length_lo;
81 };
82
83 typedef struct toc0_large_tag toc0_large_int;
84 typedef struct toc0_large_tag toc0_large_bit;
85 typedef struct toc0_large_tag toc0_large_seq;
86
87 #define TOC0_LARGE_INT(len) { 0x02, 0x82, (len) >> 8, (len) & 0xff }
88 #define TOC0_LARGE_BIT(len) { 0x03, 0x82, (len) >> 8, (len) & 0xff }
89 #define TOC0_LARGE_SEQ(len) { 0x30, 0x82, (len) >> 8, (len) & 0xff }
90
91 struct __packed toc0_cert_item {
92         toc0_large_seq tag_totalSequence;
93         struct __packed toc0_totalSequence {
94                 toc0_large_seq tag_mainSequence;
95                 struct __packed toc0_mainSequence {
96                         toc0_small_exp tag_explicit0;
97                         struct __packed toc0_explicit0 {
98                                 toc0_small_int tag_version;
99                                 uint8_t version;
100                         } explicit0;
101                         toc0_small_int tag_serialNumber;
102                         uint8_t serialNumber;
103                         toc0_small_seq tag_signature;
104                         toc0_small_seq tag_issuer;
105                         toc0_small_seq tag_validity;
106                         toc0_small_seq tag_subject;
107                         toc0_large_seq tag_subjectPublicKeyInfo;
108                         struct __packed toc0_subjectPublicKeyInfo {
109                                 toc0_small_seq tag_algorithm;
110                                 toc0_large_seq tag_publicKey;
111                                 struct __packed toc0_publicKey {
112                                         toc0_large_int tag_n;
113                                         uint8_t n[256];
114                                         toc0_small_int tag_e;
115                                         uint8_t e[3];
116                                 } publicKey;
117                         } subjectPublicKeyInfo;
118                         toc0_small_exp tag_explicit3;
119                         struct __packed toc0_explicit3 {
120                                 toc0_small_seq tag_extension;
121                                 struct __packed toc0_extension {
122                                         toc0_small_int tag_digest;
123                                         uint8_t digest[32];
124                                 } extension;
125                         } explicit3;
126                 } mainSequence;
127                 toc0_large_bit tag_sigSequence;
128                 struct __packed toc0_sigSequence {
129                         toc0_small_seq tag_algorithm;
130                         toc0_large_bit tag_signature;
131                         uint8_t signature[256];
132                 } sigSequence;
133         } totalSequence;
134 };
135
136 #define sizeof_field(TYPE, MEMBER) sizeof((((TYPE *)0)->MEMBER))
137
138 static const struct toc0_cert_item cert_item_template = {
139         TOC0_LARGE_SEQ(sizeof(struct toc0_totalSequence)),
140         {
141                 TOC0_LARGE_SEQ(sizeof(struct toc0_mainSequence)),
142                 {
143                         TOC0_SMALL_EXP(0, sizeof(struct toc0_explicit0)),
144                         {
145                                 TOC0_SMALL_INT(sizeof_field(struct toc0_explicit0, version)),
146                                 0,
147                         },
148                         TOC0_SMALL_INT(sizeof_field(struct toc0_mainSequence, serialNumber)),
149                         0,
150                         TOC0_SMALL_SEQ(0),
151                         TOC0_SMALL_SEQ(0),
152                         TOC0_SMALL_SEQ(0),
153                         TOC0_SMALL_SEQ(0),
154                         TOC0_LARGE_SEQ(sizeof(struct toc0_subjectPublicKeyInfo)),
155                         {
156                                 TOC0_SMALL_SEQ(0),
157                                 TOC0_LARGE_SEQ(sizeof(struct toc0_publicKey)),
158                                 {
159                                         TOC0_LARGE_INT(sizeof_field(struct toc0_publicKey, n)),
160                                         {},
161                                         TOC0_SMALL_INT(sizeof_field(struct toc0_publicKey, e)),
162                                         {},
163                                 },
164                         },
165                         TOC0_SMALL_EXP(3, sizeof(struct toc0_explicit3)),
166                         {
167                                 TOC0_SMALL_SEQ(sizeof(struct toc0_extension)),
168                                 {
169                                         TOC0_SMALL_INT(sizeof_field(struct toc0_extension, digest)),
170                                         {},
171                                 },
172                         },
173                 },
174                 TOC0_LARGE_BIT(sizeof(struct toc0_sigSequence)),
175                 {
176                         TOC0_SMALL_SEQ(0),
177                         TOC0_LARGE_BIT(sizeof_field(struct toc0_sigSequence, signature)),
178                         {},
179                 },
180         },
181 };
182
183 #define TOC0_DEFAULT_NUM_ITEMS          3
184 #define TOC0_DEFAULT_HEADER_LEN                                           \
185         ALIGN(                                                            \
186                 sizeof(struct toc0_main_info)                           + \
187                 sizeof(struct toc0_item_info) * TOC0_DEFAULT_NUM_ITEMS  + \
188                 sizeof(struct toc0_cert_item)                           + \
189                 sizeof(struct toc0_key_item),                             \
190         32)
191
192 static char *fw_key_file   = "fw_key.pem";
193 static char *key_item_file = "key_item.bin";
194 static char *root_key_file = "root_key.pem";
195
196 /*
197  * Create a key item in @buf, containing the public keys @root_key and @fw_key,
198  * and signed by the RSA key @root_key.
199  */
200 static int toc0_create_key_item(uint8_t *buf, uint32_t *len,
201                                 RSA *root_key, RSA *fw_key)
202 {
203         struct toc0_key_item *key_item = (void *)buf;
204         uint8_t digest[SHA256_DIGEST_LENGTH];
205         int ret = EXIT_FAILURE;
206         unsigned int sig_len;
207         int n_len, e_len;
208
209         /* Store key 0. */
210         n_len = BN_bn2bin(RSA_get0_n(root_key), key_item->key0);
211         e_len = BN_bn2bin(RSA_get0_e(root_key), key_item->key0 + n_len);
212         if (n_len + e_len > sizeof(key_item->key0)) {
213                 pr_err("Root key is too big for key item\n");
214                 goto err;
215         }
216         key_item->key0_n_len = cpu_to_le32(n_len);
217         key_item->key0_e_len = cpu_to_le32(e_len);
218
219         /* Store key 1. */
220         n_len = BN_bn2bin(RSA_get0_n(fw_key), key_item->key1);
221         e_len = BN_bn2bin(RSA_get0_e(fw_key), key_item->key1 + n_len);
222         if (n_len + e_len > sizeof(key_item->key1)) {
223                 pr_err("Firmware key is too big for key item\n");
224                 goto err;
225         }
226         key_item->key1_n_len = cpu_to_le32(n_len);
227         key_item->key1_e_len = cpu_to_le32(e_len);
228
229         /* Sign the key item. */
230         key_item->sig_len = cpu_to_le32(RSA_size(root_key));
231         SHA256(buf, key_item->sig - buf, digest);
232         if (!RSA_sign(NID_sha256, digest, sizeof(digest),
233                       key_item->sig, &sig_len, root_key)) {
234                 pr_err("Failed to sign key item\n");
235                 goto err;
236         }
237         if (sig_len != sizeof(key_item->sig)) {
238                 pr_err("Bad key item signature length\n");
239                 goto err;
240         }
241
242         *len = sizeof(*key_item);
243         ret = EXIT_SUCCESS;
244
245 err:
246         return ret;
247 }
248
249 /*
250  * Verify the key item in @buf, containing two public keys @key0 and @key1,
251  * and signed by the RSA key @key0. If @root_key is provided, only signatures
252  * by that key will be accepted. @key1 is returned in @key.
253  */
254 static int toc0_verify_key_item(const uint8_t *buf, uint32_t len,
255                                 RSA *root_key, RSA **fw_key)
256 {
257         struct toc0_key_item *key_item = (void *)buf;
258         uint8_t digest[SHA256_DIGEST_LENGTH];
259         int ret = EXIT_FAILURE;
260         int n_len, e_len;
261         RSA *key0 = NULL;
262         RSA *key1 = NULL;
263         BIGNUM *n, *e;
264
265         if (len < sizeof(*key_item))
266                 goto err;
267
268         /* Load key 0. */
269         n_len = le32_to_cpu(key_item->key0_n_len);
270         e_len = le32_to_cpu(key_item->key0_e_len);
271         if (n_len + e_len > sizeof(key_item->key0)) {
272                 pr_err("Bad root key size in key item\n");
273                 goto err;
274         }
275         n = BN_bin2bn(key_item->key0, n_len, NULL);
276         e = BN_bin2bn(key_item->key0 + n_len, e_len, NULL);
277         key0 = RSA_new();
278         if (!key0)
279                 goto err;
280         if (!RSA_set0_key(key0, n, e, NULL))
281                 goto err;
282
283         /* If a root key was provided, compare it to key 0. */
284         if (root_key && (BN_cmp(n, RSA_get0_n(root_key)) ||
285                          BN_cmp(e, RSA_get0_e(root_key)))) {
286                 pr_err("Wrong root key in key item\n");
287                 goto err;
288         }
289
290         /* Verify the key item signature. */
291         SHA256(buf, key_item->sig - buf, digest);
292         if (!RSA_verify(NID_sha256, digest, sizeof(digest),
293                         key_item->sig, le32_to_cpu(key_item->sig_len), key0)) {
294                 pr_err("Bad key item signature\n");
295                 goto err;
296         }
297
298         if (fw_key) {
299                 /* Load key 1. */
300                 n_len = le32_to_cpu(key_item->key1_n_len);
301                 e_len = le32_to_cpu(key_item->key1_e_len);
302                 if (n_len + e_len > sizeof(key_item->key1)) {
303                         pr_err("Bad firmware key size in key item\n");
304                         goto err;
305                 }
306                 n = BN_bin2bn(key_item->key1, n_len, NULL);
307                 e = BN_bin2bn(key_item->key1 + n_len, e_len, NULL);
308                 key1 = RSA_new();
309                 if (!key1)
310                         goto err;
311                 if (!RSA_set0_key(key1, n, e, NULL))
312                         goto err;
313
314                 if (*fw_key) {
315                         /* If a FW key was provided, compare it to key 1. */
316                         if (BN_cmp(n, RSA_get0_n(*fw_key)) ||
317                             BN_cmp(e, RSA_get0_e(*fw_key))) {
318                                 pr_err("Wrong firmware key in key item\n");
319                                 goto err;
320                         }
321                 } else {
322                         /* Otherwise, send key1 back to the caller. */
323                         *fw_key = key1;
324                         key1 = NULL;
325                 }
326         }
327
328         ret = EXIT_SUCCESS;
329
330 err:
331         RSA_free(key0);
332         RSA_free(key1);
333
334         return ret;
335 }
336
337 /*
338  * Create a certificate in @buf, describing the firmware with SHA256 digest
339  * @digest, and signed by the RSA key @fw_key.
340  */
341 static int toc0_create_cert_item(uint8_t *buf, uint32_t *len, RSA *fw_key,
342                                  uint8_t digest[static SHA256_DIGEST_LENGTH])
343 {
344         struct toc0_cert_item *cert_item = (void *)buf;
345         uint8_t cert_digest[SHA256_DIGEST_LENGTH];
346         struct toc0_totalSequence *totalSequence;
347         struct toc0_sigSequence *sigSequence;
348         struct toc0_extension *extension;
349         struct toc0_publicKey *publicKey;
350         int ret = EXIT_FAILURE;
351         unsigned int sig_len;
352
353         memcpy(cert_item, &cert_item_template, sizeof(*cert_item));
354         *len = sizeof(*cert_item);
355
356         /*
357          * Fill in the public key.
358          *
359          * Only 2048-bit RSA keys are supported. Since this uses a fixed-size
360          * structure, it may fail for non-standard exponents.
361          */
362         totalSequence = &cert_item->totalSequence;
363         publicKey = &totalSequence->mainSequence.subjectPublicKeyInfo.publicKey;
364         if (BN_bn2binpad(RSA_get0_n(fw_key), publicKey->n, sizeof(publicKey->n)) < 0 ||
365             BN_bn2binpad(RSA_get0_e(fw_key), publicKey->e, sizeof(publicKey->e)) < 0) {
366                 pr_err("Firmware key is too big for certificate\n");
367                 goto err;
368         }
369
370         /* Fill in the firmware digest. */
371         extension = &totalSequence->mainSequence.explicit3.extension;
372         memcpy(&extension->digest, digest, SHA256_DIGEST_LENGTH);
373
374         /*
375          * Sign the certificate.
376          *
377          * In older SBROM versions (and by default in newer versions),
378          * the last 4 bytes of the certificate are not signed.
379          *
380          * (The buffer passed to SHA256 starts at tag_mainSequence, but
381          *  the buffer size does not include the length of that tag.)
382          */
383         SHA256((uint8_t *)totalSequence, sizeof(struct toc0_mainSequence), cert_digest);
384         sigSequence = &totalSequence->sigSequence;
385         if (!RSA_sign(NID_sha256, cert_digest, SHA256_DIGEST_LENGTH,
386                       sigSequence->signature, &sig_len, fw_key)) {
387                 pr_err("Failed to sign certificate\n");
388                 goto err;
389         }
390         if (sig_len != sizeof(sigSequence->signature)) {
391                 pr_err("Bad certificate signature length\n");
392                 goto err;
393         }
394
395         ret = EXIT_SUCCESS;
396
397 err:
398         return ret;
399 }
400
401 /*
402  * Verify the certificate in @buf, describing the firmware with SHA256 digest
403  * @digest, and signed by the RSA key contained within. If @fw_key is provided,
404  * only that key will be accepted.
405  *
406  * This function is only expected to work with images created by mkimage.
407  */
408 static int toc0_verify_cert_item(const uint8_t *buf, uint32_t len, RSA *fw_key,
409                                  uint8_t digest[static SHA256_DIGEST_LENGTH])
410 {
411         const struct toc0_cert_item *cert_item = (const void *)buf;
412         uint8_t cert_digest[SHA256_DIGEST_LENGTH];
413         const struct toc0_totalSequence *totalSequence;
414         const struct toc0_sigSequence *sigSequence;
415         const struct toc0_extension *extension;
416         const struct toc0_publicKey *publicKey;
417         int ret = EXIT_FAILURE;
418         RSA *key = NULL;
419         BIGNUM *n, *e;
420
421         /* Extract the public key from the certificate. */
422         totalSequence = &cert_item->totalSequence;
423         publicKey = &totalSequence->mainSequence.subjectPublicKeyInfo.publicKey;
424         n = BN_bin2bn(publicKey->n, sizeof(publicKey->n), NULL);
425         e = BN_bin2bn(publicKey->e, sizeof(publicKey->e), NULL);
426         key = RSA_new();
427         if (!key)
428                 goto err;
429         if (!RSA_set0_key(key, n, e, NULL))
430                 goto err;
431
432         /* If a key was provided, compare it to the embedded key. */
433         if (fw_key && (BN_cmp(RSA_get0_n(key), RSA_get0_n(fw_key)) ||
434                        BN_cmp(RSA_get0_e(key), RSA_get0_e(fw_key)))) {
435                 pr_err("Wrong firmware key in certificate\n");
436                 goto err;
437         }
438
439         /* If a digest was provided, compare it to the embedded digest. */
440         extension = &totalSequence->mainSequence.explicit3.extension;
441         if (digest && memcmp(&extension->digest, digest, SHA256_DIGEST_LENGTH)) {
442                 pr_err("Wrong firmware digest in certificate\n");
443                 goto err;
444         }
445
446         /* Verify the certificate's signature. See the comment above. */
447         SHA256((uint8_t *)totalSequence, sizeof(struct toc0_mainSequence), cert_digest);
448         sigSequence = &totalSequence->sigSequence;
449         if (!RSA_verify(NID_sha256, cert_digest, SHA256_DIGEST_LENGTH,
450                         sigSequence->signature,
451                         sizeof(sigSequence->signature), key)) {
452                 pr_err("Bad certificate signature\n");
453                 goto err;
454         }
455
456         ret = EXIT_SUCCESS;
457
458 err:
459         RSA_free(key);
460
461         return ret;
462 }
463
464 /*
465  * Always create a TOC0 containing 3 items. The extra item will be ignored on
466  * SoCs which do not support it.
467  */
468 static int toc0_create(uint8_t *buf, uint32_t len, RSA *root_key, RSA *fw_key,
469                        uint8_t *key_item, uint32_t key_item_len,
470                        uint8_t *fw_item, uint32_t fw_item_len, uint32_t fw_addr)
471 {
472         struct toc0_main_info *main_info = (void *)buf;
473         struct toc0_item_info *item_info = (void *)(main_info + 1);
474         uint8_t digest[SHA256_DIGEST_LENGTH];
475         uint32_t *buf32 = (void *)buf;
476         RSA *orig_fw_key = fw_key;
477         int ret = EXIT_FAILURE;
478         uint32_t checksum = 0;
479         uint32_t item_offset;
480         uint32_t item_length;
481         int i;
482
483         /* Hash the firmware for inclusion in the certificate. */
484         SHA256(fw_item, fw_item_len, digest);
485
486         /* Create the main TOC0 header, containing three items. */
487         memcpy(main_info->name, TOC0_MAIN_INFO_NAME, sizeof(main_info->name));
488         main_info->magic        = cpu_to_le32(TOC0_MAIN_INFO_MAGIC);
489         main_info->checksum     = cpu_to_le32(BROM_STAMP_VALUE);
490         main_info->num_items    = cpu_to_le32(TOC0_DEFAULT_NUM_ITEMS);
491         memcpy(main_info->end, TOC0_MAIN_INFO_END, sizeof(main_info->end));
492
493         /* The first item links the ROTPK to the signing key. */
494         item_offset = sizeof(*main_info) +
495                       sizeof(*item_info) * TOC0_DEFAULT_NUM_ITEMS;
496         /* Using an existing key item avoids needing the root private key. */
497         if (key_item) {
498                 item_length = sizeof(*key_item);
499                 if (toc0_verify_key_item(key_item, item_length,
500                                          root_key, &fw_key))
501                         goto err;
502                 memcpy(buf + item_offset, key_item, item_length);
503         } else if (toc0_create_key_item(buf + item_offset, &item_length,
504                                         root_key, fw_key)) {
505                 goto err;
506         }
507
508         item_info->name         = cpu_to_le32(TOC0_ITEM_INFO_NAME_KEY);
509         item_info->offset       = cpu_to_le32(item_offset);
510         item_info->length       = cpu_to_le32(item_length);
511         memcpy(item_info->end, TOC0_ITEM_INFO_END, sizeof(item_info->end));
512
513         /* The second item contains a certificate signed by the firmware key. */
514         item_offset = item_offset + item_length;
515         if (toc0_create_cert_item(buf + item_offset, &item_length,
516                                   fw_key, digest))
517                 goto err;
518
519         item_info++;
520         item_info->name         = cpu_to_le32(TOC0_ITEM_INFO_NAME_CERT);
521         item_info->offset       = cpu_to_le32(item_offset);
522         item_info->length       = cpu_to_le32(item_length);
523         memcpy(item_info->end, TOC0_ITEM_INFO_END, sizeof(item_info->end));
524
525         /* The third item contains the actual boot code. */
526         item_offset = ALIGN(item_offset + item_length, 32);
527         item_length = fw_item_len;
528         if (buf + item_offset != fw_item)
529                 memmove(buf + item_offset, fw_item, item_length);
530
531         item_info++;
532         item_info->name         = cpu_to_le32(TOC0_ITEM_INFO_NAME_FIRMWARE);
533         item_info->offset       = cpu_to_le32(item_offset);
534         item_info->length       = cpu_to_le32(item_length);
535         item_info->load_addr    = cpu_to_le32(fw_addr);
536         memcpy(item_info->end, TOC0_ITEM_INFO_END, sizeof(item_info->end));
537
538         /* Pad to the required block size with 0xff to be flash-friendly. */
539         item_offset = item_offset + item_length;
540         item_length = ALIGN(item_offset, PAD_SIZE) - item_offset;
541         memset(buf + item_offset, 0xff, item_length);
542
543         /* Fill in the total padded file length. */
544         item_offset = item_offset + item_length;
545         main_info->length = cpu_to_le32(item_offset);
546
547         /* Verify enough space was provided when creating the image. */
548         assert(len >= item_offset);
549
550         /* Calculate the checksum. Yes, it's that simple. */
551         for (i = 0; i < item_offset / 4; ++i)
552                 checksum += le32_to_cpu(buf32[i]);
553         main_info->checksum = cpu_to_le32(checksum);
554
555         ret = EXIT_SUCCESS;
556
557 err:
558         if (fw_key != orig_fw_key)
559                 RSA_free(fw_key);
560
561         return ret;
562 }
563
564 static const struct toc0_item_info *
565 toc0_find_item(const struct toc0_main_info *main_info, uint32_t name,
566                uint32_t *offset, uint32_t *length)
567 {
568         const struct toc0_item_info *item_info = (void *)(main_info + 1);
569         uint32_t item_offset, item_length;
570         uint32_t num_items, main_length;
571         int i;
572
573         num_items   = le32_to_cpu(main_info->num_items);
574         main_length = le32_to_cpu(main_info->length);
575
576         for (i = 0; i < num_items; ++i, ++item_info) {
577                 if (le32_to_cpu(item_info->name) != name)
578                         continue;
579
580                 item_offset = le32_to_cpu(item_info->offset);
581                 item_length = le32_to_cpu(item_info->length);
582
583                 if (item_offset > main_length ||
584                     item_length > main_length - item_offset)
585                         continue;
586
587                 *offset = item_offset;
588                 *length = item_length;
589
590                 return item_info;
591         }
592
593         return NULL;
594 }
595
596 static int toc0_verify(const uint8_t *buf, uint32_t len, RSA *root_key)
597 {
598         const struct toc0_main_info *main_info = (void *)buf;
599         const struct toc0_item_info *item_info;
600         uint8_t digest[SHA256_DIGEST_LENGTH];
601         uint32_t main_length = le32_to_cpu(main_info->length);
602         uint32_t checksum = BROM_STAMP_VALUE;
603         uint32_t *buf32 = (void *)buf;
604         uint32_t length, offset;
605         int ret = EXIT_FAILURE;
606         RSA *fw_key = NULL;
607         int i;
608
609         if (len < main_length)
610                 goto err;
611
612         /* Verify the main header. */
613         if (memcmp(main_info->name, TOC0_MAIN_INFO_NAME, sizeof(main_info->name)))
614                 goto err;
615         if (le32_to_cpu(main_info->magic) != TOC0_MAIN_INFO_MAGIC)
616                 goto err;
617         /* Verify the checksum without modifying the buffer. */
618         for (i = 0; i < main_length / 4; ++i)
619                 checksum += le32_to_cpu(buf32[i]);
620         if (checksum != 2 * le32_to_cpu(main_info->checksum))
621                 goto err;
622         /* The length must be at least 512 byte aligned. */
623         if (main_length % 512)
624                 goto err;
625         if (memcmp(main_info->end, TOC0_MAIN_INFO_END, sizeof(main_info->end)))
626                 goto err;
627
628         /* Verify the key item if present (it is optional). */
629         item_info = toc0_find_item(main_info, TOC0_ITEM_INFO_NAME_KEY,
630                                    &offset, &length);
631         if (!item_info)
632                 fw_key = root_key;
633         else if (toc0_verify_key_item(buf + offset, length, root_key, &fw_key))
634                 goto err;
635
636         /* Hash the firmware to compare with the certificate. */
637         item_info = toc0_find_item(main_info, TOC0_ITEM_INFO_NAME_FIRMWARE,
638                                    &offset, &length);
639         if (!item_info) {
640                 pr_err("Missing firmware item\n");
641                 goto err;
642         }
643         SHA256(buf + offset, length, digest);
644
645         /* Verify the certificate item. */
646         item_info = toc0_find_item(main_info, TOC0_ITEM_INFO_NAME_CERT,
647                                    &offset, &length);
648         if (!item_info) {
649                 pr_err("Missing certificate item\n");
650                 goto err;
651         }
652         if (toc0_verify_cert_item(buf + offset, length, fw_key, digest))
653                 goto err;
654
655         ret = EXIT_SUCCESS;
656
657 err:
658         if (fw_key != root_key)
659                 RSA_free(fw_key);
660
661         return ret;
662 }
663
664 static int toc0_check_params(struct image_tool_params *params)
665 {
666         if (!params->dflag)
667                 return -EINVAL;
668
669         /*
670          * If a key directory was provided, look for key files there.
671          * Otherwise, look for them in the current directory. The key files are
672          * the "quoted" terms in the description below.
673          *
674          * A summary of the chain of trust on most SoCs:
675          *  1) eFuse contains a SHA256 digest of the public "root key".
676          *  2) Private "root key" signs the certificate item (generated here).
677          *  3) Certificate item contains a SHA256 digest of the firmware item.
678          *
679          * A summary of the chain of trust on the H6 (by default; a bit in the
680          * BROM_CONFIG eFuse makes it work like above):
681          *  1) eFuse contains a SHA256 digest of the public "root key".
682          *  2) Private "root key" signs the "key item" (generated here).
683          *  3) "Key item" contains the public "root key" and public "fw key".
684          *  4) Private "fw key" signs the certificate item (generated here).
685          *  5) Certificate item contains a SHA256 digest of the firmware item.
686          *
687          * This means there are three valid ways to generate a TOC0:
688          *  1) Provide the private "root key" only. This works everywhere.
689          *     For H6, the "root key" will also be used as the "fw key".
690          *  2) FOR H6 ONLY: Provide the private "root key" and a separate
691          *     private "fw key".
692          *  3) FOR H6 ONLY: Provide the private "fw key" and a pre-existing
693          *     "key item" containing the corresponding  public "fw key".
694          *     In this case, the private "root key" can be kept offline. The
695          *     "key item" can be extracted from a TOC0 image generated using
696          *     method #2 above.
697          *
698          *  Note that until the ROTPK_HASH eFuse is programmed, any "root key"
699          *  will be accepted by the BROM.
700          */
701         if (params->keydir) {
702                 if (asprintf(&fw_key_file, "%s/%s", params->keydir, fw_key_file) < 0)
703                         return -ENOMEM;
704                 if (asprintf(&key_item_file, "%s/%s", params->keydir, key_item_file) < 0)
705                         return -ENOMEM;
706                 if (asprintf(&root_key_file, "%s/%s", params->keydir, root_key_file) < 0)
707                         return -ENOMEM;
708         }
709
710         return 0;
711 }
712
713 static int toc0_verify_header(unsigned char *buf, int image_size,
714                               struct image_tool_params *params)
715 {
716         int ret = EXIT_FAILURE;
717         RSA *root_key = NULL;
718         FILE *fp;
719
720         /* A root public key is optional. */
721         fp = fopen(root_key_file, "rb");
722         if (fp) {
723                 pr_info("Verifying image with existing root key\n");
724                 root_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
725                 if (!root_key)
726                         root_key = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
727                 fclose(fp);
728                 if (!root_key) {
729                         pr_err("Failed to read public key from '%s'\n",
730                                root_key_file);
731                         goto err;
732                 }
733         }
734
735         ret = toc0_verify(buf, image_size, root_key);
736
737 err:
738         RSA_free(root_key);
739
740         return ret;
741 }
742
743 static const char *toc0_item_name(uint32_t name)
744 {
745         if (name == TOC0_ITEM_INFO_NAME_CERT)
746                 return "Certificate";
747         if (name == TOC0_ITEM_INFO_NAME_FIRMWARE)
748                 return "Firmware";
749         if (name == TOC0_ITEM_INFO_NAME_KEY)
750                 return "Key";
751         return "(unknown)";
752 }
753
754 static void toc0_print_header(const void *buf)
755 {
756         const struct toc0_main_info *main_info = buf;
757         const struct toc0_item_info *item_info = (void *)(main_info + 1);
758         uint32_t head_length, main_length, num_items;
759         uint32_t item_offset, item_length, item_name;
760         int load_addr = -1;
761         int i;
762
763         num_items   = le32_to_cpu(main_info->num_items);
764         head_length = sizeof(*main_info) + num_items * sizeof(*item_info);
765         main_length = le32_to_cpu(main_info->length);
766
767         printf("Allwinner TOC0 Image\n"
768                "Size: %d bytes\n"
769                "Contents: %d items\n"
770                " 00000000:%08x Headers\n",
771                main_length, num_items, head_length);
772
773         for (i = 0; i < num_items; ++i, ++item_info) {
774                 item_offset = le32_to_cpu(item_info->offset);
775                 item_length = le32_to_cpu(item_info->length);
776                 item_name   = le32_to_cpu(item_info->name);
777
778                 if (item_name == TOC0_ITEM_INFO_NAME_FIRMWARE)
779                         load_addr = le32_to_cpu(item_info->load_addr);
780
781                 printf(" %08x:%08x %s\n",
782                        item_offset, item_length,
783                        toc0_item_name(item_name));
784         }
785
786         if (num_items && item_offset + item_length < main_length) {
787                 item_offset = item_offset + item_length;
788                 item_length = main_length - item_offset;
789
790                 printf(" %08x:%08x Padding\n",
791                        item_offset, item_length);
792         }
793
794         if (load_addr != -1)
795                 printf("Load address: 0x%08x\n", load_addr);
796 }
797
798 static void toc0_set_header(void *buf, struct stat *sbuf, int ifd,
799                             struct image_tool_params *params)
800 {
801         uint32_t key_item_len = 0;
802         uint8_t *key_item = NULL;
803         int ret = EXIT_FAILURE;
804         RSA *root_key = NULL;
805         RSA *fw_key = NULL;
806         FILE *fp;
807
808         /* Either a key item or the root private key is required. */
809         fp = fopen(key_item_file, "rb");
810         if (fp) {
811                 pr_info("Creating image using existing key item\n");
812                 key_item_len = sizeof(struct toc0_key_item);
813                 key_item = OPENSSL_malloc(key_item_len);
814                 if (!key_item || fread(key_item, key_item_len, 1, fp) != 1) {
815                         pr_err("Failed to read key item from '%s'\n",
816                                root_key_file);
817                         goto err;
818                 }
819                 fclose(fp);
820                 fp = NULL;
821         }
822
823         fp = fopen(root_key_file, "rb");
824         if (fp) {
825                 root_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
826                 if (!root_key)
827                         root_key = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
828                 fclose(fp);
829                 fp = NULL;
830         }
831
832         /* When using an existing key item, the root key is optional. */
833         if (!key_item && (!root_key || !RSA_get0_d(root_key))) {
834                 pr_err("Failed to read private key from '%s'\n",
835                        root_key_file);
836                 pr_info("Try 'openssl genrsa -out root_key.pem'\n");
837                 goto err;
838         }
839
840         /* The certificate/firmware private key is always required. */
841         fp = fopen(fw_key_file, "rb");
842         if (fp) {
843                 fw_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
844                 fclose(fp);
845                 fp = NULL;
846         }
847         if (!fw_key) {
848                 /* If the root key is a private key, it can be used instead. */
849                 if (root_key && RSA_get0_d(root_key)) {
850                         pr_info("Using root key as firmware key\n");
851                         fw_key = root_key;
852                 } else {
853                         pr_err("Failed to read private key from '%s'\n",
854                                fw_key_file);
855                         goto err;
856                 }
857         }
858
859         /* Warn about potential compatibility issues. */
860         if (key_item || fw_key != root_key)
861                 pr_warn("Only H6 supports separate root and firmware keys\n");
862
863         ret = toc0_create(buf, params->file_size, root_key, fw_key,
864                           key_item, key_item_len,
865                           buf + TOC0_DEFAULT_HEADER_LEN,
866                           params->orig_file_size, params->addr);
867
868 err:
869         OPENSSL_free(key_item);
870         OPENSSL_free(root_key);
871         if (fw_key != root_key)
872                 OPENSSL_free(fw_key);
873         if (fp)
874                 fclose(fp);
875
876         if (ret != EXIT_SUCCESS)
877                 exit(ret);
878 }
879
880 static int toc0_check_image_type(uint8_t type)
881 {
882         return type == IH_TYPE_SUNXI_TOC0 ? 0 : 1;
883 }
884
885 static int toc0_vrec_header(struct image_tool_params *params,
886                             struct image_type_params *tparams)
887 {
888         tparams->hdr = calloc(tparams->header_size, 1);
889
890         /* Save off the unpadded data size for SHA256 calculation. */
891         params->orig_file_size = params->file_size - TOC0_DEFAULT_HEADER_LEN;
892
893         /* Return padding to 8K blocks. */
894         return ALIGN(params->file_size, PAD_SIZE) - params->file_size;
895 }
896
897 U_BOOT_IMAGE_TYPE(
898         sunxi_toc0,
899         "Allwinner TOC0 Boot Image support",
900         TOC0_DEFAULT_HEADER_LEN,
901         NULL,
902         toc0_check_params,
903         toc0_verify_header,
904         toc0_print_header,
905         toc0_set_header,
906         NULL,
907         toc0_check_image_type,
908         NULL,
909         toc0_vrec_header
910 );