• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 2019 - 2020, 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.haxx.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  ***************************************************************************/
22 #include "curl_setup.h"
23 
24 #ifdef USE_BEARSSL
25 
26 #include <bearssl.h>
27 
28 #include "bearssl.h"
29 #include "urldata.h"
30 #include "sendf.h"
31 #include "inet_pton.h"
32 #include "vtls.h"
33 #include "connect.h"
34 #include "select.h"
35 #include "multiif.h"
36 #include "curl_printf.h"
37 #include "curl_memory.h"
38 
39 struct x509_context {
40   const br_x509_class *vtable;
41   br_x509_minimal_context minimal;
42   bool verifyhost;
43   bool verifypeer;
44 };
45 
46 struct ssl_backend_data {
47   br_ssl_client_context ctx;
48   struct x509_context x509;
49   unsigned char buf[BR_SSL_BUFSIZE_BIDI];
50   br_x509_trust_anchor *anchors;
51   size_t anchors_len;
52   const char *protocols[2];
53   /* SSL client context is active */
54   bool active;
55   /* size of pending write, yet to be flushed */
56   size_t pending_write;
57 };
58 
59 struct cafile_parser {
60   CURLcode err;
61   bool in_cert;
62   br_x509_decoder_context xc;
63   /* array of trust anchors loaded from CAfile */
64   br_x509_trust_anchor *anchors;
65   size_t anchors_len;
66   /* buffer for DN data */
67   unsigned char dn[1024];
68   size_t dn_len;
69 };
70 
append_dn(void * ctx,const void * buf,size_t len)71 static void append_dn(void *ctx, const void *buf, size_t len)
72 {
73   struct cafile_parser *ca = ctx;
74 
75   if(ca->err != CURLE_OK || !ca->in_cert)
76     return;
77   if(sizeof(ca->dn) - ca->dn_len < len) {
78     ca->err = CURLE_FAILED_INIT;
79     return;
80   }
81   memcpy(ca->dn + ca->dn_len, buf, len);
82   ca->dn_len += len;
83 }
84 
x509_push(void * ctx,const void * buf,size_t len)85 static void x509_push(void *ctx, const void *buf, size_t len)
86 {
87   struct cafile_parser *ca = ctx;
88 
89   if(ca->in_cert)
90     br_x509_decoder_push(&ca->xc, buf, len);
91 }
92 
load_cafile(const char * path,br_x509_trust_anchor ** anchors,size_t * anchors_len)93 static CURLcode load_cafile(const char *path, br_x509_trust_anchor **anchors,
94                             size_t *anchors_len)
95 {
96   struct cafile_parser ca;
97   br_pem_decoder_context pc;
98   br_x509_trust_anchor *ta;
99   size_t ta_size;
100   br_x509_trust_anchor *new_anchors;
101   size_t new_anchors_len;
102   br_x509_pkey *pkey;
103   FILE *fp;
104   unsigned char buf[BUFSIZ], *p;
105   const char *name;
106   size_t n, i, pushed;
107 
108   fp = fopen(path, "rb");
109   if(!fp)
110     return CURLE_SSL_CACERT_BADFILE;
111 
112   ca.err = CURLE_OK;
113   ca.in_cert = FALSE;
114   ca.anchors = NULL;
115   ca.anchors_len = 0;
116   br_pem_decoder_init(&pc);
117   br_pem_decoder_setdest(&pc, x509_push, &ca);
118   for(;;) {
119     n = fread(buf, 1, sizeof(buf), fp);
120     if(n == 0)
121       break;
122     p = buf;
123     while(n) {
124       pushed = br_pem_decoder_push(&pc, p, n);
125       if(ca.err)
126         goto fail;
127       p += pushed;
128       n -= pushed;
129 
130       switch(br_pem_decoder_event(&pc)) {
131       case 0:
132         break;
133       case BR_PEM_BEGIN_OBJ:
134         name = br_pem_decoder_name(&pc);
135         if(strcmp(name, "CERTIFICATE") && strcmp(name, "X509 CERTIFICATE"))
136           break;
137         br_x509_decoder_init(&ca.xc, append_dn, &ca);
138         if(ca.anchors_len == SIZE_MAX / sizeof(ca.anchors[0])) {
139           ca.err = CURLE_OUT_OF_MEMORY;
140           goto fail;
141         }
142         new_anchors_len = ca.anchors_len + 1;
143         new_anchors = realloc(ca.anchors,
144                               new_anchors_len * sizeof(ca.anchors[0]));
145         if(!new_anchors) {
146           ca.err = CURLE_OUT_OF_MEMORY;
147           goto fail;
148         }
149         ca.anchors = new_anchors;
150         ca.anchors_len = new_anchors_len;
151         ca.in_cert = TRUE;
152         ca.dn_len = 0;
153         ta = &ca.anchors[ca.anchors_len - 1];
154         ta->dn.data = NULL;
155         break;
156       case BR_PEM_END_OBJ:
157         if(!ca.in_cert)
158           break;
159         ca.in_cert = FALSE;
160         if(br_x509_decoder_last_error(&ca.xc)) {
161           ca.err = CURLE_SSL_CACERT_BADFILE;
162           goto fail;
163         }
164         ta->flags = 0;
165         if(br_x509_decoder_isCA(&ca.xc))
166           ta->flags |= BR_X509_TA_CA;
167         pkey = br_x509_decoder_get_pkey(&ca.xc);
168         if(!pkey) {
169           ca.err = CURLE_SSL_CACERT_BADFILE;
170           goto fail;
171         }
172         ta->pkey = *pkey;
173 
174         /* calculate space needed for trust anchor data */
175         ta_size = ca.dn_len;
176         switch(pkey->key_type) {
177         case BR_KEYTYPE_RSA:
178           ta_size += pkey->key.rsa.nlen + pkey->key.rsa.elen;
179           break;
180         case BR_KEYTYPE_EC:
181           ta_size += pkey->key.ec.qlen;
182           break;
183         default:
184           ca.err = CURLE_FAILED_INIT;
185           goto fail;
186         }
187 
188         /* fill in trust anchor DN and public key data */
189         ta->dn.data = malloc(ta_size);
190         if(!ta->dn.data) {
191           ca.err = CURLE_OUT_OF_MEMORY;
192           goto fail;
193         }
194         memcpy(ta->dn.data, ca.dn, ca.dn_len);
195         ta->dn.len = ca.dn_len;
196         switch(pkey->key_type) {
197         case BR_KEYTYPE_RSA:
198           ta->pkey.key.rsa.n = ta->dn.data + ta->dn.len;
199           memcpy(ta->pkey.key.rsa.n, pkey->key.rsa.n, pkey->key.rsa.nlen);
200           ta->pkey.key.rsa.e = ta->pkey.key.rsa.n + ta->pkey.key.rsa.nlen;
201           memcpy(ta->pkey.key.rsa.e, pkey->key.rsa.e, pkey->key.rsa.elen);
202           break;
203         case BR_KEYTYPE_EC:
204           ta->pkey.key.ec.q = ta->dn.data + ta->dn.len;
205           memcpy(ta->pkey.key.ec.q, pkey->key.ec.q, pkey->key.ec.qlen);
206           break;
207         }
208         break;
209       default:
210         ca.err = CURLE_SSL_CACERT_BADFILE;
211         goto fail;
212       }
213     }
214   }
215   if(ferror(fp))
216     ca.err = CURLE_READ_ERROR;
217 
218 fail:
219   fclose(fp);
220   if(ca.err == CURLE_OK) {
221     *anchors = ca.anchors;
222     *anchors_len = ca.anchors_len;
223   }
224   else {
225     for(i = 0; i < ca.anchors_len; ++i)
226       free(ca.anchors[i].dn.data);
227     free(ca.anchors);
228   }
229 
230   return ca.err;
231 }
232 
x509_start_chain(const br_x509_class ** ctx,const char * server_name)233 static void x509_start_chain(const br_x509_class **ctx,
234                              const char *server_name)
235 {
236   struct x509_context *x509 = (struct x509_context *)ctx;
237 
238   if(!x509->verifyhost)
239     server_name = NULL;
240   x509->minimal.vtable->start_chain(&x509->minimal.vtable, server_name);
241 }
242 
x509_start_cert(const br_x509_class ** ctx,uint32_t length)243 static void x509_start_cert(const br_x509_class **ctx, uint32_t length)
244 {
245   struct x509_context *x509 = (struct x509_context *)ctx;
246 
247   x509->minimal.vtable->start_cert(&x509->minimal.vtable, length);
248 }
249 
x509_append(const br_x509_class ** ctx,const unsigned char * buf,size_t len)250 static void x509_append(const br_x509_class **ctx, const unsigned char *buf,
251                         size_t len)
252 {
253   struct x509_context *x509 = (struct x509_context *)ctx;
254 
255   x509->minimal.vtable->append(&x509->minimal.vtable, buf, len);
256 }
257 
x509_end_cert(const br_x509_class ** ctx)258 static void x509_end_cert(const br_x509_class **ctx)
259 {
260   struct x509_context *x509 = (struct x509_context *)ctx;
261 
262   x509->minimal.vtable->end_cert(&x509->minimal.vtable);
263 }
264 
x509_end_chain(const br_x509_class ** ctx)265 static unsigned x509_end_chain(const br_x509_class **ctx)
266 {
267   struct x509_context *x509 = (struct x509_context *)ctx;
268   unsigned err;
269 
270   err = x509->minimal.vtable->end_chain(&x509->minimal.vtable);
271   if(err && !x509->verifypeer) {
272     /* ignore any X.509 errors */
273     err = BR_ERR_OK;
274   }
275 
276   return err;
277 }
278 
x509_get_pkey(const br_x509_class * const * ctx,unsigned * usages)279 static const br_x509_pkey *x509_get_pkey(const br_x509_class *const *ctx,
280                                          unsigned *usages)
281 {
282   struct x509_context *x509 = (struct x509_context *)ctx;
283 
284   return x509->minimal.vtable->get_pkey(&x509->minimal.vtable, usages);
285 }
286 
287 static const br_x509_class x509_vtable = {
288   sizeof(struct x509_context),
289   x509_start_chain,
290   x509_start_cert,
291   x509_append,
292   x509_end_cert,
293   x509_end_chain,
294   x509_get_pkey
295 };
296 
bearssl_connect_step1(struct connectdata * conn,int sockindex)297 static CURLcode bearssl_connect_step1(struct connectdata *conn, int sockindex)
298 {
299   struct Curl_easy *data = conn->data;
300   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
301   struct ssl_backend_data *backend = connssl->backend;
302   const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
303 #ifndef CURL_DISABLE_PROXY
304   const char *hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
305     conn->host.name;
306 #else
307   const char *hostname = conn->host.name;
308 #endif
309   const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
310   const bool verifyhost = SSL_CONN_CONFIG(verifyhost);
311   CURLcode ret;
312   unsigned version_min, version_max;
313 #ifdef ENABLE_IPV6
314   struct in6_addr addr;
315 #else
316   struct in_addr addr;
317 #endif
318 
319   switch(SSL_CONN_CONFIG(version)) {
320   case CURL_SSLVERSION_SSLv2:
321     failf(data, "BearSSL does not support SSLv2");
322     return CURLE_SSL_CONNECT_ERROR;
323   case CURL_SSLVERSION_SSLv3:
324     failf(data, "BearSSL does not support SSLv3");
325     return CURLE_SSL_CONNECT_ERROR;
326   case CURL_SSLVERSION_TLSv1_0:
327     version_min = BR_TLS10;
328     version_max = BR_TLS10;
329     break;
330   case CURL_SSLVERSION_TLSv1_1:
331     version_min = BR_TLS11;
332     version_max = BR_TLS11;
333     break;
334   case CURL_SSLVERSION_TLSv1_2:
335     version_min = BR_TLS12;
336     version_max = BR_TLS12;
337     break;
338   case CURL_SSLVERSION_DEFAULT:
339   case CURL_SSLVERSION_TLSv1:
340     version_min = BR_TLS10;
341     version_max = BR_TLS12;
342     break;
343   default:
344     failf(data, "BearSSL: unknown CURLOPT_SSLVERSION");
345     return CURLE_SSL_CONNECT_ERROR;
346   }
347 
348   if(ssl_cafile) {
349     ret = load_cafile(ssl_cafile, &backend->anchors, &backend->anchors_len);
350     if(ret != CURLE_OK) {
351       if(verifypeer) {
352         failf(data, "error setting certificate verify locations:\n"
353               "  CAfile: %s\n", ssl_cafile);
354         return ret;
355       }
356       infof(data, "error setting certificate verify locations,"
357             " continuing anyway:\n");
358     }
359   }
360 
361   /* initialize SSL context */
362   br_ssl_client_init_full(&backend->ctx, &backend->x509.minimal,
363                           backend->anchors, backend->anchors_len);
364   br_ssl_engine_set_versions(&backend->ctx.eng, version_min, version_max);
365   br_ssl_engine_set_buffer(&backend->ctx.eng, backend->buf,
366                            sizeof(backend->buf), 1);
367 
368   /* initialize X.509 context */
369   backend->x509.vtable = &x509_vtable;
370   backend->x509.verifypeer = verifypeer;
371   backend->x509.verifyhost = verifyhost;
372   br_ssl_engine_set_x509(&backend->ctx.eng, &backend->x509.vtable);
373 
374   if(SSL_SET_OPTION(primary.sessionid)) {
375     void *session;
376 
377     Curl_ssl_sessionid_lock(conn);
378     if(!Curl_ssl_getsessionid(conn, &session, NULL, sockindex)) {
379       br_ssl_engine_set_session_parameters(&backend->ctx.eng, session);
380       infof(data, "BearSSL: re-using session ID\n");
381     }
382     Curl_ssl_sessionid_unlock(conn);
383   }
384 
385   if(conn->bits.tls_enable_alpn) {
386     int cur = 0;
387 
388     /* NOTE: when adding more protocols here, increase the size of the
389      * protocols array in `struct ssl_backend_data`.
390      */
391 
392 #ifdef USE_NGHTTP2
393     if(data->set.httpversion >= CURL_HTTP_VERSION_2
394 #ifndef CURL_DISABLE_PROXY
395       && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)
396 #endif
397       ) {
398       backend->protocols[cur++] = NGHTTP2_PROTO_VERSION_ID;
399       infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
400     }
401 #endif
402 
403     backend->protocols[cur++] = ALPN_HTTP_1_1;
404     infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
405 
406     br_ssl_engine_set_protocol_names(&backend->ctx.eng,
407                                      backend->protocols, cur);
408   }
409 
410   if((1 == Curl_inet_pton(AF_INET, hostname, &addr))
411 #ifdef ENABLE_IPV6
412       || (1 == Curl_inet_pton(AF_INET6, hostname, &addr))
413 #endif
414      ) {
415     if(verifyhost) {
416       failf(data, "BearSSL: "
417             "host verification of IP address is not supported");
418       return CURLE_PEER_FAILED_VERIFICATION;
419     }
420     hostname = NULL;
421   }
422 
423   if(!br_ssl_client_reset(&backend->ctx, hostname, 0))
424     return CURLE_FAILED_INIT;
425   backend->active = TRUE;
426 
427   connssl->connecting_state = ssl_connect_2;
428 
429   return CURLE_OK;
430 }
431 
bearssl_run_until(struct connectdata * conn,int sockindex,unsigned target)432 static CURLcode bearssl_run_until(struct connectdata *conn, int sockindex,
433                                   unsigned target)
434 {
435   struct Curl_easy *data = conn->data;
436   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
437   struct ssl_backend_data *backend = connssl->backend;
438   curl_socket_t sockfd = conn->sock[sockindex];
439   unsigned state;
440   unsigned char *buf;
441   size_t len;
442   ssize_t ret;
443   int err;
444 
445   for(;;) {
446     state = br_ssl_engine_current_state(&backend->ctx.eng);
447     if(state & BR_SSL_CLOSED) {
448       err = br_ssl_engine_last_error(&backend->ctx.eng);
449       switch(err) {
450       case BR_ERR_OK:
451         /* TLS close notify */
452         if(connssl->state != ssl_connection_complete) {
453           failf(data, "SSL: connection closed during handshake");
454           return CURLE_SSL_CONNECT_ERROR;
455         }
456         return CURLE_OK;
457       case BR_ERR_X509_EXPIRED:
458         failf(data, "SSL: X.509 verification: "
459               "certificate is expired or not yet valid");
460         return CURLE_PEER_FAILED_VERIFICATION;
461       case BR_ERR_X509_BAD_SERVER_NAME:
462         failf(data, "SSL: X.509 verification: "
463               "expected server name was not found in the chain");
464         return CURLE_PEER_FAILED_VERIFICATION;
465       case BR_ERR_X509_NOT_TRUSTED:
466         failf(data, "SSL: X.509 verification: "
467               "chain could not be linked to a trust anchor");
468         return CURLE_PEER_FAILED_VERIFICATION;
469       }
470       /* X.509 errors are documented to have the range 32..63 */
471       if(err >= 32 && err < 64)
472         return CURLE_PEER_FAILED_VERIFICATION;
473       return CURLE_SSL_CONNECT_ERROR;
474     }
475     if(state & target)
476       return CURLE_OK;
477     if(state & BR_SSL_SENDREC) {
478       buf = br_ssl_engine_sendrec_buf(&backend->ctx.eng, &len);
479       ret = swrite(sockfd, buf, len);
480       if(ret == -1) {
481         if(SOCKERRNO == EAGAIN || SOCKERRNO == EWOULDBLOCK) {
482           if(connssl->state != ssl_connection_complete)
483             connssl->connecting_state = ssl_connect_2_writing;
484           return CURLE_AGAIN;
485         }
486         return CURLE_WRITE_ERROR;
487       }
488       br_ssl_engine_sendrec_ack(&backend->ctx.eng, ret);
489     }
490     else if(state & BR_SSL_RECVREC) {
491       buf = br_ssl_engine_recvrec_buf(&backend->ctx.eng, &len);
492       ret = sread(sockfd, buf, len);
493       if(ret == 0) {
494         failf(data, "SSL: EOF without close notify");
495         return CURLE_READ_ERROR;
496       }
497       if(ret == -1) {
498         if(SOCKERRNO == EAGAIN || SOCKERRNO == EWOULDBLOCK) {
499           if(connssl->state != ssl_connection_complete)
500             connssl->connecting_state = ssl_connect_2_reading;
501           return CURLE_AGAIN;
502         }
503         return CURLE_READ_ERROR;
504       }
505       br_ssl_engine_recvrec_ack(&backend->ctx.eng, ret);
506     }
507   }
508 }
509 
bearssl_connect_step2(struct connectdata * conn,int sockindex)510 static CURLcode bearssl_connect_step2(struct connectdata *conn, int sockindex)
511 {
512   struct Curl_easy *data = conn->data;
513   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
514   struct ssl_backend_data *backend = connssl->backend;
515   CURLcode ret;
516 
517   ret = bearssl_run_until(conn, sockindex, BR_SSL_SENDAPP | BR_SSL_RECVAPP);
518   if(ret == CURLE_AGAIN)
519     return CURLE_OK;
520   if(ret == CURLE_OK) {
521     if(br_ssl_engine_current_state(&backend->ctx.eng) == BR_SSL_CLOSED) {
522       failf(data, "SSL: connection closed during handshake");
523       return CURLE_SSL_CONNECT_ERROR;
524     }
525     connssl->connecting_state = ssl_connect_3;
526   }
527   return ret;
528 }
529 
bearssl_connect_step3(struct connectdata * conn,int sockindex)530 static CURLcode bearssl_connect_step3(struct connectdata *conn, int sockindex)
531 {
532   struct Curl_easy *data = conn->data;
533   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
534   struct ssl_backend_data *backend = connssl->backend;
535   CURLcode ret;
536 
537   DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
538 
539   if(conn->bits.tls_enable_alpn) {
540     const char *protocol;
541 
542     protocol = br_ssl_engine_get_selected_protocol(&backend->ctx.eng);
543     if(protocol) {
544       infof(data, "ALPN, server accepted to use %s\n", protocol);
545 
546 #ifdef USE_NGHTTP2
547       if(!strcmp(protocol, NGHTTP2_PROTO_VERSION_ID))
548         conn->negnpn = CURL_HTTP_VERSION_2;
549       else
550 #endif
551       if(!strcmp(protocol, ALPN_HTTP_1_1))
552         conn->negnpn = CURL_HTTP_VERSION_1_1;
553       else
554         infof(data, "ALPN, unrecognized protocol %s\n", protocol);
555       Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ?
556                           BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
557     }
558     else
559       infof(data, "ALPN, server did not agree to a protocol\n");
560   }
561 
562   if(SSL_SET_OPTION(primary.sessionid)) {
563     bool incache;
564     void *oldsession;
565     br_ssl_session_parameters *session;
566 
567     session = malloc(sizeof(*session));
568     if(!session)
569       return CURLE_OUT_OF_MEMORY;
570     br_ssl_engine_get_session_parameters(&backend->ctx.eng, session);
571     Curl_ssl_sessionid_lock(conn);
572     incache = !(Curl_ssl_getsessionid(conn, &oldsession, NULL, sockindex));
573     if(incache)
574       Curl_ssl_delsessionid(conn, oldsession);
575     ret = Curl_ssl_addsessionid(conn, session, 0, sockindex);
576     Curl_ssl_sessionid_unlock(conn);
577     if(ret) {
578       free(session);
579       return CURLE_OUT_OF_MEMORY;
580     }
581   }
582 
583   connssl->connecting_state = ssl_connect_done;
584 
585   return CURLE_OK;
586 }
587 
bearssl_send(struct connectdata * conn,int sockindex,const void * buf,size_t len,CURLcode * err)588 static ssize_t bearssl_send(struct connectdata *conn, int sockindex,
589                             const void *buf, size_t len, CURLcode *err)
590 {
591   struct Curl_easy *data = conn->data;
592   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
593   struct ssl_backend_data *backend = connssl->backend;
594   unsigned char *app;
595   size_t applen;
596 
597   for(;;) {
598     *err = bearssl_run_until(conn, sockindex, BR_SSL_SENDAPP);
599     if (*err != CURLE_OK)
600       return -1;
601     app = br_ssl_engine_sendapp_buf(&backend->ctx.eng, &applen);
602     if(!app) {
603       failf(data, "SSL: connection closed during write");
604       *err = CURLE_SEND_ERROR;
605       return -1;
606     }
607     if(backend->pending_write) {
608       applen = backend->pending_write;
609       backend->pending_write = 0;
610       return applen;
611     }
612     if(applen > len)
613       applen = len;
614     memcpy(app, buf, applen);
615     br_ssl_engine_sendapp_ack(&backend->ctx.eng, applen);
616     br_ssl_engine_flush(&backend->ctx.eng, 0);
617     backend->pending_write = applen;
618   }
619 }
620 
bearssl_recv(struct connectdata * conn,int sockindex,char * buf,size_t len,CURLcode * err)621 static ssize_t bearssl_recv(struct connectdata *conn, int sockindex,
622                             char *buf, size_t len, CURLcode *err)
623 {
624   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
625   struct ssl_backend_data *backend = connssl->backend;
626   unsigned char *app;
627   size_t applen;
628 
629   *err = bearssl_run_until(conn, sockindex, BR_SSL_RECVAPP);
630   if(*err != CURLE_OK)
631     return -1;
632   app = br_ssl_engine_recvapp_buf(&backend->ctx.eng, &applen);
633   if(!app)
634     return 0;
635   if(applen > len)
636     applen = len;
637   memcpy(buf, app, applen);
638   br_ssl_engine_recvapp_ack(&backend->ctx.eng, applen);
639 
640   return applen;
641 }
642 
bearssl_connect_common(struct connectdata * conn,int sockindex,bool nonblocking,bool * done)643 static CURLcode bearssl_connect_common(struct connectdata *conn,
644                                        int sockindex,
645                                        bool nonblocking,
646                                        bool *done)
647 {
648   CURLcode ret;
649   struct Curl_easy *data = conn->data;
650   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
651   curl_socket_t sockfd = conn->sock[sockindex];
652   timediff_t timeout_ms;
653   int what;
654 
655   /* check if the connection has already been established */
656   if(ssl_connection_complete == connssl->state) {
657     *done = TRUE;
658     return CURLE_OK;
659   }
660 
661   if(ssl_connect_1 == connssl->connecting_state) {
662     ret = bearssl_connect_step1(conn, sockindex);
663     if(ret)
664       return ret;
665   }
666 
667   while(ssl_connect_2 == connssl->connecting_state ||
668         ssl_connect_2_reading == connssl->connecting_state ||
669         ssl_connect_2_writing == connssl->connecting_state) {
670     /* check allowed time left */
671     timeout_ms = Curl_timeleft(data, NULL, TRUE);
672 
673     if(timeout_ms < 0) {
674       /* no need to continue if time already is up */
675       failf(data, "SSL connection timeout");
676       return CURLE_OPERATION_TIMEDOUT;
677     }
678 
679     /* if ssl is expecting something, check if it's available. */
680     if(ssl_connect_2_reading == connssl->connecting_state ||
681        ssl_connect_2_writing == connssl->connecting_state) {
682 
683       curl_socket_t writefd = ssl_connect_2_writing ==
684         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
685       curl_socket_t readfd = ssl_connect_2_reading ==
686         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
687 
688       what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
689                                nonblocking?0:timeout_ms);
690       if(what < 0) {
691         /* fatal error */
692         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
693         return CURLE_SSL_CONNECT_ERROR;
694       }
695       else if(0 == what) {
696         if(nonblocking) {
697           *done = FALSE;
698           return CURLE_OK;
699         }
700         else {
701           /* timeout */
702           failf(data, "SSL connection timeout");
703           return CURLE_OPERATION_TIMEDOUT;
704         }
705       }
706       /* socket is readable or writable */
707     }
708 
709     /* Run transaction, and return to the caller if it failed or if this
710      * connection is done nonblocking and this loop would execute again. This
711      * permits the owner of a multi handle to abort a connection attempt
712      * before step2 has completed while ensuring that a client using select()
713      * or epoll() will always have a valid fdset to wait on.
714      */
715     ret = bearssl_connect_step2(conn, sockindex);
716     if(ret || (nonblocking &&
717                (ssl_connect_2 == connssl->connecting_state ||
718                 ssl_connect_2_reading == connssl->connecting_state ||
719                 ssl_connect_2_writing == connssl->connecting_state)))
720       return ret;
721   }
722 
723   if(ssl_connect_3 == connssl->connecting_state) {
724     ret = bearssl_connect_step3(conn, sockindex);
725     if(ret)
726       return ret;
727   }
728 
729   if(ssl_connect_done == connssl->connecting_state) {
730     connssl->state = ssl_connection_complete;
731     conn->recv[sockindex] = bearssl_recv;
732     conn->send[sockindex] = bearssl_send;
733     *done = TRUE;
734   }
735   else
736     *done = FALSE;
737 
738   /* Reset our connect state machine */
739   connssl->connecting_state = ssl_connect_1;
740 
741   return CURLE_OK;
742 }
743 
Curl_bearssl_version(char * buffer,size_t size)744 static size_t Curl_bearssl_version(char *buffer, size_t size)
745 {
746   return msnprintf(buffer, size, "BearSSL");
747 }
748 
Curl_bearssl_data_pending(const struct connectdata * conn,int connindex)749 static bool Curl_bearssl_data_pending(const struct connectdata *conn,
750                                       int connindex)
751 {
752   const struct ssl_connect_data *connssl = &conn->ssl[connindex];
753   struct ssl_backend_data *backend = connssl->backend;
754   return br_ssl_engine_current_state(&backend->ctx.eng) & BR_SSL_RECVAPP;
755 }
756 
Curl_bearssl_random(struct Curl_easy * data UNUSED_PARAM,unsigned char * entropy,size_t length)757 static CURLcode Curl_bearssl_random(struct Curl_easy *data UNUSED_PARAM,
758                                     unsigned char *entropy, size_t length)
759 {
760   static br_hmac_drbg_context ctx;
761   static bool seeded = FALSE;
762 
763   if(!seeded) {
764     br_prng_seeder seeder;
765 
766     br_hmac_drbg_init(&ctx, &br_sha256_vtable, NULL, 0);
767     seeder = br_prng_seeder_system(NULL);
768     if(!seeder || !seeder(&ctx.vtable))
769       return CURLE_FAILED_INIT;
770     seeded = TRUE;
771   }
772   br_hmac_drbg_generate(&ctx, entropy, length);
773 
774   return CURLE_OK;
775 }
776 
Curl_bearssl_connect(struct connectdata * conn,int sockindex)777 static CURLcode Curl_bearssl_connect(struct connectdata *conn, int sockindex)
778 {
779   CURLcode ret;
780   bool done = FALSE;
781 
782   ret = bearssl_connect_common(conn, sockindex, FALSE, &done);
783   if(ret)
784     return ret;
785 
786   DEBUGASSERT(done);
787 
788   return CURLE_OK;
789 }
790 
Curl_bearssl_connect_nonblocking(struct connectdata * conn,int sockindex,bool * done)791 static CURLcode Curl_bearssl_connect_nonblocking(struct connectdata *conn,
792                                                  int sockindex, bool *done)
793 {
794   return bearssl_connect_common(conn, sockindex, TRUE, done);
795 }
796 
Curl_bearssl_get_internals(struct ssl_connect_data * connssl,CURLINFO info UNUSED_PARAM)797 static void *Curl_bearssl_get_internals(struct ssl_connect_data *connssl,
798                                         CURLINFO info UNUSED_PARAM)
799 {
800   struct ssl_backend_data *backend = connssl->backend;
801   return &backend->ctx;
802 }
803 
Curl_bearssl_close(struct connectdata * conn,int sockindex)804 static void Curl_bearssl_close(struct connectdata *conn, int sockindex)
805 {
806   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
807   struct ssl_backend_data *backend = connssl->backend;
808   size_t i;
809 
810   if(backend->active) {
811     br_ssl_engine_close(&backend->ctx.eng);
812     (void)bearssl_run_until(conn, sockindex, BR_SSL_CLOSED);
813   }
814   for(i = 0; i < backend->anchors_len; ++i)
815     free(backend->anchors[i].dn.data);
816   free(backend->anchors);
817 }
818 
Curl_bearssl_session_free(void * ptr)819 static void Curl_bearssl_session_free(void *ptr)
820 {
821   free(ptr);
822 }
823 
Curl_bearssl_md5sum(unsigned char * input,size_t inputlen,unsigned char * md5sum,size_t md5len UNUSED_PARAM)824 static CURLcode Curl_bearssl_md5sum(unsigned char *input,
825                                     size_t inputlen,
826                                     unsigned char *md5sum,
827                                     size_t md5len UNUSED_PARAM)
828 {
829   br_md5_context ctx;
830 
831   br_md5_init(&ctx);
832   br_md5_update(&ctx, input, inputlen);
833   br_md5_out(&ctx, md5sum);
834   return CURLE_OK;
835 }
836 
Curl_bearssl_sha256sum(const unsigned char * input,size_t inputlen,unsigned char * sha256sum,size_t sha256len UNUSED_PARAM)837 static CURLcode Curl_bearssl_sha256sum(const unsigned char *input,
838                                        size_t inputlen,
839                                        unsigned char *sha256sum,
840                                        size_t sha256len UNUSED_PARAM)
841 {
842   br_sha256_context ctx;
843 
844   br_sha256_init(&ctx);
845   br_sha256_update(&ctx, input, inputlen);
846   br_sha256_out(&ctx, sha256sum);
847   return CURLE_OK;
848 }
849 
850 const struct Curl_ssl Curl_ssl_bearssl = {
851   { CURLSSLBACKEND_BEARSSL, "bearssl" },
852   0,
853   sizeof(struct ssl_backend_data),
854 
855   Curl_none_init,
856   Curl_none_cleanup,
857   Curl_bearssl_version,
858   Curl_none_check_cxn,
859   Curl_none_shutdown,
860   Curl_bearssl_data_pending,
861   Curl_bearssl_random,
862   Curl_none_cert_status_request,
863   Curl_bearssl_connect,
864   Curl_bearssl_connect_nonblocking,
865   Curl_bearssl_get_internals,
866   Curl_bearssl_close,
867   Curl_none_close_all,
868   Curl_bearssl_session_free,
869   Curl_none_set_engine,
870   Curl_none_set_engine_default,
871   Curl_none_engines_list,
872   Curl_none_false_start,
873   Curl_bearssl_md5sum,
874   Curl_bearssl_sha256sum
875 };
876 
877 #endif /* USE_BEARSSL */
878