sunxi_toc0.c 26 KB

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