1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 2012 - 2019, 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.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 PolarSSL-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_POLARSSL
33#include <polarssl/net.h>
34#include <polarssl/ssl.h>
35#include <polarssl/certs.h>
36#include <polarssl/x509.h>
37#include <polarssl/version.h>
38#include <polarssl/sha256.h>
39
40#if POLARSSL_VERSION_NUMBER < 0x01030000
41#error too old PolarSSL
42#endif
43
44#include <polarssl/error.h>
45#include <polarssl/entropy.h>
46#include <polarssl/ctr_drbg.h>
47
48#include "urldata.h"
49#include "sendf.h"
50#include "inet_pton.h"
51#include "polarssl.h"
52#include "vtls.h"
53#include "parsedate.h"
54#include "connect.h" /* for the connect timeout */
55#include "select.h"
56#include "strcase.h"
57#include "polarssl_threadlock.h"
58#include "multiif.h"
59#include "curl_printf.h"
60#include "curl_memory.h"
61/* The last #include file should be: */
62#include "memdebug.h"
63
64/* See https://tls.mbed.org/discussions/generic/
65 howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der
66*/
67#define RSA_PUB_DER_MAX_BYTES (38 + 2 * POLARSSL_MPI_MAX_SIZE)
68#define ECP_PUB_DER_MAX_BYTES (30 + 2 * POLARSSL_ECP_MAX_BYTES)
69
70#define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
71 RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
72
73struct ssl_backend_data {
74 ctr_drbg_context ctr_drbg;
75 entropy_context entropy;
76 ssl_context ssl;
77 int server_fd;
78 x509_crt cacert;
79 x509_crt clicert;
80 x509_crl crl;
81 rsa_context rsa;
82};
83
84#define BACKEND connssl->backend
85
86/* apply threading? */
87#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
88#define THREADING_SUPPORT
89#endif
90
91#ifndef POLARSSL_ERROR_C
92#define error_strerror(x,y,z)
93#endif /* POLARSSL_ERROR_C */
94
95
96#if defined(THREADING_SUPPORT)
97static entropy_context entropy;
98
99static int entropy_init_initialized = 0;
100
101/* start of entropy_init_mutex() */
102static void entropy_init_mutex(entropy_context *ctx)
103{
104 /* lock 0 = entropy_init_mutex() */
105 Curl_polarsslthreadlock_lock_function(0);
106 if(entropy_init_initialized == 0) {
107 entropy_init(ctx);
108 entropy_init_initialized = 1;
109 }
110 Curl_polarsslthreadlock_unlock_function(0);
111}
112/* end of entropy_init_mutex() */
113
114/* start of entropy_func_mutex() */
115static int entropy_func_mutex(void *data, unsigned char *output, size_t len)
116{
117 int ret;
118 /* lock 1 = entropy_func_mutex() */
119 Curl_polarsslthreadlock_lock_function(1);
120 ret = entropy_func(data, output, len);
121 Curl_polarsslthreadlock_unlock_function(1);
122
123 return ret;
124}
125/* end of entropy_func_mutex() */
126
127#endif /* THREADING_SUPPORT */
128
129/* Define this to enable lots of debugging for PolarSSL */
130#undef POLARSSL_DEBUG
131
132#ifdef POLARSSL_DEBUG
133static void polarssl_debug(void *context, int level, const char *line)
134{
135 struct Curl_easy *data = NULL;
136
137 if(!context)
138 return;
139
140 data = (struct Curl_easy *)context;
141
142 infof(data, "%s", line);
143 (void) level;
144}
145#else
146#endif
147
148/* ALPN for http2? */
149#ifdef POLARSSL_SSL_ALPN
150# define HAS_ALPN
151#endif
152
153static Curl_recv polarssl_recv;
154static Curl_send polarssl_send;
155
156static CURLcode polarssl_version_from_curl(int *polarver, long ssl_version)
157{
158 switch(ssl_version) {
159 case CURL_SSLVERSION_TLSv1_0:
160 *polarver = SSL_MINOR_VERSION_1;
161 return CURLE_OK;
162 case CURL_SSLVERSION_TLSv1_1:
163 *polarver = SSL_MINOR_VERSION_2;
164 return CURLE_OK;
165 case CURL_SSLVERSION_TLSv1_2:
166 *polarver = SSL_MINOR_VERSION_3;
167 return CURLE_OK;
168 case CURL_SSLVERSION_TLSv1_3:
169 break;
170 }
171 return CURLE_SSL_CONNECT_ERROR;
172}
173
174static CURLcode
175set_ssl_version_min_max(struct connectdata *conn, int sockindex)
176{
177 struct Curl_easy *data = conn->data;
178 struct ssl_connect_data* connssl = &conn->ssl[sockindex];
179 long ssl_version = SSL_CONN_CONFIG(version);
180 long ssl_version_max = SSL_CONN_CONFIG(version_max);
181 int ssl_min_ver = SSL_MINOR_VERSION_1;
182 int ssl_max_ver = SSL_MINOR_VERSION_1;
183 CURLcode result = CURLE_OK;
184
185 switch(ssl_version) {
186 case CURL_SSLVERSION_DEFAULT:
187 case CURL_SSLVERSION_TLSv1:
188 ssl_version = CURL_SSLVERSION_TLSv1_0;
189 break;
190 }
191
192 switch(ssl_version_max) {
193 case CURL_SSLVERSION_MAX_NONE:
194 case CURL_SSLVERSION_MAX_DEFAULT:
195 ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2;
196 break;
197 }
198
199 result = polarssl_version_from_curl(&ssl_min_ver, ssl_version);
200 if(result) {
201 failf(data, "unsupported min version passed via CURLOPT_SSLVERSION");
202 return result;
203 }
204 result = polarssl_version_from_curl(&ssl_max_ver, ssl_version_max >> 16);
205 if(result) {
206 failf(data, "unsupported max version passed via CURLOPT_SSLVERSION");
207 return result;
208 }
209
210 ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, ssl_min_ver);
211 ssl_set_max_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, ssl_max_ver);
212
213 return result;
214}
215
216static CURLcode
217polarssl_connect_step1(struct connectdata *conn,
218 int sockindex)
219{
220 struct Curl_easy *data = conn->data;
221 struct ssl_connect_data* connssl = &conn->ssl[sockindex];
222 const char *capath = SSL_CONN_CONFIG(CApath);
223 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
224 conn->host.name;
225 const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
226 int ret = -1;
227 char errorbuf[128];
228 errorbuf[0] = 0;
229
230 /* PolarSSL only supports SSLv3 and TLSv1 */
231 if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) {
232 failf(data, "PolarSSL does not support SSLv2");
233 return CURLE_SSL_CONNECT_ERROR;
234 }
235
236#ifdef THREADING_SUPPORT
237 entropy_init_mutex(&entropy);
238
239 if((ret = ctr_drbg_init(&BACKEND->ctr_drbg, entropy_func_mutex, &entropy,
240 NULL, 0)) != 0) {
241 error_strerror(ret, errorbuf, sizeof(errorbuf));
242 failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
243 -ret, errorbuf);
244 }
245#else
246 entropy_init(&BACKEND->entropy);
247
248 if((ret = ctr_drbg_init(&BACKEND->ctr_drbg, entropy_func, &BACKEND->entropy,
249 NULL, 0)) != 0) {
250 error_strerror(ret, errorbuf, sizeof(errorbuf));
251 failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
252 -ret, errorbuf);
253 }
254#endif /* THREADING_SUPPORT */
255
256 /* Load the trusted CA */
257 memset(&BACKEND->cacert, 0, sizeof(x509_crt));
258
259 if(SSL_CONN_CONFIG(CAfile)) {
260 ret = x509_crt_parse_file(&BACKEND->cacert,
261 SSL_CONN_CONFIG(CAfile));
262
263 if(ret<0) {
264 error_strerror(ret, errorbuf, sizeof(errorbuf));
265 failf(data, "Error reading ca cert file %s - PolarSSL: (-0x%04X) %s",
266 SSL_CONN_CONFIG(CAfile), -ret, errorbuf);
267
268 if(SSL_CONN_CONFIG(verifypeer))
269 return CURLE_SSL_CACERT_BADFILE;
270 }
271 }
272
273 if(capath) {
274 ret = x509_crt_parse_path(&BACKEND->cacert, capath);
275
276 if(ret<0) {
277 error_strerror(ret, errorbuf, sizeof(errorbuf));
278 failf(data, "Error reading ca cert path %s - PolarSSL: (-0x%04X) %s",
279 capath, -ret, errorbuf);
280
281 if(SSL_CONN_CONFIG(verifypeer))
282 return CURLE_SSL_CACERT_BADFILE;
283 }
284 }
285
286 /* Load the client certificate */
287 memset(&BACKEND->clicert, 0, sizeof(x509_crt));
288
289 if(SSL_SET_OPTION(cert)) {
290 ret = x509_crt_parse_file(&BACKEND->clicert,
291 SSL_SET_OPTION(cert));
292
293 if(ret) {
294 error_strerror(ret, errorbuf, sizeof(errorbuf));
295 failf(data, "Error reading client cert file %s - PolarSSL: (-0x%04X) %s",
296 SSL_SET_OPTION(cert), -ret, errorbuf);
297
298 return CURLE_SSL_CERTPROBLEM;
299 }
300 }
301
302 /* Load the client private key */
303 if(SSL_SET_OPTION(key)) {
304 pk_context pk;
305 pk_init(&pk);
306 ret = pk_parse_keyfile(&pk, SSL_SET_OPTION(key),
307 SSL_SET_OPTION(key_passwd));
308 if(ret == 0 && !pk_can_do(&pk, POLARSSL_PK_RSA))
309 ret = POLARSSL_ERR_PK_TYPE_MISMATCH;
310 if(ret == 0)
311 rsa_copy(&BACKEND->rsa, pk_rsa(pk));
312 else
313 rsa_free(&BACKEND->rsa);
314 pk_free(&pk);
315
316 if(ret) {
317 error_strerror(ret, errorbuf, sizeof(errorbuf));
318 failf(data, "Error reading private key %s - PolarSSL: (-0x%04X) %s",
319 SSL_SET_OPTION(key), -ret, errorbuf);
320
321 return CURLE_SSL_CERTPROBLEM;
322 }
323 }
324
325 /* Load the CRL */
326 memset(&BACKEND->crl, 0, sizeof(x509_crl));
327
328 if(SSL_SET_OPTION(CRLfile)) {
329 ret = x509_crl_parse_file(&BACKEND->crl,
330 SSL_SET_OPTION(CRLfile));
331
332 if(ret) {
333 error_strerror(ret, errorbuf, sizeof(errorbuf));
334 failf(data, "Error reading CRL file %s - PolarSSL: (-0x%04X) %s",
335 SSL_SET_OPTION(CRLfile), -ret, errorbuf);
336
337 return CURLE_SSL_CRL_BADFILE;
338 }
339 }
340
341 infof(data, "PolarSSL: Connecting to %s:%d\n", hostname, port);
342
343 if(ssl_init(&BACKEND->ssl)) {
344 failf(data, "PolarSSL: ssl_init failed");
345 return CURLE_SSL_CONNECT_ERROR;
346 }
347
348 switch(SSL_CONN_CONFIG(version)) {
349 case CURL_SSLVERSION_DEFAULT:
350 case CURL_SSLVERSION_TLSv1:
351 ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3,
352 SSL_MINOR_VERSION_1);
353 break;
354 case CURL_SSLVERSION_SSLv3:
355 ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3,
356 SSL_MINOR_VERSION_0);
357 ssl_set_max_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3,
358 SSL_MINOR_VERSION_0);
359 infof(data, "PolarSSL: Forced min. SSL Version to be SSLv3\n");
360 break;
361 case CURL_SSLVERSION_TLSv1_0:
362 case CURL_SSLVERSION_TLSv1_1:
363 case CURL_SSLVERSION_TLSv1_2:
364 case CURL_SSLVERSION_TLSv1_3:
365 {
366 CURLcode result = set_ssl_version_min_max(conn, sockindex);
367 if(result != CURLE_OK)
368 return result;
369 break;
370 }
371 default:
372 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
373 return CURLE_SSL_CONNECT_ERROR;
374 }
375
376 ssl_set_endpoint(&BACKEND->ssl, SSL_IS_CLIENT);
377 ssl_set_authmode(&BACKEND->ssl, SSL_VERIFY_OPTIONAL);
378
379 ssl_set_rng(&BACKEND->ssl, ctr_drbg_random,
380 &BACKEND->ctr_drbg);
381 ssl_set_bio(&BACKEND->ssl,
382 net_recv, &conn->sock[sockindex],
383 net_send, &conn->sock[sockindex]);
384
385 ssl_set_ciphersuites(&BACKEND->ssl, ssl_list_ciphersuites());
386
387 /* Check if there's a cached ID we can/should use here! */
388 if(SSL_SET_OPTION(primary.sessionid)) {
389 void *old_session = NULL;
390
391 Curl_ssl_sessionid_lock(conn);
392 if(!Curl_ssl_getsessionid(conn, &old_session, NULL, sockindex)) {
393 ret = ssl_set_session(&BACKEND->ssl, old_session);
394 if(ret) {
395 Curl_ssl_sessionid_unlock(conn);
396 failf(data, "ssl_set_session returned -0x%x", -ret);
397 return CURLE_SSL_CONNECT_ERROR;
398 }
399 infof(data, "PolarSSL re-using session\n");
400 }
401 Curl_ssl_sessionid_unlock(conn);
402 }
403
404 ssl_set_ca_chain(&BACKEND->ssl,
405 &BACKEND->cacert,
406 &BACKEND->crl,
407 hostname);
408
409 ssl_set_own_cert_rsa(&BACKEND->ssl,
410 &BACKEND->clicert, &BACKEND->rsa);
411
412 if(ssl_set_hostname(&BACKEND->ssl, hostname)) {
413 /* ssl_set_hostname() sets the name to use in CN/SAN checks *and* the name
414 to set in the SNI extension. So even if curl connects to a host
415 specified as an IP address, this function must be used. */
416 failf(data, "couldn't set hostname in PolarSSL");
417 return CURLE_SSL_CONNECT_ERROR;
418 }
419
420#ifdef HAS_ALPN
421 if(conn->bits.tls_enable_alpn) {
422 static const char *protocols[3];
423 int cur = 0;
424
425#ifdef USE_NGHTTP2
426 if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
427 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID;
428 infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
429 }
430#endif
431
432 protocols[cur++] = ALPN_HTTP_1_1;
433 infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
434
435 protocols[cur] = NULL;
436
437 ssl_set_alpn_protocols(&BACKEND->ssl, protocols);
438 }
439#endif
440
441#ifdef POLARSSL_DEBUG
442 ssl_set_dbg(&BACKEND->ssl, polarssl_debug, data);
443#endif
444
445 connssl->connecting_state = ssl_connect_2;
446
447 return CURLE_OK;
448}
449
450static CURLcode
451polarssl_connect_step2(struct connectdata *conn,
452 int sockindex)
453{
454 int ret;
455 struct Curl_easy *data = conn->data;
456 struct ssl_connect_data* connssl = &conn->ssl[sockindex];
457 char buffer[1024];
458 const char * const pinnedpubkey = SSL_IS_PROXY() ?
459 data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
460 data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
461
462
463 char errorbuf[128];
464 errorbuf[0] = 0;
465
466 conn->recv[sockindex] = polarssl_recv;
467 conn->send[sockindex] = polarssl_send;
468
469 ret = ssl_handshake(&BACKEND->ssl);
470
471 switch(ret) {
472 case 0:
473 break;
474
475 case POLARSSL_ERR_NET_WANT_READ:
476 connssl->connecting_state = ssl_connect_2_reading;
477 return CURLE_OK;
478
479 case POLARSSL_ERR_NET_WANT_WRITE:
480 connssl->connecting_state = ssl_connect_2_writing;
481 return CURLE_OK;
482
483 default:
484 error_strerror(ret, errorbuf, sizeof(errorbuf));
485 failf(data, "ssl_handshake returned - PolarSSL: (-0x%04X) %s",
486 -ret, errorbuf);
487 return CURLE_SSL_CONNECT_ERROR;
488 }
489
490 infof(data, "PolarSSL: Handshake complete, cipher is %s\n",
491 ssl_get_ciphersuite(&BACKEND->ssl) );
492
493 ret = ssl_get_verify_result(&BACKEND->ssl);
494
495 if(ret && SSL_CONN_CONFIG(verifypeer)) {
496 if(ret & BADCERT_EXPIRED)
497 failf(data, "Cert verify failed: BADCERT_EXPIRED");
498
499 if(ret & BADCERT_REVOKED) {
500 failf(data, "Cert verify failed: BADCERT_REVOKED");
501 return CURLE_PEER_FAILED_VERIFICATION;
502 }
503
504 if(ret & BADCERT_CN_MISMATCH)
505 failf(data, "Cert verify failed: BADCERT_CN_MISMATCH");
506
507 if(ret & BADCERT_NOT_TRUSTED)
508 failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED");
509
510 return CURLE_PEER_FAILED_VERIFICATION;
511 }
512
513 if(ssl_get_peer_cert(&(BACKEND->ssl))) {
514 /* If the session was resumed, there will be no peer certs */
515 memset(buffer, 0, sizeof(buffer));
516
517 if(x509_crt_info(buffer, sizeof(buffer), (char *)"* ",
518 ssl_get_peer_cert(&(BACKEND->ssl))) != -1)
519 infof(data, "Dumping cert info:\n%s\n", buffer);
520 }
521
522 /* adapted from mbedtls.c */
523 if(pinnedpubkey) {
524 int size;
525 CURLcode result;
526 x509_crt *p;
527 unsigned char pubkey[PUB_DER_MAX_BYTES];
528 const x509_crt *peercert;
529
530 peercert = ssl_get_peer_cert(&BACKEND->ssl);
531
532 if(!peercert || !peercert->raw.p || !peercert->raw.len) {
533 failf(data, "Failed due to missing peer certificate");
534 return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
535 }
536
537 p = calloc(1, sizeof(*p));
538
539 if(!p)
540 return CURLE_OUT_OF_MEMORY;
541
542 x509_crt_init(p);
543
544 /* Make a copy of our const peercert because pk_write_pubkey_der
545 needs a non-const key, for now.
546 https://github.com/ARMmbed/mbedtls/issues/396 */
547 if(x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) {
548 failf(data, "Failed copying peer certificate");
549 x509_crt_free(p);
550 free(p);
551 return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
552 }
553
554 size = pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES);
555
556 if(size <= 0) {
557 failf(data, "Failed copying public key from peer certificate");
558 x509_crt_free(p);
559 free(p);
560 return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
561 }
562
563 /* pk_write_pubkey_der writes data at the end of the buffer. */
564 result = Curl_pin_peer_pubkey(data,
565 pinnedpubkey,
566 &pubkey[PUB_DER_MAX_BYTES - size], size);
567 if(result) {
568 x509_crt_free(p);
569 free(p);
570 return result;
571 }
572
573 x509_crt_free(p);
574 free(p);
575 }
576
577#ifdef HAS_ALPN
578 if(conn->bits.tls_enable_alpn) {
579 const char *next_protocol = ssl_get_alpn_protocol(&BACKEND->ssl);
580
581 if(next_protocol != NULL) {
582 infof(data, "ALPN, server accepted to use %s\n", next_protocol);
583
584#ifdef USE_NGHTTP2
585 if(!strncmp(next_protocol, NGHTTP2_PROTO_VERSION_ID,
586 NGHTTP2_PROTO_VERSION_ID_LEN)) {
587 conn->negnpn = CURL_HTTP_VERSION_2;
588 }
589 else
590#endif
591 if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH)) {
592 conn->negnpn = CURL_HTTP_VERSION_1_1;
593 }
594 }
595 else
596 infof(data, "ALPN, server did not agree to a protocol\n");
597 Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ?
598 BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
599 }
600#endif
601
602 connssl->connecting_state = ssl_connect_3;
603 infof(data, "SSL connected\n");
604
605 return CURLE_OK;
606}
607
608static CURLcode
609polarssl_connect_step3(struct connectdata *conn,
610 int sockindex)
611{
612 CURLcode retcode = CURLE_OK;
613 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
614 struct Curl_easy *data = conn->data;
615
616 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
617
618 if(SSL_SET_OPTION(primary.sessionid)) {
619 int ret;
620 ssl_session *our_ssl_sessionid;
621 void *old_ssl_sessionid = NULL;
622
623 our_ssl_sessionid = calloc(1, sizeof(ssl_session));
624 if(!our_ssl_sessionid)
625 return CURLE_OUT_OF_MEMORY;
626
627 ret = ssl_get_session(&BACKEND->ssl, our_ssl_sessionid);
628 if(ret) {
629 failf(data, "ssl_get_session returned -0x%x", -ret);
630 return CURLE_SSL_CONNECT_ERROR;
631 }
632
633 /* If there's already a matching session in the cache, delete it */
634 Curl_ssl_sessionid_lock(conn);
635 if(!Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL, sockindex))
636 Curl_ssl_delsessionid(conn, old_ssl_sessionid);
637
638 retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid, 0, sockindex);
639 Curl_ssl_sessionid_unlock(conn);
640 if(retcode) {
641 free(our_ssl_sessionid);
642 failf(data, "failed to store ssl session");
643 return retcode;
644 }
645 }
646
647 connssl->connecting_state = ssl_connect_done;
648
649 return CURLE_OK;
650}
651
652static ssize_t polarssl_send(struct connectdata *conn,
653 int sockindex,
654 const void *mem,
655 size_t len,
656 CURLcode *curlcode)
657{
658 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
659 int ret = -1;
660
661 ret = ssl_write(&BACKEND->ssl,
662 (unsigned char *)mem, len);
663
664 if(ret < 0) {
665 *curlcode = (ret == POLARSSL_ERR_NET_WANT_WRITE) ?
666 CURLE_AGAIN : CURLE_SEND_ERROR;
667 ret = -1;
668 }
669
670 return ret;
671}
672
673static void Curl_polarssl_close(struct connectdata *conn, int sockindex)
674{
675 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
676 rsa_free(&BACKEND->rsa);
677 x509_crt_free(&BACKEND->clicert);
678 x509_crt_free(&BACKEND->cacert);
679 x509_crl_free(&BACKEND->crl);
680 ssl_free(&BACKEND->ssl);
681}
682
683static ssize_t polarssl_recv(struct connectdata *conn,
684 int num,
685 char *buf,
686 size_t buffersize,
687 CURLcode *curlcode)
688{
689 struct ssl_connect_data *connssl = &conn->ssl[num];
690 int ret = -1;
691 ssize_t len = -1;
692
693 memset(buf, 0, buffersize);
694 ret = ssl_read(&BACKEND->ssl, (unsigned char *)buf, buffersize);
695
696 if(ret <= 0) {
697 if(ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
698 return 0;
699
700 *curlcode = (ret == POLARSSL_ERR_NET_WANT_READ) ?
701 CURLE_AGAIN : CURLE_RECV_ERROR;
702 return -1;
703 }
704
705 len = ret;
706
707 return len;
708}
709
710static void Curl_polarssl_session_free(void *ptr)
711{
712 ssl_session_free(ptr);
713 free(ptr);
714}
715
716/* 1.3.10 was the first rebranded version. All new releases (in 1.3 branch and
717 higher) will be mbed TLS branded.. */
718
719static size_t Curl_polarssl_version(char *buffer, size_t size)
720{
721 unsigned int version = version_get_number();
722 return msnprintf(buffer, size, "%s/%d.%d.%d",
723 version >= 0x01030A00?"mbedTLS":"PolarSSL",
724 version>>24, (version>>16)&0xff, (version>>8)&0xff);
725}
726
727static CURLcode
728polarssl_connect_common(struct connectdata *conn,
729 int sockindex,
730 bool nonblocking,
731 bool *done)
732{
733 CURLcode result;
734 struct Curl_easy *data = conn->data;
735 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
736 curl_socket_t sockfd = conn->sock[sockindex];
737 timediff_t timeout_ms;
738 int what;
739
740 /* check if the connection has already been established */
741 if(ssl_connection_complete == connssl->state) {
742 *done = TRUE;
743 return CURLE_OK;
744 }
745
746 if(ssl_connect_1 == connssl->connecting_state) {
747 /* Find out how much more time we're allowed */
748 timeout_ms = Curl_timeleft(data, NULL, TRUE);
749
750 if(timeout_ms < 0) {
751 /* no need to continue if time already is up */
752 failf(data, "SSL connection timeout");
753 return CURLE_OPERATION_TIMEDOUT;
754 }
755
756 result = polarssl_connect_step1(conn, sockindex);
757 if(result)
758 return result;
759 }
760
761 while(ssl_connect_2 == connssl->connecting_state ||
762 ssl_connect_2_reading == connssl->connecting_state ||
763 ssl_connect_2_writing == connssl->connecting_state) {
764
765 /* check allowed time left */
766 timeout_ms = Curl_timeleft(data, NULL, TRUE);
767
768 if(timeout_ms < 0) {
769 /* no need to continue if time already is up */
770 failf(data, "SSL connection timeout");
771 return CURLE_OPERATION_TIMEDOUT;
772 }
773
774 /* if ssl is expecting something, check if it's available. */
775 if(connssl->connecting_state == ssl_connect_2_reading ||
776 connssl->connecting_state == ssl_connect_2_writing) {
777
778 curl_socket_t writefd = ssl_connect_2_writing ==
779 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
780 curl_socket_t readfd = ssl_connect_2_reading ==
781 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
782
783 what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
784 nonblocking?0:(time_t)timeout_ms);
785 if(what < 0) {
786 /* fatal error */
787 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
788 return CURLE_SSL_CONNECT_ERROR;
789 }
790 else if(0 == what) {
791 if(nonblocking) {
792 *done = FALSE;
793 return CURLE_OK;
794 }
795 else {
796 /* timeout */
797 failf(data, "SSL connection timeout");
798 return CURLE_OPERATION_TIMEDOUT;
799 }
800 }
801 /* socket is readable or writable */
802 }
803
804 /* Run transaction, and return to the caller if it failed or if
805 * this connection is part of a multi handle and this loop would
806 * execute again. This permits the owner of a multi handle to
807 * abort a connection attempt before step2 has completed while
808 * ensuring that a client using select() or epoll() will always
809 * have a valid fdset to wait on.
810 */
811 result = polarssl_connect_step2(conn, sockindex);
812 if(result || (nonblocking &&
813 (ssl_connect_2 == connssl->connecting_state ||
814 ssl_connect_2_reading == connssl->connecting_state ||
815 ssl_connect_2_writing == connssl->connecting_state)))
816 return result;
817
818 } /* repeat step2 until all transactions are done. */
819
820 if(ssl_connect_3 == connssl->connecting_state) {
821 result = polarssl_connect_step3(conn, sockindex);
822 if(result)
823 return result;
824 }
825
826 if(ssl_connect_done == connssl->connecting_state) {
827 connssl->state = ssl_connection_complete;
828 conn->recv[sockindex] = polarssl_recv;
829 conn->send[sockindex] = polarssl_send;
830 *done = TRUE;
831 }
832 else
833 *done = FALSE;
834
835 /* Reset our connect state machine */
836 connssl->connecting_state = ssl_connect_1;
837
838 return CURLE_OK;
839}
840
841static CURLcode Curl_polarssl_connect_nonblocking(struct connectdata *conn,
842 int sockindex, bool *done)
843{
844 return polarssl_connect_common(conn, sockindex, TRUE, done);
845}
846
847
848static CURLcode Curl_polarssl_connect(struct connectdata *conn, int sockindex)
849{
850 CURLcode result;
851 bool done = FALSE;
852
853 result = polarssl_connect_common(conn, sockindex, FALSE, &done);
854 if(result)
855 return result;
856
857 DEBUGASSERT(done);
858
859 return CURLE_OK;
860}
861
862/*
863 * return 0 error initializing SSL
864 * return 1 SSL initialized successfully
865 */
866static int Curl_polarssl_init(void)
867{
868 return Curl_polarsslthreadlock_thread_setup();
869}
870
871static void Curl_polarssl_cleanup(void)
872{
873 (void)Curl_polarsslthreadlock_thread_cleanup();
874}
875
876static bool Curl_polarssl_data_pending(const struct connectdata *conn,
877 int sockindex)
878{
879 const struct ssl_connect_data *connssl = &conn->ssl[sockindex];
880 return ssl_get_bytes_avail(&BACKEND->ssl) != 0;
881}
882
883static CURLcode Curl_polarssl_sha256sum(const unsigned char *input,
884 size_t inputlen,
885 unsigned char *sha256sum,
886 size_t sha256len UNUSED_PARAM)
887{
888 (void)sha256len;
889 sha256(input, inputlen, sha256sum, 0);
890 return CURLE_OK;
891}
892
893static void *Curl_polarssl_get_internals(struct ssl_connect_data *connssl,
894 CURLINFO info UNUSED_PARAM)
895{
896 (void)info;
897 return &BACKEND->ssl;
898}
899
900const struct Curl_ssl Curl_ssl_polarssl = {
901 { CURLSSLBACKEND_POLARSSL, "polarssl" }, /* info */
902
903 SSLSUPP_CA_PATH |
904 SSLSUPP_PINNEDPUBKEY,
905
906 sizeof(struct ssl_backend_data),
907
908 Curl_polarssl_init, /* init */
909 Curl_polarssl_cleanup, /* cleanup */
910 Curl_polarssl_version, /* version */
911 Curl_none_check_cxn, /* check_cxn */
912 Curl_none_shutdown, /* shutdown */
913 Curl_polarssl_data_pending, /* data_pending */
914 /* This might cause libcurl to use a weeker random! */
915 Curl_none_random, /* random */
916 Curl_none_cert_status_request, /* cert_status_request */
917 Curl_polarssl_connect, /* connect */
918 Curl_polarssl_connect_nonblocking, /* connect_nonblocking */
919 Curl_polarssl_get_internals, /* get_internals */
920 Curl_polarssl_close, /* close_one */
921 Curl_none_close_all, /* close_all */
922 Curl_polarssl_session_free, /* session_free */
923 Curl_none_set_engine, /* set_engine */
924 Curl_none_set_engine_default, /* set_engine_default */
925 Curl_none_engines_list, /* engines_list */
926 Curl_none_false_start, /* false_start */
927 Curl_none_md5sum, /* md5sum */
928 Curl_polarssl_sha256sum /* sha256sum */
929};
930
931#endif /* USE_POLARSSL */
932