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  *
10  * SPDX-License-Identifier: Apache-2.0
11  */
12 
13 #include <zephyr/init.h>
14 #include <zephyr/app_memory/app_memdomain.h>
15 #include <zephyr/drivers/entropy.h>
16 #include <zephyr/random/random.h>
17 #include <mbedtls/entropy.h>
18 
19 #include <mbedtls/debug.h>
20 
21 #if defined(CONFIG_MBEDTLS)
22 #if !defined(CONFIG_MBEDTLS_CFG_FILE)
23 #include "mbedtls/config.h"
24 #else
25 #include CONFIG_MBEDTLS_CFG_FILE
26 #endif /* CONFIG_MBEDTLS_CFG_FILE */
27 #endif
28 
29 #if defined(CONFIG_MBEDTLS_ENABLE_HEAP) && \
30 					defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
31 #include <mbedtls/memory_buffer_alloc.h>
32 
33 #if !defined(CONFIG_MBEDTLS_HEAP_SIZE)
34 #error "Please set heap size to be used. Set value to CONFIG_MBEDTLS_HEAP_SIZE \
35 option."
36 #endif
37 
38 static unsigned char _mbedtls_heap[CONFIG_MBEDTLS_HEAP_SIZE];
39 
init_heap(void)40 static void init_heap(void)
41 {
42 	mbedtls_memory_buffer_alloc_init(_mbedtls_heap, sizeof(_mbedtls_heap));
43 }
44 #else
45 #define init_heap(...)
46 #endif /* CONFIG_MBEDTLS_ENABLE_HEAP && MBEDTLS_MEMORY_BUFFER_ALLOC_C */
47 
48 #if defined(CONFIG_MBEDTLS_ZEPHYR_ENTROPY)
49 static const struct device *const entropy_dev =
50 			DEVICE_DT_GET_OR_NULL(DT_CHOSEN(zephyr_entropy));
51 
mbedtls_hardware_poll(void * data,unsigned char * output,size_t len,size_t * olen)52 int mbedtls_hardware_poll(void *data, unsigned char *output, size_t len,
53 			  size_t *olen)
54 {
55 	int ret;
56 	uint16_t request_len = len > UINT16_MAX ? UINT16_MAX : len;
57 
58 	ARG_UNUSED(data);
59 
60 	if (output == NULL || olen == NULL || len == 0) {
61 		return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
62 	}
63 
64 	if (!IS_ENABLED(CONFIG_ENTROPY_HAS_DRIVER)) {
65 		sys_rand_get(output, len);
66 		*olen = len;
67 
68 		return 0;
69 	}
70 
71 	if (!device_is_ready(entropy_dev)) {
72 		return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
73 	}
74 
75 	ret = entropy_get_entropy(entropy_dev, (uint8_t *)output, request_len);
76 	if (ret < 0) {
77 		return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
78 	}
79 
80 	*olen = request_len;
81 
82 	return 0;
83 }
84 #endif /* CONFIG_MBEDTLS_ZEPHYR_ENTROPY */
85 
_mbedtls_init(void)86 static int _mbedtls_init(void)
87 {
88 
89 	init_heap();
90 
91 #if defined(CONFIG_MBEDTLS_DEBUG_LEVEL)
92 	mbedtls_debug_set_threshold(CONFIG_MBEDTLS_DEBUG_LEVEL);
93 #endif
94 
95 	return 0;
96 }
97 
98 #if defined(CONFIG_MBEDTLS_INIT)
99 SYS_INIT(_mbedtls_init, POST_KERNEL, 0);
100 #endif
101 
102 /* if CONFIG_MBEDTLS_INIT is not defined then this function
103  * should be called by the platform before any mbedtls functionality
104  * is used
105  */
mbedtls_init(void)106 int mbedtls_init(void)
107 {
108 	return _mbedtls_init();
109 }
110