1 /** @file
2  * @brief mbed TLS initialization
3  *
4  * Initialize the mbed TLS library like setup the heap etc.
5  */
6 
7 /*
8  * Copyright (c) 2017 Intel Corporation
9  * Copyright (c) 2024 Nordic Semiconductor ASA
10  *
11  * SPDX-License-Identifier: Apache-2.0
12  */
13 
14 #include <zephyr/init.h>
15 #include <zephyr/app_memory/app_memdomain.h>
16 #include <mbedtls/platform_time.h>
17 
18 #include <mbedtls/debug.h>
19 
20 #if defined(CONFIG_MBEDTLS)
21 #if !defined(CONFIG_MBEDTLS_CFG_FILE)
22 #include "mbedtls/config.h"
23 #else
24 #include CONFIG_MBEDTLS_CFG_FILE
25 #endif /* CONFIG_MBEDTLS_CFG_FILE */
26 #endif
27 
28 #if defined(CONFIG_MBEDTLS_ENABLE_HEAP) && \
29 	defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
30 #include <mbedtls/memory_buffer_alloc.h>
31 
32 #ifdef CONFIG_MBEDTLS_HEAP_CUSTOM_SECTION
33 #define HEAP_MEM_ATTRIBUTES Z_GENERIC_SECTION(.mbedtls_heap)
34 #else
35 #define HEAP_MEM_ATTRIBUTES
36 #endif /* CONFIG_MBEDTLS_HEAP_CUSTOM_SECTION */
37 static unsigned char _mbedtls_heap[CONFIG_MBEDTLS_HEAP_SIZE] HEAP_MEM_ATTRIBUTES;
38 
init_heap(void)39 static void init_heap(void)
40 {
41 	mbedtls_memory_buffer_alloc_init(_mbedtls_heap, sizeof(_mbedtls_heap));
42 }
43 #else
44 #define init_heap(...)
45 #endif /* CONFIG_MBEDTLS_ENABLE_HEAP && MBEDTLS_MEMORY_BUFFER_ALLOC_C */
46 
_mbedtls_init(void)47 static int _mbedtls_init(void)
48 {
49 
50 	init_heap();
51 
52 #if defined(CONFIG_MBEDTLS_DEBUG_LEVEL)
53 	mbedtls_debug_set_threshold(CONFIG_MBEDTLS_DEBUG_LEVEL);
54 #endif
55 
56 #if defined(CONFIG_MBEDTLS_PSA_CRYPTO_CLIENT)
57 	if (psa_crypto_init() != PSA_SUCCESS) {
58 		return -EIO;
59 	}
60 #endif
61 
62 	return 0;
63 }
64 
65 #if defined(CONFIG_MBEDTLS_INIT)
66 SYS_INIT(_mbedtls_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
67 #endif
68 
69 /* if CONFIG_MBEDTLS_INIT is not defined then this function
70  * should be called by the platform before any mbedtls functionality
71  * is used
72  */
mbedtls_init(void)73 int mbedtls_init(void)
74 {
75 	return _mbedtls_init();
76 }
77 
78 /* TLS 1.3 ticket lifetime needs a timing interface */
mbedtls_ms_time(void)79 mbedtls_ms_time_t mbedtls_ms_time(void)
80 {
81 	return (mbedtls_ms_time_t)k_uptime_get();
82 }
83