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