kwbimage.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Image manipulator for Marvell SoCs
  4. * supports Kirkwood, Dove, Armada 370, Armada XP, and Armada 38x
  5. *
  6. * (C) Copyright 2013 Thomas Petazzoni
  7. * <thomas.petazzoni@free-electrons.com>
  8. *
  9. * Not implemented: support for the register headers in v1 images
  10. */
  11. #include "imagetool.h"
  12. #include <limits.h>
  13. #include <image.h>
  14. #include <stdarg.h>
  15. #include <stdint.h>
  16. #include "kwbimage.h"
  17. #ifdef CONFIG_KWB_SECURE
  18. #include <openssl/bn.h>
  19. #include <openssl/rsa.h>
  20. #include <openssl/pem.h>
  21. #include <openssl/err.h>
  22. #include <openssl/evp.h>
  23. #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
  24. (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
  25. static void RSA_get0_key(const RSA *r,
  26. const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
  27. {
  28. if (n != NULL)
  29. *n = r->n;
  30. if (e != NULL)
  31. *e = r->e;
  32. if (d != NULL)
  33. *d = r->d;
  34. }
  35. #elif !defined(LIBRESSL_VERSION_NUMBER)
  36. void EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
  37. {
  38. EVP_MD_CTX_reset(ctx);
  39. }
  40. #endif
  41. #endif
  42. static struct image_cfg_element *image_cfg;
  43. static int cfgn;
  44. #ifdef CONFIG_KWB_SECURE
  45. static int verbose_mode;
  46. #endif
  47. struct boot_mode {
  48. unsigned int id;
  49. const char *name;
  50. };
  51. /*
  52. * SHA2-256 hash
  53. */
  54. struct hash_v1 {
  55. uint8_t hash[32];
  56. };
  57. struct boot_mode boot_modes[] = {
  58. { 0x4D, "i2c" },
  59. { 0x5A, "spi" },
  60. { 0x8B, "nand" },
  61. { 0x78, "sata" },
  62. { 0x9C, "pex" },
  63. { 0x69, "uart" },
  64. { 0xAE, "sdio" },
  65. {},
  66. };
  67. struct nand_ecc_mode {
  68. unsigned int id;
  69. const char *name;
  70. };
  71. struct nand_ecc_mode nand_ecc_modes[] = {
  72. { 0x00, "default" },
  73. { 0x01, "hamming" },
  74. { 0x02, "rs" },
  75. { 0x03, "disabled" },
  76. {},
  77. };
  78. /* Used to identify an undefined execution or destination address */
  79. #define ADDR_INVALID ((uint32_t)-1)
  80. #define BINARY_MAX_ARGS 8
  81. /* In-memory representation of a line of the configuration file */
  82. enum image_cfg_type {
  83. IMAGE_CFG_VERSION = 0x1,
  84. IMAGE_CFG_BOOT_FROM,
  85. IMAGE_CFG_DEST_ADDR,
  86. IMAGE_CFG_EXEC_ADDR,
  87. IMAGE_CFG_NAND_BLKSZ,
  88. IMAGE_CFG_NAND_BADBLK_LOCATION,
  89. IMAGE_CFG_NAND_ECC_MODE,
  90. IMAGE_CFG_NAND_PAGESZ,
  91. IMAGE_CFG_BINARY,
  92. IMAGE_CFG_PAYLOAD,
  93. IMAGE_CFG_DATA,
  94. IMAGE_CFG_BAUDRATE,
  95. IMAGE_CFG_DEBUG,
  96. IMAGE_CFG_KAK,
  97. IMAGE_CFG_CSK,
  98. IMAGE_CFG_CSK_INDEX,
  99. IMAGE_CFG_JTAG_DELAY,
  100. IMAGE_CFG_BOX_ID,
  101. IMAGE_CFG_FLASH_ID,
  102. IMAGE_CFG_SEC_COMMON_IMG,
  103. IMAGE_CFG_SEC_SPECIALIZED_IMG,
  104. IMAGE_CFG_SEC_BOOT_DEV,
  105. IMAGE_CFG_SEC_FUSE_DUMP,
  106. IMAGE_CFG_COUNT
  107. } type;
  108. static const char * const id_strs[] = {
  109. [IMAGE_CFG_VERSION] = "VERSION",
  110. [IMAGE_CFG_BOOT_FROM] = "BOOT_FROM",
  111. [IMAGE_CFG_DEST_ADDR] = "DEST_ADDR",
  112. [IMAGE_CFG_EXEC_ADDR] = "EXEC_ADDR",
  113. [IMAGE_CFG_NAND_BLKSZ] = "NAND_BLKSZ",
  114. [IMAGE_CFG_NAND_BADBLK_LOCATION] = "NAND_BADBLK_LOCATION",
  115. [IMAGE_CFG_NAND_ECC_MODE] = "NAND_ECC_MODE",
  116. [IMAGE_CFG_NAND_PAGESZ] = "NAND_PAGE_SIZE",
  117. [IMAGE_CFG_BINARY] = "BINARY",
  118. [IMAGE_CFG_PAYLOAD] = "PAYLOAD",
  119. [IMAGE_CFG_DATA] = "DATA",
  120. [IMAGE_CFG_BAUDRATE] = "BAUDRATE",
  121. [IMAGE_CFG_DEBUG] = "DEBUG",
  122. [IMAGE_CFG_KAK] = "KAK",
  123. [IMAGE_CFG_CSK] = "CSK",
  124. [IMAGE_CFG_CSK_INDEX] = "CSK_INDEX",
  125. [IMAGE_CFG_JTAG_DELAY] = "JTAG_DELAY",
  126. [IMAGE_CFG_BOX_ID] = "BOX_ID",
  127. [IMAGE_CFG_FLASH_ID] = "FLASH_ID",
  128. [IMAGE_CFG_SEC_COMMON_IMG] = "SEC_COMMON_IMG",
  129. [IMAGE_CFG_SEC_SPECIALIZED_IMG] = "SEC_SPECIALIZED_IMG",
  130. [IMAGE_CFG_SEC_BOOT_DEV] = "SEC_BOOT_DEV",
  131. [IMAGE_CFG_SEC_FUSE_DUMP] = "SEC_FUSE_DUMP"
  132. };
  133. struct image_cfg_element {
  134. enum image_cfg_type type;
  135. union {
  136. unsigned int version;
  137. unsigned int bootfrom;
  138. struct {
  139. const char *file;
  140. unsigned int args[BINARY_MAX_ARGS];
  141. unsigned int nargs;
  142. } binary;
  143. const char *payload;
  144. unsigned int dstaddr;
  145. unsigned int execaddr;
  146. unsigned int nandblksz;
  147. unsigned int nandbadblklocation;
  148. unsigned int nandeccmode;
  149. unsigned int nandpagesz;
  150. struct ext_hdr_v0_reg regdata;
  151. unsigned int baudrate;
  152. unsigned int debug;
  153. const char *key_name;
  154. int csk_idx;
  155. uint8_t jtag_delay;
  156. uint32_t boxid;
  157. uint32_t flashid;
  158. bool sec_specialized_img;
  159. unsigned int sec_boot_dev;
  160. const char *name;
  161. };
  162. };
  163. #define IMAGE_CFG_ELEMENT_MAX 256
  164. /*
  165. * Utility functions to manipulate boot mode and ecc modes (convert
  166. * them back and forth between description strings and the
  167. * corresponding numerical identifiers).
  168. */
  169. static const char *image_boot_mode_name(unsigned int id)
  170. {
  171. int i;
  172. for (i = 0; boot_modes[i].name; i++)
  173. if (boot_modes[i].id == id)
  174. return boot_modes[i].name;
  175. return NULL;
  176. }
  177. int image_boot_mode_id(const char *boot_mode_name)
  178. {
  179. int i;
  180. for (i = 0; boot_modes[i].name; i++)
  181. if (!strcmp(boot_modes[i].name, boot_mode_name))
  182. return boot_modes[i].id;
  183. return -1;
  184. }
  185. int image_nand_ecc_mode_id(const char *nand_ecc_mode_name)
  186. {
  187. int i;
  188. for (i = 0; nand_ecc_modes[i].name; i++)
  189. if (!strcmp(nand_ecc_modes[i].name, nand_ecc_mode_name))
  190. return nand_ecc_modes[i].id;
  191. return -1;
  192. }
  193. static struct image_cfg_element *
  194. image_find_option(unsigned int optiontype)
  195. {
  196. int i;
  197. for (i = 0; i < cfgn; i++) {
  198. if (image_cfg[i].type == optiontype)
  199. return &image_cfg[i];
  200. }
  201. return NULL;
  202. }
  203. static unsigned int
  204. image_count_options(unsigned int optiontype)
  205. {
  206. int i;
  207. unsigned int count = 0;
  208. for (i = 0; i < cfgn; i++)
  209. if (image_cfg[i].type == optiontype)
  210. count++;
  211. return count;
  212. }
  213. #if defined(CONFIG_KWB_SECURE)
  214. static int image_get_csk_index(void)
  215. {
  216. struct image_cfg_element *e;
  217. e = image_find_option(IMAGE_CFG_CSK_INDEX);
  218. if (!e)
  219. return -1;
  220. return e->csk_idx;
  221. }
  222. static bool image_get_spezialized_img(void)
  223. {
  224. struct image_cfg_element *e;
  225. e = image_find_option(IMAGE_CFG_SEC_SPECIALIZED_IMG);
  226. if (!e)
  227. return false;
  228. return e->sec_specialized_img;
  229. }
  230. #endif
  231. /*
  232. * Compute a 8-bit checksum of a memory area. This algorithm follows
  233. * the requirements of the Marvell SoC BootROM specifications.
  234. */
  235. static uint8_t image_checksum8(void *start, uint32_t len)
  236. {
  237. uint8_t csum = 0;
  238. uint8_t *p = start;
  239. /* check len and return zero checksum if invalid */
  240. if (!len)
  241. return 0;
  242. do {
  243. csum += *p;
  244. p++;
  245. } while (--len);
  246. return csum;
  247. }
  248. size_t kwbimage_header_size(unsigned char *ptr)
  249. {
  250. if (image_version((void *)ptr) == 0)
  251. return sizeof(struct main_hdr_v0);
  252. else
  253. return KWBHEADER_V1_SIZE((struct main_hdr_v1 *)ptr);
  254. }
  255. /*
  256. * Verify checksum over a complete header that includes the checksum field.
  257. * Return 1 when OK, otherwise 0.
  258. */
  259. static int main_hdr_checksum_ok(void *hdr)
  260. {
  261. /* Offsets of checksum in v0 and v1 headers are the same */
  262. struct main_hdr_v0 *main_hdr = (struct main_hdr_v0 *)hdr;
  263. uint8_t checksum;
  264. checksum = image_checksum8(hdr, kwbimage_header_size(hdr));
  265. /* Calculated checksum includes the header checksum field. Compensate
  266. * for that.
  267. */
  268. checksum -= main_hdr->checksum;
  269. return checksum == main_hdr->checksum;
  270. }
  271. static uint32_t image_checksum32(void *start, uint32_t len)
  272. {
  273. uint32_t csum = 0;
  274. uint32_t *p = start;
  275. /* check len and return zero checksum if invalid */
  276. if (!len)
  277. return 0;
  278. if (len % sizeof(uint32_t)) {
  279. fprintf(stderr, "Length %d is not in multiple of %zu\n",
  280. len, sizeof(uint32_t));
  281. return 0;
  282. }
  283. do {
  284. csum += *p;
  285. p++;
  286. len -= sizeof(uint32_t);
  287. } while (len > 0);
  288. return csum;
  289. }
  290. static uint8_t baudrate_to_option(unsigned int baudrate)
  291. {
  292. switch (baudrate) {
  293. case 2400:
  294. return MAIN_HDR_V1_OPT_BAUD_2400;
  295. case 4800:
  296. return MAIN_HDR_V1_OPT_BAUD_4800;
  297. case 9600:
  298. return MAIN_HDR_V1_OPT_BAUD_9600;
  299. case 19200:
  300. return MAIN_HDR_V1_OPT_BAUD_19200;
  301. case 38400:
  302. return MAIN_HDR_V1_OPT_BAUD_38400;
  303. case 57600:
  304. return MAIN_HDR_V1_OPT_BAUD_57600;
  305. case 115200:
  306. return MAIN_HDR_V1_OPT_BAUD_115200;
  307. default:
  308. return MAIN_HDR_V1_OPT_BAUD_DEFAULT;
  309. }
  310. }
  311. #if defined(CONFIG_KWB_SECURE)
  312. static void kwb_msg(const char *fmt, ...)
  313. {
  314. if (verbose_mode) {
  315. va_list ap;
  316. va_start(ap, fmt);
  317. vfprintf(stdout, fmt, ap);
  318. va_end(ap);
  319. }
  320. }
  321. static int openssl_err(const char *msg)
  322. {
  323. unsigned long ssl_err = ERR_get_error();
  324. fprintf(stderr, "%s", msg);
  325. fprintf(stderr, ": %s\n",
  326. ERR_error_string(ssl_err, 0));
  327. return -1;
  328. }
  329. static int kwb_load_rsa_key(const char *keydir, const char *name, RSA **p_rsa)
  330. {
  331. char path[PATH_MAX];
  332. RSA *rsa;
  333. FILE *f;
  334. if (!keydir)
  335. keydir = ".";
  336. snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
  337. f = fopen(path, "r");
  338. if (!f) {
  339. fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
  340. path, strerror(errno));
  341. return -ENOENT;
  342. }
  343. rsa = PEM_read_RSAPrivateKey(f, 0, NULL, "");
  344. if (!rsa) {
  345. openssl_err("Failure reading private key");
  346. fclose(f);
  347. return -EPROTO;
  348. }
  349. fclose(f);
  350. *p_rsa = rsa;
  351. return 0;
  352. }
  353. static int kwb_load_cfg_key(struct image_tool_params *params,
  354. unsigned int cfg_option, const char *key_name,
  355. RSA **p_key)
  356. {
  357. struct image_cfg_element *e_key;
  358. RSA *key;
  359. int res;
  360. *p_key = NULL;
  361. e_key = image_find_option(cfg_option);
  362. if (!e_key) {
  363. fprintf(stderr, "%s not configured\n", key_name);
  364. return -ENOENT;
  365. }
  366. res = kwb_load_rsa_key(params->keydir, e_key->key_name, &key);
  367. if (res < 0) {
  368. fprintf(stderr, "Failed to load %s\n", key_name);
  369. return -ENOENT;
  370. }
  371. *p_key = key;
  372. return 0;
  373. }
  374. static int kwb_load_kak(struct image_tool_params *params, RSA **p_kak)
  375. {
  376. return kwb_load_cfg_key(params, IMAGE_CFG_KAK, "KAK", p_kak);
  377. }
  378. static int kwb_load_csk(struct image_tool_params *params, RSA **p_csk)
  379. {
  380. return kwb_load_cfg_key(params, IMAGE_CFG_CSK, "CSK", p_csk);
  381. }
  382. static int kwb_compute_pubkey_hash(struct pubkey_der_v1 *pk,
  383. struct hash_v1 *hash)
  384. {
  385. EVP_MD_CTX *ctx;
  386. unsigned int key_size;
  387. unsigned int hash_size;
  388. int ret = 0;
  389. if (!pk || !hash || pk->key[0] != 0x30 || pk->key[1] != 0x82)
  390. return -EINVAL;
  391. key_size = (pk->key[2] << 8) + pk->key[3] + 4;
  392. ctx = EVP_MD_CTX_create();
  393. if (!ctx)
  394. return openssl_err("EVP context creation failed");
  395. EVP_MD_CTX_init(ctx);
  396. if (!EVP_DigestInit(ctx, EVP_sha256())) {
  397. ret = openssl_err("Digest setup failed");
  398. goto hash_err_ctx;
  399. }
  400. if (!EVP_DigestUpdate(ctx, pk->key, key_size)) {
  401. ret = openssl_err("Hashing data failed");
  402. goto hash_err_ctx;
  403. }
  404. if (!EVP_DigestFinal(ctx, hash->hash, &hash_size)) {
  405. ret = openssl_err("Could not obtain hash");
  406. goto hash_err_ctx;
  407. }
  408. EVP_MD_CTX_cleanup(ctx);
  409. hash_err_ctx:
  410. EVP_MD_CTX_destroy(ctx);
  411. return ret;
  412. }
  413. static int kwb_import_pubkey(RSA **key, struct pubkey_der_v1 *src, char *keyname)
  414. {
  415. RSA *rsa;
  416. const unsigned char *ptr;
  417. if (!key || !src)
  418. goto fail;
  419. ptr = src->key;
  420. rsa = d2i_RSAPublicKey(key, &ptr, sizeof(src->key));
  421. if (!rsa) {
  422. openssl_err("error decoding public key");
  423. goto fail;
  424. }
  425. return 0;
  426. fail:
  427. fprintf(stderr, "Failed to decode %s pubkey\n", keyname);
  428. return -EINVAL;
  429. }
  430. static int kwb_export_pubkey(RSA *key, struct pubkey_der_v1 *dst, FILE *hashf,
  431. char *keyname)
  432. {
  433. int size_exp, size_mod, size_seq;
  434. const BIGNUM *key_e, *key_n;
  435. uint8_t *cur;
  436. char *errmsg = "Failed to encode %s\n";
  437. RSA_get0_key(key, NULL, &key_e, NULL);
  438. RSA_get0_key(key, &key_n, NULL, NULL);
  439. if (!key || !key_e || !key_n || !dst) {
  440. fprintf(stderr, "export pk failed: (%p, %p, %p, %p)",
  441. key, key_e, key_n, dst);
  442. fprintf(stderr, errmsg, keyname);
  443. return -EINVAL;
  444. }
  445. /*
  446. * According to the specs, the key should be PKCS#1 DER encoded.
  447. * But unfortunately the really required encoding seems to be different;
  448. * it violates DER...! (But it still conformes to BER.)
  449. * (Length always in long form w/ 2 byte length code; no leading zero
  450. * when MSB of first byte is set...)
  451. * So we cannot use the encoding func provided by OpenSSL and have to
  452. * do the encoding manually.
  453. */
  454. size_exp = BN_num_bytes(key_e);
  455. size_mod = BN_num_bytes(key_n);
  456. size_seq = 4 + size_mod + 4 + size_exp;
  457. if (size_mod > 256) {
  458. fprintf(stderr, "export pk failed: wrong mod size: %d\n",
  459. size_mod);
  460. fprintf(stderr, errmsg, keyname);
  461. return -EINVAL;
  462. }
  463. if (4 + size_seq > sizeof(dst->key)) {
  464. fprintf(stderr, "export pk failed: seq too large (%d, %lu)\n",
  465. 4 + size_seq, sizeof(dst->key));
  466. fprintf(stderr, errmsg, keyname);
  467. return -ENOBUFS;
  468. }
  469. cur = dst->key;
  470. /* PKCS#1 (RFC3447) RSAPublicKey structure */
  471. *cur++ = 0x30; /* SEQUENCE */
  472. *cur++ = 0x82;
  473. *cur++ = (size_seq >> 8) & 0xFF;
  474. *cur++ = size_seq & 0xFF;
  475. /* Modulus */
  476. *cur++ = 0x02; /* INTEGER */
  477. *cur++ = 0x82;
  478. *cur++ = (size_mod >> 8) & 0xFF;
  479. *cur++ = size_mod & 0xFF;
  480. BN_bn2bin(key_n, cur);
  481. cur += size_mod;
  482. /* Exponent */
  483. *cur++ = 0x02; /* INTEGER */
  484. *cur++ = 0x82;
  485. *cur++ = (size_exp >> 8) & 0xFF;
  486. *cur++ = size_exp & 0xFF;
  487. BN_bn2bin(key_e, cur);
  488. if (hashf) {
  489. struct hash_v1 pk_hash;
  490. int i;
  491. int ret = 0;
  492. ret = kwb_compute_pubkey_hash(dst, &pk_hash);
  493. if (ret < 0) {
  494. fprintf(stderr, errmsg, keyname);
  495. return ret;
  496. }
  497. fprintf(hashf, "SHA256 = ");
  498. for (i = 0 ; i < sizeof(pk_hash.hash); ++i)
  499. fprintf(hashf, "%02X", pk_hash.hash[i]);
  500. fprintf(hashf, "\n");
  501. }
  502. return 0;
  503. }
  504. int kwb_sign(RSA *key, void *data, int datasz, struct sig_v1 *sig, char *signame)
  505. {
  506. EVP_PKEY *evp_key;
  507. EVP_MD_CTX *ctx;
  508. unsigned int sig_size;
  509. int size;
  510. int ret = 0;
  511. evp_key = EVP_PKEY_new();
  512. if (!evp_key)
  513. return openssl_err("EVP_PKEY object creation failed");
  514. if (!EVP_PKEY_set1_RSA(evp_key, key)) {
  515. ret = openssl_err("EVP key setup failed");
  516. goto err_key;
  517. }
  518. size = EVP_PKEY_size(evp_key);
  519. if (size > sizeof(sig->sig)) {
  520. fprintf(stderr, "Buffer to small for signature (%d bytes)\n",
  521. size);
  522. ret = -ENOBUFS;
  523. goto err_key;
  524. }
  525. ctx = EVP_MD_CTX_create();
  526. if (!ctx) {
  527. ret = openssl_err("EVP context creation failed");
  528. goto err_key;
  529. }
  530. EVP_MD_CTX_init(ctx);
  531. if (!EVP_SignInit(ctx, EVP_sha256())) {
  532. ret = openssl_err("Signer setup failed");
  533. goto err_ctx;
  534. }
  535. if (!EVP_SignUpdate(ctx, data, datasz)) {
  536. ret = openssl_err("Signing data failed");
  537. goto err_ctx;
  538. }
  539. if (!EVP_SignFinal(ctx, sig->sig, &sig_size, evp_key)) {
  540. ret = openssl_err("Could not obtain signature");
  541. goto err_ctx;
  542. }
  543. EVP_MD_CTX_cleanup(ctx);
  544. EVP_MD_CTX_destroy(ctx);
  545. EVP_PKEY_free(evp_key);
  546. return 0;
  547. err_ctx:
  548. EVP_MD_CTX_destroy(ctx);
  549. err_key:
  550. EVP_PKEY_free(evp_key);
  551. fprintf(stderr, "Failed to create %s signature\n", signame);
  552. return ret;
  553. }
  554. int kwb_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
  555. char *signame)
  556. {
  557. EVP_PKEY *evp_key;
  558. EVP_MD_CTX *ctx;
  559. int size;
  560. int ret = 0;
  561. evp_key = EVP_PKEY_new();
  562. if (!evp_key)
  563. return openssl_err("EVP_PKEY object creation failed");
  564. if (!EVP_PKEY_set1_RSA(evp_key, key)) {
  565. ret = openssl_err("EVP key setup failed");
  566. goto err_key;
  567. }
  568. size = EVP_PKEY_size(evp_key);
  569. if (size > sizeof(sig->sig)) {
  570. fprintf(stderr, "Invalid signature size (%d bytes)\n",
  571. size);
  572. ret = -EINVAL;
  573. goto err_key;
  574. }
  575. ctx = EVP_MD_CTX_create();
  576. if (!ctx) {
  577. ret = openssl_err("EVP context creation failed");
  578. goto err_key;
  579. }
  580. EVP_MD_CTX_init(ctx);
  581. if (!EVP_VerifyInit(ctx, EVP_sha256())) {
  582. ret = openssl_err("Verifier setup failed");
  583. goto err_ctx;
  584. }
  585. if (!EVP_VerifyUpdate(ctx, data, datasz)) {
  586. ret = openssl_err("Hashing data failed");
  587. goto err_ctx;
  588. }
  589. if (EVP_VerifyFinal(ctx, sig->sig, sizeof(sig->sig), evp_key) != 1) {
  590. ret = openssl_err("Could not verify signature");
  591. goto err_ctx;
  592. }
  593. EVP_MD_CTX_cleanup(ctx);
  594. EVP_MD_CTX_destroy(ctx);
  595. EVP_PKEY_free(evp_key);
  596. return 0;
  597. err_ctx:
  598. EVP_MD_CTX_destroy(ctx);
  599. err_key:
  600. EVP_PKEY_free(evp_key);
  601. fprintf(stderr, "Failed to verify %s signature\n", signame);
  602. return ret;
  603. }
  604. int kwb_sign_and_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
  605. char *signame)
  606. {
  607. if (kwb_sign(key, data, datasz, sig, signame) < 0)
  608. return -1;
  609. if (kwb_verify(key, data, datasz, sig, signame) < 0)
  610. return -1;
  611. return 0;
  612. }
  613. int kwb_dump_fuse_cmds_38x(FILE *out, struct secure_hdr_v1 *sec_hdr)
  614. {
  615. struct hash_v1 kak_pub_hash;
  616. struct image_cfg_element *e;
  617. unsigned int fuse_line;
  618. int i, idx;
  619. uint8_t *ptr;
  620. uint32_t val;
  621. int ret = 0;
  622. if (!out || !sec_hdr)
  623. return -EINVAL;
  624. ret = kwb_compute_pubkey_hash(&sec_hdr->kak, &kak_pub_hash);
  625. if (ret < 0)
  626. goto done;
  627. fprintf(out, "# burn KAK pub key hash\n");
  628. ptr = kak_pub_hash.hash;
  629. for (fuse_line = 26; fuse_line <= 30; ++fuse_line) {
  630. fprintf(out, "fuse prog -y %u 0 ", fuse_line);
  631. for (i = 4; i-- > 0;)
  632. fprintf(out, "%02hx", (ushort)ptr[i]);
  633. ptr += 4;
  634. fprintf(out, " 00");
  635. if (fuse_line < 30) {
  636. for (i = 3; i-- > 0;)
  637. fprintf(out, "%02hx", (ushort)ptr[i]);
  638. ptr += 3;
  639. } else {
  640. fprintf(out, "000000");
  641. }
  642. fprintf(out, " 1\n");
  643. }
  644. fprintf(out, "# burn CSK selection\n");
  645. idx = image_get_csk_index();
  646. if (idx < 0 || idx > 15) {
  647. ret = -EINVAL;
  648. goto done;
  649. }
  650. if (idx > 0) {
  651. for (fuse_line = 31; fuse_line < 31 + idx; ++fuse_line)
  652. fprintf(out, "fuse prog -y %u 0 00000001 00000000 1\n",
  653. fuse_line);
  654. } else {
  655. fprintf(out, "# CSK index is 0; no mods needed\n");
  656. }
  657. e = image_find_option(IMAGE_CFG_BOX_ID);
  658. if (e) {
  659. fprintf(out, "# set box ID\n");
  660. fprintf(out, "fuse prog -y 48 0 %08x 00000000 1\n", e->boxid);
  661. }
  662. e = image_find_option(IMAGE_CFG_FLASH_ID);
  663. if (e) {
  664. fprintf(out, "# set flash ID\n");
  665. fprintf(out, "fuse prog -y 47 0 %08x 00000000 1\n", e->flashid);
  666. }
  667. fprintf(out, "# enable secure mode ");
  668. fprintf(out, "(must be the last fuse line written)\n");
  669. val = 1;
  670. e = image_find_option(IMAGE_CFG_SEC_BOOT_DEV);
  671. if (!e) {
  672. fprintf(stderr, "ERROR: secured mode boot device not given\n");
  673. ret = -EINVAL;
  674. goto done;
  675. }
  676. if (e->sec_boot_dev > 0xff) {
  677. fprintf(stderr, "ERROR: secured mode boot device invalid\n");
  678. ret = -EINVAL;
  679. goto done;
  680. }
  681. val |= (e->sec_boot_dev << 8);
  682. fprintf(out, "fuse prog -y 24 0 %08x 0103e0a9 1\n", val);
  683. fprintf(out, "# lock (unused) fuse lines (0-23)s\n");
  684. for (fuse_line = 0; fuse_line < 24; ++fuse_line)
  685. fprintf(out, "fuse prog -y %u 2 1\n", fuse_line);
  686. fprintf(out, "# OK, that's all :-)\n");
  687. done:
  688. return ret;
  689. }
  690. static int kwb_dump_fuse_cmds(struct secure_hdr_v1 *sec_hdr)
  691. {
  692. int ret = 0;
  693. struct image_cfg_element *e;
  694. e = image_find_option(IMAGE_CFG_SEC_FUSE_DUMP);
  695. if (!e)
  696. return 0;
  697. if (!strcmp(e->name, "a38x")) {
  698. FILE *out = fopen("kwb_fuses_a38x.txt", "w+");
  699. kwb_dump_fuse_cmds_38x(out, sec_hdr);
  700. fclose(out);
  701. goto done;
  702. }
  703. ret = -ENOSYS;
  704. done:
  705. return ret;
  706. }
  707. #endif
  708. static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
  709. int payloadsz)
  710. {
  711. struct image_cfg_element *e;
  712. size_t headersz;
  713. struct main_hdr_v0 *main_hdr;
  714. uint8_t *image;
  715. int has_ext = 0;
  716. /*
  717. * Calculate the size of the header and the size of the
  718. * payload
  719. */
  720. headersz = sizeof(struct main_hdr_v0);
  721. if (image_count_options(IMAGE_CFG_DATA) > 0) {
  722. has_ext = 1;
  723. headersz += sizeof(struct ext_hdr_v0);
  724. }
  725. if (image_count_options(IMAGE_CFG_PAYLOAD) > 1) {
  726. fprintf(stderr, "More than one payload, not possible\n");
  727. return NULL;
  728. }
  729. image = malloc(headersz);
  730. if (!image) {
  731. fprintf(stderr, "Cannot allocate memory for image\n");
  732. return NULL;
  733. }
  734. memset(image, 0, headersz);
  735. main_hdr = (struct main_hdr_v0 *)image;
  736. /* Fill in the main header */
  737. main_hdr->blocksize =
  738. cpu_to_le32(payloadsz + sizeof(uint32_t) - headersz);
  739. main_hdr->srcaddr = cpu_to_le32(headersz);
  740. main_hdr->ext = has_ext;
  741. main_hdr->destaddr = cpu_to_le32(params->addr);
  742. main_hdr->execaddr = cpu_to_le32(params->ep);
  743. e = image_find_option(IMAGE_CFG_BOOT_FROM);
  744. if (e)
  745. main_hdr->blockid = e->bootfrom;
  746. e = image_find_option(IMAGE_CFG_NAND_ECC_MODE);
  747. if (e)
  748. main_hdr->nandeccmode = e->nandeccmode;
  749. e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
  750. if (e)
  751. main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
  752. main_hdr->checksum = image_checksum8(image,
  753. sizeof(struct main_hdr_v0));
  754. /* Generate the ext header */
  755. if (has_ext) {
  756. struct ext_hdr_v0 *ext_hdr;
  757. int cfgi, datai;
  758. ext_hdr = (struct ext_hdr_v0 *)
  759. (image + sizeof(struct main_hdr_v0));
  760. ext_hdr->offset = cpu_to_le32(0x40);
  761. for (cfgi = 0, datai = 0; cfgi < cfgn; cfgi++) {
  762. e = &image_cfg[cfgi];
  763. if (e->type != IMAGE_CFG_DATA)
  764. continue;
  765. ext_hdr->rcfg[datai].raddr =
  766. cpu_to_le32(e->regdata.raddr);
  767. ext_hdr->rcfg[datai].rdata =
  768. cpu_to_le32(e->regdata.rdata);
  769. datai++;
  770. }
  771. ext_hdr->checksum = image_checksum8(ext_hdr,
  772. sizeof(struct ext_hdr_v0));
  773. }
  774. *imagesz = headersz;
  775. return image;
  776. }
  777. static size_t image_headersz_v1(int *hasext)
  778. {
  779. struct image_cfg_element *binarye;
  780. size_t headersz;
  781. /*
  782. * Calculate the size of the header and the size of the
  783. * payload
  784. */
  785. headersz = sizeof(struct main_hdr_v1);
  786. if (image_count_options(IMAGE_CFG_BINARY) > 1) {
  787. fprintf(stderr, "More than one binary blob, not supported\n");
  788. return 0;
  789. }
  790. if (image_count_options(IMAGE_CFG_PAYLOAD) > 1) {
  791. fprintf(stderr, "More than one payload, not possible\n");
  792. return 0;
  793. }
  794. binarye = image_find_option(IMAGE_CFG_BINARY);
  795. if (binarye) {
  796. int ret;
  797. struct stat s;
  798. ret = stat(binarye->binary.file, &s);
  799. if (ret < 0) {
  800. char cwd[PATH_MAX];
  801. char *dir = cwd;
  802. memset(cwd, 0, sizeof(cwd));
  803. if (!getcwd(cwd, sizeof(cwd))) {
  804. dir = "current working directory";
  805. perror("getcwd() failed");
  806. }
  807. fprintf(stderr,
  808. "Didn't find the file '%s' in '%s' which is mandatory to generate the image\n"
  809. "This file generally contains the DDR3 training code, and should be extracted from an existing bootable\n"
  810. "image for your board. See 'kwbimage -x' to extract it from an existing image.\n",
  811. binarye->binary.file, dir);
  812. return 0;
  813. }
  814. headersz += sizeof(struct opt_hdr_v1) +
  815. s.st_size +
  816. (binarye->binary.nargs + 2) * sizeof(uint32_t);
  817. if (hasext)
  818. *hasext = 1;
  819. }
  820. #if defined(CONFIG_KWB_SECURE)
  821. if (image_get_csk_index() >= 0) {
  822. headersz += sizeof(struct secure_hdr_v1);
  823. if (hasext)
  824. *hasext = 1;
  825. }
  826. #endif
  827. #if defined(CONFIG_SYS_U_BOOT_OFFS)
  828. if (headersz > CONFIG_SYS_U_BOOT_OFFS) {
  829. fprintf(stderr,
  830. "Error: Image header (incl. SPL image) too big!\n");
  831. fprintf(stderr, "header=0x%x CONFIG_SYS_U_BOOT_OFFS=0x%x!\n",
  832. (int)headersz, CONFIG_SYS_U_BOOT_OFFS);
  833. fprintf(stderr, "Increase CONFIG_SYS_U_BOOT_OFFS!\n");
  834. return 0;
  835. }
  836. headersz = CONFIG_SYS_U_BOOT_OFFS;
  837. #endif
  838. /*
  839. * The payload should be aligned on some reasonable
  840. * boundary
  841. */
  842. return ALIGN_SUP(headersz, 4096);
  843. }
  844. int add_binary_header_v1(uint8_t *cur)
  845. {
  846. struct image_cfg_element *binarye;
  847. struct opt_hdr_v1 *hdr = (struct opt_hdr_v1 *)cur;
  848. uint32_t *args;
  849. size_t binhdrsz;
  850. struct stat s;
  851. int argi;
  852. FILE *bin;
  853. int ret;
  854. binarye = image_find_option(IMAGE_CFG_BINARY);
  855. if (!binarye)
  856. return 0;
  857. hdr->headertype = OPT_HDR_V1_BINARY_TYPE;
  858. bin = fopen(binarye->binary.file, "r");
  859. if (!bin) {
  860. fprintf(stderr, "Cannot open binary file %s\n",
  861. binarye->binary.file);
  862. return -1;
  863. }
  864. if (fstat(fileno(bin), &s)) {
  865. fprintf(stderr, "Cannot stat binary file %s\n",
  866. binarye->binary.file);
  867. goto err_close;
  868. }
  869. binhdrsz = sizeof(struct opt_hdr_v1) +
  870. (binarye->binary.nargs + 2) * sizeof(uint32_t) +
  871. s.st_size;
  872. /*
  873. * The size includes the binary image size, rounded
  874. * up to a 4-byte boundary. Plus 4 bytes for the
  875. * next-header byte and 3-byte alignment at the end.
  876. */
  877. binhdrsz = ALIGN_SUP(binhdrsz, 4) + 4;
  878. hdr->headersz_lsb = cpu_to_le16(binhdrsz & 0xFFFF);
  879. hdr->headersz_msb = (binhdrsz & 0xFFFF0000) >> 16;
  880. cur += sizeof(struct opt_hdr_v1);
  881. args = (uint32_t *)cur;
  882. *args = cpu_to_le32(binarye->binary.nargs);
  883. args++;
  884. for (argi = 0; argi < binarye->binary.nargs; argi++)
  885. args[argi] = cpu_to_le32(binarye->binary.args[argi]);
  886. cur += (binarye->binary.nargs + 1) * sizeof(uint32_t);
  887. ret = fread(cur, s.st_size, 1, bin);
  888. if (ret != 1) {
  889. fprintf(stderr,
  890. "Could not read binary image %s\n",
  891. binarye->binary.file);
  892. goto err_close;
  893. }
  894. fclose(bin);
  895. cur += ALIGN_SUP(s.st_size, 4);
  896. /*
  897. * For now, we don't support more than one binary
  898. * header, and no other header types are
  899. * supported. So, the binary header is necessarily the
  900. * last one
  901. */
  902. *((uint32_t *)cur) = 0x00000000;
  903. cur += sizeof(uint32_t);
  904. return 0;
  905. err_close:
  906. fclose(bin);
  907. return -1;
  908. }
  909. #if defined(CONFIG_KWB_SECURE)
  910. int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
  911. {
  912. FILE *hashf;
  913. int res;
  914. hashf = fopen("pub_kak_hash.txt", "w");
  915. res = kwb_export_pubkey(kak, &secure_hdr->kak, hashf, "KAK");
  916. fclose(hashf);
  917. return res < 0 ? 1 : 0;
  918. }
  919. int kwb_sign_csk_with_kak(struct image_tool_params *params,
  920. struct secure_hdr_v1 *secure_hdr, RSA *csk)
  921. {
  922. RSA *kak = NULL;
  923. RSA *kak_pub = NULL;
  924. int csk_idx = image_get_csk_index();
  925. struct sig_v1 tmp_sig;
  926. if (csk_idx >= 16) {
  927. fprintf(stderr, "Invalid CSK index %d\n", csk_idx);
  928. return 1;
  929. }
  930. if (kwb_load_kak(params, &kak) < 0)
  931. return 1;
  932. if (export_pub_kak_hash(kak, secure_hdr))
  933. return 1;
  934. if (kwb_import_pubkey(&kak_pub, &secure_hdr->kak, "KAK") < 0)
  935. return 1;
  936. if (kwb_export_pubkey(csk, &secure_hdr->csk[csk_idx], NULL, "CSK") < 0)
  937. return 1;
  938. if (kwb_sign_and_verify(kak, &secure_hdr->csk,
  939. sizeof(secure_hdr->csk) +
  940. sizeof(secure_hdr->csksig),
  941. &tmp_sig, "CSK") < 0)
  942. return 1;
  943. if (kwb_verify(kak_pub, &secure_hdr->csk,
  944. sizeof(secure_hdr->csk) +
  945. sizeof(secure_hdr->csksig),
  946. &tmp_sig, "CSK (2)") < 0)
  947. return 1;
  948. secure_hdr->csksig = tmp_sig;
  949. return 0;
  950. }
  951. int add_secure_header_v1(struct image_tool_params *params, uint8_t *ptr,
  952. int payloadsz, size_t headersz, uint8_t *image,
  953. struct secure_hdr_v1 *secure_hdr)
  954. {
  955. struct image_cfg_element *e_jtagdelay;
  956. struct image_cfg_element *e_boxid;
  957. struct image_cfg_element *e_flashid;
  958. RSA *csk = NULL;
  959. unsigned char *image_ptr;
  960. size_t image_size;
  961. struct sig_v1 tmp_sig;
  962. bool specialized_img = image_get_spezialized_img();
  963. kwb_msg("Create secure header content\n");
  964. e_jtagdelay = image_find_option(IMAGE_CFG_JTAG_DELAY);
  965. e_boxid = image_find_option(IMAGE_CFG_BOX_ID);
  966. e_flashid = image_find_option(IMAGE_CFG_FLASH_ID);
  967. if (kwb_load_csk(params, &csk) < 0)
  968. return 1;
  969. secure_hdr->headertype = OPT_HDR_V1_SECURE_TYPE;
  970. secure_hdr->headersz_msb = 0;
  971. secure_hdr->headersz_lsb = cpu_to_le16(sizeof(struct secure_hdr_v1));
  972. if (e_jtagdelay)
  973. secure_hdr->jtag_delay = e_jtagdelay->jtag_delay;
  974. if (e_boxid && specialized_img)
  975. secure_hdr->boxid = cpu_to_le32(e_boxid->boxid);
  976. if (e_flashid && specialized_img)
  977. secure_hdr->flashid = cpu_to_le32(e_flashid->flashid);
  978. if (kwb_sign_csk_with_kak(params, secure_hdr, csk))
  979. return 1;
  980. image_ptr = ptr + headersz;
  981. image_size = payloadsz - headersz;
  982. if (kwb_sign_and_verify(csk, image_ptr, image_size,
  983. &secure_hdr->imgsig, "image") < 0)
  984. return 1;
  985. if (kwb_sign_and_verify(csk, image, headersz, &tmp_sig, "header") < 0)
  986. return 1;
  987. secure_hdr->hdrsig = tmp_sig;
  988. kwb_dump_fuse_cmds(secure_hdr);
  989. return 0;
  990. }
  991. #endif
  992. static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
  993. uint8_t *ptr, int payloadsz)
  994. {
  995. struct image_cfg_element *e;
  996. struct main_hdr_v1 *main_hdr;
  997. #if defined(CONFIG_KWB_SECURE)
  998. struct secure_hdr_v1 *secure_hdr = NULL;
  999. #endif
  1000. size_t headersz;
  1001. uint8_t *image, *cur;
  1002. int hasext = 0;
  1003. uint8_t *next_ext = NULL;
  1004. /*
  1005. * Calculate the size of the header and the size of the
  1006. * payload
  1007. */
  1008. headersz = image_headersz_v1(&hasext);
  1009. if (headersz == 0)
  1010. return NULL;
  1011. image = malloc(headersz);
  1012. if (!image) {
  1013. fprintf(stderr, "Cannot allocate memory for image\n");
  1014. return NULL;
  1015. }
  1016. memset(image, 0, headersz);
  1017. main_hdr = (struct main_hdr_v1 *)image;
  1018. cur = image;
  1019. cur += sizeof(struct main_hdr_v1);
  1020. next_ext = &main_hdr->ext;
  1021. /* Fill the main header */
  1022. main_hdr->blocksize =
  1023. cpu_to_le32(payloadsz - headersz + sizeof(uint32_t));
  1024. main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
  1025. main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
  1026. main_hdr->destaddr = cpu_to_le32(params->addr)
  1027. - sizeof(image_header_t);
  1028. main_hdr->execaddr = cpu_to_le32(params->ep);
  1029. main_hdr->srcaddr = cpu_to_le32(headersz);
  1030. main_hdr->ext = hasext;
  1031. main_hdr->version = 1;
  1032. e = image_find_option(IMAGE_CFG_BOOT_FROM);
  1033. if (e)
  1034. main_hdr->blockid = e->bootfrom;
  1035. e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
  1036. if (e)
  1037. main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
  1038. e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
  1039. if (e)
  1040. main_hdr->nandbadblklocation = e->nandbadblklocation;
  1041. e = image_find_option(IMAGE_CFG_BAUDRATE);
  1042. if (e)
  1043. main_hdr->options = baudrate_to_option(e->baudrate);
  1044. e = image_find_option(IMAGE_CFG_DEBUG);
  1045. if (e)
  1046. main_hdr->flags = e->debug ? 0x1 : 0;
  1047. e = image_find_option(IMAGE_CFG_BINARY);
  1048. if (e) {
  1049. char *s = strrchr(e->binary.file, '/');
  1050. if (strcmp(s, "/binary.0") == 0)
  1051. main_hdr->destaddr = cpu_to_le32(params->addr);
  1052. }
  1053. #if defined(CONFIG_KWB_SECURE)
  1054. if (image_get_csk_index() >= 0) {
  1055. /*
  1056. * only reserve the space here; we fill the header later since
  1057. * we need the header to be complete to compute the signatures
  1058. */
  1059. secure_hdr = (struct secure_hdr_v1 *)cur;
  1060. cur += sizeof(struct secure_hdr_v1);
  1061. next_ext = &secure_hdr->next;
  1062. }
  1063. #endif
  1064. *next_ext = 1;
  1065. if (add_binary_header_v1(cur))
  1066. return NULL;
  1067. #if defined(CONFIG_KWB_SECURE)
  1068. if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz,
  1069. headersz, image, secure_hdr))
  1070. return NULL;
  1071. #endif
  1072. /* Calculate and set the header checksum */
  1073. main_hdr->checksum = image_checksum8(main_hdr, headersz);
  1074. *imagesz = headersz;
  1075. return image;
  1076. }
  1077. int recognize_keyword(char *keyword)
  1078. {
  1079. int kw_id;
  1080. for (kw_id = 1; kw_id < IMAGE_CFG_COUNT; ++kw_id)
  1081. if (!strcmp(keyword, id_strs[kw_id]))
  1082. return kw_id;
  1083. return 0;
  1084. }
  1085. static int image_create_config_parse_oneline(char *line,
  1086. struct image_cfg_element *el)
  1087. {
  1088. char *keyword, *saveptr, *value1, *value2;
  1089. char delimiters[] = " \t";
  1090. int keyword_id, ret, argi;
  1091. char *unknown_msg = "Ignoring unknown line '%s'\n";
  1092. keyword = strtok_r(line, delimiters, &saveptr);
  1093. keyword_id = recognize_keyword(keyword);
  1094. if (!keyword_id) {
  1095. fprintf(stderr, unknown_msg, line);
  1096. return 0;
  1097. }
  1098. el->type = keyword_id;
  1099. value1 = strtok_r(NULL, delimiters, &saveptr);
  1100. if (!value1) {
  1101. fprintf(stderr, "Parameter missing in line '%s'\n", line);
  1102. return -1;
  1103. }
  1104. switch (keyword_id) {
  1105. case IMAGE_CFG_VERSION:
  1106. el->version = atoi(value1);
  1107. break;
  1108. case IMAGE_CFG_BOOT_FROM:
  1109. ret = image_boot_mode_id(value1);
  1110. if (ret < 0) {
  1111. fprintf(stderr, "Invalid boot media '%s'\n", value1);
  1112. return -1;
  1113. }
  1114. el->bootfrom = ret;
  1115. break;
  1116. case IMAGE_CFG_NAND_BLKSZ:
  1117. el->nandblksz = strtoul(value1, NULL, 16);
  1118. break;
  1119. case IMAGE_CFG_NAND_BADBLK_LOCATION:
  1120. el->nandbadblklocation = strtoul(value1, NULL, 16);
  1121. break;
  1122. case IMAGE_CFG_NAND_ECC_MODE:
  1123. ret = image_nand_ecc_mode_id(value1);
  1124. if (ret < 0) {
  1125. fprintf(stderr, "Invalid NAND ECC mode '%s'\n", value1);
  1126. return -1;
  1127. }
  1128. el->nandeccmode = ret;
  1129. break;
  1130. case IMAGE_CFG_NAND_PAGESZ:
  1131. el->nandpagesz = strtoul(value1, NULL, 16);
  1132. break;
  1133. case IMAGE_CFG_BINARY:
  1134. argi = 0;
  1135. el->binary.file = strdup(value1);
  1136. while (1) {
  1137. char *value = strtok_r(NULL, delimiters, &saveptr);
  1138. if (!value)
  1139. break;
  1140. el->binary.args[argi] = strtoul(value, NULL, 16);
  1141. argi++;
  1142. if (argi >= BINARY_MAX_ARGS) {
  1143. fprintf(stderr,
  1144. "Too many arguments for BINARY\n");
  1145. return -1;
  1146. }
  1147. }
  1148. el->binary.nargs = argi;
  1149. break;
  1150. case IMAGE_CFG_DATA:
  1151. value2 = strtok_r(NULL, delimiters, &saveptr);
  1152. if (!value1 || !value2) {
  1153. fprintf(stderr,
  1154. "Invalid number of arguments for DATA\n");
  1155. return -1;
  1156. }
  1157. el->regdata.raddr = strtoul(value1, NULL, 16);
  1158. el->regdata.rdata = strtoul(value2, NULL, 16);
  1159. break;
  1160. case IMAGE_CFG_BAUDRATE:
  1161. el->baudrate = strtoul(value1, NULL, 10);
  1162. break;
  1163. case IMAGE_CFG_DEBUG:
  1164. el->debug = strtoul(value1, NULL, 10);
  1165. break;
  1166. case IMAGE_CFG_KAK:
  1167. el->key_name = strdup(value1);
  1168. break;
  1169. case IMAGE_CFG_CSK:
  1170. el->key_name = strdup(value1);
  1171. break;
  1172. case IMAGE_CFG_CSK_INDEX:
  1173. el->csk_idx = strtol(value1, NULL, 0);
  1174. break;
  1175. case IMAGE_CFG_JTAG_DELAY:
  1176. el->jtag_delay = strtoul(value1, NULL, 0);
  1177. break;
  1178. case IMAGE_CFG_BOX_ID:
  1179. el->boxid = strtoul(value1, NULL, 0);
  1180. break;
  1181. case IMAGE_CFG_FLASH_ID:
  1182. el->flashid = strtoul(value1, NULL, 0);
  1183. break;
  1184. case IMAGE_CFG_SEC_SPECIALIZED_IMG:
  1185. el->sec_specialized_img = true;
  1186. break;
  1187. case IMAGE_CFG_SEC_COMMON_IMG:
  1188. el->sec_specialized_img = false;
  1189. break;
  1190. case IMAGE_CFG_SEC_BOOT_DEV:
  1191. el->sec_boot_dev = strtoul(value1, NULL, 0);
  1192. break;
  1193. case IMAGE_CFG_SEC_FUSE_DUMP:
  1194. el->name = strdup(value1);
  1195. break;
  1196. default:
  1197. fprintf(stderr, unknown_msg, line);
  1198. }
  1199. return 0;
  1200. }
  1201. /*
  1202. * Parse the configuration file 'fcfg' into the array of configuration
  1203. * elements 'image_cfg', and return the number of configuration
  1204. * elements in 'cfgn'.
  1205. */
  1206. static int image_create_config_parse(FILE *fcfg)
  1207. {
  1208. int ret;
  1209. int cfgi = 0;
  1210. /* Parse the configuration file */
  1211. while (!feof(fcfg)) {
  1212. char *line;
  1213. char buf[256];
  1214. /* Read the current line */
  1215. memset(buf, 0, sizeof(buf));
  1216. line = fgets(buf, sizeof(buf), fcfg);
  1217. if (!line)
  1218. break;
  1219. /* Ignore useless lines */
  1220. if (line[0] == '\n' || line[0] == '#')
  1221. continue;
  1222. /* Strip final newline */
  1223. if (line[strlen(line) - 1] == '\n')
  1224. line[strlen(line) - 1] = 0;
  1225. /* Parse the current line */
  1226. ret = image_create_config_parse_oneline(line,
  1227. &image_cfg[cfgi]);
  1228. if (ret)
  1229. return ret;
  1230. cfgi++;
  1231. if (cfgi >= IMAGE_CFG_ELEMENT_MAX) {
  1232. fprintf(stderr,
  1233. "Too many configuration elements in .cfg file\n");
  1234. return -1;
  1235. }
  1236. }
  1237. cfgn = cfgi;
  1238. return 0;
  1239. }
  1240. static int image_get_version(void)
  1241. {
  1242. struct image_cfg_element *e;
  1243. e = image_find_option(IMAGE_CFG_VERSION);
  1244. if (!e)
  1245. return -1;
  1246. return e->version;
  1247. }
  1248. static void kwbimage_set_header(void *ptr, struct stat *sbuf, int ifd,
  1249. struct image_tool_params *params)
  1250. {
  1251. FILE *fcfg;
  1252. void *image = NULL;
  1253. int version;
  1254. size_t headersz = 0;
  1255. uint32_t checksum;
  1256. int ret;
  1257. int size;
  1258. fcfg = fopen(params->imagename, "r");
  1259. if (!fcfg) {
  1260. fprintf(stderr, "Could not open input file %s\n",
  1261. params->imagename);
  1262. exit(EXIT_FAILURE);
  1263. }
  1264. image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
  1265. sizeof(struct image_cfg_element));
  1266. if (!image_cfg) {
  1267. fprintf(stderr, "Cannot allocate memory\n");
  1268. fclose(fcfg);
  1269. exit(EXIT_FAILURE);
  1270. }
  1271. memset(image_cfg, 0,
  1272. IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
  1273. rewind(fcfg);
  1274. ret = image_create_config_parse(fcfg);
  1275. fclose(fcfg);
  1276. if (ret) {
  1277. free(image_cfg);
  1278. exit(EXIT_FAILURE);
  1279. }
  1280. /* The MVEBU BootROM does not allow non word aligned payloads */
  1281. sbuf->st_size = ALIGN_SUP(sbuf->st_size, 4);
  1282. version = image_get_version();
  1283. switch (version) {
  1284. /*
  1285. * Fallback to version 0 if no version is provided in the
  1286. * cfg file
  1287. */
  1288. case -1:
  1289. case 0:
  1290. image = image_create_v0(&headersz, params, sbuf->st_size);
  1291. break;
  1292. case 1:
  1293. image = image_create_v1(&headersz, params, ptr, sbuf->st_size);
  1294. break;
  1295. default:
  1296. fprintf(stderr, "Unsupported version %d\n", version);
  1297. free(image_cfg);
  1298. exit(EXIT_FAILURE);
  1299. }
  1300. if (!image) {
  1301. fprintf(stderr, "Could not create image\n");
  1302. free(image_cfg);
  1303. exit(EXIT_FAILURE);
  1304. }
  1305. free(image_cfg);
  1306. /* Build and add image checksum header */
  1307. checksum =
  1308. cpu_to_le32(image_checksum32((uint32_t *)ptr, sbuf->st_size));
  1309. size = write(ifd, &checksum, sizeof(uint32_t));
  1310. if (size != sizeof(uint32_t)) {
  1311. fprintf(stderr, "Error:%s - Checksum write %d bytes %s\n",
  1312. params->cmdname, size, params->imagefile);
  1313. exit(EXIT_FAILURE);
  1314. }
  1315. sbuf->st_size += sizeof(uint32_t);
  1316. /* Finally copy the header into the image area */
  1317. memcpy(ptr, image, headersz);
  1318. free(image);
  1319. }
  1320. static void kwbimage_print_header(const void *ptr)
  1321. {
  1322. struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
  1323. printf("Image Type: MVEBU Boot from %s Image\n",
  1324. image_boot_mode_name(mhdr->blockid));
  1325. printf("Image version:%d\n", image_version((void *)ptr));
  1326. printf("Data Size: ");
  1327. genimg_print_size(mhdr->blocksize - sizeof(uint32_t));
  1328. printf("Load Address: %08x\n", mhdr->destaddr);
  1329. printf("Entry Point: %08x\n", mhdr->execaddr);
  1330. }
  1331. static int kwbimage_check_image_types(uint8_t type)
  1332. {
  1333. if (type == IH_TYPE_KWBIMAGE)
  1334. return EXIT_SUCCESS;
  1335. return EXIT_FAILURE;
  1336. }
  1337. static int kwbimage_verify_header(unsigned char *ptr, int image_size,
  1338. struct image_tool_params *params)
  1339. {
  1340. uint8_t checksum;
  1341. size_t header_size = kwbimage_header_size(ptr);
  1342. if (header_size > image_size)
  1343. return -FDT_ERR_BADSTRUCTURE;
  1344. if (!main_hdr_checksum_ok(ptr))
  1345. return -FDT_ERR_BADSTRUCTURE;
  1346. /* Only version 0 extended header has checksum */
  1347. if (image_version((void *)ptr) == 0) {
  1348. struct ext_hdr_v0 *ext_hdr;
  1349. ext_hdr = (struct ext_hdr_v0 *)
  1350. (ptr + sizeof(struct main_hdr_v0));
  1351. checksum = image_checksum8(ext_hdr,
  1352. sizeof(struct ext_hdr_v0)
  1353. - sizeof(uint8_t));
  1354. if (checksum != ext_hdr->checksum)
  1355. return -FDT_ERR_BADSTRUCTURE;
  1356. }
  1357. return 0;
  1358. }
  1359. static int kwbimage_generate(struct image_tool_params *params,
  1360. struct image_type_params *tparams)
  1361. {
  1362. FILE *fcfg;
  1363. int alloc_len;
  1364. int version;
  1365. void *hdr;
  1366. int ret;
  1367. fcfg = fopen(params->imagename, "r");
  1368. if (!fcfg) {
  1369. fprintf(stderr, "Could not open input file %s\n",
  1370. params->imagename);
  1371. exit(EXIT_FAILURE);
  1372. }
  1373. image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
  1374. sizeof(struct image_cfg_element));
  1375. if (!image_cfg) {
  1376. fprintf(stderr, "Cannot allocate memory\n");
  1377. fclose(fcfg);
  1378. exit(EXIT_FAILURE);
  1379. }
  1380. memset(image_cfg, 0,
  1381. IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
  1382. rewind(fcfg);
  1383. ret = image_create_config_parse(fcfg);
  1384. fclose(fcfg);
  1385. if (ret) {
  1386. free(image_cfg);
  1387. exit(EXIT_FAILURE);
  1388. }
  1389. version = image_get_version();
  1390. switch (version) {
  1391. /*
  1392. * Fallback to version 0 if no version is provided in the
  1393. * cfg file
  1394. */
  1395. case -1:
  1396. case 0:
  1397. alloc_len = sizeof(struct main_hdr_v0) +
  1398. sizeof(struct ext_hdr_v0);
  1399. break;
  1400. case 1:
  1401. alloc_len = image_headersz_v1(NULL);
  1402. break;
  1403. default:
  1404. fprintf(stderr, "Unsupported version %d\n", version);
  1405. free(image_cfg);
  1406. exit(EXIT_FAILURE);
  1407. }
  1408. free(image_cfg);
  1409. hdr = malloc(alloc_len);
  1410. if (!hdr) {
  1411. fprintf(stderr, "%s: malloc return failure: %s\n",
  1412. params->cmdname, strerror(errno));
  1413. exit(EXIT_FAILURE);
  1414. }
  1415. memset(hdr, 0, alloc_len);
  1416. tparams->header_size = alloc_len;
  1417. tparams->hdr = hdr;
  1418. /*
  1419. * The resulting image needs to be 4-byte aligned. At least
  1420. * the Marvell hdrparser tool complains if its unaligned.
  1421. * By returning 1 here in this function, called via
  1422. * tparams->vrec_header() in mkimage.c, mkimage will
  1423. * automatically pad the the resulting image to a 4-byte
  1424. * size if necessary.
  1425. */
  1426. return 1;
  1427. }
  1428. /*
  1429. * Report Error if xflag is set in addition to default
  1430. */
  1431. static int kwbimage_check_params(struct image_tool_params *params)
  1432. {
  1433. if (!strlen(params->imagename)) {
  1434. char *msg = "Configuration file for kwbimage creation omitted";
  1435. fprintf(stderr, "Error:%s - %s\n", params->cmdname, msg);
  1436. return CFG_INVALID;
  1437. }
  1438. return (params->dflag && (params->fflag || params->lflag)) ||
  1439. (params->fflag && (params->dflag || params->lflag)) ||
  1440. (params->lflag && (params->dflag || params->fflag)) ||
  1441. (params->xflag) || !(strlen(params->imagename));
  1442. }
  1443. /*
  1444. * kwbimage type parameters definition
  1445. */
  1446. U_BOOT_IMAGE_TYPE(
  1447. kwbimage,
  1448. "Marvell MVEBU Boot Image support",
  1449. 0,
  1450. NULL,
  1451. kwbimage_check_params,
  1452. kwbimage_verify_header,
  1453. kwbimage_print_header,
  1454. kwbimage_set_header,
  1455. NULL,
  1456. kwbimage_check_image_types,
  1457. NULL,
  1458. kwbimage_generate
  1459. );