• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 2012 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
9  * Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com>
10  *
11  * This software is licensed as described in the file COPYING, which
12  * you should have received as part of this distribution. The terms
13  * are also available at https://curl.se/docs/copyright.html.
14  *
15  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
16  * copies of the Software, and permit persons to whom the Software is
17  * furnished to do so, under the terms of the COPYING file.
18  *
19  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20  * KIND, either express or implied.
21  *
22  ***************************************************************************/
23 
24 /*
25  * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code
26  * but vtls.c should ever call or use these functions.
27  *
28  */
29 
30 #include "curl_setup.h"
31 
32 #ifdef USE_MBEDTLS
33 
34 /* Define this to enable lots of debugging for mbedTLS */
35 /* #define MBEDTLS_DEBUG */
36 
37 #include <mbedtls/version.h>
38 #if MBEDTLS_VERSION_NUMBER >= 0x02040000
39 #include <mbedtls/net_sockets.h>
40 #else
41 #include <mbedtls/net.h>
42 #endif
43 #include "ssl_misc.h"
44 #include <mbedtls/ssl.h>
45 #include <mbedtls/x509.h>
46 
47 #include <mbedtls/error.h>
48 #include <mbedtls/entropy.h>
49 #include <mbedtls/ctr_drbg.h>
50 #include <mbedtls/sha256.h>
51 
52 #if MBEDTLS_VERSION_MAJOR >= 2
53 #  ifdef MBEDTLS_DEBUG
54 #    include <mbedtls/debug.h>
55 #  endif
56 #endif
57 
58 #include "urldata.h"
59 #include "sendf.h"
60 #include "inet_pton.h"
61 #include "mbedtls.h"
62 #include "vtls.h"
63 #include "parsedate.h"
64 #include "connect.h" /* for the connect timeout */
65 #include "select.h"
66 #include "multiif.h"
67 #include "mbedtls_threadlock.h"
68 
69 /* The last 3 #include files should be in this order */
70 #include "curl_printf.h"
71 #include "curl_memory.h"
72 #include "memdebug.h"
73 
74 struct ssl_backend_data {
75   mbedtls_ctr_drbg_context ctr_drbg;
76   mbedtls_entropy_context entropy;
77   mbedtls_ssl_context ssl;
78   int server_fd;
79   mbedtls_x509_crt cacert;
80   mbedtls_x509_crt clicert;
81   mbedtls_x509_crl crl;
82   mbedtls_pk_context pk;
83   mbedtls_ssl_config config;
84   const char *protocols[3];
85 };
86 
87 /* apply threading? */
88 #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
89 #define THREADING_SUPPORT
90 #endif
91 
92 #ifndef MBEDTLS_ERROR_C
93 #define mbedtls_strerror(a,b,c) b[0] = 0
94 #endif
95 
96 #if defined(THREADING_SUPPORT)
97 static mbedtls_entropy_context ts_entropy;
98 
99 static int entropy_init_initialized = 0;
100 
101 /* start of entropy_init_mutex() */
entropy_init_mutex(mbedtls_entropy_context * ctx)102 static void entropy_init_mutex(mbedtls_entropy_context *ctx)
103 {
104   /* lock 0 = entropy_init_mutex() */
105   Curl_mbedtlsthreadlock_lock_function(0);
106   if(entropy_init_initialized == 0) {
107     mbedtls_entropy_init(ctx);
108     entropy_init_initialized = 1;
109   }
110   Curl_mbedtlsthreadlock_unlock_function(0);
111 }
112 /* end of entropy_init_mutex() */
113 
114 /* start of entropy_func_mutex() */
entropy_func_mutex(void * data,unsigned char * output,size_t len)115 static int entropy_func_mutex(void *data, unsigned char *output, size_t len)
116 {
117   int ret;
118   /* lock 1 = entropy_func_mutex() */
119   Curl_mbedtlsthreadlock_lock_function(1);
120   ret = mbedtls_entropy_func(data, output, len);
121   Curl_mbedtlsthreadlock_unlock_function(1);
122 
123   return ret;
124 }
125 /* end of entropy_func_mutex() */
126 
127 #endif /* THREADING_SUPPORT */
128 
129 #ifdef MBEDTLS_DEBUG
mbed_debug(void * context,int level,const char * f_name,int line_nb,const char * line)130 static void mbed_debug(void *context, int level, const char *f_name,
131                        int line_nb, const char *line)
132 {
133   struct Curl_easy *data = NULL;
134 
135   if(!context)
136     return;
137 
138   data = (struct Curl_easy *)context;
139 
140   infof(data, "%s", line);
141   (void) level;
142 }
143 #else
144 #endif
145 
146 /* ALPN for http2? */
147 #ifdef USE_NGHTTP2
148 #  undef HAS_ALPN
149 #  ifdef MBEDTLS_SSL_ALPN
150 #    define HAS_ALPN
151 #  endif
152 #endif
153 
154 
155 /*
156  *  profile
157  */
158 static const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_fr =
159 {
160   /* Hashes from SHA-1 and above */
161   MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) |
162   MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160) |
163   MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) |
164   MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
165   MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) |
166   MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
167   0xFFFFFFF, /* Any PK alg    */
168   0xFFFFFFF, /* Any curve     */
169   1024,      /* RSA min key len */
170 };
171 
172 /* See https://tls.mbed.org/discussions/generic/
173    howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der
174 */
175 #define RSA_PUB_DER_MAX_BYTES   (38 + 2 * MBEDTLS_MPI_MAX_SIZE)
176 #define ECP_PUB_DER_MAX_BYTES   (30 + 2 * MBEDTLS_ECP_MAX_BYTES)
177 
178 #define PUB_DER_MAX_BYTES   (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
179                              RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
180 
181 static Curl_recv mbed_recv;
182 static Curl_send mbed_send;
183 
mbedtls_version_from_curl(int * mbedver,long version)184 static CURLcode mbedtls_version_from_curl(int *mbedver, long version)
185 {
186   switch(version) {
187     case CURL_SSLVERSION_TLSv1_0:
188       *mbedver = MBEDTLS_SSL_MINOR_VERSION_1;
189       return CURLE_OK;
190     case CURL_SSLVERSION_TLSv1_1:
191       *mbedver = MBEDTLS_SSL_MINOR_VERSION_2;
192       return CURLE_OK;
193     case CURL_SSLVERSION_TLSv1_2:
194       *mbedver = MBEDTLS_SSL_MINOR_VERSION_3;
195       return CURLE_OK;
196     case CURL_SSLVERSION_TLSv1_3:
197       break;
198   }
199   return CURLE_SSL_CONNECT_ERROR;
200 }
201 
202 static CURLcode
set_ssl_version_min_max(struct Curl_easy * data,struct connectdata * conn,int sockindex)203 set_ssl_version_min_max(struct Curl_easy *data, struct connectdata *conn,
204                         int sockindex)
205 {
206   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
207   struct ssl_backend_data *backend = connssl->backend;
208   int mbedtls_ver_min = MBEDTLS_SSL_MINOR_VERSION_1;
209   int mbedtls_ver_max = MBEDTLS_SSL_MINOR_VERSION_1;
210   long ssl_version = SSL_CONN_CONFIG(version);
211   long ssl_version_max = SSL_CONN_CONFIG(version_max);
212   CURLcode result = CURLE_OK;
213 
214   switch(ssl_version) {
215     case CURL_SSLVERSION_DEFAULT:
216     case CURL_SSLVERSION_TLSv1:
217       ssl_version = CURL_SSLVERSION_TLSv1_0;
218       break;
219   }
220 
221   switch(ssl_version_max) {
222     case CURL_SSLVERSION_MAX_NONE:
223     case CURL_SSLVERSION_MAX_DEFAULT:
224       ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2;
225       break;
226   }
227 
228   result = mbedtls_version_from_curl(&mbedtls_ver_min, ssl_version);
229   if(result) {
230     failf(data, "unsupported min version passed via CURLOPT_SSLVERSION");
231     return result;
232   }
233   result = mbedtls_version_from_curl(&mbedtls_ver_max, ssl_version_max >> 16);
234   if(result) {
235     failf(data, "unsupported max version passed via CURLOPT_SSLVERSION");
236     return result;
237   }
238 
239   mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
240                                mbedtls_ver_min);
241   mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
242                                mbedtls_ver_max);
243 
244   return result;
245 }
246 
247 static CURLcode
mbed_connect_step1(struct Curl_easy * data,struct connectdata * conn,int sockindex)248 mbed_connect_step1(struct Curl_easy *data, struct connectdata *conn,
249                    int sockindex)
250 {
251   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
252   struct ssl_backend_data *backend = connssl->backend;
253   const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
254   const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
255   const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
256   char * const ssl_cert = SSL_SET_OPTION(primary.clientcert);
257   const struct curl_blob *ssl_cert_blob = SSL_SET_OPTION(primary.cert_blob);
258   const char * const ssl_crlfile = SSL_SET_OPTION(primary.CRLfile);
259   const char * const hostname = SSL_HOST_NAME();
260   const long int port = SSL_HOST_PORT();
261   int ret = -1;
262   char errorbuf[128];
263 
264   if((SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) ||
265      (SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv3)) {
266     failf(data, "Not supported SSL version");
267     return CURLE_NOT_BUILT_IN;
268   }
269 
270 #ifdef THREADING_SUPPORT
271   entropy_init_mutex(&ts_entropy);
272   mbedtls_ctr_drbg_init(&backend->ctr_drbg);
273 
274   ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, entropy_func_mutex,
275                               &ts_entropy, NULL, 0);
276   if(ret) {
277     mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
278     failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s",
279           -ret, errorbuf);
280   }
281 #else
282   mbedtls_entropy_init(&backend->entropy);
283   mbedtls_ctr_drbg_init(&backend->ctr_drbg);
284 
285   ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, mbedtls_entropy_func,
286                               &backend->entropy, NULL, 0);
287   if(ret) {
288     mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
289     failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s",
290           -ret, errorbuf);
291   }
292 #endif /* THREADING_SUPPORT */
293 
294   /* Load the trusted CA */
295   mbedtls_x509_crt_init(&backend->cacert);
296 
297   if(ssl_cafile) {
298     ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile);
299 
300     if(ret<0) {
301       mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
302       failf(data, "Error reading ca cert file %s - mbedTLS: (-0x%04X) %s",
303             ssl_cafile, -ret, errorbuf);
304 
305       if(verifypeer)
306         return CURLE_SSL_CACERT_BADFILE;
307     }
308   }
309 
310   if(ssl_capath) {
311     ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath);
312 
313     if(ret<0) {
314       mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
315       failf(data, "Error reading ca cert path %s - mbedTLS: (-0x%04X) %s",
316             ssl_capath, -ret, errorbuf);
317 
318       if(verifypeer)
319         return CURLE_SSL_CACERT_BADFILE;
320     }
321   }
322 
323   /* Load the client certificate */
324   mbedtls_x509_crt_init(&backend->clicert);
325 
326   if(ssl_cert) {
327     ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert);
328 
329     if(ret) {
330       mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
331       failf(data, "Error reading client cert file %s - mbedTLS: (-0x%04X) %s",
332             ssl_cert, -ret, errorbuf);
333 
334       return CURLE_SSL_CERTPROBLEM;
335     }
336   }
337 
338   if(ssl_cert_blob) {
339     const unsigned char *blob_data =
340       (const unsigned char *)ssl_cert_blob->data;
341     ret = mbedtls_x509_crt_parse(&backend->clicert, blob_data,
342                                  ssl_cert_blob->len);
343 
344     if(ret) {
345       mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
346       failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s",
347             SSL_SET_OPTION(key), -ret, errorbuf);
348       return CURLE_SSL_CERTPROBLEM;
349     }
350   }
351 
352   /* Load the client private key */
353   mbedtls_pk_init(&backend->pk);
354 
355   if(SSL_SET_OPTION(key) || SSL_SET_OPTION(key_blob)) {
356     if(SSL_SET_OPTION(key)) {
357       ret = mbedtls_pk_parse_keyfile(&backend->pk, SSL_SET_OPTION(key),
358                                      SSL_SET_OPTION(key_passwd), mbedtls_ctr_drbg_random, &backend->ctr_drbg);
359 
360       if(ret) {
361         mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
362         failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s",
363               SSL_SET_OPTION(key), -ret, errorbuf);
364         return CURLE_SSL_CERTPROBLEM;
365       }
366     }
367     else {
368       const struct curl_blob *ssl_key_blob = SSL_SET_OPTION(key_blob);
369       const unsigned char *key_data =
370         (const unsigned char *)ssl_key_blob->data;
371       const char *passwd = SSL_SET_OPTION(key_passwd);
372       ret = mbedtls_pk_parse_key(&backend->pk, key_data, ssl_key_blob->len,
373                                  (const unsigned char *)passwd,
374                                  passwd ? strlen(passwd) : 0, mbedtls_ctr_drbg_random, &backend->ctr_drbg);
375 
376       if(ret) {
377         mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
378         failf(data, "Error parsing private key - mbedTLS: (-0x%04X) %s",
379               -ret, errorbuf);
380         return CURLE_SSL_CERTPROBLEM;
381       }
382     }
383 
384     if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) ||
385                      mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY)))
386       ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
387   }
388 
389   /* Load the CRL */
390   mbedtls_x509_crl_init(&backend->crl);
391 
392   if(ssl_crlfile) {
393     ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile);
394 
395     if(ret) {
396       mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
397       failf(data, "Error reading CRL file %s - mbedTLS: (-0x%04X) %s",
398             ssl_crlfile, -ret, errorbuf);
399 
400       return CURLE_SSL_CRL_BADFILE;
401     }
402   }
403 
404   infof(data, "mbedTLS: Connecting to %s:%ld", hostname, port);
405 
406   mbedtls_ssl_config_init(&backend->config);
407 
408   mbedtls_ssl_init(&backend->ssl);
409   if(mbedtls_ssl_setup(&backend->ssl, &backend->config)) {
410     failf(data, "mbedTLS: ssl_init failed");
411     return CURLE_SSL_CONNECT_ERROR;
412   }
413   ret = mbedtls_ssl_config_defaults(&backend->config,
414                                     MBEDTLS_SSL_IS_CLIENT,
415                                     MBEDTLS_SSL_TRANSPORT_STREAM,
416                                     MBEDTLS_SSL_PRESET_DEFAULT);
417   if(ret) {
418     failf(data, "mbedTLS: ssl_config failed");
419     return CURLE_SSL_CONNECT_ERROR;
420   }
421 
422   /* new profile with RSA min key len = 1024 ... */
423   mbedtls_ssl_conf_cert_profile(&backend->config,
424                                 &mbedtls_x509_crt_profile_fr);
425 
426   switch(SSL_CONN_CONFIG(version)) {
427   case CURL_SSLVERSION_DEFAULT:
428   case CURL_SSLVERSION_TLSv1:
429     mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
430                                  MBEDTLS_SSL_MINOR_VERSION_1);
431     infof(data, "mbedTLS: Set min SSL version to TLS 1.0");
432     break;
433   case CURL_SSLVERSION_TLSv1_0:
434   case CURL_SSLVERSION_TLSv1_1:
435   case CURL_SSLVERSION_TLSv1_2:
436   case CURL_SSLVERSION_TLSv1_3:
437     {
438       CURLcode result = set_ssl_version_min_max(data, conn, sockindex);
439       if(result != CURLE_OK)
440         return result;
441       break;
442     }
443   default:
444     failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
445     return CURLE_SSL_CONNECT_ERROR;
446   }
447 
448   mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_OPTIONAL);
449 
450   mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random,
451                        &backend->ctr_drbg);
452   mbedtls_ssl_set_bio(&backend->ssl, &conn->sock[sockindex],
453                       mbedtls_net_send,
454                       mbedtls_net_recv,
455                       NULL /*  rev_timeout() */);
456 
457   mbedtls_ssl_conf_ciphersuites(&backend->config,
458                                 mbedtls_ssl_list_ciphersuites());
459 
460 #if defined(MBEDTLS_SSL_RENEGOTIATION)
461   mbedtls_ssl_conf_renegotiation(&backend->config,
462                                  MBEDTLS_SSL_RENEGOTIATION_ENABLED);
463 #endif
464 
465 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
466   mbedtls_ssl_conf_session_tickets(&backend->config,
467                                    MBEDTLS_SSL_SESSION_TICKETS_DISABLED);
468 #endif
469 
470   /* Check if there's a cached ID we can/should use here! */
471   if(SSL_SET_OPTION(primary.sessionid)) {
472     void *old_session = NULL;
473 
474     Curl_ssl_sessionid_lock(data);
475     if(!Curl_ssl_getsessionid(data, conn,
476                               SSL_IS_PROXY() ? TRUE : FALSE,
477                               &old_session, NULL, sockindex)) {
478       ret = mbedtls_ssl_set_session(&backend->ssl, old_session);
479       if(ret) {
480         Curl_ssl_sessionid_unlock(data);
481         failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret);
482         return CURLE_SSL_CONNECT_ERROR;
483       }
484       infof(data, "mbedTLS re-using session");
485     }
486     Curl_ssl_sessionid_unlock(data);
487   }
488 
489   mbedtls_ssl_conf_ca_chain(&backend->config,
490                             &backend->cacert,
491                             &backend->crl);
492 
493   if(SSL_SET_OPTION(key) || SSL_SET_OPTION(key_blob)) {
494     mbedtls_ssl_conf_own_cert(&backend->config,
495                               &backend->clicert, &backend->pk);
496   }
497   if(mbedtls_ssl_set_hostname(&backend->ssl, hostname)) {
498     /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks *and*
499        the name to set in the SNI extension. So even if curl connects to a
500        host specified as an IP address, this function must be used. */
501     failf(data, "couldn't set hostname in mbedTLS");
502     return CURLE_SSL_CONNECT_ERROR;
503   }
504 
505 #ifdef HAS_ALPN
506   if(conn->bits.tls_enable_alpn) {
507     const char **p = &backend->protocols[0];
508 #ifdef USE_NGHTTP2
509     if(data->state.httpwant >= CURL_HTTP_VERSION_2)
510       *p++ = NGHTTP2_PROTO_VERSION_ID;
511 #endif
512     *p++ = ALPN_HTTP_1_1;
513     *p = NULL;
514     /* this function doesn't clone the protocols array, which is why we need
515        to keep it around */
516     if(mbedtls_ssl_conf_alpn_protocols(&backend->config,
517                                        &backend->protocols[0])) {
518       failf(data, "Failed setting ALPN protocols");
519       return CURLE_SSL_CONNECT_ERROR;
520     }
521     for(p = &backend->protocols[0]; *p; ++p)
522       infof(data, "ALPN, offering %s", *p);
523   }
524 #endif
525 
526 #ifdef MBEDTLS_DEBUG
527   /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */
528   mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data);
529   /* - 0 No debug
530    * - 1 Error
531    * - 2 State change
532    * - 3 Informational
533    * - 4 Verbose
534    */
535   mbedtls_debug_set_threshold(4);
536 #endif
537 
538   /* give application a chance to interfere with mbedTLS set up. */
539   if(data->set.ssl.fsslctx) {
540     ret = (*data->set.ssl.fsslctx)(data, &backend->config,
541                                    data->set.ssl.fsslctxp);
542     if(ret) {
543       failf(data, "error signaled by ssl ctx callback");
544       return ret;
545     }
546   }
547 
548   connssl->connecting_state = ssl_connect_2;
549 
550   return CURLE_OK;
551 }
552 
553 static CURLcode
mbed_connect_step2(struct Curl_easy * data,struct connectdata * conn,int sockindex)554 mbed_connect_step2(struct Curl_easy *data, struct connectdata *conn,
555                    int sockindex)
556 {
557   int ret;
558   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
559   struct ssl_backend_data *backend = connssl->backend;
560   const mbedtls_x509_crt *peercert;
561   const char * const pinnedpubkey = SSL_PINNED_PUB_KEY();
562 
563   conn->recv[sockindex] = mbed_recv;
564   conn->send[sockindex] = mbed_send;
565 
566   ret = mbedtls_ssl_handshake(&backend->ssl);
567 
568   if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
569     connssl->connecting_state = ssl_connect_2_reading;
570     return CURLE_OK;
571   }
572   else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
573     connssl->connecting_state = ssl_connect_2_writing;
574     return CURLE_OK;
575   }
576   else if(ret) {
577     char errorbuf[128];
578     mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
579     failf(data, "ssl_handshake returned - mbedTLS: (-0x%04X) %s",
580           -ret, errorbuf);
581     return CURLE_SSL_CONNECT_ERROR;
582   }
583 
584   infof(data, "mbedTLS: Handshake complete, cipher is %s",
585         mbedtls_ssl_get_ciphersuite(&backend->ssl));
586 
587   ret = mbedtls_ssl_get_verify_result(&backend->ssl);
588 
589   if(!SSL_CONN_CONFIG(verifyhost))
590     /* Ignore hostname errors if verifyhost is disabled */
591     ret &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
592 
593   if(ret && SSL_CONN_CONFIG(verifypeer)) {
594     if(ret & MBEDTLS_X509_BADCERT_EXPIRED)
595       failf(data, "Cert verify failed: BADCERT_EXPIRED");
596 
597     else if(ret & MBEDTLS_X509_BADCERT_REVOKED)
598       failf(data, "Cert verify failed: BADCERT_REVOKED");
599 
600     else if(ret & MBEDTLS_X509_BADCERT_CN_MISMATCH)
601       failf(data, "Cert verify failed: BADCERT_CN_MISMATCH");
602 
603     else if(ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED)
604       failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED");
605 
606     else if(ret & MBEDTLS_X509_BADCERT_FUTURE)
607       failf(data, "Cert verify failed: BADCERT_FUTURE");
608 
609     return CURLE_PEER_FAILED_VERIFICATION;
610   }
611 
612   peercert = mbedtls_ssl_get_peer_cert(&backend->ssl);
613 
614   if(peercert && data->set.verbose) {
615     const size_t bufsize = 16384;
616     char *buffer = malloc(bufsize);
617 
618     if(!buffer)
619       return CURLE_OUT_OF_MEMORY;
620 
621     if(mbedtls_x509_crt_info(buffer, bufsize, "* ", peercert) > 0)
622       infof(data, "Dumping cert info: %s", buffer);
623     else
624       infof(data, "Unable to dump certificate information");
625 
626     free(buffer);
627   }
628 
629   if(pinnedpubkey) {
630     int size;
631     CURLcode result;
632     mbedtls_x509_crt *p;
633     unsigned char pubkey[PUB_DER_MAX_BYTES];
634 
635     if(!peercert || !peercert->raw.p || !peercert->raw.len) {
636       failf(data, "Failed due to missing peer certificate");
637       return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
638     }
639 
640     p = calloc(1, sizeof(*p));
641 
642     if(!p)
643       return CURLE_OUT_OF_MEMORY;
644 
645     mbedtls_x509_crt_init(p);
646 
647     /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der
648        needs a non-const key, for now.
649        https://github.com/ARMmbed/mbedtls/issues/396 */
650     if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) {
651       failf(data, "Failed copying peer certificate");
652       mbedtls_x509_crt_free(p);
653       free(p);
654       return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
655     }
656 
657     size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES);
658 
659     if(size <= 0) {
660       failf(data, "Failed copying public key from peer certificate");
661       mbedtls_x509_crt_free(p);
662       free(p);
663       return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
664     }
665 
666     /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */
667     result = Curl_pin_peer_pubkey(data,
668                                   pinnedpubkey,
669                                   &pubkey[PUB_DER_MAX_BYTES - size], size);
670     if(result) {
671       mbedtls_x509_crt_free(p);
672       free(p);
673       return result;
674     }
675 
676     mbedtls_x509_crt_free(p);
677     free(p);
678   }
679 
680 #ifdef HAS_ALPN
681   if(conn->bits.tls_enable_alpn) {
682     const char *next_protocol = mbedtls_ssl_get_alpn_protocol(&backend->ssl);
683 
684     if(next_protocol) {
685       infof(data, "ALPN, server accepted to use %s", next_protocol);
686 #ifdef USE_NGHTTP2
687       if(!strncmp(next_protocol, NGHTTP2_PROTO_VERSION_ID,
688                   NGHTTP2_PROTO_VERSION_ID_LEN) &&
689          !next_protocol[NGHTTP2_PROTO_VERSION_ID_LEN]) {
690         conn->negnpn = CURL_HTTP_VERSION_2;
691       }
692       else
693 #endif
694         if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH) &&
695            !next_protocol[ALPN_HTTP_1_1_LENGTH]) {
696           conn->negnpn = CURL_HTTP_VERSION_1_1;
697         }
698     }
699     else {
700       infof(data, "ALPN, server did not agree to a protocol");
701     }
702     Curl_multiuse_state(data, conn->negnpn == CURL_HTTP_VERSION_2 ?
703                         BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
704   }
705 #endif
706 
707   connssl->connecting_state = ssl_connect_3;
708   infof(data, "SSL connected");
709 
710   return CURLE_OK;
711 }
712 
713 static CURLcode
mbed_connect_step3(struct Curl_easy * data,struct connectdata * conn,int sockindex)714 mbed_connect_step3(struct Curl_easy *data, struct connectdata *conn,
715                    int sockindex)
716 {
717   CURLcode retcode = CURLE_OK;
718   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
719   struct ssl_backend_data *backend = connssl->backend;
720 
721   DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
722 
723   if(SSL_SET_OPTION(primary.sessionid)) {
724     int ret;
725     mbedtls_ssl_session *our_ssl_sessionid;
726     void *old_ssl_sessionid = NULL;
727     bool isproxy = SSL_IS_PROXY() ? TRUE : FALSE;
728 
729     our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session));
730     if(!our_ssl_sessionid)
731       return CURLE_OUT_OF_MEMORY;
732 
733     mbedtls_ssl_session_init(our_ssl_sessionid);
734 
735     ret = mbedtls_ssl_get_session(&backend->ssl, our_ssl_sessionid);
736     if(ret) {
737       if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED)
738         mbedtls_ssl_session_free(our_ssl_sessionid);
739       free(our_ssl_sessionid);
740       failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret);
741       return CURLE_SSL_CONNECT_ERROR;
742     }
743 
744     /* If there's already a matching session in the cache, delete it */
745     Curl_ssl_sessionid_lock(data);
746     if(!Curl_ssl_getsessionid(data, conn, isproxy, &old_ssl_sessionid, NULL,
747                               sockindex))
748       Curl_ssl_delsessionid(data, old_ssl_sessionid);
749 
750     retcode = Curl_ssl_addsessionid(data, conn, isproxy, our_ssl_sessionid,
751                                     0, sockindex);
752     Curl_ssl_sessionid_unlock(data);
753     if(retcode) {
754       mbedtls_ssl_session_free(our_ssl_sessionid);
755       free(our_ssl_sessionid);
756       failf(data, "failed to store ssl session");
757       return retcode;
758     }
759   }
760 
761   connssl->connecting_state = ssl_connect_done;
762 
763   return CURLE_OK;
764 }
765 
mbed_send(struct Curl_easy * data,int sockindex,const void * mem,size_t len,CURLcode * curlcode)766 static ssize_t mbed_send(struct Curl_easy *data, int sockindex,
767                          const void *mem, size_t len,
768                          CURLcode *curlcode)
769 {
770   struct connectdata *conn = data->conn;
771   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
772   struct ssl_backend_data *backend = connssl->backend;
773   int ret = -1;
774 
775   ret = mbedtls_ssl_write(&backend->ssl, (unsigned char *)mem, len);
776 
777   if(ret < 0) {
778     *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_WRITE) ?
779       CURLE_AGAIN : CURLE_SEND_ERROR;
780     ret = -1;
781   }
782 
783   return ret;
784 }
785 
mbedtls_close_all(struct Curl_easy * data)786 static void mbedtls_close_all(struct Curl_easy *data)
787 {
788   (void)data;
789 }
790 
mbedtls_close(struct Curl_easy * data,struct connectdata * conn,int sockindex)791 static void mbedtls_close(struct Curl_easy *data,
792                           struct connectdata *conn, int sockindex)
793 {
794   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
795   struct ssl_backend_data *backend = connssl->backend;
796   char buf[32];
797   (void) data;
798 
799   /* Maybe the server has already sent a close notify alert.
800      Read it to avoid an RST on the TCP connection. */
801   (void)mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf, sizeof(buf));
802 
803   mbedtls_pk_free(&backend->pk);
804   mbedtls_x509_crt_free(&backend->clicert);
805   mbedtls_x509_crt_free(&backend->cacert);
806   mbedtls_x509_crl_free(&backend->crl);
807   mbedtls_ssl_config_free(&backend->config);
808   mbedtls_ssl_free(&backend->ssl);
809   mbedtls_ctr_drbg_free(&backend->ctr_drbg);
810 #ifndef THREADING_SUPPORT
811   mbedtls_entropy_free(&backend->entropy);
812 #endif /* THREADING_SUPPORT */
813 }
814 
mbed_recv(struct Curl_easy * data,int num,char * buf,size_t buffersize,CURLcode * curlcode)815 static ssize_t mbed_recv(struct Curl_easy *data, int num,
816                          char *buf, size_t buffersize,
817                          CURLcode *curlcode)
818 {
819   struct connectdata *conn = data->conn;
820   struct ssl_connect_data *connssl = &conn->ssl[num];
821   struct ssl_backend_data *backend = connssl->backend;
822   int ret = -1;
823   ssize_t len = -1;
824 
825   ret = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf,
826                          buffersize);
827 
828   if(ret <= 0) {
829     if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
830       return 0;
831 
832     *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_READ) ?
833       CURLE_AGAIN : CURLE_RECV_ERROR;
834     return -1;
835   }
836 
837   len = ret;
838 
839   return len;
840 }
841 
mbedtls_session_free(void * ptr)842 static void mbedtls_session_free(void *ptr)
843 {
844   mbedtls_ssl_session_free(ptr);
845   free(ptr);
846 }
847 
mbedtls_version(char * buffer,size_t size)848 static size_t mbedtls_version(char *buffer, size_t size)
849 {
850 #ifdef MBEDTLS_VERSION_C
851   /* if mbedtls_version_get_number() is available it is better */
852   unsigned int version = mbedtls_version_get_number();
853   return msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version>>24,
854                    (version>>16)&0xff, (version>>8)&0xff);
855 #else
856   return msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING);
857 #endif
858 }
859 
mbedtls_random(struct Curl_easy * data,unsigned char * entropy,size_t length)860 static CURLcode mbedtls_random(struct Curl_easy *data,
861                                unsigned char *entropy, size_t length)
862 {
863 #if defined(MBEDTLS_CTR_DRBG_C)
864   int ret = -1;
865   char errorbuf[128];
866   mbedtls_entropy_context ctr_entropy;
867   mbedtls_ctr_drbg_context ctr_drbg;
868   mbedtls_entropy_init(&ctr_entropy);
869   mbedtls_ctr_drbg_init(&ctr_drbg);
870 
871   ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
872                               &ctr_entropy, NULL, 0);
873 
874   if(ret) {
875     mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
876     failf(data, "Failed - mbedTLS: ctr_drbg_seed returned (-0x%04X) %s",
877           -ret, errorbuf);
878   }
879   else {
880     ret = mbedtls_ctr_drbg_random(&ctr_drbg, entropy, length);
881 
882     if(ret) {
883       mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
884       failf(data, "mbedTLS: ctr_drbg_init returned (-0x%04X) %s",
885             -ret, errorbuf);
886     }
887   }
888 
889   mbedtls_ctr_drbg_free(&ctr_drbg);
890   mbedtls_entropy_free(&ctr_entropy);
891 
892   return ret == 0 ? CURLE_OK : CURLE_FAILED_INIT;
893 #elif defined(MBEDTLS_HAVEGE_C)
894   mbedtls_havege_state hs;
895   mbedtls_havege_init(&hs);
896   mbedtls_havege_random(&hs, entropy, length);
897   mbedtls_havege_free(&hs);
898   return CURLE_OK;
899 #else
900   return CURLE_NOT_BUILT_IN;
901 #endif
902 }
903 
904 static CURLcode
mbed_connect_common(struct Curl_easy * data,struct connectdata * conn,int sockindex,bool nonblocking,bool * done)905 mbed_connect_common(struct Curl_easy *data,
906                     struct connectdata *conn,
907                     int sockindex,
908                     bool nonblocking,
909                     bool *done)
910 {
911   CURLcode retcode;
912   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
913   curl_socket_t sockfd = conn->sock[sockindex];
914   timediff_t timeout_ms;
915   int what;
916 
917   /* check if the connection has already been established */
918   if(ssl_connection_complete == connssl->state) {
919     *done = TRUE;
920     return CURLE_OK;
921   }
922 
923   if(ssl_connect_1 == connssl->connecting_state) {
924     /* Find out how much more time we're allowed */
925     timeout_ms = Curl_timeleft(data, NULL, TRUE);
926 
927     if(timeout_ms < 0) {
928       /* no need to continue if time already is up */
929       failf(data, "SSL connection timeout");
930       return CURLE_OPERATION_TIMEDOUT;
931     }
932     retcode = mbed_connect_step1(data, conn, sockindex);
933     if(retcode)
934       return retcode;
935   }
936 
937   while(ssl_connect_2 == connssl->connecting_state ||
938         ssl_connect_2_reading == connssl->connecting_state ||
939         ssl_connect_2_writing == connssl->connecting_state) {
940 
941     /* check allowed time left */
942     timeout_ms = Curl_timeleft(data, NULL, TRUE);
943 
944     if(timeout_ms < 0) {
945       /* no need to continue if time already is up */
946       failf(data, "SSL connection timeout");
947       return CURLE_OPERATION_TIMEDOUT;
948     }
949 
950     /* if ssl is expecting something, check if it's available. */
951     if(connssl->connecting_state == ssl_connect_2_reading
952        || connssl->connecting_state == ssl_connect_2_writing) {
953 
954       curl_socket_t writefd = ssl_connect_2_writing ==
955         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
956       curl_socket_t readfd = ssl_connect_2_reading ==
957         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
958 
959       what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
960                                nonblocking ? 0 : timeout_ms);
961       if(what < 0) {
962         /* fatal error */
963         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
964         return CURLE_SSL_CONNECT_ERROR;
965       }
966       else if(0 == what) {
967         if(nonblocking) {
968           *done = FALSE;
969           return CURLE_OK;
970         }
971         else {
972           /* timeout */
973           failf(data, "SSL connection timeout");
974           return CURLE_OPERATION_TIMEDOUT;
975         }
976       }
977       /* socket is readable or writable */
978     }
979 
980     /* Run transaction, and return to the caller if it failed or if
981      * this connection is part of a multi handle and this loop would
982      * execute again. This permits the owner of a multi handle to
983      * abort a connection attempt before step2 has completed while
984      * ensuring that a client using select() or epoll() will always
985      * have a valid fdset to wait on.
986      */
987     retcode = mbed_connect_step2(data, conn, sockindex);
988     if(retcode || (nonblocking &&
989                    (ssl_connect_2 == connssl->connecting_state ||
990                     ssl_connect_2_reading == connssl->connecting_state ||
991                     ssl_connect_2_writing == connssl->connecting_state)))
992       return retcode;
993 
994   } /* repeat step2 until all transactions are done. */
995 
996   if(ssl_connect_3 == connssl->connecting_state) {
997     retcode = mbed_connect_step3(data, conn, sockindex);
998     if(retcode)
999       return retcode;
1000   }
1001 
1002   if(ssl_connect_done == connssl->connecting_state) {
1003     connssl->state = ssl_connection_complete;
1004     conn->recv[sockindex] = mbed_recv;
1005     conn->send[sockindex] = mbed_send;
1006     *done = TRUE;
1007   }
1008   else
1009     *done = FALSE;
1010 
1011   /* Reset our connect state machine */
1012   connssl->connecting_state = ssl_connect_1;
1013 
1014   return CURLE_OK;
1015 }
1016 
mbedtls_connect_nonblocking(struct Curl_easy * data,struct connectdata * conn,int sockindex,bool * done)1017 static CURLcode mbedtls_connect_nonblocking(struct Curl_easy *data,
1018                                             struct connectdata *conn,
1019                                             int sockindex, bool *done)
1020 {
1021   return mbed_connect_common(data, conn, sockindex, TRUE, done);
1022 }
1023 
1024 
mbedtls_connect(struct Curl_easy * data,struct connectdata * conn,int sockindex)1025 static CURLcode mbedtls_connect(struct Curl_easy *data,
1026                                 struct connectdata *conn, int sockindex)
1027 {
1028   CURLcode retcode;
1029   bool done = FALSE;
1030 
1031   retcode = mbed_connect_common(data, conn, sockindex, FALSE, &done);
1032   if(retcode)
1033     return retcode;
1034 
1035   DEBUGASSERT(done);
1036 
1037   return CURLE_OK;
1038 }
1039 
1040 /*
1041  * return 0 error initializing SSL
1042  * return 1 SSL initialized successfully
1043  */
mbedtls_init(void)1044 static int mbedtls_init(void)
1045 {
1046   return Curl_mbedtlsthreadlock_thread_setup();
1047 }
1048 
mbedtls_cleanup(void)1049 static void mbedtls_cleanup(void)
1050 {
1051   (void)Curl_mbedtlsthreadlock_thread_cleanup();
1052 }
1053 
mbedtls_data_pending(const struct connectdata * conn,int sockindex)1054 static bool mbedtls_data_pending(const struct connectdata *conn,
1055                                  int sockindex)
1056 {
1057   const struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1058   struct ssl_backend_data *backend = connssl->backend;
1059   return mbedtls_ssl_get_bytes_avail(&backend->ssl) != 0;
1060 }
1061 
mbedtls_sha256sum(const unsigned char * input,size_t inputlen,unsigned char * sha256sum,size_t sha256len UNUSED_PARAM)1062 static CURLcode mbedtls_sha256sum(const unsigned char *input,
1063                                   size_t inputlen,
1064                                   unsigned char *sha256sum,
1065                                   size_t sha256len UNUSED_PARAM)
1066 {
1067   (void)sha256len;
1068 #if MBEDTLS_VERSION_NUMBER < 0x02070000
1069   mbedtls_sha256(input, inputlen, sha256sum, 0);
1070 #else
1071   /* returns 0 on success, otherwise failure */
1072   if(mbedtls_sha256(input, inputlen, sha256sum, 0) != 0)
1073     return CURLE_BAD_FUNCTION_ARGUMENT;
1074 #endif
1075   return CURLE_OK;
1076 }
1077 
mbedtls_get_internals(struct ssl_connect_data * connssl,CURLINFO info UNUSED_PARAM)1078 static void *mbedtls_get_internals(struct ssl_connect_data *connssl,
1079                                    CURLINFO info UNUSED_PARAM)
1080 {
1081   struct ssl_backend_data *backend = connssl->backend;
1082   (void)info;
1083   return &backend->ssl;
1084 }
1085 
1086 const struct Curl_ssl Curl_ssl_mbedtls = {
1087   { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */
1088 
1089   SSLSUPP_CA_PATH |
1090   SSLSUPP_PINNEDPUBKEY |
1091   SSLSUPP_SSL_CTX,
1092 
1093   sizeof(struct ssl_backend_data),
1094 
1095   mbedtls_init,                     /* init */
1096   mbedtls_cleanup,                  /* cleanup */
1097   mbedtls_version,                  /* version */
1098   Curl_none_check_cxn,              /* check_cxn */
1099   Curl_none_shutdown,               /* shutdown */
1100   mbedtls_data_pending,             /* data_pending */
1101   mbedtls_random,                   /* random */
1102   Curl_none_cert_status_request,    /* cert_status_request */
1103   mbedtls_connect,                  /* connect */
1104   mbedtls_connect_nonblocking,      /* connect_nonblocking */
1105   Curl_ssl_getsock,                 /* getsock */
1106   mbedtls_get_internals,            /* get_internals */
1107   mbedtls_close,                    /* close_one */
1108   mbedtls_close_all,                /* close_all */
1109   mbedtls_session_free,             /* session_free */
1110   Curl_none_set_engine,             /* set_engine */
1111   Curl_none_set_engine_default,     /* set_engine_default */
1112   Curl_none_engines_list,           /* engines_list */
1113   Curl_none_false_start,            /* false_start */
1114   mbedtls_sha256sum,                /* sha256sum */
1115   NULL,                             /* associate_connection */
1116   NULL                              /* disassociate_connection */
1117 };
1118 
1119 #endif /* USE_MBEDTLS */
1120