1 /*
2  * SPDX-License-Identifier: Apache-2.0
3  *
4  * Copyright (c) 2020 Arm Limited
5  */
6 
7 #include "bootutil/fault_injection_hardening.h"
8 
9 #ifdef FIH_ENABLE_DELAY
10 
11 #include "mbedtls/ctr_drbg.h"
12 #include "mbedtls/entropy.h"
13 
14 /* Mbedtls implementation of the delay RNG. Can be replaced by any other RNG
15  * implementation that is backed by an entropy source by altering these
16  * functions. This is not provided as a header API and a C file implementation
17  * due to issues with inlining.
18  */
19 
20 #ifdef MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES
21 #error "FIH_ENABLE_DELAY requires an entropy source"
22 #endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */
23 
24 mbedtls_entropy_context fih_entropy_ctx;
25 mbedtls_ctr_drbg_context fih_drbg_ctx;
26 
fih_delay_init(void)27 int fih_delay_init(void)
28 {
29     mbedtls_entropy_init(&fih_entropy_ctx);
30     mbedtls_ctr_drbg_init(&fih_drbg_ctx);
31     mbedtls_ctr_drbg_seed(&fih_drbg_ctx , mbedtls_entropy_func,
32                           &fih_entropy_ctx, NULL, 0);
33 
34     return 1;
35 }
36 
fih_delay_random_uchar(void)37 unsigned char fih_delay_random_uchar(void)
38 {
39     unsigned char delay;
40 
41     mbedtls_ctr_drbg_random(&fih_drbg_ctx,(unsigned char*) &delay,
42                             sizeof(delay));
43 
44     return delay;
45 }
46 
47 #endif /* FIH_ENABLE_DELAY */
48