1 /*
2  * Copyright 2015 Freescale Semiconductor, Inc.
3  *
4  * SPDX-License-Identifier:	GPL-2.0+
5  */
6 
7 #include <common.h>
8 #include <fsl_validate.h>
9 #include <fsl_secboot_err.h>
10 #include <fsl_sfp.h>
11 #include <fsl_sec.h>
12 #include <command.h>
13 #include <malloc.h>
14 #include <dm/uclass.h>
15 #include <u-boot/rsa-mod-exp.h>
16 #include <hash.h>
17 #include <fsl_secboot_err.h>
18 #ifdef CONFIG_LS102XA
19 #include <asm/arch/immap_ls102xa.h>
20 #endif
21 
22 #define SHA256_BITS	256
23 #define SHA256_BYTES	(256/8)
24 #define SHA256_NIBBLES	(256/4)
25 #define NUM_HEX_CHARS	(sizeof(ulong) * 2)
26 
27 #define CHECK_KEY_LEN(key_len)	(((key_len) == 2 * KEY_SIZE_BYTES / 4) || \
28 				 ((key_len) == 2 * KEY_SIZE_BYTES / 2) || \
29 				 ((key_len) == 2 * KEY_SIZE_BYTES))
30 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
31 /* Global data structure */
32 static struct fsl_secboot_glb glb;
33 #endif
34 
35 /* This array contains DER value for SHA-256 */
36 static const u8 hash_identifier[] = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60,
37 		0x86, 0x48, 0x01, 0x65,	0x03, 0x04, 0x02, 0x01, 0x05, 0x00,
38 		0x04, 0x20
39 		};
40 
41 static u8 hash_val[SHA256_BYTES];
42 
43 #ifdef CONFIG_ESBC_HDR_LS
44 /* New Barker Code for LS ESBC Header */
45 static const u8 barker_code[ESBC_BARKER_LEN] = { 0x12, 0x19, 0x20, 0x01 };
46 #else
47 static const u8 barker_code[ESBC_BARKER_LEN] = { 0x68, 0x39, 0x27, 0x81 };
48 #endif
49 
50 void branch_to_self(void) __attribute__ ((noreturn));
51 
52 /*
53  * This function will put core in infinite loop.
54  * This will be called when the ESBC can not proceed further due
55  * to some unknown errors.
56  */
57 void branch_to_self(void)
58 {
59 	printf("Core is in infinite loop due to errors.\n");
60 self:
61 	goto self;
62 }
63 
64 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
65 static u32 check_ie(struct fsl_secboot_img_priv *img)
66 {
67 	if (img->hdr.ie_flag & IE_FLAG_MASK)
68 		return 1;
69 
70 	return 0;
71 }
72 
73 /* This function returns the CSF Header Address of uboot
74  * For MPC85xx based platforms, the LAW mapping for NOR
75  * flash changes in uboot code. Hence the offset needs
76  * to be calculated and added to the new NOR flash base
77  * address
78  */
79 #if defined(CONFIG_MPC85xx)
80 int get_csf_base_addr(u32 *csf_addr, u32 *flash_base_addr)
81 {
82 	struct ccsr_gur __iomem *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR);
83 	u32 csf_hdr_addr = in_be32(&gur->scratchrw[0]);
84 	u32 csf_flash_offset = csf_hdr_addr & ~(CONFIG_SYS_PBI_FLASH_BASE);
85 	u32 flash_addr, addr;
86 	int found = 0;
87 	int i = 0;
88 
89 	for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
90 		flash_addr = flash_info[i].start[0];
91 		addr = flash_info[i].start[0] + csf_flash_offset;
92 		if (memcmp((u8 *)addr, barker_code, ESBC_BARKER_LEN) == 0) {
93 			debug("Barker found on addr %x\n", addr);
94 			found = 1;
95 			break;
96 		}
97 	}
98 
99 	if (!found)
100 		return -1;
101 
102 	*csf_addr = addr;
103 	*flash_base_addr = flash_addr;
104 
105 	return 0;
106 }
107 #else
108 /* For platforms like LS1020, correct flash address is present in
109  * the header. So the function reqturns flash base address as 0
110  */
111 int get_csf_base_addr(u32 *csf_addr, u32 *flash_base_addr)
112 {
113 	struct ccsr_gur __iomem *gur = (void *)(CONFIG_SYS_FSL_GUTS_ADDR);
114 	u32 csf_hdr_addr = in_be32(&gur->scratchrw[0]);
115 
116 	if (memcmp((u8 *)(uintptr_t)csf_hdr_addr,
117 		   barker_code, ESBC_BARKER_LEN))
118 		return -1;
119 
120 	*csf_addr = csf_hdr_addr;
121 	*flash_base_addr = 0;
122 	return 0;
123 }
124 #endif
125 
126 #if defined(CONFIG_ESBC_HDR_LS)
127 static int get_ie_info_addr(uintptr_t *ie_addr)
128 {
129 	struct ccsr_gur __iomem *gur = (void *)(CONFIG_SYS_FSL_GUTS_ADDR);
130 	/* For LS-CH3, the address of IE Table is
131 	 * stated in Scratch13 and scratch14 of DCFG.
132 	 * Bootrom validates this table while validating uboot.
133 	 * DCFG is LE*/
134 	*ie_addr = in_le32(&gur->scratchrw[SCRATCH_IE_HIGH_ADR - 1]);
135 	*ie_addr = *ie_addr << 32;
136 	*ie_addr |= in_le32(&gur->scratchrw[SCRATCH_IE_LOW_ADR - 1]);
137 	return 0;
138 }
139 #else /* CONFIG_ESBC_HDR_LS */
140 static int get_ie_info_addr(uintptr_t *ie_addr)
141 {
142 	struct fsl_secboot_img_hdr *hdr;
143 	struct fsl_secboot_sg_table *sg_tbl;
144 	u32 flash_base_addr, csf_addr;
145 
146 	if (get_csf_base_addr(&csf_addr, &flash_base_addr))
147 		return -1;
148 
149 	hdr = (struct fsl_secboot_img_hdr *)(uintptr_t)csf_addr;
150 
151 	/* For SoC's with Trust Architecture v1 with corenet bus
152 	 * the sg table field in CSF header has absolute address
153 	 * for sg table in memory. In other Trust Architecture,
154 	 * this field specifies the offset of sg table from the
155 	 * base address of CSF Header
156 	 */
157 #if defined(CONFIG_FSL_TRUST_ARCH_v1) && defined(CONFIG_FSL_CORENET)
158 	sg_tbl = (struct fsl_secboot_sg_table *)
159 		 (((u32)hdr->psgtable & ~(CONFIG_SYS_PBI_FLASH_BASE)) +
160 		  flash_base_addr);
161 #else
162 	sg_tbl = (struct fsl_secboot_sg_table *)(uintptr_t)(csf_addr +
163 						 (u32)hdr->psgtable);
164 #endif
165 
166 	/* IE Key Table is the first entry in the SG Table */
167 #if defined(CONFIG_MPC85xx)
168 	*ie_addr = (uintptr_t)((sg_tbl->src_addr &
169 			~(CONFIG_SYS_PBI_FLASH_BASE)) +
170 			flash_base_addr);
171 #else
172 	*ie_addr = (uintptr_t)sg_tbl->src_addr;
173 #endif
174 
175 	debug("IE Table address is %lx\n", *ie_addr);
176 	return 0;
177 }
178 #endif /* CONFIG_ESBC_HDR_LS */
179 #endif
180 
181 #ifdef CONFIG_KEY_REVOCATION
182 /* This function checks srk_table_flag in header and set/reset srk_flag.*/
183 static u32 check_srk(struct fsl_secboot_img_priv *img)
184 {
185 #ifdef CONFIG_ESBC_HDR_LS
186 	/* In LS, No SRK Flag as SRK is always present if IE not present*/
187 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
188 	return !check_ie(img);
189 #endif
190 	return 1;
191 #else
192 	if (img->hdr.len_kr.srk_table_flag & SRK_FLAG)
193 		return 1;
194 
195 	return 0;
196 #endif
197 }
198 
199 /* This function returns ospr's key_revoc values.*/
200 static u32 get_key_revoc(void)
201 {
202 	struct ccsr_sfp_regs *sfp_regs = (void *)(CONFIG_SYS_SFP_ADDR);
203 	return (sfp_in32(&sfp_regs->ospr) & OSPR_KEY_REVOC_MASK) >>
204 		OSPR_KEY_REVOC_SHIFT;
205 }
206 
207 /* This function checks if selected key is revoked or not.*/
208 static u32 is_key_revoked(u32 keynum, u32 rev_flag)
209 {
210 	if (keynum == UNREVOCABLE_KEY)
211 		return 0;
212 
213 	if ((u32)(1 << (ALIGN_REVOC_KEY - keynum)) & rev_flag)
214 		return 1;
215 
216 	return 0;
217 }
218 
219 /* It read validates srk_table key lengths.*/
220 static u32 read_validate_srk_tbl(struct fsl_secboot_img_priv *img)
221 {
222 	int i = 0;
223 	u32 ret, key_num, key_revoc_flag, size;
224 	struct fsl_secboot_img_hdr *hdr = &img->hdr;
225 	void *esbc = (u8 *)(uintptr_t)img->ehdrloc;
226 
227 	if ((hdr->len_kr.num_srk == 0) ||
228 	    (hdr->len_kr.num_srk > MAX_KEY_ENTRIES))
229 		return ERROR_ESBC_CLIENT_HEADER_INVALID_SRK_NUM_ENTRY;
230 
231 	key_num = hdr->len_kr.srk_sel;
232 	if (key_num == 0 || key_num > hdr->len_kr.num_srk)
233 		return ERROR_ESBC_CLIENT_HEADER_INVALID_KEY_NUM;
234 
235 	/* Get revoc key from sfp */
236 	key_revoc_flag = get_key_revoc();
237 	ret = is_key_revoked(key_num, key_revoc_flag);
238 	if (ret)
239 		return ERROR_ESBC_CLIENT_HEADER_KEY_REVOKED;
240 
241 	size = hdr->len_kr.num_srk * sizeof(struct srk_table);
242 
243 	memcpy(&img->srk_tbl, esbc + hdr->srk_tbl_off, size);
244 
245 	for (i = 0; i < hdr->len_kr.num_srk; i++) {
246 		if (!CHECK_KEY_LEN(img->srk_tbl[i].key_len))
247 			return ERROR_ESBC_CLIENT_HEADER_INV_SRK_ENTRY_KEYLEN;
248 	}
249 
250 	img->key_len = img->srk_tbl[key_num - 1].key_len;
251 
252 	memcpy(&img->img_key, &(img->srk_tbl[key_num - 1].pkey),
253 	       img->key_len);
254 
255 	return 0;
256 }
257 #endif
258 
259 #ifndef CONFIG_ESBC_HDR_LS
260 static u32 read_validate_single_key(struct fsl_secboot_img_priv *img)
261 {
262 	struct fsl_secboot_img_hdr *hdr = &img->hdr;
263 	void *esbc = (u8 *)(uintptr_t)img->ehdrloc;
264 
265 	/* check key length */
266 	if (!CHECK_KEY_LEN(hdr->key_len))
267 		return ERROR_ESBC_CLIENT_HEADER_KEY_LEN;
268 
269 	memcpy(&img->img_key, esbc + hdr->pkey, hdr->key_len);
270 
271 	img->key_len = hdr->key_len;
272 
273 	return 0;
274 }
275 #endif /* CONFIG_ESBC_HDR_LS */
276 
277 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
278 
279 static void install_ie_tbl(uintptr_t ie_tbl_addr,
280 		struct fsl_secboot_img_priv *img)
281 {
282 	/* Copy IE tbl to Global Data */
283 	memcpy(&glb.ie_tbl, (u8 *)ie_tbl_addr, sizeof(struct ie_key_info));
284 	img->ie_addr = (uintptr_t)&glb.ie_tbl;
285 	glb.ie_addr = img->ie_addr;
286 }
287 
288 static u32 read_validate_ie_tbl(struct fsl_secboot_img_priv *img)
289 {
290 	struct fsl_secboot_img_hdr *hdr = &img->hdr;
291 	u32 ie_key_len, ie_revoc_flag, ie_num;
292 	struct ie_key_info *ie_info;
293 
294 	if (!img->ie_addr) {
295 		if (get_ie_info_addr(&img->ie_addr))
296 			return ERROR_IE_TABLE_NOT_FOUND;
297 		else
298 			install_ie_tbl(img->ie_addr, img);
299 		}
300 
301 	ie_info = (struct ie_key_info *)(uintptr_t)img->ie_addr;
302 	if (ie_info->num_keys == 0 || ie_info->num_keys > 32)
303 		return ERROR_ESBC_CLIENT_HEADER_INVALID_IE_NUM_ENTRY;
304 
305 	ie_num = hdr->ie_key_sel;
306 	if (ie_num == 0 || ie_num > ie_info->num_keys)
307 		return ERROR_ESBC_CLIENT_HEADER_INVALID_IE_KEY_NUM;
308 
309 	ie_revoc_flag = ie_info->key_revok;
310 	if ((u32)(1 << (ie_num - 1)) & ie_revoc_flag)
311 		return ERROR_ESBC_CLIENT_HEADER_IE_KEY_REVOKED;
312 
313 	ie_key_len = ie_info->ie_key_tbl[ie_num - 1].key_len;
314 
315 	if (!CHECK_KEY_LEN(ie_key_len))
316 		return ERROR_ESBC_CLIENT_HEADER_INV_IE_ENTRY_KEYLEN;
317 
318 	memcpy(&img->img_key, &(ie_info->ie_key_tbl[ie_num - 1].pkey),
319 	       ie_key_len);
320 
321 	img->key_len = ie_key_len;
322 	return 0;
323 }
324 #endif
325 
326 
327 /* This function return length of public key.*/
328 static inline u32 get_key_len(struct fsl_secboot_img_priv *img)
329 {
330 	return img->key_len;
331 }
332 
333 /*
334  * Handles the ESBC uboot client header verification failure.
335  * This  function  handles all the errors which might occur in the
336  * parsing and checking of ESBC uboot client header. It will also
337  * set the error bits in the SEC_MON.
338  */
339 static void fsl_secboot_header_verification_failure(void)
340 {
341 	struct ccsr_sfp_regs *sfp_regs = (void *)(CONFIG_SYS_SFP_ADDR);
342 
343 	/* 29th bit of OSPR is ITS */
344 	u32 its = sfp_in32(&sfp_regs->ospr) >> 2;
345 
346 	if (its == 1)
347 		set_sec_mon_state(HPSR_SSM_ST_SOFT_FAIL);
348 	else
349 		set_sec_mon_state(HPSR_SSM_ST_NON_SECURE);
350 
351 	printf("Generating reset request\n");
352 	do_reset(NULL, 0, 0, NULL);
353 	/* If reset doesn't coocur, halt execution */
354 	do_esbc_halt(NULL, 0, 0, NULL);
355 }
356 
357 /*
358  * Handles the ESBC uboot client image verification failure.
359  * This  function  handles all the errors which might occur in the
360  * public key hash comparison and signature verification of
361  * ESBC uboot client image. It will also
362  * set the error bits in the SEC_MON.
363  */
364 static void fsl_secboot_image_verification_failure(void)
365 {
366 	struct ccsr_sfp_regs *sfp_regs = (void *)(CONFIG_SYS_SFP_ADDR);
367 
368 	u32 its = (sfp_in32(&sfp_regs->ospr) & ITS_MASK) >> ITS_BIT;
369 
370 	if (its == 1) {
371 		set_sec_mon_state(HPSR_SSM_ST_SOFT_FAIL);
372 
373 		printf("Generating reset request\n");
374 		do_reset(NULL, 0, 0, NULL);
375 		/* If reset doesn't coocur, halt execution */
376 		do_esbc_halt(NULL, 0, 0, NULL);
377 
378 	} else {
379 		set_sec_mon_state(HPSR_SSM_ST_NON_SECURE);
380 	}
381 }
382 
383 static void fsl_secboot_bootscript_parse_failure(void)
384 {
385 	fsl_secboot_header_verification_failure();
386 }
387 
388 /*
389  * Handles the errors in esbc boot.
390  * This  function  handles all the errors which might occur in the
391  * esbc boot phase. It will call the appropriate api to log the
392  * errors and set the error bits in the SEC_MON.
393  */
394 void fsl_secboot_handle_error(int error)
395 {
396 	const struct fsl_secboot_errcode *e;
397 
398 	for (e = fsl_secboot_errcodes; e->errcode != ERROR_ESBC_CLIENT_MAX;
399 		e++) {
400 		if (e->errcode == error)
401 			printf("ERROR :: %x :: %s\n", error, e->name);
402 	}
403 
404 	/* If Boot Mode is secure, transition the SNVS state and issue
405 	 * reset based on type of failure and ITS setting.
406 	 * If Boot mode is non-secure, return from this function.
407 	 */
408 	if (fsl_check_boot_mode_secure() == 0)
409 		return;
410 
411 	switch (error) {
412 	case ERROR_ESBC_CLIENT_HEADER_BARKER:
413 	case ERROR_ESBC_CLIENT_HEADER_IMG_SIZE:
414 	case ERROR_ESBC_CLIENT_HEADER_KEY_LEN:
415 	case ERROR_ESBC_CLIENT_HEADER_SIG_LEN:
416 	case ERROR_ESBC_CLIENT_HEADER_KEY_LEN_NOT_TWICE_SIG_LEN:
417 	case ERROR_ESBC_CLIENT_HEADER_KEY_MOD_1:
418 	case ERROR_ESBC_CLIENT_HEADER_KEY_MOD_2:
419 	case ERROR_ESBC_CLIENT_HEADER_SIG_KEY_MOD:
420 	case ERROR_ESBC_CLIENT_HEADER_SG_ESBC_EP:
421 	case ERROR_ESBC_CLIENT_HEADER_SG_ENTIRES_BAD:
422 	case ERROR_KEY_TABLE_NOT_FOUND:
423 #ifdef CONFIG_KEY_REVOCATION
424 	case ERROR_ESBC_CLIENT_HEADER_KEY_REVOKED:
425 	case ERROR_ESBC_CLIENT_HEADER_INVALID_SRK_NUM_ENTRY:
426 	case ERROR_ESBC_CLIENT_HEADER_INVALID_KEY_NUM:
427 	case ERROR_ESBC_CLIENT_HEADER_INV_SRK_ENTRY_KEYLEN:
428 #endif
429 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
430 	/*@fallthrough@*/
431 	case ERROR_ESBC_CLIENT_HEADER_IE_KEY_REVOKED:
432 	case ERROR_ESBC_CLIENT_HEADER_INVALID_IE_NUM_ENTRY:
433 	case ERROR_ESBC_CLIENT_HEADER_INVALID_IE_KEY_NUM:
434 	case ERROR_ESBC_CLIENT_HEADER_INV_IE_ENTRY_KEYLEN:
435 	case ERROR_IE_TABLE_NOT_FOUND:
436 #endif
437 		fsl_secboot_header_verification_failure();
438 		break;
439 	case ERROR_ESBC_SEC_RESET:
440 	case ERROR_ESBC_SEC_DEQ:
441 	case ERROR_ESBC_SEC_ENQ:
442 	case ERROR_ESBC_SEC_DEQ_TO:
443 	case ERROR_ESBC_SEC_JOBQ_STATUS:
444 	case ERROR_ESBC_CLIENT_HASH_COMPARE_KEY:
445 	case ERROR_ESBC_CLIENT_HASH_COMPARE_EM:
446 		fsl_secboot_image_verification_failure();
447 		break;
448 	case ERROR_ESBC_MISSING_BOOTM:
449 		fsl_secboot_bootscript_parse_failure();
450 		break;
451 	case ERROR_ESBC_WRONG_CMD:
452 	default:
453 		branch_to_self();
454 		break;
455 	}
456 }
457 
458 static void fsl_secblk_handle_error(int error)
459 {
460 	switch (error) {
461 	case ERROR_ESBC_SEC_ENQ:
462 		fsl_secboot_handle_error(ERROR_ESBC_SEC_ENQ);
463 		break;
464 	case ERROR_ESBC_SEC_DEQ:
465 		fsl_secboot_handle_error(ERROR_ESBC_SEC_DEQ);
466 		break;
467 	case ERROR_ESBC_SEC_DEQ_TO:
468 		fsl_secboot_handle_error(ERROR_ESBC_SEC_DEQ_TO);
469 		break;
470 	default:
471 		printf("Job Queue Output status %x\n", error);
472 		fsl_secboot_handle_error(ERROR_ESBC_SEC_JOBQ_STATUS);
473 		break;
474 	}
475 }
476 
477 /*
478  * Calculate hash of key obtained via offset present in ESBC uboot
479  * client hdr. This function calculates the hash of key which is obtained
480  * through offset present in ESBC uboot client header.
481  */
482 static int calc_img_key_hash(struct fsl_secboot_img_priv *img)
483 {
484 	struct hash_algo *algo;
485 	void *ctx;
486 	int i, srk = 0;
487 	int ret = 0;
488 	const char *algo_name = "sha256";
489 
490 	/* Calculate hash of the esbc key */
491 	ret = hash_progressive_lookup_algo(algo_name, &algo);
492 	if (ret)
493 		return ret;
494 
495 	ret = algo->hash_init(algo, &ctx);
496 	if (ret)
497 		return ret;
498 
499 	/* Update hash for ESBC key */
500 #ifdef CONFIG_KEY_REVOCATION
501 	if (check_srk(img)) {
502 		ret = algo->hash_update(algo, ctx,
503 		      (u8 *)(uintptr_t)(img->ehdrloc + img->hdr.srk_tbl_off),
504 		      img->hdr.len_kr.num_srk * sizeof(struct srk_table), 1);
505 		srk = 1;
506 	}
507 #endif
508 	if (!srk)
509 		ret = algo->hash_update(algo, ctx,
510 			img->img_key, img->key_len, 1);
511 	if (ret)
512 		return ret;
513 
514 	/* Copy hash at destination buffer */
515 	ret = algo->hash_finish(algo, ctx, hash_val, algo->digest_size);
516 	if (ret)
517 		return ret;
518 
519 	for (i = 0; i < SHA256_BYTES; i++)
520 		img->img_key_hash[i] = hash_val[i];
521 
522 	return 0;
523 }
524 
525 /*
526  * Calculate hash of ESBC hdr and ESBC. This function calculates the
527  * single hash of ESBC header and ESBC image. If SG flag is on, all
528  * SG entries are also hashed alongwith the complete SG table.
529  */
530 static int calc_esbchdr_esbc_hash(struct fsl_secboot_img_priv *img)
531 {
532 	struct hash_algo *algo;
533 	void *ctx;
534 	int ret = 0;
535 	int key_hash = 0;
536 	const char *algo_name = "sha256";
537 
538 	/* Calculate the hash of the ESBC */
539 	ret = hash_progressive_lookup_algo(algo_name, &algo);
540 	if (ret)
541 		return ret;
542 
543 	ret = algo->hash_init(algo, &ctx);
544 	/* Copy hash at destination buffer */
545 	if (ret)
546 		return ret;
547 
548 	/* Update hash for CSF Header */
549 	ret = algo->hash_update(algo, ctx,
550 		(u8 *)&img->hdr, sizeof(struct fsl_secboot_img_hdr), 0);
551 	if (ret)
552 		return ret;
553 
554 	/* Update the hash with that of srk table if srk flag is 1
555 	 * If IE Table is selected, key is not added in the hash
556 	 * If neither srk table nor IE key table available, add key
557 	 * from header in the hash calculation
558 	 */
559 #ifdef CONFIG_KEY_REVOCATION
560 	if (check_srk(img)) {
561 		ret = algo->hash_update(algo, ctx,
562 		      (u8 *)(uintptr_t)(img->ehdrloc + img->hdr.srk_tbl_off),
563 		      img->hdr.len_kr.num_srk * sizeof(struct srk_table), 0);
564 		key_hash = 1;
565 	}
566 #endif
567 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
568 	if (!key_hash && check_ie(img))
569 		key_hash = 1;
570 #endif
571 #ifndef CONFIG_ESBC_HDR_LS
572 /* No single key support in LS ESBC header */
573 	if (!key_hash) {
574 		ret = algo->hash_update(algo, ctx,
575 			img->img_key, img->hdr.key_len, 0);
576 		key_hash = 1;
577 	}
578 #endif
579 	if (ret)
580 		return ret;
581 	if (!key_hash)
582 		return ERROR_KEY_TABLE_NOT_FOUND;
583 
584 	/* Update hash for actual Image */
585 	ret = algo->hash_update(algo, ctx,
586 		(u8 *)(*(img->img_addr_ptr)), img->img_size, 1);
587 	if (ret)
588 		return ret;
589 
590 	/* Copy hash at destination buffer */
591 	ret = algo->hash_finish(algo, ctx, hash_val, algo->digest_size);
592 	if (ret)
593 		return ret;
594 
595 	return 0;
596 }
597 
598 /*
599  * Construct encoded hash EM' wrt PKCSv1.5. This function calculates the
600  * pointers for padding, DER value and hash. And finally, constructs EM'
601  * which includes hash of complete CSF header and ESBC image. If SG flag
602  * is on, hash of SG table and entries is also included.
603  */
604 static void construct_img_encoded_hash_second(struct fsl_secboot_img_priv *img)
605 {
606 	/*
607 	 * RSA PKCSv1.5 encoding format for encoded message is below
608 	 * EM = 0x0 || 0x1 || PS || 0x0 || DER || Hash
609 	 * PS is Padding String
610 	 * DER is DER value for SHA-256
611 	 * Hash is SHA-256 hash
612 	 * *********************************************************
613 	 * representative points to first byte of EM initially and is
614 	 * filled with 0x0
615 	 * representative is incremented by 1 and second byte is filled
616 	 * with 0x1
617 	 * padding points to third byte of EM
618 	 * digest points to full length of EM - 32 bytes
619 	 * hash_id (DER value) points to 19 bytes before pDigest
620 	 * separator is one byte which separates padding and DER
621 	 */
622 
623 	size_t len;
624 	u8 *representative;
625 	u8 *padding, *digest;
626 	u8 *hash_id, *separator;
627 	int i;
628 
629 	len = (get_key_len(img) / 2) - 1;
630 	representative = img->img_encoded_hash_second;
631 	representative[0] = 0;
632 	representative[1] = 1;  /* block type 1 */
633 
634 	padding = &representative[2];
635 	digest = &representative[1] + len - 32;
636 	hash_id = digest - sizeof(hash_identifier);
637 	separator = hash_id - 1;
638 
639 	/* fill padding area pointed by padding with 0xff */
640 	memset(padding, 0xff, separator - padding);
641 
642 	/* fill byte pointed by separator */
643 	*separator = 0;
644 
645 	/* fill SHA-256 DER value  pointed by HashId */
646 	memcpy(hash_id, hash_identifier, sizeof(hash_identifier));
647 
648 	/* fill hash pointed by Digest */
649 	for (i = 0; i < SHA256_BYTES; i++)
650 		digest[i] = hash_val[i];
651 }
652 
653 /*
654  * Reads and validates the ESBC client header.
655  * This function reads key and signature from the ESBC client header.
656  * If Scatter/Gather flag is on, lengths and offsets of images
657  * present as SG entries are also read. This function also checks
658  * whether the header is valid or not.
659  */
660 static int read_validate_esbc_client_header(struct fsl_secboot_img_priv *img)
661 {
662 	struct fsl_secboot_img_hdr *hdr = &img->hdr;
663 	void *esbc = (u8 *)(uintptr_t)img->ehdrloc;
664 	u8 *k, *s;
665 	u32 ret = 0;
666 
667 	int  key_found = 0;
668 
669 	/* check barker code */
670 	if (memcmp(hdr->barker, barker_code, ESBC_BARKER_LEN))
671 		return ERROR_ESBC_CLIENT_HEADER_BARKER;
672 
673 	/* If Image Address is not passed as argument to function,
674 	 * then Address and Size must be read from the Header.
675 	 */
676 	if (*(img->img_addr_ptr) == 0) {
677 	#ifdef CONFIG_ESBC_ADDR_64BIT
678 		*(img->img_addr_ptr) = hdr->pimg64;
679 	#else
680 		*(img->img_addr_ptr) = hdr->pimg;
681 	#endif
682 	}
683 
684 	if (!hdr->img_size)
685 		return ERROR_ESBC_CLIENT_HEADER_IMG_SIZE;
686 
687 	img->img_size = hdr->img_size;
688 
689 	/* Key checking*/
690 #ifdef CONFIG_KEY_REVOCATION
691 	if (check_srk(img)) {
692 		ret = read_validate_srk_tbl(img);
693 		if (ret != 0)
694 			return ret;
695 		key_found = 1;
696 	}
697 #endif
698 
699 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
700 	if (!key_found && check_ie(img)) {
701 		ret = read_validate_ie_tbl(img);
702 		if (ret != 0)
703 			return ret;
704 		key_found = 1;
705 	}
706 #endif
707 #ifndef CONFIG_ESBC_HDR_LS
708 /* Single Key Feature not available in LS ESBC Header */
709 	if (key_found == 0) {
710 		ret = read_validate_single_key(img);
711 		if (ret != 0)
712 			return ret;
713 		key_found = 1;
714 	}
715 #endif
716 	if (!key_found)
717 		return ERROR_KEY_TABLE_NOT_FOUND;
718 
719 	/* check signaure */
720 	if (get_key_len(img) == 2 * hdr->sign_len) {
721 		/* check signature length */
722 		if (!((hdr->sign_len == KEY_SIZE_BYTES / 4) ||
723 		      (hdr->sign_len == KEY_SIZE_BYTES / 2) ||
724 		      (hdr->sign_len == KEY_SIZE_BYTES)))
725 			return ERROR_ESBC_CLIENT_HEADER_SIG_LEN;
726 	} else {
727 		return ERROR_ESBC_CLIENT_HEADER_KEY_LEN_NOT_TWICE_SIG_LEN;
728 	}
729 
730 	memcpy(&img->img_sign, esbc + hdr->psign, hdr->sign_len);
731 /* No SG support in LS-CH3 */
732 #ifndef CONFIG_ESBC_HDR_LS
733 	/* No SG support */
734 	if (hdr->sg_flag)
735 		return ERROR_ESBC_CLIENT_HEADER_SG;
736 #endif
737 
738 	/* modulus most significant bit should be set */
739 	k = (u8 *)&img->img_key;
740 
741 	if ((k[0] & 0x80) == 0)
742 		return ERROR_ESBC_CLIENT_HEADER_KEY_MOD_1;
743 
744 	/* modulus value should be odd */
745 	if ((k[get_key_len(img) / 2 - 1] & 0x1) == 0)
746 		return ERROR_ESBC_CLIENT_HEADER_KEY_MOD_2;
747 
748 	/* Check signature value < modulus value */
749 	s = (u8 *)&img->img_sign;
750 
751 	if (!(memcmp(s, k, hdr->sign_len) < 0))
752 		return ERROR_ESBC_CLIENT_HEADER_SIG_KEY_MOD;
753 
754 	return ESBC_VALID_HDR;
755 }
756 
757 static inline int str2longbe(const char *p, ulong *num)
758 {
759 	char *endptr;
760 	ulong tmp;
761 
762 	if (!p) {
763 		return 0;
764 	} else {
765 		tmp = simple_strtoul(p, &endptr, 16);
766 		if (sizeof(ulong) == 4)
767 			*num = cpu_to_be32(tmp);
768 		else
769 			*num = cpu_to_be64(tmp);
770 	}
771 
772 	return *p != '\0' && *endptr == '\0';
773 }
774 /* Function to calculate the ESBC Image Hash
775  * and hash from Digital signature.
776  * The Two hash's are compared to yield the
777  * result of signature validation.
778  */
779 static int calculate_cmp_img_sig(struct fsl_secboot_img_priv *img)
780 {
781 	int ret;
782 	uint32_t key_len;
783 	struct key_prop prop;
784 #if !defined(USE_HOSTCC)
785 	struct udevice *mod_exp_dev;
786 #endif
787 	ret = calc_esbchdr_esbc_hash(img);
788 	if (ret)
789 		return ret;
790 
791 	/* Construct encoded hash EM' wrt PKCSv1.5 */
792 	construct_img_encoded_hash_second(img);
793 
794 	/* Fill prop structure for public key */
795 	memset(&prop, 0, sizeof(struct key_prop));
796 	key_len = get_key_len(img) / 2;
797 	prop.modulus = img->img_key;
798 	prop.public_exponent = img->img_key + key_len;
799 	prop.num_bits = key_len * 8;
800 	prop.exp_len = key_len;
801 
802 	ret = uclass_get_device(UCLASS_MOD_EXP, 0, &mod_exp_dev);
803 	if (ret) {
804 		printf("RSA: Can't find Modular Exp implementation\n");
805 		return -EINVAL;
806 	}
807 
808 	ret = rsa_mod_exp(mod_exp_dev, img->img_sign, img->hdr.sign_len,
809 			  &prop, img->img_encoded_hash);
810 	if (ret)
811 		return ret;
812 
813 	/*
814 	 * compare the encoded messages EM' and EM wrt RSA PKCSv1.5
815 	 * memcmp returns zero on success
816 	 * memcmp returns non-zero on failure
817 	 */
818 	ret = memcmp(&img->img_encoded_hash_second, &img->img_encoded_hash,
819 		img->hdr.sign_len);
820 
821 	if (ret)
822 		return ERROR_ESBC_CLIENT_HASH_COMPARE_EM;
823 
824 	return 0;
825 }
826 /* Function to initialize img priv and global data structure
827  */
828 static int secboot_init(struct fsl_secboot_img_priv **img_ptr)
829 {
830 	*img_ptr = malloc(sizeof(struct fsl_secboot_img_priv));
831 
832 	struct fsl_secboot_img_priv *img = *img_ptr;
833 
834 	if (!img)
835 		return -ENOMEM;
836 	memset(img, 0, sizeof(struct fsl_secboot_img_priv));
837 
838 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
839 	if (glb.ie_addr)
840 		img->ie_addr = glb.ie_addr;
841 #endif
842 	return 0;
843 }
844 
845 
846 /* haddr - Address of the header of image to be validated.
847  * arg_hash_str - Option hash string. If provided, this
848  * overrides the key hash in the SFP fuses.
849  * img_addr_ptr - Optional pointer to address of image to be validated.
850  * If non zero addr, this overrides the addr of image in header,
851  * otherwise updated to image addr in header.
852  * Acts as both input and output of function.
853  * This pointer shouldn't be NULL.
854  */
855 int fsl_secboot_validate(uintptr_t haddr, char *arg_hash_str,
856 			uintptr_t *img_addr_ptr)
857 {
858 	struct ccsr_sfp_regs *sfp_regs = (void *)(CONFIG_SYS_SFP_ADDR);
859 	ulong hash[SHA256_BYTES/sizeof(ulong)];
860 	char hash_str[NUM_HEX_CHARS + 1];
861 	struct fsl_secboot_img_priv *img;
862 	struct fsl_secboot_img_hdr *hdr;
863 	void *esbc;
864 	int ret, i, hash_cmd = 0;
865 	u32 srk_hash[8];
866 
867 	if (arg_hash_str != NULL) {
868 		const char *cp = arg_hash_str;
869 		int i = 0;
870 
871 		if (*cp == '0' && *(cp + 1) == 'x')
872 			cp += 2;
873 
874 		/* The input string expected is in hex, where
875 		 * each 4 bits would be represented by a hex
876 		 * sha256 hash is 256 bits long, which would mean
877 		 * num of characters = 256 / 4
878 		 */
879 		if (strlen(cp) != SHA256_NIBBLES) {
880 			printf("%s is not a 256 bits hex string as expected\n",
881 			       arg_hash_str);
882 			return -1;
883 		}
884 
885 		for (i = 0; i < sizeof(hash)/sizeof(ulong); i++) {
886 			strncpy(hash_str, cp + (i * NUM_HEX_CHARS),
887 				NUM_HEX_CHARS);
888 			hash_str[NUM_HEX_CHARS] = '\0';
889 			if (!str2longbe(hash_str, &hash[i])) {
890 				printf("%s is not a 256 bits hex string ",
891 				       arg_hash_str);
892 				return -1;
893 			}
894 		}
895 
896 		hash_cmd = 1;
897 	}
898 
899 	ret = secboot_init(&img);
900 	if (ret)
901 		goto exit;
902 
903 	/* Update the information in Private Struct */
904 	hdr = &img->hdr;
905 	img->ehdrloc = haddr;
906 	img->img_addr_ptr = img_addr_ptr;
907 	esbc = (u8 *)img->ehdrloc;
908 
909 	memcpy(hdr, esbc, sizeof(struct fsl_secboot_img_hdr));
910 
911 	/* read and validate esbc header */
912 	ret = read_validate_esbc_client_header(img);
913 
914 	if (ret != ESBC_VALID_HDR) {
915 		fsl_secboot_handle_error(ret);
916 		goto exit;
917 	}
918 
919 	/* SRKH present in SFP */
920 	for (i = 0; i < NUM_SRKH_REGS; i++)
921 		srk_hash[i] = srk_in32(&sfp_regs->srk_hash[i]);
922 
923 	/*
924 	 * Calculate hash of key obtained via offset present in
925 	 * ESBC uboot client hdr
926 	 */
927 	ret = calc_img_key_hash(img);
928 	if (ret) {
929 		fsl_secblk_handle_error(ret);
930 		goto exit;
931 	}
932 
933 	/* Compare hash obtained above with SRK hash present in SFP */
934 	if (hash_cmd)
935 		ret = memcmp(&hash, &img->img_key_hash, SHA256_BYTES);
936 	else
937 		ret = memcmp(srk_hash, img->img_key_hash, SHA256_BYTES);
938 
939 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
940 	if (!hash_cmd && check_ie(img))
941 		ret = 0;
942 #endif
943 
944 	if (ret != 0) {
945 		fsl_secboot_handle_error(ERROR_ESBC_CLIENT_HASH_COMPARE_KEY);
946 		goto exit;
947 	}
948 
949 	ret = calculate_cmp_img_sig(img);
950 	if (ret) {
951 		fsl_secboot_handle_error(ret);
952 		goto exit;
953 	}
954 
955 exit:
956 	/* Free Img as it was malloc'ed*/
957 	free(img);
958 	return ret;
959 }
960