~ubuntu-branches/ubuntu/edgy/curl/edgy

« back to all changes in this revision

Viewing changes to lib/gtls.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2005-07-26 19:03:01 UTC
  • mfrom: (1.1.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20050726190301-x2m2vmjgc8fwnic5
Tags: 7.14.0-2ubuntu1
Synchronize with Debian.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/***************************************************************************
 
2
 *                                  _   _ ____  _
 
3
 *  Project                     ___| | | |  _ \| |
 
4
 *                             / __| | | | |_) | |
 
5
 *                            | (__| |_| |  _ <| |___
 
6
 *                             \___|\___/|_| \_\_____|
 
7
 *
 
8
 * Copyright (C) 1998 - 2005, 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
 * $Id: gtls.c,v 1.7 2005/04/22 20:56:26 bagder Exp $
 
22
 ***************************************************************************/
 
23
 
 
24
/*
 
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.
 
27
 *
 
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.
 
30
 */
 
31
 
 
32
#include "setup.h"
 
33
#ifdef USE_GNUTLS
 
34
#include <gnutls/gnutls.h>
 
35
#include <gnutls/x509.h>
 
36
 
 
37
#include <string.h>
 
38
#include <stdlib.h>
 
39
#include <ctype.h>
 
40
#ifdef HAVE_SYS_TYPES_H
 
41
#include <sys/types.h>
 
42
#endif
 
43
#ifdef HAVE_SYS_SOCKET_H
 
44
#include <sys/socket.h>
 
45
#endif
 
46
 
 
47
#include "urldata.h"
 
48
#include "sendf.h"
 
49
#include "gtls.h"
 
50
#include "sslgen.h"
 
51
#include "parsedate.h"
 
52
#include "connect.h" /* for the connect timeout */
 
53
#include "select.h"
 
54
#define _MPRINTF_REPLACE /* use our functions only */
 
55
#include <curl/mprintf.h>
 
56
#include "memory.h"
 
57
/* The last #include file should be: */
 
58
#include "memdebug.h"
 
59
 
 
60
/* Enable GnuTLS debugging by defining GTLSDEBUG */
 
61
/*#define GTLSDEBUG */
 
62
 
 
63
#ifdef GTLSDEBUG
 
64
static void tls_log_func(int level, const char *str)
 
65
{
 
66
    fprintf(stderr, "|<%d>| %s", level, str);
 
67
}
 
68
#endif
 
69
 
 
70
 
 
71
/* Global GnuTLS init, called from Curl_ssl_init() */
 
72
int Curl_gtls_init(void)
 
73
{
 
74
  gnutls_global_init();
 
75
#ifdef GTLSDEBUG
 
76
  gnutls_global_set_log_function(tls_log_func);
 
77
  gnutls_global_set_log_level(2);
 
78
#endif
 
79
  return 1;
 
80
}
 
81
 
 
82
int Curl_gtls_cleanup(void)
 
83
{
 
84
  gnutls_global_deinit();
 
85
  return 1;
 
86
}
 
87
 
 
88
static void showtime(struct SessionHandle *data,
 
89
                     const char *text,
 
90
                     time_t stamp)
 
91
{
 
92
  struct tm *tm;
 
93
#ifdef HAVE_GMTIME_R
 
94
  struct tm buffer;
 
95
  tm = (struct tm *)gmtime_r(&stamp, &buffer);
 
96
#else
 
97
  tm = gmtime(&stamp);
 
98
#endif
 
99
  snprintf(data->state.buffer,
 
100
           BUFSIZE,
 
101
           "\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT\n",
 
102
           text,
 
103
           Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
 
104
           tm->tm_mday,
 
105
           Curl_month[tm->tm_mon],
 
106
           tm->tm_year + 1900,
 
107
           tm->tm_hour,
 
108
           tm->tm_min,
 
109
           tm->tm_sec);
 
110
  infof(data, "%s", data->state.buffer);
 
111
}
 
112
 
 
113
/*
 
114
 * This function is called after the TCP connect has completed. Setup the TLS
 
115
 * layer and do all necessary magic.
 
116
 */
 
117
CURLcode
 
118
Curl_gtls_connect(struct connectdata *conn,
 
119
                  int sockindex)
 
120
 
 
121
{
 
122
  const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
 
123
  struct SessionHandle *data = conn->data;
 
124
  gnutls_session session;
 
125
  int rc;
 
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? */
 
131
  size_t size;
 
132
  unsigned int algo;
 
133
  unsigned int bits;
 
134
  time_t clock;
 
135
  const char *ptr;
 
136
  void *ssl_sessionid;
 
137
  size_t ssl_idsize;
 
138
 
 
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;
 
143
  }
 
144
 
 
145
  /* allocate a cred struct */
 
146
  rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
 
147
  if(rc < 0) {
 
148
    failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
 
149
    return CURLE_SSL_CONNECT_ERROR;
 
150
  }
 
151
 
 
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);
 
