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