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