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