1
/***************************************************************************
3
* Project ___| | | | _ \| |
5
* | (__| |_| | _ <| |___
6
* \___|\___/|_| \_\_____|
8
* Copyright (C) 1998 - 2005, Daniel Stenberg, <daniel@haxx.se>, et al.
10
* This software is licensed as described in the file COPYING, which
11
* you should have received as part of this distribution. The terms
12
* are also available at http://curl.haxx.se/docs/copyright.html.
14
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
* copies of the Software, and permit persons to whom the Software is
16
* furnished to do so, under the terms of the COPYING file.
18
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
* KIND, either express or implied.
21
* $Id: gtls.c,v 1.7 2005/04/22 20:56:26 bagder Exp $
22
***************************************************************************/
25
* Source file for all GnuTLS-specific code for the TLS/SSL layer. No code
26
* but sslgen.c should ever call or use these functions.
28
* Note: don't use the GnuTLS' *_t variable type names in this source code,
29
* since they were not present in 1.0.X.
34
#include <gnutls/gnutls.h>
35
#include <gnutls/x509.h>
40
#ifdef HAVE_SYS_TYPES_H
41
#include <sys/types.h>
43
#ifdef HAVE_SYS_SOCKET_H
44
#include <sys/socket.h>
51
#include "parsedate.h"
52
#include "connect.h" /* for the connect timeout */
54
#define _MPRINTF_REPLACE /* use our functions only */
55
#include <curl/mprintf.h>
57
/* The last #include file should be: */
60
/* Enable GnuTLS debugging by defining GTLSDEBUG */
61
/*#define GTLSDEBUG */
64
static void tls_log_func(int level, const char *str)
66
fprintf(stderr, "|<%d>| %s", level, str);
71
/* Global GnuTLS init, called from Curl_ssl_init() */
72
int Curl_gtls_init(void)
76
gnutls_global_set_log_function(tls_log_func);
77
gnutls_global_set_log_level(2);
82
int Curl_gtls_cleanup(void)
84
gnutls_global_deinit();
88
static void showtime(struct SessionHandle *data,
95
tm = (struct tm *)gmtime_r(&stamp, &buffer);
99
snprintf(data->state.buffer,
101
"\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT\n",
103
Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
105
Curl_month[tm->tm_mon],
110
infof(data, "%s", data->state.buffer);
114
* This function is called after the TCP connect has completed. Setup the TLS
115
* layer and do all necessary magic.
118
Curl_gtls_connect(struct connectdata *conn,
122
const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
123
struct SessionHandle *data = conn->data;
124
gnutls_session session;
126
unsigned int cert_list_size;
127
const gnutls_datum *chainp;
128
unsigned int verify_status;
129
gnutls_x509_crt x509_cert;
130
char certbuf[256]; /* big enough? */
139
/* GnuTLS only supports TLSv1 (and SSLv3?) */
140
if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
141
failf(data, "GnuTLS does not support SSLv2");
142
return CURLE_SSL_CONNECT_ERROR;
145
/* allocate a cred struct */
146
rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
148
failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
149
return CURLE_SSL_CONNECT_ERROR;
152
if(data->set.ssl.CAfile) {
153
/* set the trusted CA cert bundle file */
154
rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
155
data->set.ssl.CAfile,
156
GNUTLS_X509_FMT_PEM);
158
infof(data, "error reading ca cert file %s (%s)\n",
159
data->set.ssl.CAfile, gnutls_strerror(rc));
163
/* Initialize TLS session as a client */
164
rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
166
failf(data, "gnutls_init() failed: %d", rc);
167
return CURLE_SSL_CONNECT_ERROR;
170
/* convenient assign */
171
session = conn->ssl[sockindex].session;
173
/* Use default priorities */
174
rc = gnutls_set_default_priority(session);
176
return CURLE_SSL_CONNECT_ERROR;
178
/* Sets the priority on the certificate types supported by gnutls. Priority
179
is higher for types specified before others. After specifying the types
180
you want, you must append a 0. */
181
rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
183
return CURLE_SSL_CONNECT_ERROR;
185
/* put the anonymous credentials to the current session */
186
rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
187
conn->ssl[sockindex].cred);
189
/* set the connection handle (file descriptor for the socket) */
190
gnutls_transport_set_ptr(session,
191
(gnutls_transport_ptr)conn->sock[sockindex]);
193
/* This might be a reconnect, so we check for a session ID in the cache
194
to speed up things */
196
if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
197
/* we got a session id, use it! */
198
gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);
200
/* Informational message */
201
infof (data, "SSL re-using session ID\n");
205
rc = gnutls_handshake(session);
207
if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
211
if(data->set.timeout || data->set.connecttimeout) {
212
/* get the most strict timeout of the ones converted to milliseconds */
213
if(data->set.timeout &&
214
(data->set.timeout>data->set.connecttimeout))
215
timeout_ms = data->set.timeout*1000;
217
timeout_ms = data->set.connecttimeout*1000;
220
timeout_ms = DEFAULT_CONNECT_TIMEOUT;
222
/* Evaluate in milliseconds how much time that has passed */
223
has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle);
225
/* subtract the passed time */
226
timeout_ms -= has_passed;
229
/* a precaution, no need to continue if time already is up */
230
failf(data, "SSL connection timeout");
231
return CURLE_OPERATION_TIMEOUTED;
234
rc = Curl_select(conn->sock[sockindex],
235
conn->sock[sockindex], (int)timeout_ms);
237
/* reabable or writable, go loop*/
241
failf(data, "SSL connection timeout");
242
return CURLE_OPERATION_TIMEDOUT;
245
/* anything that gets here is fatally bad */
246
failf(data, "select on SSL socket, errno: %d", Curl_ourerrno());
247
return CURLE_SSL_CONNECT_ERROR;
255
failf(data, "gnutls_handshake() failed: %d", rc);
256
/* gnutls_perror(ret); */
257
return CURLE_SSL_CONNECT_ERROR;
260
/* This function will return the peer's raw certificate (chain) as sent by
261
the peer. These certificates are in raw format (DER encoded for
262
X.509). In case of a X.509 then a certificate list may be present. The
263
first certificate in the list is the peer's certificate, following the
264
issuer's certificate, then the issuer's issuer etc. */
266
chainp = gnutls_certificate_get_peers(session, &cert_list_size);
268
if(data->set.ssl.verifyhost) {
269
failf(data, "failed to get server cert");
270
return CURLE_SSL_PEER_CERTIFICATE;
272
infof(data, "\t common name: WARNING couldn't obtain\n");
275
/* This function will try to verify the peer's certificate and return its
276
status (trusted, invalid etc.). The value of status should be one or more
277
of the gnutls_certificate_status_t enumerated elements bitwise or'd. To
278
avoid denial of service attacks some default upper limits regarding the
279
certificate key size and chain size are set. To override them use
280
gnutls_certificate_set_verify_limits(). */
282
rc = gnutls_certificate_verify_peers2(session, &verify_status);
284
failf(data, "server cert verify failed: %d", rc);
285
return CURLE_SSL_CONNECT_ERROR;
288
/* verify_status is a bitmask of gnutls_certificate_status bits */
289
if(verify_status & GNUTLS_CERT_INVALID) {
290
if (data->set.ssl.verifypeer) {
291
failf(data, "server certificate verification failed. CAfile: %s",
292
data->set.ssl.CAfile?data->set.ssl.CAfile:"none");
293
return CURLE_SSL_CACERT;
296
infof(data, "\t server certificate verification FAILED\n");
299
infof(data, "\t server certificate verification OK\n");
301
/* initialize an X.509 certificate structure. */
302
gnutls_x509_crt_init(&x509_cert);
304
/* convert the given DER or PEM encoded Certificate to the native
305
gnutls_x509_crt_t format */
306
gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
308
size=sizeof(certbuf);
309
rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
310
0, /* the first and only one */
315
infof(data, "error fetching CN from cert:%s\n",
316
gnutls_strerror(rc));
319
/* This function will check if the given certificate's subject matches the
320
given hostname. This is a basic implementation of the matching described
321
in RFC2818 (HTTPS), which takes into account wildcards, and the subject
322
alternative name PKIX extension. Returns non zero on success, and zero on
324
rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
327
if (data->set.ssl.verifyhost > 1) {
328
failf(data, "SSL: certificate subject name (%s) does not match "
329
"target host name '%s'", certbuf, conn->host.dispname);
330
gnutls_x509_crt_deinit(x509_cert);
331
return CURLE_SSL_PEER_CERTIFICATE;
334
infof(data, "\t common name: %s (does not match '%s')\n",
335
certbuf, conn->host.dispname);
338
infof(data, "\t common name: %s (matched)\n", certbuf);
351
/* public key algorithm's parameters */
352
algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
353
infof(data, "\t certificate public key: %s\n",
354
gnutls_pk_algorithm_get_name(algo));
356
/* version of the X.509 certificate. */
357
infof(data, "\t certificate version: #%d\n",
358
gnutls_x509_crt_get_version(x509_cert));
361
size = sizeof(certbuf);
362
gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
363
infof(data, "\t subject: %s\n", certbuf);
365
clock = gnutls_x509_crt_get_activation_time(x509_cert);
366
showtime(data, "start date", clock);
368
clock = gnutls_x509_crt_get_expiration_time(x509_cert);
369
showtime(data, "expire date", clock);
371
size = sizeof(certbuf);
372
gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
373
infof(data, "\t issuer: %s\n", certbuf);
375
gnutls_x509_crt_deinit(x509_cert);
377
/* compression algorithm (if any) */
378
ptr = gnutls_compression_get_name(gnutls_compression_get(session));
379
/* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
380
infof(data, "\t compression: %s\n", ptr);
382
/* the name of the cipher used. ie 3DES. */
383
ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
384
infof(data, "\t cipher: %s\n", ptr);
386
/* the MAC algorithms name. ie SHA1 */
387
ptr = gnutls_mac_get_name(gnutls_mac_get(session));
388
infof(data, "\t MAC: %s\n", ptr);
391
/* this session was not previously in the cache, add it now */
393
/* get the session ID data size */
394
gnutls_session_get_data(session, NULL, &ssl_idsize);
395
ssl_sessionid = malloc(ssl_idsize); /* get a buffer for it */
398
/* extract session ID to the allocated buffer */
399
gnutls_session_get_data(session, ssl_sessionid, &ssl_idsize);
401
/* store this session id */
402
return Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_idsize);
410
/* return number of sent (non-SSL) bytes */
411
int Curl_gtls_send(struct connectdata *conn,
417
rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
422
void Curl_gtls_close_all(struct SessionHandle *data)
424
/* FIX: make the OpenSSL code more generic and use parts of it here */
428
static void close_one(struct connectdata *conn,
431
if(conn->ssl[index].session) {
432
gnutls_bye(conn->ssl[index].session, GNUTLS_SHUT_RDWR);
433
gnutls_deinit(conn->ssl[index].session);
435
gnutls_certificate_free_credentials(conn->ssl[index].cred);
438
void Curl_gtls_close(struct connectdata *conn)
447
* If the read would block we return -1 and set 'wouldblock' to TRUE.
448
* Otherwise we return the amount of data read. Other errors should return -1
449
* and set 'wouldblock' to FALSE.
451
ssize_t Curl_gtls_recv(struct connectdata *conn, /* connection data */
452
int num, /* socketindex */
453
char *buf, /* store read data here */
454
size_t buffersize, /* max amount to read */
459
ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
460
if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
467
failf(conn->data, "Peer closed the TLS connection");
472
failf(conn->data, "GnuTLS recv error (%d): %s",
473
(int)ret, gnutls_strerror(ret));
480
void Curl_gtls_session_free(void *ptr)
485
size_t Curl_gtls_version(char *buffer, size_t size)
487
return snprintf(buffer, size, " GnuTLS/%s", gnutls_check_version(NULL));
490
#endif /* USE_GNUTLS */