157
    if(rc < 0) {
 
158
      infof(data, "error reading ca cert file %s (%s)\n",
 
159
            data->set.ssl.CAfile, gnutls_strerror(rc));
 
160
    }
 
161
  }
 
162
 
 
163
  /* Initialize TLS session as a client */
 
164
  rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
 
165
  if(rc) {
 
166
    failf(data, "gnutls_init() failed: %d", rc);
 
167
    return CURLE_SSL_CONNECT_ERROR;
 
168
  }
 
169
 
 
170
  /* convenient assign */
 
171
  session = conn->ssl[sockindex].session;
 
172
 
 
173
  /* Use default priorities */
 
174
  rc = gnutls_set_default_priority(session);
 
175
  if(rc < 0)
 
176
    return CURLE_SSL_CONNECT_ERROR;
 
177
 
 
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);
 
182
  if(rc < 0)
 
183
    return CURLE_SSL_CONNECT_ERROR;
 
184
 
 
185
  /* put the anonymous credentials to the current session */
 
186
  rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
 
187
                              conn->ssl[sockindex].cred);
 
188
 
 
189
  /* set the connection handle (file descriptor for the socket) */
 
190
  gnutls_transport_set_ptr(session,
 
191
                           (gnutls_transport_ptr)conn->sock[sockindex]);
 
192
 
 
193
  /* This might be a reconnect, so we check for a session ID in the cache
 
194
     to speed up things */
 
195
 
 
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);
 
199
 
 
200
    /* Informational message */
 
201
    infof (data, "SSL re-using session ID\n");
 
202
  }
 
203
 
 
204
  do {
 
205
    rc = gnutls_handshake(session);
 
206
 
 
207
    if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
 
208
      long timeout_ms;
 
209
      long has_passed;
 
210
 
 
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;
 
216
        else
 
217
          timeout_ms = data->set.connecttimeout*1000;
 
218
      }
 
219
      else
 
220
        timeout_ms = DEFAULT_CONNECT_TIMEOUT;
 
221
 
 
222
      /* Evaluate in milliseconds how much time that has passed */
 
223
      has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle);
 
224
 
 
225
      /* subtract the passed time */
 
226
      timeout_ms -= has_passed;
 
227
 
 
228
      if(timeout_ms < 0) {
 
229
        /* a precaution, no need to continue if time already is up */
 
230
        failf(data, "SSL connection timeout");
 
231
        return CURLE_OPERATION_TIMEOUTED;
 
232
      }
 
233
 
 
234
      rc = Curl_select(conn->sock[sockindex],
 
235
                         conn->sock[sockindex], (int)timeout_ms);
 
236
      if(rc > 0)
 
237
        /* reabable or writable, go loop*/
 
238
        continue;
 
239
      else if(0 == rc) {
 
240
        /* timeout */
 
241
        failf(data, "SSL connection timeout");
 
242
        return CURLE_OPERATION_TIMEDOUT;
 
243
      }
 
244
      else {
 
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;
 
248
      }
 
249
    }
 
250
    else
 
251
      break;
 
252
  } while(1);
 
253
 
 
254
  if (rc < 0) {
 
255
    failf(data, "gnutls_handshake() failed: %d", rc);
 
256
    /* gnutls_perror(ret); */
 
257
    return CURLE_SSL_CONNECT_ERROR;
 
258
  }
 
259
 
 
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. */
 
265
 
 
266
  chainp = gnutls_certificate_get_peers(session, &cert_list_size);
 
267
  if(!chainp) {
 
268
    if(data->set.ssl.verifyhost) {
 
269
      failf(data, "failed to get server cert");
 
270
      return CURLE_SSL_PEER_CERTIFICATE;
 
271
    }
 
272
    infof(data, "\t common name: WARNING couldn't obtain\n");
 
273
  }
 
274
 
 
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(). */
 
281
 
 
282
  rc = gnutls_certificate_verify_peers2(session, &verify_status);
 
283
  if (rc < 0) {
 
284
    failf(data, "server cert verify failed: %d", rc);
 
285
    return CURLE_SSL_CONNECT_ERROR;
 
286
  }
 
287
 
 
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;
 
294
    }
 
295
    else
 
296
      infof(data, "\t server certificate verification FAILED\n");
 
297
  }
 
298
  else
 
299
      infof(data, "\t server certificate verification OK\n");
 
300
 
 
301
  /* initialize an X.509 certificate structure. */
 
302
  gnutls_x509_crt_init(&x509_cert);
 
303
 
 
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);
 
307
 
 
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 */
 
311
                                     FALSE,
 
312
                                     certbuf,
 
313
                                     &size);
 
