Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit cbfcfbf

Browse filesBrowse files
Add certificate bundle capability to WiFiClientSecure (espressif#6106)
* Add certificate bundle capability to WiFiClientSecure Enable usage of the ESP32 IDF's certificate bundle for WiFiClientSecure connections. Adds the ability to load a bundle or root certificates and use them for authenticating SSL servers. Based on work from Onno-Dirkzwager, Duckle29, kubo6472, meltdown03, kinafu and others. See also: - https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_crt_bundle.html - espressif#3646 - libraries/WiFiClientSecure/README.md * Fix build issues * Clean up old bundle index when NULL bundle is attached
1 parent c9b0dc9 commit cbfcfbf
Copy full SHA for cbfcfbf

File tree

Expand file treeCollapse file tree

9 files changed

+569
-5
lines changed
Filter options
Expand file treeCollapse file tree

9 files changed

+569
-5
lines changed

‎CMakeLists.txt

Copy file name to clipboardExpand all lines: CMakeLists.txt
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ set(LIBRARY_SRCS
115115
libraries/WebServer/src/Parsing.cpp
116116
libraries/WebServer/src/detail/mimetable.cpp
117117
libraries/WiFiClientSecure/src/ssl_client.cpp
118+
libraries/WiFiClientSecure/src/esp_crt_bundle.c
118119
libraries/WiFiClientSecure/src/WiFiClientSecure.cpp
119120
libraries/WiFi/src/WiFiAP.cpp
120121
libraries/WiFi/src/WiFiClient.cpp

‎libraries/WiFiClientSecure/README.md

Copy file name to clipboardExpand all lines: libraries/WiFiClientSecure/README.md
+26Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,32 @@ Then:
2626

2727
Please see the WiFiClientSecure example.
2828

29+
Using a bundle of root certificate authority certificates
30+
---------------------------------------------------------
31+
This method is similar to the single root certificate verfication above, but it uses a standard set of
32+
root certificates from Mozilla to authenticate against, while the previous method only accepts a single
33+
certificate for a given server. This allows the client to connect to all public SSL servers.
34+
35+
To use this feature in PlatformIO:
36+
1. create a certificate bundle as described in the document below, or obtain a pre-built one you trust:
37+
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_crt_bundle.htm
38+
(gen_crt_bundle.py can be found in the /tools folder)
39+
a. note: the full bundle will take up around 64k of flash space, but has minimal RAM usage, as only
40+
the index of the certificates is kept in RAM
41+
2. Place the bundle under the file name "data/cert/x509_crt_bundle.bin" in your platformio project
42+
3. add "board_build.embed_files = data/cert/x509_crt_bundle.bin" in your platformio.ini
43+
4. add the following global declaration in your project:
44+
extern const uint8_t rootca_crt_bundle_start[] asm("_binary_data_cert_x509_crt_bundle_bin_start");
45+
5. before initiating the first SSL connection, call
46+
my_client.setCACertBundle(rootca_crt_bundle_start);
47+
48+
To use this feature in Android IDE:
49+
If the Arduino IDE added support for embedding files in the meantime, then follow the instructions above.
50+
If not, you have three choices:
51+
1. convert your project to PlatformIO
52+
2. create a makefile where you can add the idf_component_register() declaration to include the certificate bundle
53+
3. Store the bundle as a SPIFFS file, but then you have to load it into RAM in runtime and waste 64k of precious memory
54+
2955
Using a root CA cert and client cert/keys
3056
-----------------------------------------
3157
This method authenticates the server and additionally also authenticates

‎libraries/WiFiClientSecure/src/WiFiClientSecure.cpp

Copy file name to clipboardExpand all lines: libraries/WiFiClientSecure/src/WiFiClientSecure.cpp
+16-2Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
*/
2020

2121
#include "WiFiClientSecure.h"
22+
#include "esp_crt_bundle.h"
2223
#include <lwip/sockets.h>
2324
#include <lwip/netdb.h>
2425
#include <errno.h>
@@ -44,6 +45,7 @@ WiFiClientSecure::WiFiClientSecure()
4445
_psKey = NULL;
4546
next = NULL;
4647
_alpn_protos = NULL;
48+
_use_ca_bundle = false;
4749
}
4850

4951

@@ -129,7 +131,7 @@ int WiFiClientSecure::connect(const char *host, uint16_t port, const char *CA_ce
129131
if(_timeout > 0){
130132
sslclient->handshake_timeout = _timeout;
131133
}
132-
int ret = start_ssl_client(sslclient, host, port, _timeout, CA_cert, cert, private_key, NULL, NULL, _use_insecure, _alpn_protos);
134+
int ret = start_ssl_client(sslclient, host, port, _timeout, CA_cert, _use_ca_bundle, cert, private_key, NULL, NULL, _use_insecure, _alpn_protos);
133135
_lastError = ret;
134136
if (ret < 0) {
135137
log_e("start_ssl_client: %d", ret);
@@ -149,7 +151,7 @@ int WiFiClientSecure::connect(const char *host, uint16_t port, const char *pskId
149151
if(_timeout > 0){
150152
sslclient->handshake_timeout = _timeout;
151153
}
152-
int ret = start_ssl_client(sslclient, host, port, _timeout, NULL, NULL, NULL, pskIdent, psKey, _use_insecure, _alpn_protos);
154+
int ret = start_ssl_client(sslclient, host, port, _timeout, NULL, false, NULL, NULL, pskIdent, psKey, _use_insecure, _alpn_protos);
153155
_lastError = ret;
154156
if (ret < 0) {
155157
log_e("start_ssl_client: %d", ret);
@@ -263,6 +265,18 @@ void WiFiClientSecure::setCACert (const char *rootCA)
263265
_CA_cert = rootCA;
264266
}
265267

268+
void WiFiClientSecure::setCACertBundle(const uint8_t * bundle)
269+
{
270+
if (bundle != NULL)
271+
{
272+
esp_crt_bundle_set(bundle);
273+
_use_ca_bundle = true;
274+
} else {
275+
esp_crt_bundle_detach(NULL);
276+
_use_ca_bundle = false;
277+
}
278+
}
279+
266280
void WiFiClientSecure::setCertificate (const char *client_ca)
267281
{
268282
_cert = client_ca;

‎libraries/WiFiClientSecure/src/WiFiClientSecure.h

Copy file name to clipboardExpand all lines: libraries/WiFiClientSecure/src/WiFiClientSecure.h
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class WiFiClientSecure : public WiFiClient
4040
const char *_pskIdent; // identity for PSK cipher suites
4141
const char *_psKey; // key in hex for PSK cipher suites
4242
const char **_alpn_protos;
43+
bool _use_ca_bundle;
4344

4445
public:
4546
WiFiClientSecure *next;
@@ -70,6 +71,7 @@ class WiFiClientSecure : public WiFiClient
7071
void setCertificate(const char *client_ca);
7172
void setPrivateKey (const char *private_key);
7273
bool loadCACert(Stream& stream, size_t size);
74+
void setCACertBundle(const uint8_t * bundle);
7375
bool loadCertificate(Stream& stream, size_t size);
7476
bool loadPrivateKey(Stream& stream, size_t size);
7577
bool verify(const char* fingerprint, const char* domain_name);
+218Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
// Copyright 2018-2019 Espressif Systems (Shanghai) PTE LTD
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
16+
#include <string.h>
17+
#include <esp_system.h>
18+
#include <esp32-hal-log.h>
19+
#include "esp_crt_bundle.h"
20+
#include "esp_err.h"
21+
22+
#define BUNDLE_HEADER_OFFSET 2
23+
#define CRT_HEADER_OFFSET 4
24+
25+
static const char *TAG = "esp-x509-crt-bundle";
26+
27+
/* a dummy certificate so that
28+
* cacert_ptr passes non-NULL check during handshake */
29+
static mbedtls_x509_crt s_dummy_crt;
30+
31+
32+
typedef struct crt_bundle_t {
33+
const uint8_t **crts;
34+
uint16_t num_certs;
35+
size_t x509_crt_bundle_len;
36+
} crt_bundle_t;
37+
38+
static crt_bundle_t s_crt_bundle;
39+
40+
static int esp_crt_verify_callback(void *buf, mbedtls_x509_crt *crt, int data, uint32_t *flags);
41+
static int esp_crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_buf, size_t pub_key_len);
42+
43+
44+
static int esp_crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_buf, size_t pub_key_len)
45+
{
46+
int ret = 0;
47+
mbedtls_x509_crt parent;
48+
const mbedtls_md_info_t *md_info;
49+
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
50+
51+
mbedtls_x509_crt_init(&parent);
52+
53+
if ( (ret = mbedtls_pk_parse_public_key(&parent.pk, pub_key_buf, pub_key_len) ) != 0) {
54+
log_e("PK parse failed with error %X", ret);
55+
goto cleanup;
56+
}
57+
58+
59+
// Fast check to avoid expensive computations when not necessary
60+
if (!mbedtls_pk_can_do(&parent.pk, child->sig_pk)) {
61+
log_e("Simple compare failed");
62+
ret = -1;
63+
goto cleanup;
64+
}
65+
66+
md_info = mbedtls_md_info_from_type(child->sig_md);
67+
if ( (ret = mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash )) != 0 ) {
68+
log_e("Internal mbedTLS error %X", ret);
69+
goto cleanup;
70+
}
71+
72+
if ( (ret = mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent.pk,
73+
child->sig_md, hash, mbedtls_md_get_size( md_info ),
74+
child->sig.p, child->sig.len )) != 0 ) {
75+
76+
log_e("PK verify failed with error %X", ret);
77+
goto cleanup;
78+
}
79+
cleanup:
80+
mbedtls_x509_crt_free(&parent);
81+
82+
return ret;
83+
}
84+
85+
86+
/* This callback is called for every certificate in the chain. If the chain
87+
* is proper each intermediate certificate is validated through its parent
88+
* in the x509_crt_verify_chain() function. So this callback should
89+
* only verify the first untrusted link in the chain is signed by the
90+
* root certificate in the trusted bundle
91+
*/
92+
int esp_crt_verify_callback(void *buf, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
93+
{
94+
mbedtls_x509_crt *child = crt;
95+
96+
/* It's OK for a trusted cert to have a weak signature hash alg.
97+
as we already trust this certificate */
98+
uint32_t flags_filtered = *flags & ~(MBEDTLS_X509_BADCERT_BAD_MD);
99+
100+
if (flags_filtered != MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
101+
return 0;
102+
}
103+
104+
105+
if (s_crt_bundle.crts == NULL) {
106+
log_e("No certificates in bundle");
107+
return MBEDTLS_ERR_X509_FATAL_ERROR;
108+
}
109+
110+
log_d("%d certificates in bundle", s_crt_bundle.num_certs);
111+
112+
size_t name_len = 0;
113+
const uint8_t *crt_name;
114+
115+
bool crt_found = false;
116+
int start = 0;
117+
int end = s_crt_bundle.num_certs - 1;
118+
int middle = (end - start) / 2;
119+
120+
/* Look for the certificate using binary search on subject name */
121+
while (start <= end) {
122+
name_len = s_crt_bundle.crts[middle][0] << 8 | s_crt_bundle.crts[middle][1];
123+
crt_name = s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET;
124+
125+
int cmp_res = memcmp(child->issuer_raw.p, crt_name, name_len );
126+
if (cmp_res == 0) {
127+
crt_found = true;
128+
break;
129+
} else if (cmp_res < 0) {
130+
end = middle - 1;
131+
} else {
132+
start = middle + 1;
133+
}
134+
middle = (start + end) / 2;
135+
}
136+
137+
int ret = MBEDTLS_ERR_X509_FATAL_ERROR;
138+
if (crt_found) {
139+
size_t key_len = s_crt_bundle.crts[middle][2] << 8 | s_crt_bundle.crts[middle][3];
140+
ret = esp_crt_check_signature(child, s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET + name_len, key_len);
141+
}
142+
143+
if (ret == 0) {
144+
log_i("Certificate validated");
145+
*flags = 0;
146+
return 0;
147+
}
148+
149+
log_e("Failed to verify certificate");
150+
return MBEDTLS_ERR_X509_FATAL_ERROR;
151+
}
152+
153+
154+
/* Initialize the bundle into an array so we can do binary search for certs,
155+
the bundle generated by the python utility is already presorted by subject name
156+
*/
157+
static esp_err_t esp_crt_bundle_init(const uint8_t *x509_bundle)
158+
{
159+
s_crt_bundle.num_certs = (x509_bundle[0] << 8) | x509_bundle[1];
160+
s_crt_bundle.crts = calloc(s_crt_bundle.num_certs, sizeof(x509_bundle));
161+
162+
if (s_crt_bundle.crts == NULL) {
163+
log_e("Unable to allocate memory for bundle");
164+
return ESP_ERR_NO_MEM;
165+
}
166+
167+
const uint8_t *cur_crt;
168+
cur_crt = x509_bundle + BUNDLE_HEADER_OFFSET;
169+
170+
for (int i = 0; i < s_crt_bundle.num_certs; i++) {
171+
s_crt_bundle.crts[i] = cur_crt;
172+
173+
size_t name_len = cur_crt[0] << 8 | cur_crt[1];
174+
size_t key_len = cur_crt[2] << 8 | cur_crt[3];
175+
cur_crt = cur_crt + CRT_HEADER_OFFSET + name_len + key_len;
176+
}
177+
178+
return ESP_OK;
179+
}
180+
181+
esp_err_t esp_crt_bundle_attach(void *conf)
182+
{
183+
esp_err_t ret = ESP_OK;
184+
// If no bundle has been set by the user then use the bundle embedded in the binary
185+
if (s_crt_bundle.crts == NULL) {
186+
log_e("Failed to attach bundle");
187+
return ret;
188+
}
189+
190+
if (conf) {
191+
/* point to a dummy certificate
192+
* This is only required so that the
193+
* cacert_ptr passes non-NULL check during handshake
194+
*/
195+
mbedtls_ssl_config *ssl_conf = (mbedtls_ssl_config *)conf;
196+
mbedtls_x509_crt_init(&s_dummy_crt);
197+
mbedtls_ssl_conf_ca_chain(ssl_conf, &s_dummy_crt, NULL);
198+
mbedtls_ssl_conf_verify(ssl_conf, esp_crt_verify_callback, NULL);
199+
}
200+
201+
return ret;
202+
}
203+
204+
void esp_crt_bundle_detach(mbedtls_ssl_config *conf)
205+
{
206+
free(s_crt_bundle.crts);
207+
s_crt_bundle.crts = NULL;
208+
if (conf) {
209+
mbedtls_ssl_conf_verify(conf, NULL, NULL);
210+
}
211+
}
212+
213+
void esp_crt_bundle_set(const uint8_t *x509_bundle)
214+
{
215+
// Free any previously used bundle
216+
free(s_crt_bundle.crts);
217+
esp_crt_bundle_init(x509_bundle);
218+
}
+68Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Copyright 2017-2019 Espressif Systems (Shanghai) PTE LTD
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
16+
#ifndef _ESP_CRT_BUNDLE_H_
17+
#define _ESP_CRT_BUNDLE_H_
18+
19+
#include "mbedtls/ssl.h"
20+
21+
#ifdef __cplusplus
22+
extern "C" {
23+
#endif
24+
25+
26+
/**
27+
* @brief Attach and enable use of a bundle for certificate verification
28+
*
29+
* Attach and enable use of a bundle for certificate verification through a verification callback.
30+
* If no specific bundle has been set through esp_crt_bundle_set() it will default to the
31+
* bundle defined in menuconfig and embedded in the binary.
32+
*
33+
* @param[in] conf The config struct for the SSL connection.
34+
*
35+
* @return
36+
* - ESP_OK if adding certificates was successful.
37+
* - Other if an error occured or an action must be taken by the calling process.
38+
*/
39+
esp_err_t esp_crt_bundle_attach(void *conf);
40+
41+
42+
/**
43+
* @brief Disable and dealloc the certification bundle
44+
*
45+
* Removes the certificate verification callback and deallocates used resources
46+
*
47+
* @param[in] conf The config struct for the SSL connection.
48+
*/
49+
void esp_crt_bundle_detach(mbedtls_ssl_config *conf);
50+
51+
52+
/**
53+
* @brief Set the default certificate bundle used for verification
54+
*
55+
* Overrides the default certificate bundle. In most use cases the bundle should be
56+
* set through menuconfig. The bundle needs to be sorted by subject name since binary search is
57+
* used to find certificates.
58+
*
59+
* @param[in] x509_bundle A pointer to the certificate bundle.
60+
*/
61+
void esp_crt_bundle_set(const uint8_t *x509_bundle);
62+
63+
64+
#ifdef __cplusplus
65+
}
66+
#endif
67+
68+
#endif //_ESP_CRT_BUNDLE_H_

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.