1 /*
2 * Copyright (c) 2019-2023, Arm Limited. All rights reserved.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 *
6 */
7
8 #include "bootutil/security_cnt.h"
9 #include "../../platform/include/tfm_plat_nv_counters.h"
10 #include "../../platform/include/tfm_plat_defs.h"
11 #include "bootutil/fault_injection_hardening.h"
12 #include <stdint.h>
13
14 #define TFM_BOOT_NV_COUNTER_FIRST PLAT_NV_COUNTER_BL2_0
15 #define TFM_BOOT_NV_COUNTER_MAX (TFM_BOOT_NV_COUNTER_FIRST + \
16 MCUBOOT_IMAGE_NUMBER)
17
get_nv_counter_from_image_id(uint32_t image_id)18 static enum tfm_nv_counter_t get_nv_counter_from_image_id(uint32_t image_id)
19 {
20 uint32_t nv_counter;
21
22 /* Avoid integer overflow */
23 /* Assumes BL2 NV counters are contiguous */
24 if ((UINT32_MAX - TFM_BOOT_NV_COUNTER_FIRST) < image_id) {
25 return TFM_BOOT_NV_COUNTER_MAX;
26 }
27
28 nv_counter = TFM_BOOT_NV_COUNTER_FIRST + image_id;
29
30 /* Check the existence of the enumerated counter value */
31 if (nv_counter >= TFM_BOOT_NV_COUNTER_MAX) {
32 return TFM_BOOT_NV_COUNTER_MAX;
33 }
34
35 return (enum tfm_nv_counter_t)nv_counter;
36 }
37
boot_nv_security_counter_init(void)38 fih_ret boot_nv_security_counter_init(void)
39 {
40 FIH_DECLARE(fih_rc, FIH_FAILURE);
41
42 fih_rc = fih_ret_encode_zero_equality(tfm_plat_init_nv_counter());
43
44 FIH_RET(fih_rc);
45 }
46
boot_nv_security_counter_get(uint32_t image_id,fih_int * security_cnt)47 fih_ret boot_nv_security_counter_get(uint32_t image_id, fih_int *security_cnt)
48 {
49 enum tfm_nv_counter_t nv_counter;
50 FIH_DECLARE(fih_rc, FIH_FAILURE);
51 uint32_t security_cnt_soft;
52
53 /* Check if it's a null-pointer. */
54 if (!security_cnt) {
55 FIH_RET(FIH_FAILURE);
56 }
57
58 nv_counter = get_nv_counter_from_image_id(image_id);
59 if (nv_counter >= TFM_BOOT_NV_COUNTER_MAX) {
60 FIH_RET(FIH_FAILURE);
61 }
62
63 fih_rc = fih_ret_encode_zero_equality(
64 tfm_plat_read_nv_counter(nv_counter,
65 sizeof(security_cnt_soft),
66 (uint8_t *)&security_cnt_soft));
67 *security_cnt = fih_int_encode(security_cnt_soft);
68
69 FIH_RET(fih_rc);
70 }
71
boot_nv_security_counter_update(uint32_t image_id,uint32_t img_security_cnt)72 int32_t boot_nv_security_counter_update(uint32_t image_id,
73 uint32_t img_security_cnt)
74 {
75 enum tfm_nv_counter_t nv_counter;
76 enum tfm_plat_err_t err;
77
78 nv_counter = get_nv_counter_from_image_id(image_id);
79 if (nv_counter >= TFM_BOOT_NV_COUNTER_MAX) {
80 return -1;
81 }
82
83 err = tfm_plat_set_nv_counter(nv_counter, img_security_cnt);
84 if (err != TFM_PLAT_ERR_SUCCESS) {
85 return -1;
86 }
87
88 return 0;
89 }
90