1 /**
2   ******************************************************************************
3   * @file    low_level_security.c
4   * @author  MCD Application Team
5   * @brief   security protection implementation for secure boot on STM32U5xx
6   *
7   ******************************************************************************
8   * @attention
9   *
10   * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
11   * Copyright (c) 2017-2020 Arm Limited
12   * All rights reserved.</center></h2>
13   *
14   * This software component is licensed by ST under BSD 3-Clause license,
15   * the "License"; You may not use this file except in compliance with the
16   * License. You may obtain a copy of the License at:
17   *                        opensource.org/licenses/BSD-3-Clause
18   *
19   ******************************************************************************
20   */
21 /* Includes ------------------------------------------------------------------*/
22 #include <string.h>
23 #include "boot_hal_cfg.h"
24 #include "mpu_armv8m_drv.h"
25 #include "region_defs.h"
26 #include "mcuboot_config/mcuboot_config.h"
27 #include "low_level_security.h"
28 #if defined(FLOW_CONTROL)
29 #include "boot_hal_flowcontrol.h"
30 #else
31 /* dummy definitions */
32 extern volatile uint32_t uFlowStage;
33 #define FLOW_CONTROL_STEP(C,B,A) ((void)0)
34 #define FLOW_CONTROL_CHECK(B,A) ((void)0)
35 #define FLOW_STAGE_CFG          (0x0)
36 #define FLOW_STAGE_CHK          (0x1)
37 #endif
38 #ifdef TFM_DEV_MODE
39 #define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
40 #else
41 #define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_OFF
42 #endif /* TFM_DEV_MODE  */
43 #include "bootutil/bootutil_log.h"
44 #if (TFM_TAMPER_ENABLE != NO_TAMPER)
45 #include "low_level_rng.h"
46 #endif /*  (TFM_TAMPER_ENABLE != NO_TAMPER)*/
47 #include "target_cfg.h"
48 
49 #define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(arr[0]))
50 
51 
52 /** @defgroup TFM_SECURITY_Private_Defines  Private Defines
53   * @{
54   */
55 /* DUAL BANK page size */
56 #define PAGE_SIZE FLASH_AREA_IMAGE_SECTOR_SIZE
57 
58 #define PAGE_MAX_NUMBER_IN_BANK 127
59 
60 /* SBSFU_Boot Vector Address  */
61 #define SBSFU_BOOT_VTOR_ADDR ((uint32_t)(BL2_CODE_START))
62 
63 
64 const struct mpu_armv8m_region_cfg_t region_cfg_init_s[] = {
65            /* background region is enabled , secure execution on unsecure flash is not possible*/
66            /* but non secure execution on unsecure flash is possible , non secure mpu is used to protect execution */
67            /* since SAU is enabled later to gain access to non secure flash */
68            /* Forbid execuction outside of flash write protected area  */
69            /* descriptor 0 is set execute readonly before jumping in Secure application */
70            {
71                0,
72                FLASH_BASE_S + S_IMAGE_PRIMARY_PARTITION_OFFSET,
73                FLASH_BASE_S + S_IMAGE_PRIMARY_PARTITION_OFFSET + FLASH_S_PARTITION_SIZE,
74                MPU_ARMV8M_MAIR_ATTR_DATANOCACHE_IDX,
75                MPU_ARMV8M_XN_EXEC_NEVER,
76                MPU_ARMV8M_AP_RW_PRIV_ONLY,
77                MPU_ARMV8M_SH_NONE,
78 #ifdef FLOW_CONTROL
79                FLOW_STEP_MPU_S_I_EN_R0,
80                FLOW_CTRL_MPU_S_I_EN_R0,
81                FLOW_STEP_MPU_S_I_CH_R0,
82                FLOW_CTRL_MPU_S_I_CH_R0,
83 #endif /* FLOW_CONTROL */
84            },
85            {
86                1,
87                FLASH_BASE_S + S_IMAGE_PRIMARY_PARTITION_OFFSET + FLASH_S_PARTITION_SIZE,
88 #if !defined(MCUBOOT_PRIMARY_ONLY) && !defined(EXTERNAL_FLASH)
89                FLASH_BASE_S + NS_IMAGE_SECONDARY_PARTITION_OFFSET + FLASH_NS_PARTITION_SIZE,
90 #else
91                FLASH_BASE_S + S_IMAGE_PRIMARY_PARTITION_OFFSET + FLASH_S_PARTITION_SIZE + FLASH_NS_PARTITION_SIZE,
92 #endif /* MCUBOOT_PRIMARY_ONLY */
93                MPU_ARMV8M_MAIR_ATTR_DATANOCACHE_IDX,
94                MPU_ARMV8M_XN_EXEC_NEVER,
95                MPU_ARMV8M_AP_RW_PRIV_ONLY,
96                MPU_ARMV8M_SH_NONE,
97 #ifdef FLOW_CONTROL
98                FLOW_STEP_MPU_S_I_EN_R1,
99                FLOW_CTRL_MPU_S_I_EN_R1,
100                FLOW_STEP_MPU_S_I_CH_R1,
101                FLOW_CTRL_MPU_S_I_CH_R1,
102 #endif /* FLOW_CONTROL */
103            },
104            {
105                2,
106                FLASH_BASE_S,
107                FLASH_BASE_S + FLASH_AREA_BL2_OFFSET,
108                MPU_ARMV8M_MAIR_ATTR_DATANOCACHE_IDX,
109                MPU_ARMV8M_XN_EXEC_NEVER,
110                MPU_ARMV8M_AP_RW_PRIV_ONLY,
111                MPU_ARMV8M_SH_NONE,
112 #ifdef FLOW_CONTROL
113                FLOW_STEP_MPU_S_I_EN_R2,
114                FLOW_CTRL_MPU_S_I_EN_R2,
115                FLOW_STEP_MPU_S_I_CH_R2,
116                FLOW_CTRL_MPU_S_I_CH_R2,
117 #endif /* FLOW_CONTROL */
118            },
119            {
120                3,
121                FLASH_BASE_S + FLASH_AREA_BL2_NOHDP_OFFSET + FLASH_AREA_BL2_NOHDP_SIZE,
122                FLASH_BASE_S + FLASH_AREA_0_OFFSET,
123                MPU_ARMV8M_MAIR_ATTR_DATANOCACHE_IDX,
124                MPU_ARMV8M_XN_EXEC_NEVER,
125                MPU_ARMV8M_AP_RW_PRIV_ONLY,
126                MPU_ARMV8M_SH_NONE,
127 #ifdef FLOW_CONTROL
128                FLOW_STEP_MPU_S_I_EN_R3,
129                FLOW_CTRL_MPU_S_I_EN_R3,
130                FLOW_STEP_MPU_S_I_CH_R3,
131                FLOW_CTRL_MPU_S_I_CH_R3,
132 #endif /* FLOW_CONTROL */
133            },
134            /* Forbid execution on full SRAM area */
135            {
136                4,
137                BL2_SRAM_AREA_BASE,
138                BL2_SRAM_AREA_END,
139                MPU_ARMV8M_MAIR_ATTR_DATA_IDX,
140                MPU_ARMV8M_XN_EXEC_NEVER,
141                MPU_ARMV8M_AP_RW_PRIV_ONLY,
142                MPU_ARMV8M_SH_NONE,
143 #ifdef FLOW_CONTROL
144                FLOW_STEP_MPU_S_I_EN_R4,
145                FLOW_CTRL_MPU_S_I_EN_R4,
146                FLOW_STEP_MPU_S_I_CH_R4,
147                FLOW_CTRL_MPU_S_I_CH_R4,
148 #endif /* FLOW_CONTROL */
149            },
150            /* forbid secure peripheral execution */
151            {
152                5,
153                PERIPH_BASE_S,
154                PERIPH_BASE_S + 0x10000000,
155                MPU_ARMV8M_MAIR_ATTR_DEVICE_IDX,
156                MPU_ARMV8M_XN_EXEC_NEVER,
157                MPU_ARMV8M_AP_RW_PRIV_ONLY,
158                MPU_ARMV8M_SH_NONE,
159 #ifdef FLOW_CONTROL
160                FLOW_STEP_MPU_S_I_EN_R5,
161                FLOW_CTRL_MPU_S_I_EN_R5,
162                FLOW_STEP_MPU_S_I_CH_R5,
163                FLOW_CTRL_MPU_S_I_CH_R5,
164 #endif /* FLOW_CONTROL */
165            },
166            /* forbid execution of flash non secure alias */
167            {
168                6,
169                FLASH_BASE_NS,
170                FLASH_BASE_NS + FLASH_TOTAL_SIZE,
171                MPU_ARMV8M_MAIR_ATTR_DATANOCACHE_IDX,
172                MPU_ARMV8M_XN_EXEC_NEVER,
173                MPU_ARMV8M_AP_RW_PRIV_ONLY,
174                MPU_ARMV8M_SH_NONE,
175 #ifdef FLOW_CONTROL
176                FLOW_STEP_MPU_S_I_EN_R6,
177                FLOW_CTRL_MPU_S_I_EN_R6,
178                FLOW_STEP_MPU_S_I_CH_R6,
179                FLOW_CTRL_MPU_S_I_CH_R6,
180 #endif /* FLOW_CONTROL */
181            }
182 };
183 
184 const struct mpu_armv8m_region_cfg_t region_cfg_init_ns[] = {
185            /* forbid execution on non secure FLASH /RAM in case of jump in non secure */
186            /* Non Secure MPU  background all access in priviligied */
187            /* reduced execution to all flash during control */
188            {
189                0,
190                FLASH_BASE_NS + NS_IMAGE_PRIMARY_PARTITION_OFFSET,
191                FLASH_BASE_NS + NS_IMAGE_PRIMARY_PARTITION_OFFSET + FLASH_NS_PARTITION_SIZE,
192                MPU_ARMV8M_MAIR_ATTR_DATANOCACHE_IDX,
193                MPU_ARMV8M_XN_EXEC_NEVER,
194                MPU_ARMV8M_AP_RW_PRIV_ONLY,
195                MPU_ARMV8M_SH_NONE,
196 #ifdef FLOW_CONTROL
197                FLOW_STEP_MPU_NS_I_EN_R0,
198                FLOW_CTRL_MPU_NS_I_EN_R0,
199                FLOW_STEP_MPU_NS_I_CH_R0,
200                FLOW_CTRL_MPU_NS_I_CH_R0,
201 #endif /* FLOW_CONTROL */
202            },
203 #if !defined(MCUBOOT_PRIMARY_ONLY) && !defined(EXTERNAL_FLASH)
204            {
205                1,
206                FLASH_BASE_NS + S_IMAGE_SECONDARY_PARTITION_OFFSET,
207                FLASH_BASE_NS + NS_IMAGE_SECONDARY_PARTITION_OFFSET + FLASH_NS_PARTITION_SIZE,
208                MPU_ARMV8M_MAIR_ATTR_DATANOCACHE_IDX,
209                MPU_ARMV8M_XN_EXEC_NEVER,
210                MPU_ARMV8M_AP_RW_PRIV_ONLY,
211                MPU_ARMV8M_SH_NONE,
212 #ifdef FLOW_CONTROL
213                FLOW_STEP_MPU_NS_I_EN_R1,
214                FLOW_CTRL_MPU_NS_I_EN_R1,
215                FLOW_STEP_MPU_NS_I_CH_R1,
216                FLOW_CTRL_MPU_NS_I_CH_R1,
217 #endif /* FLOW_CONTROL */
218            },
219 #endif /* MCUBOOT_PRIMARY_ONLY */
220            /* Forbid execuction on full SRAM area */
221            {
222                2,
223 #ifdef TFM_ERROR_HANDLER_NON_SECURE
224                SRAM1_BASE_NS + (~MPU_RBAR_BASE_Msk) + 1,
225 #else
226                SRAM1_BASE_NS,
227 #endif /*   TFM_ERROR_HANDLER_NON_SECURE */
228                SRAM1_BASE_NS + TOTAL_RAM_SIZE,
229                MPU_ARMV8M_MAIR_ATTR_DATA_IDX,
230                MPU_ARMV8M_XN_EXEC_NEVER,
231                MPU_ARMV8M_AP_RW_PRIV_ONLY,
232                MPU_ARMV8M_SH_NONE,
233 #ifdef FLOW_CONTROL
234                FLOW_STEP_MPU_NS_I_EN_R2,
235                FLOW_CTRL_MPU_NS_I_EN_R2,
236                FLOW_STEP_MPU_NS_I_CH_R2,
237                FLOW_CTRL_MPU_NS_I_CH_R2,
238 #endif /* FLOW_CONTROL */
239            },
240            /* forbid secure peripheral execution */
241            {
242                3,
243                PERIPH_BASE_NS,
244                PERIPH_BASE_NS + 0x10000000,
245                MPU_ARMV8M_MAIR_ATTR_DEVICE_IDX,
246                MPU_ARMV8M_XN_EXEC_NEVER,
247                MPU_ARMV8M_AP_RW_PRIV_ONLY,
248                MPU_ARMV8M_SH_NONE,
249 #ifdef FLOW_CONTROL
250                FLOW_STEP_MPU_NS_I_EN_R3,
251                FLOW_CTRL_MPU_NS_I_EN_R3,
252                FLOW_STEP_MPU_NS_I_CH_R3,
253                FLOW_CTRL_MPU_NS_I_CH_R3,
254 #endif /* FLOW_CONTROL */
255            }
256 };
257 
258 #if defined(__ICCARM__)
259 #pragma location=".BL2_NoHdp_Data"
260 #endif
261 const struct mpu_armv8m_region_cfg_t region_cfg_appli_s[] __attribute__((section(".BL2_NoHdp_Data"))) = {
262            /* region 0 is now enable for execution */
263            {
264                0,
265                FLASH_BASE_S + S_IMAGE_PRIMARY_PARTITION_OFFSET,
266                /* Reduce area to allow write to validate the Secure Image */
267                FLASH_BASE_S + S_IMAGE_PRIMARY_PARTITION_OFFSET + FLASH_S_PARTITION_SIZE - (~MPU_RLAR_LIMIT_Msk +1),
268                MPU_ARMV8M_MAIR_ATTR_DATA_IDX,
269                MPU_ARMV8M_XN_EXEC_OK,
270                MPU_ARMV8M_AP_RO_PRIV_ONLY,
271                MPU_ARMV8M_SH_NONE,
272 #ifdef FLOW_CONTROL
273                FLOW_STEP_MPU_S_A_EN_R0,
274                FLOW_CTRL_MPU_S_A_EN_R0,
275                FLOW_STEP_MPU_S_A_CH_R0,
276                FLOW_CTRL_MPU_S_A_CH_R0,
277 #endif /* FLOW_CONTROL */
278            }
279 };
280 
281 #if defined(__ICCARM__)
282 #pragma location=".BL2_NoHdp_Data"
283 #endif
284 const struct mpu_armv8m_region_cfg_t region_cfg_appli_ns[] __attribute__((section(".BL2_NoHdp_Data"))) = {
285            /* region 0 is now enable for execution */
286            {
287                0,
288                FLASH_BASE_NS + NS_IMAGE_PRIMARY_PARTITION_OFFSET,
289                /* Reduce area to allow write to validate the Non Secure Image */
290                FLASH_BASE_NS + NS_IMAGE_PRIMARY_PARTITION_OFFSET + FLASH_NS_PARTITION_SIZE - (~MPU_RLAR_LIMIT_Msk +1),
291                MPU_ARMV8M_MAIR_ATTR_DATA_IDX,
292                MPU_ARMV8M_XN_EXEC_OK,
293                MPU_ARMV8M_AP_RO_PRIV_ONLY,
294                MPU_ARMV8M_SH_NONE,
295 #ifdef FLOW_CONTROL
296                FLOW_STEP_MPU_NS_A_EN_R0,
297                FLOW_CTRL_MPU_NS_A_EN_R0,
298                FLOW_STEP_MPU_NS_A_CH_R0,
299                FLOW_CTRL_MPU_NS_A_CH_R0,
300 #endif /* FLOW_CONTROL */
301            }
302 };
303 
304 const struct sau_cfg_t sau_init_cfg[] = {
305 #ifdef TFM_ERROR_HANDLER_NON_SECURE
306     /* Configures SAU regions non-secure to gain access to SRAM1 non secure   */
307     {
308         0,
309         SRAM1_BASE_NS,
310         (SRAM1_BASE_NS + NS_NO_INIT_DATA_SIZE),
311         TFM_FALSE,
312 #ifdef FLOW_CONTROL
313         FLOW_STEP_SAU_I_EN_R0,
314         FLOW_CTRL_SAU_I_EN_R0,
315         FLOW_STEP_SAU_I_CH_R0,
316         FLOW_CTRL_SAU_I_CH_R0,
317 #endif /* FLOW_CONTROL */
318     },
319 #endif /* TFM_ERROR_HANDLER_NON_SECURE */
320     /* Allow non secure access to Flash non Secure peripheral for regression */
321     /* Secure HAL flash driver uses the non secure flash address to perform access on non secure flash area */
322     {
323         1,
324         (uint32_t)FLASH_NS,
325         ((uint32_t)FLASH_NS + 0x10000),
326         TFM_FALSE,
327 #ifdef FLOW_CONTROL
328         FLOW_STEP_SAU_I_EN_R1,
329         FLOW_CTRL_SAU_I_EN_R1,
330         FLOW_STEP_SAU_I_CH_R1,
331         FLOW_CTRL_SAU_I_CH_R1,
332 #endif /* FLOW_CONTROL */
333     },
334     /* Allow non secure Flash base access for Area 1/2/3 */
335     {
336         2,
337         ((uint32_t)FLASH_BASE_NS + NS_IMAGE_PRIMARY_PARTITION_OFFSET),
338 #if defined(MCUBOOT_PRIMARY_ONLY) || defined(EXTERNAL_FLASH)
339         ((uint32_t)FLASH_BASE_NS + NS_IMAGE_PRIMARY_PARTITION_OFFSET + FLASH_NS_PARTITION_SIZE),
340 #else
341         ((uint32_t)FLASH_BASE_NS + S_IMAGE_SECONDARY_PARTITION_OFFSET + FLASH_PARTITION_SIZE),
342 #endif /* MCUBOOT_PRIMARY_ONLY || EXTERNAL_FLASH */
343         TFM_FALSE,
344 #ifdef FLOW_CONTROL
345         FLOW_STEP_SAU_I_EN_R2,
346         FLOW_CTRL_SAU_I_EN_R2,
347         FLOW_STEP_SAU_I_CH_R2,
348         FLOW_CTRL_SAU_I_CH_R2,
349 #endif /* FLOW_CONTROL */
350     },
351 #if defined(MCUBOOT_EXT_LOADER)
352     /* create a region to access to loader code for hash check */
353     {
354         3,
355         LOADER_NS_ROM_ALIAS(FLASH_AREA_LOADER_OFFSET),
356         LOADER_NS_ROM_ALIAS(FLASH_TOTAL_SIZE),
357         TFM_FALSE,
358 #ifdef FLOW_CONTROL
359         FLOW_STEP_SAU_I_EN_R3,
360         FLOW_CTRL_SAU_I_EN_R3,
361         FLOW_STEP_SAU_I_CH_R3,
362         FLOW_CTRL_SAU_I_CH_R3,
363 #endif /* FLOW_CONTROL */
364     }
365 #endif
366 };
367 
368 #ifdef MCUBOOT_EXT_LOADER
369 #if defined(__ICCARM__)
370 #pragma location=".BL2_NoHdp_Data"
371 #endif
372 const struct sau_cfg_t sau_load_cfg[] __attribute__((section(".BL2_NoHdp_Data"))) = {
373     /* allow access to non secure loader area ram*/
374     {
375         0,
376         (uint32_t)LOADER_NS_DATA_START,
377         (uint32_t)LOADER_NS_DATA_LIMIT + 1,
378         TFM_FALSE,
379 #ifdef FLOW_CONTROL
380         FLOW_STEP_SAU_L_EN_R0,
381         FLOW_CTRL_SAU_L_EN_R0,
382         FLOW_STEP_SAU_L_CH_R0,
383         FLOW_CTRL_SAU_L_CH_R0,
384 #endif /* FLOW_CONTROL */
385     },
386     /* loader non secure need access to periph */
387     {
388         1,
389         (uint32_t)PERIPH_BASE_NS,
390         ((uint32_t)PERIPH_BASE_NS + 0x10000000),
391         TFM_FALSE,
392 #ifdef FLOW_CONTROL
393         FLOW_STEP_SAU_L_EN_R1,
394         FLOW_CTRL_SAU_L_EN_R1,
395         FLOW_STEP_SAU_L_CH_R1,
396         FLOW_CTRL_SAU_L_CH_R1,
397 #endif /* FLOW_CONTROL */
398     },
399     {
400         2,
401         ((uint32_t)FLASH_BASE_NS + NS_IMAGE_PRIMARY_PARTITION_OFFSET),
402 #if !defined(MCUBOOT_PRIMARY_ONLY)
403         ((uint32_t)FLASH_BASE_NS + S_IMAGE_SECONDARY_PARTITION_OFFSET + FLASH_PARTITION_SIZE),
404 #else
405         ((uint32_t)FLASH_BASE_NS + NS_IMAGE_PRIMARY_PARTITION_OFFSET + FLASH_NS_PARTITION_SIZE),
406 #endif /* MCUBOOT_PRIMARY_ONLY */
407         TFM_FALSE,
408 #ifdef FLOW_CONTROL
409         FLOW_STEP_SAU_L_EN_R2,
410         FLOW_CTRL_SAU_L_EN_R2,
411         FLOW_STEP_SAU_L_CH_R2,
412         FLOW_CTRL_SAU_L_CH_R2,
413 #endif /* FLOW_CONTROL */
414     },
415     /* allow access to non secure loader area code */
416     {
417         3,
418         (uint32_t)LOADER_NS_CODE_START,
419         (uint32_t)LOADER_NS_CODE_LIMIT + 1,
420         TFM_FALSE,
421 #ifdef FLOW_CONTROL
422         FLOW_STEP_SAU_L_EN_R3,
423         FLOW_CTRL_SAU_L_EN_R3,
424         FLOW_STEP_SAU_L_CH_R3,
425         FLOW_CTRL_SAU_L_CH_R3,
426 #endif /* FLOW_CONTROL */
427     },
428 #if defined(MCUBOOT_PRIMARY_ONLY)
429     /* allow access to non secure calleable area */
430     {
431         4,
432         (uint32_t)LOADER_CMSE_VENEER_REGION_START,
433         (uint32_t)LOADER_CMSE_VENEER_REGION_LIMIT + 1,
434         TFM_TRUE,
435 #ifdef FLOW_CONTROL
436         FLOW_STEP_SAU_L_EN_R4,
437         FLOW_CTRL_SAU_L_EN_R4,
438         FLOW_STEP_SAU_L_CH_R4,
439         FLOW_CTRL_SAU_L_CH_R4,
440 #endif /* FLOW_CONTROL */
441     }
442 #endif
443 };
444 #endif /*   MCUBOOT_EXT_LOADER */
445 
446 /**
447   * @}
448   */
449 /* Private function prototypes -----------------------------------------------*/
450 /** @defgroup TFM_SECURITY_Private_Functions  Private Functions
451   * @{
452   */
453 #ifdef TFM_OB_RDP_LEVEL_VALUE
454 static void rdp_level(uint32_t rdplevel, uint32_t current_rdplevel);
455 #endif /* TFM_OB_RDP_LEVEL_VALUE */
456 static void mpu_init_cfg(void);
457 static void mpu_appli_cfg(void);
458 static void flash_priv_cfg(void);
459 static void enable_hdp_protection(void);
460 static void lock_bl2_shared_area(void);
461 static void apply_wrp_sram2(uint32_t offset, uint32_t len);
462 #ifdef MCUBOOT_EXT_LOADER
463 static void mpu_loader_cfg(void);
464 static void sau_loader_cfg(void);
465 #if defined(MCUBOOT_EXT_LOADER) && defined(MCUBOOT_PRIMARY_ONLY)
466 static void secure_internal_flash(uint32_t offset_start, uint32_t offset_end);
467 #endif /* defined(MCUBOOT_EXT_LOADER) && defined(MCUBOOT_PRIMARY_ONLY) */
468 #endif /* MCUBOOT_EXT_LOADER */
469 static void active_tamper(void);
470 /**
471   * @}
472   */
473 
474 /** @defgroup TFM_SECURITY_Exported_Functions Exported Functions
475   * @{
476   */
477 #if defined(MCUBOOT_EXT_LOADER) && defined(MCUBOOT_PRIMARY_ONLY)
LL_SECU_SetLoaderCodeSecure(void)478 void LL_SECU_SetLoaderCodeSecure(void)
479 {
480     secure_internal_flash(FLASH_AREA_LOADER_OFFSET, FLASH_AREA_LOADER_OFFSET+LOADER_IMAGE_S_CODE_SIZE - 1);
481 }
482 /* Place code in a specific section */
483 #endif /* defined(MCUBOOT_EXT_LOADER) && defined(MCUBOOT_PRIMARY_ONLY) */
484 
485 #if defined(MCUBOOT_EXT_LOADER)
486 #if defined(__ICCARM__)
487 #pragma default_function_attributes = @ ".BL2_NoHdp_Code"
488 #else
489 __attribute__((section(".BL2_NoHdp_Code")))
490 #endif /* __ICCARM__ */
491 /**
492   * @brief  Update the runtime security protections for application start
493   *
494   * @param  None
495   * @retval None
496   */
LL_SECU_UpdateLoaderRunTimeProtections(void)497 void LL_SECU_UpdateLoaderRunTimeProtections(void)
498 {
499   /* Enable HDP protection to hide sensible boot material */
500   enable_hdp_protection();
501   /* Set MPU to enable execution of secure /non secure  loader */
502   mpu_loader_cfg();
503   /* reconfigure SAU to allow non secure execution */
504   sau_loader_cfg();
505 }
506 /* Stop placing data in specified section */
507 #if defined(__ICCARM__)
508 #pragma default_function_attributes =
509 #endif /* __ICCARM__ */
510 #endif /*MCUBOOT_EXT_LOADER*/
511 /**
512   * @brief  Apply the runtime security  protections to
513   *
514   * @param  None
515   * @note   By default, the best security protections are applied
516   * @retval None
517   */
LL_SECU_ApplyRunTimeProtections(void)518 void LL_SECU_ApplyRunTimeProtections(void)
519 {
520   /* Unsecure bottom of SRAM1 for error_handler */
521   gtzc_init_cfg();
522 
523   /* Set MPU to forbidd execution outside of not muteable code  */
524   /* Initialize not secure MPU to forbidd execution on Flash /SRAM */
525   mpu_init_cfg();
526 
527   /* Enable SAU to gain access to flash area non secure for write/read */
528   sau_and_idau_cfg();
529   /* With TFM_DEV_MODE , active tamper calls Error_Handler */
530   /* Error_Handler requires sau_and_idau_cfg */
531   active_tamper();
532   /* Lock top of SRAM2 in secure */
533   lock_bl2_shared_area();
534 
535   /* Configure Flash Privilege access */
536   flash_priv_cfg();
537 }
538 
539 /* Place code in a specific section */
540 #if defined(__ICCARM__)
541 #pragma default_function_attributes = @ ".BL2_NoHdp_Code"
542 #else
543 __attribute__((section(".BL2_NoHdp_Code")))
544 #endif /* __ICCARM__ */
545 
546 /**
547   * @brief  Update the runtime security protections for application start
548   *
549   * @param  None
550   * @retval None
551   */
LL_SECU_UpdateRunTimeProtections(void)552 void LL_SECU_UpdateRunTimeProtections(void)
553 {
554   /* Write Protect SRAM2 */
555   apply_wrp_sram2(BOOT_TFM_SHARED_DATA_BASE, BOOT_TFM_SHARED_DATA_SIZE);
556 
557   /* Enable HDP protection to hide sensible boot material */
558   enable_hdp_protection();
559 
560   /* Set MPU to enable execution of Secure and Non Secure active slots */
561   mpu_appli_cfg();
562 }
563 
564 /* Stop placing data in specified section */
565 #if defined(__ICCARM__)
566 #pragma default_function_attributes =
567 #endif /* __ICCARM__ */
568 
569 /**
570   * @brief  Check if the Static security  protections to
571   *         all the Sections in Flash:  WRP, SECURE FLASH, SECURE USER FLASH.
572   *         those protections not impacted by a Reset. They are set using the Option Bytes
573   *         When the device is locked (RDP Level2), these protections cannot be changed anymore
574   * @param  None
575   * @note   By default, the best security protections are applied to the different
576   *         flash sections in order to maximize the security level for the specific MCU.
577   * @retval None
578   */
LL_SECU_CheckStaticProtections(void)579 void LL_SECU_CheckStaticProtections(void)
580 {
581   static FLASH_OBProgramInitTypeDef flash_option_bytes_bank1 = {0};
582   static FLASH_OBProgramInitTypeDef flash_option_bytes_bank2 = {0};
583 #ifdef TFM_NSBOOT_CHECK_ENABLE
584   static FLASH_OBProgramInitTypeDef flash_option_bytes_nsboot0 = {0};
585   static FLASH_OBProgramInitTypeDef flash_option_bytes_nsboot1 = {0};
586 #endif /* TFM_NSBOOT_CHECK_ENABLE */
587 #ifdef TFM_ENABLE_SET_OB
588   HAL_StatusTypeDef ret = HAL_ERROR;
589 #endif  /* TFM_ENABLE_SET_OB  */
590   uint32_t start;
591   uint32_t end;
592 
593 #ifdef TFM_NSBOOT_CHECK_ENABLE
594   /* Get NSBOOTADD0 and NSBOOTADD1 value */
595   flash_option_bytes_nsboot0.BootAddrConfig = OB_BOOTADDR_NS0;
596   HAL_FLASHEx_OBGetConfig(&flash_option_bytes_nsboot0);
597   flash_option_bytes_nsboot1.BootAddrConfig = OB_BOOTADDR_NS1;
598   HAL_FLASHEx_OBGetConfig(&flash_option_bytes_nsboot1);
599 #endif /* TFM_NSBOOT_CHECK_ENABLE */
600 
601   /* Get bank1 areaA OB  */
602   flash_option_bytes_bank1.WRPArea = OB_WRPAREA_BANK1_AREAA;
603   flash_option_bytes_bank1.WMSecConfig = OB_WMSEC_AREA1;
604   flash_option_bytes_bank1.BootAddrConfig = OB_BOOTADDR_SEC0;
605   HAL_FLASHEx_OBGetConfig(&flash_option_bytes_bank1);
606 
607   /* Get bank2 areaB OB  */
608   flash_option_bytes_bank2.WRPArea = OB_WRPAREA_BANK2_AREAA;
609   flash_option_bytes_bank2.WMSecConfig = OB_WMSEC_AREA2;
610   HAL_FLASHEx_OBGetConfig(&flash_option_bytes_bank2);
611 
612 #ifdef TFM_ENABLE_SET_OB
613   /* Clean the option configuration */
614   flash_option_bytes_bank1.OptionType = 0;
615   flash_option_bytes_bank2.OptionType = 0;
616   flash_option_bytes_bank2.WRPArea = 0;
617   flash_option_bytes_bank1.WRPArea = 0;
618 #endif /*   TFM_ENABLE_SET_OB */
619 
620   /* Check TZEN = 1 , we are in secure */
621   if ((flash_option_bytes_bank1.USERConfig & FLASH_OPTR_TZEN) != FLASH_OPTR_TZEN)
622   {
623     BOOT_LOG_ERR("Unexpected value for TZEN");
624     Error_Handler();
625   }
626 
627   /* Check if dual bank is set */
628   if ((flash_option_bytes_bank1.USERConfig & FLASH_OPTR_DUALBANK) != FLASH_OPTR_DUALBANK)
629   {
630     BOOT_LOG_ERR("Unexpected value for dual bank configuration");
631     Error_Handler();
632   }
633 
634   /* Check if swap bank is reset */
635   if ((flash_option_bytes_bank1.USERConfig & FLASH_OPTR_SWAP_BANK) != 0)
636   {
637     BOOT_LOG_ERR("Unexpected value for swap bank configuration");
638     Error_Handler();
639   }
640 
641   /* Check secure boot address */
642   if (flash_option_bytes_bank1.BootAddr != BL2_BOOT_VTOR_ADDR)
643   {
644     BOOT_LOG_INF("BootAddr 0x%x", flash_option_bytes_bank1.BootAddr);
645     BOOT_LOG_ERR("Unexpected value for SEC BOOT Address");
646     Error_Handler();
647   }
648 
649 #ifdef TFM_NSBOOT_CHECK_ENABLE
650   /* Check non-secure boot addresses */
651   if ((flash_option_bytes_nsboot0.BootAddr != BL2_BOOT_VTOR_ADDR)
652       || (flash_option_bytes_nsboot1.BootAddr != BL2_BOOT_VTOR_ADDR))
653   {
654     BOOT_LOG_ERR("Unexpected value for NS BOOT Address");
655     Error_Handler();
656   }
657 #endif /* TFM_NSBOOT_CHECK_ENABLE */
658 
659   /* Check bank1 secure flash protection */
660   start = FLASH_AREA_SCRATCH_OFFSET / PAGE_SIZE;
661   end = (S_IMAGE_PRIMARY_PARTITION_OFFSET  + FLASH_S_PARTITION_SIZE - 1) / PAGE_SIZE;
662   if (end > PAGE_MAX_NUMBER_IN_BANK)
663   {
664     end = PAGE_MAX_NUMBER_IN_BANK;
665   }
666   if ((start != flash_option_bytes_bank1.WMSecStartPage)
667       || (end != flash_option_bytes_bank1.WMSecEndPage))
668   {
669     BOOT_LOG_INF("BANK 1 secure flash [%d, %d] : OB [%d, %d]",
670                  start, end, flash_option_bytes_bank1.WMSecStartPage, flash_option_bytes_bank1.WMSecEndPage);
671 #ifndef TFM_ENABLE_SET_OB
672     BOOT_LOG_ERR("Unexpected value for secure flash protection");
673     Error_Handler();
674 #else
675     BOOT_LOG_ERR("Unexpected value for secure flash protection: set wmsec1");
676     flash_option_bytes_bank1.WMSecStartPage = start;
677     flash_option_bytes_bank1.WMSecEndPage = end;
678     flash_option_bytes_bank1.OptionType |= OPTIONBYTE_WMSEC;
679     flash_option_bytes_bank1.WMSecConfig |= OB_WMSEC_AREA1 | OB_WMSEC_SECURE_AREA_CONFIG;
680 #endif /* TFM_ENABLE_SET_OB */
681   }
682 
683   /* Check bank2 secure flash protection */
684   start = 0;
685   end = (S_IMAGE_PRIMARY_PARTITION_OFFSET  + FLASH_S_PARTITION_SIZE - 1) / PAGE_SIZE;
686   if (end > PAGE_MAX_NUMBER_IN_BANK)
687   {
688     end = end - (PAGE_MAX_NUMBER_IN_BANK + 1);
689     if ((start != flash_option_bytes_bank2.WMSecStartPage)
690         || (end != flash_option_bytes_bank2.WMSecEndPage))
691     {
692     BOOT_LOG_INF("BANK 2 secure flash [%d, %d] : OB [%d, %d]", start, end, flash_option_bytes_bank2.WMSecStartPage,
693                    flash_option_bytes_bank2.WMSecEndPage);
694 #ifndef TFM_ENABLE_SET_OB
695     BOOT_LOG_ERR("Unexpected value for secure flash protection");
696     Error_Handler();
697 #else
698     BOOT_LOG_ERR("Unexpected value for secure flash protection : set wmsec2");
699     flash_option_bytes_bank2.WMSecStartPage = start;
700     flash_option_bytes_bank2.WMSecEndPage = end;
701     flash_option_bytes_bank2.OptionType = OPTIONBYTE_WMSEC;
702     flash_option_bytes_bank2.WMSecConfig |= OB_WMSEC_AREA2 | OB_WMSEC_SECURE_AREA_CONFIG ;
703 #endif /* TFM_ENABLE_SET_OB  */
704     }
705   }
706   /* the bank 2 must be fully unsecure */
707   else if (flash_option_bytes_bank2.WMSecEndPage >= flash_option_bytes_bank2.WMSecStartPage)
708   {
709     BOOT_LOG_INF("BANK 2 secure flash [%d, %d] : OB [%d, %d]", 127, 0, flash_option_bytes_bank2.WMSecStartPage,
710                  flash_option_bytes_bank2.WMSecEndPage);
711 #ifndef TFM_ENABLE_SET_OB
712     BOOT_LOG_ERR("Unexpected value for secure flash protection");
713     Error_Handler();
714 #else
715     /* bank is not unsecured , modify option bytes */
716     flash_option_bytes_bank2.WMSecStartPage = 127;
717     flash_option_bytes_bank2.WMSecEndPage = 0;
718     flash_option_bytes_bank2.OptionType = OPTIONBYTE_WMSEC;
719     flash_option_bytes_bank2.WMSecConfig |= OB_WMSEC_AREA2 | OB_WMSEC_SECURE_AREA_CONFIG ;
720 #endif /* TFM_ENABLE_SET_OB */
721   }
722 
723 #ifdef  TFM_WRP_PROTECT_ENABLE
724   /* Check flash write protection */
725   start = FLASH_AREA_PERSO_OFFSET / PAGE_SIZE;
726   end = (FLASH_AREA_PERSO_OFFSET + FLASH_AREA_PERSO_SIZE + FLASH_AREA_BL2_SIZE +
727          FLASH_AREA_BL2_NOHDP_SIZE - 1) / PAGE_SIZE;
728   if ((flash_option_bytes_bank1.WRPStartOffset > flash_option_bytes_bank1.WRPEndOffset)
729       || (start != flash_option_bytes_bank1.WRPStartOffset)
730       || (end != flash_option_bytes_bank1.WRPEndOffset))
731   {
732     BOOT_LOG_INF("BANK 1 flash write protection [%d, %d] : OB [%d, %d]", start, end,
733                  flash_option_bytes_bank1.WRPStartOffset,
734                  flash_option_bytes_bank1.WRPEndOffset);
735 #ifndef TFM_ENABLE_SET_OB
736     BOOT_LOG_ERR("Unexpected value for write protection ");
737     Error_Handler();
738 #else
739     flash_option_bytes_bank1.WRPStartOffset = start;
740     flash_option_bytes_bank1.WRPEndOffset = end;
741     flash_option_bytes_bank1.WRPArea |= OB_WRPAREA_BANK1_AREAA;
742 
743     BOOT_LOG_ERR("Unexpected value for write protection : set wrp1");
744     flash_option_bytes_bank1.OptionType |= OPTIONBYTE_WRP;
745 #endif /* TFM_ENABLE_SET_OB */
746   }
747 #if  defined(TFM_WRP_LOCK_ENABLE)
748   /* Check WRP lock protection */
749   if (flash_option_bytes_bank1.WRPLock != ENABLE)
750   {
751     BOOT_LOG_INF("BANK 1 WRP Lock 0x%x", flash_option_bytes_bank1.WRPLock);
752     BOOT_LOG_ERR("Unexpected value for WRP Lock");
753     Error_Handler();
754   }
755 #endif /* TFM_WRP_LOCK_ENABLE */
756 
757 #ifdef MCUBOOT_EXT_LOADER
758   /* Check flash write protection for local loader */
759   start = FLASH_AREA_LOADER_BANK_OFFSET / PAGE_SIZE;
760   end = (FLASH_B_SIZE - 1) / PAGE_SIZE;
761   if ((flash_option_bytes_bank2.WRPStartOffset > flash_option_bytes_bank2.WRPEndOffset)
762       || (start != flash_option_bytes_bank2.WRPStartOffset)
763       || (end != flash_option_bytes_bank2.WRPEndOffset))
764   {
765     BOOT_LOG_INF("BANK 2 flash write protection [%d, %d] : OB [%d, %d]", start, end,
766                  flash_option_bytes_bank2.WRPStartOffset,
767                  flash_option_bytes_bank2.WRPEndOffset);
768 #ifndef TFM_ENABLE_SET_OB
769     BOOT_LOG_ERR("Unexpected value for write protection ");
770     Error_Handler();
771 #else
772     flash_option_bytes_bank2.WRPStartOffset = start;
773     flash_option_bytes_bank2.WRPEndOffset = end;
774     flash_option_bytes_bank2.WRPArea |= OB_WRPAREA_BANK2_AREAA;
775 
776     BOOT_LOG_ERR("Unexpected value for write protection : set wrp2");
777     flash_option_bytes_bank2.OptionType |= OPTIONBYTE_WRP;
778 #endif /* TFM_ENABLE_SET_OB */
779   }
780 #if  defined(TFM_WRP_LOCK_ENABLE)
781   /* Check WRP lock protection */
782   if (flash_option_bytes_bank2.WRPLock != ENABLE)
783   {
784     BOOT_LOG_INF("BANK 2 WRP Lock 0x%x", flash_option_bytes_bank2.WRPLock);
785     BOOT_LOG_ERR("Unexpected value for WRP Lock");
786     Error_Handler();
787   }
788 #endif /* TFM_WRP_LOCK_ENABLE */
789 #endif /* MCUBOOT_EXT_LOADER */
790 #endif /* TFM_WRP_PROTECT_ENABLE */
791 
792 #ifdef  TFM_HDP_PROTECT_ENABLE
793   /* Check secure user flash protection (HDP) */
794   start = FLASH_BL2_NVCNT_AREA_OFFSET / PAGE_SIZE;
795   end = (FLASH_BL2_HDP_END) / PAGE_SIZE;
796   if (
797     (flash_option_bytes_bank1.WMSecStartPage > flash_option_bytes_bank1.WMHDPEndPage)
798     || (start < flash_option_bytes_bank1.WMSecStartPage)
799     || (end > flash_option_bytes_bank1.WMHDPEndPage)
800     || (flash_option_bytes_bank1.WMSecConfig & OB_WMSEC_HDP_AREA_DISABLE))
801   {
802     BOOT_LOG_INF("BANK 1 secure user flash [%d, %d] : OB [%d, %d]",
803                  start,
804                  end,
805                  flash_option_bytes_bank1.WMSecStartPage,
806                  flash_option_bytes_bank1.WMHDPEndPage);
807 #ifndef TFM_ENABLE_SET_OB
808     BOOT_LOG_ERR("Unexpected value for secure user flash protection");
809     Error_Handler();
810 #else
811     BOOT_LOG_ERR("Unexpected value for secure user flash protection : set hdp1");
812     flash_option_bytes_bank1.WMSecStartPage = start;
813     flash_option_bytes_bank1.WMHDPEndPage = end;
814     flash_option_bytes_bank1.OptionType |= OPTIONBYTE_WMSEC;
815     /*  clean disable */
816     flash_option_bytes_bank1.WMSecConfig &= ~OB_WMSEC_HDP_AREA_DISABLE;
817     /* enable */
818     flash_option_bytes_bank1.WMSecConfig |= OB_WMSEC_HDP_AREA_CONFIG ;
819     flash_option_bytes_bank1.WMSecConfig |= OB_WMSEC_HDP_AREA_ENABLE;
820     flash_option_bytes_bank1.WMSecConfig |= OB_WMSEC_AREA1;
821 #endif  /*  TFM_ENABLE_SET_OB */
822   }
823 #else /* TFM_HDP_PROTECT_ENABLE */
824   flash_option_bytes_bank1.WMSecConfig &= ~(OB_WMSEC_HDP_AREA_CONFIG | OB_WMSEC_HDP_AREA_ENABLE);
825   flash_option_bytes_bank1.WMSecConfig |= OB_WMSEC_HDP_AREA_DISABLE;
826 #endif /* TFM_HDP_PROTECT_ENABLE */
827 
828 #ifdef TFM_SECURE_USER_SRAM2_ERASE_AT_RESET
829   /* Check SRAM2 ERASE on reset */
830   if ((flash_option_bytes_bank1.USERConfig & FLASH_OPTR_SRAM2_RST) != 0)
831   {
832     BOOT_LOG_ERR("Unexpected value for SRAM2 ERASE at Reset");
833     Error_Handler();
834   }
835 #endif /*TFM_SECURE_USER_SRAM2_ERASE_AT_RESET */
836 
837 #ifdef TFM_ENABLE_SET_OB
838   /* Configure Options Bytes */
839   if ((flash_option_bytes_bank1.OptionType != 0) || (flash_option_bytes_bank2.OptionType != 0))
840   {
841     /* Unlock the Flash to enable the flash control register access */
842     HAL_FLASH_Unlock();
843 
844     /* Unlock the Options Bytes */
845     HAL_FLASH_OB_Unlock();
846 
847     /* Verify Options Bytes to configure */
848     if ((flash_option_bytes_bank1.OptionType & OPTIONBYTE_RDP) != 0)
849     {
850       BOOT_LOG_ERR("Unexpected value for OB RDP to program");
851       Error_Handler();
852     }
853     if ((flash_option_bytes_bank2.OptionType & OPTIONBYTE_RDP) != 0)
854     {
855       BOOT_LOG_ERR("Unexpected value for OB RDP to program");
856       Error_Handler();
857     }
858 #ifdef MCUBOOT_EXT_LOADER
859     if ((flash_option_bytes_bank2.WRPArea & ~OB_WRPAREA_BANK2_AREAA) != 0)
860 #else
861     if ((flash_option_bytes_bank2.WRPArea & ~OB_WRPAREA_BANK2_AREAA) != 0)
862 #endif
863     {
864       BOOT_LOG_ERR("Unexpected value for bank 2 OB WRP AREA to program");
865       Error_Handler();
866     }
867     if ((flash_option_bytes_bank1.WRPArea & ~OB_WRPAREA_BANK1_AREAA) != 0)
868     {
869       BOOT_LOG_ERR("Unexpected value for bank 1 OB WRP AREA to program");
870       Error_Handler();
871     }
872     if ((flash_option_bytes_bank1.OptionType) != 0)
873     {
874       /* Program the Options Bytes */
875       ret = HAL_FLASHEx_OBProgram(&flash_option_bytes_bank1);
876       if (ret != HAL_OK)
877       {
878         BOOT_LOG_ERR("Error while setting OB Bank1 config");
879         Error_Handler();
880       }
881     }
882     if ((flash_option_bytes_bank2.OptionType) != 0)
883     {
884       /* Program the Options Bytes */
885       ret = HAL_FLASHEx_OBProgram(&flash_option_bytes_bank2);
886       if (ret != HAL_OK)
887       {
888         BOOT_LOG_ERR("Error while setting OB Bank1 config");
889         Error_Handler();
890       }
891     }
892 
893     /* Launch the Options Bytes (reset the board, should not return) */
894     ret = HAL_FLASH_OB_Launch();
895     if (ret != HAL_OK)
896     {
897       BOOT_LOG_ERR("Error while execution OB_Launch");
898       Error_Handler();
899     }
900 
901     /* Code should not be reached, reset the board */
902     HAL_NVIC_SystemReset();
903   }
904 #endif /* TFM_ENABLE_SET_OB */
905 
906 #ifdef TFM_OB_BOOT_LOCK
907   /* Check Boot lock protection */
908   if (flash_option_bytes_bank1.BootLock != TFM_OB_BOOT_LOCK)
909   {
910     BOOT_LOG_INF("BootLock 0x%x", flash_option_bytes_bank1.BootLock);
911     BOOT_LOG_ERR("Unexpected value for SEC BOOT LOCK");
912     Error_Handler();
913   }
914 #endif /* TFM_OB_BOOT_LOCK */
915 
916 #ifdef TFM_OB_RDP_LEVEL_VALUE
917   /* Check RDL level : boot if current RDP level is greater or equal to selected RDP level */
918   switch (TFM_OB_RDP_LEVEL_VALUE)
919   {
920     case OB_RDP_LEVEL_2:
921       if (flash_option_bytes_bank1.RDPLevel != OB_RDP_LEVEL_2)
922       {
923         rdp_level(TFM_OB_RDP_LEVEL_VALUE, flash_option_bytes_bank1.RDPLevel);
924         Error_Handler_rdp();
925       }
926       break;
927 
928     case OB_RDP_LEVEL_1:
929       if ((flash_option_bytes_bank1.RDPLevel != OB_RDP_LEVEL_2) &&
930           (flash_option_bytes_bank1.RDPLevel != OB_RDP_LEVEL_1))
931       {
932         rdp_level(TFM_OB_RDP_LEVEL_VALUE, flash_option_bytes_bank1.RDPLevel);
933         Error_Handler_rdp();
934       }
935       break;
936 
937     case OB_RDP_LEVEL_0_5:
938       if ((flash_option_bytes_bank1.RDPLevel != OB_RDP_LEVEL_2) &&
939           (flash_option_bytes_bank1.RDPLevel != OB_RDP_LEVEL_1) &&
940           (flash_option_bytes_bank1.RDPLevel != OB_RDP_LEVEL_0_5))
941       {
942         rdp_level(TFM_OB_RDP_LEVEL_VALUE, flash_option_bytes_bank1.RDPLevel);
943         Error_Handler_rdp();
944       }
945       break;
946 
947     case OB_RDP_LEVEL_0:
948       break;
949 
950     default:
951       Error_Handler();
952       break;
953   }
954 #endif /* TFM_OB_RDP_LEVEL_VALUE */
955 }
956 
957 #ifdef TFM_OB_RDP_LEVEL_VALUE
rdp_level(uint32_t rdplevel,uint32_t current_rdplevel)958 static void rdp_level(uint32_t rdplevel, uint32_t current_rdplevel)
959 {
960   BOOT_LOG_INF("RDPLevel 0x%x (0x%x)", current_rdplevel, rdplevel);
961   BOOT_LOG_ERR("Unexpected value for RDP level");
962 
963 #ifdef TFM_ENABLE_SET_OB
964   static FLASH_OBProgramInitTypeDef flash_option_bytes_bank = {0};
965   HAL_StatusTypeDef ret = HAL_ERROR;
966 
967   /* Automatic programming to RDP 2 is not allowed */
968   if (rdplevel == OB_RDP_LEVEL_2)
969   {
970     Error_Handler();
971   }
972 
973   flash_option_bytes_bank.OptionType = OPTIONBYTE_RDP;
974   flash_option_bytes_bank.RDPLevel = rdplevel;
975   BOOT_LOG_INF("Programming RDP to %x", rdplevel);
976   BOOT_LOG_INF("Unplug/Plug jumper JP3 (IDD)");
977 
978   /* Unlock the Flash to enable the flash control register access */
979   HAL_FLASH_Unlock();
980 
981   /* Unlock the Options Bytes */
982   HAL_FLASH_OB_Unlock();
983 
984   /* Program the Options Bytes */
985   ret = HAL_FLASHEx_OBProgram(&flash_option_bytes_bank);
986   if (ret != HAL_OK)
987   {
988     BOOT_LOG_ERR("Error while setting RDP level");
989     Error_Handler();
990   }
991 
992   /* Launch the Options Bytes (reset the board, should not return) */
993   ret = HAL_FLASH_OB_Launch();
994   if (ret != HAL_OK)
995   {
996     BOOT_LOG_ERR("Error while execution OB_Launch");
997     Error_Handler();
998   }
999 
1000   /* Code should not be reached, reset the board */
1001   HAL_NVIC_SystemReset();
1002 #endif /* TFM_ENABLE_SET_OB */
1003 }
1004 #endif /* TFM_OB_RDP_LEVEL_VALUE */
1005 #if defined(MCUBOOT_EXT_LOADER) && defined(MCUBOOT_PRIMARY_ONLY)
secure_internal_flash(uint32_t offset_start,uint32_t offset_end)1006 static void secure_internal_flash(uint32_t offset_start, uint32_t offset_end)
1007 {
1008     volatile uint32_t *SecBB[8]= {&FLASH_S->SECBB1R1, &FLASH_S->SECBB1R2, &FLASH_S->SECBB1R3, &FLASH_S->SECBB1R4,
1009       &FLASH_S->SECBB2R1, &FLASH_S->SECBB2R2, &FLASH_S->SECBB2R3, &FLASH_S->SECBB2R4};
1010     volatile uint32_t *ptr;
1011     uint32_t regwrite=0x0, index;
1012     uint32_t block_start = offset_start;
1013     uint32_t block_end =  offset_end;
1014     block_start = block_start / PAGE_SIZE;
1015     block_end = (block_end / PAGE_SIZE) ;
1016     /* Check alignment to avoid further problem  */
1017     if (offset_start & (PAGE_SIZE-1))
1018         Error_Handler();
1019 
1020     /* configuration stage */
1021     if (uFlowStage == FLOW_STAGE_CFG)
1022     {
1023       /* 1f is for 32 bits */
1024       for (index = block_start & ~0x1f; index < (8<<5) ; index++)
1025       { /* clean register on index aligned */
1026         if (!(index & 0x1f)){
1027            regwrite=0x0;
1028         }
1029         if ((index >= block_start) && (index <= block_end))
1030           regwrite = regwrite | ( 1 << (index & 0x1f));
1031         /* write register when 32 sub block are set or last block to set  */
1032         if ((index & 0x1f ) == 0x1f) {
1033           ptr = (uint32_t *)SecBB[index>>5];
1034           *ptr = regwrite;
1035         }
1036       }
1037       FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_FLASH_S_L_EN, FLOW_CTRL_FLASH_S_L_EN);
1038     }
1039     /* verification stage */
1040     else
1041     {
1042       /*  1f is for 32 bits */
1043       for (index = block_start & ~0x1f; index < (8<<5) ; index++)
1044       { /* clean register on index aligned */
1045         if (!(index & 0x1f)){
1046            regwrite=0x0;
1047         }
1048         if ((index >= block_start) && (index <= block_end))
1049           regwrite = regwrite | ( 1 << (index & 0x1f));
1050         /* write register when 32 sub block are set or last block to set  */
1051         if ((index & 0x1f ) == 0x1f) {
1052           ptr = (uint32_t *)SecBB[index>>5];
1053           if (*ptr != regwrite)
1054           {
1055             Error_Handler();
1056           }
1057         }
1058       }
1059       FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_FLASH_S_L_CH, FLOW_CTRL_FLASH_S_L_CH);
1060     }
1061 }
1062 #endif /* defined(MCUBOOT_EXT_LOADER) && defined(MCUBOOT_PRIMARY_ONLY)  */
1063 /**
1064   * @brief  Memory Config Init
1065   * @param  None
1066   * @retval None
1067   */
gtzc_init_cfg(void)1068 void  gtzc_init_cfg(void)
1069 {
1070    __HAL_RCC_GTZC1_CLK_ENABLE();
1071 #ifdef TFM_ERROR_HANDLER_NON_SECURE
1072   /*  unsecure only one block in SRAM1 */
1073   GTZC_MPCBB1_S->SECCFGR[0] = 0xfffffffe;
1074 #endif /*  TFM_ERROR_HANDLER_NON_SECURE */
1075 
1076 }
1077 
1078 /**
1079   * @brief  Sau idau init
1080   * @param  None
1081   * @retval None
1082   */
sau_and_idau_cfg(void)1083 void sau_and_idau_cfg(void)
1084 {
1085   uint32_t i;
1086   uint32_t rnr;
1087   uint32_t rbar;
1088   uint32_t rlar;
1089   uint32_t rnr_reg;
1090   uint32_t rbar_reg;
1091   uint32_t rlar_reg;
1092   uint32_t ctrl_reg;
1093 
1094   /* configuration stage */
1095   if (uFlowStage == FLOW_STAGE_CFG)
1096   {
1097     /* Disable SAU */
1098     TZ_SAU_Disable();
1099 
1100     for (i = 0; i < ARRAY_SIZE(sau_init_cfg); i++)
1101     {
1102       SAU->RNR = sau_init_cfg[i].RNR;
1103       SAU->RBAR = sau_init_cfg[i].RBAR & SAU_RBAR_BADDR_Msk;
1104       SAU->RLAR = (sau_init_cfg[i].RLAR & SAU_RLAR_LADDR_Msk) |
1105                   (sau_init_cfg[i].nsc ? SAU_RLAR_NSC_Msk : 0U) |
1106                   SAU_RLAR_ENABLE_Msk;
1107 
1108       /* Execution stopped if flow control failed */
1109       FLOW_CONTROL_STEP(uFlowProtectValue, sau_init_cfg[i].flow_step_enable,
1110                                            sau_init_cfg[i].flow_ctrl_enable);
1111     }
1112 
1113     /* Force memory writes before continuing */
1114     __DSB();
1115     /* Flush and refill pipeline with updated permissions */
1116     __ISB();
1117     /* Enable SAU */
1118     TZ_SAU_Enable();
1119 
1120     /* Execution stopped if flow control failed */
1121     FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_SAU_I_EN, FLOW_CTRL_SAU_I_EN);
1122   }
1123   /* verification stage */
1124   else
1125   {
1126     for (i = 0; i < ARRAY_SIZE(sau_init_cfg); i++)
1127     {
1128       SAU->RNR = sau_init_cfg[i].RNR;
1129 
1130       rnr = sau_init_cfg[i].RNR;
1131       rbar = sau_init_cfg[i].RBAR & SAU_RBAR_BADDR_Msk;
1132       rlar = (sau_init_cfg[i].RLAR & SAU_RLAR_LADDR_Msk) |
1133                   (sau_init_cfg[i].nsc ? SAU_RLAR_NSC_Msk : 0U) |
1134                   SAU_RLAR_ENABLE_Msk;
1135 
1136       rnr_reg = SAU->RNR;
1137       rbar_reg = SAU->RBAR;
1138       rlar_reg = SAU->RLAR;
1139 
1140       if ((rnr_reg != rnr) || (rbar_reg != rbar) || (rlar_reg != rlar))
1141       {
1142         Error_Handler();
1143       }
1144 
1145       /* Execution stopped if flow control failed */
1146       FLOW_CONTROL_STEP(uFlowProtectValue, sau_init_cfg[i].flow_step_check,
1147                                            sau_init_cfg[i].flow_ctrl_check);
1148     }
1149 
1150     ctrl_reg = SAU->CTRL;
1151     if ((ctrl_reg && SAU_CTRL_ENABLE_Msk) != 1U)
1152     {
1153       Error_Handler();
1154     }
1155     else
1156     {
1157       /* Execution stopped if flow control failed */
1158       FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_SAU_I_CH, FLOW_CTRL_SAU_I_CH);
1159     }
1160   }
1161 }
1162 
1163 #ifdef MCUBOOT_EXT_LOADER
1164 #if defined(__ICCARM__)
1165 #pragma default_function_attributes = @ ".BL2_NoHdp_Code"
1166 #else
1167 __attribute__((section(".BL2_NoHdp_Code")))
1168 #endif /* __ICCARM__ */
1169 /**
1170   * @brief  Sau idau update for executing loader
1171   * @param  None
1172   * @retval None
1173   */
sau_loader_cfg(void)1174 static void sau_loader_cfg(void)
1175 {
1176   uint32_t i;
1177   uint32_t rnr;
1178   uint32_t rbar;
1179   uint32_t rlar;
1180   uint32_t rnr_reg;
1181   uint32_t rbar_reg;
1182   uint32_t rlar_reg;
1183   uint32_t ctrl_reg;
1184 
1185   /* configuration stage */
1186   if (uFlowStage == FLOW_STAGE_CFG)
1187   {
1188     /* Disable SAU */
1189     TZ_SAU_Disable();
1190 
1191     for (i = 0; i < ARRAY_SIZE(sau_load_cfg); i++)
1192     {
1193       SAU->RNR = sau_load_cfg[i].RNR;
1194       SAU->RBAR = sau_load_cfg[i].RBAR & SAU_RBAR_BADDR_Msk;
1195       SAU->RLAR = (sau_load_cfg[i].RLAR & SAU_RLAR_LADDR_Msk) |
1196                   (sau_load_cfg[i].nsc ? SAU_RLAR_NSC_Msk : 0U) |
1197                   SAU_RLAR_ENABLE_Msk;
1198 
1199       /* Execution stopped if flow control failed */
1200       FLOW_CONTROL_STEP(uFlowProtectValue, sau_load_cfg[i].flow_step_enable,
1201                                            sau_load_cfg[i].flow_ctrl_enable);
1202     }
1203 
1204     /* Force memory writes before continuing */
1205     __DSB();
1206     /* Flush and refill pipeline with updated permissions */
1207     __ISB();
1208     /* Enable SAU */
1209     TZ_SAU_Enable();
1210 
1211     /* Execution stopped if flow control failed */
1212     FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_SAU_L_EN, FLOW_CTRL_SAU_L_EN);
1213   }
1214   /* verification stage */
1215   else
1216   {
1217     for (i = 0; i < ARRAY_SIZE(sau_load_cfg); i++)
1218     {
1219       SAU->RNR = sau_load_cfg[i].RNR;
1220 
1221       rnr = sau_load_cfg[i].RNR;
1222       rbar = sau_load_cfg[i].RBAR & SAU_RBAR_BADDR_Msk;
1223       rlar = (sau_load_cfg[i].RLAR & SAU_RLAR_LADDR_Msk) |
1224                   (sau_load_cfg[i].nsc ? SAU_RLAR_NSC_Msk : 0U) |
1225                   SAU_RLAR_ENABLE_Msk;
1226 
1227       rnr_reg = SAU->RNR;
1228       rbar_reg = SAU->RBAR;
1229       rlar_reg = SAU->RLAR;
1230 
1231       if ((rnr_reg != rnr) || (rbar_reg != rbar) || (rlar_reg != rlar))
1232       {
1233         Error_Handler();
1234       }
1235 
1236       /* Execution stopped if flow control failed */
1237       FLOW_CONTROL_STEP(uFlowProtectValue, sau_load_cfg[i].flow_step_check,
1238                                            sau_load_cfg[i].flow_ctrl_check);
1239     }
1240 
1241     ctrl_reg = SAU->CTRL;
1242     if ((ctrl_reg && SAU_CTRL_ENABLE_Msk) != 1U)
1243     {
1244       Error_Handler();
1245     }
1246     else
1247     {
1248       /* Execution stopped if flow control failed */
1249       FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_SAU_L_CH, FLOW_CTRL_SAU_L_CH);
1250     }
1251 
1252 /* FIX ME to INDENT better */
1253 #if 1
1254    /* set up floating point */
1255 /*
1256 // <e>Setup behaviour of Floating Point Unit
1257 */
1258 #define TZ_FPU_NS_USAGE 1
1259 
1260 /*
1261 // <o>Floating Point Unit usage
1262 //     <0=> Secure state only
1263 //     <3=> Secure and Non-Secure state
1264 //   <i> Value for SCB->NSACR register bits CP10, CP11
1265 */
1266 #define SCB_NSACR_CP10_11_VAL       3
1267 
1268 /*
1269 // <o>Treat floating-point registers as Secure
1270 //     <0=> Disabled
1271 //     <1=> Enabled
1272 //   <i> Value for FPU->FPCCR register bit TS
1273 */
1274 #define FPU_FPCCR_TS_VAL            0
1275 
1276 /*
1277 // <o>Clear on return (CLRONRET) accessibility
1278 //     <0=> Secure and Non-Secure state
1279 //     <1=> Secure state only
1280 //   <i> Value for FPU->FPCCR register bit CLRONRETS
1281 */
1282 #define FPU_FPCCR_CLRONRETS_VAL     0
1283 
1284 /*
1285 // <o>Clear floating-point caller saved registers on exception return
1286 //     <0=> Disabled
1287 //     <1=> Enabled
1288 //   <i> Value for FPU->FPCCR register bit CLRONRET
1289 */
1290 #define FPU_FPCCR_CLRONRET_VAL      1
1291     SCB->NSACR = (SCB->NSACR & ~(SCB_NSACR_CP10_Msk | SCB_NSACR_CP11_Msk)) |
1292                    ((SCB_NSACR_CP10_11_VAL << SCB_NSACR_CP10_Pos) & (SCB_NSACR_CP10_Msk | SCB_NSACR_CP11_Msk));
1293 
1294     FPU->FPCCR = (FPU->FPCCR & ~(FPU_FPCCR_TS_Msk | FPU_FPCCR_CLRONRETS_Msk | FPU_FPCCR_CLRONRET_Msk)) |
1295                    ((FPU_FPCCR_TS_VAL        << FPU_FPCCR_TS_Pos       ) & FPU_FPCCR_TS_Msk       ) |
1296                    ((FPU_FPCCR_CLRONRETS_VAL << FPU_FPCCR_CLRONRETS_Pos) & FPU_FPCCR_CLRONRETS_Msk) |
1297                    ((FPU_FPCCR_CLRONRET_VAL  << FPU_FPCCR_CLRONRET_Pos ) & FPU_FPCCR_CLRONRET_Msk );
1298     /* Lock SAU config */
1299     __HAL_RCC_SYSCFG_CLK_ENABLE();
1300     SYSCFG->CSLCKR |= SYSCFG_CSLCKR_LOCKSAU;
1301 #endif
1302   }
1303 }
1304 /* Stop placing data in specified section */
1305 #if defined(__ICCARM__)
1306 #pragma default_function_attributes =
1307 #endif /* __ICCARM__ */
1308 #endif /* MCUBOOT_EXT_LOADER */
1309 /**
1310   * @brief  mpu init
1311   * @param  None
1312   * @retval None
1313   */
mpu_init_cfg(void)1314 static void mpu_init_cfg(void)
1315 {
1316 #ifdef TFM_BOOT_MPU_PROTECTION
1317   struct mpu_armv8m_dev_t dev_mpu_s = { MPU_BASE };
1318   struct mpu_armv8m_dev_t dev_mpu_ns = { MPU_BASE_NS };
1319   int32_t i;
1320 
1321   /* configuration stage */
1322   if (uFlowStage == FLOW_STAGE_CFG)
1323   {
1324     /* configure secure MPU regions */
1325     for (i = 0; i < ARRAY_SIZE(region_cfg_init_s); i++)
1326     {
1327       if (mpu_armv8m_region_enable(&dev_mpu_s,
1328         (struct mpu_armv8m_region_cfg_t *)&region_cfg_init_s[i]) != MPU_ARMV8M_OK)
1329       {
1330         Error_Handler();
1331       }
1332       else
1333       {
1334         /* Execution stopped if flow control failed */
1335         FLOW_CONTROL_STEP(uFlowProtectValue, region_cfg_init_s[i].flow_step_enable,
1336                                              region_cfg_init_s[i].flow_ctrl_enable);
1337       }
1338     }
1339 
1340     /* enable secure MPU */
1341     mpu_armv8m_enable(&dev_mpu_s, PRIVILEGED_DEFAULT_ENABLE, HARDFAULT_NMI_ENABLE);
1342     FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_MPU_S_I_EN, FLOW_CTRL_MPU_S_I_EN);
1343 
1344     /* configure non secure MPU regions */
1345     for (i = 0; i < ARRAY_SIZE(region_cfg_init_ns); i++)
1346     {
1347       if (mpu_armv8m_region_enable(&dev_mpu_ns,
1348         (struct mpu_armv8m_region_cfg_t *)&region_cfg_init_ns[i]) != MPU_ARMV8M_OK)
1349       {
1350         Error_Handler();
1351       }
1352       else
1353       {
1354         /* Execution stopped if flow control failed */
1355         FLOW_CONTROL_STEP(uFlowProtectValue, region_cfg_init_ns[i].flow_step_enable,
1356                                              region_cfg_init_ns[i].flow_ctrl_enable);
1357       }
1358     }
1359 
1360     /* enable non secure MPU */
1361     mpu_armv8m_enable(&dev_mpu_ns, PRIVILEGED_DEFAULT_ENABLE, HARDFAULT_NMI_ENABLE);
1362     FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_MPU_NS_I_EN, FLOW_CTRL_MPU_NS_I_EN);
1363   }
1364   /* verification stage */
1365   else
1366   {
1367     /* check secure MPU regions */
1368     for (i = 0; i < ARRAY_SIZE(region_cfg_init_s); i++)
1369     {
1370       if (mpu_armv8m_region_enable_check(&dev_mpu_s,
1371         (struct mpu_armv8m_region_cfg_t *)&region_cfg_init_s[i]) != MPU_ARMV8M_OK)
1372       {
1373         Error_Handler();
1374       }
1375       else
1376       {
1377         /* Execution stopped if flow control failed */
1378         FLOW_CONTROL_STEP(uFlowProtectValue, region_cfg_init_s[i].flow_step_check,
1379                                              region_cfg_init_s[i].flow_ctrl_check);
1380       }
1381     }
1382 
1383     /* check secure MPU */
1384     if (mpu_armv8m_check(&dev_mpu_s, PRIVILEGED_DEFAULT_ENABLE,
1385                       HARDFAULT_NMI_ENABLE) != MPU_ARMV8M_OK)
1386     {
1387       Error_Handler();
1388     }
1389     else
1390     {
1391       /* Execution stopped if flow control failed */
1392       FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_MPU_S_I_CH, FLOW_CTRL_MPU_S_I_CH);
1393     }
1394 
1395     /* check non secure MPU regions */
1396     for (i = 0; i < ARRAY_SIZE(region_cfg_init_ns); i++)
1397     {
1398       if (mpu_armv8m_region_enable_check(&dev_mpu_ns,
1399         (struct mpu_armv8m_region_cfg_t *)&region_cfg_init_ns[i]) != MPU_ARMV8M_OK)
1400       {
1401         Error_Handler();
1402       }
1403       else
1404       {
1405         /* Execution stopped if flow control failed */
1406         FLOW_CONTROL_STEP(uFlowProtectValue, region_cfg_init_ns[i].flow_step_check,
1407                                              region_cfg_init_ns[i].flow_ctrl_check);
1408       }
1409     }
1410 
1411     /* check non secure MPU */
1412     if (mpu_armv8m_check(&dev_mpu_ns, PRIVILEGED_DEFAULT_ENABLE,
1413                       HARDFAULT_NMI_ENABLE) != MPU_ARMV8M_OK)
1414     {
1415       Error_Handler();
1416     }
1417     else
1418     {
1419       /* Execution stopped if flow control failed */
1420       FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_MPU_NS_I_CH, FLOW_CTRL_MPU_NS_I_CH);
1421     }
1422   }
1423 #endif /* TFM_BOOT_MPU_PROTECTION */
1424 }
1425 
1426 /* Place code in a specific section */
1427 #if defined(__ICCARM__)
1428 #pragma default_function_attributes = @ ".BL2_NoHdp_Code"
1429 #else
1430 __attribute__((section(".BL2_NoHdp_Code")))
1431 #endif /* __ICCARM__ */
1432 
mpu_appli_cfg(void)1433 static void mpu_appli_cfg(void)
1434 {
1435 #ifdef TFM_BOOT_MPU_PROTECTION
1436   static struct mpu_armv8m_dev_t dev_mpu_s = { MPU_BASE };
1437   static struct mpu_armv8m_dev_t dev_mpu_ns = { MPU_BASE_NS };
1438   int32_t i;
1439 
1440   /* configuration stage */
1441   if (uFlowStage == FLOW_STAGE_CFG)
1442   {
1443     /* configure secure MPU regions */
1444     for (i = 0; i < ARRAY_SIZE(region_cfg_appli_s); i++)
1445     {
1446       if (mpu_armv8m_region_enable(&dev_mpu_s,
1447         (struct mpu_armv8m_region_cfg_t *)&region_cfg_appli_s[i]) != MPU_ARMV8M_OK)
1448       {
1449         Error_Handler();
1450       }
1451       else
1452       {
1453         /* Execution stopped if flow control failed */
1454         FLOW_CONTROL_STEP(uFlowProtectValue, region_cfg_appli_s[i].flow_step_enable,
1455                                              region_cfg_appli_s[i].flow_ctrl_enable);
1456       }
1457     }
1458 
1459     /* configure non secure MPU regions */
1460     for (i = 0; i < ARRAY_SIZE(region_cfg_appli_ns); i++)
1461     {
1462 
1463       if (mpu_armv8m_region_enable(&dev_mpu_ns,
1464         (struct mpu_armv8m_region_cfg_t *)&region_cfg_appli_ns[i]) != MPU_ARMV8M_OK)
1465       {
1466         Error_Handler();
1467       }
1468       else
1469       {
1470         /* Execution stopped if flow control failed */
1471         FLOW_CONTROL_STEP(uFlowProtectValue, region_cfg_appli_ns[i].flow_step_enable,
1472                                              region_cfg_appli_ns[i].flow_ctrl_enable);
1473       }
1474 
1475     }
1476   }
1477   else
1478   {
1479     /* check secure MPU regions */
1480     for (i = 0; i < ARRAY_SIZE(region_cfg_appli_s); i++)
1481     {
1482       if (mpu_armv8m_region_enable_check(&dev_mpu_s,
1483         (struct mpu_armv8m_region_cfg_t *)&region_cfg_appli_s[i]) != MPU_ARMV8M_OK)
1484       {
1485         Error_Handler();
1486       }
1487       else
1488       {
1489         /* Execution stopped if flow control failed */
1490         FLOW_CONTROL_STEP(uFlowProtectValue, region_cfg_appli_s[i].flow_step_check,
1491                                              region_cfg_appli_s[i].flow_ctrl_check);
1492       }
1493     }
1494 
1495     /* check non secure MPU regions */
1496     for (i = 0; i < ARRAY_SIZE(region_cfg_appli_ns); i++)
1497     {
1498       if (mpu_armv8m_region_enable_check(&dev_mpu_ns,
1499         (struct mpu_armv8m_region_cfg_t *)&region_cfg_appli_ns[i]) != MPU_ARMV8M_OK)
1500       {
1501         Error_Handler();
1502       }
1503       else
1504       {
1505         /* Execution stopped if flow control failed */
1506         FLOW_CONTROL_STEP(uFlowProtectValue, region_cfg_appli_ns[i].flow_step_check,
1507                                              region_cfg_appli_ns[i].flow_ctrl_check);
1508       }
1509     }
1510   }
1511 #endif /* TFM_BOOT_MPU_PROTECTION */
1512 }
1513 /* Stop placing data in specified section */
1514 #if defined(__ICCARM__)
1515 #pragma default_function_attributes =
1516 #endif /* __ICCARM__ */
1517 
1518 #ifdef MCUBOOT_EXT_LOADER
1519 /* Place code in a specific section */
1520 #if defined(__ICCARM__)
1521 #pragma default_function_attributes = @ ".BL2_NoHdp_Code"
1522 #else
1523 __attribute__((section(".BL2_NoHdp_Code")))
1524 #endif /* __ICCARM__ */
mpu_loader_cfg(void)1525 static void mpu_loader_cfg(void)
1526 {
1527 #ifdef TFM_BOOT_MPU_PROTECTION
1528 #if defined(MCUBOOT_PRIMARY_ONLY)
1529   static struct mpu_armv8m_dev_t dev_mpu_s = { MPU_BASE };
1530 
1531   /* configuration stage */
1532   if (uFlowStage == FLOW_STAGE_CFG)
1533   {
1534     /* secure region 2 is configured to allow read /write to NS_RAM */
1535     mpu_armv8m_region_disable(&dev_mpu_s, 2);
1536     /* Execution stopped if flow control failed */
1537     FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_MPU_S_L_DI_R2, FLOW_CTRL_MPU_S_L_DI_R2);
1538 
1539   }
1540   else
1541   {
1542     /* check region 2 is disabled */
1543     if (mpu_armv8m_region_disable_check(&dev_mpu_s, 2) != MPU_ARMV8M_OK)
1544     {
1545       Error_Handler();
1546     }
1547     else
1548     {
1549       /* Execution stopped if flow control failed */
1550       FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_MPU_S_L_CH_R2, FLOW_CTRL_MPU_S_L_CH_R2);
1551     }
1552 
1553   }
1554 #endif /* MCUBOOT_PRIMARY_ONLY */
1555 #endif /* TFM_BOOT_MPU_PROTECTION  */
1556 
1557   /* configuration stage */
1558   if (uFlowStage != FLOW_STAGE_CFG)
1559   {
1560     /* Lock Secure MPU config */
1561     __HAL_RCC_SYSCFG_CLK_ENABLE();
1562     SYSCFG->CSLCKR |= SYSCFG_CSLCKR_LOCKSMPU;
1563 
1564     /* Lock Non Secure MPU config */
1565     __HAL_RCC_SYSCFG_CLK_ENABLE();
1566     SYSCFG->CSLCKR |= SYSCFG_CNSLCKR_LOCKNSMPU;
1567   }
1568 }
1569 /* Stop placing data in specified section */
1570 #if defined(__ICCARM__)
1571 #pragma default_function_attributes =
1572 #endif /* __ICCARM__ */
1573 #endif /* MCUBOOT_EXT_LOADER */
1574 
1575 /**
1576   * @brief  lock bl2 shared sram in secure
1577   * @param  None
1578   * @retval None
1579   */
lock_bl2_shared_area(void)1580 static void lock_bl2_shared_area(void)
1581 {
1582  uint32_t lockAttributes = GTZC_MCPBB_SUPERBLOCK_LOCKED;
1583 
1584   /* assumption shared area in SRAM2 in the last 8 Kbytes super block */
1585   /*  This area in SRAM 2 is updated BL2 and can be lock to avoid any changes */
1586   if (
1587     (BOOT_TFM_SHARED_DATA_BASE >= S_RAM_ALIAS(_SRAM2_TOP - GTZC_MPCBB_SUPERBLOCK_SIZE))
1588     && (BOOT_TFM_SHARED_DATA_SIZE <= GTZC_MPCBB_SUPERBLOCK_SIZE))
1589   {
1590     __HAL_RCC_GTZC1_CLK_ENABLE();
1591     HAL_GTZC_MPCBB_LockConfig(S_RAM_ALIAS(_SRAM2_TOP - GTZC_MPCBB_SUPERBLOCK_SIZE),
1592                                             1,
1593                                             &lockAttributes);
1594   }
1595   else Error_Handler();
1596 }
1597 
1598 /**
1599   * @brief  configure flash privilege access
1600   * @param  None
1601   * @retval None
1602   */
flash_priv_cfg(void)1603 static void flash_priv_cfg(void)
1604 {
1605 #ifdef TFM_FLASH_PRIVONLY_ENABLE
1606   /* configuration stage */
1607   if (uFlowStage == FLOW_STAGE_CFG)
1608   {
1609     /* Configure Flash Privilege access */
1610     HAL_FLASHEx_ConfigPrivMode(FLASH_SPRIV_DENIED);
1611     /* Execution stopped if flow control failed */
1612     FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_FLASH_P_EN, FLOW_CTRL_FLASH_P_EN);
1613 #endif /*  TFM_FLASH_PRIVONLY_ENABLE */
1614   }
1615   /* verification stage */
1616   else
1617   {
1618     if (HAL_FLASHEx_GetPrivMode() != FLASH_SPRIV_DENIED)
1619     {
1620       Error_Handler();
1621     }
1622     else
1623     {
1624       /* Execution stopped if flow control failed */
1625       FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_FLASH_P_CH, FLOW_CTRL_FLASH_P_CH);
1626     }
1627   }
1628 }
1629 
1630 /* Place code in a specific section */
1631 #if defined(__ICCARM__)
1632 #pragma default_function_attributes = @ ".BL2_NoHdp_Code"
1633 #else
1634 __attribute__((section(".BL2_NoHdp_Code")))
1635 #endif /* __ICCARM__ */
1636 
1637 /**
1638   * @brief  Enable HDP protection
1639   * @param  None
1640   * @retval None
1641   */
enable_hdp_protection(void)1642 static void enable_hdp_protection(void)
1643 {
1644 #ifdef TFM_HDP_PROTECT_ENABLE
1645   do
1646   {
1647     /* Activate HDP protection */
1648     SET_BIT(FLASH->SECHDPCR, FLASH_SECHDPCR_HDP1_ACCDIS);
1649   } while ((FLASH->SECHDPCR & FLASH_SECHDPCR_HDP1_ACCDIS) != FLASH_SECHDPCR_HDP1_ACCDIS);
1650 
1651   if ((FLASH->SECHDPCR & FLASH_SECHDPCR_HDP1_ACCDIS) != FLASH_SECHDPCR_HDP1_ACCDIS)
1652   {
1653     /* Security issue : execution stopped ! */
1654     Error_Handler();
1655   }
1656 #endif /* TFM_HDP_PROTECT_ENABLE */
1657 }
1658 
1659 /* Stop placing data in specified section */
1660 #if defined(__ICCARM__)
1661 #pragma default_function_attributes =
1662 #endif /* __ICCARM__ */
1663 
1664 /* Place code in a specific section */
1665 #if defined(__ICCARM__)
1666 #pragma default_function_attributes = @ ".BL2_NoHdp_Code"
1667 #else
1668 __attribute__((section(".BL2_NoHdp_Code")))
1669 #endif /* __ICCARM__ */
1670 
apply_wrp_sram2(uint32_t offset,uint32_t len)1671 static void apply_wrp_sram2(uint32_t offset, uint32_t len)
1672 {
1673   uint32_t start_offset = ((offset - SRAM2_BASE_S)/ SRAM2_PAGE_SIZE);
1674   uint32_t end_offset = start_offset + (len -1)/SRAM2_PAGE_SIZE;
1675   uint32_t index;
1676   uint32_t val0 = 0;
1677   uint32_t val1 = 0;
1678   RCC->AHB1ENR |= RCC_AHB1ENR_RAMCFGEN;
1679   __HAL_RCC_SYSCFG_CLK_ENABLE();
1680 #if 0
1681   BOOT_LOG_INF("SRAM2 write protection [0x%x, 0x%x] : %d %d", offset, len, start_offset, end_offset);
1682 #endif
1683   for (index = start_offset; index <= end_offset; index ++)
1684   {
1685     if (index > 31U)
1686     {
1687       val1 |= (1 << (index - 32U));
1688     }
1689     else
1690     {
1691       val0 |= (1 << index);
1692     }
1693   }
1694 
1695 #if 0
1696   BOOT_LOG_INF("SRAM2 write protection [0x%x] : %x", (uint32_t)&RAMCFG_SRAM2_S->WPR1, val0);
1697   BOOT_LOG_INF("SRAM2 write protection [0x%x] : %x", (uint32_t)&RAMCFG_SRAM2_S->WPR2, val1);
1698 #endif
1699   RAMCFG_SRAM2_S->WPR1 = val0;
1700   RAMCFG_SRAM2_S->WPR2 = val1;
1701 }
1702 /* Stop placing data in specified section */
1703 #if defined(__ICCARM__)
1704 #pragma default_function_attributes =
1705 #endif /* __ICCARM__ */
1706 
1707 #if (TFM_TAMPER_ENABLE != NO_TAMPER)
1708 const RTC_SecureStateTypeDef TamperSecureConf = {
1709     .rtcSecureFull = RTC_SECURE_FULL_NO,
1710     .rtcNonSecureFeatures = RTC_NONSECURE_FEATURE_ALL,
1711     .tampSecureFull = TAMP_SECURE_FULL_YES,
1712     .MonotonicCounterSecure = TAMP_MONOTONIC_CNT_SECURE_NO,
1713     .backupRegisterStartZone2 = 0,
1714     .backupRegisterStartZone3 = 0
1715 };
1716 const RTC_PrivilegeStateTypeDef TamperPrivConf = {
1717     .rtcPrivilegeFull = RTC_PRIVILEGE_FULL_NO,
1718     .rtcPrivilegeFeatures = RTC_PRIVILEGE_FEATURE_NONE,
1719     .tampPrivilegeFull = TAMP_PRIVILEGE_FULL_YES,
1720     .MonotonicCounterPrivilege = TAMP_MONOTONIC_CNT_PRIVILEGE_NO,
1721     .backupRegisterStartZone2 = 0,
1722     .backupRegisterStartZone3 = 0
1723 };
1724 const RTC_InternalTamperTypeDef InternalTamperConf = {
1725     .IntTamper = RTC_INT_TAMPER_1 | RTC_INT_TAMPER_9,
1726     .TimeStampOnTamperDetection = RTC_TIMESTAMPONTAMPERDETECTION_DISABLE,
1727     .NoErase                  = RTC_TAMPER_ERASE_BACKUP_ENABLE
1728 };
1729 /* Place code in a specific section */
1730 #if defined(__ICCARM__)
1731 #pragma default_function_attributes = @ ".BL2_NoHdp_Code"
1732 #else
1733 __attribute__((section(".BL2_NoHdp_Code")))
1734 #endif /* __ICCARM__ */
TAMP_IRQHandler(void)1735 void TAMP_IRQHandler(void)
1736 {
1737     NVIC_SystemReset();
1738 }
1739 /* Stop placing data in specified section */
1740 #if defined(__ICCARM__)
1741 #pragma default_function_attributes =
1742 #endif /* __ICCARM__ */
1743 #ifdef TFM_DEV_MODE
1744 extern volatile uint32_t TamperEventCleared;
1745 #endif
1746 #endif /* (TFM_TAMPER_ENABLE != NO_TAMPER) */
1747 RTC_HandleTypeDef RTCHandle;
1748 
active_tamper(void)1749 static void active_tamper(void)
1750 {
1751 #if 0
1752     fih_int fih_rc = FIH_FAILURE;
1753 #endif
1754 #if (TFM_TAMPER_ENABLE == ALL_TAMPER)
1755     RTC_ActiveTampersTypeDef sAllTamper;
1756     /*  use random generator to feed  */
1757     uint32_t Seed[4]={0,0,0,0};
1758     uint32_t len=0;
1759     uint32_t j;
1760 #endif /* (TFM_TAMPER_ENABLE == ALL_TAMPER) */
1761 #if (TFM_TAMPER_ENABLE != NO_TAMPER)
1762     RTC_SecureStateTypeDef TamperSecureConfGet;
1763     RTC_PrivilegeStateTypeDef TamperPrivConfGet;
1764 #endif /* TFM_TAMPER_ENABLE != NO_TAMPER) */
1765     /* configuration stage */
1766     if (uFlowStage == FLOW_STAGE_CFG)
1767     {
1768 #if defined(TFM_DEV_MODE) && (TFM_TAMPER_ENABLE != NO_TAMPER)
1769         if (TamperEventCleared) {
1770             BOOT_LOG_INF("Boot with TAMPER Event Active");
1771 #if (TFM_TAMPER_ENABLE == ALL_TAMPER)
1772             /* avoid several re-boot in DEV_MODE with Tamper active */
1773             BOOT_LOG_INF("Plug the tamper cable, and reboot");
1774             BOOT_LOG_INF("Or");
1775 #endif
1776             BOOT_LOG_INF("Build and Flash with flag #define TFM_TAMPER_ENABLE NO_TAMPER\n");
1777             Error_Handler();
1778         }
1779 #endif /*  TFM_DEV_MODE && (TFM_TAMPER_ENABLE != NO_TAMPER) */
1780 
1781         /* RTC Init */
1782         RTCHandle.Instance = RTC;
1783         RTCHandle.Init.HourFormat     = RTC_HOURFORMAT_12;
1784         RTCHandle.Init.AsynchPrediv   = RTC_ASYNCH_PREDIV;
1785         RTCHandle.Init.SynchPrediv    = RTC_SYNCH_PREDIV;
1786         RTCHandle.Init.OutPut         = RTC_OUTPUT_DISABLE;
1787         RTCHandle.Init.OutPutRemap    = RTC_OUTPUT_REMAP_NONE;
1788         RTCHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
1789         RTCHandle.Init.OutPutType     = RTC_OUTPUT_TYPE_PUSHPULL;
1790         RTCHandle.Init.OutPutPullUp   = RTC_OUTPUT_PULLUP_NONE;
1791 
1792         if (HAL_RTC_Init(&RTCHandle) != HAL_OK)
1793         {
1794             Error_Handler();
1795         }
1796 #if (TFM_TAMPER_ENABLE == ALL_TAMPER)
1797         /* generate random seed */
1798         mbedtls_hardware_poll(NULL, (unsigned char *)Seed, sizeof(Seed),(size_t *)&len);
1799         if (len == 0)
1800         {
1801             Error_Handler();
1802         }
1803         BOOT_LOG_INF("TAMPER SEED [0x%x,0x%x,0x%x,0x%x]", Seed[0], Seed[1], Seed[2], Seed[3]);
1804         /* Configure active tamper common parameters  */
1805         sAllTamper.ActiveFilter = RTC_ATAMP_FILTER_ENABLE;
1806         sAllTamper.ActiveAsyncPrescaler = RTC_ATAMP_ASYNCPRES_RTCCLK_32;
1807         sAllTamper.TimeStampOnTamperDetection = RTC_TIMESTAMPONTAMPERDETECTION_ENABLE;
1808         sAllTamper.ActiveOutputChangePeriod = 4;
1809         sAllTamper.Seed[0] = Seed[0];
1810         sAllTamper.Seed[1] = Seed[1];
1811         sAllTamper.Seed[2] = Seed[2];
1812         sAllTamper.Seed[3] = Seed[3];
1813 
1814         /* Disable all Active Tampers */
1815         /* No active tamper */
1816         for (j = 0; j <= RTC_ATAMP_8; j++)
1817         {
1818             sAllTamper.TampInput[j].Enable = RTC_ATAMP_DISABLE;
1819         }
1820 
1821         sAllTamper.TampInput[7].Enable = RTC_ATAMP_ENABLE;
1822         sAllTamper.TampInput[7].Output = 7;
1823         sAllTamper.TampInput[7].NoErase =  RTC_TAMPER_ERASE_BACKUP_ENABLE;
1824         sAllTamper.TampInput[7].MaskFlag = RTC_TAMPERMASK_FLAG_DISABLE;
1825         sAllTamper.TampInput[7].Interrupt = RTC_ATAMP_INTERRUPT_ENABLE;
1826         /* Set active tampers */
1827         if (HAL_RTCEx_SetActiveTampers(&RTCHandle, &sAllTamper) != HAL_OK)
1828         {
1829             Error_Handler();
1830         }
1831         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_ACT_EN, FLOW_CTRL_TAMP_ACT_EN);
1832 #else
1833         HAL_RTCEx_DeactivateTamper(&RTCHandle, RTC_TAMPER_ALL);
1834 #endif  /* (TFM_TAMPER_ENABLE == ALL_TAMPER) */
1835 #if (TFM_TAMPER_ENABLE != NO_TAMPER)
1836         /*  Internal Tamper activation  */
1837         /*  Enable Cryptographic IPs fault (tamp_itamp9), Backup domain voltage threshold monitoring (tamp_itamp1)*/
1838         if (HAL_RTCEx_SetInternalTamper(&RTCHandle,(RTC_InternalTamperTypeDef *)&InternalTamperConf)!=HAL_OK)
1839         {
1840             Error_Handler();
1841         }
1842         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_INT_EN, FLOW_CTRL_TAMP_INT_EN);
1843 
1844         /*  Set tamper configuration secure only  */
1845         if (HAL_RTCEx_SecureModeSet(&RTCHandle, (RTC_SecureStateTypeDef *)&TamperSecureConf) != HAL_OK)
1846         {
1847             Error_Handler();
1848         }
1849         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_SEC_EN, FLOW_CTRL_TAMP_SEC_EN);
1850 
1851         /*  Set tamper configuration privileged only   */
1852         if (HAL_RTCEx_PrivilegeModeSet(&RTCHandle,(RTC_PrivilegeStateTypeDef *)&TamperPrivConf) != HAL_OK)
1853         {
1854             Error_Handler();
1855         }
1856         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_PRIV_EN, FLOW_CTRL_TAMP_PRIV_EN);
1857 
1858         /*  Activate Secret Erase */
1859         HAL_RTCEx_Erase_SecretDev_Conf(&RTCHandle,(uint32_t)TAMP_SECRETDEVICE_ERASE_ENABLE);
1860         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_CFG_EN, FLOW_CTRL_TAMP_CFG_EN);
1861         BOOT_LOG_INF("TAMPER Activated");
1862 #else
1863         HAL_RTCEx_DeactivateInternalTamper(&RTCHandle, RTC_INT_TAMPER_ALL);
1864 #endif /* (TFM_TAMPER_ENABLE != NO_TAMPER) */
1865     }
1866 #if (TFM_TAMPER_ENABLE != NO_TAMPER)
1867     /* verification stage */
1868     else
1869     {
1870 #if (TFM_TAMPER_ENABLE == ALL_TAMPER)
1871         /* Check active tampers */
1872         if ((READ_BIT(TAMP->ATOR, TAMP_ATOR_INITS) == 0U) ||
1873             (READ_REG(TAMP->IER) != 0x00000080U) ||
1874             (READ_REG(TAMP->ATCR1) != 0x84050080U) ||
1875             (READ_REG(TAMP->ATCR2) != 0xE0000000U) ||
1876             (READ_REG(TAMP->CR1) != 0x01010080U) ||
1877             (READ_REG(TAMP->CR2) != 0x00000000U))
1878         {
1879             Error_Handler();
1880         }
1881         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_ACT_CH, FLOW_CTRL_TAMP_ACT_CH);
1882 #endif  /* (TFM_TAMPER_ENABLE == ALL_TAMPER) */
1883         /*  Check Internal Tamper activation */
1884         if ((READ_BIT(RTC->CR, RTC_CR_TAMPTS) != InternalTamperConf.TimeStampOnTamperDetection) ||
1885 #if (TFM_TAMPER_ENABLE == ALL_TAMPER)
1886             (READ_REG(TAMP->CR1) != 0x01010080U) ||
1887 #else
1888             (READ_REG(TAMP->CR1) != 0x01010000U) ||
1889 #endif /* (TFM_TAMPER_ENABLE == ALL_TAMPER) */
1890             (READ_REG(TAMP->CR3) != 0x00000000U))
1891         {
1892             Error_Handler();
1893         }
1894         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_INT_CH, FLOW_CTRL_TAMP_INT_CH);
1895 #if 0
1896         /*  Check tamper configuration secure only  */
1897         if (HAL_RTCEx_SecureModeGet(&RTCHandle, (RTC_SecureStateTypeDef *)&TamperSecureConfGet) != HAL_OK)
1898         {
1899             Error_Handler();
1900         }
1901         FIH_CALL(boot_fih_memequal, fih_rc,(void *)&TamperSecureConf, (void *)&TamperSecureConfGet, sizeof(TamperSecureConf));
1902         if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
1903                 Error_Handler();
1904         }
1905 #endif
1906         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_SEC_CH, FLOW_CTRL_TAMP_SEC_CH);
1907 #if 0
1908         /*  Check tamper configuration privileged only   */
1909         if (HAL_RTCEx_PrivilegeModeGet(&RTCHandle,(RTC_PrivilegeStateTypeDef *)&TamperPrivConfGet) != HAL_OK)
1910         {
1911             Error_Handler();
1912         }
1913         FIH_CALL(boot_fih_memequal, fih_rc,(void *)&TamperPrivConf, (void *)&TamperPrivConfGet, sizeof(TamperPrivConf));
1914         if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
1915                 Error_Handler();
1916         }
1917 #endif
1918         FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_PRIV_CH, FLOW_CTRL_TAMP_PRIV_CH);
1919 
1920         /*  Check Secret Erase */
1921 #if 0
1922         /* On U5 Cut 2 only */
1923         if (READ_BIT(TAMP->ERCFGR, TAMP_ERCFGR0) != TAMP_ERCFGR0)
1924         {
1925             Error_Handler();
1926         }
1927 #endif
1928     FLOW_CONTROL_STEP(uFlowProtectValue, FLOW_STEP_TAMP_CFG_CH, FLOW_CTRL_TAMP_CFG_CH);
1929     }
1930 #endif /*  TFM_TAMPER_ENABLE != NO_TAMPER */
1931 }
1932 /**
1933   * @}
1934   */
1935 
1936 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
1937