Imported Upstream version 7.32.0
[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/abstract.h>
36 #include <gnutls/gnutls.h>
37 #include <gnutls/x509.h>
38
39 #ifdef USE_GNUTLS_NETTLE
40 #include <gnutls/crypto.h>
41 #include <nettle/md5.h>
42 #else
43 #include <gcrypt.h>
44 #endif
45
46 #include "urldata.h"
47 #include "sendf.h"
48 #include "inet_pton.h"
49 #include "gtls.h"
50 #include "vtls.h"
51 #include "parsedate.h"
52 #include "connect.h" /* for the connect timeout */
53 #include "select.h"
54 #include "rawstr.h"
55 #include "warnless.h"
56
57 #define _MPRINTF_REPLACE /* use our functions only */
58 #include <curl/mprintf.h>
59 #include "curl_memory.h"
60 /* The last #include file should be: */
61 #include "memdebug.h"
62
63 /*
64  Some hackish cast macros based on:
65  http://library.gnome.org/devel/glib/unstable/glib-Type-Conversion-Macros.html
66 */
67 #ifndef GNUTLS_POINTER_TO_INT_CAST
68 #define GNUTLS_POINTER_TO_INT_CAST(p) ((int) (long) (p))
69 #endif
70 #ifndef GNUTLS_INT_TO_POINTER_CAST
71 #define GNUTLS_INT_TO_POINTER_CAST(i) ((void*) (long) (i))
72 #endif
73
74 /* Enable GnuTLS debugging by defining GTLSDEBUG */
75 /*#define GTLSDEBUG */
76
77 #ifdef GTLSDEBUG
78 static void tls_log_func(int level, const char *str)
79 {
80     fprintf(stderr, "|<%d>| %s", level, str);
81 }
82 #endif
83 static bool gtls_inited = FALSE;
84
85 #if defined(GNUTLS_VERSION_NUMBER)
86 #  if (GNUTLS_VERSION_NUMBER >= 0x020c00)
87 #    undef gnutls_transport_set_lowat
88 #    define gnutls_transport_set_lowat(A,B) Curl_nop_stmt
89 #    define USE_GNUTLS_PRIORITY_SET_DIRECT 1
90 #  endif
91 #  if (GNUTLS_VERSION_NUMBER >= 0x020c03)
92 #    define GNUTLS_MAPS_WINSOCK_ERRORS 1
93 #  endif
94
95 #  ifdef USE_NGHTTP2
96 #    undef HAS_ALPN
97 #    if (GNUTLS_VERSION_NUMBER >= 0x030200)
98 #      define HAS_ALPN
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     }
311     else if((rc < 0) && !gnutls_error_is_fatal(rc)) {
312       const char *strerr = NULL;
313
314       if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) {
315         int alert = gnutls_alert_get(session);
316         strerr = gnutls_alert_get_name(alert);
317       }
318
319       if(strerr == NULL)
320         strerr = gnutls_strerror(rc);
321
322       failf(data, "gnutls_handshake() warning: %s", strerr);
323     }
324     else if(rc < 0) {
325       const char *strerr = NULL;
326
327       if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) {
328         int alert = gnutls_alert_get(session);
329         strerr = gnutls_alert_get_name(alert);
330       }
331
332       if(strerr == NULL)
333         strerr = gnutls_strerror(rc);
334
335       failf(data, "gnutls_handshake() failed: %s", strerr);
336       return CURLE_SSL_CONNECT_ERROR;
337     }
338
339     /* Reset our connect state machine */
340     connssl->connecting_state = ssl_connect_1;
341     return CURLE_OK;
342   }
343 }
344
345 static gnutls_x509_crt_fmt_t do_file_type(const char *type)
346 {
347   if(!type || !type[0])
348     return GNUTLS_X509_FMT_PEM;
349   if(Curl_raw_equal(type, "PEM"))
350     return GNUTLS_X509_FMT_PEM;
351   if(Curl_raw_equal(type, "DER"))
352     return GNUTLS_X509_FMT_DER;
353   return -1;
354 }
355
356 static CURLcode
357 gtls_connect_step1(struct connectdata *conn,
358                    int sockindex)
359 {
360   struct SessionHandle *data = conn->data;
361   gnutls_session_t session;
362   int rc;
363   void *ssl_sessionid;
364   size_t ssl_idsize;
365   bool sni = TRUE; /* default is SNI enabled */
366 #ifdef ENABLE_IPV6
367   struct in6_addr addr;
368 #else
369   struct in_addr addr;
370 #endif
371 #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
372   static const int cipher_priority[] = {
373   /* These two ciphers were added to GnuTLS as late as ver. 3.0.1,
374      but this code path is only ever used for ver. < 2.12.0.
375      GNUTLS_CIPHER_AES_128_GCM,
376      GNUTLS_CIPHER_AES_256_GCM,
377   */
378     GNUTLS_CIPHER_AES_128_CBC,
379     GNUTLS_CIPHER_AES_256_CBC,
380     GNUTLS_CIPHER_CAMELLIA_128_CBC,
381     GNUTLS_CIPHER_CAMELLIA_256_CBC,
382     GNUTLS_CIPHER_3DES_CBC,
383   };
384   static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
385   static int protocol_priority[] = { 0, 0, 0, 0 };
386 #else
387 #define GNUTLS_CIPHERS "NORMAL:-ARCFOUR-128:-CTYPE-ALL:+CTYPE-X509"
388 /* If GnuTLS was compiled without support for SRP it will error out if SRP is
389    requested in the priority string, so treat it specially
390  */
391 #define GNUTLS_SRP "+SRP"
392   const char* prioritylist;
393   const char *err = NULL;
394 #endif
395 #ifdef HAS_ALPN
396   int protocols_size = 2;
397   gnutls_datum_t protocols[2];
398 #endif
399
400   if(conn->ssl[sockindex].state == ssl_connection_complete)
401     /* to make us tolerant against being called more than once for the
402        same connection */
403     return CURLE_OK;
404
405   if(!gtls_inited)
406     Curl_gtls_init();
407
408   /* GnuTLS only supports SSLv3 and TLSv1 */
409   if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
410     failf(data, "GnuTLS does not support SSLv2");
411     return CURLE_SSL_CONNECT_ERROR;
412   }
413   else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
414     sni = FALSE; /* SSLv3 has no SNI */
415
416   /* allocate a cred struct */
417   rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
418   if(rc != GNUTLS_E_SUCCESS) {
419     failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
420     return CURLE_SSL_CONNECT_ERROR;
421   }
422
423 #ifdef USE_TLS_SRP
424   if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
425     infof(data, "Using TLS-SRP username: %s\n", data->set.ssl.username);
426
427     rc = gnutls_srp_allocate_client_credentials(
428            &conn->ssl[sockindex].srp_client_cred);
429     if(rc != GNUTLS_E_SUCCESS) {
430       failf(data, "gnutls_srp_allocate_client_cred() failed: %s",
431             gnutls_strerror(rc));
432       return CURLE_OUT_OF_MEMORY;
433     }
434
435     rc = gnutls_srp_set_client_credentials(conn->ssl[sockindex].
436                                            srp_client_cred,
437                                            data->set.ssl.username,
438                                            data->set.ssl.password);
439     if(rc != GNUTLS_E_SUCCESS) {
440       failf(data, "gnutls_srp_set_client_cred() failed: %s",
441             gnutls_strerror(rc));
442       return CURLE_BAD_FUNCTION_ARGUMENT;
443     }
444   }
445 #endif
446
447   if(data->set.ssl.CAfile) {
448     /* set the trusted CA cert bundle file */
449     gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
450                                         GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
451
452     rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
453                                                 data->set.ssl.CAfile,
454                                                 GNUTLS_X509_FMT_PEM);
455     if(rc < 0) {
456       infof(data, "error reading ca cert file %s (%s)\n",
457             data->set.ssl.CAfile, gnutls_strerror(rc));
458       if(data->set.ssl.verifypeer)
459         return CURLE_SSL_CACERT_BADFILE;
460     }
461     else
462       infof(data, "found %d certificates in %s\n",
463             rc, data->set.ssl.CAfile);
464   }
465
466   if(data->set.ssl.CRLfile) {
467     /* set the CRL list file */
468     rc = gnutls_certificate_set_x509_crl_file(conn->ssl[sockindex].cred,
469                                               data->set.ssl.CRLfile,
470                                               GNUTLS_X509_FMT_PEM);
471     if(rc < 0) {
472       failf(data, "error reading crl file %s (%s)",
473             data->set.ssl.CRLfile, gnutls_strerror(rc));
474       return CURLE_SSL_CRL_BADFILE;
475     }
476     else
477       infof(data, "found %d CRL in %s\n",
478             rc, data->set.ssl.CRLfile);
479   }
480
481   /* Initialize TLS session as a client */
482   rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
483   if(rc != GNUTLS_E_SUCCESS) {
484     failf(data, "gnutls_init() failed: %d", rc);
485     return CURLE_SSL_CONNECT_ERROR;
486   }
487
488   /* convenient assign */
489   session = conn->ssl[sockindex].session;
490
491   if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
492 #ifdef ENABLE_IPV6
493      (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
494 #endif
495      sni &&
496      (gnutls_server_name_set(session, GNUTLS_NAME_DNS, conn->host.name,
497                              strlen(conn->host.name)) < 0))
498     infof(data, "WARNING: failed to configure server name indication (SNI) "
499           "TLS extension\n");
500
501   /* Use default priorities */
502   rc = gnutls_set_default_priority(session);
503   if(rc != GNUTLS_E_SUCCESS)
504     return CURLE_SSL_CONNECT_ERROR;
505
506 #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
507   rc = gnutls_cipher_set_priority(session, cipher_priority);
508   if(rc != GNUTLS_E_SUCCESS)
509     return CURLE_SSL_CONNECT_ERROR;
510
511   /* Sets the priority on the certificate types supported by gnutls. Priority
512    is higher for types specified before others. After specifying the types
513    you want, you must append a 0. */
514   rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
515   if(rc != GNUTLS_E_SUCCESS)
516     return CURLE_SSL_CONNECT_ERROR;
517
518   if(data->set.ssl.cipher_list != NULL) {
519     failf(data, "can't pass a custom cipher list to older GnuTLS"
520           " versions");
521     return CURLE_SSL_CONNECT_ERROR;
522   }
523
524   switch (data->set.ssl.version) {
525     case CURL_SSLVERSION_SSLv3:
526       protocol_priority[0] = GNUTLS_SSL3;
527       break;
528     case CURL_SSLVERSION_DEFAULT:
529     case CURL_SSLVERSION_TLSv1:
530       protocol_priority[0] = GNUTLS_TLS1_0;
531       protocol_priority[1] = GNUTLS_TLS1_1;
532       protocol_priority[2] = GNUTLS_TLS1_2;
533       break;
534     case CURL_SSLVERSION_TLSv1_0:
535       protocol_priority[0] = GNUTLS_TLS1_0;
536       break;
537     case CURL_SSLVERSION_TLSv1_1:
538       protocol_priority[0] = GNUTLS_TLS1_1;
539       break;
540     case CURL_SSLVERSION_TLSv1_2:
541       protocol_priority[0] = GNUTLS_TLS1_2;
542     break;
543       case CURL_SSLVERSION_SSLv2:
544     default:
545       failf(data, "GnuTLS does not support SSLv2");
546       return CURLE_SSL_CONNECT_ERROR;
547       break;
548   }
549   rc = gnutls_protocol_set_priority(session, protocol_priority);
550   if(rc != GNUTLS_E_SUCCESS) {
551     failf(data, "Did you pass a valid GnuTLS cipher list?");
552     return CURLE_SSL_CONNECT_ERROR;
553   }
554
555 #else
556   /* Ensure +SRP comes at the *end* of all relevant strings so that it can be
557    * removed if a run-time error indicates that SRP is not supported by this
558    * GnuTLS version */
559   switch (data->set.ssl.version) {
560     case CURL_SSLVERSION_SSLv3:
561       prioritylist = GNUTLS_CIPHERS ":-VERS-TLS-ALL:+VERS-SSL3.0";
562       sni = false;
563       break;
564     case CURL_SSLVERSION_DEFAULT:
565     case CURL_SSLVERSION_TLSv1:
566       prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:" GNUTLS_SRP;
567       break;
568     case CURL_SSLVERSION_TLSv1_0:
569       prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
570                      "+VERS-TLS1.0:" GNUTLS_SRP;
571       break;
572     case CURL_SSLVERSION_TLSv1_1:
573       prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
574                      "+VERS-TLS1.1:" GNUTLS_SRP;
575       break;
576     case CURL_SSLVERSION_TLSv1_2:
577       prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
578                      "+VERS-TLS1.2:" GNUTLS_SRP;
579       break;
580     case CURL_SSLVERSION_SSLv2:
581     default:
582       failf(data, "GnuTLS does not support SSLv2");
583       return CURLE_SSL_CONNECT_ERROR;
584       break;
585   }
586   rc = gnutls_priority_set_direct(session, prioritylist, &err);
587   if((rc == GNUTLS_E_INVALID_REQUEST) && err) {
588     if(!strcmp(err, GNUTLS_SRP)) {
589       /* This GnuTLS was probably compiled without support for SRP.
590        * Note that fact and try again without it. */
591       int validprioritylen = curlx_uztosi(err - prioritylist);
592       char *prioritycopy = strdup(prioritylist);
593       if(!prioritycopy)
594         return CURLE_OUT_OF_MEMORY;
595
596       infof(data, "This GnuTLS does not support SRP\n");
597       if(validprioritylen)
598         /* Remove the :+SRP */
599         prioritycopy[validprioritylen - 1] = 0;
600       rc = gnutls_priority_set_direct(session, prioritycopy, &err);
601       free(prioritycopy);
602     }
603   }
604   if(rc != GNUTLS_E_SUCCESS) {
605     failf(data, "Error %d setting GnuTLS cipher list starting with %s",
606           rc, err);
607     return CURLE_SSL_CONNECT_ERROR;
608   }
609 #endif
610
611 #ifdef HAS_ALPN
612   if(data->set.httpversion == CURL_HTTP_VERSION_2_0) {
613     if(data->set.ssl_enable_alpn) {
614       protocols[0].data = NGHTTP2_PROTO_VERSION_ID;
615       protocols[0].size = NGHTTP2_PROTO_VERSION_ID_LEN;
616       protocols[1].data = ALPN_HTTP_1_1;
617       protocols[1].size = ALPN_HTTP_1_1_LENGTH;
618       gnutls_alpn_set_protocols(session, protocols, protocols_size, 0);
619       infof(data, "ALPN, offering %s, %s\n", NGHTTP2_PROTO_VERSION_ID,
620             ALPN_HTTP_1_1);
621       connssl->asked_for_h2 = TRUE;
622     }
623     else {
624       infof(data, "SSL, can't negotiate HTTP/2.0 without ALPN\n");
625     }
626   }
627 #endif
628
629   if(data->set.str[STRING_CERT]) {
630     if(gnutls_certificate_set_x509_key_file(
631          conn->ssl[sockindex].cred,
632          data->set.str[STRING_CERT],
633          data->set.str[STRING_KEY] ?
634          data->set.str[STRING_KEY] : data->set.str[STRING_CERT],
635          do_file_type(data->set.str[STRING_CERT_TYPE]) ) !=
636        GNUTLS_E_SUCCESS) {
637       failf(data, "error reading X.509 key or certificate file");
638       return CURLE_SSL_CONNECT_ERROR;
639     }
640   }
641
642 #ifdef USE_TLS_SRP
643   /* put the credentials to the current session */
644   if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
645     rc = gnutls_credentials_set(session, GNUTLS_CRD_SRP,
646                                 conn->ssl[sockindex].srp_client_cred);
647     if(rc != GNUTLS_E_SUCCESS)
648       failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
649   }
650   else
651 #endif
652     rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
653                                 conn->ssl[sockindex].cred);
654
655   /* set the connection handle (file descriptor for the socket) */
656   gnutls_transport_set_ptr(session,
657                            GNUTLS_INT_TO_POINTER_CAST(conn->sock[sockindex]));
658
659   /* register callback functions to send and receive data. */
660   gnutls_transport_set_push_function(session, Curl_gtls_push);
661   gnutls_transport_set_pull_function(session, Curl_gtls_pull);
662
663   /* lowat must be set to zero when using custom push and pull functions. */
664   gnutls_transport_set_lowat(session, 0);
665
666   /* This might be a reconnect, so we check for a session ID in the cache
667      to speed up things */
668
669   if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
670     /* we got a session id, use it! */
671     gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);
672
673     /* Informational message */
674     infof (data, "SSL re-using session ID\n");
675   }
676
677   return CURLE_OK;
678 }
679
680 static CURLcode pkp_pin_peer_pubkey(gnutls_x509_crt_t cert,
681                                     const char *pinnedpubkey)
682 {
683   /* Scratch */
684   size_t len1 = 0, len2 = 0;
685   unsigned char *buff1 = NULL;
686
687   gnutls_pubkey_t key = NULL;
688
689   /* Result is returned to caller */
690   int ret = 0;
691   CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
692
693   /* if a path wasn't specified, don't pin */
694   if(NULL == pinnedpubkey)
695     return CURLE_OK;
696
697   if(NULL == cert)
698     return result;
699
700   do {
701     /* Begin Gyrations to get the public key     */
702     gnutls_pubkey_init(&key);
703
704     ret = gnutls_pubkey_import_x509(key, cert, 0);
705     if(ret < 0)
706       break; /* failed */
707
708     ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1);
709     if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0)
710       break; /* failed */
711
712     buff1 = malloc(len1);
713     if(NULL == buff1)
714       break; /* failed */
715
716     len2 = len1;
717
718     ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2);
719     if(ret < 0 || len1 != len2)
720       break; /* failed */
721
722     /* End Gyrations */
723
724     /* The one good exit point */
725     result = Curl_pin_peer_pubkey(pinnedpubkey, buff1, len1);
726   } while(0);
727
728   if(NULL != key)
729     gnutls_pubkey_deinit(key);
730
731   Curl_safefree(buff1);
732
733   return result;
734 }
735
736 static Curl_recv gtls_recv;
737 static Curl_send gtls_send;
738
739 static CURLcode
740 gtls_connect_step3(struct connectdata *conn,
741                    int sockindex)
742 {
743   unsigned int cert_list_size;
744   const gnutls_datum_t *chainp;
745   unsigned int verify_status;
746   gnutls_x509_crt_t x509_cert,x509_issuer;
747   gnutls_datum_t issuerp;
748   char certbuf[256] = ""; /* big enough? */
749   size_t size;
750   unsigned int algo;
751   unsigned int bits;
752   time_t certclock;
753   const char *ptr;
754   struct SessionHandle *data = conn->data;
755   gnutls_session_t session = conn->ssl[sockindex].session;
756   int rc;
757   bool incache;
758   void *ssl_sessionid;
759 #ifdef HAS_ALPN
760   gnutls_datum_t proto;
761 #endif
762   CURLcode result = CURLE_OK;
763
764   /* This function will return the peer's raw certificate (chain) as sent by
765      the peer. These certificates are in raw format (DER encoded for
766      X.509). In case of a X.509 then a certificate list may be present. The
767      first certificate in the list is the peer's certificate, following the
768      issuer's certificate, then the issuer's issuer etc. */
769
770   chainp = gnutls_certificate_get_peers(session, &cert_list_size);
771   if(!chainp) {
772     if(data->set.ssl.verifypeer ||
773        data->set.ssl.verifyhost ||
774        data->set.ssl.issuercert) {
775 #ifdef USE_TLS_SRP
776       if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
777          && data->set.ssl.username != NULL
778          && !data->set.ssl.verifypeer
779          && gnutls_cipher_get(session)) {
780         /* no peer cert, but auth is ok if we have SRP user and cipher and no
781            peer verify */
782       }
783       else {
784 #endif
785         failf(data, "failed to get server cert");
786         return CURLE_PEER_FAILED_VERIFICATION;
787 #ifdef USE_TLS_SRP
788       }
789 #endif
790     }
791     infof(data, "\t common name: WARNING couldn't obtain\n");
792   }
793
794   if(data->set.ssl.verifypeer) {
795     /* This function will try to verify the peer's certificate and return its
796        status (trusted, invalid etc.). The value of status should be one or
797        more of the gnutls_certificate_status_t enumerated elements bitwise
798        or'd. To avoid denial of service attacks some default upper limits
799        regarding the certificate key size and chain size are set. To override
800        them use gnutls_certificate_set_verify_limits(). */
801
802     rc = gnutls_certificate_verify_peers2(session, &verify_status);
803     if(rc < 0) {
804       failf(data, "server cert verify failed: %d", rc);
805       return CURLE_SSL_CONNECT_ERROR;
806     }
807
808     /* verify_status is a bitmask of gnutls_certificate_status bits */
809     if(verify_status & GNUTLS_CERT_INVALID) {
810       if(data->set.ssl.verifypeer) {
811         failf(data, "server certificate verification failed. CAfile: %s "
812               "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
813               data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
814         return CURLE_SSL_CACERT;
815       }
816       else
817         infof(data, "\t server certificate verification FAILED\n");
818     }
819     else
820       infof(data, "\t server certificate verification OK\n");
821   }
822   else
823     infof(data, "\t server certificate verification SKIPPED\n");
824
825   /* initialize an X.509 certificate structure. */
826   gnutls_x509_crt_init(&x509_cert);
827
828   if(chainp)
829     /* convert the given DER or PEM encoded Certificate to the native
830        gnutls_x509_crt_t format */
831     gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
832
833   if(data->set.ssl.issuercert) {
834     gnutls_x509_crt_init(&x509_issuer);
835     issuerp = load_file(data->set.ssl.issuercert);
836     gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
837     rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
838     gnutls_x509_crt_deinit(x509_issuer);
839     unload_file(issuerp);
840     if(rc <= 0) {
841       failf(data, "server certificate issuer check failed (IssuerCert: %s)",
842             data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
843       gnutls_x509_crt_deinit(x509_cert);
844       return CURLE_SSL_ISSUER_ERROR;
845     }
846     infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
847           data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
848   }
849
850   size=sizeof(certbuf);
851   rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
852                                      0, /* the first and only one */
853                                      FALSE,
854                                      certbuf,
855                                      &size);
856   if(rc) {
857     infof(data, "error fetching CN from cert:%s\n",
858           gnutls_strerror(rc));
859   }
860
861   /* This function will check if the given certificate's subject matches the
862      given hostname. This is a basic implementation of the matching described
863      in RFC2818 (HTTPS), which takes into account wildcards, and the subject
864      alternative name PKIX extension. Returns non zero on success, and zero on
865      failure. */
866   rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
867 #if GNUTLS_VERSION_NUMBER < 0x030306
868   /* Before 3.3.6, gnutls_x509_crt_check_hostname() didn't check IP
869      addresses. */
870   if(!rc) {
871 #ifdef ENABLE_IPV6
872     #define use_addr in6_addr
873 #else
874     #define use_addr in_addr
875 #endif
876     unsigned char addrbuf[sizeof(struct use_addr)];
877     unsigned char certaddr[sizeof(struct use_addr)];
878     size_t addrlen = 0, certaddrlen;
879     int i;
880     int ret = 0;
881
882     if(Curl_inet_pton(AF_INET, conn->host.name, addrbuf) > 0)
883       addrlen = 4;
884 #ifdef ENABLE_IPV6
885     else if(Curl_inet_pton(AF_INET6, conn->host.name, addrbuf) > 0)
886       addrlen = 16;
887 #endif
888
889     if(addrlen) {
890       for(i=0; ; i++) {
891         certaddrlen = sizeof(certaddr);
892         ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
893                                                    &certaddrlen, NULL);
894         /* If this happens, it wasn't an IP address. */
895         if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
896           continue;
897         if(ret < 0)
898           break;
899         if(ret != GNUTLS_SAN_IPADDRESS)
900           continue;
901         if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) {
902           rc = 1;
903           break;
904         }
905       }
906     }
907   }
908 #endif
909   if(!rc) {
910     if(data->set.ssl.verifyhost) {
911       failf(data, "SSL: certificate subject name (%s) does not match "
912             "target host name '%s'", certbuf, conn->host.dispname);
913       gnutls_x509_crt_deinit(x509_cert);
914       return CURLE_PEER_FAILED_VERIFICATION;
915     }
916     else
917       infof(data, "\t common name: %s (does not match '%s')\n",
918             certbuf, conn->host.dispname);
919   }
920   else
921     infof(data, "\t common name: %s (matched)\n", certbuf);
922
923   /* Check for time-based validity */
924   certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
925
926   if(certclock == (time_t)-1) {
927     if(data->set.ssl.verifypeer) {
928       failf(data, "server cert expiration date verify failed");
929       gnutls_x509_crt_deinit(x509_cert);
930       return CURLE_SSL_CONNECT_ERROR;
931     }
932     else
933       infof(data, "\t server certificate expiration date verify FAILED\n");
934   }
935   else {
936     if(certclock < time(NULL)) {
937       if(data->set.ssl.verifypeer) {
938         failf(data, "server certificate expiration date has passed.");
939         gnutls_x509_crt_deinit(x509_cert);
940         return CURLE_PEER_FAILED_VERIFICATION;
941       }
942       else
943         infof(data, "\t server certificate expiration date FAILED\n");
944     }
945     else
946       infof(data, "\t server certificate expiration date OK\n");
947   }
948
949   certclock = gnutls_x509_crt_get_activation_time(x509_cert);
950
951   if(certclock == (time_t)-1) {
952     if(data->set.ssl.verifypeer) {
953       failf(data, "server cert activation date verify failed");
954       gnutls_x509_crt_deinit(x509_cert);
955       return CURLE_SSL_CONNECT_ERROR;
956     }
957     else
958       infof(data, "\t server certificate activation date verify FAILED\n");
959   }
960   else {
961     if(certclock > time(NULL)) {
962       if(data->set.ssl.verifypeer) {
963         failf(data, "server certificate not activated yet.");
964         gnutls_x509_crt_deinit(x509_cert);
965         return CURLE_PEER_FAILED_VERIFICATION;
966       }
967       else
968         infof(data, "\t server certificate activation date FAILED\n");
969     }
970     else
971       infof(data, "\t server certificate activation date OK\n");
972   }
973
974   ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
975   if(ptr) {
976     result = pkp_pin_peer_pubkey(x509_cert, ptr);
977     if(result != CURLE_OK) {
978       failf(data, "SSL: public key does not match pinned public key!");
979       gnutls_x509_crt_deinit(x509_cert);
980       return result;
981     }
982   }
983
984   /* Show:
985
986   - ciphers used
987   - subject
988   - start date
989   - expire date
990   - common name
991   - issuer
992
993   */
994
995   /* public key algorithm's parameters */
996   algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
997   infof(data, "\t certificate public key: %s\n",
998         gnutls_pk_algorithm_get_name(algo));
999
1000   /* version of the X.509 certificate. */
1001   infof(data, "\t certificate version: #%d\n",
1002         gnutls_x509_crt_get_version(x509_cert));
1003
1004
1005   size = sizeof(certbuf);
1006   gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
1007   infof(data, "\t subject: %s\n", certbuf);
1008
1009   certclock = gnutls_x509_crt_get_activation_time(x509_cert);
1010   showtime(data, "start date", certclock);
1011
1012   certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
1013   showtime(data, "expire date", certclock);
1014
1015   size = sizeof(certbuf);
1016   gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
1017   infof(data, "\t issuer: %s\n", certbuf);
1018
1019   gnutls_x509_crt_deinit(x509_cert);
1020
1021   /* compression algorithm (if any) */
1022   ptr = gnutls_compression_get_name(gnutls_compression_get(session));
1023   /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
1024   infof(data, "\t compression: %s\n", ptr);
1025
1026   /* the name of the cipher used. ie 3DES. */
1027   ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
1028   infof(data, "\t cipher: %s\n", ptr);
1029
1030   /* the MAC algorithms name. ie SHA1 */
1031   ptr = gnutls_mac_get_name(gnutls_mac_get(session));
1032   infof(data, "\t MAC: %s\n", ptr);
1033
1034 #ifdef HAS_ALPN
1035   if(data->set.ssl_enable_alpn) {
1036     rc = gnutls_alpn_get_selected_protocol(session, &proto);
1037     if(rc == 0) {
1038       infof(data, "ALPN, server accepted to use %.*s\n", proto.size,
1039           proto.data);
1040
1041       if(proto.size == NGHTTP2_PROTO_VERSION_ID_LEN &&
1042         memcmp(NGHTTP2_PROTO_VERSION_ID, proto.data,
1043         NGHTTP2_PROTO_VERSION_ID_LEN) == 0) {
1044         conn->negnpn = NPN_HTTP2;
1045       }
1046       else if(proto.size == ALPN_HTTP_1_1_LENGTH && memcmp(ALPN_HTTP_1_1,
1047           proto.data, ALPN_HTTP_1_1_LENGTH) == 0) {
1048         conn->negnpn = NPN_HTTP1_1;
1049       }
1050     }
1051     else if(connssl->asked_for_h2) {
1052       infof(data, "ALPN, server did not agree to a protocol\n");
1053     }
1054   }
1055 #endif
1056
1057   conn->ssl[sockindex].state = ssl_connection_complete;
1058   conn->recv[sockindex] = gtls_recv;
1059   conn->send[sockindex] = gtls_send;
1060
1061   {
1062     /* we always unconditionally get the session id here, as even if we
1063        already got it from the cache and asked to use it in the connection, it
1064        might've been rejected and then a new one is in use now and we need to
1065        detect that. */
1066     void *connect_sessionid;
1067     size_t connect_idsize = 0;
1068
1069     /* get the session ID data size */
1070     gnutls_session_get_data(session, NULL, &connect_idsize);
1071     connect_sessionid = malloc(connect_idsize); /* get a buffer for it */
1072
1073     if(connect_sessionid) {
1074       /* extract session ID to the allocated buffer */
1075       gnutls_session_get_data(session, connect_sessionid, &connect_idsize);
1076
1077       incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
1078       if(incache) {
1079         /* there was one before in the cache, so instead of risking that the
1080            previous one was rejected, we just kill that and store the new */
1081         Curl_ssl_delsessionid(conn, ssl_sessionid);
1082       }
1083
1084       /* store this session id */
1085       result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
1086       if(result) {
1087         free(connect_sessionid);
1088         result = CURLE_OUT_OF_MEMORY;
1089       }
1090     }
1091     else
1092       result = CURLE_OUT_OF_MEMORY;
1093   }
1094
1095   return result;
1096 }
1097
1098
1099 /*
1100  * This function is called after the TCP connect has completed. Setup the TLS
1101  * layer and do all necessary magic.
1102  */
1103 /* We use connssl->connecting_state to keep track of the connection status;
1104    there are three states: 'ssl_connect_1' (not started yet or complete),
1105    'ssl_connect_2_reading' (waiting for data from server), and
1106    'ssl_connect_2_writing' (waiting to be able to write).
1107  */
1108 static CURLcode
1109 gtls_connect_common(struct connectdata *conn,
1110                     int sockindex,
1111                     bool nonblocking,
1112                     bool *done)
1113 {
1114   int rc;
1115   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1116
1117   /* Initiate the connection, if not already done */
1118   if(ssl_connect_1==connssl->connecting_state) {
1119     rc = gtls_connect_step1 (conn, sockindex);
1120     if(rc)
1121       return rc;
1122   }
1123
1124   rc = handshake(conn, sockindex, TRUE, nonblocking);
1125   if(rc)
1126     /* handshake() sets its own error message with failf() */
1127     return rc;
1128
1129   /* Finish connecting once the handshake is done */
1130   if(ssl_connect_1==connssl->connecting_state) {
1131     rc = gtls_connect_step3(conn, sockindex);
1132     if(rc)
1133       return rc;
1134   }
1135
1136   *done = ssl_connect_1==connssl->connecting_state;
1137
1138   return CURLE_OK;
1139 }
1140
1141 CURLcode
1142 Curl_gtls_connect_nonblocking(struct connectdata *conn,
1143                               int sockindex,
1144                               bool *done)
1145 {
1146   return gtls_connect_common(conn, sockindex, TRUE, done);
1147 }
1148
1149 CURLcode
1150 Curl_gtls_connect(struct connectdata *conn,
1151                   int sockindex)
1152
1153 {
1154   CURLcode result;
1155   bool done = FALSE;
1156
1157   result = gtls_connect_common(conn, sockindex, FALSE, &done);
1158   if(result)
1159     return result;
1160
1161   DEBUGASSERT(done);
1162
1163   return CURLE_OK;
1164 }
1165
1166 static ssize_t gtls_send(struct connectdata *conn,
1167                          int sockindex,
1168                          const void *mem,
1169                          size_t len,
1170                          CURLcode *curlcode)
1171 {
1172   ssize_t rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
1173
1174   if(rc < 0 ) {
1175     *curlcode = (rc == GNUTLS_E_AGAIN)
1176       ? CURLE_AGAIN
1177       : CURLE_SEND_ERROR;
1178
1179     rc = -1;
1180   }
1181
1182   return rc;
1183 }
1184
1185 void Curl_gtls_close_all(struct SessionHandle *data)
1186 {
1187   /* FIX: make the OpenSSL code more generic and use parts of it here */
1188   (void)data;
1189 }
1190
1191 static void close_one(struct connectdata *conn,
1192                       int idx)
1193 {
1194   if(conn->ssl[idx].session) {
1195     gnutls_bye(conn->ssl[idx].session, GNUTLS_SHUT_RDWR);
1196     gnutls_deinit(conn->ssl[idx].session);
1197     conn->ssl[idx].session = NULL;
1198   }
1199   if(conn->ssl[idx].cred) {
1200     gnutls_certificate_free_credentials(conn->ssl[idx].cred);
1201     conn->ssl[idx].cred = NULL;
1202   }
1203 #ifdef USE_TLS_SRP
1204   if(conn->ssl[idx].srp_client_cred) {
1205     gnutls_srp_free_client_credentials(conn->ssl[idx].srp_client_cred);
1206     conn->ssl[idx].srp_client_cred = NULL;
1207   }
1208 #endif
1209 }
1210
1211 void Curl_gtls_close(struct connectdata *conn, int sockindex)
1212 {
1213   close_one(conn, sockindex);
1214 }
1215
1216 /*
1217  * This function is called to shut down the SSL layer but keep the
1218  * socket open (CCC - Clear Command Channel)
1219  */
1220 int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
1221 {
1222   ssize_t result;
1223   int retval = 0;
1224   struct SessionHandle *data = conn->data;
1225   int done = 0;
1226   char buf[120];
1227
1228   /* This has only been tested on the proftpd server, and the mod_tls code
1229      sends a close notify alert without waiting for a close notify alert in
1230      response. Thus we wait for a close notify alert from the server, but
1231      we do not send one. Let's hope other servers do the same... */
1232
1233   if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
1234       gnutls_bye(conn->ssl[sockindex].session, GNUTLS_SHUT_WR);
1235
1236   if(conn->ssl[sockindex].session) {
1237     while(!done) {
1238       int what = Curl_socket_ready(conn->sock[sockindex],
1239                                    CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
1240       if(what > 0) {
1241         /* Something to read, let's do it and hope that it is the close
1242            notify alert from the server */
1243         result = gnutls_record_recv(conn->ssl[sockindex].session,
1244                                     buf, sizeof(buf));
1245         switch(result) {
1246         case 0:
1247           /* This is the expected response. There was no data but only
1248              the close notify alert */
1249           done = 1;
1250           break;
1251         case GNUTLS_E_AGAIN:
1252         case GNUTLS_E_INTERRUPTED:
1253           infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED\n");
1254           break;
1255         default:
1256           retval = -1;
1257           done = 1;
1258           break;
1259         }
1260       }
1261       else if(0 == what) {
1262         /* timeout */
1263         failf(data, "SSL shutdown timeout");
1264         done = 1;
1265         break;
1266       }
1267       else {
1268         /* anything that gets here is fatally bad */
1269         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1270         retval = -1;
1271         done = 1;
1272       }
1273     }
1274     gnutls_deinit(conn->ssl[sockindex].session);
1275   }
1276   gnutls_certificate_free_credentials(conn->ssl[sockindex].cred);
1277
1278 #ifdef USE_TLS_SRP
1279   if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
1280      && data->set.ssl.username != NULL)
1281     gnutls_srp_free_client_credentials(conn->ssl[sockindex].srp_client_cred);
1282 #endif
1283
1284   conn->ssl[sockindex].cred = NULL;
1285   conn->ssl[sockindex].session = NULL;
1286
1287   return retval;
1288 }
1289
1290 static ssize_t gtls_recv(struct connectdata *conn, /* connection data */
1291                          int num,                  /* socketindex */
1292                          char *buf,                /* store read data here */
1293                          size_t buffersize,        /* max amount to read */
1294                          CURLcode *curlcode)
1295 {
1296   ssize_t ret;
1297
1298   ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
1299   if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
1300     *curlcode = CURLE_AGAIN;
1301     return -1;
1302   }
1303
1304   if(ret == GNUTLS_E_REHANDSHAKE) {
1305     /* BLOCKING call, this is bad but a work-around for now. Fixing this "the
1306        proper way" takes a whole lot of work. */
1307     CURLcode result = handshake(conn, num, FALSE, FALSE);
1308     if(result)
1309       /* handshake() writes error message on its own */
1310       *curlcode = result;
1311     else
1312       *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
1313     return -1;
1314   }
1315
1316   if(ret < 0) {
1317     failf(conn->data, "GnuTLS recv error (%d): %s",
1318           (int)ret, gnutls_strerror((int)ret));
1319     *curlcode = CURLE_RECV_ERROR;
1320     return -1;
1321   }
1322
1323   return ret;
1324 }
1325
1326 void Curl_gtls_session_free(void *ptr)
1327 {
1328   free(ptr);
1329 }
1330
1331 size_t Curl_gtls_version(char *buffer, size_t size)
1332 {
1333   return snprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
1334 }
1335
1336 #ifndef USE_GNUTLS_NETTLE
1337 static int Curl_gtls_seed(struct SessionHandle *data)
1338 {
1339   /* we have the "SSL is seeded" boolean static to prevent multiple
1340      time-consuming seedings in vain */
1341   static bool ssl_seeded = FALSE;
1342
1343   /* Quickly add a bit of entropy */
1344   gcry_fast_random_poll();
1345
1346   if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
1347      data->set.str[STRING_SSL_EGDSOCKET]) {
1348
1349     /* TODO: to a good job seeding the RNG
1350        This may involve the gcry_control function and these options:
1351        GCRYCTL_SET_RANDOM_SEED_FILE
1352        GCRYCTL_SET_RNDEGD_SOCKET
1353     */
1354     ssl_seeded = TRUE;
1355   }
1356   return 0;
1357 }
1358 #endif
1359
1360 /* data might be NULL! */
1361 int Curl_gtls_random(struct SessionHandle *data,
1362                      unsigned char *entropy,
1363                      size_t length)
1364 {
1365 #if defined(USE_GNUTLS_NETTLE)
1366   (void)data;
1367   gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length);
1368 #elif defined(USE_GNUTLS)
1369   if(data)
1370     Curl_gtls_seed(data); /* Initiate the seed if not already done */
1371   gcry_randomize(entropy, length, GCRY_STRONG_RANDOM);
1372 #endif
1373   return 0;
1374 }
1375
1376 void Curl_gtls_md5sum(unsigned char *tmp, /* input */
1377                       size_t tmplen,
1378                       unsigned char *md5sum, /* output */
1379                       size_t md5len)
1380 {
1381 #if defined(USE_GNUTLS_NETTLE)
1382   struct md5_ctx MD5pw;
1383   md5_init(&MD5pw);
1384   md5_update(&MD5pw, (unsigned int)tmplen, tmp);
1385   md5_digest(&MD5pw, (unsigned int)md5len, md5sum);
1386 #elif defined(USE_GNUTLS)
1387   gcry_md_hd_t MD5pw;
1388   gcry_md_open(&MD5pw, GCRY_MD_MD5, 0);
1389   gcry_md_write(MD5pw, tmp, tmplen);
1390   memcpy(md5sum, gcry_md_read (MD5pw, 0), md5len);
1391   gcry_md_close(MD5pw);
1392 #endif
1393 }
1394
1395 #endif /* USE_GNUTLS */