1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
24 * Source file for all GnuTLS-specific code for the TLS/SSL layer. No code
25 * but sslgen.c should ever call or use these functions.
27 * Note: don't use the GnuTLS' *_t variable type names in this source code,
28 * since they were not present in 1.0.X.
31 #include "curl_setup.h"
35 #include <gnutls/gnutls.h>
36 #include <gnutls/x509.h>
38 #ifdef USE_GNUTLS_NETTLE
39 #include <gnutls/crypto.h>
40 #include <nettle/md5.h>
47 #include "inet_pton.h"
50 #include "parsedate.h"
51 #include "connect.h" /* for the connect timeout */
55 #define _MPRINTF_REPLACE /* use our functions only */
56 #include <curl/mprintf.h>
57 #include "curl_memory.h"
58 /* The last #include file should be: */
62 Some hackish cast macros based on:
63 http://library.gnome.org/devel/glib/unstable/glib-Type-Conversion-Macros.html
65 #ifndef GNUTLS_POINTER_TO_INT_CAST
66 #define GNUTLS_POINTER_TO_INT_CAST(p) ((int) (long) (p))
68 #ifndef GNUTLS_INT_TO_POINTER_CAST
69 #define GNUTLS_INT_TO_POINTER_CAST(i) ((void*) (long) (i))
72 /* Enable GnuTLS debugging by defining GTLSDEBUG */
73 /*#define GTLSDEBUG */
76 static void tls_log_func(int level, const char *str)
78 fprintf(stderr, "|<%d>| %s", level, str);
81 static bool gtls_inited = FALSE;
83 #if defined(GNUTLS_VERSION_NUMBER)
84 # if (GNUTLS_VERSION_NUMBER >= 0x020c00)
85 # undef gnutls_transport_set_lowat
86 # define gnutls_transport_set_lowat(A,B) Curl_nop_stmt
87 # define USE_GNUTLS_PRIORITY_SET_DIRECT 1
89 # if (GNUTLS_VERSION_NUMBER >= 0x020c03)
90 # define GNUTLS_MAPS_WINSOCK_ERRORS 1
95 * Custom push and pull callback functions used by GNU TLS to read and write
96 * to the socket. These functions are simple wrappers to send() and recv()
97 * (although here using the sread/swrite macros as defined by
99 * We use custom functions rather than the GNU TLS defaults because it allows
100 * us to get specific about the fourth "flags" argument, and to use arbitrary
101 * private data with gnutls_transport_set_ptr if we wish.
103 * When these custom push and pull callbacks fail, GNU TLS checks its own
104 * session-specific error variable, and when not set also its own global
105 * errno variable, in order to take appropriate action. GNU TLS does not
106 * require that the transport is actually a socket. This implies that for
107 * Windows builds these callbacks should ideally set the session-specific
108 * error variable using function gnutls_transport_set_errno or as a last
109 * resort global errno variable using gnutls_transport_set_global_errno,
110 * with a transport agnostic error value. This implies that some winsock
111 * error translation must take place in these callbacks.
113 * Paragraph above applies to GNU TLS versions older than 2.12.3, since
114 * this version GNU TLS does its own internal winsock error translation
115 * using system_errno() function.
118 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
119 # define gtls_EINTR 4
121 # define gtls_EAGAIN 11
122 static int gtls_mapped_sockerrno(void)
136 static ssize_t Curl_gtls_push(void *s, const void *buf, size_t len)
138 ssize_t ret = swrite(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
139 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
141 gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
146 static ssize_t Curl_gtls_pull(void *s, void *buf, size_t len)
148 ssize_t ret = sread(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
149 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
151 gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
158 * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that
159 * are not thread-safe and thus this function itself is not thread-safe and
160 * must only be called from within curl_global_init() to keep the thread
161 * situation under control!
163 int Curl_gtls_init(void)
167 ret = gnutls_global_init()?0:1;
169 gnutls_global_set_log_function(tls_log_func);
170 gnutls_global_set_log_level(2);
177 int Curl_gtls_cleanup(void)
180 gnutls_global_deinit();
186 static void showtime(struct SessionHandle *data,
191 const struct tm *tm = &buffer;
192 CURLcode result = Curl_gmtime(stamp, &buffer);
196 snprintf(data->state.buffer,
198 "\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT\n",
200 Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
202 Curl_month[tm->tm_mon],
207 infof(data, "%s\n", data->state.buffer);
210 static gnutls_datum load_file (const char *file)
213 gnutls_datum loaded_file = { NULL, 0 };
217 if(!(f = fopen(file, "r")))
219 if(fseek(f, 0, SEEK_END) != 0
220 || (filelen = ftell(f)) < 0
221 || fseek(f, 0, SEEK_SET) != 0
222 || !(ptr = malloc((size_t)filelen)))
224 if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) {
229 loaded_file.data = ptr;
230 loaded_file.size = (unsigned int)filelen;
236 static void unload_file(gnutls_datum data) {
241 /* this function does a SSL/TLS (re-)handshake */
242 static CURLcode handshake(struct connectdata *conn,
247 struct SessionHandle *data = conn->data;
248 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
249 gnutls_session session = conn->ssl[sockindex].session;
250 curl_socket_t sockfd = conn->sock[sockindex];
256 /* check allowed time left */
257 timeout_ms = Curl_timeleft(data, NULL, duringconnect);
260 /* no need to continue if time already is up */
261 failf(data, "SSL connection timeout");
262 return CURLE_OPERATION_TIMEDOUT;
265 /* if ssl is expecting something, check if it's available. */
266 if(connssl->connecting_state == ssl_connect_2_reading
267 || connssl->connecting_state == ssl_connect_2_writing) {
269 curl_socket_t writefd = ssl_connect_2_writing==
270 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
271 curl_socket_t readfd = ssl_connect_2_reading==
272 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
274 what = Curl_socket_ready(readfd, writefd,
276 timeout_ms?timeout_ms:1000);
279 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
280 return CURLE_SSL_CONNECT_ERROR;
285 else if(timeout_ms) {
287 failf(data, "SSL connection timeout at %ld", timeout_ms);
288 return CURLE_OPERATION_TIMEDOUT;
291 /* socket is readable or writable */
294 rc = gnutls_handshake(session);
296 if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
297 connssl->connecting_state =
298 gnutls_record_get_direction(session)?
299 ssl_connect_2_writing:ssl_connect_2_reading;
304 else if((rc < 0) && !gnutls_error_is_fatal(rc)) {
305 const char *strerr = NULL;
307 if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) {
308 int alert = gnutls_alert_get(session);
309 strerr = gnutls_alert_get_name(alert);
313 strerr = gnutls_strerror(rc);
315 failf(data, "gnutls_handshake() warning: %s", strerr);
318 const char *strerr = NULL;
320 if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) {
321 int alert = gnutls_alert_get(session);
322 strerr = gnutls_alert_get_name(alert);
326 strerr = gnutls_strerror(rc);
328 failf(data, "gnutls_handshake() failed: %s", strerr);
329 return CURLE_SSL_CONNECT_ERROR;
332 /* Reset our connect state machine */
333 connssl->connecting_state = ssl_connect_1;
338 static gnutls_x509_crt_fmt do_file_type(const char *type)
340 if(!type || !type[0])
341 return GNUTLS_X509_FMT_PEM;
342 if(Curl_raw_equal(type, "PEM"))
343 return GNUTLS_X509_FMT_PEM;
344 if(Curl_raw_equal(type, "DER"))
345 return GNUTLS_X509_FMT_DER;
350 gtls_connect_step1(struct connectdata *conn,
353 #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
354 static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
356 struct SessionHandle *data = conn->data;
357 gnutls_session session;
361 bool sni = TRUE; /* default is SNI enabled */
363 struct in6_addr addr;
368 if(conn->ssl[sockindex].state == ssl_connection_complete)
369 /* to make us tolerant against being called more than once for the
376 /* GnuTLS only supports SSLv3 and TLSv1 */
377 if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
378 failf(data, "GnuTLS does not support SSLv2");
379 return CURLE_SSL_CONNECT_ERROR;
381 else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
382 sni = FALSE; /* SSLv3 has no SNI */
384 /* allocate a cred struct */
385 rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
386 if(rc != GNUTLS_E_SUCCESS) {
387 failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
388 return CURLE_SSL_CONNECT_ERROR;
392 if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
393 infof(data, "Using TLS-SRP username: %s\n", data->set.ssl.username);
395 rc = gnutls_srp_allocate_client_credentials(
396 &conn->ssl[sockindex].srp_client_cred);
397 if(rc != GNUTLS_E_SUCCESS) {
398 failf(data, "gnutls_srp_allocate_client_cred() failed: %s",
399 gnutls_strerror(rc));
400 return CURLE_OUT_OF_MEMORY;
403 rc = gnutls_srp_set_client_credentials(conn->ssl[sockindex].
405 data->set.ssl.username,
406 data->set.ssl.password);
407 if(rc != GNUTLS_E_SUCCESS) {
408 failf(data, "gnutls_srp_set_client_cred() failed: %s",
409 gnutls_strerror(rc));
410 return CURLE_BAD_FUNCTION_ARGUMENT;
415 if(data->set.ssl.CAfile) {
416 /* set the trusted CA cert bundle file */
417 gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
418 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
420 rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
421 data->set.ssl.CAfile,
422 GNUTLS_X509_FMT_PEM);
424 infof(data, "error reading ca cert file %s (%s)\n",
425 data->set.ssl.CAfile, gnutls_strerror(rc));
426 if(data->set.ssl.verifypeer)
427 return CURLE_SSL_CACERT_BADFILE;
430 infof(data, "found %d certificates in %s\n",
431 rc, data->set.ssl.CAfile);
434 if(data->set.ssl.CRLfile) {
435 /* set the CRL list file */
436 rc = gnutls_certificate_set_x509_crl_file(conn->ssl[sockindex].cred,
437 data->set.ssl.CRLfile,
438 GNUTLS_X509_FMT_PEM);
440 failf(data, "error reading crl file %s (%s)",
441 data->set.ssl.CRLfile, gnutls_strerror(rc));
442 return CURLE_SSL_CRL_BADFILE;
445 infof(data, "found %d CRL in %s\n",
446 rc, data->set.ssl.CRLfile);
449 /* Initialize TLS session as a client */
450 rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
451 if(rc != GNUTLS_E_SUCCESS) {
452 failf(data, "gnutls_init() failed: %d", rc);
453 return CURLE_SSL_CONNECT_ERROR;
456 /* convenient assign */
457 session = conn->ssl[sockindex].session;
459 if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
461 (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
464 (gnutls_server_name_set(session, GNUTLS_NAME_DNS, conn->host.name,
465 strlen(conn->host.name)) < 0))
466 infof(data, "WARNING: failed to configure server name indication (SNI) "
469 /* Use default priorities */
470 rc = gnutls_set_default_priority(session);
471 if(rc != GNUTLS_E_SUCCESS)
472 return CURLE_SSL_CONNECT_ERROR;
474 if(data->set.ssl.version == CURL_SSLVERSION_SSLv3) {
475 #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
476 static const int protocol_priority[] = { GNUTLS_SSL3, 0 };
477 rc = gnutls_protocol_set_priority(session, protocol_priority);
480 /* the combination of the cipher ARCFOUR with SSL 3.0 and TLS 1.0 is not
481 vulnerable to attacks such as the BEAST, why this code now explicitly
484 rc = gnutls_priority_set_direct(session,
485 "NORMAL:-VERS-TLS-ALL:+VERS-SSL3.0:"
486 "-CIPHER-ALL:+ARCFOUR-128",
489 if(rc != GNUTLS_E_SUCCESS)
490 return CURLE_SSL_CONNECT_ERROR;
493 #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
494 /* Sets the priority on the certificate types supported by gnutls. Priority
495 is higher for types specified before others. After specifying the types
496 you want, you must append a 0. */
497 rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
498 if(rc != GNUTLS_E_SUCCESS)
499 return CURLE_SSL_CONNECT_ERROR;
502 if(data->set.str[STRING_CERT]) {
503 if(gnutls_certificate_set_x509_key_file(
504 conn->ssl[sockindex].cred,
505 data->set.str[STRING_CERT],
506 data->set.str[STRING_KEY] ?
507 data->set.str[STRING_KEY] : data->set.str[STRING_CERT],
508 do_file_type(data->set.str[STRING_CERT_TYPE]) ) !=
510 failf(data, "error reading X.509 key or certificate file");
511 return CURLE_SSL_CONNECT_ERROR;
516 /* put the credentials to the current session */
517 if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
518 rc = gnutls_credentials_set(session, GNUTLS_CRD_SRP,
519 conn->ssl[sockindex].srp_client_cred);
520 if(rc != GNUTLS_E_SUCCESS)
521 failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
525 rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
526 conn->ssl[sockindex].cred);
528 /* set the connection handle (file descriptor for the socket) */
529 gnutls_transport_set_ptr(session,
530 GNUTLS_INT_TO_POINTER_CAST(conn->sock[sockindex]));
532 /* register callback functions to send and receive data. */
533 gnutls_transport_set_push_function(session, Curl_gtls_push);
534 gnutls_transport_set_pull_function(session, Curl_gtls_pull);
536 /* lowat must be set to zero when using custom push and pull functions. */
537 gnutls_transport_set_lowat(session, 0);
539 /* This might be a reconnect, so we check for a session ID in the cache
540 to speed up things */
542 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
543 /* we got a session id, use it! */
544 gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);
546 /* Informational message */
547 infof (data, "SSL re-using session ID\n");
553 static Curl_recv gtls_recv;
554 static Curl_send gtls_send;
557 gtls_connect_step3(struct connectdata *conn,
560 unsigned int cert_list_size;
561 const gnutls_datum *chainp;
562 unsigned int verify_status;
563 gnutls_x509_crt x509_cert,x509_issuer;
564 gnutls_datum issuerp;
565 char certbuf[256]; /* big enough? */
571 struct SessionHandle *data = conn->data;
572 gnutls_session session = conn->ssl[sockindex].session;
576 CURLcode result = CURLE_OK;
578 /* This function will return the peer's raw certificate (chain) as sent by
579 the peer. These certificates are in raw format (DER encoded for
580 X.509). In case of a X.509 then a certificate list may be present. The
581 first certificate in the list is the peer's certificate, following the
582 issuer's certificate, then the issuer's issuer etc. */
584 chainp = gnutls_certificate_get_peers(session, &cert_list_size);
586 if(data->set.ssl.verifypeer ||
587 data->set.ssl.verifyhost ||
588 data->set.ssl.issuercert) {
590 if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
591 && data->set.ssl.username != NULL
592 && !data->set.ssl.verifypeer
593 && gnutls_cipher_get(session)) {
594 /* no peer cert, but auth is ok if we have SRP user and cipher and no
599 failf(data, "failed to get server cert");
600 return CURLE_PEER_FAILED_VERIFICATION;
605 infof(data, "\t common name: WARNING couldn't obtain\n");
608 if(data->set.ssl.verifypeer) {
609 /* This function will try to verify the peer's certificate and return its
610 status (trusted, invalid etc.). The value of status should be one or
611 more of the gnutls_certificate_status_t enumerated elements bitwise
612 or'd. To avoid denial of service attacks some default upper limits
613 regarding the certificate key size and chain size are set. To override
614 them use gnutls_certificate_set_verify_limits(). */
616 rc = gnutls_certificate_verify_peers2(session, &verify_status);
618 failf(data, "server cert verify failed: %d", rc);
619 return CURLE_SSL_CONNECT_ERROR;
622 /* verify_status is a bitmask of gnutls_certificate_status bits */
623 if(verify_status & GNUTLS_CERT_INVALID) {
624 if(data->set.ssl.verifypeer) {
625 failf(data, "server certificate verification failed. CAfile: %s "
626 "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
627 data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
628 return CURLE_SSL_CACERT;
631 infof(data, "\t server certificate verification FAILED\n");
634 infof(data, "\t server certificate verification OK\n");
637 infof(data, "\t server certificate verification SKIPPED\n");
638 goto after_server_cert_verification;
641 /* initialize an X.509 certificate structure. */
642 gnutls_x509_crt_init(&x509_cert);
644 /* convert the given DER or PEM encoded Certificate to the native
645 gnutls_x509_crt_t format */
646 gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
648 if(data->set.ssl.issuercert) {
649 gnutls_x509_crt_init(&x509_issuer);
650 issuerp = load_file(data->set.ssl.issuercert);
651 gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
652 rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
653 unload_file(issuerp);
655 failf(data, "server certificate issuer check failed (IssuerCert: %s)",
656 data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
657 return CURLE_SSL_ISSUER_ERROR;
659 infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
660 data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
663 size=sizeof(certbuf);
664 rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
665 0, /* the first and only one */
670 infof(data, "error fetching CN from cert:%s\n",
671 gnutls_strerror(rc));
674 /* This function will check if the given certificate's subject matches the
675 given hostname. This is a basic implementation of the matching described
676 in RFC2818 (HTTPS), which takes into account wildcards, and the subject
677 alternative name PKIX extension. Returns non zero on success, and zero on
679 rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
682 if(data->set.ssl.verifyhost) {
683 failf(data, "SSL: certificate subject name (%s) does not match "
684 "target host name '%s'", certbuf, conn->host.dispname);
685 gnutls_x509_crt_deinit(x509_cert);
686 return CURLE_PEER_FAILED_VERIFICATION;
689 infof(data, "\t common name: %s (does not match '%s')\n",
690 certbuf, conn->host.dispname);
693 infof(data, "\t common name: %s (matched)\n", certbuf);
695 /* Check for time-based validity */
696 certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
698 if(certclock == (time_t)-1) {
699 failf(data, "server cert expiration date verify failed");
700 return CURLE_SSL_CONNECT_ERROR;
703 if(certclock < time(NULL)) {
704 if(data->set.ssl.verifypeer) {
705 failf(data, "server certificate expiration date has passed.");
706 return CURLE_PEER_FAILED_VERIFICATION;
709 infof(data, "\t server certificate expiration date FAILED\n");
712 infof(data, "\t server certificate expiration date OK\n");
714 certclock = gnutls_x509_crt_get_activation_time(x509_cert);
716 if(certclock == (time_t)-1) {
717 failf(data, "server cert activation date verify failed");
718 return CURLE_SSL_CONNECT_ERROR;
721 if(certclock > time(NULL)) {
722 if(data->set.ssl.verifypeer) {
723 failf(data, "server certificate not activated yet.");
724 return CURLE_PEER_FAILED_VERIFICATION;
727 infof(data, "\t server certificate activation date FAILED\n");
730 infof(data, "\t server certificate activation date OK\n");
743 /* public key algorithm's parameters */
744 algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
745 infof(data, "\t certificate public key: %s\n",
746 gnutls_pk_algorithm_get_name(algo));
748 /* version of the X.509 certificate. */
749 infof(data, "\t certificate version: #%d\n",
750 gnutls_x509_crt_get_version(x509_cert));
753 size = sizeof(certbuf);
754 gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
755 infof(data, "\t subject: %s\n", certbuf);
757 certclock = gnutls_x509_crt_get_activation_time(x509_cert);
758 showtime(data, "start date", certclock);
760 certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
761 showtime(data, "expire date", certclock);
763 size = sizeof(certbuf);
764 gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
765 infof(data, "\t issuer: %s\n", certbuf);
767 gnutls_x509_crt_deinit(x509_cert);
769 after_server_cert_verification:
771 /* compression algorithm (if any) */
772 ptr = gnutls_compression_get_name(gnutls_compression_get(session));
773 /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
774 infof(data, "\t compression: %s\n", ptr);
776 /* the name of the cipher used. ie 3DES. */
777 ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
778 infof(data, "\t cipher: %s\n", ptr);
780 /* the MAC algorithms name. ie SHA1 */
781 ptr = gnutls_mac_get_name(gnutls_mac_get(session));
782 infof(data, "\t MAC: %s\n", ptr);
784 conn->ssl[sockindex].state = ssl_connection_complete;
785 conn->recv[sockindex] = gtls_recv;
786 conn->send[sockindex] = gtls_send;
789 /* we always unconditionally get the session id here, as even if we
790 already got it from the cache and asked to use it in the connection, it
791 might've been rejected and then a new one is in use now and we need to
793 void *connect_sessionid;
794 size_t connect_idsize;
796 /* get the session ID data size */
797 gnutls_session_get_data(session, NULL, &connect_idsize);
798 connect_sessionid = malloc(connect_idsize); /* get a buffer for it */
800 if(connect_sessionid) {
801 /* extract session ID to the allocated buffer */
802 gnutls_session_get_data(session, connect_sessionid, &connect_idsize);
804 incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
806 /* there was one before in the cache, so instead of risking that the
807 previous one was rejected, we just kill that and store the new */
808 Curl_ssl_delsessionid(conn, ssl_sessionid);
811 /* store this session id */
812 result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
814 free(connect_sessionid);
815 result = CURLE_OUT_OF_MEMORY;
819 result = CURLE_OUT_OF_MEMORY;
827 * This function is called after the TCP connect has completed. Setup the TLS
828 * layer and do all necessary magic.
830 /* We use connssl->connecting_state to keep track of the connection status;
831 there are three states: 'ssl_connect_1' (not started yet or complete),
832 'ssl_connect_2_reading' (waiting for data from server), and
833 'ssl_connect_2_writing' (waiting to be able to write).
836 gtls_connect_common(struct connectdata *conn,
842 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
844 /* Initiate the connection, if not already done */
845 if(ssl_connect_1==connssl->connecting_state) {
846 rc = gtls_connect_step1 (conn, sockindex);
851 rc = handshake(conn, sockindex, TRUE, nonblocking);
853 /* handshake() sets its own error message with failf() */
856 /* Finish connecting once the handshake is done */
857 if(ssl_connect_1==connssl->connecting_state) {
858 rc = gtls_connect_step3(conn, sockindex);
863 *done = ssl_connect_1==connssl->connecting_state;
869 Curl_gtls_connect_nonblocking(struct connectdata *conn,
873 return gtls_connect_common(conn, sockindex, TRUE, done);
877 Curl_gtls_connect(struct connectdata *conn,
884 retcode = gtls_connect_common(conn, sockindex, FALSE, &done);
893 static ssize_t gtls_send(struct connectdata *conn,
899 ssize_t rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
902 *curlcode = (rc == GNUTLS_E_AGAIN)
912 void Curl_gtls_close_all(struct SessionHandle *data)
914 /* FIX: make the OpenSSL code more generic and use parts of it here */
918 static void close_one(struct connectdata *conn,
921 if(conn->ssl[idx].session) {
922 gnutls_bye(conn->ssl[idx].session, GNUTLS_SHUT_RDWR);
923 gnutls_deinit(conn->ssl[idx].session);
924 conn->ssl[idx].session = NULL;
926 if(conn->ssl[idx].cred) {
927 gnutls_certificate_free_credentials(conn->ssl[idx].cred);
928 conn->ssl[idx].cred = NULL;
931 if(conn->ssl[idx].srp_client_cred) {
932 gnutls_srp_free_client_credentials(conn->ssl[idx].srp_client_cred);
933 conn->ssl[idx].srp_client_cred = NULL;
938 void Curl_gtls_close(struct connectdata *conn, int sockindex)
940 close_one(conn, sockindex);
944 * This function is called to shut down the SSL layer but keep the
945 * socket open (CCC - Clear Command Channel)
947 int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
951 struct SessionHandle *data = conn->data;
955 /* This has only been tested on the proftpd server, and the mod_tls code
956 sends a close notify alert without waiting for a close notify alert in
957 response. Thus we wait for a close notify alert from the server, but
958 we do not send one. Let's hope other servers do the same... */
960 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
961 gnutls_bye(conn->ssl[sockindex].session, GNUTLS_SHUT_WR);
963 if(conn->ssl[sockindex].session) {
965 int what = Curl_socket_ready(conn->sock[sockindex],
966 CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
968 /* Something to read, let's do it and hope that it is the close
969 notify alert from the server */
970 result = gnutls_record_recv(conn->ssl[sockindex].session,
974 /* This is the expected response. There was no data but only
975 the close notify alert */
979 case GNUTLS_E_INTERRUPTED:
980 infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED\n");
990 failf(data, "SSL shutdown timeout");
995 /* anything that gets here is fatally bad */
996 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1001 gnutls_deinit(conn->ssl[sockindex].session);
1003 gnutls_certificate_free_credentials(conn->ssl[sockindex].cred);
1006 if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
1007 && data->set.ssl.username != NULL)
1008 gnutls_srp_free_client_credentials(conn->ssl[sockindex].srp_client_cred);
1011 conn->ssl[sockindex].cred = NULL;
1012 conn->ssl[sockindex].session = NULL;
1017 static ssize_t gtls_recv(struct connectdata *conn, /* connection data */
1018 int num, /* socketindex */
1019 char *buf, /* store read data here */
1020 size_t buffersize, /* max amount to read */
1025 ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
1026 if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
1027 *curlcode = CURLE_AGAIN;
1031 if(ret == GNUTLS_E_REHANDSHAKE) {
1032 /* BLOCKING call, this is bad but a work-around for now. Fixing this "the
1033 proper way" takes a whole lot of work. */
1034 CURLcode rc = handshake(conn, num, FALSE, FALSE);
1036 /* handshake() writes error message on its own */
1039 *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
1044 failf(conn->data, "GnuTLS recv error (%d): %s",
1045 (int)ret, gnutls_strerror((int)ret));
1046 *curlcode = CURLE_RECV_ERROR;
1053 void Curl_gtls_session_free(void *ptr)
1058 size_t Curl_gtls_version(char *buffer, size_t size)
1060 return snprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
1063 int Curl_gtls_seed(struct SessionHandle *data)
1065 /* we have the "SSL is seeded" boolean static to prevent multiple
1066 time-consuming seedings in vain */
1067 static bool ssl_seeded = FALSE;
1069 /* Quickly add a bit of entropy */
1070 #ifndef USE_GNUTLS_NETTLE
1071 gcry_fast_random_poll();
1074 if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
1075 data->set.str[STRING_SSL_EGDSOCKET]) {
1077 /* TODO: to a good job seeding the RNG
1078 This may involve the gcry_control function and these options:
1079 GCRYCTL_SET_RANDOM_SEED_FILE
1080 GCRYCTL_SET_RNDEGD_SOCKET
1087 void Curl_gtls_random(struct SessionHandle *data,
1088 unsigned char *entropy,
1091 #if defined(USE_GNUTLS_NETTLE)
1093 gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length);
1094 #elif defined(USE_GNUTLS)
1095 Curl_gtls_seed(data); /* Initiate the seed if not already done */
1096 gcry_randomize(entropy, length, GCRY_STRONG_RANDOM);
1100 void Curl_gtls_md5sum(unsigned char *tmp, /* input */
1102 unsigned char *md5sum, /* output */
1105 #if defined(USE_GNUTLS_NETTLE)
1106 struct md5_ctx MD5pw;
1108 md5_update(&MD5pw, tmplen, tmp);
1109 md5_digest(&MD5pw, md5len, md5sum);
1110 #elif defined(USE_GNUTLS)
1112 gcry_md_open(&MD5pw, GCRY_MD_MD5, 0);
1113 gcry_md_write(MD5pw, tmp, tmplen);
1114 memcpy(md5sum, gcry_md_read (MD5pw, 0), md5len);
1115 gcry_md_close(MD5pw);
1119 #endif /* USE_GNUTLS */