314
  if(rc) {
 
315
    infof(data, "error fetching CN from cert:%s\n",
 
316
          gnutls_strerror(rc));
 
317
  }
 
318
 
 
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
 
323
     failure. */
 
324
  rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
 
325
 
 
326
  if(!rc) {
 
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;
 
332
    }
 
333
    else
 
334
      infof(data, "\t common name: %s (does not match '%s')\n",
 
335
            certbuf, conn->host.dispname);
 
336
  }
 
337
  else
 
338
    infof(data, "\t common name: %s (matched)\n", certbuf);
 
339
 
 
340
  /* Show:
 
341
 
 
342
  - ciphers used
 
343
  - subject
 
344
  - start date
 
345
  - expire date
 
346
  - common name
 
347
  - issuer
 
348
 
 
349
  */
 
350
 
 
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));
 
355
 
 
356
  /* version of the X.509 certificate. */
 
357
  infof(data, "\t certificate version: #%d\n",
 
358
        gnutls_x509_crt_get_version(x509_cert));
 
359
 
 
360
 
 
361
  size = sizeof(certbuf);
 
362
  gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
 
363
  infof(data, "\t subject: %s\n", certbuf);
 
364
 
 
365
  clock = gnutls_x509_crt_get_activation_time(x509_cert);
 
366
  showtime(data, "start date", clock);
 
367
 
 
368
  clock = gnutls_x509_crt_get_expiration_time(x509_cert);
 
369
  showtime(data, "expire date", clock);
 
370
 
 
371
  size = sizeof(certbuf);
 
372
  gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
 
373
  infof(data, "\t issuer: %s\n", certbuf);
 
374
 
 
375
  gnutls_x509_crt_deinit(x509_cert);
 
376
 
 
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);
 
381
 
 
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);
 
385
 
 
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);
 
389
 
 
390
  if(!ssl_sessionid) {
 
391
    /* this session was not previously in the cache, add it now */
 
392
 
 
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 */
 
396
 
 
397
    if(ssl_sessionid) {
 
398
      /* extract session ID to the allocated buffer */
 
399
      gnutls_session_get_data(session, ssl_sessionid, &ssl_idsize);
 
400
 
 
401
      /* store this session id */
 
402
      return Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_idsize);
 
403
    }
 
404
  }
 
405
 
 
406
  return CURLE_OK;
 
407
}
 
408
 
 
409
 
 
410
/* return number of sent (non-SSL) bytes */
 
411
int Curl_gtls_send(struct connectdata *conn,
 
412
                   int sockindex,
 
413
                   void *mem,
 
414
                   size_t len)
 
415
{
 
416
  int rc;
 
417
  rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
 
418
 
 
419
  return rc;
 
420
}
 
421
 
 
422
void Curl_gtls_close_all(struct SessionHandle *data)
 
423
{
 
424
  /* FIX: make the OpenSSL code more generic and use parts of it here */
 
425
  (void)data;
 
426
}
 
427
 
 
428
static void close_one(struct connectdata *conn,
 
429
                      int index)
 
430
{
 
431
  if(conn->ssl[index].session) {
 
432
    gnutls_bye(conn->ssl[index].session, GNUTLS_SHUT_RDWR);
 
433
    gnutls_deinit(conn->ssl[index].session);
 
434
  }
 
435
  gnutls_certificate_free_credentials(conn->ssl[index].cred);
 
436
}
 
437
 
 
438
void Curl_gtls_close(struct connectdata *conn)
 
439
{
 
440
  if(conn->ssl[0].use)
 
441
    close_one(conn, 0);
 
442
  if(conn->ssl[1].use)
 
443
    close_one(conn, 1);
 
444
}
 
445
 
 
446
/*
 
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.
 
450
 */
 
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 */
 
455
                       bool *wouldblock)
 
456
{
 
457
  ssize_t ret;
 
458
 
 
459
  ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
 
460
  if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
 
461
    *wouldblock = TRUE;
 
462
    return -1;
 
463
  }
 
464
 
 
465
  *wouldblock = FALSE;
 
466
  if (!ret) {
 
467
    failf(conn->data, "Peer closed the TLS connection");
 
468
    return -1;
 
469
  }
 
470
 
 
471
  if (ret < 0) {
 
472
    failf(conn->data, "GnuTLS recv error (%d): %s",
 
473
          (int)ret, gnutls_strerror(ret));
 
474
    return -1;
 
475
  }
 
476
 
 
477
  return ret;
 
478
}
 
479
 
 
480
void Curl_gtls_session_free(void *ptr)
 
481
{
 
482
  free(ptr);
 
483
}
 
484
 
 
485
size_t Curl_gtls_version(char *buffer, size_t size)
 
486
{
 
487
  return snprintf(buffer, size, " GnuTLS/%s", gnutls_check_version(NULL));
 
488
}
 
489
 
 
490
#endif /* USE_GNUTLS */