1 /*
2 * SPDX-FileCopyrightText: 2018-2024 Espressif Systems (Shanghai) CO LTD
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6 #include <string.h>
7 #include <stdbool.h>
8 #include "esp_crt_bundle.h"
9 #include "esp_log.h"
10
11 #define BUNDLE_HEADER_OFFSET 2
12 #define CRT_HEADER_OFFSET 4
13
14 static const char *TAG = "esp-x509-crt-bundle";
15
16 /* a dummy certificate so that
17 * cacert_ptr passes non-NULL check during handshake */
18 static const mbedtls_x509_crt s_dummy_crt;
19
20 extern const uint8_t x509_crt_imported_bundle_bin_start[] asm("_binary_x509_crt_bundle_start");
21 extern const uint8_t x509_crt_imported_bundle_bin_end[] asm("_binary_x509_crt_bundle_end");
22
23
24 typedef struct crt_bundle_t {
25 const uint8_t **crts;
26 uint16_t num_certs;
27 size_t x509_crt_bundle_len;
28 } crt_bundle_t;
29
30 static crt_bundle_t s_crt_bundle;
31
32 static int esp_crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_buf, size_t pub_key_len);
33
34
esp_crt_check_signature(mbedtls_x509_crt * child,const uint8_t * pub_key_buf,size_t pub_key_len)35 static int esp_crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_buf, size_t pub_key_len)
36 {
37 int ret = 0;
38 mbedtls_x509_crt parent;
39 const mbedtls_md_info_t *md_info;
40 unsigned char hash[MBEDTLS_MD_MAX_SIZE];
41
42 mbedtls_x509_crt_init(&parent);
43
44 if ( (ret = mbedtls_pk_parse_public_key(&parent.pk, pub_key_buf, pub_key_len) ) != 0) {
45 ESP_LOGE(TAG, "PK parse failed with error %X", ret);
46 goto cleanup;
47 }
48
49
50 // Fast check to avoid expensive computations when not necessary
51 if (!mbedtls_pk_can_do(&parent.pk, child->MBEDTLS_PRIVATE(sig_pk))) {
52 ESP_LOGE(TAG, "Simple compare failed");
53 ret = -1;
54 goto cleanup;
55 }
56
57 md_info = mbedtls_md_info_from_type(child->MBEDTLS_PRIVATE(sig_md));
58 if ( (ret = mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash )) != 0 ) {
59 ESP_LOGE(TAG, "Internal mbedTLS error %X", ret);
60 goto cleanup;
61 }
62
63 if ( (ret = mbedtls_pk_verify_ext( child->MBEDTLS_PRIVATE(sig_pk), child->MBEDTLS_PRIVATE(sig_opts), &parent.pk,
64 child->MBEDTLS_PRIVATE(sig_md), hash, mbedtls_md_get_size( md_info ),
65 child->MBEDTLS_PRIVATE(sig).p, child->MBEDTLS_PRIVATE(sig).len )) != 0 ) {
66
67 ESP_LOGE(TAG, "PK verify failed with error %X", ret);
68 goto cleanup;
69 }
70 cleanup:
71 mbedtls_x509_crt_free(&parent);
72
73 return ret;
74 }
75
76
77 /* This callback is called for every certificate in the chain. If the chain
78 * is proper each intermediate certificate is validated through its parent
79 * in the x509_crt_verify_chain() function. So this callback should
80 * only verify the first untrusted link in the chain is signed by the
81 * root certificate in the trusted bundle
82 */
esp_crt_verify_callback(void * buf,mbedtls_x509_crt * crt,int depth,uint32_t * flags)83 int esp_crt_verify_callback(void *buf, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
84 {
85 mbedtls_x509_crt *child = crt;
86
87 /* It's OK for a trusted cert to have a weak signature hash alg.
88 as we already trust this certificate */
89 uint32_t flags_filtered = *flags & ~(MBEDTLS_X509_BADCERT_BAD_MD);
90
91 if (flags_filtered != MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
92 return 0;
93 }
94
95
96 if (s_crt_bundle.crts == NULL) {
97 ESP_LOGE(TAG, "No certificates in bundle");
98 return MBEDTLS_ERR_X509_FATAL_ERROR;
99 }
100
101 ESP_LOGD(TAG, "%d certificates in bundle", s_crt_bundle.num_certs);
102
103 size_t name_len = 0;
104 const uint8_t *crt_name;
105
106 bool crt_found = false;
107 int start = 0;
108 int end = s_crt_bundle.num_certs - 1;
109 int middle = (end - start) / 2;
110
111 /* Look for the certificate using binary search on subject name */
112 while (start <= end) {
113 name_len = s_crt_bundle.crts[middle][0] << 8 | s_crt_bundle.crts[middle][1];
114 crt_name = s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET;
115
116 int cmp_res = memcmp(child->issuer_raw.p, crt_name, name_len );
117 if (cmp_res == 0) {
118 crt_found = true;
119 break;
120 } else if (cmp_res < 0) {
121 end = middle - 1;
122 } else {
123 start = middle + 1;
124 }
125 middle = (start + end) / 2;
126 }
127
128 int ret = MBEDTLS_ERR_X509_FATAL_ERROR;
129 if (crt_found) {
130 size_t key_len = s_crt_bundle.crts[middle][2] << 8 | s_crt_bundle.crts[middle][3];
131 ret = esp_crt_check_signature(child, s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET + name_len, key_len);
132 }
133
134 if (ret == 0) {
135 ESP_LOGI(TAG, "Certificate validated");
136 *flags = 0;
137 return 0;
138 }
139
140 ESP_LOGE(TAG, "Failed to verify certificate");
141 return MBEDTLS_ERR_X509_FATAL_ERROR;
142 }
143
144
145 /* Initialize the bundle into an array so we can do binary search for certs,
146 the bundle generated by the python utility is already presorted by subject name
147 */
esp_crt_bundle_init(const uint8_t * x509_bundle,size_t bundle_size)148 static esp_err_t esp_crt_bundle_init(const uint8_t *x509_bundle, size_t bundle_size)
149 {
150 if (bundle_size < BUNDLE_HEADER_OFFSET + CRT_HEADER_OFFSET) {
151 ESP_LOGE(TAG, "Invalid certificate bundle");
152 return ESP_ERR_INVALID_ARG;
153 }
154
155 uint16_t num_certs = (x509_bundle[0] << 8) | x509_bundle[1];
156 if (num_certs > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS) {
157 ESP_LOGE(TAG, "No. of certs in the certificate bundle = %d exceeds\n"
158 "Max allowed certificates in the certificate bundle = %d\n"
159 "Please update the menuconfig option with appropriate value", num_certs, CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS);
160 return ESP_ERR_INVALID_ARG;
161 }
162
163 const uint8_t **crts = calloc(num_certs, sizeof(x509_bundle));
164 if (crts == NULL) {
165 ESP_LOGE(TAG, "Unable to allocate memory for bundle");
166 return ESP_ERR_NO_MEM;
167 }
168
169 const uint8_t *cur_crt;
170 /* This is the maximum region that is allowed to access */
171 const uint8_t *bundle_end = x509_bundle + bundle_size;
172 cur_crt = x509_bundle + BUNDLE_HEADER_OFFSET;
173
174 for (int i = 0; i < num_certs; i++) {
175 crts[i] = cur_crt;
176 if (cur_crt + CRT_HEADER_OFFSET > bundle_end) {
177 ESP_LOGE(TAG, "Invalid certificate bundle");
178 free(crts);
179 return ESP_ERR_INVALID_ARG;
180 }
181 size_t name_len = cur_crt[0] << 8 | cur_crt[1];
182 size_t key_len = cur_crt[2] << 8 | cur_crt[3];
183 cur_crt = cur_crt + CRT_HEADER_OFFSET + name_len + key_len;
184 }
185
186 if (cur_crt > bundle_end) {
187 ESP_LOGE(TAG, "Invalid certificate bundle");
188 free(crts);
189 return ESP_ERR_INVALID_ARG;
190 }
191
192 /* The previous crt bundle is only updated when initialization of the
193 * current crt_bundle is successful */
194 /* Free previous crt_bundle */
195 free(s_crt_bundle.crts);
196 s_crt_bundle.num_certs = num_certs;
197 s_crt_bundle.crts = crts;
198 return ESP_OK;
199 }
200
esp_crt_bundle_attach(void * conf)201 esp_err_t esp_crt_bundle_attach(void *conf)
202 {
203 esp_err_t ret = ESP_OK;
204 // If no bundle has been set by the user then use the bundle embedded in the binary
205 if (s_crt_bundle.crts == NULL) {
206 ret = esp_crt_bundle_init(x509_crt_imported_bundle_bin_start, x509_crt_imported_bundle_bin_end - x509_crt_imported_bundle_bin_start);
207 }
208
209 if (ret != ESP_OK) {
210 ESP_LOGE(TAG, "Failed to attach bundle");
211 return ret;
212 }
213
214 if (conf) {
215 /* point to a dummy certificate
216 * This is only required so that the
217 * cacert_ptr passes non-NULL check during handshake
218 */
219 mbedtls_ssl_config *ssl_conf = (mbedtls_ssl_config *)conf;
220 mbedtls_ssl_conf_ca_chain(ssl_conf, (mbedtls_x509_crt*)&s_dummy_crt, NULL);
221 mbedtls_ssl_conf_verify(ssl_conf, esp_crt_verify_callback, NULL);
222 }
223
224 return ret;
225 }
226
esp_crt_bundle_detach(mbedtls_ssl_config * conf)227 void esp_crt_bundle_detach(mbedtls_ssl_config *conf)
228 {
229 free(s_crt_bundle.crts);
230 s_crt_bundle.crts = NULL;
231 if (conf) {
232 mbedtls_ssl_conf_verify(conf, NULL, NULL);
233 }
234 }
235
esp_crt_bundle_set(const uint8_t * x509_bundle,size_t bundle_size)236 esp_err_t esp_crt_bundle_set(const uint8_t *x509_bundle, size_t bundle_size)
237 {
238 return esp_crt_bundle_init(x509_bundle, bundle_size);
239 }
240
esp_crt_bundle_in_use(const mbedtls_x509_crt * ca_chain)241 bool esp_crt_bundle_in_use(const mbedtls_x509_crt* ca_chain)
242 {
243 return ((ca_chain == &s_dummy_crt) ? true : false);
244 }
245