kwbimage.c 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Image manipulator for Marvell SoCs
  4. * supports Kirkwood, Dove, Armada 370, Armada XP, Armada 375, Armada 38x and
  5. * Armada 39x
  6. *
  7. * (C) Copyright 2013 Thomas Petazzoni
  8. * <thomas.petazzoni@free-electrons.com>
  9. */
  10. #define OPENSSL_API_COMPAT 0x10101000L
  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. #include <openssl/bn.h>
  18. #include <openssl/rsa.h>
  19. #include <openssl/pem.h>
  20. #include <openssl/err.h>
  21. #include <openssl/evp.h>
  22. #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
  23. (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
  24. static void RSA_get0_key(const RSA *r,
  25. const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
  26. {
  27. if (n != NULL)
  28. *n = r->n;
  29. if (e != NULL)
  30. *e = r->e;
  31. if (d != NULL)
  32. *d = r->d;
  33. }
  34. #elif !defined(LIBRESSL_VERSION_NUMBER)
  35. void EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
  36. {
  37. EVP_MD_CTX_reset(ctx);
  38. }
  39. #endif
  40. static struct image_cfg_element *image_cfg;
  41. static int cfgn;
  42. static int verbose_mode;
  43. struct boot_mode {
  44. unsigned int id;
  45. const char *name;
  46. };
  47. /*
  48. * SHA2-256 hash
  49. */
  50. struct hash_v1 {
  51. uint8_t hash[32];
  52. };
  53. struct boot_mode boot_modes[] = {
  54. { IBR_HDR_I2C_ID, "i2c" },
  55. { IBR_HDR_SPI_ID, "spi" },
  56. { IBR_HDR_NAND_ID, "nand" },
  57. { IBR_HDR_SATA_ID, "sata" },
  58. { IBR_HDR_PEX_ID, "pex" },
  59. { IBR_HDR_UART_ID, "uart" },
  60. { IBR_HDR_SDIO_ID, "sdio" },
  61. {},
  62. };
  63. struct nand_ecc_mode {
  64. unsigned int id;
  65. const char *name;
  66. };
  67. struct nand_ecc_mode nand_ecc_modes[] = {
  68. { IBR_HDR_ECC_DEFAULT, "default" },
  69. { IBR_HDR_ECC_FORCED_HAMMING, "hamming" },
  70. { IBR_HDR_ECC_FORCED_RS, "rs" },
  71. { IBR_HDR_ECC_DISABLED, "disabled" },
  72. {},
  73. };
  74. /* Used to identify an undefined execution or destination address */
  75. #define ADDR_INVALID ((uint32_t)-1)
  76. #define BINARY_MAX_ARGS 255
  77. /* In-memory representation of a line of the configuration file */
  78. enum image_cfg_type {
  79. IMAGE_CFG_VERSION = 0x1,
  80. IMAGE_CFG_BOOT_FROM,
  81. IMAGE_CFG_DEST_ADDR,
  82. IMAGE_CFG_EXEC_ADDR,
  83. IMAGE_CFG_NAND_BLKSZ,
  84. IMAGE_CFG_NAND_BADBLK_LOCATION,
  85. IMAGE_CFG_NAND_ECC_MODE,
  86. IMAGE_CFG_NAND_PAGESZ,
  87. IMAGE_CFG_CPU,
  88. IMAGE_CFG_BINARY,
  89. IMAGE_CFG_DATA,
  90. IMAGE_CFG_DATA_DELAY,
  91. IMAGE_CFG_BAUDRATE,
  92. IMAGE_CFG_UART_PORT,
  93. IMAGE_CFG_UART_MPP,
  94. IMAGE_CFG_DEBUG,
  95. IMAGE_CFG_KAK,
  96. IMAGE_CFG_CSK,
  97. IMAGE_CFG_CSK_INDEX,
  98. IMAGE_CFG_JTAG_DELAY,
  99. IMAGE_CFG_BOX_ID,
  100. IMAGE_CFG_FLASH_ID,
  101. IMAGE_CFG_SEC_COMMON_IMG,
  102. IMAGE_CFG_SEC_SPECIALIZED_IMG,
  103. IMAGE_CFG_SEC_BOOT_DEV,
  104. IMAGE_CFG_SEC_FUSE_DUMP,
  105. IMAGE_CFG_COUNT
  106. } type;
  107. static const char * const id_strs[] = {
  108. [IMAGE_CFG_VERSION] = "VERSION",
  109. [IMAGE_CFG_BOOT_FROM] = "BOOT_FROM",
  110. [IMAGE_CFG_DEST_ADDR] = "DEST_ADDR",
  111. [IMAGE_CFG_EXEC_ADDR] = "EXEC_ADDR",
  112. [IMAGE_CFG_NAND_BLKSZ] = "NAND_BLKSZ",
  113. [IMAGE_CFG_NAND_BADBLK_LOCATION] = "NAND_BADBLK_LOCATION",
  114. [IMAGE_CFG_NAND_ECC_MODE] = "NAND_ECC_MODE",
  115. [IMAGE_CFG_NAND_PAGESZ] = "NAND_PAGE_SIZE",
  116. [IMAGE_CFG_CPU] = "CPU",
  117. [IMAGE_CFG_BINARY] = "BINARY",
  118. [IMAGE_CFG_DATA] = "DATA",
  119. [IMAGE_CFG_DATA_DELAY] = "DATA_DELAY",
  120. [IMAGE_CFG_BAUDRATE] = "BAUDRATE",
  121. [IMAGE_CFG_UART_PORT] = "UART_PORT",
  122. [IMAGE_CFG_UART_MPP] = "UART_MPP",
  123. [IMAGE_CFG_DEBUG] = "DEBUG",
  124. [IMAGE_CFG_KAK] = "KAK",
  125. [IMAGE_CFG_CSK] = "CSK",
  126. [IMAGE_CFG_CSK_INDEX] = "CSK_INDEX",
  127. [IMAGE_CFG_JTAG_DELAY] = "JTAG_DELAY",
  128. [IMAGE_CFG_BOX_ID] = "BOX_ID",
  129. [IMAGE_CFG_FLASH_ID] = "FLASH_ID",
  130. [IMAGE_CFG_SEC_COMMON_IMG] = "SEC_COMMON_IMG",
  131. [IMAGE_CFG_SEC_SPECIALIZED_IMG] = "SEC_SPECIALIZED_IMG",
  132. [IMAGE_CFG_SEC_BOOT_DEV] = "SEC_BOOT_DEV",
  133. [IMAGE_CFG_SEC_FUSE_DUMP] = "SEC_FUSE_DUMP"
  134. };
  135. struct image_cfg_element {
  136. enum image_cfg_type type;
  137. union {
  138. unsigned int version;
  139. unsigned int cpu_sheeva;
  140. unsigned int bootfrom;
  141. struct {
  142. const char *file;
  143. unsigned int loadaddr;
  144. unsigned int args[BINARY_MAX_ARGS];
  145. unsigned int nargs;
  146. } binary;
  147. unsigned int dstaddr;
  148. unsigned int execaddr;
  149. unsigned int nandblksz;
  150. unsigned int nandbadblklocation;
  151. unsigned int nandeccmode;
  152. unsigned int nandpagesz;
  153. struct ext_hdr_v0_reg regdata;
  154. unsigned int regdata_delay;
  155. unsigned int baudrate;
  156. unsigned int uart_port;
  157. unsigned int uart_mpp;
  158. unsigned int debug;
  159. const char *key_name;
  160. int csk_idx;
  161. uint8_t jtag_delay;
  162. uint32_t boxid;
  163. uint32_t flashid;
  164. bool sec_specialized_img;
  165. unsigned int sec_boot_dev;
  166. const char *name;
  167. };
  168. };
  169. #define IMAGE_CFG_ELEMENT_MAX 256
  170. /*
  171. * Utility functions to manipulate boot mode and ecc modes (convert
  172. * them back and forth between description strings and the
  173. * corresponding numerical identifiers).
  174. */
  175. static const char *image_boot_mode_name(unsigned int id)
  176. {
  177. int i;
  178. for (i = 0; boot_modes[i].name; i++)
  179. if (boot_modes[i].id == id)
  180. return boot_modes[i].name;
  181. return NULL;
  182. }
  183. static int image_boot_mode_id(const char *boot_mode_name)
  184. {
  185. int i;
  186. for (i = 0; boot_modes[i].name; i++)
  187. if (!strcmp(boot_modes[i].name, boot_mode_name))
  188. return boot_modes[i].id;
  189. return -1;
  190. }
  191. static const char *image_nand_ecc_mode_name(unsigned int id)
  192. {
  193. int i;
  194. for (i = 0; nand_ecc_modes[i].name; i++)
  195. if (nand_ecc_modes[i].id == id)
  196. return nand_ecc_modes[i].name;
  197. return NULL;
  198. }
  199. static int image_nand_ecc_mode_id(const char *nand_ecc_mode_name)
  200. {
  201. int i;
  202. for (i = 0; nand_ecc_modes[i].name; i++)
  203. if (!strcmp(nand_ecc_modes[i].name, nand_ecc_mode_name))
  204. return nand_ecc_modes[i].id;
  205. return -1;
  206. }
  207. static struct image_cfg_element *
  208. image_find_option(unsigned int optiontype)
  209. {
  210. int i;
  211. for (i = 0; i < cfgn; i++) {
  212. if (image_cfg[i].type == optiontype)
  213. return &image_cfg[i];
  214. }
  215. return NULL;
  216. }
  217. static unsigned int
  218. image_count_options(unsigned int optiontype)
  219. {
  220. int i;
  221. unsigned int count = 0;
  222. for (i = 0; i < cfgn; i++)
  223. if (image_cfg[i].type == optiontype)
  224. count++;
  225. return count;
  226. }
  227. static int image_get_csk_index(void)
  228. {
  229. struct image_cfg_element *e;
  230. e = image_find_option(IMAGE_CFG_CSK_INDEX);
  231. if (!e)
  232. return -1;
  233. return e->csk_idx;
  234. }
  235. static bool image_get_spezialized_img(void)
  236. {
  237. struct image_cfg_element *e;
  238. e = image_find_option(IMAGE_CFG_SEC_SPECIALIZED_IMG);
  239. if (!e)
  240. return false;
  241. return e->sec_specialized_img;
  242. }
  243. static int image_get_bootfrom(void)
  244. {
  245. struct image_cfg_element *e;
  246. e = image_find_option(IMAGE_CFG_BOOT_FROM);
  247. if (!e)
  248. /* fallback to SPI if no BOOT_FROM is not provided */
  249. return IBR_HDR_SPI_ID;
  250. return e->bootfrom;
  251. }
  252. static int image_is_cpu_sheeva(void)
  253. {
  254. struct image_cfg_element *e;
  255. e = image_find_option(IMAGE_CFG_CPU);
  256. if (!e)
  257. return 0;
  258. return e->cpu_sheeva;
  259. }
  260. /*
  261. * Compute a 8-bit checksum of a memory area. This algorithm follows
  262. * the requirements of the Marvell SoC BootROM specifications.
  263. */
  264. static uint8_t image_checksum8(void *start, uint32_t len)
  265. {
  266. uint8_t csum = 0;
  267. uint8_t *p = start;
  268. /* check len and return zero checksum if invalid */
  269. if (!len)
  270. return 0;
  271. do {
  272. csum += *p;
  273. p++;
  274. } while (--len);
  275. return csum;
  276. }
  277. /*
  278. * Verify checksum over a complete header that includes the checksum field.
  279. * Return 1 when OK, otherwise 0.
  280. */
  281. static int main_hdr_checksum_ok(void *hdr)
  282. {
  283. /* Offsets of checksum in v0 and v1 headers are the same */
  284. struct main_hdr_v0 *main_hdr = (struct main_hdr_v0 *)hdr;
  285. uint8_t checksum;
  286. checksum = image_checksum8(hdr, kwbheader_size_for_csum(hdr));
  287. /* Calculated checksum includes the header checksum field. Compensate
  288. * for that.
  289. */
  290. checksum -= main_hdr->checksum;
  291. return checksum == main_hdr->checksum;
  292. }
  293. static uint32_t image_checksum32(void *start, uint32_t len)
  294. {
  295. uint32_t csum = 0;
  296. uint32_t *p = start;
  297. /* check len and return zero checksum if invalid */
  298. if (!len)
  299. return 0;
  300. if (len % sizeof(uint32_t)) {
  301. fprintf(stderr, "Length %d is not in multiple of %zu\n",
  302. len, sizeof(uint32_t));
  303. return 0;
  304. }
  305. do {
  306. csum += *p;
  307. p++;
  308. len -= sizeof(uint32_t);
  309. } while (len > 0);
  310. return csum;
  311. }
  312. static unsigned int options_to_baudrate(uint8_t options)
  313. {
  314. switch (options & 0x7) {
  315. case MAIN_HDR_V1_OPT_BAUD_2400:
  316. return 2400;
  317. case MAIN_HDR_V1_OPT_BAUD_4800:
  318. return 4800;
  319. case MAIN_HDR_V1_OPT_BAUD_9600:
  320. return 9600;
  321. case MAIN_HDR_V1_OPT_BAUD_19200:
  322. return 19200;
  323. case MAIN_HDR_V1_OPT_BAUD_38400:
  324. return 38400;
  325. case MAIN_HDR_V1_OPT_BAUD_57600:
  326. return 57600;
  327. case MAIN_HDR_V1_OPT_BAUD_115200:
  328. return 115200;
  329. case MAIN_HDR_V1_OPT_BAUD_DEFAULT:
  330. default:
  331. return 0;
  332. }
  333. }
  334. static uint8_t baudrate_to_option(unsigned int baudrate)
  335. {
  336. switch (baudrate) {
  337. case 2400:
  338. return MAIN_HDR_V1_OPT_BAUD_2400;
  339. case 4800:
  340. return MAIN_HDR_V1_OPT_BAUD_4800;
  341. case 9600:
  342. return MAIN_HDR_V1_OPT_BAUD_9600;
  343. case 19200:
  344. return MAIN_HDR_V1_OPT_BAUD_19200;
  345. case 38400:
  346. return MAIN_HDR_V1_OPT_BAUD_38400;
  347. case 57600:
  348. return MAIN_HDR_V1_OPT_BAUD_57600;
  349. case 115200:
  350. return MAIN_HDR_V1_OPT_BAUD_115200;
  351. default:
  352. return MAIN_HDR_V1_OPT_BAUD_DEFAULT;
  353. }
  354. }
  355. static void kwb_msg(const char *fmt, ...)
  356. {
  357. if (verbose_mode) {
  358. va_list ap;
  359. va_start(ap, fmt);
  360. vfprintf(stdout, fmt, ap);
  361. va_end(ap);
  362. }
  363. }
  364. static int openssl_err(const char *msg)
  365. {
  366. unsigned long ssl_err = ERR_get_error();
  367. fprintf(stderr, "%s", msg);
  368. fprintf(stderr, ": %s\n",
  369. ERR_error_string(ssl_err, 0));
  370. return -1;
  371. }
  372. static int kwb_load_rsa_key(const char *keydir, const char *name, RSA **p_rsa)
  373. {
  374. char path[PATH_MAX];
  375. RSA *rsa;
  376. FILE *f;
  377. if (!keydir)
  378. keydir = ".";
  379. snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
  380. f = fopen(path, "r");
  381. if (!f) {
  382. fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
  383. path, strerror(errno));
  384. return -ENOENT;
  385. }
  386. rsa = PEM_read_RSAPrivateKey(f, 0, NULL, "");
  387. if (!rsa) {
  388. openssl_err("Failure reading private key");
  389. fclose(f);
  390. return -EPROTO;
  391. }
  392. fclose(f);
  393. *p_rsa = rsa;
  394. return 0;
  395. }
  396. static int kwb_load_cfg_key(struct image_tool_params *params,
  397. unsigned int cfg_option, const char *key_name,
  398. RSA **p_key)
  399. {
  400. struct image_cfg_element *e_key;
  401. RSA *key;
  402. int res;
  403. *p_key = NULL;
  404. e_key = image_find_option(cfg_option);
  405. if (!e_key) {
  406. fprintf(stderr, "%s not configured\n", key_name);
  407. return -ENOENT;
  408. }
  409. res = kwb_load_rsa_key(params->keydir, e_key->key_name, &key);
  410. if (res < 0) {
  411. fprintf(stderr, "Failed to load %s\n", key_name);
  412. return -ENOENT;
  413. }
  414. *p_key = key;
  415. return 0;
  416. }
  417. static int kwb_load_kak(struct image_tool_params *params, RSA **p_kak)
  418. {
  419. return kwb_load_cfg_key(params, IMAGE_CFG_KAK, "KAK", p_kak);
  420. }
  421. static int kwb_load_csk(struct image_tool_params *params, RSA **p_csk)
  422. {
  423. return kwb_load_cfg_key(params, IMAGE_CFG_CSK, "CSK", p_csk);
  424. }
  425. static int kwb_compute_pubkey_hash(struct pubkey_der_v1 *pk,
  426. struct hash_v1 *hash)
  427. {
  428. EVP_MD_CTX *ctx;
  429. unsigned int key_size;
  430. unsigned int hash_size;
  431. int ret = 0;
  432. if (!pk || !hash || pk->key[0] != 0x30 || pk->key[1] != 0x82)
  433. return -EINVAL;
  434. key_size = (pk->key[2] << 8) + pk->key[3] + 4;
  435. ctx = EVP_MD_CTX_create();
  436. if (!ctx)
  437. return openssl_err("EVP context creation failed");
  438. EVP_MD_CTX_init(ctx);
  439. if (!EVP_DigestInit(ctx, EVP_sha256())) {
  440. ret = openssl_err("Digest setup failed");
  441. goto hash_err_ctx;
  442. }
  443. if (!EVP_DigestUpdate(ctx, pk->key, key_size)) {
  444. ret = openssl_err("Hashing data failed");
  445. goto hash_err_ctx;
  446. }
  447. if (!EVP_DigestFinal(ctx, hash->hash, &hash_size)) {
  448. ret = openssl_err("Could not obtain hash");
  449. goto hash_err_ctx;
  450. }
  451. EVP_MD_CTX_cleanup(ctx);
  452. hash_err_ctx:
  453. EVP_MD_CTX_destroy(ctx);
  454. return ret;
  455. }
  456. static int kwb_import_pubkey(RSA **key, struct pubkey_der_v1 *src, char *keyname)
  457. {
  458. RSA *rsa;
  459. const unsigned char *ptr;
  460. if (!key || !src)
  461. goto fail;
  462. ptr = src->key;
  463. rsa = d2i_RSAPublicKey(key, &ptr, sizeof(src->key));
  464. if (!rsa) {
  465. openssl_err("error decoding public key");
  466. goto fail;
  467. }
  468. return 0;
  469. fail:
  470. fprintf(stderr, "Failed to decode %s pubkey\n", keyname);
  471. return -EINVAL;
  472. }
  473. static int kwb_export_pubkey(RSA *key, struct pubkey_der_v1 *dst, FILE *hashf,
  474. char *keyname)
  475. {
  476. int size_exp, size_mod, size_seq;
  477. const BIGNUM *key_e, *key_n;
  478. uint8_t *cur;
  479. char *errmsg = "Failed to encode %s\n";
  480. RSA_get0_key(key, NULL, &key_e, NULL);
  481. RSA_get0_key(key, &key_n, NULL, NULL);
  482. if (!key || !key_e || !key_n || !dst) {
  483. fprintf(stderr, "export pk failed: (%p, %p, %p, %p)",
  484. key, key_e, key_n, dst);
  485. fprintf(stderr, errmsg, keyname);
  486. return -EINVAL;
  487. }
  488. /*
  489. * According to the specs, the key should be PKCS#1 DER encoded.
  490. * But unfortunately the really required encoding seems to be different;
  491. * it violates DER...! (But it still conformes to BER.)
  492. * (Length always in long form w/ 2 byte length code; no leading zero
  493. * when MSB of first byte is set...)
  494. * So we cannot use the encoding func provided by OpenSSL and have to
  495. * do the encoding manually.
  496. */
  497. size_exp = BN_num_bytes(key_e);
  498. size_mod = BN_num_bytes(key_n);
  499. size_seq = 4 + size_mod + 4 + size_exp;
  500. if (size_mod > 256) {
  501. fprintf(stderr, "export pk failed: wrong mod size: %d\n",
  502. size_mod);
  503. fprintf(stderr, errmsg, keyname);
  504. return -EINVAL;
  505. }
  506. if (4 + size_seq > sizeof(dst->key)) {
  507. fprintf(stderr, "export pk failed: seq too large (%d, %zu)\n",
  508. 4 + size_seq, sizeof(dst->key));
  509. fprintf(stderr, errmsg, keyname);
  510. return -ENOBUFS;
  511. }
  512. cur = dst->key;
  513. /* PKCS#1 (RFC3447) RSAPublicKey structure */
  514. *cur++ = 0x30; /* SEQUENCE */
  515. *cur++ = 0x82;
  516. *cur++ = (size_seq >> 8) & 0xFF;
  517. *cur++ = size_seq & 0xFF;
  518. /* Modulus */
  519. *cur++ = 0x02; /* INTEGER */
  520. *cur++ = 0x82;
  521. *cur++ = (size_mod >> 8) & 0xFF;
  522. *cur++ = size_mod & 0xFF;
  523. BN_bn2bin(key_n, cur);
  524. cur += size_mod;
  525. /* Exponent */
  526. *cur++ = 0x02; /* INTEGER */
  527. *cur++ = 0x82;
  528. *cur++ = (size_exp >> 8) & 0xFF;
  529. *cur++ = size_exp & 0xFF;
  530. BN_bn2bin(key_e, cur);
  531. if (hashf) {
  532. struct hash_v1 pk_hash;
  533. int i;
  534. int ret = 0;
  535. ret = kwb_compute_pubkey_hash(dst, &pk_hash);
  536. if (ret < 0) {
  537. fprintf(stderr, errmsg, keyname);
  538. return ret;
  539. }
  540. fprintf(hashf, "SHA256 = ");
  541. for (i = 0 ; i < sizeof(pk_hash.hash); ++i)
  542. fprintf(hashf, "%02X", pk_hash.hash[i]);
  543. fprintf(hashf, "\n");
  544. }
  545. return 0;
  546. }
  547. static int kwb_sign(RSA *key, void *data, int datasz, struct sig_v1 *sig,
  548. char *signame)
  549. {
  550. EVP_PKEY *evp_key;
  551. EVP_MD_CTX *ctx;
  552. unsigned int sig_size;
  553. int size;
  554. int ret = 0;
  555. evp_key = EVP_PKEY_new();
  556. if (!evp_key)
  557. return openssl_err("EVP_PKEY object creation failed");
  558. if (!EVP_PKEY_set1_RSA(evp_key, key)) {
  559. ret = openssl_err("EVP key setup failed");
  560. goto err_key;
  561. }
  562. size = EVP_PKEY_size(evp_key);
  563. if (size > sizeof(sig->sig)) {
  564. fprintf(stderr, "Buffer to small for signature (%d bytes)\n",
  565. size);
  566. ret = -ENOBUFS;
  567. goto err_key;
  568. }
  569. ctx = EVP_MD_CTX_create();
  570. if (!ctx) {
  571. ret = openssl_err("EVP context creation failed");
  572. goto err_key;
  573. }
  574. EVP_MD_CTX_init(ctx);
  575. if (!EVP_SignInit(ctx, EVP_sha256())) {
  576. ret = openssl_err("Signer setup failed");
  577. goto err_ctx;
  578. }
  579. if (!EVP_SignUpdate(ctx, data, datasz)) {
  580. ret = openssl_err("Signing data failed");
  581. goto err_ctx;
  582. }
  583. if (!EVP_SignFinal(ctx, sig->sig, &sig_size, evp_key)) {
  584. ret = openssl_err("Could not obtain signature");
  585. goto err_ctx;
  586. }
  587. EVP_MD_CTX_cleanup(ctx);
  588. EVP_MD_CTX_destroy(ctx);
  589. EVP_PKEY_free(evp_key);
  590. return 0;
  591. err_ctx:
  592. EVP_MD_CTX_destroy(ctx);
  593. err_key:
  594. EVP_PKEY_free(evp_key);
  595. fprintf(stderr, "Failed to create %s signature\n", signame);
  596. return ret;
  597. }
  598. static int kwb_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
  599. char *signame)
  600. {
  601. EVP_PKEY *evp_key;
  602. EVP_MD_CTX *ctx;
  603. int size;
  604. int ret = 0;
  605. evp_key = EVP_PKEY_new();
  606. if (!evp_key)
  607. return openssl_err("EVP_PKEY object creation failed");
  608. if (!EVP_PKEY_set1_RSA(evp_key, key)) {
  609. ret = openssl_err("EVP key setup failed");
  610. goto err_key;
  611. }
  612. size = EVP_PKEY_size(evp_key);
  613. if (size > sizeof(sig->sig)) {
  614. fprintf(stderr, "Invalid signature size (%d bytes)\n",
  615. size);
  616. ret = -EINVAL;
  617. goto err_key;
  618. }
  619. ctx = EVP_MD_CTX_create();
  620. if (!ctx) {
  621. ret = openssl_err("EVP context creation failed");
  622. goto err_key;
  623. }
  624. EVP_MD_CTX_init(ctx);
  625. if (!EVP_VerifyInit(ctx, EVP_sha256())) {
  626. ret = openssl_err("Verifier setup failed");
  627. goto err_ctx;
  628. }
  629. if (!EVP_VerifyUpdate(ctx, data, datasz)) {
  630. ret = openssl_err("Hashing data failed");
  631. goto err_ctx;
  632. }
  633. if (EVP_VerifyFinal(ctx, sig->sig, sizeof(sig->sig), evp_key) != 1) {
  634. ret = openssl_err("Could not verify signature");
  635. goto err_ctx;
  636. }
  637. EVP_MD_CTX_cleanup(ctx);
  638. EVP_MD_CTX_destroy(ctx);
  639. EVP_PKEY_free(evp_key);
  640. return 0;
  641. err_ctx:
  642. EVP_MD_CTX_destroy(ctx);
  643. err_key:
  644. EVP_PKEY_free(evp_key);
  645. fprintf(stderr, "Failed to verify %s signature\n", signame);
  646. return ret;
  647. }
  648. static int kwb_sign_and_verify(RSA *key, void *data, int datasz,
  649. struct sig_v1 *sig, char *signame)
  650. {
  651. if (kwb_sign(key, data, datasz, sig, signame) < 0)
  652. return -1;
  653. if (kwb_verify(key, data, datasz, sig, signame) < 0)
  654. return -1;
  655. return 0;
  656. }
  657. static int kwb_dump_fuse_cmds_38x(FILE *out, struct secure_hdr_v1 *sec_hdr)
  658. {
  659. struct hash_v1 kak_pub_hash;
  660. struct image_cfg_element *e;
  661. unsigned int fuse_line;
  662. int i, idx;
  663. uint8_t *ptr;
  664. uint32_t val;
  665. int ret = 0;
  666. if (!out || !sec_hdr)
  667. return -EINVAL;
  668. ret = kwb_compute_pubkey_hash(&sec_hdr->kak, &kak_pub_hash);
  669. if (ret < 0)
  670. goto done;
  671. fprintf(out, "# burn KAK pub key hash\n");
  672. ptr = kak_pub_hash.hash;
  673. for (fuse_line = 26; fuse_line <= 30; ++fuse_line) {
  674. fprintf(out, "fuse prog -y %u 0 ", fuse_line);
  675. for (i = 4; i-- > 0;)
  676. fprintf(out, "%02hx", (ushort)ptr[i]);
  677. ptr += 4;
  678. fprintf(out, " 00");
  679. if (fuse_line < 30) {
  680. for (i = 3; i-- > 0;)
  681. fprintf(out, "%02hx", (ushort)ptr[i]);
  682. ptr += 3;
  683. } else {
  684. fprintf(out, "000000");
  685. }
  686. fprintf(out, " 1\n");
  687. }
  688. fprintf(out, "# burn CSK selection\n");
  689. idx = image_get_csk_index();
  690. if (idx < 0 || idx > 15) {
  691. ret = -EINVAL;
  692. goto done;
  693. }
  694. if (idx > 0) {
  695. for (fuse_line = 31; fuse_line < 31 + idx; ++fuse_line)
  696. fprintf(out, "fuse prog -y %u 0 00000001 00000000 1\n",
  697. fuse_line);
  698. } else {
  699. fprintf(out, "# CSK index is 0; no mods needed\n");
  700. }
  701. e = image_find_option(IMAGE_CFG_BOX_ID);
  702. if (e) {
  703. fprintf(out, "# set box ID\n");
  704. fprintf(out, "fuse prog -y 48 0 %08x 00000000 1\n", e->boxid);
  705. }
  706. e = image_find_option(IMAGE_CFG_FLASH_ID);
  707. if (e) {
  708. fprintf(out, "# set flash ID\n");
  709. fprintf(out, "fuse prog -y 47 0 %08x 00000000 1\n", e->flashid);
  710. }
  711. fprintf(out, "# enable secure mode ");
  712. fprintf(out, "(must be the last fuse line written)\n");
  713. val = 1;
  714. e = image_find_option(IMAGE_CFG_SEC_BOOT_DEV);
  715. if (!e) {
  716. fprintf(stderr, "ERROR: secured mode boot device not given\n");
  717. ret = -EINVAL;
  718. goto done;
  719. }
  720. if (e->sec_boot_dev > 0xff) {
  721. fprintf(stderr, "ERROR: secured mode boot device invalid\n");
  722. ret = -EINVAL;
  723. goto done;
  724. }
  725. val |= (e->sec_boot_dev << 8);
  726. fprintf(out, "fuse prog -y 24 0 %08x 0103e0a9 1\n", val);
  727. fprintf(out, "# lock (unused) fuse lines (0-23)s\n");
  728. for (fuse_line = 0; fuse_line < 24; ++fuse_line)
  729. fprintf(out, "fuse prog -y %u 2 1\n", fuse_line);
  730. fprintf(out, "# OK, that's all :-)\n");
  731. done:
  732. return ret;
  733. }
  734. static int kwb_dump_fuse_cmds(struct secure_hdr_v1 *sec_hdr)
  735. {
  736. int ret = 0;
  737. struct image_cfg_element *e;
  738. e = image_find_option(IMAGE_CFG_SEC_FUSE_DUMP);
  739. if (!e)
  740. return 0;
  741. if (!strcmp(e->name, "a38x")) {
  742. FILE *out = fopen("kwb_fuses_a38x.txt", "w+");
  743. if (!out) {
  744. fprintf(stderr, "Couldn't open eFuse settings: '%s': %s\n",
  745. "kwb_fuses_a38x.txt", strerror(errno));
  746. return -ENOENT;
  747. }
  748. kwb_dump_fuse_cmds_38x(out, sec_hdr);
  749. fclose(out);
  750. goto done;
  751. }
  752. ret = -ENOSYS;
  753. done:
  754. return ret;
  755. }
  756. static size_t image_headersz_align(size_t headersz, uint8_t blockid)
  757. {
  758. /*
  759. * Header needs to be 4-byte aligned, which is already ensured by code
  760. * above. Moreover UART images must have header aligned to 128 bytes
  761. * (xmodem block size), NAND images to 256 bytes (ECC calculation),
  762. * and SATA and SDIO images to 512 bytes (storage block size).
  763. * Note that SPI images do not have to have header size aligned
  764. * to 256 bytes because it is possible to read from SPI storage from
  765. * any offset (read offset does not have to be aligned to block size).
  766. */
  767. if (blockid == IBR_HDR_UART_ID)
  768. return ALIGN(headersz, 128);
  769. else if (blockid == IBR_HDR_NAND_ID)
  770. return ALIGN(headersz, 256);
  771. else if (blockid == IBR_HDR_SATA_ID || blockid == IBR_HDR_SDIO_ID)
  772. return ALIGN(headersz, 512);
  773. else
  774. return headersz;
  775. }
  776. static size_t image_headersz_v0(int *hasext)
  777. {
  778. size_t headersz;
  779. headersz = sizeof(struct main_hdr_v0);
  780. if (image_count_options(IMAGE_CFG_DATA) > 0) {
  781. headersz += sizeof(struct ext_hdr_v0);
  782. if (hasext)
  783. *hasext = 1;
  784. }
  785. return image_headersz_align(headersz, image_get_bootfrom());
  786. }
  787. static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
  788. int payloadsz)
  789. {
  790. struct image_cfg_element *e;
  791. size_t headersz;
  792. struct main_hdr_v0 *main_hdr;
  793. uint8_t *image;
  794. int has_ext = 0;
  795. /*
  796. * Calculate the size of the header and the size of the
  797. * payload
  798. */
  799. headersz = image_headersz_v0(&has_ext);
  800. image = malloc(headersz);
  801. if (!image) {
  802. fprintf(stderr, "Cannot allocate memory for image\n");
  803. return NULL;
  804. }
  805. memset(image, 0, headersz);
  806. main_hdr = (struct main_hdr_v0 *)image;
  807. /* Fill in the main header */
  808. main_hdr->blocksize =
  809. cpu_to_le32(payloadsz);
  810. main_hdr->srcaddr = cpu_to_le32(headersz);
  811. main_hdr->ext = has_ext;
  812. main_hdr->version = 0;
  813. main_hdr->destaddr = cpu_to_le32(params->addr);
  814. main_hdr->execaddr = cpu_to_le32(params->ep);
  815. main_hdr->blockid = image_get_bootfrom();
  816. e = image_find_option(IMAGE_CFG_NAND_ECC_MODE);
  817. if (e)
  818. main_hdr->nandeccmode = e->nandeccmode;
  819. e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
  820. if (e)
  821. main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
  822. main_hdr->checksum = image_checksum8(image,
  823. sizeof(struct main_hdr_v0));
  824. /*
  825. * For SATA srcaddr is specified in number of sectors starting from
  826. * sector 0. The main header is stored at sector number 1.
  827. * This expects the sector size to be 512 bytes.
  828. * Header size is already aligned.
  829. */
  830. if (main_hdr->blockid == IBR_HDR_SATA_ID)
  831. main_hdr->srcaddr = cpu_to_le32(headersz / 512 + 1);
  832. /*
  833. * For SDIO srcaddr is specified in number of sectors starting from
  834. * sector 0. The main header is stored at sector number 0.
  835. * This expects sector size to be 512 bytes.
  836. * Header size is already aligned.
  837. */
  838. if (main_hdr->blockid == IBR_HDR_SDIO_ID)
  839. main_hdr->srcaddr = cpu_to_le32(headersz / 512);
  840. /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
  841. if (main_hdr->blockid == IBR_HDR_PEX_ID)
  842. main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
  843. /* Generate the ext header */
  844. if (has_ext) {
  845. struct ext_hdr_v0 *ext_hdr;
  846. int cfgi, datai;
  847. ext_hdr = (struct ext_hdr_v0 *)
  848. (image + sizeof(struct main_hdr_v0));
  849. ext_hdr->offset = cpu_to_le32(0x40);
  850. for (cfgi = 0, datai = 0; cfgi < cfgn; cfgi++) {
  851. e = &image_cfg[cfgi];
  852. if (e->type != IMAGE_CFG_DATA)
  853. continue;
  854. ext_hdr->rcfg[datai].raddr =
  855. cpu_to_le32(e->regdata.raddr);
  856. ext_hdr->rcfg[datai].rdata =
  857. cpu_to_le32(e->regdata.rdata);
  858. datai++;
  859. }
  860. ext_hdr->checksum = image_checksum8(ext_hdr,
  861. sizeof(struct ext_hdr_v0));
  862. }
  863. *imagesz = headersz;
  864. return image;
  865. }
  866. static size_t image_headersz_v1(int *hasext)
  867. {
  868. struct image_cfg_element *e;
  869. unsigned int count;
  870. size_t headersz;
  871. int cpu_sheeva;
  872. struct stat s;
  873. int cfgi;
  874. int ret;
  875. /*
  876. * Calculate the size of the header and the size of the
  877. * payload
  878. */
  879. headersz = sizeof(struct main_hdr_v1);
  880. if (image_get_csk_index() >= 0) {
  881. headersz += sizeof(struct secure_hdr_v1);
  882. if (hasext)
  883. *hasext = 1;
  884. }
  885. cpu_sheeva = image_is_cpu_sheeva();
  886. count = 0;
  887. for (cfgi = 0; cfgi < cfgn; cfgi++) {
  888. e = &image_cfg[cfgi];
  889. if (e->type == IMAGE_CFG_DATA)
  890. count++;
  891. if (e->type == IMAGE_CFG_DATA_DELAY ||
  892. (e->type == IMAGE_CFG_BINARY && count > 0)) {
  893. headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
  894. count = 0;
  895. }
  896. if (e->type != IMAGE_CFG_BINARY)
  897. continue;
  898. ret = stat(e->binary.file, &s);
  899. if (ret < 0) {
  900. char cwd[PATH_MAX];
  901. char *dir = cwd;
  902. memset(cwd, 0, sizeof(cwd));
  903. if (!getcwd(cwd, sizeof(cwd))) {
  904. dir = "current working directory";
  905. perror("getcwd() failed");
  906. }
  907. fprintf(stderr,
  908. "Didn't find the file '%s' in '%s' which is mandatory to generate the image\n"
  909. "This file generally contains the DDR3 training code, and should be extracted from an existing bootable\n"
  910. "image for your board. Use 'dumpimage -T kwbimage -p 0' to extract it from an existing image.\n",
  911. e->binary.file, dir);
  912. return 0;
  913. }
  914. headersz += sizeof(struct opt_hdr_v1) + sizeof(uint32_t) +
  915. (e->binary.nargs) * sizeof(uint32_t);
  916. if (e->binary.loadaddr) {
  917. /*
  918. * BootROM loads kwbimage header (in which the
  919. * executable code is also stored) to address
  920. * 0x40004000 or 0x40000000. Thus there is
  921. * restriction for the load address of the N-th
  922. * BINARY image.
  923. */
  924. unsigned int base_addr, low_addr, high_addr;
  925. base_addr = cpu_sheeva ? 0x40004000 : 0x40000000;
  926. low_addr = base_addr + headersz;
  927. high_addr = low_addr +
  928. (BINARY_MAX_ARGS - e->binary.nargs) * sizeof(uint32_t);
  929. if (cpu_sheeva && e->binary.loadaddr % 16) {
  930. fprintf(stderr,
  931. "Invalid LOAD_ADDRESS 0x%08x for BINARY %s with %d args.\n"
  932. "Address for CPU SHEEVA must be 16-byte aligned.\n",
  933. e->binary.loadaddr, e->binary.file, e->binary.nargs);
  934. return 0;
  935. }
  936. if (e->binary.loadaddr % 4 || e->binary.loadaddr < low_addr ||
  937. e->binary.loadaddr > high_addr) {
  938. fprintf(stderr,
  939. "Invalid LOAD_ADDRESS 0x%08x for BINARY %s with %d args.\n"
  940. "Address must be 4-byte aligned and in range 0x%08x-0x%08x.\n",
  941. e->binary.loadaddr, e->binary.file,
  942. e->binary.nargs, low_addr, high_addr);
  943. return 0;
  944. }
  945. headersz = e->binary.loadaddr - base_addr;
  946. } else if (cpu_sheeva) {
  947. headersz = ALIGN(headersz, 16);
  948. } else {
  949. headersz = ALIGN(headersz, 4);
  950. }
  951. headersz += ALIGN(s.st_size, 4) + sizeof(uint32_t);
  952. if (hasext)
  953. *hasext = 1;
  954. }
  955. if (count > 0)
  956. headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
  957. return image_headersz_align(headersz, image_get_bootfrom());
  958. }
  959. static int add_binary_header_v1(uint8_t **cur, uint8_t **next_ext,
  960. struct image_cfg_element *binarye,
  961. struct main_hdr_v1 *main_hdr)
  962. {
  963. struct opt_hdr_v1 *hdr = (struct opt_hdr_v1 *)*cur;
  964. uint32_t base_addr;
  965. uint32_t add_args;
  966. uint32_t offset;
  967. uint32_t *args;
  968. size_t binhdrsz;
  969. int cpu_sheeva;
  970. struct stat s;
  971. int argi;
  972. FILE *bin;
  973. int ret;
  974. hdr->headertype = OPT_HDR_V1_BINARY_TYPE;
  975. bin = fopen(binarye->binary.file, "r");
  976. if (!bin) {
  977. fprintf(stderr, "Cannot open binary file %s\n",
  978. binarye->binary.file);
  979. return -1;
  980. }
  981. if (fstat(fileno(bin), &s)) {
  982. fprintf(stderr, "Cannot stat binary file %s\n",
  983. binarye->binary.file);
  984. goto err_close;
  985. }
  986. *cur += sizeof(struct opt_hdr_v1);
  987. args = (uint32_t *)*cur;
  988. *args = cpu_to_le32(binarye->binary.nargs);
  989. args++;
  990. for (argi = 0; argi < binarye->binary.nargs; argi++)
  991. args[argi] = cpu_to_le32(binarye->binary.args[argi]);
  992. *cur += (binarye->binary.nargs + 1) * sizeof(uint32_t);
  993. /*
  994. * ARM executable code inside the BIN header on platforms with Sheeva
  995. * CPU (A370 and AXP) must always be aligned with the 128-bit boundary.
  996. * In the case when this code is not position independent (e.g. ARM
  997. * SPL), it must be placed at fixed load and execute address.
  998. * This requirement can be met by inserting dummy arguments into
  999. * BIN header, if needed.
  1000. */
  1001. cpu_sheeva = image_is_cpu_sheeva();
  1002. base_addr = cpu_sheeva ? 0x40004000 : 0x40000000;
  1003. offset = *cur - (uint8_t *)main_hdr;
  1004. if (binarye->binary.loadaddr)
  1005. add_args = (binarye->binary.loadaddr - base_addr - offset) / sizeof(uint32_t);
  1006. else if (cpu_sheeva)
  1007. add_args = ((16 - offset % 16) % 16) / sizeof(uint32_t);
  1008. else
  1009. add_args = 0;
  1010. if (add_args) {
  1011. *(args - 1) = cpu_to_le32(binarye->binary.nargs + add_args);
  1012. *cur += add_args * sizeof(uint32_t);
  1013. }
  1014. ret = fread(*cur, s.st_size, 1, bin);
  1015. if (ret != 1) {
  1016. fprintf(stderr,
  1017. "Could not read binary image %s\n",
  1018. binarye->binary.file);
  1019. goto err_close;
  1020. }
  1021. fclose(bin);
  1022. *cur += ALIGN(s.st_size, 4);
  1023. *((uint32_t *)*cur) = 0x00000000;
  1024. **next_ext = 1;
  1025. *next_ext = *cur;
  1026. *cur += sizeof(uint32_t);
  1027. binhdrsz = sizeof(struct opt_hdr_v1) +
  1028. (binarye->binary.nargs + add_args + 2) * sizeof(uint32_t) +
  1029. ALIGN(s.st_size, 4);
  1030. hdr->headersz_lsb = cpu_to_le16(binhdrsz & 0xFFFF);
  1031. hdr->headersz_msb = (binhdrsz & 0xFFFF0000) >> 16;
  1032. return 0;
  1033. err_close:
  1034. fclose(bin);
  1035. return -1;
  1036. }
  1037. static int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
  1038. {
  1039. FILE *hashf;
  1040. int res;
  1041. hashf = fopen("pub_kak_hash.txt", "w");
  1042. if (!hashf) {
  1043. fprintf(stderr, "Couldn't open hash file: '%s': %s\n",
  1044. "pub_kak_hash.txt", strerror(errno));
  1045. return 1;
  1046. }
  1047. res = kwb_export_pubkey(kak, &secure_hdr->kak, hashf, "KAK");
  1048. fclose(hashf);
  1049. return res < 0 ? 1 : 0;
  1050. }
  1051. static int kwb_sign_csk_with_kak(struct image_tool_params *params,
  1052. struct secure_hdr_v1 *secure_hdr, RSA *csk)
  1053. {
  1054. RSA *kak = NULL;
  1055. RSA *kak_pub = NULL;
  1056. int csk_idx = image_get_csk_index();
  1057. struct sig_v1 tmp_sig;
  1058. if (csk_idx < 0 || csk_idx > 15) {
  1059. fprintf(stderr, "Invalid CSK index %d\n", csk_idx);
  1060. return 1;
  1061. }
  1062. if (kwb_load_kak(params, &kak) < 0)
  1063. return 1;
  1064. if (export_pub_kak_hash(kak, secure_hdr))
  1065. return 1;
  1066. if (kwb_import_pubkey(&kak_pub, &secure_hdr->kak, "KAK") < 0)
  1067. return 1;
  1068. if (kwb_export_pubkey(csk, &secure_hdr->csk[csk_idx], NULL, "CSK") < 0)
  1069. return 1;
  1070. if (kwb_sign_and_verify(kak, &secure_hdr->csk,
  1071. sizeof(secure_hdr->csk) +
  1072. sizeof(secure_hdr->csksig),
  1073. &tmp_sig, "CSK") < 0)
  1074. return 1;
  1075. if (kwb_verify(kak_pub, &secure_hdr->csk,
  1076. sizeof(secure_hdr->csk) +
  1077. sizeof(secure_hdr->csksig),
  1078. &tmp_sig, "CSK (2)") < 0)
  1079. return 1;
  1080. secure_hdr->csksig = tmp_sig;
  1081. return 0;
  1082. }
  1083. static int add_secure_header_v1(struct image_tool_params *params, uint8_t *ptr,
  1084. int payloadsz, size_t headersz, uint8_t *image,
  1085. struct secure_hdr_v1 *secure_hdr)
  1086. {
  1087. struct image_cfg_element *e_jtagdelay;
  1088. struct image_cfg_element *e_boxid;
  1089. struct image_cfg_element *e_flashid;
  1090. RSA *csk = NULL;
  1091. unsigned char *image_ptr;
  1092. size_t image_size;
  1093. struct sig_v1 tmp_sig;
  1094. bool specialized_img = image_get_spezialized_img();
  1095. kwb_msg("Create secure header content\n");
  1096. e_jtagdelay = image_find_option(IMAGE_CFG_JTAG_DELAY);
  1097. e_boxid = image_find_option(IMAGE_CFG_BOX_ID);
  1098. e_flashid = image_find_option(IMAGE_CFG_FLASH_ID);
  1099. if (kwb_load_csk(params, &csk) < 0)
  1100. return 1;
  1101. secure_hdr->headertype = OPT_HDR_V1_SECURE_TYPE;
  1102. secure_hdr->headersz_msb = 0;
  1103. secure_hdr->headersz_lsb = cpu_to_le16(sizeof(struct secure_hdr_v1));
  1104. if (e_jtagdelay)
  1105. secure_hdr->jtag_delay = e_jtagdelay->jtag_delay;
  1106. if (e_boxid && specialized_img)
  1107. secure_hdr->boxid = cpu_to_le32(e_boxid->boxid);
  1108. if (e_flashid && specialized_img)
  1109. secure_hdr->flashid = cpu_to_le32(e_flashid->flashid);
  1110. if (kwb_sign_csk_with_kak(params, secure_hdr, csk))
  1111. return 1;
  1112. image_ptr = ptr + headersz;
  1113. image_size = payloadsz - headersz;
  1114. if (kwb_sign_and_verify(csk, image_ptr, image_size,
  1115. &secure_hdr->imgsig, "image") < 0)
  1116. return 1;
  1117. if (kwb_sign_and_verify(csk, image, headersz, &tmp_sig, "header") < 0)
  1118. return 1;
  1119. secure_hdr->hdrsig = tmp_sig;
  1120. kwb_dump_fuse_cmds(secure_hdr);
  1121. return 0;
  1122. }
  1123. static void finish_register_set_header_v1(uint8_t **cur, uint8_t **next_ext,
  1124. struct register_set_hdr_v1 *register_set_hdr,
  1125. int *datai, uint8_t delay)
  1126. {
  1127. int size = sizeof(struct register_set_hdr_v1) + 8 * (*datai) + 4;
  1128. register_set_hdr->headertype = OPT_HDR_V1_REGISTER_TYPE;
  1129. register_set_hdr->headersz_lsb = cpu_to_le16(size & 0xFFFF);
  1130. register_set_hdr->headersz_msb = size >> 16;
  1131. register_set_hdr->data[*datai].last_entry.delay = delay;
  1132. *cur += size;
  1133. **next_ext = 1;
  1134. *next_ext = &register_set_hdr->data[*datai].last_entry.next;
  1135. *datai = 0;
  1136. }
  1137. static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
  1138. uint8_t *ptr, int payloadsz)
  1139. {
  1140. struct image_cfg_element *e;
  1141. struct main_hdr_v1 *main_hdr;
  1142. struct opt_hdr_v1 *ohdr;
  1143. struct register_set_hdr_v1 *register_set_hdr;
  1144. struct secure_hdr_v1 *secure_hdr = NULL;
  1145. size_t headersz;
  1146. uint8_t *image, *cur;
  1147. int hasext = 0;
  1148. uint8_t *next_ext = NULL;
  1149. int cfgi, datai;
  1150. uint8_t delay;
  1151. /*
  1152. * Calculate the size of the header and the size of the
  1153. * payload
  1154. */
  1155. headersz = image_headersz_v1(&hasext);
  1156. if (headersz == 0)
  1157. return NULL;
  1158. image = malloc(headersz);
  1159. if (!image) {
  1160. fprintf(stderr, "Cannot allocate memory for image\n");
  1161. return NULL;
  1162. }
  1163. memset(image, 0, headersz);
  1164. main_hdr = (struct main_hdr_v1 *)image;
  1165. cur = image;
  1166. cur += sizeof(struct main_hdr_v1);
  1167. next_ext = &main_hdr->ext;
  1168. /* Fill the main header */
  1169. main_hdr->blocksize =
  1170. cpu_to_le32(payloadsz);
  1171. main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
  1172. main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
  1173. main_hdr->destaddr = cpu_to_le32(params->addr);
  1174. main_hdr->execaddr = cpu_to_le32(params->ep);
  1175. main_hdr->srcaddr = cpu_to_le32(headersz);
  1176. main_hdr->ext = hasext;
  1177. main_hdr->version = 1;
  1178. main_hdr->blockid = image_get_bootfrom();
  1179. e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
  1180. if (e)
  1181. main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
  1182. e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
  1183. if (e)
  1184. main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
  1185. e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
  1186. if (e)
  1187. main_hdr->nandbadblklocation = e->nandbadblklocation;
  1188. e = image_find_option(IMAGE_CFG_BAUDRATE);
  1189. if (e)
  1190. main_hdr->options |= baudrate_to_option(e->baudrate);
  1191. e = image_find_option(IMAGE_CFG_UART_PORT);
  1192. if (e)
  1193. main_hdr->options |= (e->uart_port & 3) << 3;
  1194. e = image_find_option(IMAGE_CFG_UART_MPP);
  1195. if (e)
  1196. main_hdr->options |= (e->uart_mpp & 7) << 5;
  1197. e = image_find_option(IMAGE_CFG_DEBUG);
  1198. if (e)
  1199. main_hdr->flags = e->debug ? 0x1 : 0;
  1200. /*
  1201. * For SATA srcaddr is specified in number of sectors starting from
  1202. * sector 0. The main header is stored at sector number 1.
  1203. * This expects the sector size to be 512 bytes.
  1204. * Header size is already aligned.
  1205. */
  1206. if (main_hdr->blockid == IBR_HDR_SATA_ID)
  1207. main_hdr->srcaddr = cpu_to_le32(headersz / 512 + 1);
  1208. /*
  1209. * For SDIO srcaddr is specified in number of sectors starting from
  1210. * sector 0. The main header is stored at sector number 0.
  1211. * This expects sector size to be 512 bytes.
  1212. * Header size is already aligned.
  1213. */
  1214. if (main_hdr->blockid == IBR_HDR_SDIO_ID)
  1215. main_hdr->srcaddr = cpu_to_le32(headersz / 512);
  1216. /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
  1217. if (main_hdr->blockid == IBR_HDR_PEX_ID)
  1218. main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
  1219. if (image_get_csk_index() >= 0) {
  1220. /*
  1221. * only reserve the space here; we fill the header later since
  1222. * we need the header to be complete to compute the signatures
  1223. */
  1224. secure_hdr = (struct secure_hdr_v1 *)cur;
  1225. cur += sizeof(struct secure_hdr_v1);
  1226. *next_ext = 1;
  1227. next_ext = &secure_hdr->next;
  1228. }
  1229. datai = 0;
  1230. for (cfgi = 0; cfgi < cfgn; cfgi++) {
  1231. e = &image_cfg[cfgi];
  1232. if (e->type != IMAGE_CFG_DATA &&
  1233. e->type != IMAGE_CFG_DATA_DELAY &&
  1234. e->type != IMAGE_CFG_BINARY)
  1235. continue;
  1236. if (datai == 0)
  1237. register_set_hdr = (struct register_set_hdr_v1 *)cur;
  1238. /* If delay is not specified, use the smallest possible value. */
  1239. if (e->type == IMAGE_CFG_DATA_DELAY)
  1240. delay = e->regdata_delay;
  1241. else
  1242. delay = REGISTER_SET_HDR_OPT_DELAY_MS(0);
  1243. /*
  1244. * DATA_DELAY command is the last entry in the register set
  1245. * header and BINARY command inserts new binary header.
  1246. * Therefore BINARY command requires to finish register set
  1247. * header if some DATA command was specified. And DATA_DELAY
  1248. * command automatically finish register set header even when
  1249. * there was no DATA command.
  1250. */
  1251. if (e->type == IMAGE_CFG_DATA_DELAY ||
  1252. (e->type == IMAGE_CFG_BINARY && datai != 0))
  1253. finish_register_set_header_v1(&cur, &next_ext, register_set_hdr,
  1254. &datai, delay);
  1255. if (e->type == IMAGE_CFG_DATA) {
  1256. register_set_hdr->data[datai].entry.address =
  1257. cpu_to_le32(e->regdata.raddr);
  1258. register_set_hdr->data[datai].entry.value =
  1259. cpu_to_le32(e->regdata.rdata);
  1260. datai++;
  1261. }
  1262. if (e->type == IMAGE_CFG_BINARY) {
  1263. if (add_binary_header_v1(&cur, &next_ext, e, main_hdr))
  1264. return NULL;
  1265. }
  1266. }
  1267. if (datai != 0) {
  1268. /* Set delay to the smallest possible value. */
  1269. delay = REGISTER_SET_HDR_OPT_DELAY_MS(0);
  1270. finish_register_set_header_v1(&cur, &next_ext, register_set_hdr,
  1271. &datai, delay);
  1272. }
  1273. if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz + headersz,
  1274. headersz, image, secure_hdr))
  1275. return NULL;
  1276. *imagesz = headersz;
  1277. /* Fill the real header size without padding into the main header */
  1278. headersz = sizeof(*main_hdr);
  1279. for_each_opt_hdr_v1 (ohdr, main_hdr)
  1280. headersz += opt_hdr_v1_size(ohdr);
  1281. main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
  1282. main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
  1283. /* Calculate and set the header checksum */
  1284. main_hdr->checksum = image_checksum8(main_hdr, headersz);
  1285. return image;
  1286. }
  1287. static int recognize_keyword(char *keyword)
  1288. {
  1289. int kw_id;
  1290. for (kw_id = 1; kw_id < IMAGE_CFG_COUNT; ++kw_id)
  1291. if (!strcmp(keyword, id_strs[kw_id]))
  1292. return kw_id;
  1293. return 0;
  1294. }
  1295. static int image_create_config_parse_oneline(char *line,
  1296. struct image_cfg_element *el)
  1297. {
  1298. char *keyword, *saveptr, *value1, *value2;
  1299. char delimiters[] = " \t";
  1300. int keyword_id, ret, argi;
  1301. char *unknown_msg = "Ignoring unknown line '%s'\n";
  1302. keyword = strtok_r(line, delimiters, &saveptr);
  1303. keyword_id = recognize_keyword(keyword);
  1304. if (!keyword_id) {
  1305. fprintf(stderr, unknown_msg, line);
  1306. return 0;
  1307. }
  1308. el->type = keyword_id;
  1309. value1 = strtok_r(NULL, delimiters, &saveptr);
  1310. if (!value1) {
  1311. fprintf(stderr, "Parameter missing in line '%s'\n", line);
  1312. return -1;
  1313. }
  1314. switch (keyword_id) {
  1315. case IMAGE_CFG_VERSION:
  1316. el->version = atoi(value1);
  1317. break;
  1318. case IMAGE_CFG_CPU:
  1319. if (strcmp(value1, "FEROCEON") == 0)
  1320. el->cpu_sheeva = 0;
  1321. else if (strcmp(value1, "SHEEVA") == 0)
  1322. el->cpu_sheeva = 1;
  1323. else if (strcmp(value1, "A9") == 0)
  1324. el->cpu_sheeva = 0;
  1325. else {
  1326. fprintf(stderr, "Invalid CPU %s\n", value1);
  1327. return -1;
  1328. }
  1329. break;
  1330. case IMAGE_CFG_BOOT_FROM:
  1331. ret = image_boot_mode_id(value1);
  1332. if (ret < 0) {
  1333. fprintf(stderr, "Invalid boot media '%s'\n", value1);
  1334. return -1;
  1335. }
  1336. el->bootfrom = ret;
  1337. break;
  1338. case IMAGE_CFG_NAND_BLKSZ:
  1339. el->nandblksz = strtoul(value1, NULL, 16);
  1340. break;
  1341. case IMAGE_CFG_NAND_BADBLK_LOCATION:
  1342. el->nandbadblklocation = strtoul(value1, NULL, 16);
  1343. break;
  1344. case IMAGE_CFG_NAND_ECC_MODE:
  1345. ret = image_nand_ecc_mode_id(value1);
  1346. if (ret < 0) {
  1347. fprintf(stderr, "Invalid NAND ECC mode '%s'\n", value1);
  1348. return -1;
  1349. }
  1350. el->nandeccmode = ret;
  1351. break;
  1352. case IMAGE_CFG_NAND_PAGESZ:
  1353. el->nandpagesz = strtoul(value1, NULL, 16);
  1354. break;
  1355. case IMAGE_CFG_BINARY:
  1356. argi = 0;
  1357. el->binary.file = strdup(value1);
  1358. while (1) {
  1359. char *value = strtok_r(NULL, delimiters, &saveptr);
  1360. char *endptr;
  1361. if (!value)
  1362. break;
  1363. if (!strcmp(value, "LOAD_ADDRESS")) {
  1364. value = strtok_r(NULL, delimiters, &saveptr);
  1365. if (!value) {
  1366. fprintf(stderr,
  1367. "Missing address argument for BINARY LOAD_ADDRESS\n");
  1368. return -1;
  1369. }
  1370. el->binary.loadaddr = strtoul(value, &endptr, 16);
  1371. if (*endptr) {
  1372. fprintf(stderr,
  1373. "Invalid argument '%s' for BINARY LOAD_ADDRESS\n",
  1374. value);
  1375. return -1;
  1376. }
  1377. value = strtok_r(NULL, delimiters, &saveptr);
  1378. if (value) {
  1379. fprintf(stderr,
  1380. "Unexpected argument '%s' after BINARY LOAD_ADDRESS\n",
  1381. value);
  1382. return -1;
  1383. }
  1384. break;
  1385. }
  1386. el->binary.args[argi] = strtoul(value, &endptr, 16);
  1387. if (*endptr) {
  1388. fprintf(stderr, "Invalid argument '%s' for BINARY\n", value);
  1389. return -1;
  1390. }
  1391. argi++;
  1392. if (argi >= BINARY_MAX_ARGS) {
  1393. fprintf(stderr,
  1394. "Too many arguments for BINARY\n");
  1395. return -1;
  1396. }
  1397. }
  1398. el->binary.nargs = argi;
  1399. break;
  1400. case IMAGE_CFG_DATA:
  1401. value2 = strtok_r(NULL, delimiters, &saveptr);
  1402. if (!value1 || !value2) {
  1403. fprintf(stderr,
  1404. "Invalid number of arguments for DATA\n");
  1405. return -1;
  1406. }
  1407. el->regdata.raddr = strtoul(value1, NULL, 16);
  1408. el->regdata.rdata = strtoul(value2, NULL, 16);
  1409. break;
  1410. case IMAGE_CFG_DATA_DELAY:
  1411. if (!strcmp(value1, "SDRAM_SETUP"))
  1412. el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_SDRAM_SETUP;
  1413. else
  1414. el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_MS(strtoul(value1, NULL, 10));
  1415. if (el->regdata_delay > 255) {
  1416. fprintf(stderr, "Maximal DATA_DELAY is 255\n");
  1417. return -1;
  1418. }
  1419. break;
  1420. case IMAGE_CFG_BAUDRATE:
  1421. el->baudrate = strtoul(value1, NULL, 10);
  1422. break;
  1423. case IMAGE_CFG_UART_PORT:
  1424. el->uart_port = strtoul(value1, NULL, 16);
  1425. break;
  1426. case IMAGE_CFG_UART_MPP:
  1427. el->uart_mpp = strtoul(value1, NULL, 16);
  1428. break;
  1429. case IMAGE_CFG_DEBUG:
  1430. el->debug = strtoul(value1, NULL, 10);
  1431. break;
  1432. case IMAGE_CFG_KAK:
  1433. el->key_name = strdup(value1);
  1434. break;
  1435. case IMAGE_CFG_CSK:
  1436. el->key_name = strdup(value1);
  1437. break;
  1438. case IMAGE_CFG_CSK_INDEX:
  1439. el->csk_idx = strtol(value1, NULL, 0);
  1440. break;
  1441. case IMAGE_CFG_JTAG_DELAY:
  1442. el->jtag_delay = strtoul(value1, NULL, 0);
  1443. break;
  1444. case IMAGE_CFG_BOX_ID:
  1445. el->boxid = strtoul(value1, NULL, 0);
  1446. break;
  1447. case IMAGE_CFG_FLASH_ID:
  1448. el->flashid = strtoul(value1, NULL, 0);
  1449. break;
  1450. case IMAGE_CFG_SEC_SPECIALIZED_IMG:
  1451. el->sec_specialized_img = true;
  1452. break;
  1453. case IMAGE_CFG_SEC_COMMON_IMG:
  1454. el->sec_specialized_img = false;
  1455. break;
  1456. case IMAGE_CFG_SEC_BOOT_DEV:
  1457. el->sec_boot_dev = strtoul(value1, NULL, 0);
  1458. break;
  1459. case IMAGE_CFG_SEC_FUSE_DUMP:
  1460. el->name = strdup(value1);
  1461. break;
  1462. default:
  1463. fprintf(stderr, unknown_msg, line);
  1464. }
  1465. return 0;
  1466. }
  1467. /*
  1468. * Parse the configuration file 'fcfg' into the array of configuration
  1469. * elements 'image_cfg', and return the number of configuration
  1470. * elements in 'cfgn'.
  1471. */
  1472. static int image_create_config_parse(FILE *fcfg)
  1473. {
  1474. int ret;
  1475. int cfgi = 0;
  1476. /* Parse the configuration file */
  1477. while (!feof(fcfg)) {
  1478. char *line;
  1479. char buf[256];
  1480. /* Read the current line */
  1481. memset(buf, 0, sizeof(buf));
  1482. line = fgets(buf, sizeof(buf), fcfg);
  1483. if (!line)
  1484. break;
  1485. /* Ignore useless lines */
  1486. if (line[0] == '\n' || line[0] == '#')
  1487. continue;
  1488. /* Strip final newline */
  1489. if (line[strlen(line) - 1] == '\n')
  1490. line[strlen(line) - 1] = 0;
  1491. /* Parse the current line */
  1492. ret = image_create_config_parse_oneline(line,
  1493. &image_cfg[cfgi]);
  1494. if (ret)
  1495. return ret;
  1496. cfgi++;
  1497. if (cfgi >= IMAGE_CFG_ELEMENT_MAX) {
  1498. fprintf(stderr,
  1499. "Too many configuration elements in .cfg file\n");
  1500. return -1;
  1501. }
  1502. }
  1503. cfgn = cfgi;
  1504. return 0;
  1505. }
  1506. static int image_get_version(void)
  1507. {
  1508. struct image_cfg_element *e;
  1509. e = image_find_option(IMAGE_CFG_VERSION);
  1510. if (!e)
  1511. return -1;
  1512. return e->version;
  1513. }
  1514. static void kwbimage_set_header(void *ptr, struct stat *sbuf, int ifd,
  1515. struct image_tool_params *params)
  1516. {
  1517. FILE *fcfg;
  1518. void *image = NULL;
  1519. int version;
  1520. size_t headersz = 0;
  1521. size_t datasz;
  1522. uint32_t checksum;
  1523. struct stat s;
  1524. int ret;
  1525. /*
  1526. * Do not use sbuf->st_size as it contains size with padding.
  1527. * We need original image data size, so stat original file.
  1528. */
  1529. if (stat(params->datafile, &s)) {
  1530. fprintf(stderr, "Could not stat data file %s: %s\n",
  1531. params->datafile, strerror(errno));
  1532. exit(EXIT_FAILURE);
  1533. }
  1534. datasz = ALIGN(s.st_size, 4);
  1535. fcfg = fopen(params->imagename, "r");
  1536. if (!fcfg) {
  1537. fprintf(stderr, "Could not open input file %s\n",
  1538. params->imagename);
  1539. exit(EXIT_FAILURE);
  1540. }
  1541. image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
  1542. sizeof(struct image_cfg_element));
  1543. if (!image_cfg) {
  1544. fprintf(stderr, "Cannot allocate memory\n");
  1545. fclose(fcfg);
  1546. exit(EXIT_FAILURE);
  1547. }
  1548. memset(image_cfg, 0,
  1549. IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
  1550. rewind(fcfg);
  1551. ret = image_create_config_parse(fcfg);
  1552. fclose(fcfg);
  1553. if (ret) {
  1554. free(image_cfg);
  1555. exit(EXIT_FAILURE);
  1556. }
  1557. version = image_get_version();
  1558. switch (version) {
  1559. /*
  1560. * Fallback to version 0 if no version is provided in the
  1561. * cfg file
  1562. */
  1563. case -1:
  1564. case 0:
  1565. image = image_create_v0(&headersz, params, datasz + 4);
  1566. break;
  1567. case 1:
  1568. image = image_create_v1(&headersz, params, ptr, datasz + 4);
  1569. break;
  1570. default:
  1571. fprintf(stderr, "Unsupported version %d\n", version);
  1572. free(image_cfg);
  1573. exit(EXIT_FAILURE);
  1574. }
  1575. if (!image) {
  1576. fprintf(stderr, "Could not create image\n");
  1577. free(image_cfg);
  1578. exit(EXIT_FAILURE);
  1579. }
  1580. free(image_cfg);
  1581. /* Build and add image data checksum */
  1582. checksum = cpu_to_le32(image_checksum32((uint8_t *)ptr + headersz,
  1583. datasz));
  1584. memcpy((uint8_t *)ptr + headersz + datasz, &checksum, sizeof(uint32_t));
  1585. /* Finally copy the header into the image area */
  1586. memcpy(ptr, image, headersz);
  1587. free(image);
  1588. }
  1589. static void kwbimage_print_header(const void *ptr)
  1590. {
  1591. struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
  1592. struct opt_hdr_v1 *ohdr;
  1593. printf("Image Type: MVEBU Boot from %s Image\n",
  1594. image_boot_mode_name(mhdr->blockid));
  1595. printf("Image version:%d\n", kwbimage_version(ptr));
  1596. for_each_opt_hdr_v1 (ohdr, mhdr) {
  1597. if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE) {
  1598. printf("BIN Img Size: ");
  1599. genimg_print_size(opt_hdr_v1_size(ohdr) - 12 -
  1600. 4 * ohdr->data[0]);
  1601. printf("BIN Img Offs: %08x\n",
  1602. (unsigned)((uint8_t *)ohdr - (uint8_t *)mhdr) +
  1603. 8 + 4 * ohdr->data[0]);
  1604. }
  1605. }
  1606. printf("Data Size: ");
  1607. genimg_print_size(mhdr->blocksize - sizeof(uint32_t));
  1608. printf("Load Address: %08x\n", mhdr->destaddr);
  1609. printf("Entry Point: %08x\n", mhdr->execaddr);
  1610. }
  1611. static int kwbimage_check_image_types(uint8_t type)
  1612. {
  1613. if (type == IH_TYPE_KWBIMAGE)
  1614. return EXIT_SUCCESS;
  1615. return EXIT_FAILURE;
  1616. }
  1617. static int kwbimage_verify_header(unsigned char *ptr, int image_size,
  1618. struct image_tool_params *params)
  1619. {
  1620. size_t header_size = kwbheader_size(ptr);
  1621. uint8_t blockid;
  1622. uint32_t offset;
  1623. uint32_t size;
  1624. uint8_t csum;
  1625. if (header_size > image_size)
  1626. return -FDT_ERR_BADSTRUCTURE;
  1627. if (!main_hdr_checksum_ok(ptr))
  1628. return -FDT_ERR_BADSTRUCTURE;
  1629. /* Only version 0 extended header has checksum */
  1630. if (kwbimage_version(ptr) == 0) {
  1631. struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
  1632. if (mhdr->ext) {
  1633. struct ext_hdr_v0 *ext_hdr = (void *)(mhdr + 1);
  1634. csum = image_checksum8(ext_hdr, sizeof(*ext_hdr) - 1);
  1635. if (csum != ext_hdr->checksum)
  1636. return -FDT_ERR_BADSTRUCTURE;
  1637. }
  1638. blockid = mhdr->blockid;
  1639. offset = le32_to_cpu(mhdr->srcaddr);
  1640. size = le32_to_cpu(mhdr->blocksize);
  1641. } else if (kwbimage_version(ptr) == 1) {
  1642. struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
  1643. const uint8_t *mhdr_end;
  1644. struct opt_hdr_v1 *ohdr;
  1645. mhdr_end = (uint8_t *)mhdr + header_size;
  1646. for_each_opt_hdr_v1 (ohdr, ptr)
  1647. if (!opt_hdr_v1_valid_size(ohdr, mhdr_end))
  1648. return -FDT_ERR_BADSTRUCTURE;
  1649. blockid = mhdr->blockid;
  1650. offset = le32_to_cpu(mhdr->srcaddr);
  1651. size = le32_to_cpu(mhdr->blocksize);
  1652. } else {
  1653. return -FDT_ERR_BADSTRUCTURE;
  1654. }
  1655. /*
  1656. * For SATA srcaddr is specified in number of sectors.
  1657. * The main header is must be stored at sector number 1.
  1658. * This expects that sector size is 512 bytes and recalculates
  1659. * data offset to bytes relative to the main header.
  1660. */
  1661. if (blockid == IBR_HDR_SATA_ID) {
  1662. if (offset < 1)
  1663. return -FDT_ERR_BADSTRUCTURE;
  1664. offset -= 1;
  1665. offset *= 512;
  1666. }
  1667. /*
  1668. * For SDIO srcaddr is specified in number of sectors.
  1669. * This expects that sector size is 512 bytes and recalculates
  1670. * data offset to bytes.
  1671. */
  1672. if (blockid == IBR_HDR_SDIO_ID)
  1673. offset *= 512;
  1674. /*
  1675. * For PCIe srcaddr is always set to 0xFFFFFFFF.
  1676. * This expects that data starts after all headers.
  1677. */
  1678. if (blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
  1679. offset = header_size;
  1680. if (offset > image_size || offset % 4 != 0)
  1681. return -FDT_ERR_BADSTRUCTURE;
  1682. if (size < 4 || offset + size > image_size || size % 4 != 0)
  1683. return -FDT_ERR_BADSTRUCTURE;
  1684. if (image_checksum32(ptr + offset, size - 4) !=
  1685. *(uint32_t *)(ptr + offset + size - 4))
  1686. return -FDT_ERR_BADSTRUCTURE;
  1687. return 0;
  1688. }
  1689. static int kwbimage_generate(struct image_tool_params *params,
  1690. struct image_type_params *tparams)
  1691. {
  1692. FILE *fcfg;
  1693. struct stat s;
  1694. int alloc_len;
  1695. int bootfrom;
  1696. int version;
  1697. void *hdr;
  1698. int ret;
  1699. fcfg = fopen(params->imagename, "r");
  1700. if (!fcfg) {
  1701. fprintf(stderr, "Could not open input file %s\n",
  1702. params->imagename);
  1703. exit(EXIT_FAILURE);
  1704. }
  1705. if (stat(params->datafile, &s)) {
  1706. fprintf(stderr, "Could not stat data file %s: %s\n",
  1707. params->datafile, strerror(errno));
  1708. exit(EXIT_FAILURE);
  1709. }
  1710. image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
  1711. sizeof(struct image_cfg_element));
  1712. if (!image_cfg) {
  1713. fprintf(stderr, "Cannot allocate memory\n");
  1714. fclose(fcfg);
  1715. exit(EXIT_FAILURE);
  1716. }
  1717. memset(image_cfg, 0,
  1718. IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
  1719. rewind(fcfg);
  1720. ret = image_create_config_parse(fcfg);
  1721. fclose(fcfg);
  1722. if (ret) {
  1723. free(image_cfg);
  1724. exit(EXIT_FAILURE);
  1725. }
  1726. bootfrom = image_get_bootfrom();
  1727. version = image_get_version();
  1728. switch (version) {
  1729. /*
  1730. * Fallback to version 0 if no version is provided in the
  1731. * cfg file
  1732. */
  1733. case -1:
  1734. case 0:
  1735. alloc_len = image_headersz_v0(NULL);
  1736. break;
  1737. case 1:
  1738. alloc_len = image_headersz_v1(NULL);
  1739. if (!alloc_len) {
  1740. free(image_cfg);
  1741. exit(EXIT_FAILURE);
  1742. }
  1743. if (alloc_len > 192*1024) {
  1744. fprintf(stderr, "Header is too big (%u bytes), maximal kwbimage header size is %u bytes\n", alloc_len, 192*1024);
  1745. free(image_cfg);
  1746. exit(EXIT_FAILURE);
  1747. }
  1748. break;
  1749. default:
  1750. fprintf(stderr, "Unsupported version %d\n", version);
  1751. free(image_cfg);
  1752. exit(EXIT_FAILURE);
  1753. }
  1754. free(image_cfg);
  1755. hdr = malloc(alloc_len);
  1756. if (!hdr) {
  1757. fprintf(stderr, "%s: malloc return failure: %s\n",
  1758. params->cmdname, strerror(errno));
  1759. exit(EXIT_FAILURE);
  1760. }
  1761. memset(hdr, 0, alloc_len);
  1762. tparams->header_size = alloc_len;
  1763. tparams->hdr = hdr;
  1764. /*
  1765. * The resulting image needs to be 4-byte aligned. At least
  1766. * the Marvell hdrparser tool complains if its unaligned.
  1767. * After the image data is stored 4-byte checksum.
  1768. * Final UART image must be aligned to 128 bytes.
  1769. * Final SPI and NAND images must be aligned to 256 bytes.
  1770. * Final SATA and SDIO images must be aligned to 512 bytes.
  1771. */
  1772. if (bootfrom == IBR_HDR_SPI_ID || bootfrom == IBR_HDR_NAND_ID)
  1773. return 4 + (256 - (alloc_len + s.st_size + 4) % 256) % 256;
  1774. else if (bootfrom == IBR_HDR_SATA_ID || bootfrom == IBR_HDR_SDIO_ID)
  1775. return 4 + (512 - (alloc_len + s.st_size + 4) % 512) % 512;
  1776. else if (bootfrom == IBR_HDR_UART_ID)
  1777. return 4 + (128 - (alloc_len + s.st_size + 4) % 128) % 128;
  1778. else
  1779. return 4 + (4 - s.st_size % 4) % 4;
  1780. }
  1781. static int kwbimage_generate_config(void *ptr, struct image_tool_params *params)
  1782. {
  1783. struct main_hdr_v0 *mhdr0 = (struct main_hdr_v0 *)ptr;
  1784. struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
  1785. size_t header_size = kwbheader_size(ptr);
  1786. struct register_set_hdr_v1 *regset_hdr;
  1787. struct ext_hdr_v0_reg *regdata;
  1788. struct ext_hdr_v0 *ehdr0;
  1789. struct opt_hdr_v1 *ohdr;
  1790. unsigned offset;
  1791. int cur_idx;
  1792. int version;
  1793. FILE *f;
  1794. int i;
  1795. f = fopen(params->outfile, "w");
  1796. if (!f) {
  1797. fprintf(stderr, "Can't open \"%s\": %s\n", params->outfile, strerror(errno));
  1798. return -1;
  1799. }
  1800. version = kwbimage_version(ptr);
  1801. if (version != 0)
  1802. fprintf(f, "VERSION %d\n", version);
  1803. fprintf(f, "BOOT_FROM %s\n", image_boot_mode_name(mhdr->blockid) ?: "<unknown>");
  1804. if (version == 0 && mhdr->blockid == IBR_HDR_NAND_ID)
  1805. fprintf(f, "NAND_ECC_MODE %s\n", image_nand_ecc_mode_name(mhdr0->nandeccmode));
  1806. if (mhdr->blockid == IBR_HDR_NAND_ID)
  1807. fprintf(f, "NAND_PAGE_SIZE 0x%x\n", (unsigned)mhdr->nandpagesize);
  1808. if (version != 0 && mhdr->blockid == IBR_HDR_NAND_ID) {
  1809. fprintf(f, "NAND_BLKSZ 0x%x\n", (unsigned)mhdr->nandblocksize);
  1810. fprintf(f, "NAND_BADBLK_LOCATION 0x%x\n", (unsigned)mhdr->nandbadblklocation);
  1811. }
  1812. if (version == 0 && mhdr->blockid == IBR_HDR_SATA_ID)
  1813. fprintf(f, "SATA_PIO_MODE %u\n", (unsigned)mhdr0->satapiomode);
  1814. /*
  1815. * Addresses and sizes which are specified by mkimage command line
  1816. * arguments and not in kwbimage config file
  1817. */
  1818. if (version != 0)
  1819. fprintf(f, "#HEADER_SIZE 0x%x\n",
  1820. ((unsigned)mhdr->headersz_msb << 8) | le16_to_cpu(mhdr->headersz_lsb));
  1821. fprintf(f, "#SRC_ADDRESS 0x%x\n", le32_to_cpu(mhdr->srcaddr));
  1822. fprintf(f, "#BLOCK_SIZE 0x%x\n", le32_to_cpu(mhdr->blocksize));
  1823. fprintf(f, "#DEST_ADDRESS 0x%08x\n", le32_to_cpu(mhdr->destaddr));
  1824. fprintf(f, "#EXEC_ADDRESS 0x%08x\n", le32_to_cpu(mhdr->execaddr));
  1825. if (version != 0) {
  1826. if (options_to_baudrate(mhdr->options))
  1827. fprintf(f, "BAUDRATE %u\n", options_to_baudrate(mhdr->options));
  1828. if (options_to_baudrate(mhdr->options) ||
  1829. ((mhdr->options >> 3) & 0x3) || ((mhdr->options >> 5) & 0x7)) {
  1830. fprintf(f, "UART_PORT %u\n", (unsigned)((mhdr->options >> 3) & 0x3));
  1831. fprintf(f, "UART_MPP 0x%x\n", (unsigned)((mhdr->options >> 5) & 0x7));
  1832. }
  1833. if (mhdr->flags & 0x1)
  1834. fprintf(f, "DEBUG 1\n");
  1835. }
  1836. cur_idx = 1;
  1837. for_each_opt_hdr_v1(ohdr, ptr) {
  1838. if (ohdr->headertype == OPT_HDR_V1_SECURE_TYPE) {
  1839. fprintf(f, "#SECURE_HEADER\n");
  1840. } else if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE) {
  1841. fprintf(f, "BINARY binary%d.bin", cur_idx);
  1842. for (i = 0; i < ohdr->data[0]; i++)
  1843. fprintf(f, " 0x%x", le32_to_cpu(((uint32_t *)ohdr->data)[i + 1]));
  1844. offset = (unsigned)((uint8_t *)ohdr - (uint8_t *)mhdr) + 8 + 4 * ohdr->data[0];
  1845. fprintf(f, " LOAD_ADDRESS 0x%08x\n", 0x40000000 + offset);
  1846. fprintf(f, " # for CPU SHEEVA: LOAD_ADDRESS 0x%08x\n", 0x40004000 + offset);
  1847. cur_idx++;
  1848. } else if (ohdr->headertype == OPT_HDR_V1_REGISTER_TYPE) {
  1849. regset_hdr = (struct register_set_hdr_v1 *)ohdr;
  1850. for (i = 0;
  1851. i < opt_hdr_v1_size(ohdr) - sizeof(struct opt_hdr_v1) -
  1852. sizeof(regset_hdr->data[0].last_entry);
  1853. i++)
  1854. fprintf(f, "DATA 0x%08x 0x%08x\n",
  1855. le32_to_cpu(regset_hdr->data[i].entry.address),
  1856. le32_to_cpu(regset_hdr->data[i].entry.value));
  1857. if (opt_hdr_v1_size(ohdr) - sizeof(struct opt_hdr_v1) >=
  1858. sizeof(regset_hdr->data[0].last_entry)) {
  1859. if (regset_hdr->data[0].last_entry.delay)
  1860. fprintf(f, "DATA_DELAY %u\n",
  1861. (unsigned)regset_hdr->data[0].last_entry.delay);
  1862. else
  1863. fprintf(f, "DATA_DELAY SDRAM_SETUP\n");
  1864. }
  1865. }
  1866. }
  1867. if (version == 0 && mhdr0->ext) {
  1868. ehdr0 = (struct ext_hdr_v0 *)(mhdr0 + 1);
  1869. if (ehdr0->offset) {
  1870. for (regdata = (struct ext_hdr_v0_reg *)((uint8_t *)ptr + ehdr0->offset);
  1871. (uint8_t *)regdata < (uint8_t *)ptr + header_size && regdata->raddr &&
  1872. regdata->rdata;
  1873. regdata++)
  1874. fprintf(f, "DATA 0x%08x 0x%08x\n", le32_to_cpu(regdata->raddr),
  1875. le32_to_cpu(regdata->rdata));
  1876. }
  1877. }
  1878. if (version == 0 && le16_to_cpu(mhdr0->ddrinitdelay))
  1879. fprintf(f, "DDR_INIT_DELAY %u\n", (unsigned)le16_to_cpu(mhdr0->ddrinitdelay));
  1880. /* Undocumented reserved fields */
  1881. if (version == 0 && (mhdr0->rsvd1[0] || mhdr0->rsvd1[1] || mhdr0->rsvd1[2]))
  1882. fprintf(f, "#RSVD1 0x%x 0x%x 0x%x\n", (unsigned)mhdr0->rsvd1[0],
  1883. (unsigned)mhdr0->rsvd1[1], (unsigned)mhdr0->rsvd1[2]);
  1884. if (version == 0 && mhdr0->rsvd3)
  1885. fprintf(f, "#RSVD3 0x%x\n", (unsigned)mhdr0->rsvd3);
  1886. if (version == 0 && le16_to_cpu(mhdr0->rsvd2))
  1887. fprintf(f, "#RSVD2 0x%x\n", (unsigned)le16_to_cpu(mhdr0->rsvd2));
  1888. if (version != 0 && mhdr->reserved4)
  1889. fprintf(f, "#RESERVED4 0x%x\n", (unsigned)mhdr->reserved4);
  1890. if (version != 0 && mhdr->reserved5)
  1891. fprintf(f, "#RESERVED5 0x%x\n", (unsigned)le16_to_cpu(mhdr->reserved5));
  1892. fclose(f);
  1893. return 0;
  1894. }
  1895. static int kwbimage_extract_subimage(void *ptr, struct image_tool_params *params)
  1896. {
  1897. struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
  1898. size_t header_size = kwbheader_size(ptr);
  1899. struct opt_hdr_v1 *ohdr;
  1900. int idx = params->pflag;
  1901. int cur_idx;
  1902. uint32_t offset;
  1903. ulong image;
  1904. ulong size;
  1905. /* Generate kwbimage config file when '-p -1' is specified */
  1906. if (idx == -1)
  1907. return kwbimage_generate_config(ptr, params);
  1908. image = 0;
  1909. size = 0;
  1910. if (idx == 0) {
  1911. /* Extract data image when -p is not specified or when '-p 0' is specified */
  1912. offset = le32_to_cpu(mhdr->srcaddr);
  1913. if (mhdr->blockid == IBR_HDR_SATA_ID) {
  1914. offset -= 1;
  1915. offset *= 512;
  1916. }
  1917. if (mhdr->blockid == IBR_HDR_SDIO_ID)
  1918. offset *= 512;
  1919. if (mhdr->blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
  1920. offset = header_size;
  1921. image = (ulong)((uint8_t *)ptr + offset);
  1922. size = le32_to_cpu(mhdr->blocksize) - 4;
  1923. } else {
  1924. /* Extract N-th binary header executabe image when other '-p N' is specified */
  1925. cur_idx = 1;
  1926. for_each_opt_hdr_v1(ohdr, ptr) {
  1927. if (ohdr->headertype != OPT_HDR_V1_BINARY_TYPE)
  1928. continue;
  1929. if (idx == cur_idx) {
  1930. image = (ulong)&ohdr->data[4 + 4 * ohdr->data[0]];
  1931. size = opt_hdr_v1_size(ohdr) - 12 - 4 * ohdr->data[0];
  1932. break;
  1933. }
  1934. ++cur_idx;
  1935. }
  1936. if (!image) {
  1937. fprintf(stderr, "Argument -p %d is invalid\n", idx);
  1938. fprintf(stderr, "Available subimages:\n");
  1939. fprintf(stderr, " -p -1 - kwbimage config file\n");
  1940. fprintf(stderr, " -p 0 - data image\n");
  1941. if (cur_idx - 1 > 0)
  1942. fprintf(stderr, " -p N - Nth binary header image (totally: %d)\n",
  1943. cur_idx - 1);
  1944. return -1;
  1945. }
  1946. }
  1947. return imagetool_save_subimage(params->outfile, image, size);
  1948. }
  1949. /*
  1950. * Report Error if xflag is set in addition to default
  1951. */
  1952. static int kwbimage_check_params(struct image_tool_params *params)
  1953. {
  1954. if (!params->lflag && !params->iflag &&
  1955. (!params->imagename || !strlen(params->imagename))) {
  1956. char *msg = "Configuration file for kwbimage creation omitted";
  1957. fprintf(stderr, "Error:%s - %s\n", params->cmdname, msg);
  1958. return 1;
  1959. }
  1960. return (params->dflag && (params->fflag || params->lflag)) ||
  1961. (params->fflag && (params->dflag || params->lflag)) ||
  1962. (params->lflag && (params->dflag || params->fflag)) ||
  1963. (params->xflag);
  1964. }
  1965. /*
  1966. * kwbimage type parameters definition
  1967. */
  1968. U_BOOT_IMAGE_TYPE(
  1969. kwbimage,
  1970. "Marvell MVEBU Boot Image support",
  1971. 0,
  1972. NULL,
  1973. kwbimage_check_params,
  1974. kwbimage_verify_header,
  1975. kwbimage_print_header,
  1976. kwbimage_set_header,
  1977. kwbimage_extract_subimage,
  1978. kwbimage_check_image_types,
  1979. NULL,
  1980. kwbimage_generate
  1981. );