1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com>
9 * Copyright (C) 2012 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
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 http://curl.haxx.se/docs/copyright.html.
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.
19 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20 * KIND, either express or implied.
22 ***************************************************************************/
25 * Source file for all PolarSSL-specific code for the TLS/SSL layer. No code
26 * but sslgen.c should ever call or use these functions.
30 #include "curl_setup.h"
34 #include <polarssl/net.h>
35 #include <polarssl/ssl.h>
36 #include <polarssl/certs.h>
37 #include <polarssl/x509.h>
38 #include <polarssl/version.h>
40 #if POLARSSL_VERSION_NUMBER >= 0x01000000
41 #include <polarssl/error.h>
42 #endif /* POLARSSL_VERSION_NUMBER >= 0x01000000 */
44 #if POLARSSL_VERSION_NUMBER>0x01010000
45 #include <polarssl/entropy.h>
46 #include <polarssl/ctr_drbg.h>
48 #include <polarssl/havege.h>
49 #endif /* POLARSSL_VERSION_NUMBER>0x01010000 */
52 #if POLARSSL_VERSION_NUMBER<0x01000000
54 Earlier versions of polarssl had no WANT_READ or WANT_WRITE, only TRY_AGAIN
56 #define POLARSSL_ERR_NET_WANT_READ POLARSSL_ERR_NET_TRY_AGAIN
57 #define POLARSSL_ERR_NET_WANT_WRITE POLARSSL_ERR_NET_TRY_AGAIN
62 #include "inet_pton.h"
65 #include "parsedate.h"
66 #include "connect.h" /* for the connect timeout */
69 #include "polarssl_threadlock.h"
71 #define _MPRINTF_REPLACE /* use our functions only */
72 #include <curl/mprintf.h>
73 #include "curl_memory.h"
74 /* The last #include file should be: */
77 /* apply threading? */
78 #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
79 #define THREADING_SUPPORT
82 #if defined(THREADING_SUPPORT) && POLARSSL_VERSION_NUMBER>0x01010000
83 static entropy_context entropy;
85 static int entropy_init_initialized = 0;
87 /* start of entropy_init_mutex() */
88 static void entropy_init_mutex(entropy_context *ctx)
90 /* lock 0 = entropy_init_mutex() */
91 polarsslthreadlock_lock_function(0);
92 if(entropy_init_initialized == 0) {
94 entropy_init_initialized = 1;
96 polarsslthreadlock_unlock_function(0);
98 /* end of entropy_init_mutex() */
100 /* start of entropy_func_mutex() */
101 static int entropy_func_mutex(void *data, unsigned char *output, size_t len)
104 /* lock 1 = entropy_func_mutex() */
105 polarsslthreadlock_lock_function(1);
106 ret = entropy_func(data, output, len);
107 polarsslthreadlock_unlock_function(1);
111 /* end of entropy_func_mutex() */
113 #endif /* THREADING_SUPPORT && POLARSSL_VERSION_NUMBER>0x01010000 */
115 /* Define this to enable lots of debugging for PolarSSL */
116 #undef POLARSSL_DEBUG
118 #ifdef POLARSSL_DEBUG
119 static void polarssl_debug(void *context, int level, char *line)
121 struct SessionHandle *data = NULL;
126 data = (struct SessionHandle *)context;
128 infof(data, "%s\n", line);
133 static Curl_recv polarssl_recv;
134 static Curl_send polarssl_send;
138 polarssl_connect_step1(struct connectdata *conn,
141 struct SessionHandle *data = conn->data;
142 struct ssl_connect_data* connssl = &conn->ssl[sockindex];
144 bool sni = TRUE; /* default is SNI enabled */
147 struct in6_addr addr;
151 void *old_session = NULL;
152 size_t old_session_size = 0;
155 memset(errorbuf, 0, sizeof(errorbuf));
158 /* PolarSSL only supports SSLv3 and TLSv1 */
159 if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
160 failf(data, "PolarSSL does not support SSLv2");
161 return CURLE_SSL_CONNECT_ERROR;
163 else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
164 sni = FALSE; /* SSLv3 has no SNI */
166 #if POLARSSL_VERSION_NUMBER<0x01010000
167 havege_init(&connssl->hs);
169 #ifdef THREADING_SUPPORT
170 entropy_init_mutex(&entropy);
172 if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func_mutex, &entropy,
173 connssl->ssn.id, connssl->ssn.length)) != 0) {
174 #ifdef POLARSSL_ERROR_C
175 error_strerror(ret, errorbuf, sizeof(errorbuf));
176 #endif /* POLARSSL_ERROR_C */
177 failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
181 entropy_init(&connssl->entropy);
183 if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func, &connssl->entropy,
184 connssl->ssn.id, connssl->ssn.length)) != 0) {
185 #ifdef POLARSSL_ERROR_C
186 error_strerror(ret, errorbuf, sizeof(errorbuf));
187 #endif /* POLARSSL_ERROR_C */
188 failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
191 #endif /* THREADING_SUPPORT */
192 #endif /* POLARSSL_VERSION_NUMBER<0x01010000 */
194 /* Load the trusted CA */
195 memset(&connssl->cacert, 0, sizeof(x509_cert));
197 if(data->set.str[STRING_SSL_CAFILE]) {
198 ret = x509parse_crtfile(&connssl->cacert,
199 data->set.str[STRING_SSL_CAFILE]);
202 #ifdef POLARSSL_ERROR_C
203 error_strerror(ret, errorbuf, sizeof(errorbuf));
204 #endif /* POLARSSL_ERROR_C */
205 failf(data, "Error reading ca cert file %s - PolarSSL: (-0x%04X) %s",
206 data->set.str[STRING_SSL_CAFILE], -ret, errorbuf);
208 if(data->set.ssl.verifypeer)
209 return CURLE_SSL_CACERT_BADFILE;
213 /* Load the client certificate */
214 memset(&connssl->clicert, 0, sizeof(x509_cert));
216 if(data->set.str[STRING_CERT]) {
217 ret = x509parse_crtfile(&connssl->clicert,
218 data->set.str[STRING_CERT]);
221 #ifdef POLARSSL_ERROR_C
222 error_strerror(ret, errorbuf, sizeof(errorbuf));
223 #endif /* POLARSSL_ERROR_C */
224 failf(data, "Error reading client cert file %s - PolarSSL: (-0x%04X) %s",
225 data->set.str[STRING_CERT], -ret, errorbuf);
227 return CURLE_SSL_CERTPROBLEM;
231 /* Load the client private key */
232 if(data->set.str[STRING_KEY]) {
233 ret = x509parse_keyfile(&connssl->rsa,
234 data->set.str[STRING_KEY],
235 data->set.str[STRING_KEY_PASSWD]);
238 #ifdef POLARSSL_ERROR_C
239 error_strerror(ret, errorbuf, sizeof(errorbuf));
240 #endif /* POLARSSL_ERROR_C */
241 failf(data, "Error reading private key %s - PolarSSL: (-0x%04X) %s",
242 data->set.str[STRING_KEY], -ret, errorbuf);
244 return CURLE_SSL_CERTPROBLEM;
249 memset(&connssl->crl, 0, sizeof(x509_crl));
251 if(data->set.str[STRING_SSL_CRLFILE]) {
252 ret = x509parse_crlfile(&connssl->crl,
253 data->set.str[STRING_SSL_CRLFILE]);
256 #ifdef POLARSSL_ERROR_C
257 error_strerror(ret, errorbuf, sizeof(errorbuf));
258 #endif /* POLARSSL_ERROR_C */
259 failf(data, "Error reading CRL file %s - PolarSSL: (-0x%04X) %s",
260 data->set.str[STRING_SSL_CRLFILE], -ret, errorbuf);
262 return CURLE_SSL_CRL_BADFILE;
266 infof(data, "PolarSSL: Connecting to %s:%d\n",
267 conn->host.name, conn->remote_port);
269 if(ssl_init(&connssl->ssl)) {
270 failf(data, "PolarSSL: ssl_init failed");
271 return CURLE_SSL_CONNECT_ERROR;
274 ssl_set_endpoint(&connssl->ssl, SSL_IS_CLIENT);
275 ssl_set_authmode(&connssl->ssl, SSL_VERIFY_OPTIONAL);
277 #if POLARSSL_VERSION_NUMBER<0x01010000
278 ssl_set_rng(&connssl->ssl, havege_rand,
281 ssl_set_rng(&connssl->ssl, ctr_drbg_random,
283 #endif /* POLARSSL_VERSION_NUMBER<0x01010000 */
284 ssl_set_bio(&connssl->ssl,
285 net_recv, &conn->sock[sockindex],
286 net_send, &conn->sock[sockindex]);
289 #if POLARSSL_VERSION_NUMBER<0x01000000
290 ssl_set_ciphers(&connssl->ssl, ssl_default_ciphers);
292 ssl_set_ciphersuites(&connssl->ssl, ssl_default_ciphersuites);
294 if(!Curl_ssl_getsessionid(conn, &old_session, &old_session_size)) {
295 memcpy(&connssl->ssn, old_session, old_session_size);
296 infof(data, "PolarSSL re-using session\n");
299 /* PolarSSL SVN revision r1316 to r1317, matching <1.2.0 is to cover Ubuntu's
300 1.1.4 version and the like */
301 #if POLARSSL_VERSION_NUMBER<0x01020000
302 ssl_set_session(&connssl->ssl, 1, 600,
305 ssl_set_session(&connssl->ssl,
309 ssl_set_ca_chain(&connssl->ssl,
314 ssl_set_own_cert(&connssl->ssl,
315 &connssl->clicert, &connssl->rsa);
317 if(!Curl_inet_pton(AF_INET, conn->host.name, &addr) &&
319 !Curl_inet_pton(AF_INET6, conn->host.name, &addr) &&
321 sni && ssl_set_hostname(&connssl->ssl, conn->host.name)) {
322 infof(data, "WARNING: failed to configure "
323 "server name indication (SNI) TLS extension\n");
326 #ifdef POLARSSL_DEBUG
327 ssl_set_dbg(&connssl->ssl, polarssl_debug, data);
330 connssl->connecting_state = ssl_connect_2;
336 polarssl_connect_step2(struct connectdata *conn,
340 struct SessionHandle *data = conn->data;
341 struct ssl_connect_data* connssl = &conn->ssl[sockindex];
345 memset(errorbuf, 0, sizeof(errorbuf));
347 conn->recv[sockindex] = polarssl_recv;
348 conn->send[sockindex] = polarssl_send;
351 if(!(ret = ssl_handshake(&connssl->ssl)))
353 else if(ret != POLARSSL_ERR_NET_WANT_READ &&
354 ret != POLARSSL_ERR_NET_WANT_WRITE) {
355 #ifdef POLARSSL_ERROR_C
356 error_strerror(ret, errorbuf, sizeof(errorbuf));
357 #endif /* POLARSSL_ERROR_C */
358 failf(data, "ssl_handshake returned - PolarSSL: (-0x%04X) %s",
361 return CURLE_SSL_CONNECT_ERROR;
364 if(ret == POLARSSL_ERR_NET_WANT_READ) {
365 connssl->connecting_state = ssl_connect_2_reading;
368 if(ret == POLARSSL_ERR_NET_WANT_WRITE) {
369 connssl->connecting_state = ssl_connect_2_writing;
372 failf(data, "SSL_connect failed with error %d.", ret);
373 return CURLE_SSL_CONNECT_ERROR;
378 infof(data, "PolarSSL: Handshake complete, cipher is %s\n",
379 #if POLARSSL_VERSION_NUMBER<0x01000000
380 ssl_get_cipher(&conn->ssl[sockindex].ssl)
381 #elif POLARSSL_VERSION_NUMBER >= 0x01010000
382 ssl_get_ciphersuite(&conn->ssl[sockindex].ssl)
384 ssl_get_ciphersuite_name(&conn->ssl[sockindex].ssl)
388 ret = ssl_get_verify_result(&conn->ssl[sockindex].ssl);
390 if(ret && data->set.ssl.verifypeer) {
391 if(ret & BADCERT_EXPIRED)
392 failf(data, "Cert verify failed: BADCERT_EXPIRED");
394 if(ret & BADCERT_REVOKED) {
395 failf(data, "Cert verify failed: BADCERT_REVOKED");
396 return CURLE_SSL_CACERT;
399 if(ret & BADCERT_CN_MISMATCH)
400 failf(data, "Cert verify failed: BADCERT_CN_MISMATCH");
402 if(ret & BADCERT_NOT_TRUSTED)
403 failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED");
405 return CURLE_PEER_FAILED_VERIFICATION;
408 /* PolarSSL SVN revision r1316 to r1317, matching <1.2.0 is to cover Ubuntu's
409 1.1.4 version and the like */
410 #if POLARSSL_VERSION_NUMBER<0x01020000
411 if(conn->ssl[sockindex].ssl.peer_cert) {
413 if(ssl_get_peer_cert(&(connssl->ssl))) {
415 /* If the session was resumed, there will be no peer certs */
416 memset(buffer, 0, sizeof(buffer));
418 /* PolarSSL SVN revision r1316 to r1317, matching <1.2.0 is to cover Ubuntu's
419 1.1.4 version and the like */
420 #if POLARSSL_VERSION_NUMBER<0x01020000
421 if(x509parse_cert_info(buffer, sizeof(buffer), (char *)"* ",
422 conn->ssl[sockindex].ssl.peer_cert) != -1)
424 if(x509parse_cert_info(buffer, sizeof(buffer), (char *)"* ",
425 ssl_get_peer_cert(&(connssl->ssl))) != -1)
427 infof(data, "Dumping cert info:\n%s\n", buffer);
430 connssl->connecting_state = ssl_connect_3;
431 infof(data, "SSL connected\n");
437 polarssl_connect_step3(struct connectdata *conn,
440 CURLcode retcode = CURLE_OK;
441 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
442 struct SessionHandle *data = conn->data;
443 void *old_ssl_sessionid = NULL;
444 ssl_session *our_ssl_sessionid = &conn->ssl[sockindex].ssn ;
447 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
449 /* Save the current session data for possible re-use */
450 incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL));
452 if(old_ssl_sessionid != our_ssl_sessionid) {
453 infof(data, "old SSL session ID is stale, removing\n");
454 Curl_ssl_delsessionid(conn, old_ssl_sessionid);
459 void *new_session = malloc(sizeof(ssl_session));
462 memcpy(new_session, our_ssl_sessionid,
463 sizeof(ssl_session));
465 retcode = Curl_ssl_addsessionid(conn, new_session,
466 sizeof(ssl_session));
469 retcode = CURLE_OUT_OF_MEMORY;
473 failf(data, "failed to store ssl session");
478 connssl->connecting_state = ssl_connect_done;
483 static ssize_t polarssl_send(struct connectdata *conn,
491 ret = ssl_write(&conn->ssl[sockindex].ssl,
492 (unsigned char *)mem, len);
495 *curlcode = (ret == POLARSSL_ERR_NET_WANT_WRITE) ?
496 CURLE_AGAIN : CURLE_SEND_ERROR;
503 void Curl_polarssl_close_all(struct SessionHandle *data)
508 void Curl_polarssl_close(struct connectdata *conn, int sockindex)
510 rsa_free(&conn->ssl[sockindex].rsa);
511 x509_free(&conn->ssl[sockindex].clicert);
512 x509_free(&conn->ssl[sockindex].cacert);
513 x509_crl_free(&conn->ssl[sockindex].crl);
514 ssl_free(&conn->ssl[sockindex].ssl);
517 static ssize_t polarssl_recv(struct connectdata *conn,
526 memset(buf, 0, buffersize);
527 ret = ssl_read(&conn->ssl[num].ssl, (unsigned char *)buf, buffersize);
530 if(ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
533 *curlcode = (ret == POLARSSL_ERR_NET_WANT_READ) ?
534 CURLE_AGAIN : CURLE_RECV_ERROR;
543 void Curl_polarssl_session_free(void *ptr)
548 size_t Curl_polarssl_version(char *buffer, size_t size)
550 unsigned int version = version_get_number();
551 return snprintf(buffer, size, "PolarSSL/%d.%d.%d", version>>24,
552 (version>>16)&0xff, (version>>8)&0xff);
556 polarssl_connect_common(struct connectdata *conn,
562 struct SessionHandle *data = conn->data;
563 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
564 curl_socket_t sockfd = conn->sock[sockindex];
568 /* check if the connection has already been established */
569 if(ssl_connection_complete == connssl->state) {
574 if(ssl_connect_1==connssl->connecting_state) {
575 /* Find out how much more time we're allowed */
576 timeout_ms = Curl_timeleft(data, NULL, TRUE);
579 /* no need to continue if time already is up */
580 failf(data, "SSL connection timeout");
581 return CURLE_OPERATION_TIMEDOUT;
583 retcode = polarssl_connect_step1(conn, sockindex);
588 while(ssl_connect_2 == connssl->connecting_state ||
589 ssl_connect_2_reading == connssl->connecting_state ||
590 ssl_connect_2_writing == connssl->connecting_state) {
592 /* check allowed time left */
593 timeout_ms = Curl_timeleft(data, NULL, TRUE);
596 /* no need to continue if time already is up */
597 failf(data, "SSL connection timeout");
598 return CURLE_OPERATION_TIMEDOUT;
601 /* if ssl is expecting something, check if it's available. */
602 if(connssl->connecting_state == ssl_connect_2_reading
603 || connssl->connecting_state == ssl_connect_2_writing) {
605 curl_socket_t writefd = ssl_connect_2_writing==
606 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
607 curl_socket_t readfd = ssl_connect_2_reading==
608 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
610 what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms);
613 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
614 return CURLE_SSL_CONNECT_ERROR;
623 failf(data, "SSL connection timeout");
624 return CURLE_OPERATION_TIMEDOUT;
627 /* socket is readable or writable */
630 /* Run transaction, and return to the caller if it failed or if
631 * this connection is part of a multi handle and this loop would
632 * execute again. This permits the owner of a multi handle to
633 * abort a connection attempt before step2 has completed while
634 * ensuring that a client using select() or epoll() will always
635 * have a valid fdset to wait on.
637 retcode = polarssl_connect_step2(conn, sockindex);
638 if(retcode || (nonblocking &&
639 (ssl_connect_2 == connssl->connecting_state ||
640 ssl_connect_2_reading == connssl->connecting_state ||
641 ssl_connect_2_writing == connssl->connecting_state)))
644 } /* repeat step2 until all transactions are done. */
646 if(ssl_connect_3==connssl->connecting_state) {
647 retcode = polarssl_connect_step3(conn, sockindex);
652 if(ssl_connect_done==connssl->connecting_state) {
653 connssl->state = ssl_connection_complete;
654 conn->recv[sockindex] = polarssl_recv;
655 conn->send[sockindex] = polarssl_send;
661 /* Reset our connect state machine */
662 connssl->connecting_state = ssl_connect_1;
668 Curl_polarssl_connect_nonblocking(struct connectdata *conn,
672 return polarssl_connect_common(conn, sockindex, TRUE, done);
677 Curl_polarssl_connect(struct connectdata *conn,
683 retcode = polarssl_connect_common(conn, sockindex, FALSE, &done);
693 * return 0 error initializing SSL
694 * return 1 SSL initialized successfully
696 int polarssl_init(void)
698 return polarsslthreadlock_thread_setup();
701 void polarssl_cleanup(void)
703 (void)polarsslthreadlock_thread_cleanup();
706 #endif /* USE_POLARSSL */