1 /*
2  * Copyright 2015 Freescale Semiconductor, Inc.
3  *
4  * SPDX-License-Identifier:	GPL-2.0+
5  */
6 
7 #include <common.h>
8 #include <dm.h>
9 #include <fsl_validate.h>
10 #include <fsl_secboot_err.h>
11 #include <fsl_sfp.h>
12 #include <fsl_sec.h>
13 #include <command.h>
14 #include <malloc.h>
15 #include <u-boot/rsa-mod-exp.h>
16 #include <hash.h>
17 #include <fsl_secboot_err.h>
18 #ifdef CONFIG_ARCH_LS1021A
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 #ifndef CONFIG_SPL_BUILD
397 	const struct fsl_secboot_errcode *e;
398 
399 	for (e = fsl_secboot_errcodes; e->errcode != ERROR_ESBC_CLIENT_MAX;
400 		e++) {
401 		if (e->errcode == error)
402 			printf("ERROR :: %x :: %s\n", error, e->name);
403 	}
404 #else
405 	printf("ERROR :: %x\n", error);
406 #endif
407 
408 	/* If Boot Mode is secure, transition the SNVS state and issue
409 	 * reset based on type of failure and ITS setting.
410 	 * If Boot mode is non-secure, return from this function.
411 	 */
412 	if (fsl_check_boot_mode_secure() == 0)
413 		return;
414 
415 	switch (error) {
416 	case ERROR_ESBC_CLIENT_HEADER_BARKER:
417 	case ERROR_ESBC_CLIENT_HEADER_IMG_SIZE:
418 	case ERROR_ESBC_CLIENT_HEADER_KEY_LEN:
419 	case ERROR_ESBC_CLIENT_HEADER_SIG_LEN:
420 	case ERROR_ESBC_CLIENT_HEADER_KEY_LEN_NOT_TWICE_SIG_LEN:
421 	case ERROR_ESBC_CLIENT_HEADER_KEY_MOD_1:
422 	case ERROR_ESBC_CLIENT_HEADER_KEY_MOD_2:
423 	case ERROR_ESBC_CLIENT_HEADER_SIG_KEY_MOD:
424 	case ERROR_ESBC_CLIENT_HEADER_SG_ESBC_EP:
425 	case ERROR_ESBC_CLIENT_HEADER_SG_ENTIRES_BAD:
426 	case ERROR_KEY_TABLE_NOT_FOUND:
427 #ifdef CONFIG_KEY_REVOCATION
428 	case ERROR_ESBC_CLIENT_HEADER_KEY_REVOKED:
429 	case ERROR_ESBC_CLIENT_HEADER_INVALID_SRK_NUM_ENTRY:
430 	case ERROR_ESBC_CLIENT_HEADER_INVALID_KEY_NUM:
431 	case ERROR_ESBC_CLIENT_HEADER_INV_SRK_ENTRY_KEYLEN:
432 #endif
433 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
434 	/*@fallthrough@*/
435 	case ERROR_ESBC_CLIENT_HEADER_IE_KEY_REVOKED:
436 	case ERROR_ESBC_CLIENT_HEADER_INVALID_IE_NUM_ENTRY:
437 	case ERROR_ESBC_CLIENT_HEADER_INVALID_IE_KEY_NUM:
438 	case ERROR_ESBC_CLIENT_HEADER_INV_IE_ENTRY_KEYLEN:
439 	case ERROR_IE_TABLE_NOT_FOUND:
440 #endif
441 		fsl_secboot_header_verification_failure();
442 		break;
443 	case ERROR_ESBC_SEC_RESET:
444 	case ERROR_ESBC_SEC_DEQ:
445 	case ERROR_ESBC_SEC_ENQ:
446 	case ERROR_ESBC_SEC_DEQ_TO:
447 	case ERROR_ESBC_SEC_JOBQ_STATUS:
448 	case ERROR_ESBC_CLIENT_HASH_COMPARE_KEY:
449 	case ERROR_ESBC_CLIENT_HASH_COMPARE_EM:
450 		fsl_secboot_image_verification_failure();
451 		break;
452 	case ERROR_ESBC_MISSING_BOOTM:
453 		fsl_secboot_bootscript_parse_failure();
454 		break;
455 	case ERROR_ESBC_WRONG_CMD:
456 	default:
457 		branch_to_self();
458 		break;
459 	}
460 }
461 
462 static void fsl_secblk_handle_error(int error)
463 {
464 	switch (error) {
465 	case ERROR_ESBC_SEC_ENQ:
466 		fsl_secboot_handle_error(ERROR_ESBC_SEC_ENQ);
467 		break;
468 	case ERROR_ESBC_SEC_DEQ:
469 		fsl_secboot_handle_error(ERROR_ESBC_SEC_DEQ);
470 		break;
471 	case ERROR_ESBC_SEC_DEQ_TO:
472 		fsl_secboot_handle_error(ERROR_ESBC_SEC_DEQ_TO);
473 		break;
474 	default:
475 		printf("Job Queue Output status %x\n", error);
476 		fsl_secboot_handle_error(ERROR_ESBC_SEC_JOBQ_STATUS);
477 		break;
478 	}
479 }
480 
481 /*
482  * Calculate hash of key obtained via offset present in ESBC uboot
483  * client hdr. This function calculates the hash of key which is obtained
484  * through offset present in ESBC uboot client header.
485  */
486 static int calc_img_key_hash(struct fsl_secboot_img_priv *img)
487 {
488 	struct hash_algo *algo;
489 	void *ctx;
490 	int i, srk = 0;
491 	int ret = 0;
492 	const char *algo_name = "sha256";
493 
494 	/* Calculate hash of the esbc key */
495 	ret = hash_progressive_lookup_algo(algo_name, &algo);
496 	if (ret)
497 		return ret;
498 
499 	ret = algo->hash_init(algo, &ctx);
500 	if (ret)
501 		return ret;
502 
503 	/* Update hash for ESBC key */
504 #ifdef CONFIG_KEY_REVOCATION
505 	if (check_srk(img)) {
506 		ret = algo->hash_update(algo, ctx,
507 		      (u8 *)(uintptr_t)(img->ehdrloc + img->hdr.srk_tbl_off),
508 		      img->hdr.len_kr.num_srk * sizeof(struct srk_table), 1);
509 		srk = 1;
510 	}
511 #endif
512 	if (!srk)
513 		ret = algo->hash_update(algo, ctx,
514 			img->img_key, img->key_len, 1);
515 	if (ret)
516 		return ret;
517 
518 	/* Copy hash at destination buffer */
519 	ret = algo->hash_finish(algo, ctx, hash_val, algo->digest_size);
520 	if (ret)
521 		return ret;
522 
523 	for (i = 0; i < SHA256_BYTES; i++)
524 		img->img_key_hash[i] = hash_val[i];
525 
526 	return 0;
527 }
528 
529 /*
530  * Calculate hash of ESBC hdr and ESBC. This function calculates the
531  * single hash of ESBC header and ESBC image. If SG flag is on, all
532  * SG entries are also hashed alongwith the complete SG table.
533  */
534 static int calc_esbchdr_esbc_hash(struct fsl_secboot_img_priv *img)
535 {
536 	struct hash_algo *algo;
537 	void *ctx;
538 	int ret = 0;
539 	int key_hash = 0;
540 	const char *algo_name = "sha256";
541 
542 	/* Calculate the hash of the ESBC */
543 	ret = hash_progressive_lookup_algo(algo_name, &algo);
544 	if (ret)
545 		return ret;
546 
547 	ret = algo->hash_init(algo, &ctx);
548 	/* Copy hash at destination buffer */
549 	if (ret)
550 		return ret;
551 
552 	/* Update hash for CSF Header */
553 	ret = algo->hash_update(algo, ctx,
554 		(u8 *)&img->hdr, sizeof(struct fsl_secboot_img_hdr), 0);
555 	if (ret)
556 		return ret;
557 
558 	/* Update the hash with that of srk table if srk flag is 1
559 	 * If IE Table is selected, key is not added in the hash
560 	 * If neither srk table nor IE key table available, add key
561 	 * from header in the hash calculation
562 	 */
563 #ifdef CONFIG_KEY_REVOCATION
564 	if (check_srk(img)) {
565 		ret = algo->hash_update(algo, ctx,
566 		      (u8 *)(uintptr_t)(img->ehdrloc + img->hdr.srk_tbl_off),
567 		      img->hdr.len_kr.num_srk * sizeof(struct srk_table), 0);
568 		key_hash = 1;
569 	}
570 #endif
571 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
572 	if (!key_hash && check_ie(img))
573 		key_hash = 1;
574 #endif
575 #ifndef CONFIG_ESBC_HDR_LS
576 /* No single key support in LS ESBC header */
577 	if (!key_hash) {
578 		ret = algo->hash_update(algo, ctx,
579 			img->img_key, img->hdr.key_len, 0);
580 		key_hash = 1;
581 	}
582 #endif
583 	if (ret)
584 		return ret;
585 	if (!key_hash)
586 		return ERROR_KEY_TABLE_NOT_FOUND;
587 
588 	/* Update hash for actual Image */
589 	ret = algo->hash_update(algo, ctx,
590 		(u8 *)(*(img->img_addr_ptr)), img->img_size, 1);
591 	if (ret)
592 		return ret;
593 
594 	/* Copy hash at destination buffer */
595 	ret = algo->hash_finish(algo, ctx, hash_val, algo->digest_size);
596 	if (ret)
597 		return ret;
598 
599 	return 0;
600 }
601 
602 /*
603  * Construct encoded hash EM' wrt PKCSv1.5. This function calculates the
604  * pointers for padding, DER value and hash. And finally, constructs EM'
605  * which includes hash of complete CSF header and ESBC image. If SG flag
606  * is on, hash of SG table and entries is also included.
607  */
608 static void construct_img_encoded_hash_second(struct fsl_secboot_img_priv *img)
609 {
610 	/*
611 	 * RSA PKCSv1.5 encoding format for encoded message is below
612 	 * EM = 0x0 || 0x1 || PS || 0x0 || DER || Hash
613 	 * PS is Padding String
614 	 * DER is DER value for SHA-256
615 	 * Hash is SHA-256 hash
616 	 * *********************************************************
617 	 * representative points to first byte of EM initially and is
618 	 * filled with 0x0
619 	 * representative is incremented by 1 and second byte is filled
620 	 * with 0x1
621 	 * padding points to third byte of EM
622 	 * digest points to full length of EM - 32 bytes
623 	 * hash_id (DER value) points to 19 bytes before pDigest
624 	 * separator is one byte which separates padding and DER
625 	 */
626 
627 	size_t len;
628 	u8 *representative;
629 	u8 *padding, *digest;
630 	u8 *hash_id, *separator;
631 	int i;
632 
633 	len = (get_key_len(img) / 2) - 1;
634 	representative = img->img_encoded_hash_second;
635 	representative[0] = 0;
636 	representative[1] = 1;  /* block type 1 */
637 
638 	padding = &representative[2];
639 	digest = &representative[1] + len - 32;
640 	hash_id = digest - sizeof(hash_identifier);
641 	separator = hash_id - 1;
642 
643 	/* fill padding area pointed by padding with 0xff */
644 	memset(padding, 0xff, separator - padding);
645 
646 	/* fill byte pointed by separator */
647 	*separator = 0;
648 
649 	/* fill SHA-256 DER value  pointed by HashId */
650 	memcpy(hash_id, hash_identifier, sizeof(hash_identifier));
651 
652 	/* fill hash pointed by Digest */
653 	for (i = 0; i < SHA256_BYTES; i++)
654 		digest[i] = hash_val[i];
655 }
656 
657 /*
658  * Reads and validates the ESBC client header.
659  * This function reads key and signature from the ESBC client header.
660  * If Scatter/Gather flag is on, lengths and offsets of images
661  * present as SG entries are also read. This function also checks
662  * whether the header is valid or not.
663  */
664 static int read_validate_esbc_client_header(struct fsl_secboot_img_priv *img)
665 {
666 	struct fsl_secboot_img_hdr *hdr = &img->hdr;
667 	void *esbc = (u8 *)(uintptr_t)img->ehdrloc;
668 	u8 *k, *s;
669 	u32 ret = 0;
670 
671 	int  key_found = 0;
672 
673 	/* check barker code */
674 	if (memcmp(hdr->barker, barker_code, ESBC_BARKER_LEN))
675 		return ERROR_ESBC_CLIENT_HEADER_BARKER;
676 
677 	/* If Image Address is not passed as argument to function,
678 	 * then Address and Size must be read from the Header.
679 	 */
680 	if (*(img->img_addr_ptr) == 0) {
681 	#ifdef CONFIG_ESBC_ADDR_64BIT
682 		*(img->img_addr_ptr) = hdr->pimg64;
683 	#else
684 		*(img->img_addr_ptr) = hdr->pimg;
685 	#endif
686 	}
687 
688 	if (!hdr->img_size)
689 		return ERROR_ESBC_CLIENT_HEADER_IMG_SIZE;
690 
691 	img->img_size = hdr->img_size;
692 
693 	/* Key checking*/
694 #ifdef CONFIG_KEY_REVOCATION
695 	if (check_srk(img)) {
696 		ret = read_validate_srk_tbl(img);
697 		if (ret != 0)
698 			return ret;
699 		key_found = 1;
700 	}
701 #endif
702 
703 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
704 	if (!key_found && check_ie(img)) {
705 		ret = read_validate_ie_tbl(img);
706 		if (ret != 0)
707 			return ret;
708 		key_found = 1;
709 	}
710 #endif
711 #ifndef CONFIG_ESBC_HDR_LS
712 /* Single Key Feature not available in LS ESBC Header */
713 	if (key_found == 0) {
714 		ret = read_validate_single_key(img);
715 		if (ret != 0)
716 			return ret;
717 		key_found = 1;
718 	}
719 #endif
720 	if (!key_found)
721 		return ERROR_KEY_TABLE_NOT_FOUND;
722 
723 	/* check signaure */
724 	if (get_key_len(img) == 2 * hdr->sign_len) {
725 		/* check signature length */
726 		if (!((hdr->sign_len == KEY_SIZE_BYTES / 4) ||
727 		      (hdr->sign_len == KEY_SIZE_BYTES / 2) ||
728 		      (hdr->sign_len == KEY_SIZE_BYTES)))
729 			return ERROR_ESBC_CLIENT_HEADER_SIG_LEN;
730 	} else {
731 		return ERROR_ESBC_CLIENT_HEADER_KEY_LEN_NOT_TWICE_SIG_LEN;
732 	}
733 
734 	memcpy(&img->img_sign, esbc + hdr->psign, hdr->sign_len);
735 /* No SG support in LS-CH3 */
736 #ifndef CONFIG_ESBC_HDR_LS
737 	/* No SG support */
738 	if (hdr->sg_flag)
739 		return ERROR_ESBC_CLIENT_HEADER_SG;
740 #endif
741 
742 	/* modulus most significant bit should be set */
743 	k = (u8 *)&img->img_key;
744 
745 	if ((k[0] & 0x80) == 0)
746 		return ERROR_ESBC_CLIENT_HEADER_KEY_MOD_1;
747 
748 	/* modulus value should be odd */
749 	if ((k[get_key_len(img) / 2 - 1] & 0x1) == 0)
750 		return ERROR_ESBC_CLIENT_HEADER_KEY_MOD_2;
751 
752 	/* Check signature value < modulus value */
753 	s = (u8 *)&img->img_sign;
754 
755 	if (!(memcmp(s, k, hdr->sign_len) < 0))
756 		return ERROR_ESBC_CLIENT_HEADER_SIG_KEY_MOD;
757 
758 	return ESBC_VALID_HDR;
759 }
760 
761 static inline int str2longbe(const char *p, ulong *num)
762 {
763 	char *endptr;
764 	ulong tmp;
765 
766 	if (!p) {
767 		return 0;
768 	} else {
769 		tmp = simple_strtoul(p, &endptr, 16);
770 		if (sizeof(ulong) == 4)
771 			*num = cpu_to_be32(tmp);
772 		else
773 			*num = cpu_to_be64(tmp);
774 	}
775 
776 	return *p != '\0' && *endptr == '\0';
777 }
778 /* Function to calculate the ESBC Image Hash
779  * and hash from Digital signature.
780  * The Two hash's are compared to yield the
781  * result of signature validation.
782  */
783 static int calculate_cmp_img_sig(struct fsl_secboot_img_priv *img)
784 {
785 	int ret;
786 	uint32_t key_len;
787 	struct key_prop prop;
788 #if !defined(USE_HOSTCC)
789 	struct udevice *mod_exp_dev;
790 #endif
791 	ret = calc_esbchdr_esbc_hash(img);
792 	if (ret)
793 		return ret;
794 
795 	/* Construct encoded hash EM' wrt PKCSv1.5 */
796 	construct_img_encoded_hash_second(img);
797 
798 	/* Fill prop structure for public key */
799 	memset(&prop, 0, sizeof(struct key_prop));
800 	key_len = get_key_len(img) / 2;
801 	prop.modulus = img->img_key;
802 	prop.public_exponent = img->img_key + key_len;
803 	prop.num_bits = key_len * 8;
804 	prop.exp_len = key_len;
805 
806 	ret = uclass_get_device(UCLASS_MOD_EXP, 0, &mod_exp_dev);
807 	if (ret) {
808 		printf("RSA: Can't find Modular Exp implementation\n");
809 		return -EINVAL;
810 	}
811 
812 	ret = rsa_mod_exp(mod_exp_dev, img->img_sign, img->hdr.sign_len,
813 			  &prop, img->img_encoded_hash);
814 	if (ret)
815 		return ret;
816 
817 	/*
818 	 * compare the encoded messages EM' and EM wrt RSA PKCSv1.5
819 	 * memcmp returns zero on success
820 	 * memcmp returns non-zero on failure
821 	 */
822 	ret = memcmp(&img->img_encoded_hash_second, &img->img_encoded_hash,
823 		img->hdr.sign_len);
824 
825 	if (ret)
826 		return ERROR_ESBC_CLIENT_HASH_COMPARE_EM;
827 
828 	return 0;
829 }
830 /* Function to initialize img priv and global data structure
831  */
832 static int secboot_init(struct fsl_secboot_img_priv **img_ptr)
833 {
834 	*img_ptr = malloc(sizeof(struct fsl_secboot_img_priv));
835 
836 	struct fsl_secboot_img_priv *img = *img_ptr;
837 
838 	if (!img)
839 		return -ENOMEM;
840 	memset(img, 0, sizeof(struct fsl_secboot_img_priv));
841 
842 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
843 	if (glb.ie_addr)
844 		img->ie_addr = glb.ie_addr;
845 #endif
846 	return 0;
847 }
848 
849 
850 /* haddr - Address of the header of image to be validated.
851  * arg_hash_str - Option hash string. If provided, this
852  * overrides the key hash in the SFP fuses.
853  * img_addr_ptr - Optional pointer to address of image to be validated.
854  * If non zero addr, this overrides the addr of image in header,
855  * otherwise updated to image addr in header.
856  * Acts as both input and output of function.
857  * This pointer shouldn't be NULL.
858  */
859 int fsl_secboot_validate(uintptr_t haddr, char *arg_hash_str,
860 			uintptr_t *img_addr_ptr)
861 {
862 	struct ccsr_sfp_regs *sfp_regs = (void *)(CONFIG_SYS_SFP_ADDR);
863 	ulong hash[SHA256_BYTES/sizeof(ulong)];
864 	char hash_str[NUM_HEX_CHARS + 1];
865 	struct fsl_secboot_img_priv *img;
866 	struct fsl_secboot_img_hdr *hdr;
867 	void *esbc;
868 	int ret, i, hash_cmd = 0;
869 	u32 srk_hash[8];
870 
871 	if (arg_hash_str != NULL) {
872 		const char *cp = arg_hash_str;
873 		int i = 0;
874 
875 		if (*cp == '0' && *(cp + 1) == 'x')
876 			cp += 2;
877 
878 		/* The input string expected is in hex, where
879 		 * each 4 bits would be represented by a hex
880 		 * sha256 hash is 256 bits long, which would mean
881 		 * num of characters = 256 / 4
882 		 */
883 		if (strlen(cp) != SHA256_NIBBLES) {
884 			printf("%s is not a 256 bits hex string as expected\n",
885 			       arg_hash_str);
886 			return -1;
887 		}
888 
889 		for (i = 0; i < sizeof(hash)/sizeof(ulong); i++) {
890 			strncpy(hash_str, cp + (i * NUM_HEX_CHARS),
891 				NUM_HEX_CHARS);
892 			hash_str[NUM_HEX_CHARS] = '\0';
893 			if (!str2longbe(hash_str, &hash[i])) {
894 				printf("%s is not a 256 bits hex string ",
895 				       arg_hash_str);
896 				return -1;
897 			}
898 		}
899 
900 		hash_cmd = 1;
901 	}
902 
903 	ret = secboot_init(&img);
904 	if (ret)
905 		goto exit;
906 
907 	/* Update the information in Private Struct */
908 	hdr = &img->hdr;
909 	img->ehdrloc = haddr;
910 	img->img_addr_ptr = img_addr_ptr;
911 	esbc = (u8 *)img->ehdrloc;
912 
913 	memcpy(hdr, esbc, sizeof(struct fsl_secboot_img_hdr));
914 
915 	/* read and validate esbc header */
916 	ret = read_validate_esbc_client_header(img);
917 
918 	if (ret != ESBC_VALID_HDR) {
919 		fsl_secboot_handle_error(ret);
920 		goto exit;
921 	}
922 
923 	/* SRKH present in SFP */
924 	for (i = 0; i < NUM_SRKH_REGS; i++)
925 		srk_hash[i] = srk_in32(&sfp_regs->srk_hash[i]);
926 
927 	/*
928 	 * Calculate hash of key obtained via offset present in
929 	 * ESBC uboot client hdr
930 	 */
931 	ret = calc_img_key_hash(img);
932 	if (ret) {
933 		fsl_secblk_handle_error(ret);
934 		goto exit;
935 	}
936 
937 	/* Compare hash obtained above with SRK hash present in SFP */
938 	if (hash_cmd)
939 		ret = memcmp(&hash, &img->img_key_hash, SHA256_BYTES);
940 	else
941 		ret = memcmp(srk_hash, img->img_key_hash, SHA256_BYTES);
942 
943 #if defined(CONFIG_FSL_ISBC_KEY_EXT)
944 	if (!hash_cmd && check_ie(img))
945 		ret = 0;
946 #endif
947 
948 	if (ret != 0) {
949 		fsl_secboot_handle_error(ERROR_ESBC_CLIENT_HASH_COMPARE_KEY);
950 		goto exit;
951 	}
952 
953 	ret = calculate_cmp_img_sig(img);
954 	if (ret) {
955 		fsl_secboot_handle_error(ret);
956 		goto exit;
957 	}
958 
959 exit:
960 	/* Free Img as it was malloc'ed*/
961 	free(img);
962 	return ret;
963 }
964