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.3"
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 
usage_err(char * msg)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 
usage(void)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 
get_file_size(char * filename)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 
checksum32(uint32_t * start,int len)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
create_rsa_signature(mbedtls_pk_context * pk_ctx,const unsigned char * input,size_t ilen,const char * pers,uint8_t * signature)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_ret(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  */
verify_rsa_signature(const unsigned char * pub_key,size_t klen,const unsigned char * input,size_t ilen,const char * pers,uint8_t * signature)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 	unsigned char			*pkey = (unsigned char *)pub_key;
358 
359 	/* Not sure this is required,
360 	 * but it's safer to start with empty buffer
361 	 */
362 	memset(hash, 0, sizeof(hash));
363 
364 	mbedtls_pk_init(&pk_ctx);
365 	mbedtls_ctr_drbg_init(&ctr_drbg);
366 	mbedtls_entropy_init(&entropy);
367 
368 	/* Seed the random number generator */
369 	rval = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
370 				(const unsigned char *)pers, strlen(pers));
371 	if (rval != 0) {
372 		fprintf(stderr, " Failed in ctr_drbg_init call (%d)!\n", rval);
373 		goto verify_exit;
374 	}
375 
376 	/* Check ability to read the public key */
377 	rval = mbedtls_pk_parse_subpubkey(&pkey, pub_key + klen, &pk_ctx);
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_ret(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  */
image_encrypt(uint8_t * buf,uint32_t blen)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_ret(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  */
verify_secure_header_signatures(header_t * main_hdr,sec_entry_t * sec_ext)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  */
verify_and_copy_file_name_entry(const char * element_name,const char * element,char * copy_to)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  */
parse_sec_config_file(char * filename)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 
format_sec_ext(char * filename,FILE * out_fd)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 
884 		/* Data in the output buffer is aligned to the buffer end */
885 		der_buf_start = output_buf + sizeof(output_buf) - output_len;
886 		/* In the header DER data is aligned
887 		 * to the start of appropriate field
888 		 */
889 		bzero(out_der_key, MAX_RSA_DER_BYTE_LEN);
890 		memcpy(out_der_key, der_buf_start, output_len);
891 
892 	} /* for every private key file */
893 
894 	/* The CSK block signature can be created here */
895 	if (create_rsa_signature(&opts.sec_opts->kak_pk,
896 				 &sec_ext.csk_keys[0][0],
897 				 sizeof(sec_ext.csk_keys),
898 				 opts.sec_opts->csk_key_file[
899 					 opts.sec_opts->csk_index],
900 				 sec_ext.csk_sign) != 0) {
901 		fprintf(stderr, "Failed to sign CSK keys block!\n");
902 		return 1;
903 	}
904 
905 	/* Check that everything is correct */
906 	if (verify_rsa_signature(sec_ext.kak_key,
907 				 MAX_RSA_DER_BYTE_LEN,
908 				 &sec_ext.csk_keys[0][0],
909 				 sizeof(sec_ext.csk_keys),
910 				 opts.sec_opts->kak_key_file,
911 				 sec_ext.csk_sign) != 0) {
912 		fprintf(stderr, "Failed to verify CSK keys block signature!\n");
913 		return 1;
914 	}
915 
916 	/* AES encryption stuff */
917 	if (strlen(opts.sec_opts->aes_key_file) != 0) {
918 		FILE		*in_fd;
919 
920 		in_fd = fopen(opts.sec_opts->aes_key_file, "rb");
921 		if (in_fd == NULL) {
922 			fprintf(stderr, "Failed to open AES key file %s\n",
923 				opts.sec_opts->aes_key_file);
924 			return 1;
925 		}
926 
927 		/* Read the AES key in ASCII format byte by byte */
928 		for (index = 0; index < AES_KEY_BYTE_LEN; index++) {
929 			if (fscanf(in_fd, "%02hhx",
930 			    opts.sec_opts->aes_key + index) != 1) {
931 				fprintf(stderr,
932 					"Failed to read AES key byte %d ",
933 					index);
934 				fprintf(stderr,
935 					"from file %s\n",
936 					opts.sec_opts->aes_key_file);
937 				fclose(in_fd);
938 				return 1;
939 			}
940 		}
941 		fclose(in_fd);
942 		sec_ext.encrypt_en = 1;
943 	} else {
944 		sec_ext.encrypt_en = 0;
945 	}
946 
947 	/* Fill the rest of the trusted boot extension fields */
948 	sec_ext.box_id		= opts.sec_opts->box_id;
949 	sec_ext.flash_id	= opts.sec_opts->flash_id;
950 	sec_ext.efuse_dis	= opts.sec_opts->efuse_disable;
951 	sec_ext.jtag_delay	= opts.sec_opts->jtag_delay;
952 	sec_ext.jtag_en		= opts.sec_opts->jtag_enable;
953 
954 	memcpy(sec_ext.cp_ctrl_arr,
955 	       opts.sec_opts->cp_ctrl_arr,
956 	       sizeof(uint32_t) * CP_CTRL_EL_ARRAY_SZ);
957 	memcpy(sec_ext.cp_efuse_arr,
958 	       opts.sec_opts->cp_efuse_arr,
959 	       sizeof(uint32_t) * CP_CTRL_EL_ARRAY_SZ);
960 
961 	/* Write the resulting extension to file
962 	 * (image and header signature fields are still empty)
963 	 */
964 
965 	/* Write extension header */
966 	written = fwrite(&header, sizeof(ext_header_t), 1, out_fd);
967 	if (written != 1) {
968 		fprintf(stderr,
969 			"Failed to write SEC extension header to the file\n");
970 		return 1;
971 	}
972 	/* Write extension body */
973 	written = fwrite(&sec_ext, sizeof(sec_entry_t), 1, out_fd);
974 	if (written != 1) {
975 		fprintf(stderr,
976 			"Failed to write SEC extension body to the file\n");
977 		return 1;
978 	}
979 
980 	return 0;
981 }
982 
983 /*******************************************************************************
984  *    finalize_secure_ext
985  *          Make final changes to secure extension - calculate image and header
986  *          signatures and encrypt the image if needed.
987  *          The main header checksum and image size fields updated accordingly
988  *    INPUT:
989  *          header       Main header
990  *          prolog_buf   the entire prolog buffer
991  *          prolog_size  prolog buffer length
992  *          image_buf    buffer containing the input binary image
993  *          image_size   image buffer size.
994  *    OUTPUT:
995  *          none
996  *    RETURN:
997  *          0 on success
998  */
finalize_secure_ext(header_t * header,uint8_t * prolog_buf,uint32_t prolog_size,uint8_t * image_buf,int image_size)999 int finalize_secure_ext(header_t *header,
1000 			uint8_t *prolog_buf, uint32_t prolog_size,
1001 			uint8_t *image_buf, int image_size)
1002 {
1003 	int		cur_ext, offset;
1004 	uint8_t		*final_image = image_buf;
1005 	uint32_t	final_image_sz = image_size;
1006 	uint8_t		hdr_sign[RSA_SIGN_BYTE_LEN];
1007 	sec_entry_t	*sec_ext = 0;
1008 
1009 	/* Find the Trusted Boot Header between available extensions */
1010 	for (cur_ext = 0, offset = sizeof(header_t);
1011 	     cur_ext < header->ext_count; cur_ext++) {
1012 		ext_header_t *ext_hdr = (ext_header_t *)(prolog_buf + offset);
1013 
1014 		if (ext_hdr->type == EXT_TYPE_SECURITY) {
1015 			sec_ext = (sec_entry_t *)(prolog_buf + offset +
1016 				   sizeof(ext_header_t) + ext_hdr->offset);
1017 			break;
1018 		}
1019 
1020 		offset += sizeof(ext_header_t);
1021 		/* If offset is Zero, the extension follows its header */
1022 		if (ext_hdr->offset == 0)
1023 			offset += ext_hdr->size;
1024 	}
1025 
1026 	if (sec_ext == 0) {
1027 		fprintf(stderr, "Error: No Trusted Boot extension found!\n");
1028 		return -1;
1029 	}
1030 
1031 	if (sec_ext->encrypt_en) {
1032 		/* Encrypt the image if needed */
1033 		fprintf(stdout, "Encrypting the image...\n");
1034 
1035 		if (image_encrypt(image_buf, image_size) != 0) {
1036 			fprintf(stderr, "Failed to encrypt the image!\n");
1037 			return -1;
1038 		}
1039 
1040 		/* Image size and checksum should be updated after encryption.
1041 		 * This way the image could be verified by the BootROM
1042 		 * before decryption.
1043 		 */
1044 		final_image = opts.sec_opts->encrypted_image;
1045 		final_image_sz = opts.sec_opts->enc_image_sz;
1046 
1047 		header->boot_image_size = final_image_sz;
1048 		header->boot_image_checksum =
1049 			checksum32((uint32_t *)final_image, final_image_sz);
1050 	} /* AES encryption */
1051 
1052 	/* Create the image signature first, since it will be later
1053 	 * signed along with the header signature
1054 	 */
1055 	if (create_rsa_signature(&opts.sec_opts->csk_pk[
1056 					opts.sec_opts->csk_index],
1057 				 final_image, final_image_sz,
1058 				 opts.sec_opts->csk_key_file[
1059 					opts.sec_opts->csk_index],
1060 				 sec_ext->image_sign) != 0) {
1061 		fprintf(stderr, "Failed to sign image!\n");
1062 		return -1;
1063 	}
1064 	/* Check that the image signature is correct */
1065 	if (verify_rsa_signature(sec_ext->csk_keys[opts.sec_opts->csk_index],
1066 				 MAX_RSA_DER_BYTE_LEN,
1067 				 final_image, final_image_sz,
1068 				 opts.sec_opts->csk_key_file[
1069 					 opts.sec_opts->csk_index],
1070 				 sec_ext->image_sign) != 0) {
1071 		fprintf(stderr, "Failed to verify image signature!\n");
1072 		return -1;
1073 	}
1074 
1075 	/* Sign the headers and all the extensions block
1076 	 * when the header signature field is empty
1077 	 */
1078 	if (create_rsa_signature(&opts.sec_opts->csk_pk[
1079 					 opts.sec_opts->csk_index],
1080 				 prolog_buf, prolog_size,
1081 				 opts.sec_opts->csk_key_file[
1082 					 opts.sec_opts->csk_index],
1083 				 hdr_sign) != 0) {
1084 		fprintf(stderr, "Failed to sign header!\n");
1085 		return -1;
1086 	}
1087 	/* Check that the header signature is correct */
1088 	if (verify_rsa_signature(sec_ext->csk_keys[opts.sec_opts->csk_index],
1089 				 MAX_RSA_DER_BYTE_LEN,
1090 				 prolog_buf, prolog_size,
1091 				 opts.sec_opts->csk_key_file[
1092 					 opts.sec_opts->csk_index],
1093 				 hdr_sign) != 0) {
1094 		fprintf(stderr, "Failed to verify header signature!\n");
1095 		return -1;
1096 	}
1097 
1098 	/* Finally, copy the header signature into the trusted boot extension */
1099 	memcpy(sec_ext->header_sign, hdr_sign, RSA_SIGN_BYTE_LEN);
1100 
1101 	return 0;
1102 }
1103 
1104 #endif /* CONFIG_MVEBU_SECURE_BOOT */
1105 
1106 
1107 #define FMT_HEX		0
1108 #define FMT_DEC		1
1109 #define FMT_BIN		2
1110 #define FMT_NONE	3
1111 
do_print_field(unsigned int value,char * name,int start,int size,int format)1112 void do_print_field(unsigned int value, char *name,
1113 		    int start, int size, int format)
1114 {
1115 	fprintf(stdout, "[0x%05x : 0x%05x]  %-26s",
1116 		start, start + size - 1, name);
1117 
1118 	switch (format) {
1119 	case FMT_HEX:
1120 		printf("0x%x\n", value);
1121 		break;
1122 	case FMT_DEC:
1123 		printf("%d\n", value);
1124 		break;
1125 	default:
1126 		printf("\n");
1127 		break;
1128 	}
1129 }
1130 
1131 #define print_field(st, type, field, hex, base) \
1132 			do_print_field((int)st->field, #field, \
1133 			base + offsetof(type, field), sizeof(st->field), hex)
1134 
print_header(uint8_t * buf,int base)1135 int print_header(uint8_t *buf, int base)
1136 {
1137 	header_t *main_hdr;
1138 
1139 	main_hdr = (header_t *)buf;
1140 
1141 	fprintf(stdout, "########### Header ##############\n");
1142 	print_field(main_hdr, header_t, magic, FMT_HEX, base);
1143 	print_field(main_hdr, header_t, prolog_size, FMT_DEC, base);
1144 	print_field(main_hdr, header_t, prolog_checksum, FMT_HEX, base);
1145 	print_field(main_hdr, header_t, boot_image_size, FMT_DEC, base);
1146 	print_field(main_hdr, header_t, boot_image_checksum, FMT_HEX, base);
1147 	print_field(main_hdr, header_t, rsrvd0, FMT_HEX, base);
1148 	print_field(main_hdr, header_t, load_addr, FMT_HEX, base);
1149 	print_field(main_hdr, header_t, exec_addr, FMT_HEX, base);
1150 	print_field(main_hdr, header_t, uart_cfg, FMT_HEX, base);
1151 	print_field(main_hdr, header_t, baudrate, FMT_HEX, base);
1152 	print_field(main_hdr, header_t, ext_count, FMT_DEC, base);
1153 	print_field(main_hdr, header_t, aux_flags, FMT_HEX, base);
1154 	print_field(main_hdr, header_t, io_arg_0, FMT_HEX, base);
1155 	print_field(main_hdr, header_t, io_arg_1, FMT_HEX, base);
1156 	print_field(main_hdr, header_t, io_arg_2, FMT_HEX, base);
1157 	print_field(main_hdr, header_t, io_arg_3, FMT_HEX, base);
1158 	print_field(main_hdr, header_t, rsrvd1, FMT_HEX, base);
1159 	print_field(main_hdr, header_t, rsrvd2, FMT_HEX, base);
1160 	print_field(main_hdr, header_t, rsrvd3, FMT_HEX, base);
1161 
1162 	return sizeof(header_t);
1163 }
1164 
print_ext_hdr(ext_header_t * ext_hdr,int base)1165 int print_ext_hdr(ext_header_t *ext_hdr, int base)
1166 {
1167 	print_field(ext_hdr, ext_header_t, type, FMT_HEX, base);
1168 	print_field(ext_hdr, ext_header_t, offset, FMT_HEX, base);
1169 	print_field(ext_hdr, ext_header_t, reserved, FMT_HEX, base);
1170 	print_field(ext_hdr, ext_header_t, size, FMT_DEC, base);
1171 
1172 	return base + sizeof(ext_header_t);
1173 }
1174 
print_sec_ext(ext_header_t * ext_hdr,int base)1175 void print_sec_ext(ext_header_t *ext_hdr, int base)
1176 {
1177 	sec_entry_t	*sec_entry;
1178 	uint32_t	new_base;
1179 
1180 	fprintf(stdout, "\n########### Secure extension ###########\n");
1181 
1182 	new_base = print_ext_hdr(ext_hdr, base);
1183 
1184 	sec_entry = (sec_entry_t *)(ext_hdr + 1);
1185 
1186 	do_print_field(0, "KAK key", new_base, MAX_RSA_DER_BYTE_LEN, FMT_NONE);
1187 	new_base += MAX_RSA_DER_BYTE_LEN;
1188 	print_field(sec_entry, sec_entry_t, jtag_delay, FMT_DEC, base);
1189 	print_field(sec_entry, sec_entry_t, box_id, FMT_HEX, base);
1190 	print_field(sec_entry, sec_entry_t, flash_id, FMT_HEX, base);
1191 	print_field(sec_entry, sec_entry_t, encrypt_en, FMT_DEC, base);
1192 	print_field(sec_entry, sec_entry_t, efuse_dis, FMT_DEC, base);
1193 	new_base += 6 * sizeof(uint32_t);
1194 	do_print_field(0, "header signature",
1195 		       new_base, RSA_SIGN_BYTE_LEN, FMT_NONE);
1196 	new_base += RSA_SIGN_BYTE_LEN;
1197 	do_print_field(0, "image signature",
1198 		       new_base, RSA_SIGN_BYTE_LEN, FMT_NONE);
1199 	new_base += RSA_SIGN_BYTE_LEN;
1200 	do_print_field(0, "CSK keys", new_base,
1201 		       CSK_ARR_SZ * MAX_RSA_DER_BYTE_LEN, FMT_NONE);
1202 	new_base += CSK_ARR_SZ * MAX_RSA_DER_BYTE_LEN;
1203 	do_print_field(0, "CSK block signature",
1204 		       new_base, RSA_SIGN_BYTE_LEN, FMT_NONE);
1205 	new_base += RSA_SIGN_BYTE_LEN;
1206 	do_print_field(0, "control", new_base,
1207 		       CP_CTRL_EL_ARRAY_SZ * 2, FMT_NONE);
1208 
1209 }
1210 
print_bin_ext(ext_header_t * ext_hdr,int base)1211 void print_bin_ext(ext_header_t *ext_hdr, int base)
1212 {
1213 	fprintf(stdout, "\n########### Binary extension ###########\n");
1214 	base = print_ext_hdr(ext_hdr, base);
1215 	do_print_field(0, "binary image", base, ext_hdr->size, FMT_NONE);
1216 }
1217 
print_extension(void * buf,int base,int count,int ext_size)1218 int print_extension(void *buf, int base, int count, int ext_size)
1219 {
1220 	ext_header_t *ext_hdr = buf;
1221 	int pad = ext_size;
1222 	int curr_size;
1223 
1224 	while (count--) {
1225 		if (ext_hdr->type == EXT_TYPE_BINARY)
1226 			print_bin_ext(ext_hdr, base);
1227 		else if (ext_hdr->type == EXT_TYPE_SECURITY)
1228 			print_sec_ext(ext_hdr, base);
1229 
1230 		curr_size = sizeof(ext_header_t) + ext_hdr->size;
1231 		base += curr_size;
1232 		pad  -= curr_size;
1233 		ext_hdr = (ext_header_t *)((uintptr_t)ext_hdr + curr_size);
1234 	}
1235 
1236 	if (pad)
1237 		do_print_field(0, "padding", base, pad, FMT_NONE);
1238 
1239 	return ext_size;
1240 }
1241 
parse_image(uint8_t * buf,int size)1242 int parse_image(uint8_t *buf, int size)
1243 {
1244 	int base = 0;
1245 	int ret = 1;
1246 	header_t *main_hdr;
1247 	uint32_t checksum, prolog_checksum;
1248 
1249 
1250 	fprintf(stdout,
1251 		"################### Prolog Start ######################\n\n");
1252 	main_hdr = (header_t *)buf;
1253 	base += print_header(buf, base);
1254 
1255 	if (main_hdr->ext_count)
1256 		base += print_extension(buf + base, base,
1257 					main_hdr->ext_count,
1258 					main_hdr->prolog_size -
1259 					sizeof(header_t));
1260 
1261 	if (base < main_hdr->prolog_size) {
1262 		fprintf(stdout, "\n########### Padding ##############\n");
1263 		do_print_field(0, "prolog padding",
1264 			       base, main_hdr->prolog_size - base, FMT_HEX);
1265 		base = main_hdr->prolog_size;
1266 	}
1267 	fprintf(stdout,
1268 		"\n################### Prolog End ######################\n");
1269 
1270 	fprintf(stdout,
1271 		"\n################### Boot image ######################\n");
1272 
1273 	do_print_field(0, "boot image", base, size - base - 4, FMT_NONE);
1274 
1275 	fprintf(stdout,
1276 		"################### Image end ########################\n");
1277 
1278 	/* Check sanity for certain values */
1279 	printf("\nChecking values:\n");
1280 
1281 	if (main_hdr->magic == MAIN_HDR_MAGIC) {
1282 		fprintf(stdout, "Headers magic:    OK!\n");
1283 	} else {
1284 		fprintf(stderr,
1285 			"\n****** ERROR: HEADER MAGIC 0x%08x != 0x%08x\n",
1286 			main_hdr->magic, MAIN_HDR_MAGIC);
1287 		goto error;
1288 	}
1289 
1290 	/* headers checksum */
1291 	/* clear the checksum field in header to calculate checksum */
1292 	prolog_checksum = main_hdr->prolog_checksum;
1293 	main_hdr->prolog_checksum = 0;
1294 	checksum = checksum32((uint32_t *)buf, main_hdr->prolog_size);
1295 
1296 	if (checksum == prolog_checksum) {
1297 		fprintf(stdout, "Headers checksum: OK!\n");
1298 	} else {
1299 		fprintf(stderr,
1300 			"\n***** ERROR: BAD HEADER CHECKSUM 0x%08x != 0x%08x\n",
1301 			checksum, prolog_checksum);
1302 		goto error;
1303 	}
1304 
1305 	/* boot image checksum */
1306 	checksum = checksum32((uint32_t *)(buf + main_hdr->prolog_size),
1307 			      main_hdr->boot_image_size);
1308 	if (checksum == main_hdr->boot_image_checksum) {
1309 		fprintf(stdout, "Image checksum:   OK!\n");
1310 	} else {
1311 		fprintf(stderr,
1312 			"\n****** ERROR: BAD IMAGE CHECKSUM 0x%08x != 0x%08x\n",
1313 			checksum, main_hdr->boot_image_checksum);
1314 		goto error;
1315 	}
1316 
1317 #ifdef CONFIG_MVEBU_SECURE_BOOT
1318 	/* RSA signatures */
1319 	if (main_hdr->ext_count) {
1320 		uint8_t		ext_num = main_hdr->ext_count;
1321 		ext_header_t	*ext_hdr = (ext_header_t *)(main_hdr + 1);
1322 		unsigned char	hash[32];
1323 		int		i;
1324 
1325 		while (ext_num--) {
1326 			if (ext_hdr->type == EXT_TYPE_SECURITY) {
1327 				sec_entry_t  *sec_entry =
1328 						(sec_entry_t *)(ext_hdr + 1);
1329 
1330 				ret = verify_secure_header_signatures(
1331 							main_hdr, sec_entry);
1332 				if (ret != 0) {
1333 					fprintf(stderr,
1334 						"\n****** FAILED TO VERIFY ");
1335 					fprintf(stderr,
1336 						"RSA SIGNATURES ********\n");
1337 					goto error;
1338 				}
1339 
1340 				mbedtls_sha256_ret(sec_entry->kak_key,
1341 					       MAX_RSA_DER_BYTE_LEN, hash, 0);
1342 				fprintf(stdout,
1343 					">>>>>>>>>> KAK KEY HASH >>>>>>>>>>\n");
1344 				fprintf(stdout, "SHA256: ");
1345 				for (i = 0; i < 32; i++)
1346 					fprintf(stdout, "%02X", hash[i]);
1347 
1348 				fprintf(stdout,
1349 					"\n<<<<<<<<< KAK KEY HASH <<<<<<<<<\n");
1350 
1351 				break;
1352 			}
1353 			ext_hdr =
1354 				(ext_header_t *)((uint8_t *)(ext_hdr + 1) +
1355 				 ext_hdr->size);
1356 		}
1357 	}
1358 #endif
1359 
1360 	ret = 0;
1361 error:
1362 	return ret;
1363 }
1364 
format_bin_ext(char * filename,FILE * out_fd)1365 int format_bin_ext(char *filename, FILE *out_fd)
1366 {
1367 	ext_header_t header;
1368 	FILE *in_fd;
1369 	int size, written;
1370 	int aligned_size, pad_bytes;
1371 	char c;
1372 
1373 	in_fd = fopen(filename, "rb");
1374 	if (in_fd == NULL) {
1375 		fprintf(stderr, "failed to open bin extension file %s\n",
1376 			filename);
1377 		return 1;
1378 	}
1379 
1380 	size = get_file_size(filename);
1381 	if (size <= 0) {
1382 		fprintf(stderr, "bin extension file size is bad\n");
1383 		return 1;
1384 	}
1385 
1386 	/* Align extension size to 8 bytes */
1387 	aligned_size = (size + 7) & (~7);
1388 	pad_bytes    = aligned_size - size;
1389 
1390 	header.type = EXT_TYPE_BINARY;
1391 	header.offset = 0;
1392 	header.size = aligned_size;
1393 	header.reserved = 0;
1394 
1395 	/* Write header */
1396 	written = fwrite(&header, sizeof(ext_header_t), 1, out_fd);
1397 	if (written != 1) {
1398 		fprintf(stderr, "failed writing header to extension file\n");
1399 		return 1;
1400 	}
1401 
1402 	/* Write image */
1403 	while (size--) {
1404 		c = getc(in_fd);
1405 		fputc(c, out_fd);
1406 	}
1407 
1408 	while (pad_bytes--)
1409 		fputc(0, out_fd);
1410 
1411 	fclose(in_fd);
1412 
1413 	return 0;
1414 }
1415 
1416 /* ****************************************
1417  *
1418  * Write all extensions (binary, secure
1419  * extensions) to file
1420  *
1421  * ****************************************/
1422 
format_extensions(char * ext_filename)1423 int format_extensions(char *ext_filename)
1424 {
1425 	FILE *out_fd;
1426 	int ret = 0;
1427 
1428 	out_fd = fopen(ext_filename, "wb");
1429 	if (out_fd == NULL) {
1430 		fprintf(stderr, "failed to open extension output file %s",
1431 			ext_filename);
1432 		return 1;
1433 	}
1434 
1435 	if (strncmp(opts.bin_ext_file, "NA", MAX_FILENAME)) {
1436 		if (format_bin_ext(opts.bin_ext_file, out_fd)) {
1437 			ret = 1;
1438 			goto error;
1439 		}
1440 	}
1441 #ifdef CONFIG_MVEBU_SECURE_BOOT
1442 	if (strncmp(opts.sec_cfg_file, "NA", MAX_FILENAME)) {
1443 		if (format_sec_ext(opts.sec_cfg_file, out_fd)) {
1444 			ret = 1;
1445 			goto error;
1446 		}
1447 	}
1448 #endif
1449 
1450 error:
1451 	fflush(out_fd);
1452 	fclose(out_fd);
1453 	return ret;
1454 }
1455 
update_uart(header_t * header)1456 void update_uart(header_t *header)
1457 {
1458 	header->uart_cfg = 0;
1459 	header->baudrate = 0;
1460 
1461 	if (opts.disable_print)
1462 		uart_set_mode(header->uart_cfg, UART_MODE_DISABLE);
1463 
1464 	if (opts.baudrate)
1465 		header->baudrate = (opts.baudrate / 1200);
1466 }
1467 
1468 /* ****************************************
1469  *
1470  * Write the image prolog, i.e.
1471  * main header and extensions, to file
1472  *
1473  * ****************************************/
1474 
write_prolog(int ext_cnt,char * ext_filename,uint8_t * image_buf,int image_size,FILE * out_fd)1475 int write_prolog(int ext_cnt, char *ext_filename,
1476 		 uint8_t *image_buf, int image_size, FILE *out_fd)
1477 {
1478 	header_t		*header;
1479 	int main_hdr_size = sizeof(header_t);
1480 	int prolog_size = main_hdr_size;
1481 	FILE *ext_fd;
1482 	char *buf;
1483 	int written, read;
1484 	int ret = 1;
1485 
1486 
1487 	if (ext_cnt)
1488 		prolog_size +=  get_file_size(ext_filename);
1489 
1490 	prolog_size = ((prolog_size + PROLOG_ALIGNMENT) &
1491 		     (~(PROLOG_ALIGNMENT-1)));
1492 
1493 	/* Allocate a zeroed buffer to zero the padding bytes */
1494 	buf = calloc(prolog_size, 1);
1495 	if (buf == NULL) {
1496 		fprintf(stderr, "Error: failed allocating checksum buffer\n");
1497 		return 1;
1498 	}
1499 
1500 	header = (header_t *)buf;
1501 	header->magic       = MAIN_HDR_MAGIC;
1502 	header->prolog_size = prolog_size;
1503 	header->load_addr   = opts.load_addr;
1504 	header->exec_addr   = opts.exec_addr;
1505 	header->io_arg_0    = opts.nfc_io_args;
1506 	header->ext_count   = ext_cnt;
1507 	header->aux_flags   = 0;
1508 	header->boot_image_size = (image_size + 3) & (~0x3);
1509 	header->boot_image_checksum = checksum32((uint32_t *)image_buf,
1510 						 image_size);
1511 
1512 	update_uart(header);
1513 
1514 	/* Populate buffer with main header and extensions */
1515 	if (ext_cnt) {
1516 		ext_fd = fopen(ext_filename, "rb");
1517 		if (ext_fd == NULL) {
1518 			fprintf(stderr,
1519 				"Error: failed to open extensions file\n");
1520 			goto error;
1521 		}
1522 
1523 		read = fread(&buf[main_hdr_size],
1524 			     get_file_size(ext_filename), 1, ext_fd);
1525 		if (read != 1) {
1526 			fprintf(stderr,
1527 				"Error: failed to open extensions file\n");
1528 			goto error;
1529 		}
1530 
1531 #ifdef CONFIG_MVEBU_SECURE_BOOT
1532 		/* Secure boot mode? */
1533 		if (opts.sec_opts != 0) {
1534 			ret = finalize_secure_ext(header, (uint8_t *)buf,
1535 						  prolog_size, image_buf,
1536 						  image_size);
1537 			if (ret != 0) {
1538 				fprintf(stderr, "Error: failed to handle ");
1539 				fprintf(stderr, "secure extension!\n");
1540 				goto error;
1541 			}
1542 		} /* secure boot mode */
1543 #endif
1544 	}
1545 
1546 	/* Update the total prolog checksum */
1547 	header->prolog_checksum = checksum32((uint32_t *)buf, prolog_size);
1548 
1549 	/* Now spill everything to output file */
1550 	written = fwrite(buf, prolog_size, 1, out_fd);
1551 	if (written != 1) {
1552 		fprintf(stderr,
1553 			"Error: failed to write prolog to output file\n");
1554 		goto error;
1555 	}
1556 
1557 	ret = 0;
1558 
1559 error:
1560 	free(buf);
1561 	return ret;
1562 }
1563 
write_boot_image(uint8_t * buf,uint32_t image_size,FILE * out_fd)1564 int write_boot_image(uint8_t *buf, uint32_t image_size, FILE *out_fd)
1565 {
1566 	int written;
1567 
1568 	written = fwrite(buf, image_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 
main(int argc,char * argv[])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, file_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 	 * Always align the image to 16 byte boundary
1688 	 */
1689 	file_size  = get_file_size(in_file);
1690 	image_size = (file_size + AES_BLOCK_SZ - 1) & ~(AES_BLOCK_SZ - 1);
1691 	image_buf  = calloc(image_size, 1);
1692 	if (image_buf == NULL) {
1693 		fprintf(stderr, "Error: failed allocating input buffer\n");
1694 		return 1;
1695 	}
1696 
1697 	read = fread(image_buf, file_size, 1, in_fd);
1698 	if (read != 1) {
1699 		fprintf(stderr, "Error: failed to read input file\n");
1700 		goto main_exit;
1701 	}
1702 
1703 	/* Parse the input image and leave */
1704 	if (parse) {
1705 		if (opts.key_index >= CSK_ARR_SZ) {
1706 			fprintf(stderr,
1707 				"Wrong key IDX value. Valid values 0 - %d\n",
1708 				CSK_ARR_SZ - 1);
1709 			goto main_exit;
1710 		}
1711 		ret = parse_image(image_buf, image_size);
1712 		goto main_exit;
1713 	}
1714 
1715 	/* Create a blob file from all extensions */
1716 	if (ext_cnt) {
1717 		ret = format_extensions(ext_file);
1718 		if (ret)
1719 			goto main_exit;
1720 	}
1721 
1722 	out_fd = fopen(out_file, "wb");
1723 	if (out_fd == NULL) {
1724 		fprintf(stderr,
1725 			"Error: Failed to open output file %s\n", out_file);
1726 		goto main_exit;
1727 	}
1728 
1729 	ret = write_prolog(ext_cnt, ext_file, image_buf, image_size, out_fd);
1730 	if (ret)
1731 		goto main_exit;
1732 
1733 #ifdef CONFIG_MVEBU_SECURE_BOOT
1734 	if (opts.sec_opts && (opts.sec_opts->encrypted_image != 0) &&
1735 	    (opts.sec_opts->enc_image_sz != 0)) {
1736 		ret = write_boot_image(opts.sec_opts->encrypted_image,
1737 				       opts.sec_opts->enc_image_sz, out_fd);
1738 	} else
1739 #endif
1740 		ret = write_boot_image(image_buf, image_size, out_fd);
1741 	if (ret)
1742 		goto main_exit;
1743 
1744 main_exit:
1745 	if (in_fd)
1746 		fclose(in_fd);
1747 
1748 	if (out_fd)
1749 		fclose(out_fd);
1750 
1751 	if (image_buf)
1752 		free(image_buf);
1753 
1754 	unlink(ext_file);
1755 
1756 #ifdef CONFIG_MVEBU_SECURE_BOOT
1757 	if (opts.sec_opts) {
1758 		if (opts.sec_opts->encrypted_image)
1759 			free(opts.sec_opts->encrypted_image);
1760 		free(opts.sec_opts);
1761 	}
1762 #endif
1763 	exit(ret);
1764 }
1765