doimage.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  1. /*
  2. * Copyright (C) 2018 Marvell International Ltd.
  3. *
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. * https://spdx.org/licenses
  6. */
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include <stdint.h>
  10. #include <stddef.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <sys/stat.h>
  14. #include <sys/time.h>
  15. #ifdef CONFIG_MVEBU_SECURE_BOOT
  16. #include <libconfig.h> /* for parsing config file */
  17. /* mbedTLS stuff */
  18. #include <mbedtls/version.h>
  19. #if defined(MBEDTLS_BIGNUM_C) && defined(MBEDTLS_ENTROPY_C) && \
  20. defined(MBEDTLS_SHA256_C) && \
  21. defined(MBEDTLS_PK_PARSE_C) && defined(MBEDTLS_FS_IO) && \
  22. defined(MBEDTLS_CTR_DRBG_C)
  23. #include <mbedtls/error.h>
  24. #include <mbedtls/entropy.h>
  25. #include <mbedtls/ctr_drbg.h>
  26. #include <mbedtls/md.h>
  27. #include <mbedtls/pk.h>
  28. #include <mbedtls/sha256.h>
  29. #include <mbedtls/x509.h>
  30. #else
  31. #error "Bad mbedTLS configuration!"
  32. #endif
  33. #endif /* CONFIG_MVEBU_SECURE_BOOT */
  34. #define MAX_FILENAME 256
  35. #define CSK_ARR_SZ 16
  36. #define CSK_ARR_EMPTY_FILE "*"
  37. #define AES_KEY_BIT_LEN 256
  38. #define AES_KEY_BYTE_LEN (AES_KEY_BIT_LEN >> 3)
  39. #define AES_BLOCK_SZ 16
  40. #define RSA_SIGN_BYTE_LEN 256
  41. #define MAX_RSA_DER_BYTE_LEN 524
  42. /* Number of address pairs in control array */
  43. #define CP_CTRL_EL_ARRAY_SZ 32
  44. #define VERSION_STRING "Marvell(C) doimage utility version 3.3"
  45. /* A8K definitions */
  46. /* Extension header types */
  47. #define EXT_TYPE_SECURITY 0x1
  48. #define EXT_TYPE_BINARY 0x2
  49. #define MAIN_HDR_MAGIC 0xB105B002
  50. /* PROLOG alignment considerations:
  51. * 128B: To allow supporting XMODEM protocol.
  52. * 8KB: To align the boot image to the largest NAND page size, and simplify
  53. * the read operations from NAND.
  54. * We choose the largest page size, in order to use a single image for all
  55. * NAND page sizes.
  56. */
  57. #define PROLOG_ALIGNMENT (8 << 10)
  58. /* UART argument bitfield */
  59. #define UART_MODE_UNMODIFIED 0x0
  60. #define UART_MODE_DISABLE 0x1
  61. #define UART_MODE_UPDATE 0x2
  62. typedef struct _main_header {
  63. uint32_t magic; /* 0-3 */
  64. uint32_t prolog_size; /* 4-7 */
  65. uint32_t prolog_checksum; /* 8-11 */
  66. uint32_t boot_image_size; /* 12-15 */
  67. uint32_t boot_image_checksum; /* 16-19 */
  68. uint32_t rsrvd0; /* 20-23 */
  69. uint32_t load_addr; /* 24-27 */
  70. uint32_t exec_addr; /* 28-31 */
  71. uint8_t uart_cfg; /* 32 */
  72. uint8_t baudrate; /* 33 */
  73. uint8_t ext_count; /* 34 */
  74. uint8_t aux_flags; /* 35 */
  75. uint32_t io_arg_0; /* 36-39 */
  76. uint32_t io_arg_1; /* 40-43 */
  77. uint32_t io_arg_2; /* 43-47 */
  78. uint32_t io_arg_3; /* 48-51 */
  79. uint32_t rsrvd1; /* 52-55 */
  80. uint32_t rsrvd2; /* 56-59 */
  81. uint32_t rsrvd3; /* 60-63 */
  82. } header_t;
  83. typedef struct _ext_header {
  84. uint8_t type;
  85. uint8_t offset;
  86. uint16_t reserved;
  87. uint32_t size;
  88. } ext_header_t;
  89. typedef struct _sec_entry {
  90. uint8_t kak_key[MAX_RSA_DER_BYTE_LEN];
  91. uint32_t jtag_delay;
  92. uint32_t box_id;
  93. uint32_t flash_id;
  94. uint32_t jtag_en;
  95. uint32_t encrypt_en;
  96. uint32_t efuse_dis;
  97. uint8_t header_sign[RSA_SIGN_BYTE_LEN];
  98. uint8_t image_sign[RSA_SIGN_BYTE_LEN];
  99. uint8_t csk_keys[CSK_ARR_SZ][MAX_RSA_DER_BYTE_LEN];
  100. uint8_t csk_sign[RSA_SIGN_BYTE_LEN];
  101. uint32_t cp_ctrl_arr[CP_CTRL_EL_ARRAY_SZ];
  102. uint32_t cp_efuse_arr[CP_CTRL_EL_ARRAY_SZ];
  103. } sec_entry_t;
  104. /* A8K definitions end */
  105. /* UART argument bitfield */
  106. #define UART_MODE_UNMODIFIED 0x0
  107. #define UART_MODE_DISABLE 0x1
  108. #define UART_MODE_UPDATE 0x2
  109. #define uart_set_mode(arg, mode) (arg |= (mode & 0x3))
  110. typedef struct _sec_options {
  111. #ifdef CONFIG_MVEBU_SECURE_BOOT
  112. char aes_key_file[MAX_FILENAME+1];
  113. char kak_key_file[MAX_FILENAME+1];
  114. char csk_key_file[CSK_ARR_SZ][MAX_FILENAME+1];
  115. uint32_t box_id;
  116. uint32_t flash_id;
  117. uint32_t jtag_delay;
  118. uint8_t csk_index;
  119. uint8_t jtag_enable;
  120. uint8_t efuse_disable;
  121. uint32_t cp_ctrl_arr[CP_CTRL_EL_ARRAY_SZ];
  122. uint32_t cp_efuse_arr[CP_CTRL_EL_ARRAY_SZ];
  123. mbedtls_pk_context kak_pk;
  124. mbedtls_pk_context csk_pk[CSK_ARR_SZ];
  125. uint8_t aes_key[AES_KEY_BYTE_LEN];
  126. uint8_t *encrypted_image;
  127. uint32_t enc_image_sz;
  128. #endif
  129. } sec_options;
  130. typedef struct _options {
  131. char bin_ext_file[MAX_FILENAME+1];
  132. char sec_cfg_file[MAX_FILENAME+1];
  133. sec_options *sec_opts;
  134. uint32_t load_addr;
  135. uint32_t exec_addr;
  136. uint32_t baudrate;
  137. uint8_t disable_print;
  138. int8_t key_index; /* For header signatures verification only */
  139. uint32_t nfc_io_args;
  140. } options_t;
  141. void usage_err(char *msg)
  142. {
  143. fprintf(stderr, "Error: %s\n", msg);
  144. fprintf(stderr, "run 'doimage -h' to get usage information\n");
  145. exit(-1);
  146. }
  147. void usage(void)
  148. {
  149. printf("\n\n%s\n\n", VERSION_STRING);
  150. printf("Usage: doimage [options] <input_file> [output_file]\n");
  151. printf("create bootrom image from u-boot and boot extensions\n\n");
  152. printf("Arguments\n");
  153. printf(" input_file name of boot image file.\n");
  154. printf(" if -p is used, name of the bootrom image file");
  155. printf(" to parse.\n");
  156. printf(" output_file name of output bootrom image file\n");
  157. printf("\nOptions\n");
  158. printf(" -s target SOC name. supports a8020,a7020\n");
  159. printf(" different SOCs may have different boot image\n");
  160. printf(" format so it's mandatory to know the target SOC\n");
  161. printf(" -i boot I/F name. supports nand, spi, nor\n");
  162. printf(" This affects certain parameters coded in the\n");
  163. printf(" image header\n");
  164. printf(" -l boot image load address. default is 0x0\n");
  165. printf(" -e boot image entry address. default is 0x0\n");
  166. printf(" -b binary extension image file.\n");
  167. printf(" This image is executed before the boot image.\n");
  168. printf(" This is typically used to initialize the memory ");
  169. printf(" controller.\n");
  170. printf(" Currently supports only a single file.\n");
  171. #ifdef CONFIG_MVEBU_SECURE_BOOT
  172. printf(" -c Make trusted boot image using parameters\n");
  173. printf(" from the configuration file.\n");
  174. #endif
  175. printf(" -p Parse and display a pre-built boot image\n");
  176. #ifdef CONFIG_MVEBU_SECURE_BOOT
  177. printf(" -k Key index for RSA signatures verification\n");
  178. printf(" when parsing the boot image\n");
  179. #endif
  180. printf(" -m Disable prints of bootrom and binary extension\n");
  181. printf(" -u UART baudrate used for bootrom prints.\n");
  182. printf(" Must be multiple of 1200\n");
  183. printf(" -h Show this help message\n");
  184. printf(" IO-ROM NFC-NAND boot parameters:\n");
  185. printf(" -n NAND device block size in KB [Default is 64KB].\n");
  186. printf(" -t NAND cell technology (SLC [Default] or MLC)\n");
  187. exit(-1);
  188. }
  189. /* globals */
  190. static options_t opts = {
  191. .bin_ext_file = "NA",
  192. .sec_cfg_file = "NA",
  193. .sec_opts = 0,
  194. .load_addr = 0x0,
  195. .exec_addr = 0x0,
  196. .disable_print = 0,
  197. .baudrate = 0,
  198. .key_index = -1,
  199. };
  200. int get_file_size(char *filename)
  201. {
  202. struct stat st;
  203. if (stat(filename, &st) == 0)
  204. return st.st_size;
  205. return -1;
  206. }
  207. uint32_t checksum32(uint32_t *start, int len)
  208. {
  209. uint32_t sum = 0;
  210. uint32_t *startp = start;
  211. do {
  212. sum += *startp;
  213. startp++;
  214. len -= 4;
  215. } while (len > 0);
  216. return sum;
  217. }
  218. /*******************************************************************************
  219. * create_rsa_signature (memory buffer content)
  220. * Create RSASSA-PSS/SHA-256 signature for memory buffer
  221. * using RSA Private Key
  222. * INPUT:
  223. * pk_ctx Private Key context
  224. * input memory buffer
  225. * ilen buffer length
  226. * pers personalization string for seeding the RNG.
  227. * For instance a private key file name.
  228. * OUTPUT:
  229. * signature RSA-2048 signature
  230. * RETURN:
  231. * 0 on success
  232. */
  233. #ifdef CONFIG_MVEBU_SECURE_BOOT
  234. int create_rsa_signature(mbedtls_pk_context *pk_ctx,
  235. const unsigned char *input,
  236. size_t ilen,
  237. const char *pers,
  238. uint8_t *signature)
  239. {
  240. mbedtls_entropy_context entropy;
  241. mbedtls_ctr_drbg_context ctr_drbg;
  242. unsigned char hash[32];
  243. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  244. int rval;
  245. /* Not sure this is required,
  246. * but it's safer to start with empty buffers
  247. */
  248. memset(hash, 0, sizeof(hash));
  249. memset(buf, 0, sizeof(buf));
  250. mbedtls_ctr_drbg_init(&ctr_drbg);
  251. mbedtls_entropy_init(&entropy);
  252. /* Seed the random number generator */
  253. rval = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  254. (const unsigned char *)pers, strlen(pers));
  255. if (rval != 0) {
  256. fprintf(stderr, " Failed in ctr_drbg_init call (%d)!\n", rval);
  257. goto sign_exit;
  258. }
  259. /* The PK context should be already initialized.
  260. * Set the padding type for this PK context
  261. */
  262. mbedtls_rsa_set_padding(mbedtls_pk_rsa(*pk_ctx),
  263. MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA256);
  264. /* First compute the SHA256 hash for the input blob */
  265. mbedtls_sha256_ret(input, ilen, hash, 0);
  266. /* Then calculate the hash signature */
  267. rval = mbedtls_rsa_rsassa_pss_sign(mbedtls_pk_rsa(*pk_ctx),
  268. mbedtls_ctr_drbg_random,
  269. &ctr_drbg,
  270. MBEDTLS_RSA_PRIVATE,
  271. MBEDTLS_MD_SHA256, 0, hash, buf);
  272. if (rval != 0) {
  273. fprintf(stderr,
  274. "Failed to create RSA signature for %s. Error %d\n",
  275. pers, rval);
  276. goto sign_exit;
  277. }
  278. memcpy(signature, buf, 256);
  279. sign_exit:
  280. mbedtls_ctr_drbg_free(&ctr_drbg);
  281. mbedtls_entropy_free(&entropy);
  282. return rval;
  283. } /* end of create_rsa_signature */
  284. /*******************************************************************************
  285. * verify_rsa_signature (memory buffer content)
  286. * Verify RSASSA-PSS/SHA-256 signature for memory buffer
  287. * using RSA Public Key
  288. * INPUT:
  289. * pub_key Public Key buffer
  290. * ilen Public Key buffer length
  291. * input memory buffer
  292. * ilen buffer length
  293. * pers personalization string for seeding the RNG.
  294. * signature RSA-2048 signature
  295. * OUTPUT:
  296. * none
  297. * RETURN:
  298. * 0 on success
  299. */
  300. int verify_rsa_signature(const unsigned char *pub_key,
  301. size_t klen,
  302. const unsigned char *input,
  303. size_t ilen,
  304. const char *pers,
  305. uint8_t *signature)
  306. {
  307. mbedtls_entropy_context entropy;
  308. mbedtls_ctr_drbg_context ctr_drbg;
  309. mbedtls_pk_context pk_ctx;
  310. unsigned char hash[32];
  311. int rval;
  312. unsigned char *pkey = (unsigned char *)pub_key;
  313. /* Not sure this is required,
  314. * but it's safer to start with empty buffer
  315. */
  316. memset(hash, 0, sizeof(hash));
  317. mbedtls_pk_init(&pk_ctx);
  318. mbedtls_ctr_drbg_init(&ctr_drbg);
  319. mbedtls_entropy_init(&entropy);
  320. /* Seed the random number generator */
  321. rval = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  322. (const unsigned char *)pers, strlen(pers));
  323. if (rval != 0) {
  324. fprintf(stderr, " Failed in ctr_drbg_init call (%d)!\n", rval);
  325. goto verify_exit;
  326. }
  327. /* Check ability to read the public key */
  328. rval = mbedtls_pk_parse_subpubkey(&pkey, pub_key + klen, &pk_ctx);
  329. if (rval != 0) {
  330. fprintf(stderr, " Failed in pk_parse_public_key (%#x)!\n",
  331. rval);
  332. goto verify_exit;
  333. }
  334. /* Set the padding type for the new PK context */
  335. mbedtls_rsa_set_padding(mbedtls_pk_rsa(pk_ctx),
  336. MBEDTLS_RSA_PKCS_V21,
  337. MBEDTLS_MD_SHA256);
  338. /* Compute the SHA256 hash for the input buffer */
  339. mbedtls_sha256_ret(input, ilen, hash, 0);
  340. rval = mbedtls_rsa_rsassa_pss_verify(mbedtls_pk_rsa(pk_ctx),
  341. mbedtls_ctr_drbg_random,
  342. &ctr_drbg,
  343. MBEDTLS_RSA_PUBLIC,
  344. MBEDTLS_MD_SHA256, 0,
  345. hash, signature);
  346. if (rval != 0)
  347. fprintf(stderr, "Failed to verify signature (%d)!\n", rval);
  348. verify_exit:
  349. mbedtls_pk_free(&pk_ctx);
  350. mbedtls_ctr_drbg_free(&ctr_drbg);
  351. mbedtls_entropy_free(&entropy);
  352. return rval;
  353. } /* end of verify_rsa_signature */
  354. /*******************************************************************************
  355. * image_encrypt
  356. * Encrypt image buffer using AES-256-CBC scheme.
  357. * The resulting image is saved into opts.sec_opts->encrypted_image
  358. * and the adjusted image size into opts.sec_opts->enc_image_sz
  359. * First AES_BLOCK_SZ bytes of the output image contain IV
  360. * INPUT:
  361. * buf Source buffer to encrypt
  362. * blen Source buffer length
  363. * OUTPUT:
  364. * none
  365. * RETURN:
  366. * 0 on success
  367. */
  368. int image_encrypt(uint8_t *buf, uint32_t blen)
  369. {
  370. struct timeval tv;
  371. char *ptmp = (char *)&tv;
  372. unsigned char digest[32];
  373. unsigned char IV[AES_BLOCK_SZ];
  374. int i, k;
  375. mbedtls_aes_context aes_ctx;
  376. int rval = -1;
  377. uint8_t *test_img = 0;
  378. if (AES_BLOCK_SZ > 32) {
  379. fprintf(stderr, "Unsupported AES block size %d\n",
  380. AES_BLOCK_SZ);
  381. return rval;
  382. }
  383. mbedtls_aes_init(&aes_ctx);
  384. memset(IV, 0, AES_BLOCK_SZ);
  385. memset(digest, 0, 32);
  386. /* Generate initialization vector and init the AES engine
  387. * Use file name XOR current time and finally SHA-256
  388. * [0...AES_BLOCK_SZ-1]
  389. */
  390. k = strlen(opts.sec_opts->aes_key_file);
  391. if (k > AES_BLOCK_SZ)
  392. k = AES_BLOCK_SZ;
  393. memcpy(IV, opts.sec_opts->aes_key_file, k);
  394. gettimeofday(&tv, 0);
  395. for (i = 0, k = 0; i < AES_BLOCK_SZ; i++,
  396. k = (k+1) % sizeof(struct timeval))
  397. IV[i] ^= ptmp[k];
  398. /* compute SHA-256 digest of the results
  399. * and use it as the init vector (IV)
  400. */
  401. mbedtls_sha256_ret(IV, AES_BLOCK_SZ, digest, 0);
  402. memcpy(IV, digest, AES_BLOCK_SZ);
  403. mbedtls_aes_setkey_enc(&aes_ctx, opts.sec_opts->aes_key,
  404. AES_KEY_BIT_LEN);
  405. /* The output image has to include extra space for IV
  406. * and to be aligned to the AES block size.
  407. * The input image buffer has to be already aligned to AES_BLOCK_SZ
  408. * and padded with zeroes
  409. */
  410. opts.sec_opts->enc_image_sz = (blen + 2 * AES_BLOCK_SZ - 1) &
  411. ~(AES_BLOCK_SZ - 1);
  412. opts.sec_opts->encrypted_image = calloc(opts.sec_opts->enc_image_sz, 1);
  413. if (opts.sec_opts->encrypted_image == 0) {
  414. fprintf(stderr, "Failed to allocate encrypted image!\n");
  415. goto encrypt_exit;
  416. }
  417. /* Put IV into the output buffer next to the encrypted image
  418. * Since the IV is modified by the encryption function,
  419. * this should be done now
  420. */
  421. memcpy(opts.sec_opts->encrypted_image +
  422. opts.sec_opts->enc_image_sz - AES_BLOCK_SZ,
  423. IV, AES_BLOCK_SZ);
  424. rval = mbedtls_aes_crypt_cbc(&aes_ctx, MBEDTLS_AES_ENCRYPT,
  425. opts.sec_opts->enc_image_sz - AES_BLOCK_SZ,
  426. IV, buf, opts.sec_opts->encrypted_image);
  427. if (rval != 0) {
  428. fprintf(stderr, "Failed to encrypt the image! Error %d\n",
  429. rval);
  430. goto encrypt_exit;
  431. }
  432. mbedtls_aes_free(&aes_ctx);
  433. /* Try to decrypt the image and compare it with the original data */
  434. mbedtls_aes_init(&aes_ctx);
  435. mbedtls_aes_setkey_dec(&aes_ctx, opts.sec_opts->aes_key,
  436. AES_KEY_BIT_LEN);
  437. test_img = calloc(opts.sec_opts->enc_image_sz - AES_BLOCK_SZ, 1);
  438. if (test_img == 0) {
  439. fprintf(stderr, "Failed to allocate test image!d\n");
  440. rval = -1;
  441. goto encrypt_exit;
  442. }
  443. memcpy(IV, opts.sec_opts->encrypted_image +
  444. opts.sec_opts->enc_image_sz - AES_BLOCK_SZ,
  445. AES_BLOCK_SZ);
  446. rval = mbedtls_aes_crypt_cbc(&aes_ctx, MBEDTLS_AES_DECRYPT,
  447. opts.sec_opts->enc_image_sz - AES_BLOCK_SZ,
  448. IV, opts.sec_opts->encrypted_image, test_img);
  449. if (rval != 0) {
  450. fprintf(stderr, "Failed to decrypt the image! Error %d\n",
  451. rval);
  452. goto encrypt_exit;
  453. }
  454. for (i = 0; i < blen; i++) {
  455. if (buf[i] != test_img[i]) {
  456. fprintf(stderr, "Failed to compare the image after");
  457. fprintf(stderr, " decryption! Byte count is %d\n", i);
  458. rval = -1;
  459. goto encrypt_exit;
  460. }
  461. }
  462. encrypt_exit:
  463. mbedtls_aes_free(&aes_ctx);
  464. if (test_img)
  465. free(test_img);
  466. return rval;
  467. } /* end of image_encrypt */
  468. /*******************************************************************************
  469. * verify_secure_header_signatures
  470. * Verify CSK array, header and image signatures and print results
  471. * INPUT:
  472. * main_hdr Main header
  473. * sec_ext Secure extension
  474. * OUTPUT:
  475. * none
  476. * RETURN:
  477. * 0 on success
  478. */
  479. int verify_secure_header_signatures(header_t *main_hdr, sec_entry_t *sec_ext)
  480. {
  481. uint8_t *image = (uint8_t *)main_hdr + main_hdr->prolog_size;
  482. uint8_t signature[RSA_SIGN_BYTE_LEN];
  483. int rval = -1;
  484. /* Save headers signature and reset it in the secure header */
  485. memcpy(signature, sec_ext->header_sign, RSA_SIGN_BYTE_LEN);
  486. memset(sec_ext->header_sign, 0, RSA_SIGN_BYTE_LEN);
  487. fprintf(stdout, "\nCheck RSA Signatures\n");
  488. fprintf(stdout, "#########################\n");
  489. fprintf(stdout, "CSK Block Signature: ");
  490. if (verify_rsa_signature(sec_ext->kak_key,
  491. MAX_RSA_DER_BYTE_LEN,
  492. &sec_ext->csk_keys[0][0],
  493. sizeof(sec_ext->csk_keys),
  494. "CSK Block Signature: ",
  495. sec_ext->csk_sign) != 0) {
  496. fprintf(stdout, "ERROR\n");
  497. goto ver_error;
  498. }
  499. fprintf(stdout, "OK\n");
  500. if (opts.key_index != -1) {
  501. fprintf(stdout, "Image Signature: ");
  502. if (verify_rsa_signature(sec_ext->csk_keys[opts.key_index],
  503. MAX_RSA_DER_BYTE_LEN,
  504. image, main_hdr->boot_image_size,
  505. "Image Signature: ",
  506. sec_ext->image_sign) != 0) {
  507. fprintf(stdout, "ERROR\n");
  508. goto ver_error;
  509. }
  510. fprintf(stdout, "OK\n");
  511. fprintf(stdout, "Header Signature: ");
  512. if (verify_rsa_signature(sec_ext->csk_keys[opts.key_index],
  513. MAX_RSA_DER_BYTE_LEN,
  514. (uint8_t *)main_hdr,
  515. main_hdr->prolog_size,
  516. "Header Signature: ",
  517. signature) != 0) {
  518. fprintf(stdout, "ERROR\n");
  519. goto ver_error;
  520. }
  521. fprintf(stdout, "OK\n");
  522. } else {
  523. fprintf(stdout, "SKIP Image and Header Signatures");
  524. fprintf(stdout, " check (undefined key index)\n");
  525. }
  526. rval = 0;
  527. ver_error:
  528. memcpy(sec_ext->header_sign, signature, RSA_SIGN_BYTE_LEN);
  529. return rval;
  530. }
  531. /*******************************************************************************
  532. * verify_and_copy_file_name_entry
  533. * INPUT:
  534. * element_name
  535. * element
  536. * OUTPUT:
  537. * copy_to
  538. * RETURN:
  539. * 0 on success
  540. */
  541. int verify_and_copy_file_name_entry(const char *element_name,
  542. const char *element, char *copy_to)
  543. {
  544. int element_length = strlen(element);
  545. if (element_length >= MAX_FILENAME) {
  546. fprintf(stderr, "The file name %s for %s is too long (%d). ",
  547. element, element_name, element_length);
  548. fprintf(stderr, "Maximum allowed %d characters!\n",
  549. MAX_FILENAME);
  550. return -1;
  551. } else if (element_length == 0) {
  552. fprintf(stderr, "The file name for %s is empty!\n",
  553. element_name);
  554. return -1;
  555. }
  556. memcpy(copy_to, element, element_length);
  557. return 0;
  558. }
  559. /*******************************************************************************
  560. * parse_sec_config_file
  561. * Read the secure boot configuration from a file
  562. * into internal structures
  563. * INPUT:
  564. * filename File name
  565. * OUTPUT:
  566. * none
  567. * RETURN:
  568. * 0 on success
  569. */
  570. int parse_sec_config_file(char *filename)
  571. {
  572. config_t sec_cfg;
  573. int array_sz, element, rval = -1;
  574. const char *cfg_string;
  575. int32_t cfg_int32;
  576. const config_setting_t *csk_array, *control_array;
  577. sec_options *sec_opt = 0;
  578. config_init(&sec_cfg);
  579. if (config_read_file(&sec_cfg, filename) != CONFIG_TRUE) {
  580. fprintf(stderr, "Failed to read data from config file ");
  581. fprintf(stderr, "%s\n\t%s at line %d\n",
  582. filename, config_error_text(&sec_cfg),
  583. config_error_line(&sec_cfg));
  584. goto exit_parse;
  585. }
  586. sec_opt = (sec_options *)calloc(sizeof(sec_options), 1);
  587. if (sec_opt == 0) {
  588. fprintf(stderr,
  589. "Cannot allocate memory for secure boot options!\n");
  590. goto exit_parse;
  591. }
  592. /* KAK file name */
  593. if (config_lookup_string(&sec_cfg, "kak_key_file",
  594. &cfg_string) != CONFIG_TRUE) {
  595. fprintf(stderr, "The \"kak_key_file\" undefined!\n");
  596. goto exit_parse;
  597. }
  598. if (verify_and_copy_file_name_entry("kak_key_file",
  599. cfg_string, sec_opt->kak_key_file))
  600. goto exit_parse;
  601. /* AES file name - can be empty/undefined */
  602. if (config_lookup_string(&sec_cfg, "aes_key_file",
  603. &cfg_string) == CONFIG_TRUE) {
  604. if (verify_and_copy_file_name_entry("aes_key_file",
  605. cfg_string,
  606. sec_opt->aes_key_file))
  607. goto exit_parse;
  608. }
  609. /* CSK file names array */
  610. csk_array = config_lookup(&sec_cfg, "csk_key_file");
  611. if (csk_array == NULL) {
  612. fprintf(stderr, "The \"csk_key_file\" undefined!\n");
  613. goto exit_parse;
  614. }
  615. array_sz = config_setting_length(csk_array);
  616. if (array_sz > CSK_ARR_SZ) {
  617. fprintf(stderr, "The \"csk_key_file\" array is too big! ");
  618. fprintf(stderr, "Only first %d elements will be used\n",
  619. CSK_ARR_SZ);
  620. array_sz = CSK_ARR_SZ;
  621. } else if (array_sz == 0) {
  622. fprintf(stderr, "The \"csk_key_file\" array is empty!\n");
  623. goto exit_parse;
  624. }
  625. for (element = 0; element < array_sz; element++) {
  626. cfg_string = config_setting_get_string_elem(csk_array, element);
  627. if (verify_and_copy_file_name_entry(
  628. "csk_key_file", cfg_string,
  629. sec_opt->csk_key_file[element])) {
  630. fprintf(stderr, "Bad csk_key_file[%d] entry!\n",
  631. element);
  632. goto exit_parse;
  633. }
  634. }
  635. /* JTAG options */
  636. if (config_lookup_bool(&sec_cfg, "jtag.enable",
  637. &cfg_int32) != CONFIG_TRUE) {
  638. fprintf(stderr, "Error obtaining \"jtag.enable\" element. ");
  639. fprintf(stderr, "Using default - FALSE\n");
  640. cfg_int32 = 0;
  641. }
  642. sec_opt->jtag_enable = cfg_int32;
  643. if (config_lookup_int(&sec_cfg, "jtag.delay",
  644. &cfg_int32) != CONFIG_TRUE) {
  645. fprintf(stderr, "Error obtaining \"jtag.delay\" element. ");
  646. fprintf(stderr, "Using default - 0us\n");
  647. cfg_int32 = 0;
  648. }
  649. sec_opt->jtag_delay = cfg_int32;
  650. /* eFUSE option */
  651. if (config_lookup_bool(&sec_cfg, "efuse_disable",
  652. &cfg_int32) != CONFIG_TRUE) {
  653. fprintf(stderr, "Error obtaining \"efuse_disable\" element. ");
  654. fprintf(stderr, "Using default - TRUE\n");
  655. cfg_int32 = 1;
  656. }
  657. sec_opt->efuse_disable = cfg_int32;
  658. /* Box ID option */
  659. if (config_lookup_int(&sec_cfg, "box_id", &cfg_int32) != CONFIG_TRUE) {
  660. fprintf(stderr, "Error obtaining \"box_id\" element. ");
  661. fprintf(stderr, "Using default - 0x0\n");
  662. cfg_int32 = 0;
  663. }
  664. sec_opt->box_id = cfg_int32;
  665. /* Flash ID option */
  666. if (config_lookup_int(&sec_cfg, "flash_id",
  667. &cfg_int32) != CONFIG_TRUE) {
  668. fprintf(stderr, "Error obtaining \"flash_id\" element. ");
  669. fprintf(stderr, "Using default - 0x0\n");
  670. cfg_int32 = 0;
  671. }
  672. sec_opt->flash_id = cfg_int32;
  673. /* CSK index option */
  674. if (config_lookup_int(&sec_cfg, "csk_key_index",
  675. &cfg_int32) != CONFIG_TRUE) {
  676. fprintf(stderr, "Error obtaining \"flash_id\" element. ");
  677. fprintf(stderr, "Using default - 0x0\n");
  678. cfg_int32 = 0;
  679. }
  680. sec_opt->csk_index = cfg_int32;
  681. /* Secure boot control array */
  682. control_array = config_lookup(&sec_cfg, "control");
  683. if (control_array != NULL) {
  684. array_sz = config_setting_length(control_array);
  685. if (array_sz == 0)
  686. fprintf(stderr, "The \"control\" array is empty!\n");
  687. } else {
  688. fprintf(stderr, "The \"control\" is undefined!\n");
  689. array_sz = 0;
  690. }
  691. for (element = 0; element < CP_CTRL_EL_ARRAY_SZ; element++) {
  692. sec_opt->cp_ctrl_arr[element] =
  693. config_setting_get_int_elem(control_array, element * 2);
  694. sec_opt->cp_efuse_arr[element] =
  695. config_setting_get_int_elem(control_array,
  696. element * 2 + 1);
  697. }
  698. opts.sec_opts = sec_opt;
  699. rval = 0;
  700. exit_parse:
  701. config_destroy(&sec_cfg);
  702. if (sec_opt && (rval != 0))
  703. free(sec_opt);
  704. return rval;
  705. } /* end of parse_sec_config_file */
  706. int format_sec_ext(char *filename, FILE *out_fd)
  707. {
  708. ext_header_t header;
  709. sec_entry_t sec_ext;
  710. int index;
  711. int written;
  712. #define DER_BUF_SZ 1600
  713. /* First, parse the configuration file */
  714. if (parse_sec_config_file(filename)) {
  715. fprintf(stderr,
  716. "failed parsing configuration file %s\n", filename);
  717. return 1;
  718. }
  719. /* Everything except signatures can be created at this stage */
  720. header.type = EXT_TYPE_SECURITY;
  721. header.offset = 0;
  722. header.size = sizeof(sec_entry_t);
  723. header.reserved = 0;
  724. /* Bring up RSA context and read private keys from their files */
  725. for (index = 0; index < (CSK_ARR_SZ + 1); index++) {
  726. /* for every private key file */
  727. mbedtls_pk_context *pk_ctx = (index == CSK_ARR_SZ) ?
  728. &opts.sec_opts->kak_pk :
  729. &opts.sec_opts->csk_pk[index];
  730. char *fname = (index == CSK_ARR_SZ) ?
  731. opts.sec_opts->kak_key_file :
  732. opts.sec_opts->csk_key_file[index];
  733. uint8_t *out_der_key = (index == CSK_ARR_SZ) ?
  734. sec_ext.kak_key :
  735. sec_ext.csk_keys[index];
  736. size_t output_len;
  737. unsigned char output_buf[DER_BUF_SZ];
  738. unsigned char *der_buf_start;
  739. /* Handle invalid/reserved file names */
  740. if (strncmp(CSK_ARR_EMPTY_FILE, fname,
  741. strlen(CSK_ARR_EMPTY_FILE)) == 0) {
  742. if (opts.sec_opts->csk_index == index) {
  743. fprintf(stderr,
  744. "CSK file with index %d cannot be %s\n",
  745. index, CSK_ARR_EMPTY_FILE);
  746. return 1;
  747. } else if (index == CSK_ARR_SZ) {
  748. fprintf(stderr, "KAK file name cannot be %s\n",
  749. CSK_ARR_EMPTY_FILE);
  750. return 1;
  751. }
  752. /* this key will be empty in CSK array */
  753. continue;
  754. }
  755. mbedtls_pk_init(pk_ctx);
  756. /* Read the private RSA key into the context
  757. * and verify it (no password)
  758. */
  759. if (mbedtls_pk_parse_keyfile(pk_ctx, fname, "") != 0) {
  760. fprintf(stderr,
  761. "Cannot read RSA private key file %s\n", fname);
  762. return 1;
  763. }
  764. /* Create a public key out of private one
  765. * and store it in DER format
  766. */
  767. output_len = mbedtls_pk_write_pubkey_der(pk_ctx,
  768. output_buf,
  769. DER_BUF_SZ);
  770. if (output_len < 0) {
  771. fprintf(stderr,
  772. "Failed to create DER coded PUB key (%s)\n",
  773. fname);
  774. return 1;
  775. }
  776. /* Data in the output buffer is aligned to the buffer end */
  777. der_buf_start = output_buf + sizeof(output_buf) - output_len;
  778. /* In the header DER data is aligned
  779. * to the start of appropriate field
  780. */
  781. bzero(out_der_key, MAX_RSA_DER_BYTE_LEN);
  782. memcpy(out_der_key, der_buf_start, output_len);
  783. } /* for every private key file */
  784. /* The CSK block signature can be created here */
  785. if (create_rsa_signature(&opts.sec_opts->kak_pk,
  786. &sec_ext.csk_keys[0][0],
  787. sizeof(sec_ext.csk_keys),
  788. opts.sec_opts->csk_key_file[
  789. opts.sec_opts->csk_index],
  790. sec_ext.csk_sign) != 0) {
  791. fprintf(stderr, "Failed to sign CSK keys block!\n");
  792. return 1;
  793. }
  794. /* Check that everything is correct */
  795. if (verify_rsa_signature(sec_ext.kak_key,
  796. MAX_RSA_DER_BYTE_LEN,
  797. &sec_ext.csk_keys[0][0],
  798. sizeof(sec_ext.csk_keys),
  799. opts.sec_opts->kak_key_file,
  800. sec_ext.csk_sign) != 0) {
  801. fprintf(stderr, "Failed to verify CSK keys block signature!\n");
  802. return 1;
  803. }
  804. /* AES encryption stuff */
  805. if (strlen(opts.sec_opts->aes_key_file) != 0) {
  806. FILE *in_fd;
  807. in_fd = fopen(opts.sec_opts->aes_key_file, "rb");
  808. if (in_fd == NULL) {
  809. fprintf(stderr, "Failed to open AES key file %s\n",
  810. opts.sec_opts->aes_key_file);
  811. return 1;
  812. }
  813. /* Read the AES key in ASCII format byte by byte */
  814. for (index = 0; index < AES_KEY_BYTE_LEN; index++) {
  815. if (fscanf(in_fd, "%02hhx",
  816. opts.sec_opts->aes_key + index) != 1) {
  817. fprintf(stderr,
  818. "Failed to read AES key byte %d ",
  819. index);
  820. fprintf(stderr,
  821. "from file %s\n",
  822. opts.sec_opts->aes_key_file);
  823. fclose(in_fd);
  824. return 1;
  825. }
  826. }
  827. fclose(in_fd);
  828. sec_ext.encrypt_en = 1;
  829. } else {
  830. sec_ext.encrypt_en = 0;
  831. }
  832. /* Fill the rest of the trusted boot extension fields */
  833. sec_ext.box_id = opts.sec_opts->box_id;
  834. sec_ext.flash_id = opts.sec_opts->flash_id;
  835. sec_ext.efuse_dis = opts.sec_opts->efuse_disable;
  836. sec_ext.jtag_delay = opts.sec_opts->jtag_delay;
  837. sec_ext.jtag_en = opts.sec_opts->jtag_enable;
  838. memcpy(sec_ext.cp_ctrl_arr,
  839. opts.sec_opts->cp_ctrl_arr,
  840. sizeof(uint32_t) * CP_CTRL_EL_ARRAY_SZ);
  841. memcpy(sec_ext.cp_efuse_arr,
  842. opts.sec_opts->cp_efuse_arr,
  843. sizeof(uint32_t) * CP_CTRL_EL_ARRAY_SZ);
  844. /* Write the resulting extension to file
  845. * (image and header signature fields are still empty)
  846. */
  847. /* Write extension header */
  848. written = fwrite(&header, sizeof(ext_header_t), 1, out_fd);
  849. if (written != 1) {
  850. fprintf(stderr,
  851. "Failed to write SEC extension header to the file\n");
  852. return 1;
  853. }
  854. /* Write extension body */
  855. written = fwrite(&sec_ext, sizeof(sec_entry_t), 1, out_fd);
  856. if (written != 1) {
  857. fprintf(stderr,
  858. "Failed to write SEC extension body to the file\n");
  859. return 1;
  860. }
  861. return 0;
  862. }
  863. /*******************************************************************************
  864. * finalize_secure_ext
  865. * Make final changes to secure extension - calculate image and header
  866. * signatures and encrypt the image if needed.
  867. * The main header checksum and image size fields updated accordingly
  868. * INPUT:
  869. * header Main header
  870. * prolog_buf the entire prolog buffer
  871. * prolog_size prolog buffer length
  872. * image_buf buffer containing the input binary image
  873. * image_size image buffer size.
  874. * OUTPUT:
  875. * none
  876. * RETURN:
  877. * 0 on success
  878. */
  879. int finalize_secure_ext(header_t *header,
  880. uint8_t *prolog_buf, uint32_t prolog_size,
  881. uint8_t *image_buf, int image_size)
  882. {
  883. int cur_ext, offset;
  884. uint8_t *final_image = image_buf;
  885. uint32_t final_image_sz = image_size;
  886. uint8_t hdr_sign[RSA_SIGN_BYTE_LEN];
  887. sec_entry_t *sec_ext = 0;
  888. /* Find the Trusted Boot Header between available extensions */
  889. for (cur_ext = 0, offset = sizeof(header_t);
  890. cur_ext < header->ext_count; cur_ext++) {
  891. ext_header_t *ext_hdr = (ext_header_t *)(prolog_buf + offset);
  892. if (ext_hdr->type == EXT_TYPE_SECURITY) {
  893. sec_ext = (sec_entry_t *)(prolog_buf + offset +
  894. sizeof(ext_header_t) + ext_hdr->offset);
  895. break;
  896. }
  897. offset += sizeof(ext_header_t);
  898. /* If offset is Zero, the extension follows its header */
  899. if (ext_hdr->offset == 0)
  900. offset += ext_hdr->size;
  901. }
  902. if (sec_ext == 0) {
  903. fprintf(stderr, "Error: No Trusted Boot extension found!\n");
  904. return -1;
  905. }
  906. if (sec_ext->encrypt_en) {
  907. /* Encrypt the image if needed */
  908. fprintf(stdout, "Encrypting the image...\n");
  909. if (image_encrypt(image_buf, image_size) != 0) {
  910. fprintf(stderr, "Failed to encrypt the image!\n");
  911. return -1;
  912. }
  913. /* Image size and checksum should be updated after encryption.
  914. * This way the image could be verified by the BootROM
  915. * before decryption.
  916. */
  917. final_image = opts.sec_opts->encrypted_image;
  918. final_image_sz = opts.sec_opts->enc_image_sz;
  919. header->boot_image_size = final_image_sz;
  920. header->boot_image_checksum =
  921. checksum32((uint32_t *)final_image, final_image_sz);
  922. } /* AES encryption */
  923. /* Create the image signature first, since it will be later
  924. * signed along with the header signature
  925. */
  926. if (create_rsa_signature(&opts.sec_opts->csk_pk[
  927. opts.sec_opts->csk_index],
  928. final_image, final_image_sz,
  929. opts.sec_opts->csk_key_file[
  930. opts.sec_opts->csk_index],
  931. sec_ext->image_sign) != 0) {
  932. fprintf(stderr, "Failed to sign image!\n");
  933. return -1;
  934. }
  935. /* Check that the image signature is correct */
  936. if (verify_rsa_signature(sec_ext->csk_keys[opts.sec_opts->csk_index],
  937. MAX_RSA_DER_BYTE_LEN,
  938. final_image, final_image_sz,
  939. opts.sec_opts->csk_key_file[
  940. opts.sec_opts->csk_index],
  941. sec_ext->image_sign) != 0) {
  942. fprintf(stderr, "Failed to verify image signature!\n");
  943. return -1;
  944. }
  945. /* Sign the headers and all the extensions block
  946. * when the header signature field is empty
  947. */
  948. if (create_rsa_signature(&opts.sec_opts->csk_pk[
  949. opts.sec_opts->csk_index],
  950. prolog_buf, prolog_size,
  951. opts.sec_opts->csk_key_file[
  952. opts.sec_opts->csk_index],
  953. hdr_sign) != 0) {
  954. fprintf(stderr, "Failed to sign header!\n");
  955. return -1;
  956. }
  957. /* Check that the header signature is correct */
  958. if (verify_rsa_signature(sec_ext->csk_keys[opts.sec_opts->csk_index],
  959. MAX_RSA_DER_BYTE_LEN,
  960. prolog_buf, prolog_size,
  961. opts.sec_opts->csk_key_file[
  962. opts.sec_opts->csk_index],
  963. hdr_sign) != 0) {
  964. fprintf(stderr, "Failed to verify header signature!\n");
  965. return -1;
  966. }
  967. /* Finally, copy the header signature into the trusted boot extension */
  968. memcpy(sec_ext->header_sign, hdr_sign, RSA_SIGN_BYTE_LEN);
  969. return 0;
  970. }
  971. #endif /* CONFIG_MVEBU_SECURE_BOOT */
  972. #define FMT_HEX 0
  973. #define FMT_DEC 1
  974. #define FMT_BIN 2
  975. #define FMT_NONE 3
  976. void do_print_field(unsigned int value, char *name,
  977. int start, int size, int format)
  978. {
  979. fprintf(stdout, "[0x%05x : 0x%05x] %-26s",
  980. start, start + size - 1, name);
  981. switch (format) {
  982. case FMT_HEX:
  983. printf("0x%x\n", value);
  984. break;
  985. case FMT_DEC:
  986. printf("%d\n", value);
  987. break;
  988. default:
  989. printf("\n");
  990. break;
  991. }
  992. }
  993. #define print_field(st, type, field, hex, base) \
  994. do_print_field((int)st->field, #field, \
  995. base + offsetof(type, field), sizeof(st->field), hex)
  996. int print_header(uint8_t *buf, int base)
  997. {
  998. header_t *main_hdr;
  999. main_hdr = (header_t *)buf;
  1000. fprintf(stdout, "########### Header ##############\n");
  1001. print_field(main_hdr, header_t, magic, FMT_HEX, base);
  1002. print_field(main_hdr, header_t, prolog_size, FMT_DEC, base);
  1003. print_field(main_hdr, header_t, prolog_checksum, FMT_HEX, base);
  1004. print_field(main_hdr, header_t, boot_image_size, FMT_DEC, base);
  1005. print_field(main_hdr, header_t, boot_image_checksum, FMT_HEX, base);
  1006. print_field(main_hdr, header_t, rsrvd0, FMT_HEX, base);
  1007. print_field(main_hdr, header_t, load_addr, FMT_HEX, base);
  1008. print_field(main_hdr, header_t, exec_addr, FMT_HEX, base);
  1009. print_field(main_hdr, header_t, uart_cfg, FMT_HEX, base);
  1010. print_field(main_hdr, header_t, baudrate, FMT_HEX, base);
  1011. print_field(main_hdr, header_t, ext_count, FMT_DEC, base);
  1012. print_field(main_hdr, header_t, aux_flags, FMT_HEX, base);
  1013. print_field(main_hdr, header_t, io_arg_0, FMT_HEX, base);
  1014. print_field(main_hdr, header_t, io_arg_1, FMT_HEX, base);
  1015. print_field(main_hdr, header_t, io_arg_2, FMT_HEX, base);
  1016. print_field(main_hdr, header_t, io_arg_3, FMT_HEX, base);
  1017. print_field(main_hdr, header_t, rsrvd1, FMT_HEX, base);
  1018. print_field(main_hdr, header_t, rsrvd2, FMT_HEX, base);
  1019. print_field(main_hdr, header_t, rsrvd3, FMT_HEX, base);
  1020. return sizeof(header_t);
  1021. }
  1022. int print_ext_hdr(ext_header_t *ext_hdr, int base)
  1023. {
  1024. print_field(ext_hdr, ext_header_t, type, FMT_HEX, base);
  1025. print_field(ext_hdr, ext_header_t, offset, FMT_HEX, base);
  1026. print_field(ext_hdr, ext_header_t, reserved, FMT_HEX, base);
  1027. print_field(ext_hdr, ext_header_t, size, FMT_DEC, base);
  1028. return base + sizeof(ext_header_t);
  1029. }
  1030. void print_sec_ext(ext_header_t *ext_hdr, int base)
  1031. {
  1032. sec_entry_t *sec_entry;
  1033. uint32_t new_base;
  1034. fprintf(stdout, "\n########### Secure extension ###########\n");
  1035. new_base = print_ext_hdr(ext_hdr, base);
  1036. sec_entry = (sec_entry_t *)(ext_hdr + 1);
  1037. do_print_field(0, "KAK key", new_base, MAX_RSA_DER_BYTE_LEN, FMT_NONE);
  1038. new_base += MAX_RSA_DER_BYTE_LEN;
  1039. print_field(sec_entry, sec_entry_t, jtag_delay, FMT_DEC, base);
  1040. print_field(sec_entry, sec_entry_t, box_id, FMT_HEX, base);
  1041. print_field(sec_entry, sec_entry_t, flash_id, FMT_HEX, base);
  1042. print_field(sec_entry, sec_entry_t, encrypt_en, FMT_DEC, base);
  1043. print_field(sec_entry, sec_entry_t, efuse_dis, FMT_DEC, base);
  1044. new_base += 6 * sizeof(uint32_t);
  1045. do_print_field(0, "header signature",
  1046. new_base, RSA_SIGN_BYTE_LEN, FMT_NONE);
  1047. new_base += RSA_SIGN_BYTE_LEN;
  1048. do_print_field(0, "image signature",
  1049. new_base, RSA_SIGN_BYTE_LEN, FMT_NONE);
  1050. new_base += RSA_SIGN_BYTE_LEN;
  1051. do_print_field(0, "CSK keys", new_base,
  1052. CSK_ARR_SZ * MAX_RSA_DER_BYTE_LEN, FMT_NONE);
  1053. new_base += CSK_ARR_SZ * MAX_RSA_DER_BYTE_LEN;
  1054. do_print_field(0, "CSK block signature",
  1055. new_base, RSA_SIGN_BYTE_LEN, FMT_NONE);
  1056. new_base += RSA_SIGN_BYTE_LEN;
  1057. do_print_field(0, "control", new_base,
  1058. CP_CTRL_EL_ARRAY_SZ * 2, FMT_NONE);
  1059. }
  1060. void print_bin_ext(ext_header_t *ext_hdr, int base)
  1061. {
  1062. fprintf(stdout, "\n########### Binary extension ###########\n");
  1063. base = print_ext_hdr(ext_hdr, base);
  1064. do_print_field(0, "binary image", base, ext_hdr->size, FMT_NONE);
  1065. }
  1066. int print_extension(void *buf, int base, int count, int ext_size)
  1067. {
  1068. ext_header_t *ext_hdr = buf;
  1069. int pad = ext_size;
  1070. int curr_size;
  1071. while (count--) {
  1072. if (ext_hdr->type == EXT_TYPE_BINARY)
  1073. print_bin_ext(ext_hdr, base);
  1074. else if (ext_hdr->type == EXT_TYPE_SECURITY)
  1075. print_sec_ext(ext_hdr, base);
  1076. curr_size = sizeof(ext_header_t) + ext_hdr->size;
  1077. base += curr_size;
  1078. pad -= curr_size;
  1079. ext_hdr = (ext_header_t *)((uintptr_t)ext_hdr + curr_size);
  1080. }
  1081. if (pad)
  1082. do_print_field(0, "padding", base, pad, FMT_NONE);
  1083. return ext_size;
  1084. }
  1085. int parse_image(uint8_t *buf, int size)
  1086. {
  1087. int base = 0;
  1088. int ret = 1;
  1089. header_t *main_hdr;
  1090. uint32_t checksum, prolog_checksum;
  1091. fprintf(stdout,
  1092. "################### Prolog Start ######################\n\n");
  1093. main_hdr = (header_t *)buf;
  1094. base += print_header(buf, base);
  1095. if (main_hdr->ext_count)
  1096. base += print_extension(buf + base, base,
  1097. main_hdr->ext_count,
  1098. main_hdr->prolog_size -
  1099. sizeof(header_t));
  1100. if (base < main_hdr->prolog_size) {
  1101. fprintf(stdout, "\n########### Padding ##############\n");
  1102. do_print_field(0, "prolog padding",
  1103. base, main_hdr->prolog_size - base, FMT_HEX);
  1104. base = main_hdr->prolog_size;
  1105. }
  1106. fprintf(stdout,
  1107. "\n################### Prolog End ######################\n");
  1108. fprintf(stdout,
  1109. "\n################### Boot image ######################\n");
  1110. do_print_field(0, "boot image", base, size - base - 4, FMT_NONE);
  1111. fprintf(stdout,
  1112. "################### Image end ########################\n");
  1113. /* Check sanity for certain values */
  1114. printf("\nChecking values:\n");
  1115. if (main_hdr->magic == MAIN_HDR_MAGIC) {
  1116. fprintf(stdout, "Headers magic: OK!\n");
  1117. } else {
  1118. fprintf(stderr,
  1119. "\n****** ERROR: HEADER MAGIC 0x%08x != 0x%08x\n",
  1120. main_hdr->magic, MAIN_HDR_MAGIC);
  1121. goto error;
  1122. }
  1123. /* headers checksum */
  1124. /* clear the checksum field in header to calculate checksum */
  1125. prolog_checksum = main_hdr->prolog_checksum;
  1126. main_hdr->prolog_checksum = 0;
  1127. checksum = checksum32((uint32_t *)buf, main_hdr->prolog_size);
  1128. if (checksum == prolog_checksum) {
  1129. fprintf(stdout, "Headers checksum: OK!\n");
  1130. } else {
  1131. fprintf(stderr,
  1132. "\n***** ERROR: BAD HEADER CHECKSUM 0x%08x != 0x%08x\n",
  1133. checksum, prolog_checksum);
  1134. goto error;
  1135. }
  1136. /* boot image checksum */
  1137. checksum = checksum32((uint32_t *)(buf + main_hdr->prolog_size),
  1138. main_hdr->boot_image_size);
  1139. if (checksum == main_hdr->boot_image_checksum) {
  1140. fprintf(stdout, "Image checksum: OK!\n");
  1141. } else {
  1142. fprintf(stderr,
  1143. "\n****** ERROR: BAD IMAGE CHECKSUM 0x%08x != 0x%08x\n",
  1144. checksum, main_hdr->boot_image_checksum);
  1145. goto error;
  1146. }
  1147. #ifdef CONFIG_MVEBU_SECURE_BOOT
  1148. /* RSA signatures */
  1149. if (main_hdr->ext_count) {
  1150. uint8_t ext_num = main_hdr->ext_count;
  1151. ext_header_t *ext_hdr = (ext_header_t *)(main_hdr + 1);
  1152. unsigned char hash[32];
  1153. int i;
  1154. while (ext_num--) {
  1155. if (ext_hdr->type == EXT_TYPE_SECURITY) {
  1156. sec_entry_t *sec_entry =
  1157. (sec_entry_t *)(ext_hdr + 1);
  1158. ret = verify_secure_header_signatures(
  1159. main_hdr, sec_entry);
  1160. if (ret != 0) {
  1161. fprintf(stderr,
  1162. "\n****** FAILED TO VERIFY ");
  1163. fprintf(stderr,
  1164. "RSA SIGNATURES ********\n");
  1165. goto error;
  1166. }
  1167. mbedtls_sha256_ret(sec_entry->kak_key,
  1168. MAX_RSA_DER_BYTE_LEN, hash, 0);
  1169. fprintf(stdout,
  1170. ">>>>>>>>>> KAK KEY HASH >>>>>>>>>>\n");
  1171. fprintf(stdout, "SHA256: ");
  1172. for (i = 0; i < 32; i++)
  1173. fprintf(stdout, "%02X", hash[i]);
  1174. fprintf(stdout,
  1175. "\n<<<<<<<<< KAK KEY HASH <<<<<<<<<\n");
  1176. break;
  1177. }
  1178. ext_hdr =
  1179. (ext_header_t *)((uint8_t *)(ext_hdr + 1) +
  1180. ext_hdr->size);
  1181. }
  1182. }
  1183. #endif
  1184. ret = 0;
  1185. error:
  1186. return ret;
  1187. }
  1188. int format_bin_ext(char *filename, FILE *out_fd)
  1189. {
  1190. ext_header_t header;
  1191. FILE *in_fd;
  1192. int size, written;
  1193. int aligned_size, pad_bytes;
  1194. char c;
  1195. in_fd = fopen(filename, "rb");
  1196. if (in_fd == NULL) {
  1197. fprintf(stderr, "failed to open bin extension file %s\n",
  1198. filename);
  1199. return 1;
  1200. }
  1201. size = get_file_size(filename);
  1202. if (size <= 0) {
  1203. fprintf(stderr, "bin extension file size is bad\n");
  1204. return 1;
  1205. }
  1206. /* Align extension size to 8 bytes */
  1207. aligned_size = (size + 7) & (~7);
  1208. pad_bytes = aligned_size - size;
  1209. header.type = EXT_TYPE_BINARY;
  1210. header.offset = 0;
  1211. header.size = aligned_size;
  1212. header.reserved = 0;
  1213. /* Write header */
  1214. written = fwrite(&header, sizeof(ext_header_t), 1, out_fd);
  1215. if (written != 1) {
  1216. fprintf(stderr, "failed writing header to extension file\n");
  1217. return 1;
  1218. }
  1219. /* Write image */
  1220. while (size--) {
  1221. c = getc(in_fd);
  1222. fputc(c, out_fd);
  1223. }
  1224. while (pad_bytes--)
  1225. fputc(0, out_fd);
  1226. fclose(in_fd);
  1227. return 0;
  1228. }
  1229. /* ****************************************
  1230. *
  1231. * Write all extensions (binary, secure
  1232. * extensions) to file
  1233. *
  1234. * ****************************************/
  1235. int format_extensions(char *ext_filename)
  1236. {
  1237. FILE *out_fd;
  1238. int ret = 0;
  1239. out_fd = fopen(ext_filename, "wb");
  1240. if (out_fd == NULL) {
  1241. fprintf(stderr, "failed to open extension output file %s",
  1242. ext_filename);
  1243. return 1;
  1244. }
  1245. if (strncmp(opts.bin_ext_file, "NA", MAX_FILENAME)) {
  1246. if (format_bin_ext(opts.bin_ext_file, out_fd)) {
  1247. ret = 1;
  1248. goto error;
  1249. }
  1250. }
  1251. #ifdef CONFIG_MVEBU_SECURE_BOOT
  1252. if (strncmp(opts.sec_cfg_file, "NA", MAX_FILENAME)) {
  1253. if (format_sec_ext(opts.sec_cfg_file, out_fd)) {
  1254. ret = 1;
  1255. goto error;
  1256. }
  1257. }
  1258. #endif
  1259. error:
  1260. fflush(out_fd);
  1261. fclose(out_fd);
  1262. return ret;
  1263. }
  1264. void update_uart(header_t *header)
  1265. {
  1266. header->uart_cfg = 0;
  1267. header->baudrate = 0;
  1268. if (opts.disable_print)
  1269. uart_set_mode(header->uart_cfg, UART_MODE_DISABLE);
  1270. if (opts.baudrate)
  1271. header->baudrate = (opts.baudrate / 1200);
  1272. }
  1273. /* ****************************************
  1274. *
  1275. * Write the image prolog, i.e.
  1276. * main header and extensions, to file
  1277. *
  1278. * ****************************************/
  1279. int write_prolog(int ext_cnt, char *ext_filename,
  1280. uint8_t *image_buf, int image_size, FILE *out_fd)
  1281. {
  1282. header_t *header;
  1283. int main_hdr_size = sizeof(header_t);
  1284. int prolog_size = main_hdr_size;
  1285. FILE *ext_fd;
  1286. char *buf;
  1287. int written, read;
  1288. int ret = 1;
  1289. if (ext_cnt)
  1290. prolog_size += get_file_size(ext_filename);
  1291. prolog_size = ((prolog_size + PROLOG_ALIGNMENT) &
  1292. (~(PROLOG_ALIGNMENT-1)));
  1293. /* Allocate a zeroed buffer to zero the padding bytes */
  1294. buf = calloc(prolog_size, 1);
  1295. if (buf == NULL) {
  1296. fprintf(stderr, "Error: failed allocating checksum buffer\n");
  1297. return 1;
  1298. }
  1299. header = (header_t *)buf;
  1300. header->magic = MAIN_HDR_MAGIC;
  1301. header->prolog_size = prolog_size;
  1302. header->load_addr = opts.load_addr;
  1303. header->exec_addr = opts.exec_addr;
  1304. header->io_arg_0 = opts.nfc_io_args;
  1305. header->ext_count = ext_cnt;
  1306. header->aux_flags = 0;
  1307. header->boot_image_size = (image_size + 3) & (~0x3);
  1308. header->boot_image_checksum = checksum32((uint32_t *)image_buf,
  1309. image_size);
  1310. update_uart(header);
  1311. /* Populate buffer with main header and extensions */
  1312. if (ext_cnt) {
  1313. ext_fd = fopen(ext_filename, "rb");
  1314. if (ext_fd == NULL) {
  1315. fprintf(stderr,
  1316. "Error: failed to open extensions file\n");
  1317. goto error;
  1318. }
  1319. read = fread(&buf[main_hdr_size],
  1320. get_file_size(ext_filename), 1, ext_fd);
  1321. if (read != 1) {
  1322. fprintf(stderr,
  1323. "Error: failed to open extensions file\n");
  1324. goto error;
  1325. }
  1326. #ifdef CONFIG_MVEBU_SECURE_BOOT
  1327. /* Secure boot mode? */
  1328. if (opts.sec_opts != 0) {
  1329. ret = finalize_secure_ext(header, (uint8_t *)buf,
  1330. prolog_size, image_buf,
  1331. image_size);
  1332. if (ret != 0) {
  1333. fprintf(stderr, "Error: failed to handle ");
  1334. fprintf(stderr, "secure extension!\n");
  1335. goto error;
  1336. }
  1337. } /* secure boot mode */
  1338. #endif
  1339. }
  1340. /* Update the total prolog checksum */
  1341. header->prolog_checksum = checksum32((uint32_t *)buf, prolog_size);
  1342. /* Now spill everything to output file */
  1343. written = fwrite(buf, prolog_size, 1, out_fd);
  1344. if (written != 1) {
  1345. fprintf(stderr,
  1346. "Error: failed to write prolog to output file\n");
  1347. goto error;
  1348. }
  1349. ret = 0;
  1350. error:
  1351. free(buf);
  1352. return ret;
  1353. }
  1354. int write_boot_image(uint8_t *buf, uint32_t image_size, FILE *out_fd)
  1355. {
  1356. int written;
  1357. written = fwrite(buf, image_size, 1, out_fd);
  1358. if (written != 1) {
  1359. fprintf(stderr, "Error: Failed to write boot image\n");
  1360. goto error;
  1361. }
  1362. return 0;
  1363. error:
  1364. return 1;
  1365. }
  1366. int main(int argc, char *argv[])
  1367. {
  1368. char in_file[MAX_FILENAME+1] = { 0 };
  1369. char out_file[MAX_FILENAME+1] = { 0 };
  1370. char ext_file[MAX_FILENAME+1] = { 0 };
  1371. FILE *in_fd = NULL;
  1372. FILE *out_fd = NULL;
  1373. int parse = 0;
  1374. int ext_cnt = 0;
  1375. int opt;
  1376. int ret = 0;
  1377. int image_size, file_size;
  1378. uint8_t *image_buf = NULL;
  1379. int read;
  1380. size_t len;
  1381. uint32_t nand_block_size_kb, mlc_nand;
  1382. /* Create temporary file for building extensions
  1383. * Use process ID for allowing multiple parallel runs
  1384. */
  1385. snprintf(ext_file, MAX_FILENAME, "/tmp/ext_file-%x", getpid());
  1386. while ((opt = getopt(argc, argv, "hpms:i:l:e:a:b:u:n:t:c:k:")) != -1) {
  1387. switch (opt) {
  1388. case 'h':
  1389. usage();
  1390. break;
  1391. case 'l':
  1392. opts.load_addr = strtoul(optarg, NULL, 0);
  1393. break;
  1394. case 'e':
  1395. opts.exec_addr = strtoul(optarg, NULL, 0);
  1396. break;
  1397. case 'm':
  1398. opts.disable_print = 1;
  1399. break;
  1400. case 'u':
  1401. opts.baudrate = strtoul(optarg, NULL, 0);
  1402. break;
  1403. case 'b':
  1404. strncpy(opts.bin_ext_file, optarg, MAX_FILENAME);
  1405. ext_cnt++;
  1406. break;
  1407. case 'p':
  1408. parse = 1;
  1409. break;
  1410. case 'n':
  1411. nand_block_size_kb = strtoul(optarg, NULL, 0);
  1412. opts.nfc_io_args |= (nand_block_size_kb / 64);
  1413. break;
  1414. case 't':
  1415. mlc_nand = 0;
  1416. if (!strncmp("MLC", optarg, 3))
  1417. mlc_nand = 1;
  1418. opts.nfc_io_args |= (mlc_nand << 8);
  1419. break;
  1420. #ifdef CONFIG_MVEBU_SECURE_BOOT
  1421. case 'c': /* SEC extension */
  1422. strncpy(opts.sec_cfg_file, optarg, MAX_FILENAME);
  1423. ext_cnt++;
  1424. break;
  1425. case 'k':
  1426. opts.key_index = strtoul(optarg, NULL, 0);
  1427. break;
  1428. #endif
  1429. default: /* '?' */
  1430. usage_err("Unknown argument");
  1431. exit(EXIT_FAILURE);
  1432. }
  1433. }
  1434. /* Check validity of inputes */
  1435. if (opts.load_addr % 8)
  1436. usage_err("Load address must be 8 bytes aligned");
  1437. if (opts.baudrate % 1200)
  1438. usage_err("Baudrate must be a multiple of 1200");
  1439. /* The remaining arguments are the input
  1440. * and potentially output file
  1441. */
  1442. /* Input file must exist so exit if not */
  1443. if (optind >= argc)
  1444. usage_err("missing input file name");
  1445. len = strlen(argv[optind]);
  1446. if (len > MAX_FILENAME)
  1447. usage_err("file name too long");
  1448. memcpy(in_file, argv[optind], len);
  1449. optind++;
  1450. /* Output file must exist in non parse mode */
  1451. if (optind < argc) {
  1452. len = strlen(argv[optind]);
  1453. if (len > MAX_FILENAME)
  1454. usage_err("file name too long");
  1455. memcpy(out_file, argv[optind], len);
  1456. } else if (!parse)
  1457. usage_err("missing output file name");
  1458. /* open the input file */
  1459. in_fd = fopen(in_file, "rb");
  1460. if (in_fd == NULL) {
  1461. printf("Error: Failed to open input file %s\n", in_file);
  1462. goto main_exit;
  1463. }
  1464. /* Read the input file to buffer
  1465. * Always align the image to 16 byte boundary
  1466. */
  1467. file_size = get_file_size(in_file);
  1468. image_size = (file_size + AES_BLOCK_SZ - 1) & ~(AES_BLOCK_SZ - 1);
  1469. image_buf = calloc(image_size, 1);
  1470. if (image_buf == NULL) {
  1471. fprintf(stderr, "Error: failed allocating input buffer\n");
  1472. return 1;
  1473. }
  1474. read = fread(image_buf, file_size, 1, in_fd);
  1475. if (read != 1) {
  1476. fprintf(stderr, "Error: failed to read input file\n");
  1477. goto main_exit;
  1478. }
  1479. /* Parse the input image and leave */
  1480. if (parse) {
  1481. if (opts.key_index >= CSK_ARR_SZ) {
  1482. fprintf(stderr,
  1483. "Wrong key IDX value. Valid values 0 - %d\n",
  1484. CSK_ARR_SZ - 1);
  1485. goto main_exit;
  1486. }
  1487. ret = parse_image(image_buf, image_size);
  1488. goto main_exit;
  1489. }
  1490. /* Create a blob file from all extensions */
  1491. if (ext_cnt) {
  1492. ret = format_extensions(ext_file);
  1493. if (ret)
  1494. goto main_exit;
  1495. }
  1496. out_fd = fopen(out_file, "wb");
  1497. if (out_fd == NULL) {
  1498. fprintf(stderr,
  1499. "Error: Failed to open output file %s\n", out_file);
  1500. goto main_exit;
  1501. }
  1502. ret = write_prolog(ext_cnt, ext_file, image_buf, image_size, out_fd);
  1503. if (ret)
  1504. goto main_exit;
  1505. #ifdef CONFIG_MVEBU_SECURE_BOOT
  1506. if (opts.sec_opts && (opts.sec_opts->encrypted_image != 0) &&
  1507. (opts.sec_opts->enc_image_sz != 0)) {
  1508. ret = write_boot_image(opts.sec_opts->encrypted_image,
  1509. opts.sec_opts->enc_image_sz, out_fd);
  1510. } else
  1511. #endif
  1512. ret = write_boot_image(image_buf, image_size, out_fd);
  1513. if (ret)
  1514. goto main_exit;
  1515. main_exit:
  1516. if (in_fd)
  1517. fclose(in_fd);
  1518. if (out_fd)
  1519. fclose(out_fd);
  1520. if (image_buf)
  1521. free(image_buf);
  1522. unlink(ext_file);
  1523. #ifdef CONFIG_MVEBU_SECURE_BOOT
  1524. if (opts.sec_opts) {
  1525. if (opts.sec_opts->encrypted_image)
  1526. free(opts.sec_opts->encrypted_image);
  1527. free(opts.sec_opts);
  1528. }
  1529. #endif
  1530. exit(ret);
  1531. }