1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Michael Forney, <mforney@mforney.org>
9 *
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.se/docs/copyright.html.
13 *
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 * SPDX-License-Identifier: curl
22 *
23 ***************************************************************************/
24 #include "curl_setup.h"
25
26 #ifdef USE_BEARSSL
27
28 #include <bearssl.h>
29
30 #include "bearssl.h"
31 #include "cipher_suite.h"
32 #include "urldata.h"
33 #include "sendf.h"
34 #include "inet_pton.h"
35 #include "vtls.h"
36 #include "vtls_int.h"
37 #include "vtls_scache.h"
38 #include "connect.h"
39 #include "select.h"
40 #include "multiif.h"
41 #include "curl_printf.h"
42
43 /* The last #include files should be: */
44 #include "curl_memory.h"
45 #include "memdebug.h"
46
47 struct x509_context {
48 const br_x509_class *vtable;
49 br_x509_minimal_context minimal;
50 br_x509_decoder_context decoder;
51 bool verifyhost;
52 bool verifypeer;
53 int cert_num;
54 };
55
56 struct bearssl_ssl_backend_data {
57 br_ssl_client_context ctx;
58 struct x509_context x509;
59 unsigned char buf[BR_SSL_BUFSIZE_BIDI];
60 br_x509_trust_anchor *anchors;
61 size_t anchors_len;
62 const char *protocols[ALPN_ENTRIES_MAX];
63 /* SSL client context is active */
64 bool active;
65 /* size of pending write, yet to be flushed */
66 size_t pending_write;
67 BIT(sent_shutdown);
68 };
69
70 struct cafile_parser {
71 CURLcode err;
72 bool in_cert;
73 br_x509_decoder_context xc;
74 /* array of trust anchors loaded from CAfile */
75 br_x509_trust_anchor *anchors;
76 size_t anchors_len;
77 /* buffer for DN data */
78 unsigned char dn[1024];
79 size_t dn_len;
80 };
81
82 #define CAFILE_SOURCE_PATH 1
83 #define CAFILE_SOURCE_BLOB 2
84 struct cafile_source {
85 int type;
86 const char *data;
87 size_t len;
88 };
89
append_dn(void * ctx,const void * buf,size_t len)90 static void append_dn(void *ctx, const void *buf, size_t len)
91 {
92 struct cafile_parser *ca = ctx;
93
94 if(ca->err != CURLE_OK || !ca->in_cert)
95 return;
96 if(sizeof(ca->dn) - ca->dn_len < len) {
97 ca->err = CURLE_FAILED_INIT;
98 return;
99 }
100 memcpy(ca->dn + ca->dn_len, buf, len);
101 ca->dn_len += len;
102 }
103
x509_push(void * ctx,const void * buf,size_t len)104 static void x509_push(void *ctx, const void *buf, size_t len)
105 {
106 struct cafile_parser *ca = ctx;
107
108 if(ca->in_cert)
109 br_x509_decoder_push(&ca->xc, buf, len);
110 }
111
load_cafile(struct cafile_source * source,br_x509_trust_anchor ** anchors,size_t * anchors_len)112 static CURLcode load_cafile(struct cafile_source *source,
113 br_x509_trust_anchor **anchors,
114 size_t *anchors_len)
115 {
116 struct cafile_parser ca;
117 br_pem_decoder_context pc;
118 br_x509_trust_anchor *ta;
119 size_t ta_size;
120 br_x509_trust_anchor *new_anchors;
121 size_t new_anchors_len;
122 br_x509_pkey *pkey;
123 FILE *fp = 0;
124 unsigned char buf[BUFSIZ];
125 const unsigned char *p = NULL;
126 const char *name;
127 size_t n = 0, i, pushed;
128
129 DEBUGASSERT(source->type == CAFILE_SOURCE_PATH
130 || source->type == CAFILE_SOURCE_BLOB);
131
132 if(source->type == CAFILE_SOURCE_PATH) {
133 fp = fopen(source->data, "rb");
134 if(!fp)
135 return CURLE_SSL_CACERT_BADFILE;
136 }
137
138 if(source->type == CAFILE_SOURCE_BLOB && source->len > (size_t)INT_MAX)
139 return CURLE_SSL_CACERT_BADFILE;
140
141 ca.err = CURLE_OK;
142 ca.in_cert = FALSE;
143 ca.anchors = NULL;
144 ca.anchors_len = 0;
145 br_pem_decoder_init(&pc);
146 br_pem_decoder_setdest(&pc, x509_push, &ca);
147 do {
148 if(source->type == CAFILE_SOURCE_PATH) {
149 n = fread(buf, 1, sizeof(buf), fp);
150 if(n == 0)
151 break;
152 p = buf;
153 }
154 else if(source->type == CAFILE_SOURCE_BLOB) {
155 n = source->len;
156 p = (unsigned char *) source->data;
157 }
158 while(n) {
159 pushed = br_pem_decoder_push(&pc, p, n);
160 if(ca.err)
161 goto fail;
162 p += pushed;
163 n -= pushed;
164
165 switch(br_pem_decoder_event(&pc)) {
166 case 0:
167 break;
168 case BR_PEM_BEGIN_OBJ:
169 name = br_pem_decoder_name(&pc);
170 if(strcmp(name, "CERTIFICATE") && strcmp(name, "X509 CERTIFICATE"))
171 break;
172 br_x509_decoder_init(&ca.xc, append_dn, &ca);
173 ca.in_cert = TRUE;
174 ca.dn_len = 0;
175 break;
176 case BR_PEM_END_OBJ:
177 if(!ca.in_cert)
178 break;
179 ca.in_cert = FALSE;
180 if(br_x509_decoder_last_error(&ca.xc)) {
181 ca.err = CURLE_SSL_CACERT_BADFILE;
182 goto fail;
183 }
184 /* add trust anchor */
185 if(ca.anchors_len == SIZE_MAX / sizeof(ca.anchors[0])) {
186 ca.err = CURLE_OUT_OF_MEMORY;
187 goto fail;
188 }
189 new_anchors_len = ca.anchors_len + 1;
190 new_anchors = realloc(ca.anchors,
191 new_anchors_len * sizeof(ca.anchors[0]));
192 if(!new_anchors) {
193 ca.err = CURLE_OUT_OF_MEMORY;
194 goto fail;
195 }
196 ca.anchors = new_anchors;
197 ca.anchors_len = new_anchors_len;
198 ta = &ca.anchors[ca.anchors_len - 1];
199 ta->dn.data = NULL;
200 ta->flags = 0;
201 if(br_x509_decoder_isCA(&ca.xc))
202 ta->flags |= BR_X509_TA_CA;
203 pkey = br_x509_decoder_get_pkey(&ca.xc);
204 if(!pkey) {
205 ca.err = CURLE_SSL_CACERT_BADFILE;
206 goto fail;
207 }
208 ta->pkey = *pkey;
209
210 /* calculate space needed for trust anchor data */
211 ta_size = ca.dn_len;
212 switch(pkey->key_type) {
213 case BR_KEYTYPE_RSA:
214 ta_size += pkey->key.rsa.nlen + pkey->key.rsa.elen;
215 break;
216 case BR_KEYTYPE_EC:
217 ta_size += pkey->key.ec.qlen;
218 break;
219 default:
220 ca.err = CURLE_FAILED_INIT;
221 goto fail;
222 }
223
224 /* fill in trust anchor DN and public key data */
225 ta->dn.data = malloc(ta_size);
226 if(!ta->dn.data) {
227 ca.err = CURLE_OUT_OF_MEMORY;
228 goto fail;
229 }
230 memcpy(ta->dn.data, ca.dn, ca.dn_len);
231 ta->dn.len = ca.dn_len;
232 switch(pkey->key_type) {
233 case BR_KEYTYPE_RSA:
234 ta->pkey.key.rsa.n = ta->dn.data + ta->dn.len;
235 memcpy(ta->pkey.key.rsa.n, pkey->key.rsa.n, pkey->key.rsa.nlen);
236 ta->pkey.key.rsa.e = ta->pkey.key.rsa.n + ta->pkey.key.rsa.nlen;
237 memcpy(ta->pkey.key.rsa.e, pkey->key.rsa.e, pkey->key.rsa.elen);
238 break;
239 case BR_KEYTYPE_EC:
240 ta->pkey.key.ec.q = ta->dn.data + ta->dn.len;
241 memcpy(ta->pkey.key.ec.q, pkey->key.ec.q, pkey->key.ec.qlen);
242 break;
243 }
244 break;
245 default:
246 ca.err = CURLE_SSL_CACERT_BADFILE;
247 goto fail;
248 }
249 }
250 } while(source->type != CAFILE_SOURCE_BLOB);
251 if(fp && ferror(fp))
252 ca.err = CURLE_READ_ERROR;
253 else if(ca.in_cert)
254 ca.err = CURLE_SSL_CACERT_BADFILE;
255
256 fail:
257 if(fp)
258 fclose(fp);
259 if(ca.err == CURLE_OK) {
260 *anchors = ca.anchors;
261 *anchors_len = ca.anchors_len;
262 }
263 else {
264 for(i = 0; i < ca.anchors_len; ++i)
265 free(ca.anchors[i].dn.data);
266 free(ca.anchors);
267 }
268
269 return ca.err;
270 }
271
x509_start_chain(const br_x509_class ** ctx,const char * server_name)272 static void x509_start_chain(const br_x509_class **ctx,
273 const char *server_name)
274 {
275 struct x509_context *x509 = (struct x509_context *)ctx;
276
277 if(!x509->verifypeer) {
278 x509->cert_num = 0;
279 return;
280 }
281
282 if(!x509->verifyhost)
283 server_name = NULL;
284 x509->minimal.vtable->start_chain(&x509->minimal.vtable, server_name);
285 }
286
x509_start_cert(const br_x509_class ** ctx,uint32_t length)287 static void x509_start_cert(const br_x509_class **ctx, uint32_t length)
288 {
289 struct x509_context *x509 = (struct x509_context *)ctx;
290
291 if(!x509->verifypeer) {
292 /* Only decode the first cert in the chain to obtain the public key */
293 if(x509->cert_num == 0)
294 br_x509_decoder_init(&x509->decoder, NULL, NULL);
295 return;
296 }
297
298 x509->minimal.vtable->start_cert(&x509->minimal.vtable, length);
299 }
300
x509_append(const br_x509_class ** ctx,const unsigned char * buf,size_t len)301 static void x509_append(const br_x509_class **ctx, const unsigned char *buf,
302 size_t len)
303 {
304 struct x509_context *x509 = (struct x509_context *)ctx;
305
306 if(!x509->verifypeer) {
307 if(x509->cert_num == 0)
308 br_x509_decoder_push(&x509->decoder, buf, len);
309 return;
310 }
311
312 x509->minimal.vtable->append(&x509->minimal.vtable, buf, len);
313 }
314
x509_end_cert(const br_x509_class ** ctx)315 static void x509_end_cert(const br_x509_class **ctx)
316 {
317 struct x509_context *x509 = (struct x509_context *)ctx;
318
319 if(!x509->verifypeer) {
320 x509->cert_num++;
321 return;
322 }
323
324 x509->minimal.vtable->end_cert(&x509->minimal.vtable);
325 }
326
x509_end_chain(const br_x509_class ** ctx)327 static unsigned x509_end_chain(const br_x509_class **ctx)
328 {
329 struct x509_context *x509 = (struct x509_context *)ctx;
330
331 if(!x509->verifypeer) {
332 return (unsigned)br_x509_decoder_last_error(&x509->decoder);
333 }
334
335 return x509->minimal.vtable->end_chain(&x509->minimal.vtable);
336 }
337
x509_get_pkey(const br_x509_class * const * ctx,unsigned * usages)338 static const br_x509_pkey *x509_get_pkey(const br_x509_class *const *ctx,
339 unsigned *usages)
340 {
341 struct x509_context *x509 = (struct x509_context *)ctx;
342
343 if(!x509->verifypeer) {
344 /* Nothing in the chain is verified, just return the public key of the
345 first certificate and allow its usage for both TLS_RSA_* and
346 TLS_ECDHE_* */
347 if(usages)
348 *usages = BR_KEYTYPE_KEYX | BR_KEYTYPE_SIGN;
349 return br_x509_decoder_get_pkey(&x509->decoder);
350 }
351
352 return x509->minimal.vtable->get_pkey(&x509->minimal.vtable, usages);
353 }
354
355 static const br_x509_class x509_vtable = {
356 sizeof(struct x509_context),
357 x509_start_chain,
358 x509_start_cert,
359 x509_append,
360 x509_end_cert,
361 x509_end_chain,
362 x509_get_pkey
363 };
364
365 static CURLcode
bearssl_set_ssl_version_min_max(struct Curl_easy * data,br_ssl_engine_context * ssl_eng,struct ssl_primary_config * conn_config)366 bearssl_set_ssl_version_min_max(struct Curl_easy *data,
367 br_ssl_engine_context *ssl_eng,
368 struct ssl_primary_config *conn_config)
369 {
370 unsigned version_min, version_max;
371
372 switch(conn_config->version) {
373 case CURL_SSLVERSION_DEFAULT:
374 case CURL_SSLVERSION_TLSv1:
375 case CURL_SSLVERSION_TLSv1_0:
376 version_min = BR_TLS10;
377 break;
378 case CURL_SSLVERSION_TLSv1_1:
379 version_min = BR_TLS11;
380 break;
381 case CURL_SSLVERSION_TLSv1_2:
382 version_min = BR_TLS12;
383 break;
384 case CURL_SSLVERSION_TLSv1_3:
385 failf(data, "BearSSL: does not support TLS 1.3");
386 return CURLE_SSL_CONNECT_ERROR;
387 default:
388 failf(data, "BearSSL: unsupported minimum TLS version value");
389 return CURLE_SSL_CONNECT_ERROR;
390 }
391
392 switch(conn_config->version_max) {
393 case CURL_SSLVERSION_MAX_DEFAULT:
394 case CURL_SSLVERSION_MAX_NONE:
395 case CURL_SSLVERSION_MAX_TLSv1_3:
396 case CURL_SSLVERSION_MAX_TLSv1_2:
397 version_max = BR_TLS12;
398 break;
399 case CURL_SSLVERSION_MAX_TLSv1_1:
400 version_max = BR_TLS11;
401 break;
402 case CURL_SSLVERSION_MAX_TLSv1_0:
403 version_max = BR_TLS10;
404 break;
405 default:
406 failf(data, "BearSSL: unsupported maximum TLS version value");
407 return CURLE_SSL_CONNECT_ERROR;
408 }
409
410 br_ssl_engine_set_versions(ssl_eng, version_min, version_max);
411
412 return CURLE_OK;
413 }
414
415 static const uint16_t ciphertable[] = {
416 /* RFC 2246 TLS 1.0 */
417 BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x000A */
418
419 /* RFC 3268 TLS 1.0 AES */
420 BR_TLS_RSA_WITH_AES_128_CBC_SHA, /* 0x002F */
421 BR_TLS_RSA_WITH_AES_256_CBC_SHA, /* 0x0035 */
422
423 /* RFC 5246 TLS 1.2 */
424 BR_TLS_RSA_WITH_AES_128_CBC_SHA256, /* 0x003C */
425 BR_TLS_RSA_WITH_AES_256_CBC_SHA256, /* 0x003D */
426
427 /* RFC 5288 TLS 1.2 AES GCM */
428 BR_TLS_RSA_WITH_AES_128_GCM_SHA256, /* 0x009C */
429 BR_TLS_RSA_WITH_AES_256_GCM_SHA384, /* 0x009D */
430
431 /* RFC 4492 TLS 1.0 ECC */
432 BR_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC003 */
433 BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC004 */
434 BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC005 */
435 BR_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC008 */
436 BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC009 */
437 BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC00A */
438 BR_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC00D */
439 BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, /* 0xC00E */
440 BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, /* 0xC00F */
441 BR_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC012 */
442 BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, /* 0xC013 */
443 BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, /* 0xC014 */
444
445 /* RFC 5289 TLS 1.2 ECC HMAC SHA256/384 */
446 BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC023 */
447 BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC024 */
448 BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC025 */
449 BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC026 */
450 BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, /* 0xC027 */
451 BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, /* 0xC028 */
452 BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, /* 0xC029 */
453 BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, /* 0xC02A */
454
455 /* RFC 5289 TLS 1.2 GCM */
456 BR_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02B */
457 BR_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02C */
458 BR_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02D */
459 BR_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02E */
460 BR_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, /* 0xC02F */
461 BR_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, /* 0xC030 */
462 BR_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, /* 0xC031 */
463 BR_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, /* 0xC032 */
464
465 #ifdef BR_TLS_RSA_WITH_AES_128_CCM
466 /* RFC 6655 TLS 1.2 CCM
467 Supported since BearSSL 0.6 */
468 BR_TLS_RSA_WITH_AES_128_CCM, /* 0xC09C */
469 BR_TLS_RSA_WITH_AES_256_CCM, /* 0xC09D */
470 BR_TLS_RSA_WITH_AES_128_CCM_8, /* 0xC0A0 */
471 BR_TLS_RSA_WITH_AES_256_CCM_8, /* 0xC0A1 */
472
473 /* RFC 7251 TLS 1.2 ECC CCM
474 Supported since BearSSL 0.6 */
475 BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, /* 0xC0AC */
476 BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, /* 0xC0AD */
477 BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, /* 0xC0AE */
478 BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8, /* 0xC0AF */
479 #endif
480
481 /* RFC 7905 TLS 1.2 ChaCha20-Poly1305
482 Supported since BearSSL 0.2 */
483 BR_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA8 */
484 BR_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA9 */
485 };
486
487 #define NUM_OF_CIPHERS (sizeof(ciphertable) / sizeof(ciphertable[0]))
488
bearssl_set_selected_ciphers(struct Curl_easy * data,br_ssl_engine_context * ssl_eng,const char * ciphers)489 static CURLcode bearssl_set_selected_ciphers(struct Curl_easy *data,
490 br_ssl_engine_context *ssl_eng,
491 const char *ciphers)
492 {
493 uint16_t selected[NUM_OF_CIPHERS];
494 size_t count = 0, i;
495 const char *ptr, *end;
496
497 for(ptr = ciphers; ptr[0] != '\0' && count < NUM_OF_CIPHERS; ptr = end) {
498 uint16_t id = Curl_cipher_suite_walk_str(&ptr, &end);
499
500 /* Check if cipher is supported */
501 if(id) {
502 for(i = 0; i < NUM_OF_CIPHERS && ciphertable[i] != id; i++);
503 if(i == NUM_OF_CIPHERS)
504 id = 0;
505 }
506 if(!id) {
507 if(ptr[0] != '\0')
508 infof(data, "BearSSL: unknown cipher in list: \"%.*s\"",
509 (int) (end - ptr), ptr);
510 continue;
511 }
512
513 /* No duplicates allowed */
514 for(i = 0; i < count && selected[i] != id; i++);
515 if(i < count) {
516 infof(data, "BearSSL: duplicate cipher in list: \"%.*s\"",
517 (int) (end - ptr), ptr);
518 continue;
519 }
520
521 selected[count++] = id;
522 }
523
524 if(count == 0) {
525 failf(data, "BearSSL: no supported cipher in list");
526 return CURLE_SSL_CIPHER;
527 }
528
529 br_ssl_engine_set_suites(ssl_eng, selected, count);
530 return CURLE_OK;
531 }
532
bearssl_connect_step1(struct Curl_cfilter * cf,struct Curl_easy * data)533 static CURLcode bearssl_connect_step1(struct Curl_cfilter *cf,
534 struct Curl_easy *data)
535 {
536 struct ssl_connect_data *connssl = cf->ctx;
537 struct bearssl_ssl_backend_data *backend =
538 (struct bearssl_ssl_backend_data *)connssl->backend;
539 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
540 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
541 const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
542 const char * const ssl_cafile =
543 /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
544 (ca_info_blob ? NULL : conn_config->CAfile);
545 const char *hostname = connssl->peer.hostname;
546 const bool verifypeer = conn_config->verifypeer;
547 const bool verifyhost = conn_config->verifyhost;
548 CURLcode ret;
549 int session_set = 0;
550
551 DEBUGASSERT(backend);
552 CURL_TRC_CF(data, cf, "connect_step1");
553
554 if(verifypeer) {
555 if(ca_info_blob) {
556 struct cafile_source source;
557 source.type = CAFILE_SOURCE_BLOB;
558 source.data = ca_info_blob->data;
559 source.len = ca_info_blob->len;
560
561 CURL_TRC_CF(data, cf, "connect_step1, load ca_info_blob");
562 ret = load_cafile(&source, &backend->anchors, &backend->anchors_len);
563 if(ret != CURLE_OK) {
564 failf(data, "error importing CA certificate blob");
565 return ret;
566 }
567 }
568
569 if(ssl_cafile) {
570 struct cafile_source source;
571 source.type = CAFILE_SOURCE_PATH;
572 source.data = ssl_cafile;
573 source.len = 0;
574
575 CURL_TRC_CF(data, cf, "connect_step1, load cafile");
576 ret = load_cafile(&source, &backend->anchors, &backend->anchors_len);
577 if(ret != CURLE_OK) {
578 failf(data, "error setting certificate verify locations."
579 " CAfile: %s", ssl_cafile);
580 return ret;
581 }
582 }
583 }
584
585 /* initialize SSL context */
586 br_ssl_client_init_full(&backend->ctx, &backend->x509.minimal,
587 backend->anchors, backend->anchors_len);
588
589 ret = bearssl_set_ssl_version_min_max(data, &backend->ctx.eng, conn_config);
590 if(ret != CURLE_OK)
591 return ret;
592
593 br_ssl_engine_set_buffer(&backend->ctx.eng, backend->buf,
594 sizeof(backend->buf), 1);
595
596 if(conn_config->cipher_list) {
597 /* Override the ciphers as specified. For the default cipher list see the
598 BearSSL source code of br_ssl_client_init_full() */
599 CURL_TRC_CF(data, cf, "connect_step1, set ciphers");
600 ret = bearssl_set_selected_ciphers(data, &backend->ctx.eng,
601 conn_config->cipher_list);
602 if(ret)
603 return ret;
604 }
605
606 /* initialize X.509 context */
607 backend->x509.vtable = &x509_vtable;
608 backend->x509.verifypeer = verifypeer;
609 backend->x509.verifyhost = verifyhost;
610 br_ssl_engine_set_x509(&backend->ctx.eng, &backend->x509.vtable);
611
612 if(ssl_config->primary.cache_session) {
613 struct Curl_ssl_session *sc_session = NULL;
614 const br_ssl_session_parameters *session;
615
616 ret = Curl_ssl_scache_take(cf, data, connssl->peer.scache_key,
617 &sc_session);
618 if(!ret && sc_session && sc_session->sdata && sc_session->sdata_len) {
619 session = (br_ssl_session_parameters *)(void *)sc_session->sdata;
620 br_ssl_engine_set_session_parameters(&backend->ctx.eng, session);
621 session_set = 1;
622 infof(data, "BearSSL: reusing session ID");
623 /* single use of sessions */
624 Curl_ssl_scache_return(cf, data, connssl->peer.scache_key, sc_session);
625 }
626 }
627
628 if(connssl->alpn) {
629 struct alpn_proto_buf proto;
630 size_t i;
631
632 for(i = 0; i < connssl->alpn->count; ++i) {
633 backend->protocols[i] = connssl->alpn->entries[i];
634 }
635 br_ssl_engine_set_protocol_names(&backend->ctx.eng, backend->protocols,
636 connssl->alpn->count);
637 Curl_alpn_to_proto_str(&proto, connssl->alpn);
638 infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
639 }
640
641 if(connssl->peer.type != CURL_SSL_PEER_DNS) {
642 if(verifyhost) {
643 failf(data, "BearSSL: "
644 "host verification of IP address is not supported");
645 return CURLE_PEER_FAILED_VERIFICATION;
646 }
647 hostname = NULL;
648 }
649 else {
650 if(!connssl->peer.sni) {
651 failf(data, "Failed to set SNI");
652 return CURLE_SSL_CONNECT_ERROR;
653 }
654 hostname = connssl->peer.sni;
655 CURL_TRC_CF(data, cf, "connect_step1, SNI set");
656 }
657
658 /* give application a chance to interfere with SSL set up. */
659 if(data->set.ssl.fsslctx) {
660 Curl_set_in_callback(data, TRUE);
661 ret = (*data->set.ssl.fsslctx)(data, &backend->ctx,
662 data->set.ssl.fsslctxp);
663 Curl_set_in_callback(data, FALSE);
664 if(ret) {
665 failf(data, "BearSSL: error signaled by ssl ctx callback");
666 return ret;
667 }
668 }
669
670 if(!br_ssl_client_reset(&backend->ctx, hostname, session_set))
671 return CURLE_FAILED_INIT;
672 backend->active = TRUE;
673
674 connssl->connecting_state = ssl_connect_2;
675
676 return CURLE_OK;
677 }
678
bearssl_run_until(struct Curl_cfilter * cf,struct Curl_easy * data,unsigned target)679 static CURLcode bearssl_run_until(struct Curl_cfilter *cf,
680 struct Curl_easy *data,
681 unsigned target)
682 {
683 struct ssl_connect_data *connssl = cf->ctx;
684 struct bearssl_ssl_backend_data *backend =
685 (struct bearssl_ssl_backend_data *)connssl->backend;
686 unsigned state;
687 unsigned char *buf;
688 size_t len;
689 ssize_t ret;
690 CURLcode result;
691 int err;
692
693 DEBUGASSERT(backend);
694
695 connssl->io_need = CURL_SSL_IO_NEED_NONE;
696 for(;;) {
697 state = br_ssl_engine_current_state(&backend->ctx.eng);
698 if(state & BR_SSL_CLOSED) {
699 err = br_ssl_engine_last_error(&backend->ctx.eng);
700 switch(err) {
701 case BR_ERR_OK:
702 /* TLS close notify */
703 if(connssl->state != ssl_connection_complete) {
704 failf(data, "SSL: connection closed during handshake");
705 return CURLE_SSL_CONNECT_ERROR;
706 }
707 return CURLE_OK;
708 case BR_ERR_X509_EXPIRED:
709 failf(data, "SSL: X.509 verification: "
710 "certificate is expired or not yet valid");
711 return CURLE_PEER_FAILED_VERIFICATION;
712 case BR_ERR_X509_BAD_SERVER_NAME:
713 failf(data, "SSL: X.509 verification: "
714 "expected server name was not found in the chain");
715 return CURLE_PEER_FAILED_VERIFICATION;
716 case BR_ERR_X509_NOT_TRUSTED:
717 failf(data, "SSL: X.509 verification: "
718 "chain could not be linked to a trust anchor");
719 return CURLE_PEER_FAILED_VERIFICATION;
720 default:;
721 }
722 failf(data, "BearSSL: connection error 0x%04x", err);
723 /* X.509 errors are documented to have the range 32..63 */
724 if(err >= 32 && err < 64)
725 return CURLE_PEER_FAILED_VERIFICATION;
726 return CURLE_SSL_CONNECT_ERROR;
727 }
728 if(state & target)
729 return CURLE_OK;
730 if(state & BR_SSL_SENDREC) {
731 buf = br_ssl_engine_sendrec_buf(&backend->ctx.eng, &len);
732 ret = Curl_conn_cf_send(cf->next, data, (char *)buf, len, FALSE,
733 &result);
734 CURL_TRC_CF(data, cf, "ssl_send(len=%zu) -> %zd, %d", len, ret, result);
735 if(ret <= 0) {
736 if(result == CURLE_AGAIN)
737 connssl->io_need |= CURL_SSL_IO_NEED_SEND;
738 return result;
739 }
740 br_ssl_engine_sendrec_ack(&backend->ctx.eng, ret);
741 }
742 else if(state & BR_SSL_RECVREC) {
743 buf = br_ssl_engine_recvrec_buf(&backend->ctx.eng, &len);
744 ret = Curl_conn_cf_recv(cf->next, data, (char *)buf, len, &result);
745 CURL_TRC_CF(data, cf, "ssl_recv(len=%zu) -> %zd, %d", len, ret, result);
746 if(ret == 0) {
747 failf(data, "SSL: EOF without close notify");
748 return CURLE_RECV_ERROR;
749 }
750 if(ret <= 0) {
751 if(result == CURLE_AGAIN)
752 connssl->io_need |= CURL_SSL_IO_NEED_RECV;
753 return result;
754 }
755 br_ssl_engine_recvrec_ack(&backend->ctx.eng, ret);
756 }
757 }
758 }
759
bearssl_connect_step2(struct Curl_cfilter * cf,struct Curl_easy * data)760 static CURLcode bearssl_connect_step2(struct Curl_cfilter *cf,
761 struct Curl_easy *data)
762 {
763 struct ssl_connect_data *connssl = cf->ctx;
764 struct bearssl_ssl_backend_data *backend =
765 (struct bearssl_ssl_backend_data *)connssl->backend;
766 br_ssl_session_parameters session;
767 char cipher_str[64];
768 CURLcode ret;
769
770 DEBUGASSERT(backend);
771 CURL_TRC_CF(data, cf, "connect_step2");
772
773 ret = bearssl_run_until(cf, data, BR_SSL_SENDAPP | BR_SSL_RECVAPP);
774 if(ret == CURLE_AGAIN)
775 return CURLE_OK;
776 if(ret == CURLE_OK) {
777 unsigned int tver;
778 int subver = 0;
779
780 if(br_ssl_engine_current_state(&backend->ctx.eng) == BR_SSL_CLOSED) {
781 failf(data, "SSL: connection closed during handshake");
782 return CURLE_SSL_CONNECT_ERROR;
783 }
784 connssl->connecting_state = ssl_connect_3;
785 /* Informational message */
786 tver = br_ssl_engine_get_version(&backend->ctx.eng);
787 switch(tver) {
788 case BR_TLS12:
789 subver = 2; /* 1.2 */
790 break;
791 case BR_TLS11:
792 subver = 1; /* 1.1 */
793 break;
794 case BR_TLS10: /* 1.0 */
795 default: /* unknown, leave it at zero */
796 break;
797 }
798 br_ssl_engine_get_session_parameters(&backend->ctx.eng, &session);
799 Curl_cipher_suite_get_str(session.cipher_suite, cipher_str,
800 sizeof(cipher_str), TRUE);
801 infof(data, "BearSSL: TLS v1.%d connection using %s", subver,
802 cipher_str);
803 }
804 return ret;
805 }
806
bearssl_connect_step3(struct Curl_cfilter * cf,struct Curl_easy * data)807 static CURLcode bearssl_connect_step3(struct Curl_cfilter *cf,
808 struct Curl_easy *data)
809 {
810 struct ssl_connect_data *connssl = cf->ctx;
811 struct bearssl_ssl_backend_data *backend =
812 (struct bearssl_ssl_backend_data *)connssl->backend;
813 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
814 CURLcode ret;
815
816 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
817 DEBUGASSERT(backend);
818 CURL_TRC_CF(data, cf, "connect_step3");
819
820 if(connssl->alpn) {
821 const char *proto;
822
823 proto = br_ssl_engine_get_selected_protocol(&backend->ctx.eng);
824 Curl_alpn_set_negotiated(cf, data, connssl, (const unsigned char *)proto,
825 proto ? strlen(proto) : 0);
826 }
827
828 if(ssl_config->primary.cache_session) {
829 struct Curl_ssl_session *sc_session;
830 br_ssl_session_parameters *session;
831
832 session = malloc(sizeof(*session));
833 if(!session)
834 return CURLE_OUT_OF_MEMORY;
835 br_ssl_engine_get_session_parameters(&backend->ctx.eng, session);
836 ret = Curl_ssl_session_create((unsigned char *)session, sizeof(*session),
837 (int)session->version,
838 connssl->negotiated.alpn,
839 0, -1, &sc_session);
840 if(!ret) {
841 ret = Curl_ssl_scache_put(cf, data, connssl->peer.scache_key,
842 sc_session);
843 /* took ownership of `sc_session` */
844 }
845 if(ret)
846 return ret;
847 }
848
849 connssl->connecting_state = ssl_connect_done;
850
851 return CURLE_OK;
852 }
853
bearssl_send(struct Curl_cfilter * cf,struct Curl_easy * data,const void * buf,size_t len,CURLcode * err)854 static ssize_t bearssl_send(struct Curl_cfilter *cf, struct Curl_easy *data,
855 const void *buf, size_t len, CURLcode *err)
856 {
857 struct ssl_connect_data *connssl = cf->ctx;
858 struct bearssl_ssl_backend_data *backend =
859 (struct bearssl_ssl_backend_data *)connssl->backend;
860 unsigned char *app;
861 size_t applen;
862
863 DEBUGASSERT(backend);
864
865 for(;;) {
866 *err = bearssl_run_until(cf, data, BR_SSL_SENDAPP);
867 if(*err)
868 return -1;
869 app = br_ssl_engine_sendapp_buf(&backend->ctx.eng, &applen);
870 if(!app) {
871 failf(data, "SSL: connection closed during write");
872 *err = CURLE_SEND_ERROR;
873 return -1;
874 }
875 if(backend->pending_write) {
876 applen = backend->pending_write;
877 backend->pending_write = 0;
878 return applen;
879 }
880 if(applen > len)
881 applen = len;
882 memcpy(app, buf, applen);
883 br_ssl_engine_sendapp_ack(&backend->ctx.eng, applen);
884 br_ssl_engine_flush(&backend->ctx.eng, 0);
885 backend->pending_write = applen;
886 }
887 }
888
bearssl_recv(struct Curl_cfilter * cf,struct Curl_easy * data,char * buf,size_t len,CURLcode * err)889 static ssize_t bearssl_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
890 char *buf, size_t len, CURLcode *err)
891 {
892 struct ssl_connect_data *connssl = cf->ctx;
893 struct bearssl_ssl_backend_data *backend =
894 (struct bearssl_ssl_backend_data *)connssl->backend;
895 unsigned char *app;
896 size_t applen;
897
898 DEBUGASSERT(backend);
899
900 *err = bearssl_run_until(cf, data, BR_SSL_RECVAPP);
901 if(*err != CURLE_OK)
902 return -1;
903 app = br_ssl_engine_recvapp_buf(&backend->ctx.eng, &applen);
904 if(!app)
905 return 0;
906 if(applen > len)
907 applen = len;
908 memcpy(buf, app, applen);
909 br_ssl_engine_recvapp_ack(&backend->ctx.eng, applen);
910
911 return applen;
912 }
913
bearssl_connect_common(struct Curl_cfilter * cf,struct Curl_easy * data,bool nonblocking,bool * done)914 static CURLcode bearssl_connect_common(struct Curl_cfilter *cf,
915 struct Curl_easy *data,
916 bool nonblocking,
917 bool *done)
918 {
919 CURLcode ret;
920 struct ssl_connect_data *connssl = cf->ctx;
921 curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
922 timediff_t timeout_ms;
923 int what;
924
925 CURL_TRC_CF(data, cf, "connect_common(blocking=%d)", !nonblocking);
926 /* check if the connection has already been established */
927 if(ssl_connection_complete == connssl->state) {
928 CURL_TRC_CF(data, cf, "connect_common, connected");
929 *done = TRUE;
930 return CURLE_OK;
931 }
932
933 if(ssl_connect_1 == connssl->connecting_state) {
934 ret = bearssl_connect_step1(cf, data);
935 if(ret)
936 return ret;
937 }
938
939 while(ssl_connect_2 == connssl->connecting_state) {
940 /* check allowed time left */
941 timeout_ms = Curl_timeleft(data, NULL, TRUE);
942
943 if(timeout_ms < 0) {
944 /* no need to continue if time already is up */
945 failf(data, "SSL connection timeout");
946 return CURLE_OPERATION_TIMEDOUT;
947 }
948
949 /* if ssl is expecting something, check if it is available. */
950 if(connssl->io_need) {
951 curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ?
952 sockfd : CURL_SOCKET_BAD;
953 curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ?
954 sockfd : CURL_SOCKET_BAD;
955
956 CURL_TRC_CF(data, cf, "connect_common, check socket");
957 what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
958 nonblocking ? 0 : timeout_ms);
959 CURL_TRC_CF(data, cf, "connect_common, check socket -> %d", what);
960 if(what < 0) {
961 /* fatal error */
962 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
963 return CURLE_SSL_CONNECT_ERROR;
964 }
965 else if(0 == what) {
966 if(nonblocking) {
967 *done = FALSE;
968 return CURLE_OK;
969 }
970 else {
971 /* timeout */
972 failf(data, "SSL connection timeout");
973 return CURLE_OPERATION_TIMEDOUT;
974 }
975 }
976 /* socket is readable or writable */
977 }
978
979 /* Run transaction, and return to the caller if it failed or if this
980 * connection is done nonblocking and this loop would execute again. This
981 * permits the owner of a multi handle to abort a connection attempt
982 * before step2 has completed while ensuring that a client using select()
983 * or epoll() will always have a valid fdset to wait on.
984 */
985 connssl->io_need = CURL_SSL_IO_NEED_NONE;
986 ret = bearssl_connect_step2(cf, data);
987 if(ret || (nonblocking && (ssl_connect_2 == connssl->connecting_state)))
988 return ret;
989 }
990
991 if(ssl_connect_3 == connssl->connecting_state) {
992 ret = bearssl_connect_step3(cf, data);
993 if(ret)
994 return ret;
995 }
996
997 if(ssl_connect_done == connssl->connecting_state) {
998 connssl->state = ssl_connection_complete;
999 *done = TRUE;
1000 }
1001 else
1002 *done = FALSE;
1003
1004 /* Reset our connect state machine */
1005 connssl->connecting_state = ssl_connect_1;
1006
1007 return CURLE_OK;
1008 }
1009
bearssl_version(char * buffer,size_t size)1010 static size_t bearssl_version(char *buffer, size_t size)
1011 {
1012 return msnprintf(buffer, size, "BearSSL");
1013 }
1014
bearssl_data_pending(struct Curl_cfilter * cf,const struct Curl_easy * data)1015 static bool bearssl_data_pending(struct Curl_cfilter *cf,
1016 const struct Curl_easy *data)
1017 {
1018 struct ssl_connect_data *ctx = cf->ctx;
1019 struct bearssl_ssl_backend_data *backend;
1020
1021 (void)data;
1022 DEBUGASSERT(ctx && ctx->backend);
1023 backend = (struct bearssl_ssl_backend_data *)ctx->backend;
1024 return br_ssl_engine_current_state(&backend->ctx.eng) & BR_SSL_RECVAPP;
1025 }
1026
bearssl_random(struct Curl_easy * data UNUSED_PARAM,unsigned char * entropy,size_t length)1027 static CURLcode bearssl_random(struct Curl_easy *data UNUSED_PARAM,
1028 unsigned char *entropy, size_t length)
1029 {
1030 static br_hmac_drbg_context ctx;
1031 static bool seeded = FALSE;
1032
1033 if(!seeded) {
1034 br_prng_seeder seeder;
1035
1036 br_hmac_drbg_init(&ctx, &br_sha256_vtable, NULL, 0);
1037 seeder = br_prng_seeder_system(NULL);
1038 if(!seeder || !seeder(&ctx.vtable))
1039 return CURLE_FAILED_INIT;
1040 seeded = TRUE;
1041 }
1042 br_hmac_drbg_generate(&ctx, entropy, length);
1043
1044 return CURLE_OK;
1045 }
1046
bearssl_connect(struct Curl_cfilter * cf,struct Curl_easy * data)1047 static CURLcode bearssl_connect(struct Curl_cfilter *cf,
1048 struct Curl_easy *data)
1049 {
1050 CURLcode ret;
1051 bool done = FALSE;
1052
1053 ret = bearssl_connect_common(cf, data, FALSE, &done);
1054 if(ret)
1055 return ret;
1056
1057 DEBUGASSERT(done);
1058
1059 return CURLE_OK;
1060 }
1061
bearssl_connect_nonblocking(struct Curl_cfilter * cf,struct Curl_easy * data,bool * done)1062 static CURLcode bearssl_connect_nonblocking(struct Curl_cfilter *cf,
1063 struct Curl_easy *data,
1064 bool *done)
1065 {
1066 return bearssl_connect_common(cf, data, TRUE, done);
1067 }
1068
bearssl_get_internals(struct ssl_connect_data * connssl,CURLINFO info UNUSED_PARAM)1069 static void *bearssl_get_internals(struct ssl_connect_data *connssl,
1070 CURLINFO info UNUSED_PARAM)
1071 {
1072 struct bearssl_ssl_backend_data *backend =
1073 (struct bearssl_ssl_backend_data *)connssl->backend;
1074 DEBUGASSERT(backend);
1075 return &backend->ctx;
1076 }
1077
bearssl_shutdown(struct Curl_cfilter * cf,struct Curl_easy * data,bool send_shutdown,bool * done)1078 static CURLcode bearssl_shutdown(struct Curl_cfilter *cf,
1079 struct Curl_easy *data,
1080 bool send_shutdown, bool *done)
1081 {
1082 struct ssl_connect_data *connssl = cf->ctx;
1083 struct bearssl_ssl_backend_data *backend =
1084 (struct bearssl_ssl_backend_data *)connssl->backend;
1085 CURLcode result;
1086
1087 DEBUGASSERT(backend);
1088 if(!backend->active || cf->shutdown) {
1089 *done = TRUE;
1090 return CURLE_OK;
1091 }
1092
1093 *done = FALSE;
1094 if(!backend->sent_shutdown) {
1095 (void)send_shutdown; /* unknown how to suppress our close notify */
1096 br_ssl_engine_close(&backend->ctx.eng);
1097 backend->sent_shutdown = TRUE;
1098 }
1099
1100 result = bearssl_run_until(cf, data, BR_SSL_CLOSED);
1101 if(result == CURLE_OK) {
1102 *done = TRUE;
1103 }
1104 else if(result == CURLE_AGAIN) {
1105 CURL_TRC_CF(data, cf, "shutdown EAGAIN, io_need=%x", connssl->io_need);
1106 result = CURLE_OK;
1107 }
1108 else
1109 CURL_TRC_CF(data, cf, "shutdown error: %d", result);
1110
1111 cf->shutdown = (result || *done);
1112 return result;
1113 }
1114
bearssl_close(struct Curl_cfilter * cf,struct Curl_easy * data)1115 static void bearssl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
1116 {
1117 struct ssl_connect_data *connssl = cf->ctx;
1118 struct bearssl_ssl_backend_data *backend =
1119 (struct bearssl_ssl_backend_data *)connssl->backend;
1120 size_t i;
1121
1122 (void)data;
1123 DEBUGASSERT(backend);
1124
1125 backend->active = FALSE;
1126 if(backend->anchors) {
1127 for(i = 0; i < backend->anchors_len; ++i)
1128 free(backend->anchors[i].dn.data);
1129 Curl_safefree(backend->anchors);
1130 }
1131 }
1132
bearssl_sha256sum(const unsigned char * input,size_t inputlen,unsigned char * sha256sum,size_t sha256len UNUSED_PARAM)1133 static CURLcode bearssl_sha256sum(const unsigned char *input,
1134 size_t inputlen,
1135 unsigned char *sha256sum,
1136 size_t sha256len UNUSED_PARAM)
1137 {
1138 br_sha256_context ctx;
1139
1140 br_sha256_init(&ctx);
1141 br_sha256_update(&ctx, input, inputlen);
1142 br_sha256_out(&ctx, sha256sum);
1143 return CURLE_OK;
1144 }
1145
1146 const struct Curl_ssl Curl_ssl_bearssl = {
1147 { CURLSSLBACKEND_BEARSSL, "bearssl" }, /* info */
1148
1149 SSLSUPP_CAINFO_BLOB |
1150 SSLSUPP_SSL_CTX |
1151 SSLSUPP_HTTPS_PROXY |
1152 SSLSUPP_CIPHER_LIST,
1153
1154 sizeof(struct bearssl_ssl_backend_data),
1155
1156 NULL, /* init */
1157 NULL, /* cleanup */
1158 bearssl_version, /* version */
1159 bearssl_shutdown, /* shutdown */
1160 bearssl_data_pending, /* data_pending */
1161 bearssl_random, /* random */
1162 NULL, /* cert_status_request */
1163 bearssl_connect, /* connect */
1164 bearssl_connect_nonblocking, /* connect_nonblocking */
1165 Curl_ssl_adjust_pollset, /* adjust_pollset */
1166 bearssl_get_internals, /* get_internals */
1167 bearssl_close, /* close_one */
1168 NULL, /* close_all */
1169 NULL, /* set_engine */
1170 NULL, /* set_engine_default */
1171 NULL, /* engines_list */
1172 NULL, /* false_start */
1173 bearssl_sha256sum, /* sha256sum */
1174 bearssl_recv, /* recv decrypted data */
1175 bearssl_send, /* send data to encrypt */
1176 NULL, /* get_channel_binding */
1177 };
1178
1179 #endif /* USE_BEARSSL */
1180