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