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