2 * Image manipulator for Marvell SoCs
3 * supports Kirkwood, Dove, Armada 370, Armada XP, and Armada 38x
5 * (C) Copyright 2013 Thomas Petazzoni
6 * <thomas.petazzoni@free-electrons.com>
8 * SPDX-License-Identifier: GPL-2.0+
10 * Not implemented: support for the register headers in v1 images
13 #include "imagetool.h"
20 #ifdef CONFIG_KWB_SECURE
21 #include <openssl/bn.h>
22 #include <openssl/rsa.h>
23 #include <openssl/pem.h>
24 #include <openssl/err.h>
25 #include <openssl/evp.h>
27 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
28 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
29 static void RSA_get0_key(const RSA *r,
30 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
40 #elif !defined(LIBRESSL_VERSION_NUMBER)
41 void EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
43 EVP_MD_CTX_reset(ctx);
48 static struct image_cfg_element *image_cfg;
50 #ifdef CONFIG_KWB_SECURE
51 static int verbose_mode;
66 struct boot_mode boot_modes[] = {
77 struct nand_ecc_mode {
82 struct nand_ecc_mode nand_ecc_modes[] = {
90 /* Used to identify an undefined execution or destination address */
91 #define ADDR_INVALID ((uint32_t)-1)
93 #define BINARY_MAX_ARGS 8
95 /* In-memory representation of a line of the configuration file */
98 IMAGE_CFG_VERSION = 0x1,
102 IMAGE_CFG_NAND_BLKSZ,
103 IMAGE_CFG_NAND_BADBLK_LOCATION,
104 IMAGE_CFG_NAND_ECC_MODE,
105 IMAGE_CFG_NAND_PAGESZ,
114 IMAGE_CFG_JTAG_DELAY,
117 IMAGE_CFG_SEC_COMMON_IMG,
118 IMAGE_CFG_SEC_SPECIALIZED_IMG,
119 IMAGE_CFG_SEC_BOOT_DEV,
120 IMAGE_CFG_SEC_FUSE_DUMP,
125 static const char * const id_strs[] = {
126 [IMAGE_CFG_VERSION] = "VERSION",
127 [IMAGE_CFG_BOOT_FROM] = "BOOT_FROM",
128 [IMAGE_CFG_DEST_ADDR] = "DEST_ADDR",
129 [IMAGE_CFG_EXEC_ADDR] = "EXEC_ADDR",
130 [IMAGE_CFG_NAND_BLKSZ] = "NAND_BLKSZ",
131 [IMAGE_CFG_NAND_BADBLK_LOCATION] = "NAND_BADBLK_LOCATION",
132 [IMAGE_CFG_NAND_ECC_MODE] = "NAND_ECC_MODE",
133 [IMAGE_CFG_NAND_PAGESZ] = "NAND_PAGE_SIZE",
134 [IMAGE_CFG_BINARY] = "BINARY",
135 [IMAGE_CFG_PAYLOAD] = "PAYLOAD",
136 [IMAGE_CFG_DATA] = "DATA",
137 [IMAGE_CFG_BAUDRATE] = "BAUDRATE",
138 [IMAGE_CFG_DEBUG] = "DEBUG",
139 [IMAGE_CFG_KAK] = "KAK",
140 [IMAGE_CFG_CSK] = "CSK",
141 [IMAGE_CFG_CSK_INDEX] = "CSK_INDEX",
142 [IMAGE_CFG_JTAG_DELAY] = "JTAG_DELAY",
143 [IMAGE_CFG_BOX_ID] = "BOX_ID",
144 [IMAGE_CFG_FLASH_ID] = "FLASH_ID",
145 [IMAGE_CFG_SEC_COMMON_IMG] = "SEC_COMMON_IMG",
146 [IMAGE_CFG_SEC_SPECIALIZED_IMG] = "SEC_SPECIALIZED_IMG",
147 [IMAGE_CFG_SEC_BOOT_DEV] = "SEC_BOOT_DEV",
148 [IMAGE_CFG_SEC_FUSE_DUMP] = "SEC_FUSE_DUMP"
151 struct image_cfg_element {
152 enum image_cfg_type type;
154 unsigned int version;
155 unsigned int bootfrom;
158 unsigned int args[BINARY_MAX_ARGS];
162 unsigned int dstaddr;
163 unsigned int execaddr;
164 unsigned int nandblksz;
165 unsigned int nandbadblklocation;
166 unsigned int nandeccmode;
167 unsigned int nandpagesz;
168 struct ext_hdr_v0_reg regdata;
169 unsigned int baudrate;
171 const char *key_name;
176 bool sec_specialized_img;
177 unsigned int sec_boot_dev;
182 #define IMAGE_CFG_ELEMENT_MAX 256
185 * Utility functions to manipulate boot mode and ecc modes (convert
186 * them back and forth between description strings and the
187 * corresponding numerical identifiers).
190 static const char *image_boot_mode_name(unsigned int id)
194 for (i = 0; boot_modes[i].name; i++)
195 if (boot_modes[i].id == id)
196 return boot_modes[i].name;
200 int image_boot_mode_id(const char *boot_mode_name)
204 for (i = 0; boot_modes[i].name; i++)
205 if (!strcmp(boot_modes[i].name, boot_mode_name))
206 return boot_modes[i].id;
211 int image_nand_ecc_mode_id(const char *nand_ecc_mode_name)
215 for (i = 0; nand_ecc_modes[i].name; i++)
216 if (!strcmp(nand_ecc_modes[i].name, nand_ecc_mode_name))
217 return nand_ecc_modes[i].id;
221 static struct image_cfg_element *
222 image_find_option(unsigned int optiontype)
226 for (i = 0; i < cfgn; i++) {
227 if (image_cfg[i].type == optiontype)
228 return &image_cfg[i];
235 image_count_options(unsigned int optiontype)
238 unsigned int count = 0;
240 for (i = 0; i < cfgn; i++)
241 if (image_cfg[i].type == optiontype)
247 #if defined(CONFIG_KWB_SECURE)
249 static int image_get_csk_index(void)
251 struct image_cfg_element *e;
253 e = image_find_option(IMAGE_CFG_CSK_INDEX);
260 static bool image_get_spezialized_img(void)
262 struct image_cfg_element *e;
264 e = image_find_option(IMAGE_CFG_SEC_SPECIALIZED_IMG);
268 return e->sec_specialized_img;
274 * Compute a 8-bit checksum of a memory area. This algorithm follows
275 * the requirements of the Marvell SoC BootROM specifications.
277 static uint8_t image_checksum8(void *start, uint32_t len)
282 /* check len and return zero checksum if invalid */
294 size_t kwbimage_header_size(unsigned char *ptr)
296 if (image_version((void *)ptr) == 0)
297 return sizeof(struct main_hdr_v0);
299 return KWBHEADER_V1_SIZE((struct main_hdr_v1 *)ptr);
303 * Verify checksum over a complete header that includes the checksum field.
304 * Return 1 when OK, otherwise 0.
306 static int main_hdr_checksum_ok(void *hdr)
308 /* Offsets of checksum in v0 and v1 headers are the same */
309 struct main_hdr_v0 *main_hdr = (struct main_hdr_v0 *)hdr;
312 checksum = image_checksum8(hdr, kwbimage_header_size(hdr));
313 /* Calculated checksum includes the header checksum field. Compensate
316 checksum -= main_hdr->checksum;
318 return checksum == main_hdr->checksum;
321 static uint32_t image_checksum32(void *start, uint32_t len)
326 /* check len and return zero checksum if invalid */
330 if (len % sizeof(uint32_t)) {
331 fprintf(stderr, "Length %d is not in multiple of %zu\n",
332 len, sizeof(uint32_t));
339 len -= sizeof(uint32_t);
345 static uint8_t baudrate_to_option(unsigned int baudrate)
349 return MAIN_HDR_V1_OPT_BAUD_2400;
351 return MAIN_HDR_V1_OPT_BAUD_4800;
353 return MAIN_HDR_V1_OPT_BAUD_9600;
355 return MAIN_HDR_V1_OPT_BAUD_19200;
357 return MAIN_HDR_V1_OPT_BAUD_38400;
359 return MAIN_HDR_V1_OPT_BAUD_57600;
361 return MAIN_HDR_V1_OPT_BAUD_115200;
363 return MAIN_HDR_V1_OPT_BAUD_DEFAULT;
367 #if defined(CONFIG_KWB_SECURE)
368 static void kwb_msg(const char *fmt, ...)
374 vfprintf(stdout, fmt, ap);
379 static int openssl_err(const char *msg)
381 unsigned long ssl_err = ERR_get_error();
383 fprintf(stderr, "%s", msg);
384 fprintf(stderr, ": %s\n",
385 ERR_error_string(ssl_err, 0));
390 static int kwb_load_rsa_key(const char *keydir, const char *name, RSA **p_rsa)
399 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
400 f = fopen(path, "r");
402 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
403 path, strerror(errno));
407 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, "");
409 openssl_err("Failure reading private key");
419 static int kwb_load_cfg_key(struct image_tool_params *params,
420 unsigned int cfg_option, const char *key_name,
423 struct image_cfg_element *e_key;
429 e_key = image_find_option(cfg_option);
431 fprintf(stderr, "%s not configured\n", key_name);
435 res = kwb_load_rsa_key(params->keydir, e_key->key_name, &key);
437 fprintf(stderr, "Failed to load %s\n", key_name);
446 static int kwb_load_kak(struct image_tool_params *params, RSA **p_kak)
448 return kwb_load_cfg_key(params, IMAGE_CFG_KAK, "KAK", p_kak);
451 static int kwb_load_csk(struct image_tool_params *params, RSA **p_csk)
453 return kwb_load_cfg_key(params, IMAGE_CFG_CSK, "CSK", p_csk);
456 static int kwb_compute_pubkey_hash(struct pubkey_der_v1 *pk,
457 struct hash_v1 *hash)
460 unsigned int key_size;
461 unsigned int hash_size;
464 if (!pk || !hash || pk->key[0] != 0x30 || pk->key[1] != 0x82)
467 key_size = (pk->key[2] << 8) + pk->key[3] + 4;
469 ctx = EVP_MD_CTX_create();
471 return openssl_err("EVP context creation failed");
473 EVP_MD_CTX_init(ctx);
474 if (!EVP_DigestInit(ctx, EVP_sha256())) {
475 ret = openssl_err("Digest setup failed");
479 if (!EVP_DigestUpdate(ctx, pk->key, key_size)) {
480 ret = openssl_err("Hashing data failed");
484 if (!EVP_DigestFinal(ctx, hash->hash, &hash_size)) {
485 ret = openssl_err("Could not obtain hash");
489 EVP_MD_CTX_cleanup(ctx);
492 EVP_MD_CTX_destroy(ctx);
496 static int kwb_import_pubkey(RSA **key, struct pubkey_der_v1 *src, char *keyname)
499 const unsigned char *ptr;
505 rsa = d2i_RSAPublicKey(key, &ptr, sizeof(src->key));
507 openssl_err("error decoding public key");
513 fprintf(stderr, "Failed to decode %s pubkey\n", keyname);
517 static int kwb_export_pubkey(RSA *key, struct pubkey_der_v1 *dst, FILE *hashf,
520 int size_exp, size_mod, size_seq;
521 const BIGNUM *key_e, *key_n;
523 char *errmsg = "Failed to encode %s\n";
525 RSA_get0_key(key, NULL, &key_e, NULL);
526 RSA_get0_key(key, &key_n, NULL, NULL);
528 if (!key || !key_e || !key_n || !dst) {
529 fprintf(stderr, "export pk failed: (%p, %p, %p, %p)",
530 key, key_e, key_n, dst);
531 fprintf(stderr, errmsg, keyname);
536 * According to the specs, the key should be PKCS#1 DER encoded.
537 * But unfortunately the really required encoding seems to be different;
538 * it violates DER...! (But it still conformes to BER.)
539 * (Length always in long form w/ 2 byte length code; no leading zero
540 * when MSB of first byte is set...)
541 * So we cannot use the encoding func provided by OpenSSL and have to
542 * do the encoding manually.
545 size_exp = BN_num_bytes(key_e);
546 size_mod = BN_num_bytes(key_n);
547 size_seq = 4 + size_mod + 4 + size_exp;
549 if (size_mod > 256) {
550 fprintf(stderr, "export pk failed: wrong mod size: %d\n",
552 fprintf(stderr, errmsg, keyname);
556 if (4 + size_seq > sizeof(dst->key)) {
557 fprintf(stderr, "export pk failed: seq too large (%d, %lu)\n",
558 4 + size_seq, sizeof(dst->key));
559 fprintf(stderr, errmsg, keyname);
565 /* PKCS#1 (RFC3447) RSAPublicKey structure */
566 *cur++ = 0x30; /* SEQUENCE */
568 *cur++ = (size_seq >> 8) & 0xFF;
569 *cur++ = size_seq & 0xFF;
571 *cur++ = 0x02; /* INTEGER */
573 *cur++ = (size_mod >> 8) & 0xFF;
574 *cur++ = size_mod & 0xFF;
575 BN_bn2bin(key_n, cur);
578 *cur++ = 0x02; /* INTEGER */
580 *cur++ = (size_exp >> 8) & 0xFF;
581 *cur++ = size_exp & 0xFF;
582 BN_bn2bin(key_e, cur);
585 struct hash_v1 pk_hash;
589 ret = kwb_compute_pubkey_hash(dst, &pk_hash);
591 fprintf(stderr, errmsg, keyname);
595 fprintf(hashf, "SHA256 = ");
596 for (i = 0 ; i < sizeof(pk_hash.hash); ++i)
597 fprintf(hashf, "%02X", pk_hash.hash[i]);
598 fprintf(hashf, "\n");
604 int kwb_sign(RSA *key, void *data, int datasz, struct sig_v1 *sig, char *signame)
608 unsigned int sig_size;
612 evp_key = EVP_PKEY_new();
614 return openssl_err("EVP_PKEY object creation failed");
616 if (!EVP_PKEY_set1_RSA(evp_key, key)) {
617 ret = openssl_err("EVP key setup failed");
621 size = EVP_PKEY_size(evp_key);
622 if (size > sizeof(sig->sig)) {
623 fprintf(stderr, "Buffer to small for signature (%d bytes)\n",
629 ctx = EVP_MD_CTX_create();
631 ret = openssl_err("EVP context creation failed");
634 EVP_MD_CTX_init(ctx);
635 if (!EVP_SignInit(ctx, EVP_sha256())) {
636 ret = openssl_err("Signer setup failed");
640 if (!EVP_SignUpdate(ctx, data, datasz)) {
641 ret = openssl_err("Signing data failed");
645 if (!EVP_SignFinal(ctx, sig->sig, &sig_size, evp_key)) {
646 ret = openssl_err("Could not obtain signature");
650 EVP_MD_CTX_cleanup(ctx);
651 EVP_MD_CTX_destroy(ctx);
652 EVP_PKEY_free(evp_key);
657 EVP_MD_CTX_destroy(ctx);
659 EVP_PKEY_free(evp_key);
660 fprintf(stderr, "Failed to create %s signature\n", signame);
664 int kwb_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
672 evp_key = EVP_PKEY_new();
674 return openssl_err("EVP_PKEY object creation failed");
676 if (!EVP_PKEY_set1_RSA(evp_key, key)) {
677 ret = openssl_err("EVP key setup failed");
681 size = EVP_PKEY_size(evp_key);
682 if (size > sizeof(sig->sig)) {
683 fprintf(stderr, "Invalid signature size (%d bytes)\n",
689 ctx = EVP_MD_CTX_create();
691 ret = openssl_err("EVP context creation failed");
694 EVP_MD_CTX_init(ctx);
695 if (!EVP_VerifyInit(ctx, EVP_sha256())) {
696 ret = openssl_err("Verifier setup failed");
700 if (!EVP_VerifyUpdate(ctx, data, datasz)) {
701 ret = openssl_err("Hashing data failed");
705 if (!EVP_VerifyFinal(ctx, sig->sig, sizeof(sig->sig), evp_key)) {
706 ret = openssl_err("Could not verify signature");
710 EVP_MD_CTX_cleanup(ctx);
711 EVP_MD_CTX_destroy(ctx);
712 EVP_PKEY_free(evp_key);
717 EVP_MD_CTX_destroy(ctx);
719 EVP_PKEY_free(evp_key);
720 fprintf(stderr, "Failed to verify %s signature\n", signame);
724 int kwb_sign_and_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
727 if (kwb_sign(key, data, datasz, sig, signame) < 0)
730 if (kwb_verify(key, data, datasz, sig, signame) < 0)
737 int kwb_dump_fuse_cmds_38x(FILE *out, struct secure_hdr_v1 *sec_hdr)
739 struct hash_v1 kak_pub_hash;
740 struct image_cfg_element *e;
741 unsigned int fuse_line;
747 if (!out || !sec_hdr)
750 ret = kwb_compute_pubkey_hash(&sec_hdr->kak, &kak_pub_hash);
754 fprintf(out, "# burn KAK pub key hash\n");
755 ptr = kak_pub_hash.hash;
756 for (fuse_line = 26; fuse_line <= 30; ++fuse_line) {
757 fprintf(out, "fuse prog -y %u 0 ", fuse_line);
759 for (i = 4; i-- > 0;)
760 fprintf(out, "%02hx", (ushort)ptr[i]);
764 if (fuse_line < 30) {
765 for (i = 3; i-- > 0;)
766 fprintf(out, "%02hx", (ushort)ptr[i]);
769 fprintf(out, "000000");
772 fprintf(out, " 1\n");
775 fprintf(out, "# burn CSK selection\n");
777 idx = image_get_csk_index();
778 if (idx < 0 || idx > 15) {
783 for (fuse_line = 31; fuse_line < 31 + idx; ++fuse_line)
784 fprintf(out, "fuse prog -y %u 0 00000001 00000000 1\n",
787 fprintf(out, "# CSK index is 0; no mods needed\n");
790 e = image_find_option(IMAGE_CFG_BOX_ID);
792 fprintf(out, "# set box ID\n");
793 fprintf(out, "fuse prog -y 48 0 %08x 00000000 1\n", e->boxid);
796 e = image_find_option(IMAGE_CFG_FLASH_ID);
798 fprintf(out, "# set flash ID\n");
799 fprintf(out, "fuse prog -y 47 0 %08x 00000000 1\n", e->flashid);
802 fprintf(out, "# enable secure mode ");
803 fprintf(out, "(must be the last fuse line written)\n");
806 e = image_find_option(IMAGE_CFG_SEC_BOOT_DEV);
808 fprintf(stderr, "ERROR: secured mode boot device not given\n");
813 if (e->sec_boot_dev > 0xff) {
814 fprintf(stderr, "ERROR: secured mode boot device invalid\n");
819 val |= (e->sec_boot_dev << 8);
821 fprintf(out, "fuse prog -y 24 0 %08x 0103e0a9 1\n", val);
823 fprintf(out, "# lock (unused) fuse lines (0-23)s\n");
824 for (fuse_line = 0; fuse_line < 24; ++fuse_line)
825 fprintf(out, "fuse prog -y %u 2 1\n", fuse_line);
827 fprintf(out, "# OK, that's all :-)\n");
833 static int kwb_dump_fuse_cmds(struct secure_hdr_v1 *sec_hdr)
836 struct image_cfg_element *e;
838 e = image_find_option(IMAGE_CFG_SEC_FUSE_DUMP);
842 if (!strcmp(e->name, "a38x")) {
843 FILE *out = fopen("kwb_fuses_a38x.txt", "w+");
845 kwb_dump_fuse_cmds_38x(out, sec_hdr);
858 static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
861 struct image_cfg_element *e;
863 struct main_hdr_v0 *main_hdr;
868 * Calculate the size of the header and the size of the
871 headersz = sizeof(struct main_hdr_v0);
873 if (image_count_options(IMAGE_CFG_DATA) > 0) {
875 headersz += sizeof(struct ext_hdr_v0);
878 if (image_count_options(IMAGE_CFG_PAYLOAD) > 1) {
879 fprintf(stderr, "More than one payload, not possible\n");
883 image = malloc(headersz);
885 fprintf(stderr, "Cannot allocate memory for image\n");
889 memset(image, 0, headersz);
891 main_hdr = (struct main_hdr_v0 *)image;
893 /* Fill in the main header */
894 main_hdr->blocksize =
895 cpu_to_le32(payloadsz + sizeof(uint32_t) - headersz);
896 main_hdr->srcaddr = cpu_to_le32(headersz);
897 main_hdr->ext = has_ext;
898 main_hdr->destaddr = cpu_to_le32(params->addr);
899 main_hdr->execaddr = cpu_to_le32(params->ep);
901 e = image_find_option(IMAGE_CFG_BOOT_FROM);
903 main_hdr->blockid = e->bootfrom;
904 e = image_find_option(IMAGE_CFG_NAND_ECC_MODE);
906 main_hdr->nandeccmode = e->nandeccmode;
907 e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
909 main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
910 main_hdr->checksum = image_checksum8(image,
911 sizeof(struct main_hdr_v0));
913 /* Generate the ext header */
915 struct ext_hdr_v0 *ext_hdr;
918 ext_hdr = (struct ext_hdr_v0 *)
919 (image + sizeof(struct main_hdr_v0));
920 ext_hdr->offset = cpu_to_le32(0x40);
922 for (cfgi = 0, datai = 0; cfgi < cfgn; cfgi++) {
923 e = &image_cfg[cfgi];
924 if (e->type != IMAGE_CFG_DATA)
927 ext_hdr->rcfg[datai].raddr =
928 cpu_to_le32(e->regdata.raddr);
929 ext_hdr->rcfg[datai].rdata =
930 cpu_to_le32(e->regdata.rdata);
934 ext_hdr->checksum = image_checksum8(ext_hdr,
935 sizeof(struct ext_hdr_v0));
942 static size_t image_headersz_v1(int *hasext)
944 struct image_cfg_element *binarye;
948 * Calculate the size of the header and the size of the
951 headersz = sizeof(struct main_hdr_v1);
953 if (image_count_options(IMAGE_CFG_BINARY) > 1) {
954 fprintf(stderr, "More than one binary blob, not supported\n");
958 if (image_count_options(IMAGE_CFG_PAYLOAD) > 1) {
959 fprintf(stderr, "More than one payload, not possible\n");
963 binarye = image_find_option(IMAGE_CFG_BINARY);
968 ret = stat(binarye->binary.file, &s);
973 memset(cwd, 0, sizeof(cwd));
974 if (!getcwd(cwd, sizeof(cwd))) {
975 dir = "current working directory";
976 perror("getcwd() failed");
980 "Didn't find the file '%s' in '%s' which is mandatory to generate the image\n"
981 "This file generally contains the DDR3 training code, and should be extracted from an existing bootable\n"
982 "image for your board. See 'kwbimage -x' to extract it from an existing image.\n",
983 binarye->binary.file, dir);
987 headersz += sizeof(struct opt_hdr_v1) +
989 (binarye->binary.nargs + 2) * sizeof(uint32_t);
994 #if defined(CONFIG_KWB_SECURE)
995 if (image_get_csk_index() >= 0) {
996 headersz += sizeof(struct secure_hdr_v1);
1002 #if defined(CONFIG_SYS_U_BOOT_OFFS)
1003 if (headersz > CONFIG_SYS_U_BOOT_OFFS) {
1005 "Error: Image header (incl. SPL image) too big!\n");
1006 fprintf(stderr, "header=0x%x CONFIG_SYS_U_BOOT_OFFS=0x%x!\n",
1007 (int)headersz, CONFIG_SYS_U_BOOT_OFFS);
1008 fprintf(stderr, "Increase CONFIG_SYS_U_BOOT_OFFS!\n");
1012 headersz = CONFIG_SYS_U_BOOT_OFFS;
1016 * The payload should be aligned on some reasonable
1019 return ALIGN_SUP(headersz, 4096);
1022 int add_binary_header_v1(uint8_t *cur)
1024 struct image_cfg_element *binarye;
1025 struct opt_hdr_v1 *hdr = (struct opt_hdr_v1 *)cur;
1033 binarye = image_find_option(IMAGE_CFG_BINARY);
1038 hdr->headertype = OPT_HDR_V1_BINARY_TYPE;
1040 bin = fopen(binarye->binary.file, "r");
1042 fprintf(stderr, "Cannot open binary file %s\n",
1043 binarye->binary.file);
1047 if (fstat(fileno(bin), &s)) {
1048 fprintf(stderr, "Cannot stat binary file %s\n",
1049 binarye->binary.file);
1053 binhdrsz = sizeof(struct opt_hdr_v1) +
1054 (binarye->binary.nargs + 2) * sizeof(uint32_t) +
1058 * The size includes the binary image size, rounded
1059 * up to a 4-byte boundary. Plus 4 bytes for the
1060 * next-header byte and 3-byte alignment at the end.
1062 binhdrsz = ALIGN_SUP(binhdrsz, 4) + 4;
1063 hdr->headersz_lsb = cpu_to_le16(binhdrsz & 0xFFFF);
1064 hdr->headersz_msb = (binhdrsz & 0xFFFF0000) >> 16;
1066 cur += sizeof(struct opt_hdr_v1);
1068 args = (uint32_t *)cur;
1069 *args = cpu_to_le32(binarye->binary.nargs);
1071 for (argi = 0; argi < binarye->binary.nargs; argi++)
1072 args[argi] = cpu_to_le32(binarye->binary.args[argi]);
1074 cur += (binarye->binary.nargs + 1) * sizeof(uint32_t);
1076 ret = fread(cur, s.st_size, 1, bin);
1079 "Could not read binary image %s\n",
1080 binarye->binary.file);
1086 cur += ALIGN_SUP(s.st_size, 4);
1089 * For now, we don't support more than one binary
1090 * header, and no other header types are
1091 * supported. So, the binary header is necessarily the
1094 *((uint32_t *)cur) = 0x00000000;
1096 cur += sizeof(uint32_t);
1106 #if defined(CONFIG_KWB_SECURE)
1108 int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
1113 hashf = fopen("pub_kak_hash.txt", "w");
1115 res = kwb_export_pubkey(kak, &secure_hdr->kak, hashf, "KAK");
1119 return res < 0 ? 1 : 0;
1122 int kwb_sign_csk_with_kak(struct image_tool_params *params,
1123 struct secure_hdr_v1 *secure_hdr, RSA *csk)
1126 RSA *kak_pub = NULL;
1127 int csk_idx = image_get_csk_index();
1128 struct sig_v1 tmp_sig;
1130 if (csk_idx >= 16) {
1131 fprintf(stderr, "Invalid CSK index %d\n", csk_idx);
1135 if (kwb_load_kak(params, &kak) < 0)
1138 if (export_pub_kak_hash(kak, secure_hdr))
1141 if (kwb_import_pubkey(&kak_pub, &secure_hdr->kak, "KAK") < 0)
1144 if (kwb_export_pubkey(csk, &secure_hdr->csk[csk_idx], NULL, "CSK") < 0)
1147 if (kwb_sign_and_verify(kak, &secure_hdr->csk,
1148 sizeof(secure_hdr->csk) +
1149 sizeof(secure_hdr->csksig),
1150 &tmp_sig, "CSK") < 0)
1153 if (kwb_verify(kak_pub, &secure_hdr->csk,
1154 sizeof(secure_hdr->csk) +
1155 sizeof(secure_hdr->csksig),
1156 &tmp_sig, "CSK (2)") < 0)
1159 secure_hdr->csksig = tmp_sig;
1164 int add_secure_header_v1(struct image_tool_params *params, uint8_t *ptr,
1165 int payloadsz, size_t headersz, uint8_t *image,
1166 struct secure_hdr_v1 *secure_hdr)
1168 struct image_cfg_element *e_jtagdelay;
1169 struct image_cfg_element *e_boxid;
1170 struct image_cfg_element *e_flashid;
1172 unsigned char *image_ptr;
1174 struct sig_v1 tmp_sig;
1175 bool specialized_img = image_get_spezialized_img();
1177 kwb_msg("Create secure header content\n");
1179 e_jtagdelay = image_find_option(IMAGE_CFG_JTAG_DELAY);
1180 e_boxid = image_find_option(IMAGE_CFG_BOX_ID);
1181 e_flashid = image_find_option(IMAGE_CFG_FLASH_ID);
1183 if (kwb_load_csk(params, &csk) < 0)
1186 secure_hdr->headertype = OPT_HDR_V1_SECURE_TYPE;
1187 secure_hdr->headersz_msb = 0;
1188 secure_hdr->headersz_lsb = cpu_to_le16(sizeof(struct secure_hdr_v1));
1190 secure_hdr->jtag_delay = e_jtagdelay->jtag_delay;
1191 if (e_boxid && specialized_img)
1192 secure_hdr->boxid = cpu_to_le32(e_boxid->boxid);
1193 if (e_flashid && specialized_img)
1194 secure_hdr->flashid = cpu_to_le32(e_flashid->flashid);
1196 if (kwb_sign_csk_with_kak(params, secure_hdr, csk))
1199 image_ptr = ptr + headersz;
1200 image_size = payloadsz - headersz;
1202 if (kwb_sign_and_verify(csk, image_ptr, image_size,
1203 &secure_hdr->imgsig, "image") < 0)
1206 if (kwb_sign_and_verify(csk, image, headersz, &tmp_sig, "header") < 0)
1209 secure_hdr->hdrsig = tmp_sig;
1211 kwb_dump_fuse_cmds(secure_hdr);
1217 static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
1218 uint8_t *ptr, int payloadsz)
1220 struct image_cfg_element *e;
1221 struct main_hdr_v1 *main_hdr;
1222 #if defined(CONFIG_KWB_SECURE)
1223 struct secure_hdr_v1 *secure_hdr = NULL;
1226 uint8_t *image, *cur;
1228 uint8_t *next_ext = NULL;
1231 * Calculate the size of the header and the size of the
1234 headersz = image_headersz_v1(&hasext);
1238 image = malloc(headersz);
1240 fprintf(stderr, "Cannot allocate memory for image\n");
1244 memset(image, 0, headersz);
1246 main_hdr = (struct main_hdr_v1 *)image;
1248 cur += sizeof(struct main_hdr_v1);
1249 next_ext = &main_hdr->ext;
1251 /* Fill the main header */
1252 main_hdr->blocksize =
1253 cpu_to_le32(payloadsz - headersz + sizeof(uint32_t));
1254 main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
1255 main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
1256 main_hdr->destaddr = cpu_to_le32(params->addr)
1257 - sizeof(image_header_t);
1258 main_hdr->execaddr = cpu_to_le32(params->ep);
1259 main_hdr->srcaddr = cpu_to_le32(headersz);
1260 main_hdr->ext = hasext;
1261 main_hdr->version = 1;
1262 e = image_find_option(IMAGE_CFG_BOOT_FROM);
1264 main_hdr->blockid = e->bootfrom;
1265 e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
1267 main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
1268 e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
1270 main_hdr->nandbadblklocation = e->nandbadblklocation;
1271 e = image_find_option(IMAGE_CFG_BAUDRATE);
1273 main_hdr->options = baudrate_to_option(e->baudrate);
1274 e = image_find_option(IMAGE_CFG_DEBUG);
1276 main_hdr->flags = e->debug ? 0x1 : 0;
1278 #if defined(CONFIG_KWB_SECURE)
1279 if (image_get_csk_index() >= 0) {
1281 * only reserve the space here; we fill the header later since
1282 * we need the header to be complete to compute the signatures
1284 secure_hdr = (struct secure_hdr_v1 *)cur;
1285 cur += sizeof(struct secure_hdr_v1);
1286 next_ext = &secure_hdr->next;
1291 if (add_binary_header_v1(cur))
1294 #if defined(CONFIG_KWB_SECURE)
1295 if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz,
1296 headersz, image, secure_hdr))
1300 /* Calculate and set the header checksum */
1301 main_hdr->checksum = image_checksum8(main_hdr, headersz);
1303 *imagesz = headersz;
1307 int recognize_keyword(char *keyword)
1311 for (kw_id = 1; kw_id < IMAGE_CFG_COUNT; ++kw_id)
1312 if (!strcmp(keyword, id_strs[kw_id]))
1318 static int image_create_config_parse_oneline(char *line,
1319 struct image_cfg_element *el)
1321 char *keyword, *saveptr, *value1, *value2;
1322 char delimiters[] = " \t";
1323 int keyword_id, ret, argi;
1324 char *unknown_msg = "Ignoring unknown line '%s'\n";
1326 keyword = strtok_r(line, delimiters, &saveptr);
1327 keyword_id = recognize_keyword(keyword);
1330 fprintf(stderr, unknown_msg, line);
1334 el->type = keyword_id;
1336 value1 = strtok_r(NULL, delimiters, &saveptr);
1339 fprintf(stderr, "Parameter missing in line '%s'\n", line);
1343 switch (keyword_id) {
1344 case IMAGE_CFG_VERSION:
1345 el->version = atoi(value1);
1347 case IMAGE_CFG_BOOT_FROM:
1348 ret = image_boot_mode_id(value1);
1351 fprintf(stderr, "Invalid boot media '%s'\n", value1);
1356 case IMAGE_CFG_NAND_BLKSZ:
1357 el->nandblksz = strtoul(value1, NULL, 16);
1359 case IMAGE_CFG_NAND_BADBLK_LOCATION:
1360 el->nandbadblklocation = strtoul(value1, NULL, 16);
1362 case IMAGE_CFG_NAND_ECC_MODE:
1363 ret = image_nand_ecc_mode_id(value1);
1366 fprintf(stderr, "Invalid NAND ECC mode '%s'\n", value1);
1369 el->nandeccmode = ret;
1371 case IMAGE_CFG_NAND_PAGESZ:
1372 el->nandpagesz = strtoul(value1, NULL, 16);
1374 case IMAGE_CFG_BINARY:
1377 el->binary.file = strdup(value1);
1379 char *value = strtok_r(NULL, delimiters, &saveptr);
1383 el->binary.args[argi] = strtoul(value, NULL, 16);
1385 if (argi >= BINARY_MAX_ARGS) {
1387 "Too many arguments for BINARY\n");
1391 el->binary.nargs = argi;
1393 case IMAGE_CFG_DATA:
1394 value2 = strtok_r(NULL, delimiters, &saveptr);
1396 if (!value1 || !value2) {
1398 "Invalid number of arguments for DATA\n");
1402 el->regdata.raddr = strtoul(value1, NULL, 16);
1403 el->regdata.rdata = strtoul(value2, NULL, 16);
1405 case IMAGE_CFG_BAUDRATE:
1406 el->baudrate = strtoul(value1, NULL, 10);
1408 case IMAGE_CFG_DEBUG:
1409 el->debug = strtoul(value1, NULL, 10);
1412 el->key_name = strdup(value1);
1415 el->key_name = strdup(value1);
1417 case IMAGE_CFG_CSK_INDEX:
1418 el->csk_idx = strtol(value1, NULL, 0);
1420 case IMAGE_CFG_JTAG_DELAY:
1421 el->jtag_delay = strtoul(value1, NULL, 0);
1423 case IMAGE_CFG_BOX_ID:
1424 el->boxid = strtoul(value1, NULL, 0);
1426 case IMAGE_CFG_FLASH_ID:
1427 el->flashid = strtoul(value1, NULL, 0);
1429 case IMAGE_CFG_SEC_SPECIALIZED_IMG:
1430 el->sec_specialized_img = true;
1432 case IMAGE_CFG_SEC_COMMON_IMG:
1433 el->sec_specialized_img = false;
1435 case IMAGE_CFG_SEC_BOOT_DEV:
1436 el->sec_boot_dev = strtoul(value1, NULL, 0);
1438 case IMAGE_CFG_SEC_FUSE_DUMP:
1439 el->name = strdup(value1);
1442 fprintf(stderr, unknown_msg, line);
1449 * Parse the configuration file 'fcfg' into the array of configuration
1450 * elements 'image_cfg', and return the number of configuration
1451 * elements in 'cfgn'.
1453 static int image_create_config_parse(FILE *fcfg)
1458 /* Parse the configuration file */
1459 while (!feof(fcfg)) {
1463 /* Read the current line */
1464 memset(buf, 0, sizeof(buf));
1465 line = fgets(buf, sizeof(buf), fcfg);
1469 /* Ignore useless lines */
1470 if (line[0] == '\n' || line[0] == '#')
1473 /* Strip final newline */
1474 if (line[strlen(line) - 1] == '\n')
1475 line[strlen(line) - 1] = 0;
1477 /* Parse the current line */
1478 ret = image_create_config_parse_oneline(line,
1485 if (cfgi >= IMAGE_CFG_ELEMENT_MAX) {
1487 "Too many configuration elements in .cfg file\n");
1496 static int image_get_version(void)
1498 struct image_cfg_element *e;
1500 e = image_find_option(IMAGE_CFG_VERSION);
1507 static void kwbimage_set_header(void *ptr, struct stat *sbuf, int ifd,
1508 struct image_tool_params *params)
1513 size_t headersz = 0;
1518 fcfg = fopen(params->imagename, "r");
1520 fprintf(stderr, "Could not open input file %s\n",
1525 image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
1526 sizeof(struct image_cfg_element));
1528 fprintf(stderr, "Cannot allocate memory\n");
1533 memset(image_cfg, 0,
1534 IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
1537 ret = image_create_config_parse(fcfg);
1544 /* The MVEBU BootROM does not allow non word aligned payloads */
1545 sbuf->st_size = ALIGN_SUP(sbuf->st_size, 4);
1547 version = image_get_version();
1550 * Fallback to version 0 if no version is provided in the
1555 image = image_create_v0(&headersz, params, sbuf->st_size);
1559 image = image_create_v1(&headersz, params, ptr, sbuf->st_size);
1563 fprintf(stderr, "Unsupported version %d\n", version);
1569 fprintf(stderr, "Could not create image\n");
1576 /* Build and add image checksum header */
1578 cpu_to_le32(image_checksum32((uint32_t *)ptr, sbuf->st_size));
1579 size = write(ifd, &checksum, sizeof(uint32_t));
1580 if (size != sizeof(uint32_t)) {
1581 fprintf(stderr, "Error:%s - Checksum write %d bytes %s\n",
1582 params->cmdname, size, params->imagefile);
1586 sbuf->st_size += sizeof(uint32_t);
1588 /* Finally copy the header into the image area */
1589 memcpy(ptr, image, headersz);
1594 static void kwbimage_print_header(const void *ptr)
1596 struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
1598 printf("Image Type: MVEBU Boot from %s Image\n",
1599 image_boot_mode_name(mhdr->blockid));
1600 printf("Image version:%d\n", image_version((void *)ptr));
1601 printf("Data Size: ");
1602 genimg_print_size(mhdr->blocksize - sizeof(uint32_t));
1603 printf("Load Address: %08x\n", mhdr->destaddr);
1604 printf("Entry Point: %08x\n", mhdr->execaddr);
1607 static int kwbimage_check_image_types(uint8_t type)
1609 if (type == IH_TYPE_KWBIMAGE)
1610 return EXIT_SUCCESS;
1612 return EXIT_FAILURE;
1615 static int kwbimage_verify_header(unsigned char *ptr, int image_size,
1616 struct image_tool_params *params)
1620 if (!main_hdr_checksum_ok(ptr))
1621 return -FDT_ERR_BADSTRUCTURE;
1623 /* Only version 0 extended header has checksum */
1624 if (image_version((void *)ptr) == 0) {
1625 struct ext_hdr_v0 *ext_hdr;
1627 ext_hdr = (struct ext_hdr_v0 *)
1628 (ptr + sizeof(struct main_hdr_v0));
1629 checksum = image_checksum8(ext_hdr,
1630 sizeof(struct ext_hdr_v0)
1632 if (checksum != ext_hdr->checksum)
1633 return -FDT_ERR_BADSTRUCTURE;
1639 static int kwbimage_generate(struct image_tool_params *params,
1640 struct image_type_params *tparams)
1648 fcfg = fopen(params->imagename, "r");
1650 fprintf(stderr, "Could not open input file %s\n",
1655 image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
1656 sizeof(struct image_cfg_element));
1658 fprintf(stderr, "Cannot allocate memory\n");
1663 memset(image_cfg, 0,
1664 IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
1667 ret = image_create_config_parse(fcfg);
1674 version = image_get_version();
1677 * Fallback to version 0 if no version is provided in the
1682 alloc_len = sizeof(struct main_hdr_v0) +
1683 sizeof(struct ext_hdr_v0);
1687 alloc_len = image_headersz_v1(NULL);
1691 fprintf(stderr, "Unsupported version %d\n", version);
1698 hdr = malloc(alloc_len);
1700 fprintf(stderr, "%s: malloc return failure: %s\n",
1701 params->cmdname, strerror(errno));
1705 memset(hdr, 0, alloc_len);
1706 tparams->header_size = alloc_len;
1710 * The resulting image needs to be 4-byte aligned. At least
1711 * the Marvell hdrparser tool complains if its unaligned.
1712 * By returning 1 here in this function, called via
1713 * tparams->vrec_header() in mkimage.c, mkimage will
1714 * automatically pad the the resulting image to a 4-byte
1715 * size if necessary.
1721 * Report Error if xflag is set in addition to default
1723 static int kwbimage_check_params(struct image_tool_params *params)
1725 if (!strlen(params->imagename)) {
1726 char *msg = "Configuration file for kwbimage creation omitted";
1728 fprintf(stderr, "Error:%s - %s\n", params->cmdname, msg);
1732 return (params->dflag && (params->fflag || params->lflag)) ||
1733 (params->fflag && (params->dflag || params->lflag)) ||
1734 (params->lflag && (params->dflag || params->fflag)) ||
1735 (params->xflag) || !(strlen(params->imagename));
1739 * kwbimage type parameters definition
1743 "Marvell MVEBU Boot Image support",
1746 kwbimage_check_params,
1747 kwbimage_verify_header,
1748 kwbimage_print_header,
1749 kwbimage_set_header,
1751 kwbimage_check_image_types,