]> rtime.felk.cvut.cz Git - hornmich/skoda-qr-demo.git/blob - QRScanner/mobile/jni/thirdparty/curl/lib/gtls.c
Add MuPDF native source codes
[hornmich/skoda-qr-demo.git] / QRScanner / mobile / jni / thirdparty / curl / lib / gtls.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2012, 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 sslgen.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 "sslgen.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 #endif
93
94 /*
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
98  * curl_setup_once.h).
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.
102  *
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.
112  *
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.
116  */
117
118 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
119 #  define gtls_EINTR  4
120 #  define gtls_EIO    5
121 #  define gtls_EAGAIN 11
122 static int gtls_mapped_sockerrno(void)
123 {
124   switch(SOCKERRNO) {
125   case WSAEWOULDBLOCK:
126     return gtls_EAGAIN;
127   case WSAEINTR:
128     return gtls_EINTR;
129   default:
130     break;
131   }
132   return gtls_EIO;
133 }
134 #endif
135
136 static ssize_t Curl_gtls_push(void *s, const void *buf, size_t len)
137 {
138   ssize_t ret = swrite(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
139 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
140   if(ret < 0)
141     gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
142 #endif
143   return ret;
144 }
145
146 static ssize_t Curl_gtls_pull(void *s, void *buf, size_t len)
147 {
148   ssize_t ret = sread(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
149 #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
150   if(ret < 0)
151     gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
152 #endif
153   return ret;
154 }
155
156 /* Curl_gtls_init()
157  *
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!
162  */
163 int Curl_gtls_init(void)
164 {
165   int ret = 1;
166   if(!gtls_inited) {
167     ret = gnutls_global_init()?0:1;
168 #ifdef GTLSDEBUG
169     gnutls_global_set_log_function(tls_log_func);
170     gnutls_global_set_log_level(2);
171 #endif
172     gtls_inited = TRUE;
173   }
174   return ret;
175 }
176
177 int Curl_gtls_cleanup(void)
178 {
179   if(gtls_inited) {
180     gnutls_global_deinit();
181     gtls_inited = FALSE;
182   }
183   return 1;
184 }
185
186 static void showtime(struct SessionHandle *data,
187                      const char *text,
188                      time_t stamp)
189 {
190   struct tm buffer;
191   const struct tm *tm = &buffer;
192   CURLcode result = Curl_gmtime(stamp, &buffer);
193   if(result)
194     return;
195
196   snprintf(data->state.buffer,
197            BUFSIZE,
198            "\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT\n",
199            text,
200            Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
201            tm->tm_mday,
202            Curl_month[tm->tm_mon],
203            tm->tm_year + 1900,
204            tm->tm_hour,
205            tm->tm_min,
206            tm->tm_sec);
207   infof(data, "%s\n", data->state.buffer);
208 }
209
210 static gnutls_datum load_file (const char *file)
211 {
212   FILE *f;
213   gnutls_datum loaded_file = { NULL, 0 };
214   long filelen;
215   void *ptr;
216
217   if(!(f = fopen(file, "r")))
218     return loaded_file;
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)))
223     goto out;
224   if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) {
225     free(ptr);
226     goto out;
227   }
228
229   loaded_file.data = ptr;
230   loaded_file.size = (unsigned int)filelen;
231 out:
232   fclose(f);
233   return loaded_file;
234 }
235
236 static void unload_file(gnutls_datum data) {
237   free(data.data);
238 }
239
240
241 /* this function does a SSL/TLS (re-)handshake */
242 static CURLcode handshake(struct connectdata *conn,
243                           int sockindex,
244                           bool duringconnect,
245                           bool nonblocking)
246 {
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];
251   long timeout_ms;
252   int rc;
253   int what;
254
255   for(;;) {
256     /* check allowed time left */
257     timeout_ms = Curl_timeleft(data, NULL, duringconnect);
258
259     if(timeout_ms < 0) {
260       /* no need to continue if time already is up */
261       failf(data, "SSL connection timeout");
262       return CURLE_OPERATION_TIMEDOUT;
263     }
264
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) {
268
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;
273
274       what = Curl_socket_ready(readfd, writefd,
275                                nonblocking?0:
276                                timeout_ms?timeout_ms:1000);
277       if(what < 0) {
278         /* fatal error */
279         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
280         return CURLE_SSL_CONNECT_ERROR;
281       }
282       else if(0 == what) {
283         if(nonblocking)
284           return CURLE_OK;
285         else if(timeout_ms) {
286           /* timeout */
287           failf(data, "SSL connection timeout at %ld", timeout_ms);
288           return CURLE_OPERATION_TIMEDOUT;
289         }
290       }
291       /* socket is readable or writable */
292     }
293
294     rc = gnutls_handshake(session);
295
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;
300       continue;
301       if(nonblocking)
302         return CURLE_OK;
303     }
304     else if((rc < 0) && !gnutls_error_is_fatal(rc)) {
305       const char *strerr = NULL;
306
307       if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) {
308         int alert = gnutls_alert_get(session);
309         strerr = gnutls_alert_get_name(alert);
310       }
311
312       if(strerr == NULL)
313         strerr = gnutls_strerror(rc);
314
315       failf(data, "gnutls_handshake() warning: %s", strerr);
316     }
317     else if(rc < 0) {
318       const char *strerr = NULL;
319
320       if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) {
321         int alert = gnutls_alert_get(session);
322         strerr = gnutls_alert_get_name(alert);
323       }
324
325       if(strerr == NULL)
326         strerr = gnutls_strerror(rc);
327
328       failf(data, "gnutls_handshake() failed: %s", strerr);
329       return CURLE_SSL_CONNECT_ERROR;
330     }
331
332     /* Reset our connect state machine */
333     connssl->connecting_state = ssl_connect_1;
334     return CURLE_OK;
335   }
336 }
337
338 static gnutls_x509_crt_fmt do_file_type(const char *type)
339 {
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;
346   return -1;
347 }
348
349 static CURLcode
350 gtls_connect_step1(struct connectdata *conn,
351                    int sockindex)
352 {
353 #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
354   static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
355 #endif
356   struct SessionHandle *data = conn->data;
357   gnutls_session session;
358   int rc;
359   void *ssl_sessionid;
360   size_t ssl_idsize;
361   bool sni = TRUE; /* default is SNI enabled */
362 #ifdef ENABLE_IPV6
363   struct in6_addr addr;
364 #else
365   struct in_addr addr;
366 #endif
367
368   if(conn->ssl[sockindex].state == ssl_connection_complete)
369     /* to make us tolerant against being called more than once for the
370        same connection */
371     return CURLE_OK;
372
373   if(!gtls_inited)
374     Curl_gtls_init();
375
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;
380   }
381   else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
382     sni = FALSE; /* SSLv3 has no SNI */
383
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;
389   }
390
391 #ifdef USE_TLS_SRP
392   if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
393     infof(data, "Using TLS-SRP username: %s\n", data->set.ssl.username);
394
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;
401     }
402
403     rc = gnutls_srp_set_client_credentials(conn->ssl[sockindex].
404                                            srp_client_cred,
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;
411     }
412   }
413 #endif
414
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);
419
420     rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
421                                                 data->set.ssl.CAfile,
422                                                 GNUTLS_X509_FMT_PEM);
423     if(rc < 0) {
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;
428     }
429     else
430       infof(data, "found %d certificates in %s\n",
431             rc, data->set.ssl.CAfile);
432   }
433
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);
439     if(rc < 0) {
440       failf(data, "error reading crl file %s (%s)",
441             data->set.ssl.CRLfile, gnutls_strerror(rc));
442       return CURLE_SSL_CRL_BADFILE;
443     }
444     else
445       infof(data, "found %d CRL in %s\n",
446             rc, data->set.ssl.CRLfile);
447   }
448
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;
454   }
455
456   /* convenient assign */
457   session = conn->ssl[sockindex].session;
458
459   if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
460 #ifdef ENABLE_IPV6
461      (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
462 #endif
463      sni &&
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) "
467           "TLS extension\n");
468
469   /* Use default priorities */
470   rc = gnutls_set_default_priority(session);
471   if(rc != GNUTLS_E_SUCCESS)
472     return CURLE_SSL_CONNECT_ERROR;
473
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);
478 #else
479     const char *err;
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
482        asks for that
483     */
484     rc = gnutls_priority_set_direct(session,
485                                     "NORMAL:-VERS-TLS-ALL:+VERS-SSL3.0:"
486                                     "-CIPHER-ALL:+ARCFOUR-128",
487                                     &err);
488 #endif
489     if(rc != GNUTLS_E_SUCCESS)
490       return CURLE_SSL_CONNECT_ERROR;
491   }
492
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;
500 #endif
501
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]) ) !=
509        GNUTLS_E_SUCCESS) {
510       failf(data, "error reading X.509 key or certificate file");
511       return CURLE_SSL_CONNECT_ERROR;
512     }
513   }
514
515 #ifdef USE_TLS_SRP
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));
522   }
523   else
524 #endif
525     rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
526                                 conn->ssl[sockindex].cred);
527
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]));
531
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);
535
536   /* lowat must be set to zero when using custom push and pull functions. */
537   gnutls_transport_set_lowat(session, 0);
538
539   /* This might be a reconnect, so we check for a session ID in the cache
540      to speed up things */
541
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);
545
546     /* Informational message */
547     infof (data, "SSL re-using session ID\n");
548   }
549
550   return CURLE_OK;
551 }
552
553 static Curl_recv gtls_recv;
554 static Curl_send gtls_send;
555
556 static CURLcode
557 gtls_connect_step3(struct connectdata *conn,
558                    int sockindex)
559 {
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? */
566   size_t size;
567   unsigned int algo;
568   unsigned int bits;
569   time_t certclock;
570   const char *ptr;
571   struct SessionHandle *data = conn->data;
572   gnutls_session session = conn->ssl[sockindex].session;
573   int rc;
574   int incache;
575   void *ssl_sessionid;
576   CURLcode result = CURLE_OK;
577
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. */
583
584   chainp = gnutls_certificate_get_peers(session, &cert_list_size);
585   if(!chainp) {
586     if(data->set.ssl.verifypeer ||
587        data->set.ssl.verifyhost ||
588        data->set.ssl.issuercert) {
589 #ifdef USE_TLS_SRP
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
595            peer verify */
596       }
597       else {
598 #endif
599         failf(data, "failed to get server cert");
600         return CURLE_PEER_FAILED_VERIFICATION;
601 #ifdef USE_TLS_SRP
602       }
603 #endif
604     }
605     infof(data, "\t common name: WARNING couldn't obtain\n");
606   }
607
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(). */
615
616     rc = gnutls_certificate_verify_peers2(session, &verify_status);
617     if(rc < 0) {
618       failf(data, "server cert verify failed: %d", rc);
619       return CURLE_SSL_CONNECT_ERROR;
620     }
621
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;
629       }
630       else
631         infof(data, "\t server certificate verification FAILED\n");
632     }
633     else
634       infof(data, "\t server certificate verification OK\n");
635   }
636   else {
637     infof(data, "\t server certificate verification SKIPPED\n");
638     goto after_server_cert_verification;
639   }
640
641   /* initialize an X.509 certificate structure. */
642   gnutls_x509_crt_init(&x509_cert);
643
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);
647
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);
654     if(rc <= 0) {
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;
658     }
659     infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
660           data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
661   }
662
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 */
666                                      FALSE,
667                                      certbuf,
668                                      &size);
669   if(rc) {
670     infof(data, "error fetching CN from cert:%s\n",
671           gnutls_strerror(rc));
672   }
673
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
678      failure. */
679   rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
680
681   if(!rc) {
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;
687     }
688     else
689       infof(data, "\t common name: %s (does not match '%s')\n",
690             certbuf, conn->host.dispname);
691   }
692   else
693     infof(data, "\t common name: %s (matched)\n", certbuf);
694
695   /* Check for time-based validity */
696   certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
697
698   if(certclock == (time_t)-1) {
699     failf(data, "server cert expiration date verify failed");
700     return CURLE_SSL_CONNECT_ERROR;
701   }
702
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;
707     }
708     else
709       infof(data, "\t server certificate expiration date FAILED\n");
710   }
711   else
712     infof(data, "\t server certificate expiration date OK\n");
713
714   certclock = gnutls_x509_crt_get_activation_time(x509_cert);
715
716   if(certclock == (time_t)-1) {
717     failf(data, "server cert activation date verify failed");
718     return CURLE_SSL_CONNECT_ERROR;
719   }
720
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;
725     }
726     else
727       infof(data, "\t server certificate activation date FAILED\n");
728   }
729   else
730     infof(data, "\t server certificate activation date OK\n");
731
732   /* Show:
733
734   - ciphers used
735   - subject
736   - start date
737   - expire date
738   - common name
739   - issuer
740
741   */
742
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));
747
748   /* version of the X.509 certificate. */
749   infof(data, "\t certificate version: #%d\n",
750         gnutls_x509_crt_get_version(x509_cert));
751
752
753   size = sizeof(certbuf);
754   gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
755   infof(data, "\t subject: %s\n", certbuf);
756
757   certclock = gnutls_x509_crt_get_activation_time(x509_cert);
758   showtime(data, "start date", certclock);
759
760   certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
761   showtime(data, "expire date", certclock);
762
763   size = sizeof(certbuf);
764   gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
765   infof(data, "\t issuer: %s\n", certbuf);
766
767   gnutls_x509_crt_deinit(x509_cert);
768
769 after_server_cert_verification:
770
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);
775
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);
779
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);
783
784   conn->ssl[sockindex].state = ssl_connection_complete;
785   conn->recv[sockindex] = gtls_recv;
786   conn->send[sockindex] = gtls_send;
787
788   {
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
792        detect that. */
793     void *connect_sessionid;
794     size_t connect_idsize;
795
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 */
799
800     if(connect_sessionid) {
801       /* extract session ID to the allocated buffer */
802       gnutls_session_get_data(session, connect_sessionid, &connect_idsize);
803
804       incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
805       if(incache) {
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);
809       }
810
811       /* store this session id */
812       result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
813       if(result) {
814         free(connect_sessionid);
815         result = CURLE_OUT_OF_MEMORY;
816       }
817     }
818     else
819       result = CURLE_OUT_OF_MEMORY;
820   }
821
822   return result;
823 }
824
825
826 /*
827  * This function is called after the TCP connect has completed. Setup the TLS
828  * layer and do all necessary magic.
829  */
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).
834  */
835 static CURLcode
836 gtls_connect_common(struct connectdata *conn,
837                     int sockindex,
838                     bool nonblocking,
839                     bool *done)
840 {
841   int rc;
842   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
843
844   /* Initiate the connection, if not already done */
845   if(ssl_connect_1==connssl->connecting_state) {
846     rc = gtls_connect_step1 (conn, sockindex);
847     if(rc)
848       return rc;
849   }
850
851   rc = handshake(conn, sockindex, TRUE, nonblocking);
852   if(rc)
853     /* handshake() sets its own error message with failf() */
854     return rc;
855
856   /* Finish connecting once the handshake is done */
857   if(ssl_connect_1==connssl->connecting_state) {
858     rc = gtls_connect_step3(conn, sockindex);
859     if(rc)
860       return rc;
861   }
862
863   *done = ssl_connect_1==connssl->connecting_state;
864
865   return CURLE_OK;
866 }
867
868 CURLcode
869 Curl_gtls_connect_nonblocking(struct connectdata *conn,
870                               int sockindex,
871                               bool *done)
872 {
873   return gtls_connect_common(conn, sockindex, TRUE, done);
874 }
875
876 CURLcode
877 Curl_gtls_connect(struct connectdata *conn,
878                   int sockindex)
879
880 {
881   CURLcode retcode;
882   bool done = FALSE;
883
884   retcode = gtls_connect_common(conn, sockindex, FALSE, &done);
885   if(retcode)
886     return retcode;
887
888   DEBUGASSERT(done);
889
890   return CURLE_OK;
891 }
892
893 static ssize_t gtls_send(struct connectdata *conn,
894                          int sockindex,
895                          const void *mem,
896                          size_t len,
897                          CURLcode *curlcode)
898 {
899   ssize_t rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
900
901   if(rc < 0 ) {
902     *curlcode = (rc == GNUTLS_E_AGAIN)
903       ? CURLE_AGAIN
904       : CURLE_SEND_ERROR;
905
906     rc = -1;
907   }
908
909   return rc;
910 }
911
912 void Curl_gtls_close_all(struct SessionHandle *data)
913 {
914   /* FIX: make the OpenSSL code more generic and use parts of it here */
915   (void)data;
916 }
917
918 static void close_one(struct connectdata *conn,
919                       int idx)
920 {
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;
925   }
926   if(conn->ssl[idx].cred) {
927     gnutls_certificate_free_credentials(conn->ssl[idx].cred);
928     conn->ssl[idx].cred = NULL;
929   }
930 #ifdef USE_TLS_SRP
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;
934   }
935 #endif
936 }
937
938 void Curl_gtls_close(struct connectdata *conn, int sockindex)
939 {
940   close_one(conn, sockindex);
941 }
942
943 /*
944  * This function is called to shut down the SSL layer but keep the
945  * socket open (CCC - Clear Command Channel)
946  */
947 int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
948 {
949   ssize_t result;
950   int retval = 0;
951   struct SessionHandle *data = conn->data;
952   int done = 0;
953   char buf[120];
954
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... */
959
960   if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
961       gnutls_bye(conn->ssl[sockindex].session, GNUTLS_SHUT_WR);
962
963   if(conn->ssl[sockindex].session) {
964     while(!done) {
965       int what = Curl_socket_ready(conn->sock[sockindex],
966                                    CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
967       if(what > 0) {
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,
971                                     buf, sizeof(buf));
972         switch(result) {
973         case 0:
974           /* This is the expected response. There was no data but only
975              the close notify alert */
976           done = 1;
977           break;
978         case GNUTLS_E_AGAIN:
979         case GNUTLS_E_INTERRUPTED:
980           infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED\n");
981           break;
982         default:
983           retval = -1;
984           done = 1;
985           break;
986         }
987       }
988       else if(0 == what) {
989         /* timeout */
990         failf(data, "SSL shutdown timeout");
991         done = 1;
992         break;
993       }
994       else {
995         /* anything that gets here is fatally bad */
996         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
997         retval = -1;
998         done = 1;
999       }
1000     }
1001     gnutls_deinit(conn->ssl[sockindex].session);
1002   }
1003   gnutls_certificate_free_credentials(conn->ssl[sockindex].cred);
1004
1005 #ifdef USE_TLS_SRP
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);
1009 #endif
1010
1011   conn->ssl[sockindex].cred = NULL;
1012   conn->ssl[sockindex].session = NULL;
1013
1014   return retval;
1015 }
1016
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 */
1021                          CURLcode *curlcode)
1022 {
1023   ssize_t ret;
1024
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;
1028     return -1;
1029   }
1030
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);
1035     if(rc)
1036       /* handshake() writes error message on its own */
1037       *curlcode = rc;
1038     else
1039       *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
1040     return -1;
1041   }
1042
1043   if(ret < 0) {
1044     failf(conn->data, "GnuTLS recv error (%d): %s",
1045           (int)ret, gnutls_strerror((int)ret));
1046     *curlcode = CURLE_RECV_ERROR;
1047     return -1;
1048   }
1049
1050   return ret;
1051 }
1052
1053 void Curl_gtls_session_free(void *ptr)
1054 {
1055   free(ptr);
1056 }
1057
1058 size_t Curl_gtls_version(char *buffer, size_t size)
1059 {
1060   return snprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
1061 }
1062
1063 int Curl_gtls_seed(struct SessionHandle *data)
1064 {
1065   /* we have the "SSL is seeded" boolean static to prevent multiple
1066      time-consuming seedings in vain */
1067   static bool ssl_seeded = FALSE;
1068
1069   /* Quickly add a bit of entropy */
1070 #ifndef USE_GNUTLS_NETTLE
1071   gcry_fast_random_poll();
1072 #endif
1073
1074   if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
1075      data->set.str[STRING_SSL_EGDSOCKET]) {
1076
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
1081     */
1082     ssl_seeded = TRUE;
1083   }
1084   return 0;
1085 }
1086
1087 void Curl_gtls_random(struct SessionHandle *data,
1088                       unsigned char *entropy,
1089                       size_t length)
1090 {
1091 #if defined(USE_GNUTLS_NETTLE)
1092   (void)data;
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);
1097 #endif
1098 }
1099
1100 void Curl_gtls_md5sum(unsigned char *tmp, /* input */
1101                       size_t tmplen,
1102                       unsigned char *md5sum, /* output */
1103                       size_t md5len)
1104 {
1105 #if defined(USE_GNUTLS_NETTLE)
1106   struct md5_ctx MD5pw;
1107   md5_init(&MD5pw);
1108   md5_update(&MD5pw, tmplen, tmp);
1109   md5_digest(&MD5pw, md5len, md5sum);
1110 #elif defined(USE_GNUTLS)
1111   gcry_md_hd_t MD5pw;
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);
1116 #endif
1117 }
1118
1119 #endif /* USE_GNUTLS */