gnutls: don't use deprecated type names anymore
[platform/upstream/curl.git] / lib / vtls / gtls.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
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.
13  *
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.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 /*
24  * Source file for all GnuTLS-specific code for the TLS/SSL layer. No code
25  * but vtls.c should ever call or use these functions.
26  *
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.
29  */
30
31 #include "curl_setup.h"
32
33 #ifdef USE_GNUTLS
34
35 #include <gnutls/gnutls.h>
36 #include <gnutls/x509.h>
37
38 #ifdef USE_GNUTLS_NETTLE
39 #include <gnutls/crypto.h>
40 #include <nettle/md5.h>
41 #else
42 #include <gcrypt.h>
43 #endif
44
45 #include "urldata.h"
46 #include "sendf.h"
47 #include "inet_pton.h"
48 #include "gtls.h"
49 #include "vtls.h"
50 #include "parsedate.h"
51 #include "connect.h" /* for the connect timeout */
52 #include "select.h"
53 #include "rawstr.h"
54
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: */
59 #include "memdebug.h"
60
61 /*
62  Some hackish cast macros based on:
63  http://library.gnome.org/devel/glib/unstable/glib-Type-Conversion-Macros.html
64 */
65 #ifndef GNUTLS_POINTER_TO_INT_CAST
66 #define GNUTLS_POINTER_TO_INT_CAST(p) ((int) (long) (p))
67 #endif
68 #ifndef GNUTLS_INT_TO_POINTER_CAST
69 #define GNUTLS_INT_TO_POINTER_CAST(i) ((void*) (long) (i))
70 #endif
71
72 /* Enable GnuTLS debugging by defining GTLSDEBUG */
73 /*#define GTLSDEBUG */
74
75 #ifdef GTLSDEBUG
76 static void tls_log_func(int level, const char *str)
77 {
78     fprintf(stderr, "|<%d>| %s", level, str);
79 }
80 #endif
81 static bool gtls_inited = FALSE;
82
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
88 #  endif
89 #  if (GNUTLS_VERSION_NUMBER >= 0x020c03)
90 #    define GNUTLS_MAPS_WINSOCK_ERRORS 1
91 #  endif
92
93 #  ifdef USE_NGHTTP2
94 #    undef HAS_ALPN
95 #    if (GNUTLS_VERSION_NUMBER >= 0x030200)
96 #      define HAS_ALPN
97 #    else
98 #      error http2 builds require GnuTLS >= 3.2.0 for ALPN support
99 #    endif
100 #  endif
101 #endif
102
103 /*
104  * Custom push and pull callback functions used by GNU TLS to read and write
105  * to the socket.  These functions are simple wrappers to send() and recv()
106  * (although here using the sread/swrite macros as defined by
107  * curl_setup_once.h).
108  * We use custom functions rather than the GNU TLS defaults because it allows
109  * us to get specific about the fourth "flags" argument, and to use arbitrary
110  * private data with gnutls_transport_set_ptr if we wish.
111  *
112  * When these custom push and pull callbacks fail, GNU TLS checks its own
113  * session-specific error variable, and when not set also its own global
114  * errno variable, in order to take appropriate action. GNU TLS does not
115  * require that the transport is actually a socket. This implies that for
116  * Windows builds these callbacks should ideally set the session-specific
117  * error variable using function gnutls_transport_set_errno or as a last
118  * resort global errno variable using gnutls_transport_set_global_errno,
119  * with a transport agnostic error value. This implies that some winsock
120  * error translation must take place in these callbacks.
121  *
122  * Paragraph above applies to GNU TLS versions older than 2.12.3, since
123  * this version GNU TLS does its own internal winsock error translation
124  * using system_errno() function.
125  */
126
127 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
128 #  define gtls_EINTR  4
129 #  define gtls_EIO    5
130 #  define gtls_EAGAIN 11
131 static int gtls_mapped_sockerrno(void)
132 {
133   switch(SOCKERRNO) {
134   case WSAEWOULDBLOCK:
135     return gtls_EAGAIN;
136   case WSAEINTR:
137     return gtls_EINTR;
138   default:
139     break;
140   }
141   return gtls_EIO;
142 }
143 #endif
144
145 static ssize_t Curl_gtls_push(void *s, const void *buf, size_t len)
146 {
147   ssize_t ret = swrite(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
148 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
149   if(ret < 0)
150     gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
151 #endif
152   return ret;
153 }
154
155 static ssize_t Curl_gtls_pull(void *s, void *buf, size_t len)
156 {
157   ssize_t ret = sread(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
158 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
159   if(ret < 0)
160     gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
161 #endif
162   return ret;
163 }
164
165 /* Curl_gtls_init()
166  *
167  * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that
168  * are not thread-safe and thus this function itself is not thread-safe and
169  * must only be called from within curl_global_init() to keep the thread
170  * situation under control!
171  */
172 int Curl_gtls_init(void)
173 {
174   int ret = 1;
175   if(!gtls_inited) {
176     ret = gnutls_global_init()?0:1;
177 #ifdef GTLSDEBUG
178     gnutls_global_set_log_function(tls_log_func);
179     gnutls_global_set_log_level(2);
180 #endif
181     gtls_inited = TRUE;
182   }
183   return ret;
184 }
185
186 int Curl_gtls_cleanup(void)
187 {
188   if(gtls_inited) {
189     gnutls_global_deinit();
190     gtls_inited = FALSE;
191   }
192   return 1;
193 }
194
195 static void showtime(struct SessionHandle *data,
196                      const char *text,
197                      time_t stamp)
198 {
199   struct tm buffer;
200   const struct tm *tm = &buffer;
201   CURLcode result = Curl_gmtime(stamp, &buffer);
202   if(result)
203     return;
204
205   snprintf(data->state.buffer,
206            BUFSIZE,
207            "\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT\n",
208            text,
209            Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
210            tm->tm_mday,
211            Curl_month[tm->tm_mon],
212            tm->tm_year + 1900,
213            tm->tm_hour,
214            tm->tm_min,
215            tm->tm_sec);
216   infof(data, "%s\n", data->state.buffer);
217 }
218
219 static gnutls_datum_t load_file (const char *file)
220 {
221   FILE *f;
222   gnutls_datum_t loaded_file = { NULL, 0 };
223   long filelen;
224   void *ptr;
225
226   if(!(f = fopen(file, "r")))
227     return loaded_file;
228   if(fseek(f, 0, SEEK_END) != 0
229      || (filelen = ftell(f)) < 0
230      || fseek(f, 0, SEEK_SET) != 0
231      || !(ptr = malloc((size_t)filelen)))
232     goto out;
233   if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) {
234     free(ptr);
235     goto out;
236   }
237
238   loaded_file.data = ptr;
239   loaded_file.size = (unsigned int)filelen;
240 out:
241   fclose(f);
242   return loaded_file;
243 }
244
245 static void unload_file(gnutls_datum_t data) {
246   free(data.data);
247 }
248
249
250 /* this function does a SSL/TLS (re-)handshake */
251 static CURLcode handshake(struct connectdata *conn,
252                           int sockindex,
253                           bool duringconnect,
254                           bool nonblocking)
255 {
256   struct SessionHandle *data = conn->data;
257   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
258   gnutls_session_t session = conn->ssl[sockindex].session;
259   curl_socket_t sockfd = conn->sock[sockindex];
260   long timeout_ms;
261   int rc;
262   int what;
263
264   for(;;) {
265     /* check allowed time left */
266     timeout_ms = Curl_timeleft(data, NULL, duringconnect);
267
268     if(timeout_ms < 0) {
269       /* no need to continue if time already is up */
270       failf(data, "SSL connection timeout");
271       return CURLE_OPERATION_TIMEDOUT;
272     }
273
274     /* if ssl is expecting something, check if it's available. */
275     if(connssl->connecting_state == ssl_connect_2_reading
276        || connssl->connecting_state == ssl_connect_2_writing) {
277
278       curl_socket_t writefd = ssl_connect_2_writing==
279         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
280       curl_socket_t readfd = ssl_connect_2_reading==
281         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
282
283       what = Curl_socket_ready(readfd, writefd,
284                                nonblocking?0:
285                                timeout_ms?timeout_ms:1000);
286       if(what < 0) {
287         /* fatal error */
288         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
289         return CURLE_SSL_CONNECT_ERROR;
290       }
291       else if(0 == what) {
292         if(nonblocking)
293           return CURLE_OK;
294         else if(timeout_ms) {
295           /* timeout */
296           failf(data, "SSL connection timeout at %ld", timeout_ms);
297           return CURLE_OPERATION_TIMEDOUT;
298         }
299       }
300       /* socket is readable or writable */
301     }
302
303     rc = gnutls_handshake(session);
304
305     if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
306       connssl->connecting_state =
307         gnutls_record_get_direction(session)?
308         ssl_connect_2_writing:ssl_connect_2_reading;
309       continue;
310       if(nonblocking)
311         return CURLE_OK;
312     }
313     else if((rc < 0) && !gnutls_error_is_fatal(rc)) {
314       const char *strerr = NULL;
315
316       if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) {
317         int alert = gnutls_alert_get(session);
318         strerr = gnutls_alert_get_name(alert);
319       }
320
321       if(strerr == NULL)
322         strerr = gnutls_strerror(rc);
323
324       failf(data, "gnutls_handshake() warning: %s", strerr);
325     }
326     else if(rc < 0) {
327       const char *strerr = NULL;
328
329       if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) {
330         int alert = gnutls_alert_get(session);
331         strerr = gnutls_alert_get_name(alert);
332       }
333
334       if(strerr == NULL)
335         strerr = gnutls_strerror(rc);
336
337       failf(data, "gnutls_handshake() failed: %s", strerr);
338       return CURLE_SSL_CONNECT_ERROR;
339     }
340
341     /* Reset our connect state machine */
342     connssl->connecting_state = ssl_connect_1;
343     return CURLE_OK;
344   }
345 }
346
347 static gnutls_x509_crt_fmt_t do_file_type(const char *type)
348 {
349   if(!type || !type[0])
350     return GNUTLS_X509_FMT_PEM;
351   if(Curl_raw_equal(type, "PEM"))
352     return GNUTLS_X509_FMT_PEM;
353   if(Curl_raw_equal(type, "DER"))
354     return GNUTLS_X509_FMT_DER;
355   return -1;
356 }
357
358 static CURLcode
359 gtls_connect_step1(struct connectdata *conn,
360                    int sockindex)
361 {
362   struct SessionHandle *data = conn->data;
363   gnutls_session_t session;
364   int rc;
365   void *ssl_sessionid;
366   size_t ssl_idsize;
367   bool sni = TRUE; /* default is SNI enabled */
368 #ifdef ENABLE_IPV6
369   struct in6_addr addr;
370 #else
371   struct in_addr addr;
372 #endif
373 #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
374   static int cipher_priority[] = { GNUTLS_CIPHER_AES_128_GCM,
375     GNUTLS_CIPHER_AES_256_GCM, GNUTLS_CIPHER_AES_128_CBC,
376     GNUTLS_CIPHER_AES_256_CBC, GNUTLS_CIPHER_CAMELLIA_128_CBC,
377     GNUTLS_CIPHER_CAMELLIA_256_CBC, GNUTLS_CIPHER_3DES_CBC,
378   };
379   static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
380   static int protocol_priority[] = { 0, 0, 0, 0 };
381 #else
382 #define GNUTLS_CIPHERS "NORMAL:-ARCFOUR-128:-CTYPE-ALL:+CTYPE-X509"
383   const char* prioritylist;
384   const char *err;
385 #endif
386 #ifdef HAS_ALPN
387   int protocols_size = 2;
388   gnutls_datum_t protocols[2];
389 #endif
390
391   if(conn->ssl[sockindex].state == ssl_connection_complete)
392     /* to make us tolerant against being called more than once for the
393        same connection */
394     return CURLE_OK;
395
396   if(!gtls_inited)
397     Curl_gtls_init();
398
399   /* GnuTLS only supports SSLv3 and TLSv1 */
400   if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
401     failf(data, "GnuTLS does not support SSLv2");
402     return CURLE_SSL_CONNECT_ERROR;
403   }
404   else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
405     sni = FALSE; /* SSLv3 has no SNI */
406
407   /* allocate a cred struct */
408   rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
409   if(rc != GNUTLS_E_SUCCESS) {
410     failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
411     return CURLE_SSL_CONNECT_ERROR;
412   }
413
414 #ifdef USE_TLS_SRP
415   if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
416     infof(data, "Using TLS-SRP username: %s\n", data->set.ssl.username);
417
418     rc = gnutls_srp_allocate_client_credentials(
419            &conn->ssl[sockindex].srp_client_cred);
420     if(rc != GNUTLS_E_SUCCESS) {
421       failf(data, "gnutls_srp_allocate_client_cred() failed: %s",
422             gnutls_strerror(rc));
423       return CURLE_OUT_OF_MEMORY;
424     }
425
426     rc = gnutls_srp_set_client_credentials(conn->ssl[sockindex].
427                                            srp_client_cred,
428                                            data->set.ssl.username,
429                                            data->set.ssl.password);
430     if(rc != GNUTLS_E_SUCCESS) {
431       failf(data, "gnutls_srp_set_client_cred() failed: %s",
432             gnutls_strerror(rc));
433       return CURLE_BAD_FUNCTION_ARGUMENT;
434     }
435   }
436 #endif
437
438   if(data->set.ssl.CAfile) {
439     /* set the trusted CA cert bundle file */
440     gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
441                                         GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
442
443     rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
444                                                 data->set.ssl.CAfile,
445                                                 GNUTLS_X509_FMT_PEM);
446     if(rc < 0) {
447       infof(data, "error reading ca cert file %s (%s)\n",
448             data->set.ssl.CAfile, gnutls_strerror(rc));
449       if(data->set.ssl.verifypeer)
450         return CURLE_SSL_CACERT_BADFILE;
451     }
452     else
453       infof(data, "found %d certificates in %s\n",
454             rc, data->set.ssl.CAfile);
455   }
456
457   if(data->set.ssl.CRLfile) {
458     /* set the CRL list file */
459     rc = gnutls_certificate_set_x509_crl_file(conn->ssl[sockindex].cred,
460                                               data->set.ssl.CRLfile,
461                                               GNUTLS_X509_FMT_PEM);
462     if(rc < 0) {
463       failf(data, "error reading crl file %s (%s)",
464             data->set.ssl.CRLfile, gnutls_strerror(rc));
465       return CURLE_SSL_CRL_BADFILE;
466     }
467     else
468       infof(data, "found %d CRL in %s\n",
469             rc, data->set.ssl.CRLfile);
470   }
471
472   /* Initialize TLS session as a client */
473   rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
474   if(rc != GNUTLS_E_SUCCESS) {
475     failf(data, "gnutls_init() failed: %d", rc);
476     return CURLE_SSL_CONNECT_ERROR;
477   }
478
479   /* convenient assign */
480   session = conn->ssl[sockindex].session;
481
482   if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
483 #ifdef ENABLE_IPV6
484      (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
485 #endif
486      sni &&
487      (gnutls_server_name_set(session, GNUTLS_NAME_DNS, conn->host.name,
488                              strlen(conn->host.name)) < 0))
489     infof(data, "WARNING: failed to configure server name indication (SNI) "
490           "TLS extension\n");
491
492   /* Use default priorities */
493   rc = gnutls_set_default_priority(session);
494   if(rc != GNUTLS_E_SUCCESS)
495     return CURLE_SSL_CONNECT_ERROR;
496
497 #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
498   rc = gnutls_cipher_set_priority(session, cipher_priority);
499   if(rc != GNUTLS_E_SUCCESS)
500     return CURLE_SSL_CONNECT_ERROR;
501
502   /* Sets the priority on the certificate types supported by gnutls. Priority
503    is higher for types specified before others. After specifying the types
504    you want, you must append a 0. */
505   rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
506   if(rc != GNUTLS_E_SUCCESS)
507     return CURLE_SSL_CONNECT_ERROR;
508
509   if(data->set.ssl.cipher_list != NULL) {
510     failf(data, "can't pass a custom cipher list to older GnuTLS"
511           " versions");
512     return CURLE_SSL_CONNECT_ERROR;
513   }
514
515   switch (data->set.ssl.version) {
516     case CURL_SSLVERSION_SSLv3:
517       protocol_priority[0] = GNUTLS_SSL3;
518       break;
519     case CURL_SSLVERSION_DEFAULT:
520     case CURL_SSLVERSION_TLSv1:
521       protocol_priority[0] = GNUTLS_TLS1_0;
522       protocol_priority[1] = GNUTLS_TLS1_1;
523       protocol_priority[2] = GNUTLS_TLS1_2;
524       break;
525     case CURL_SSLVERSION_TLSv1_0:
526       protocol_priority[0] = GNUTLS_TLS1_0;
527       break;
528     case CURL_SSLVERSION_TLSv1_1:
529       protocol_priority[0] = GNUTLS_TLS1_1;
530       break;
531     case CURL_SSLVERSION_TLSv1_2:
532       protocol_priority[0] = GNUTLS_TLS1_2;
533     break;
534       case CURL_SSLVERSION_SSLv2:
535     default:
536       failf(data, "GnuTLS does not support SSLv2");
537       return CURLE_SSL_CONNECT_ERROR;
538       break;
539   }
540   rc = gnutls_protocol_set_priority(session, protocol_priority);
541 #else
542   switch (data->set.ssl.version) {
543     case CURL_SSLVERSION_SSLv3:
544       prioritylist = GNUTLS_CIPHERS ":-VERS-TLS-ALL:+VERS-SSL3.0";
545       sni = false;
546       break;
547     case CURL_SSLVERSION_DEFAULT:
548     case CURL_SSLVERSION_TLSv1:
549       prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0";
550       break;
551     case CURL_SSLVERSION_TLSv1_0:
552       prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
553                      "+VERS-TLS1.0";
554       break;
555     case CURL_SSLVERSION_TLSv1_1:
556       prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
557                      "+VERS-TLS1.1";
558       break;
559     case CURL_SSLVERSION_TLSv1_2:
560       prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
561                      "+VERS-TLS1.2";
562       break;
563     case CURL_SSLVERSION_SSLv2:
564     default:
565       failf(data, "GnuTLS does not support SSLv2");
566       return CURLE_SSL_CONNECT_ERROR;
567       break;
568   }
569   rc = gnutls_priority_set_direct(session, prioritylist, &err);
570 #endif
571
572 #ifdef HAS_ALPN
573   if(data->set.httpversion == CURL_HTTP_VERSION_2_0) {
574     if(data->set.ssl_enable_alpn) {
575       protocols[0].data = NGHTTP2_PROTO_VERSION_ID;
576       protocols[0].size = NGHTTP2_PROTO_VERSION_ID_LEN;
577       protocols[1].data = ALPN_HTTP_1_1;
578       protocols[1].size = ALPN_HTTP_1_1_LENGTH;
579       gnutls_alpn_set_protocols(session, protocols, protocols_size, 0);
580       infof(data, "ALPN, offering %s, %s\n", NGHTTP2_PROTO_VERSION_ID,
581             ALPN_HTTP_1_1);
582     }
583     else {
584       infof(data, "SSL, can't negotiate HTTP/2.0 without ALPN\n");
585     }
586   }
587 #endif
588
589   if(rc != GNUTLS_E_SUCCESS) {
590     failf(data, "Did you pass a valid GnuTLS cipher list?");
591     return CURLE_SSL_CONNECT_ERROR;
592   }
593
594
595   if(data->set.str[STRING_CERT]) {
596     if(gnutls_certificate_set_x509_key_file(
597          conn->ssl[sockindex].cred,
598          data->set.str[STRING_CERT],
599          data->set.str[STRING_KEY] ?
600          data->set.str[STRING_KEY] : data->set.str[STRING_CERT],
601          do_file_type(data->set.str[STRING_CERT_TYPE]) ) !=
602        GNUTLS_E_SUCCESS) {
603       failf(data, "error reading X.509 key or certificate file");
604       return CURLE_SSL_CONNECT_ERROR;
605     }
606   }
607
608 #ifdef USE_TLS_SRP
609   /* put the credentials to the current session */
610   if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
611     rc = gnutls_credentials_set(session, GNUTLS_CRD_SRP,
612                                 conn->ssl[sockindex].srp_client_cred);
613     if(rc != GNUTLS_E_SUCCESS)
614       failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
615   }
616   else
617 #endif
618     rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
619                                 conn->ssl[sockindex].cred);
620
621   /* set the connection handle (file descriptor for the socket) */
622   gnutls_transport_set_ptr(session,
623                            GNUTLS_INT_TO_POINTER_CAST(conn->sock[sockindex]));
624
625   /* register callback functions to send and receive data. */
626   gnutls_transport_set_push_function(session, Curl_gtls_push);
627   gnutls_transport_set_pull_function(session, Curl_gtls_pull);
628
629   /* lowat must be set to zero when using custom push and pull functions. */
630   gnutls_transport_set_lowat(session, 0);
631
632   /* This might be a reconnect, so we check for a session ID in the cache
633      to speed up things */
634
635   if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
636     /* we got a session id, use it! */
637     gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);
638
639     /* Informational message */
640     infof (data, "SSL re-using session ID\n");
641   }
642
643   return CURLE_OK;
644 }
645
646 static Curl_recv gtls_recv;
647 static Curl_send gtls_send;
648
649 static CURLcode
650 gtls_connect_step3(struct connectdata *conn,
651                    int sockindex)
652 {
653   unsigned int cert_list_size;
654   const gnutls_datum_t *chainp;
655   unsigned int verify_status;
656   gnutls_x509_crt_t x509_cert,x509_issuer;
657   gnutls_datum_t issuerp;
658   char certbuf[256]; /* big enough? */
659   size_t size;
660   unsigned int algo;
661   unsigned int bits;
662   time_t certclock;
663   const char *ptr;
664   struct SessionHandle *data = conn->data;
665   gnutls_session_t session = conn->ssl[sockindex].session;
666   int rc;
667   int incache;
668   void *ssl_sessionid;
669 #ifdef HAS_ALPN
670   gnutls_datum_t proto;
671 #endif
672   CURLcode result = CURLE_OK;
673
674   /* This function will return the peer's raw certificate (chain) as sent by
675      the peer. These certificates are in raw format (DER encoded for
676      X.509). In case of a X.509 then a certificate list may be present. The
677      first certificate in the list is the peer's certificate, following the
678      issuer's certificate, then the issuer's issuer etc. */
679
680   chainp = gnutls_certificate_get_peers(session, &cert_list_size);
681   if(!chainp) {
682     if(data->set.ssl.verifypeer ||
683        data->set.ssl.verifyhost ||
684        data->set.ssl.issuercert) {
685 #ifdef USE_TLS_SRP
686       if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
687          && data->set.ssl.username != NULL
688          && !data->set.ssl.verifypeer
689          && gnutls_cipher_get(session)) {
690         /* no peer cert, but auth is ok if we have SRP user and cipher and no
691            peer verify */
692       }
693       else {
694 #endif
695         failf(data, "failed to get server cert");
696         return CURLE_PEER_FAILED_VERIFICATION;
697 #ifdef USE_TLS_SRP
698       }
699 #endif
700     }
701     infof(data, "\t common name: WARNING couldn't obtain\n");
702   }
703
704   if(data->set.ssl.verifypeer) {
705     /* This function will try to verify the peer's certificate and return its
706        status (trusted, invalid etc.). The value of status should be one or
707        more of the gnutls_certificate_status_t enumerated elements bitwise
708        or'd. To avoid denial of service attacks some default upper limits
709        regarding the certificate key size and chain size are set. To override
710        them use gnutls_certificate_set_verify_limits(). */
711
712     rc = gnutls_certificate_verify_peers2(session, &verify_status);
713     if(rc < 0) {
714       failf(data, "server cert verify failed: %d", rc);
715       return CURLE_SSL_CONNECT_ERROR;
716     }
717
718     /* verify_status is a bitmask of gnutls_certificate_status bits */
719     if(verify_status & GNUTLS_CERT_INVALID) {
720       if(data->set.ssl.verifypeer) {
721         failf(data, "server certificate verification failed. CAfile: %s "
722               "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
723               data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
724         return CURLE_SSL_CACERT;
725       }
726       else
727         infof(data, "\t server certificate verification FAILED\n");
728     }
729     else
730       infof(data, "\t server certificate verification OK\n");
731   }
732   else
733     infof(data, "\t server certificate verification SKIPPED\n");
734
735   /* initialize an X.509 certificate structure. */
736   gnutls_x509_crt_init(&x509_cert);
737
738   if(chainp)
739     /* convert the given DER or PEM encoded Certificate to the native
740        gnutls_x509_crt_t format */
741     gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
742
743   if(data->set.ssl.issuercert) {
744     gnutls_x509_crt_init(&x509_issuer);
745     issuerp = load_file(data->set.ssl.issuercert);
746     gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
747     rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
748     unload_file(issuerp);
749     if(rc <= 0) {
750       failf(data, "server certificate issuer check failed (IssuerCert: %s)",
751             data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
752       return CURLE_SSL_ISSUER_ERROR;
753     }
754     infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
755           data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
756   }
757
758   size=sizeof(certbuf);
759   rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
760                                      0, /* the first and only one */
761                                      FALSE,
762                                      certbuf,
763                                      &size);
764   if(rc) {
765     infof(data, "error fetching CN from cert:%s\n",
766           gnutls_strerror(rc));
767   }
768
769   /* This function will check if the given certificate's subject matches the
770      given hostname. This is a basic implementation of the matching described
771      in RFC2818 (HTTPS), which takes into account wildcards, and the subject
772      alternative name PKIX extension. Returns non zero on success, and zero on
773      failure. */
774   rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
775
776   if(!rc) {
777     if(data->set.ssl.verifyhost) {
778       failf(data, "SSL: certificate subject name (%s) does not match "
779             "target host name '%s'", certbuf, conn->host.dispname);
780       gnutls_x509_crt_deinit(x509_cert);
781       return CURLE_PEER_FAILED_VERIFICATION;
782     }
783     else
784       infof(data, "\t common name: %s (does not match '%s')\n",
785             certbuf, conn->host.dispname);
786   }
787   else
788     infof(data, "\t common name: %s (matched)\n", certbuf);
789
790   /* Check for time-based validity */
791   certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
792
793   if(certclock == (time_t)-1) {
794     failf(data, "server cert expiration date verify failed");
795     return CURLE_SSL_CONNECT_ERROR;
796   }
797
798   if(certclock < time(NULL)) {
799     if(data->set.ssl.verifypeer) {
800       failf(data, "server certificate expiration date has passed.");
801       return CURLE_PEER_FAILED_VERIFICATION;
802     }
803     else
804       infof(data, "\t server certificate expiration date FAILED\n");
805   }
806   else
807     infof(data, "\t server certificate expiration date OK\n");
808
809   certclock = gnutls_x509_crt_get_activation_time(x509_cert);
810
811   if(certclock == (time_t)-1) {
812     failf(data, "server cert activation date verify failed");
813     return CURLE_SSL_CONNECT_ERROR;
814   }
815
816   if(certclock > time(NULL)) {
817     if(data->set.ssl.verifypeer) {
818       failf(data, "server certificate not activated yet.");
819       return CURLE_PEER_FAILED_VERIFICATION;
820     }
821     else
822       infof(data, "\t server certificate activation date FAILED\n");
823   }
824   else
825     infof(data, "\t server certificate activation date OK\n");
826
827   /* Show:
828
829   - ciphers used
830   - subject
831   - start date
832   - expire date
833   - common name
834   - issuer
835
836   */
837
838   /* public key algorithm's parameters */
839   algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
840   infof(data, "\t certificate public key: %s\n",
841         gnutls_pk_algorithm_get_name(algo));
842
843   /* version of the X.509 certificate. */
844   infof(data, "\t certificate version: #%d\n",
845         gnutls_x509_crt_get_version(x509_cert));
846
847
848   size = sizeof(certbuf);
849   gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
850   infof(data, "\t subject: %s\n", certbuf);
851
852   certclock = gnutls_x509_crt_get_activation_time(x509_cert);
853   showtime(data, "start date", certclock);
854
855   certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
856   showtime(data, "expire date", certclock);
857
858   size = sizeof(certbuf);
859   gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
860   infof(data, "\t issuer: %s\n", certbuf);
861
862   gnutls_x509_crt_deinit(x509_cert);
863
864   /* compression algorithm (if any) */
865   ptr = gnutls_compression_get_name(gnutls_compression_get(session));
866   /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
867   infof(data, "\t compression: %s\n", ptr);
868
869   /* the name of the cipher used. ie 3DES. */
870   ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
871   infof(data, "\t cipher: %s\n", ptr);
872
873   /* the MAC algorithms name. ie SHA1 */
874   ptr = gnutls_mac_get_name(gnutls_mac_get(session));
875   infof(data, "\t MAC: %s\n", ptr);
876
877 #ifdef HAS_ALPN
878   if(data->set.ssl_enable_alpn) {
879     rc = gnutls_alpn_get_selected_protocol(session, &proto);
880     if(rc == 0) {
881       infof(data, "ALPN, server accepted to use %.*s\n", proto.size,
882           proto.data);
883
884       if(proto.size == NGHTTP2_PROTO_VERSION_ID_LEN &&
885         memcmp(NGHTTP2_PROTO_VERSION_ID, proto.data,
886         NGHTTP2_PROTO_VERSION_ID_LEN) == 0) {
887         conn->negnpn = NPN_HTTP2;
888       }
889       else if(proto.size == ALPN_HTTP_1_1_LENGTH && memcmp(ALPN_HTTP_1_1,
890           proto.data, ALPN_HTTP_1_1_LENGTH) == 0) {
891         conn->negnpn = NPN_HTTP1_1;
892       }
893     }
894     else {
895       infof(data, "ALPN, server did not agree to a protocol\n");
896     }
897   }
898 #endif
899
900   conn->ssl[sockindex].state = ssl_connection_complete;
901   conn->recv[sockindex] = gtls_recv;
902   conn->send[sockindex] = gtls_send;
903
904   {
905     /* we always unconditionally get the session id here, as even if we
906        already got it from the cache and asked to use it in the connection, it
907        might've been rejected and then a new one is in use now and we need to
908        detect that. */
909     void *connect_sessionid;
910     size_t connect_idsize;
911
912     /* get the session ID data size */
913     gnutls_session_get_data(session, NULL, &connect_idsize);
914     connect_sessionid = malloc(connect_idsize); /* get a buffer for it */
915
916     if(connect_sessionid) {
917       /* extract session ID to the allocated buffer */
918       gnutls_session_get_data(session, connect_sessionid, &connect_idsize);
919
920       incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
921       if(incache) {
922         /* there was one before in the cache, so instead of risking that the
923            previous one was rejected, we just kill that and store the new */
924         Curl_ssl_delsessionid(conn, ssl_sessionid);
925       }
926
927       /* store this session id */
928       result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
929       if(result) {
930         free(connect_sessionid);
931         result = CURLE_OUT_OF_MEMORY;
932       }
933     }
934     else
935       result = CURLE_OUT_OF_MEMORY;
936   }
937
938   return result;
939 }
940
941
942 /*
943  * This function is called after the TCP connect has completed. Setup the TLS
944  * layer and do all necessary magic.
945  */
946 /* We use connssl->connecting_state to keep track of the connection status;
947    there are three states: 'ssl_connect_1' (not started yet or complete),
948    'ssl_connect_2_reading' (waiting for data from server), and
949    'ssl_connect_2_writing' (waiting to be able to write).
950  */
951 static CURLcode
952 gtls_connect_common(struct connectdata *conn,
953                     int sockindex,
954                     bool nonblocking,
955                     bool *done)
956 {
957   int rc;
958   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
959
960   /* Initiate the connection, if not already done */
961   if(ssl_connect_1==connssl->connecting_state) {
962     rc = gtls_connect_step1 (conn, sockindex);
963     if(rc)
964       return rc;
965   }
966
967   rc = handshake(conn, sockindex, TRUE, nonblocking);
968   if(rc)
969     /* handshake() sets its own error message with failf() */
970     return rc;
971
972   /* Finish connecting once the handshake is done */
973   if(ssl_connect_1==connssl->connecting_state) {
974     rc = gtls_connect_step3(conn, sockindex);
975     if(rc)
976       return rc;
977   }
978
979   *done = ssl_connect_1==connssl->connecting_state;
980
981   return CURLE_OK;
982 }
983
984 CURLcode
985 Curl_gtls_connect_nonblocking(struct connectdata *conn,
986                               int sockindex,
987                               bool *done)
988 {
989   return gtls_connect_common(conn, sockindex, TRUE, done);
990 }
991
992 CURLcode
993 Curl_gtls_connect(struct connectdata *conn,
994                   int sockindex)
995
996 {
997   CURLcode retcode;
998   bool done = FALSE;
999
1000   retcode = gtls_connect_common(conn, sockindex, FALSE, &done);
1001   if(retcode)
1002     return retcode;
1003
1004   DEBUGASSERT(done);
1005
1006   return CURLE_OK;
1007 }
1008
1009 static ssize_t gtls_send(struct connectdata *conn,
1010                          int sockindex,
1011                          const void *mem,
1012                          size_t len,
1013                          CURLcode *curlcode)
1014 {
1015   ssize_t rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
1016
1017   if(rc < 0 ) {
1018     *curlcode = (rc == GNUTLS_E_AGAIN)
1019       ? CURLE_AGAIN
1020       : CURLE_SEND_ERROR;
1021
1022     rc = -1;
1023   }
1024
1025   return rc;
1026 }
1027
1028 void Curl_gtls_close_all(struct SessionHandle *data)
1029 {
1030   /* FIX: make the OpenSSL code more generic and use parts of it here */
1031   (void)data;
1032 }
1033
1034 static void close_one(struct connectdata *conn,
1035                       int idx)
1036 {
1037   if(conn->ssl[idx].session) {
1038     gnutls_bye(conn->ssl[idx].session, GNUTLS_SHUT_RDWR);
1039     gnutls_deinit(conn->ssl[idx].session);
1040     conn->ssl[idx].session = NULL;
1041   }
1042   if(conn->ssl[idx].cred) {
1043     gnutls_certificate_free_credentials(conn->ssl[idx].cred);
1044     conn->ssl[idx].cred = NULL;
1045   }
1046 #ifdef USE_TLS_SRP
1047   if(conn->ssl[idx].srp_client_cred) {
1048     gnutls_srp_free_client_credentials(conn->ssl[idx].srp_client_cred);
1049     conn->ssl[idx].srp_client_cred = NULL;
1050   }
1051 #endif
1052 }
1053
1054 void Curl_gtls_close(struct connectdata *conn, int sockindex)
1055 {
1056   close_one(conn, sockindex);
1057 }
1058
1059 /*
1060  * This function is called to shut down the SSL layer but keep the
1061  * socket open (CCC - Clear Command Channel)
1062  */
1063 int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
1064 {
1065   ssize_t result;
1066   int retval = 0;
1067   struct SessionHandle *data = conn->data;
1068   int done = 0;
1069   char buf[120];
1070
1071   /* This has only been tested on the proftpd server, and the mod_tls code
1072      sends a close notify alert without waiting for a close notify alert in
1073      response. Thus we wait for a close notify alert from the server, but
1074      we do not send one. Let's hope other servers do the same... */
1075
1076   if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
1077       gnutls_bye(conn->ssl[sockindex].session, GNUTLS_SHUT_WR);
1078
1079   if(conn->ssl[sockindex].session) {
1080     while(!done) {
1081       int what = Curl_socket_ready(conn->sock[sockindex],
1082                                    CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
1083       if(what > 0) {
1084         /* Something to read, let's do it and hope that it is the close
1085            notify alert from the server */
1086         result = gnutls_record_recv(conn->ssl[sockindex].session,
1087                                     buf, sizeof(buf));
1088         switch(result) {
1089         case 0:
1090           /* This is the expected response. There was no data but only
1091              the close notify alert */
1092           done = 1;
1093           break;
1094         case GNUTLS_E_AGAIN:
1095         case GNUTLS_E_INTERRUPTED:
1096           infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED\n");
1097           break;
1098         default:
1099           retval = -1;
1100           done = 1;
1101           break;
1102         }
1103       }
1104       else if(0 == what) {
1105         /* timeout */
1106         failf(data, "SSL shutdown timeout");
1107         done = 1;
1108         break;
1109       }
1110       else {
1111         /* anything that gets here is fatally bad */
1112         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1113         retval = -1;
1114         done = 1;
1115       }
1116     }
1117     gnutls_deinit(conn->ssl[sockindex].session);
1118   }
1119   gnutls_certificate_free_credentials(conn->ssl[sockindex].cred);
1120
1121 #ifdef USE_TLS_SRP
1122   if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
1123      && data->set.ssl.username != NULL)
1124     gnutls_srp_free_client_credentials(conn->ssl[sockindex].srp_client_cred);
1125 #endif
1126
1127   conn->ssl[sockindex].cred = NULL;
1128   conn->ssl[sockindex].session = NULL;
1129
1130   return retval;
1131 }
1132
1133 static ssize_t gtls_recv(struct connectdata *conn, /* connection data */
1134                          int num,                  /* socketindex */
1135                          char *buf,                /* store read data here */
1136                          size_t buffersize,        /* max amount to read */
1137                          CURLcode *curlcode)
1138 {
1139   ssize_t ret;
1140
1141   ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
1142   if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
1143     *curlcode = CURLE_AGAIN;
1144     return -1;
1145   }
1146
1147   if(ret == GNUTLS_E_REHANDSHAKE) {
1148     /* BLOCKING call, this is bad but a work-around for now. Fixing this "the
1149        proper way" takes a whole lot of work. */
1150     CURLcode rc = handshake(conn, num, FALSE, FALSE);
1151     if(rc)
1152       /* handshake() writes error message on its own */
1153       *curlcode = rc;
1154     else
1155       *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
1156     return -1;
1157   }
1158
1159   if(ret < 0) {
1160     failf(conn->data, "GnuTLS recv error (%d): %s",
1161           (int)ret, gnutls_strerror((int)ret));
1162     *curlcode = CURLE_RECV_ERROR;
1163     return -1;
1164   }
1165
1166   return ret;
1167 }
1168
1169 void Curl_gtls_session_free(void *ptr)
1170 {
1171   free(ptr);
1172 }
1173
1174 size_t Curl_gtls_version(char *buffer, size_t size)
1175 {
1176   return snprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
1177 }
1178
1179 int Curl_gtls_seed(struct SessionHandle *data)
1180 {
1181   /* we have the "SSL is seeded" boolean static to prevent multiple
1182      time-consuming seedings in vain */
1183   static bool ssl_seeded = FALSE;
1184
1185   /* Quickly add a bit of entropy */
1186 #ifndef USE_GNUTLS_NETTLE
1187   gcry_fast_random_poll();
1188 #endif
1189
1190   if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
1191      data->set.str[STRING_SSL_EGDSOCKET]) {
1192
1193     /* TODO: to a good job seeding the RNG
1194        This may involve the gcry_control function and these options:
1195        GCRYCTL_SET_RANDOM_SEED_FILE
1196        GCRYCTL_SET_RNDEGD_SOCKET
1197     */
1198     ssl_seeded = TRUE;
1199   }
1200   return 0;
1201 }
1202
1203 void Curl_gtls_random(struct SessionHandle *data,
1204                       unsigned char *entropy,
1205                       size_t length)
1206 {
1207 #if defined(USE_GNUTLS_NETTLE)
1208   (void)data;
1209   gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length);
1210 #elif defined(USE_GNUTLS)
1211   Curl_gtls_seed(data); /* Initiate the seed if not already done */
1212   gcry_randomize(entropy, length, GCRY_STRONG_RANDOM);
1213 #endif
1214 }
1215
1216 void Curl_gtls_md5sum(unsigned char *tmp, /* input */
1217                       size_t tmplen,
1218                       unsigned char *md5sum, /* output */
1219                       size_t md5len)
1220 {
1221 #if defined(USE_GNUTLS_NETTLE)
1222   struct md5_ctx MD5pw;
1223   md5_init(&MD5pw);
1224   md5_update(&MD5pw, (unsigned int)tmplen, tmp);
1225   md5_digest(&MD5pw, (unsigned int)md5len, md5sum);
1226 #elif defined(USE_GNUTLS)
1227   gcry_md_hd_t MD5pw;
1228   gcry_md_open(&MD5pw, GCRY_MD_MD5, 0);
1229   gcry_md_write(MD5pw, tmp, tmplen);
1230   memcpy(md5sum, gcry_md_read (MD5pw, 0), md5len);
1231   gcry_md_close(MD5pw);
1232 #endif
1233 }
1234
1235 #endif /* USE_GNUTLS */