~ubuntu-branches/ubuntu/wily/curl/wily

« back to all changes in this revision

Viewing changes to .pc/09_openssl-recv.patch/lib/ssluse.c

  • Committer: Package Import Robot
  • Author(s): Oussama Bounaim
  • Date: 2013-07-23 18:42:00 UTC
  • mfrom: (70.2.1 curl)
  • Revision ID: package-import@ubuntu.com-20130723184200-w0qx6nwya6ay03ul
Tags: 7.31.0-2ubuntu1
* Merge from Debian, Remaining changes: 
  - Drop dependencies not in main:
    + Build-Depends: Drop stunnel4 and libssh2-1-dev.
    + Drop libssh2-1-dev from binary package Depends.
  - Add new libcurl3-udeb package.
  - Add new curl-udeb package.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/***************************************************************************
 
2
 *                                  _   _ ____  _
 
3
 *  Project                     ___| | | |  _ \| |
 
4
 *                             / __| | | | |_) | |
 
5
 *                            | (__| |_| |  _ <| |___
 
6
 *                             \___|\___/|_| \_\_____|
 
7
 *
 
8
 * Copyright (C) 1998 - 2013, 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 OpenSSL-specific code for the TLS/SSL layer. No code
 
25
 * but sslgen.c should ever call or use these functions.
 
26
 */
 
27
 
 
28
/*
 
29
 * The original SSLeay-using code for curl was written by Linas Vepstas and
 
30
 * Sampo Kellomaki 1998.
 
31
 */
 
32
 
 
33
#include "curl_setup.h"
 
34
 
 
35
#ifdef HAVE_LIMITS_H
 
36
#include <limits.h>
 
37
#endif
 
38
 
 
39
#include "urldata.h"
 
40
#include "sendf.h"
 
41
#include "formdata.h" /* for the boundary function */
 
42
#include "url.h" /* for the ssl config check function */
 
43
#include "inet_pton.h"
 
44
#include "ssluse.h"
 
45
#include "connect.h"
 
46
#include "strequal.h"
 
47
#include "select.h"
 
48
#include "sslgen.h"
 
49
#include "rawstr.h"
 
50
#include "hostcheck.h"
 
51
 
 
52
#define _MPRINTF_REPLACE /* use the internal *printf() functions */
 
53
#include <curl/mprintf.h>
 
54
 
 
55
#ifdef USE_SSLEAY
 
56
 
 
57
#ifdef USE_OPENSSL
 
58
#include <openssl/rand.h>
 
59
#include <openssl/x509v3.h>
 
60
#include <openssl/dsa.h>
 
61
#include <openssl/dh.h>
 
62
#include <openssl/err.h>
 
63
#include <openssl/md5.h>
 
64
#else
 
65
#include <rand.h>
 
66
#include <x509v3.h>
 
67
#include <md5.h>
 
68
#endif
 
69
 
 
70
#include "warnless.h"
 
71
#include "curl_memory.h"
 
72
#include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
 
73
 
 
74
/* The last #include file should be: */
 
75
#include "memdebug.h"
 
76
 
 
77
#ifndef OPENSSL_VERSION_NUMBER
 
78
#error "OPENSSL_VERSION_NUMBER not defined"
 
79
#endif
 
80
 
 
81
#if OPENSSL_VERSION_NUMBER >= 0x0090581fL
 
82
#define HAVE_SSL_GET1_SESSION 1
 
83
#else
 
84
#undef HAVE_SSL_GET1_SESSION
 
85
#endif
 
86
 
 
87
#if OPENSSL_VERSION_NUMBER >= 0x00904100L
 
88
#define HAVE_USERDATA_IN_PWD_CALLBACK 1
 
89
#else
 
90
#undef HAVE_USERDATA_IN_PWD_CALLBACK
 
91
#endif
 
92
 
 
93
#if OPENSSL_VERSION_NUMBER >= 0x00907001L
 
94
/* ENGINE_load_private_key() takes four arguments */
 
95
#define HAVE_ENGINE_LOAD_FOUR_ARGS
 
96
#include <openssl/ui.h>
 
97
#else
 
98
/* ENGINE_load_private_key() takes three arguments */
 
99
#undef HAVE_ENGINE_LOAD_FOUR_ARGS
 
100
#endif
 
101
 
 
102
#if (OPENSSL_VERSION_NUMBER >= 0x00903001L) && defined(HAVE_OPENSSL_PKCS12_H)
 
103
/* OpenSSL has PKCS 12 support */
 
104
#define HAVE_PKCS12_SUPPORT
 
105
#else
 
106
/* OpenSSL/SSLEay does not have PKCS12 support */
 
107
#undef HAVE_PKCS12_SUPPORT
 
108
#endif
 
109
 
 
110
#if OPENSSL_VERSION_NUMBER >= 0x00906001L
 
111
#define HAVE_ERR_ERROR_STRING_N 1
 
112
#endif
 
113
 
 
114
#if OPENSSL_VERSION_NUMBER >= 0x00909000L
 
115
#define SSL_METHOD_QUAL const
 
116
#else
 
117
#define SSL_METHOD_QUAL
 
118
#endif
 
119
 
 
120
#if OPENSSL_VERSION_NUMBER >= 0x00907000L
 
121
/* 0.9.6 didn't have X509_STORE_set_flags() */
 
122
#define HAVE_X509_STORE_SET_FLAGS 1
 
123
#else
 
124
#define X509_STORE_set_flags(x,y) Curl_nop_stmt
 
125
#endif
 
126
 
 
127
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
 
128
#define HAVE_ERR_REMOVE_THREAD_STATE 1
 
129
#endif
 
130
 
 
131
#ifndef HAVE_SSLV2_CLIENT_METHOD
 
132
#undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
 
133
#define OPENSSL_NO_SSL2
 
134
#endif
 
135
 
 
136
/*
 
137
 * Number of bytes to read from the random number seed file. This must be
 
138
 * a finite value (because some entropy "files" like /dev/urandom have
 
139
 * an infinite length), but must be large enough to provide enough
 
140
 * entopy to properly seed OpenSSL's PRNG.
 
141
 */
 
142
#define RAND_LOAD_LENGTH 1024
 
143
 
 
144
#ifndef HAVE_USERDATA_IN_PWD_CALLBACK
 
145
static char global_passwd[64];
 
146
#endif
 
147
 
 
148
static int passwd_callback(char *buf, int num, int encrypting
 
149
#ifdef HAVE_USERDATA_IN_PWD_CALLBACK
 
150
                           /* This was introduced in 0.9.4, we can set this
 
151
                              using SSL_CTX_set_default_passwd_cb_userdata()
 
152
                              */
 
153
                           , void *global_passwd
 
154
#endif
 
155
                           )
 
156
{
 
157
  DEBUGASSERT(0 == encrypting);
 
158
 
 
159
  if(!encrypting) {
 
160
    int klen = curlx_uztosi(strlen((char *)global_passwd));
 
161
    if(num > klen) {
 
162
      memcpy(buf, global_passwd, klen+1);
 
163
      return klen;
 
164
    }
 
165
  }
 
166
  return 0;
 
167
}
 
168
 
 
169
/*
 
170
 * rand_enough() is a function that returns TRUE if we have seeded the random
 
171
 * engine properly. We use some preprocessor magic to provide a seed_enough()
 
172
 * macro to use, just to prevent a compiler warning on this function if we
 
173
 * pass in an argument that is never used.
 
174
 */
 
175
 
 
176
#ifdef HAVE_RAND_STATUS
 
177
#define seed_enough(x) rand_enough()
 
178
static bool rand_enough(void)
 
179
{
 
180
  return (0 != RAND_status()) ? TRUE : FALSE;
 
181
}
 
182
#else
 
183
#define seed_enough(x) rand_enough(x)
 
184
static bool rand_enough(int nread)
 
185
{
 
186
  /* this is a very silly decision to make */
 
187
  return (nread > 500) ? TRUE : FALSE;
 
188
}
 
189
#endif
 
190
 
 
191
static int ossl_seed(struct SessionHandle *data)
 
192
{
 
193
  char *buf = data->state.buffer; /* point to the big buffer */
 
194
  int nread=0;
 
195
 
 
196
  /* Q: should we add support for a random file name as a libcurl option?
 
197
     A: Yes, it is here */
 
198
 
 
199
#ifndef RANDOM_FILE
 
200
  /* if RANDOM_FILE isn't defined, we only perform this if an option tells
 
201
     us to! */
 
202
  if(data->set.ssl.random_file)
 
203
#define RANDOM_FILE "" /* doesn't matter won't be used */
 
204
#endif
 
205
  {
 
206
    /* let the option override the define */
 
207
    nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
 
208
                             data->set.str[STRING_SSL_RANDOM_FILE]:
 
209
                             RANDOM_FILE),
 
210
                            RAND_LOAD_LENGTH);
 
211
    if(seed_enough(nread))
 
212
      return nread;
 
213
  }
 
214
 
 
215
#if defined(HAVE_RAND_EGD)
 
216
  /* only available in OpenSSL 0.9.5 and later */
 
217
  /* EGD_SOCKET is set at configure time or not at all */
 
218
#ifndef EGD_SOCKET
 
219
  /* If we don't have the define set, we only do this if the egd-option
 
220
     is set */
 
221
  if(data->set.str[STRING_SSL_EGDSOCKET])
 
222
#define EGD_SOCKET "" /* doesn't matter won't be used */
 
223
#endif
 
224
  {
 
225
    /* If there's an option and a define, the option overrides the
 
226
       define */
 
227
    int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
 
228
                       data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
 
229
    if(-1 != ret) {
 
230
      nread += ret;
 
231
      if(seed_enough(nread))
 
232
        return nread;
 
233
    }
 
234
  }
 
235
#endif
 
236
 
 
237
  /* If we get here, it means we need to seed the PRNG using a "silly"
 
238
     approach! */
 
239
  do {
 
240
    unsigned char randb[64];
 
241
    int len = sizeof(randb);
 
242
    RAND_bytes(randb, len);
 
243
    RAND_add(randb, len, (len >> 1));
 
244
  } while(!RAND_status());
 
245
 
 
246
  /* generates a default path for the random seed file */
 
247
  buf[0]=0; /* blank it first */
 
248
  RAND_file_name(buf, BUFSIZE);
 
249
  if(buf[0]) {
 
250
    /* we got a file name to try */
 
251
    nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
 
252
    if(seed_enough(nread))
 
253
      return nread;
 
254
  }
 
255
 
 
256
  infof(data, "libcurl is now using a weak random seed!\n");
 
257
  return nread;
 
258
}
 
259
 
 
260
int Curl_ossl_seed(struct SessionHandle *data)
 
261
{
 
262
  /* we have the "SSL is seeded" boolean static to prevent multiple
 
263
     time-consuming seedings in vain */
 
264
  static bool ssl_seeded = FALSE;
 
265
 
 
266
  if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
 
267
     data->set.str[STRING_SSL_EGDSOCKET]) {
 
268
    ossl_seed(data);
 
269
    ssl_seeded = TRUE;
 
270
  }
 
271
  return 0;
 
272
}
 
273
 
 
274
 
 
275
#ifndef SSL_FILETYPE_ENGINE
 
276
#define SSL_FILETYPE_ENGINE 42
 
277
#endif
 
278
#ifndef SSL_FILETYPE_PKCS12
 
279
#define SSL_FILETYPE_PKCS12 43
 
280
#endif
 
281
static int do_file_type(const char *type)
 
282
{
 
283
  if(!type || !type[0])
 
284
    return SSL_FILETYPE_PEM;
 
285
  if(Curl_raw_equal(type, "PEM"))
 
286
    return SSL_FILETYPE_PEM;
 
287
  if(Curl_raw_equal(type, "DER"))
 
288
    return SSL_FILETYPE_ASN1;
 
289
  if(Curl_raw_equal(type, "ENG"))
 
290
    return SSL_FILETYPE_ENGINE;
 
291
  if(Curl_raw_equal(type, "P12"))
 
292
    return SSL_FILETYPE_PKCS12;
 
293
  return -1;
 
294
}
 
295
 
 
296
static
 
297
int cert_stuff(struct connectdata *conn,
 
298
               SSL_CTX* ctx,
 
299
               char *cert_file,
 
300
               const char *cert_type,
 
301
               char *key_file,
 
302
               const char *key_type)
 
303
{
 
304
  struct SessionHandle *data = conn->data;
 
305
 
 
306
  int file_type = do_file_type(cert_type);
 
307
 
 
308
  if(cert_file != NULL || file_type == SSL_FILETYPE_ENGINE) {
 
309
    SSL *ssl;
 
310
    X509 *x509;
 
311
    int cert_done = 0;
 
312
 
 
313
    if(data->set.str[STRING_KEY_PASSWD]) {
 
314
#ifndef HAVE_USERDATA_IN_PWD_CALLBACK
 
315
      /*
 
316
       * If password has been given, we store that in the global
 
317
       * area (*shudder*) for a while:
 
318
       */
 
319
      size_t len = strlen(data->set.str[STRING_KEY_PASSWD]);
 
320
      if(len < sizeof(global_passwd))
 
321
        memcpy(global_passwd, data->set.str[STRING_KEY_PASSWD], len+1);
 
322
      else
 
323
        global_passwd[0] = '\0';
 
324
#else
 
325
      /*
 
326
       * We set the password in the callback userdata
 
327
       */
 
328
      SSL_CTX_set_default_passwd_cb_userdata(ctx,
 
329
                                             data->set.str[STRING_KEY_PASSWD]);
 
330
#endif
 
331
      /* Set passwd callback: */
 
332
      SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
 
333
    }
 
334
 
 
335
 
 
336
#define SSL_CLIENT_CERT_ERR \
 
337
    "unable to use client certificate (no key found or wrong pass phrase?)"
 
338
 
 
339
    switch(file_type) {
 
340
    case SSL_FILETYPE_PEM:
 
341
      /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
 
342
      if(SSL_CTX_use_certificate_chain_file(ctx,
 
343
                                            cert_file) != 1) {
 
344
        failf(data, SSL_CLIENT_CERT_ERR);
 
345
        return 0;
 
346
      }
 
347
      break;
 
348
 
 
349
    case SSL_FILETYPE_ASN1:
 
350
      /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
 
351
         we use the case above for PEM so this can only be performed with
 
352
         ASN1 files. */
 
353
      if(SSL_CTX_use_certificate_file(ctx,
 
354
                                      cert_file,
 
355
                                      file_type) != 1) {
 
356
        failf(data, SSL_CLIENT_CERT_ERR);
 
357
        return 0;
 
358
      }
 
359
      break;
 
360
    case SSL_FILETYPE_ENGINE:
 
361
#if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
 
362
      {
 
363
        if(data->state.engine) {
 
364
          const char *cmd_name = "LOAD_CERT_CTRL";
 
365
          struct {
 
366
            const char *cert_id;
 
367
            X509 *cert;
 
368
          } params;
 
369
 
 
370
          params.cert_id = cert_file;
 
371
          params.cert = NULL;
 
372
 
 
373
          /* Does the engine supports LOAD_CERT_CTRL ? */
 
374
          if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
 
375
                          0, (void *)cmd_name, NULL)) {
 
376
            failf(data, "ssl engine does not support loading certificates");
 
377
            return 0;
 
378
          }
 
379
 
 
380
          /* Load the certificate from the engine */
 
381
          if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
 
382
                              0, &params, NULL, 1)) {
 
383
            failf(data, "ssl engine cannot load client cert with id"
 
384
                  " '%s' [%s]", cert_file,
 
385
                  ERR_error_string(ERR_get_error(), NULL));
 
386
            return 0;
 
387
          }
 
388
 
 
389
          if(!params.cert) {
 
390
            failf(data, "ssl engine didn't initialized the certificate "
 
391
                  "properly.");
 
392
            return 0;
 
393
          }
 
394
 
 
395
          if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
 
396
            failf(data, "unable to set client certificate");
 
397
            X509_free(params.cert);
 
398
            return 0;
 
399
          }
 
400
          X509_free(params.cert); /* we don't need the handle any more... */
 
401
        }
 
402
        else {
 
403
          failf(data, "crypto engine not set, can't load certificate");
 
404
          return 0;
 
405
        }
 
406
      }
 
407
      break;
 
408
#else
 
409
      failf(data, "file type ENG for certificate not implemented");
 
410
      return 0;
 
411
#endif
 
412
 
 
413
    case SSL_FILETYPE_PKCS12:
 
414
    {
 
415
#ifdef HAVE_PKCS12_SUPPORT
 
416
      FILE *f;
 
417
      PKCS12 *p12;
 
418
      EVP_PKEY *pri;
 
419
      STACK_OF(X509) *ca = NULL;
 
420
      int i;
 
421
 
 
422
      f = fopen(cert_file,"rb");
 
423
      if(!f) {
 
424
        failf(data, "could not open PKCS12 file '%s'", cert_file);
 
425
        return 0;
 
426
      }
 
427
      p12 = d2i_PKCS12_fp(f, NULL);
 
428
      fclose(f);
 
429
 
 
430
      if(!p12) {
 
431
        failf(data, "error reading PKCS12 file '%s'", cert_file );
 
432
        return 0;
 
433
      }
 
434
 
 
435
      PKCS12_PBE_add();
 
436
 
 
437
      if(!PKCS12_parse(p12, data->set.str[STRING_KEY_PASSWD], &pri, &x509,
 
438
                       &ca)) {
 
439
        failf(data,
 
440
              "could not parse PKCS12 file, check password, OpenSSL error %s",
 
441
              ERR_error_string(ERR_get_error(), NULL) );
 
442
        PKCS12_free(p12);
 
443
        return 0;
 
444
      }
 
445
 
 
446
      PKCS12_free(p12);
 
447
 
 
448
      if(SSL_CTX_use_certificate(ctx, x509) != 1) {
 
449
        failf(data, SSL_CLIENT_CERT_ERR);
 
450
        goto fail;
 
451
      }
 
452
 
 
453
      if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
 
454
        failf(data, "unable to use private key from PKCS12 file '%s'",
 
455
              cert_file);
 
456
        goto fail;
 
457
      }
 
458
 
 
459
      if(!SSL_CTX_check_private_key (ctx)) {
 
460
        failf(data, "private key from PKCS12 file '%s' "
 
461
              "does not match certificate in same file", cert_file);
 
462
        goto fail;
 
463
      }
 
464
      /* Set Certificate Verification chain */
 
465
      if(ca && sk_X509_num(ca)) {
 
466
        for(i = 0; i < sk_X509_num(ca); i++) {
 
467
          /*
 
468
           * Note that sk_X509_pop() is used below to make sure the cert is
 
469
           * removed from the stack properly before getting passed to
 
470
           * SSL_CTX_add_extra_chain_cert(). Previously we used
 
471
           * sk_X509_value() instead, but then we'd clean it in the subsequent
 
472
           * sk_X509_pop_free() call.
 
473
           */
 
474
          X509 *x = sk_X509_pop(ca);
 
475
          if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
 
476
            failf(data, "cannot add certificate to certificate chain");
 
477
            goto fail;
 
478
          }
 
479
          /* SSL_CTX_add_client_CA() seems to work with either sk_* function,
 
480
           * presumably because it duplicates what we pass to it.
 
481
           */
 
482
          if(!SSL_CTX_add_client_CA(ctx, x)) {
 
483
            failf(data, "cannot add certificate to client CA list");
 
484
            goto fail;
 
485
          }
 
486
        }
 
487
      }
 
488
 
 
489
      cert_done = 1;
 
490
  fail:
 
491
      EVP_PKEY_free(pri);
 
492
      X509_free(x509);
 
493
      sk_X509_pop_free(ca, X509_free);
 
494
 
 
495
      if(!cert_done)
 
496
        return 0; /* failure! */
 
497
#else
 
498
      failf(data, "file type P12 for certificate not supported");
 
499
      return 0;
 
500
#endif
 
501
    }
 
502
    default:
 
503
      failf(data, "not supported file type '%s' for certificate", cert_type);
 
504
      return 0;
 
505
    }
 
506
 
 
507
    file_type = do_file_type(key_type);
 
508
 
 
509
    switch(file_type) {
 
510
    case SSL_FILETYPE_PEM:
 
511
      if(cert_done)
 
512
        break;
 
513
      if(key_file == NULL)
 
514
        /* cert & key can only be in PEM case in the same file */
 
515
        key_file=cert_file;
 
516
    case SSL_FILETYPE_ASN1:
 
517
      if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
 
518
        failf(data, "unable to set private key file: '%s' type %s",
 
519
              key_file, key_type?key_type:"PEM");
 
520
        return 0;
 
521
      }
 
522
      break;
 
523
    case SSL_FILETYPE_ENGINE:
 
524
#ifdef HAVE_OPENSSL_ENGINE_H
 
525
      {                         /* XXXX still needs some work */
 
526
        EVP_PKEY *priv_key = NULL;
 
527
        if(data->state.engine) {
 
528
#ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
 
529
          UI_METHOD *ui_method = UI_OpenSSL();
 
530
#endif
 
531
          /* the typecast below was added to please mingw32 */
 
532
          priv_key = (EVP_PKEY *)
 
533
            ENGINE_load_private_key(data->state.engine,key_file,
 
534
#ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
 
535
                                    ui_method,
 
536
#endif
 
537
                                    data->set.str[STRING_KEY_PASSWD]);
 
538
          if(!priv_key) {
 
539
            failf(data, "failed to load private key from crypto engine");
 
540
            return 0;
 
541
          }
 
542
          if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
 
543
            failf(data, "unable to set private key");
 
544
            EVP_PKEY_free(priv_key);
 
545
            return 0;
 
546
          }
 
547
          EVP_PKEY_free(priv_key);  /* we don't need the handle any more... */
 
548
        }
 
549
        else {
 
550
          failf(data, "crypto engine not set, can't load private key");
 
551
          return 0;
 
552
        }
 
553
      }
 
554
      break;
 
555
#else
 
556
      failf(data, "file type ENG for private key not supported");
 
557
      return 0;
 
558
#endif
 
559
    case SSL_FILETYPE_PKCS12:
 
560
      if(!cert_done) {
 
561
        failf(data, "file type P12 for private key not supported");
 
562
        return 0;
 
563
      }
 
564
      break;
 
565
    default:
 
566
      failf(data, "not supported file type for private key");
 
567
      return 0;
 
568
    }
 
569
 
 
570
    ssl=SSL_new(ctx);
 
571
    if(NULL == ssl) {
 
572
      failf(data,"unable to create an SSL structure");
 
573
      return 0;
 
574
    }
 
575
 
 
576
    x509=SSL_get_certificate(ssl);
 
577
 
 
578
    /* This version was provided by Evan Jordan and is supposed to not
 
579
       leak memory as the previous version: */
 
580
    if(x509 != NULL) {
 
581
      EVP_PKEY *pktmp = X509_get_pubkey(x509);
 
582
      EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(ssl));
 
583
      EVP_PKEY_free(pktmp);
 
584
    }
 
585
 
 
586
    SSL_free(ssl);
 
587
 
 
588
    /* If we are using DSA, we can copy the parameters from
 
589
     * the private key */
 
590
 
 
591
 
 
592
    /* Now we know that a key and cert have been set against
 
593
     * the SSL context */
 
594
    if(!SSL_CTX_check_private_key(ctx)) {
 
595
      failf(data, "Private key does not match the certificate public key");
 
596
      return 0;
 
597
    }
 
598
#ifndef HAVE_USERDATA_IN_PWD_CALLBACK
 
599
    /* erase it now */
 
600
    memset(global_passwd, 0, sizeof(global_passwd));
 
601
#endif
 
602
  }
 
603
  return 1;
 
604
}
 
605
 
 
606
/* returns non-zero on failure */
 
607
static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
 
608
{
 
609
#if 0
 
610
  return X509_NAME_oneline(a, buf, size);
 
611
#else
 
612
  BIO *bio_out = BIO_new(BIO_s_mem());
 
613
  BUF_MEM *biomem;
 
614
  int rc;
 
615
 
 
616
  if(!bio_out)
 
617
    return 1; /* alloc failed! */
 
618
 
 
619
  rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
 
620
  BIO_get_mem_ptr(bio_out, &biomem);
 
621
 
 
622
  if((size_t)biomem->length < size)
 
623
    size = biomem->length;
 
624
  else
 
625
    size--; /* don't overwrite the buffer end */
 
626
 
 
627
  memcpy(buf, biomem->data, size);
 
628
  buf[size]=0;
 
629
 
 
630
  BIO_free(bio_out);
 
631
 
 
632
  return !rc;
 
633
#endif
 
634
}
 
635
 
 
636
static
 
637
int cert_verify_callback(int ok, X509_STORE_CTX *ctx)
 
638
{
 
639
  X509 *err_cert;
 
640
  char buf[256];
 
641
 
 
642
  err_cert=X509_STORE_CTX_get_current_cert(ctx);
 
643
  (void)x509_name_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
 
644
  return ok;
 
645
}
 
646
 
 
647
/* Return error string for last OpenSSL error
 
648
 */
 
649
static char *SSL_strerror(unsigned long error, char *buf, size_t size)
 
650
{
 
651
#ifdef HAVE_ERR_ERROR_STRING_N
 
652
  /* OpenSSL 0.9.6 and later has a function named
 
653
     ERRO_error_string_n() that takes the size of the buffer as a
 
654
     third argument */
 
655
  ERR_error_string_n(error, buf, size);
 
656
#else
 
657
  (void) size;
 
658
  ERR_error_string(error, buf);
 
659
#endif
 
660
  return buf;
 
661
}
 
662
 
 
663
#endif /* USE_SSLEAY */
 
664
 
 
665
#ifdef USE_SSLEAY
 
666
/**
 
667
 * Global SSL init
 
668
 *
 
669
 * @retval 0 error initializing SSL
 
670
 * @retval 1 SSL initialized successfully
 
671
 */
 
672
int Curl_ossl_init(void)
 
673
{
 
674
#ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
 
675
  ENGINE_load_builtin_engines();
 
676
#endif
 
677
 
 
678
  /* Lets get nice error messages */
 
679
  SSL_load_error_strings();
 
680
 
 
681
  /* Init the global ciphers and digests */
 
682
  if(!SSLeay_add_ssl_algorithms())
 
683
    return 0;
 
684
 
 
685
  OpenSSL_add_all_algorithms();
 
686
 
 
687
  return 1;
 
688
}
 
689
 
 
690
#endif /* USE_SSLEAY */
 
691
 
 
692
#ifdef USE_SSLEAY
 
693
 
 
694
/* Global cleanup */
 
695
void Curl_ossl_cleanup(void)
 
696
{
 
697
  /* Free ciphers and digests lists */
 
698
  EVP_cleanup();
 
699
 
 
700
#ifdef HAVE_ENGINE_CLEANUP
 
701
  /* Free engine list */
 
702
  ENGINE_cleanup();
 
703
#endif
 
704
 
 
705
#ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
 
706
  /* Free OpenSSL ex_data table */
 
707
  CRYPTO_cleanup_all_ex_data();
 
708
#endif
 
709
 
 
710
  /* Free OpenSSL error strings */
 
711
  ERR_free_strings();
 
712
 
 
713
  /* Free thread local error state, destroying hash upon zero refcount */
 
714
#ifdef HAVE_ERR_REMOVE_THREAD_STATE
 
715
  ERR_remove_thread_state(NULL);
 
716
#else
 
717
  ERR_remove_state(0);
 
718
#endif
 
719
}
 
720
 
 
721
/*
 
722
 * This function uses SSL_peek to determine connection status.
 
723
 *
 
724
 * Return codes:
 
725
 *     1 means the connection is still in place
 
726
 *     0 means the connection has been closed
 
727
 *    -1 means the connection status is unknown
 
728
 */
 
729
int Curl_ossl_check_cxn(struct connectdata *conn)
 
730
{
 
731
  int rc;
 
732
  char buf;
 
733
 
 
734
  rc = SSL_peek(conn->ssl[FIRSTSOCKET].handle, (void*)&buf, 1);
 
735
  if(rc > 0)
 
736
    return 1; /* connection still in place */
 
737
 
 
738
  if(rc == 0)
 
739
    return 0; /* connection has been closed */
 
740
 
 
741
  return -1; /* connection status unknown */
 
742
}
 
743
 
 
744
/* Selects an OpenSSL crypto engine
 
745
 */
 
746
CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine)
 
747
{
 
748
#if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
 
749
  ENGINE *e;
 
750
 
 
751
#if OPENSSL_VERSION_NUMBER >= 0x00909000L
 
752
  e = ENGINE_by_id(engine);
 
753
#else
 
754
  /* avoid memory leak */
 
755
  for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
 
756
    const char *e_id = ENGINE_get_id(e);
 
757
    if(!strcmp(engine, e_id))
 
758
      break;
 
759
  }
 
760
#endif
 
761
 
 
762
  if(!e) {
 
763
    failf(data, "SSL Engine '%s' not found", engine);
 
764
    return CURLE_SSL_ENGINE_NOTFOUND;
 
765
  }
 
766
 
 
767
  if(data->state.engine) {
 
768
    ENGINE_finish(data->state.engine);
 
769
    ENGINE_free(data->state.engine);
 
770
    data->state.engine = NULL;
 
771
  }
 
772
  if(!ENGINE_init(e)) {
 
773
    char buf[256];
 
774
 
 
775
    ENGINE_free(e);
 
776
    failf(data, "Failed to initialise SSL Engine '%s':\n%s",
 
777
          engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf)));
 
778
    return CURLE_SSL_ENGINE_INITFAILED;
 
779
  }
 
780
  data->state.engine = e;
 
781
  return CURLE_OK;
 
782
#else
 
783
  (void)engine;
 
784
  failf(data, "SSL Engine not supported");
 
785
  return CURLE_SSL_ENGINE_NOTFOUND;
 
786
#endif
 
787
}
 
788
 
 
789
/* Sets engine as default for all SSL operations
 
790
 */
 
791
CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data)
 
792
{
 
793
#ifdef HAVE_OPENSSL_ENGINE_H
 
794
  if(data->state.engine) {
 
795
    if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
 
796
      infof(data,"set default crypto engine '%s'\n",
 
797
            ENGINE_get_id(data->state.engine));
 
798
    }
 
799
    else {
 
800
      failf(data, "set default crypto engine '%s' failed",
 
801
            ENGINE_get_id(data->state.engine));
 
802
      return CURLE_SSL_ENGINE_SETFAILED;
 
803
    }
 
804
  }
 
805
#else
 
806
  (void) data;
 
807
#endif
 
808
  return CURLE_OK;
 
809
}
 
810
 
 
811
/* Return list of OpenSSL crypto engine names.
 
812
 */
 
813
struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data)
 
814
{
 
815
  struct curl_slist *list = NULL;
 
816
#if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
 
817
  struct curl_slist *beg;
 
818
  ENGINE *e;
 
819
 
 
820
  for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
 
821
    beg = curl_slist_append(list, ENGINE_get_id(e));
 
822
    if(!beg) {
 
823
      curl_slist_free_all(list);
 
824
      return NULL;
 
825
    }
 
826
    list = beg;
 
827
  }
 
828
#endif
 
829
  (void) data;
 
830
  return list;
 
831
}
 
832
 
 
833
 
 
834
/*
 
835
 * This function is called when an SSL connection is closed.
 
836
 */
 
837
void Curl_ossl_close(struct connectdata *conn, int sockindex)
 
838
{
 
839
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
 
840
 
 
841
  if(connssl->handle) {
 
842
    (void)SSL_shutdown(connssl->handle);
 
843
    SSL_set_connect_state(connssl->handle);
 
844
 
 
845
    SSL_free (connssl->handle);
 
846
    connssl->handle = NULL;
 
847
  }
 
848
  if(connssl->ctx) {
 
849
    SSL_CTX_free (connssl->ctx);
 
850
    connssl->ctx = NULL;
 
851
  }
 
852
}
 
853
 
 
854
/*
 
855
 * This function is called to shut down the SSL layer but keep the
 
856
 * socket open (CCC - Clear Command Channel)
 
857
 */
 
858
int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
 
859
{
 
860
  int retval = 0;
 
861
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
 
862
  struct SessionHandle *data = conn->data;
 
863
  char buf[120]; /* We will use this for the OpenSSL error buffer, so it has
 
864
                    to be at least 120 bytes long. */
 
865
  unsigned long sslerror;
 
866
  ssize_t nread;
 
867
  int buffsize;
 
868
  int err;
 
869
  int done = 0;
 
870
 
 
871
  /* This has only been tested on the proftpd server, and the mod_tls code
 
872
     sends a close notify alert without waiting for a close notify alert in
 
873
     response. Thus we wait for a close notify alert from the server, but
 
874
     we do not send one. Let's hope other servers do the same... */
 
875
 
 
876
  if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
 
877
      (void)SSL_shutdown(connssl->handle);
 
878
 
 
879
  if(connssl->handle) {
 
880
    buffsize = (int)sizeof(buf);
 
881
    while(!done) {
 
882
      int what = Curl_socket_ready(conn->sock[sockindex],
 
883
                                   CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
 
884
      if(what > 0) {
 
885
        ERR_clear_error();
 
886
 
 
887
        /* Something to read, let's do it and hope that it is the close
 
888
           notify alert from the server */
 
889
        nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
 
890
                                  buffsize);
 
891
        err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
 
892
 
 
893
        switch(err) {
 
894
        case SSL_ERROR_NONE: /* this is not an error */
 
895
        case SSL_ERROR_ZERO_RETURN: /* no more data */
 
896
          /* This is the expected response. There was no data but only
 
897
             the close notify alert */
 
898
          done = 1;
 
899
          break;
 
900
        case SSL_ERROR_WANT_READ:
 
901
          /* there's data pending, re-invoke SSL_read() */
 
902
          infof(data, "SSL_ERROR_WANT_READ\n");
 
903
          break;
 
904
        case SSL_ERROR_WANT_WRITE:
 
905
          /* SSL wants a write. Really odd. Let's bail out. */
 
906
          infof(data, "SSL_ERROR_WANT_WRITE\n");
 
907
          done = 1;
 
908
          break;
 
909
        default:
 
910
          /* openssl/ssl.h says "look at error stack/return value/errno" */
 
911
          sslerror = ERR_get_error();
 
912
          failf(conn->data, "SSL read: %s, errno %d",
 
913
                ERR_error_string(sslerror, buf),
 
914
                SOCKERRNO);
 
915
          done = 1;
 
916
          break;
 
917
        }
 
918
      }
 
919
      else if(0 == what) {
 
920
        /* timeout */
 
921
        failf(data, "SSL shutdown timeout");
 
922
        done = 1;
 
923
      }
 
924
      else {
 
925
        /* anything that gets here is fatally bad */
 
926
        failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
 
927
        retval = -1;
 
928
        done = 1;
 
929
      }
 
930
    } /* while()-loop for the select() */
 
931
 
 
932
    if(data->set.verbose) {
 
933
#ifdef HAVE_SSL_GET_SHUTDOWN
 
934
      switch(SSL_get_shutdown(connssl->handle)) {
 
935
      case SSL_SENT_SHUTDOWN:
 
936
        infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
 
937
        break;
 
938
      case SSL_RECEIVED_SHUTDOWN:
 
939
        infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
 
940
        break;
 
941
      case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
 
942
        infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
 
943
              "SSL_RECEIVED__SHUTDOWN\n");
 
944
        break;
 
945
      }
 
946
#endif
 
947
    }
 
948
 
 
949
    SSL_free (connssl->handle);
 
950
    connssl->handle = NULL;
 
951
  }
 
952
  return retval;
 
953
}
 
954
 
 
955
void Curl_ossl_session_free(void *ptr)
 
956
{
 
957
  /* free the ID */
 
958
  SSL_SESSION_free(ptr);
 
959
}
 
960
 
 
961
/*
 
962
 * This function is called when the 'data' struct is going away. Close
 
963
 * down everything and free all resources!
 
964
 */
 
965
int Curl_ossl_close_all(struct SessionHandle *data)
 
966
{
 
967
#ifdef HAVE_OPENSSL_ENGINE_H
 
968
  if(data->state.engine) {
 
969
    ENGINE_finish(data->state.engine);
 
970
    ENGINE_free(data->state.engine);
 
971
    data->state.engine = NULL;
 
972
  }
 
973
#else
 
974
  (void)data;
 
975
#endif
 
976
  return 0;
 
977
}
 
978
 
 
979
static int asn1_output(const ASN1_UTCTIME *tm,
 
980
                       char *buf,
 
981
                       size_t sizeofbuf)
 
982
{
 
983
  const char *asn1_string;
 
984
  int gmt=FALSE;
 
985
  int i;
 
986
  int year=0,month=0,day=0,hour=0,minute=0,second=0;
 
987
 
 
988
  i=tm->length;
 
989
  asn1_string=(const char *)tm->data;
 
990
 
 
991
  if(i < 10)
 
992
    return 1;
 
993
  if(asn1_string[i-1] == 'Z')
 
994
    gmt=TRUE;
 
995
  for(i=0; i<10; i++)
 
996
    if((asn1_string[i] > '9') || (asn1_string[i] < '0'))
 
997
      return 2;
 
998
 
 
999
  year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0');
 
1000
  if(year < 50)
 
1001
    year+=100;
 
1002
 
 
1003
  month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0');
 
1004
  if((month > 12) || (month < 1))
 
1005
    return 3;
 
1006
 
 
1007
  day= (asn1_string[4]-'0')*10+(asn1_string[5]-'0');
 
1008
  hour= (asn1_string[6]-'0')*10+(asn1_string[7]-'0');
 
1009
  minute=  (asn1_string[8]-'0')*10+(asn1_string[9]-'0');
 
1010
 
 
1011
  if((asn1_string[10] >= '0') && (asn1_string[10] <= '9') &&
 
1012
     (asn1_string[11] >= '0') && (asn1_string[11] <= '9'))
 
1013
    second= (asn1_string[10]-'0')*10+(asn1_string[11]-'0');
 
1014
 
 
1015
  snprintf(buf, sizeofbuf,
 
1016
           "%04d-%02d-%02d %02d:%02d:%02d %s",
 
1017
           year+1900, month, day, hour, minute, second, (gmt?"GMT":""));
 
1018
 
 
1019
  return 0;
 
1020
}
 
1021
 
 
1022
/* ====================================================== */
 
1023
 
 
1024
 
 
1025
/* Quote from RFC2818 section 3.1 "Server Identity"
 
1026
 
 
1027
   If a subjectAltName extension of type dNSName is present, that MUST
 
1028
   be used as the identity. Otherwise, the (most specific) Common Name
 
1029
   field in the Subject field of the certificate MUST be used. Although
 
1030
   the use of the Common Name is existing practice, it is deprecated and
 
1031
   Certification Authorities are encouraged to use the dNSName instead.
 
1032
 
 
1033
   Matching is performed using the matching rules specified by
 
1034
   [RFC2459].  If more than one identity of a given type is present in
 
1035
   the certificate (e.g., more than one dNSName name, a match in any one
 
1036
   of the set is considered acceptable.) Names may contain the wildcard
 
1037
   character * which is considered to match any single domain name
 
1038
   component or component fragment. E.g., *.a.com matches foo.a.com but
 
1039
   not bar.foo.a.com. f*.com matches foo.com but not bar.com.
 
1040
 
 
1041
   In some cases, the URI is specified as an IP address rather than a
 
1042
   hostname. In this case, the iPAddress subjectAltName must be present
 
1043
   in the certificate and must exactly match the IP in the URI.
 
1044
 
 
1045
*/
 
1046
static CURLcode verifyhost(struct connectdata *conn,
 
1047
                           X509 *server_cert)
 
1048
{
 
1049
  int matched = -1; /* -1 is no alternative match yet, 1 means match and 0
 
1050
                       means mismatch */
 
1051
  int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
 
1052
  size_t addrlen = 0;
 
1053
  struct SessionHandle *data = conn->data;
 
1054
  STACK_OF(GENERAL_NAME) *altnames;
 
1055
#ifdef ENABLE_IPV6
 
1056
  struct in6_addr addr;
 
1057
#else
 
1058
  struct in_addr addr;
 
1059
#endif
 
1060
  CURLcode res = CURLE_OK;
 
1061
 
 
1062
#ifdef ENABLE_IPV6
 
1063
  if(conn->bits.ipv6_ip &&
 
1064
     Curl_inet_pton(AF_INET6, conn->host.name, &addr)) {
 
1065
    target = GEN_IPADD;
 
1066
    addrlen = sizeof(struct in6_addr);
 
1067
  }
 
1068
  else
 
1069
#endif
 
1070
    if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) {
 
1071
      target = GEN_IPADD;
 
1072
      addrlen = sizeof(struct in_addr);
 
1073
    }
 
1074
 
 
1075
  /* get a "list" of alternative names */
 
1076
  altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
 
1077
 
 
1078
  if(altnames) {
 
1079
    int numalts;
 
1080
    int i;
 
1081
 
 
1082
    /* get amount of alternatives, RFC2459 claims there MUST be at least
 
1083
       one, but we don't depend on it... */
 
1084
    numalts = sk_GENERAL_NAME_num(altnames);
 
1085
 
 
1086
    /* loop through all alternatives while none has matched */
 
1087
    for(i=0; (i<numalts) && (matched != 1); i++) {
 
1088
      /* get a handle to alternative name number i */
 
1089
      const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
 
1090
 
 
1091
      /* only check alternatives of the same type the target is */
 
1092
      if(check->type == target) {
 
1093
        /* get data and length */
 
1094
        const char *altptr = (char *)ASN1_STRING_data(check->d.ia5);
 
1095
        size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
 
1096
 
 
1097
        switch(target) {
 
1098
        case GEN_DNS: /* name/pattern comparison */
 
1099
          /* The OpenSSL man page explicitly says: "In general it cannot be
 
1100
             assumed that the data returned by ASN1_STRING_data() is null
 
1101
             terminated or does not contain embedded nulls." But also that
 
1102
             "The actual format of the data will depend on the actual string
 
1103
             type itself: for example for and IA5String the data will be ASCII"
 
1104
 
 
1105
             Gisle researched the OpenSSL sources:
 
1106
             "I checked the 0.9.6 and 0.9.8 sources before my patch and
 
1107
             it always 0-terminates an IA5String."
 
1108
          */
 
1109
          if((altlen == strlen(altptr)) &&
 
1110
             /* if this isn't true, there was an embedded zero in the name
 
1111
                string and we cannot match it. */
 
1112
             Curl_cert_hostcheck(altptr, conn->host.name))
 
1113
            matched = 1;
 
1114
          else
 
1115
            matched = 0;
 
1116
          break;
 
1117
 
 
1118
        case GEN_IPADD: /* IP address comparison */
 
1119
          /* compare alternative IP address if the data chunk is the same size
 
1120
             our server IP address is */
 
1121
          if((altlen == addrlen) && !memcmp(altptr, &addr, altlen))
 
1122
            matched = 1;
 
1123
          else
 
1124
            matched = 0;
 
1125
          break;
 
1126
        }
 
1127
      }
 
1128
    }
 
1129
    GENERAL_NAMES_free(altnames);
 
1130
  }
 
1131
 
 
1132
  if(matched == 1)
 
1133
    /* an alternative name matched the server hostname */
 
1134
    infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname);
 
1135
  else if(matched == 0) {
 
1136
    /* an alternative name field existed, but didn't match and then
 
1137
       we MUST fail */
 
1138
    infof(data, "\t subjectAltName does not match %s\n", conn->host.dispname);
 
1139
    res = CURLE_PEER_FAILED_VERIFICATION;
 
1140
  }
 
1141
  else {
 
1142
    /* we have to look to the last occurrence of a commonName in the
 
1143
       distinguished one to get the most significant one. */
 
1144
    int j,i=-1 ;
 
1145
 
 
1146
/* The following is done because of a bug in 0.9.6b */
 
1147
 
 
1148
    unsigned char *nulstr = (unsigned char *)"";
 
1149
    unsigned char *peer_CN = nulstr;
 
1150
 
 
1151
    X509_NAME *name = X509_get_subject_name(server_cert) ;
 
1152
    if(name)
 
1153
      while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0)
 
1154
        i=j;
 
1155
 
 
1156
    /* we have the name entry and we will now convert this to a string
 
1157
       that we can use for comparison. Doing this we support BMPstring,
 
1158
       UTF8 etc. */
 
1159
 
 
1160
    if(i>=0) {
 
1161
      ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name,i));
 
1162
 
 
1163
      /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
 
1164
         is already UTF-8 encoded. We check for this case and copy the raw
 
1165
         string manually to avoid the problem. This code can be made
 
1166
         conditional in the future when OpenSSL has been fixed. Work-around
 
1167
         brought by Alexis S. L. Carvalho. */
 
1168
      if(tmp) {
 
1169
        if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
 
1170
          j = ASN1_STRING_length(tmp);
 
1171
          if(j >= 0) {
 
1172
            peer_CN = OPENSSL_malloc(j+1);
 
1173
            if(peer_CN) {
 
1174
              memcpy(peer_CN, ASN1_STRING_data(tmp), j);
 
1175
              peer_CN[j] = '\0';
 
1176
            }
 
1177
          }
 
1178
        }
 
1179
        else /* not a UTF8 name */
 
1180
          j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
 
1181
 
 
1182
        if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
 
1183
          /* there was a terminating zero before the end of string, this
 
1184
             cannot match and we return failure! */
 
1185
          failf(data, "SSL: illegal cert name field");
 
1186
          res = CURLE_PEER_FAILED_VERIFICATION;
 
1187
        }
 
1188
      }
 
1189
    }
 
1190
 
 
1191
    if(peer_CN == nulstr)
 
1192
       peer_CN = NULL;
 
1193
    else {
 
1194
      /* convert peer_CN from UTF8 */
 
1195
      CURLcode rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
 
1196
      /* Curl_convert_from_utf8 calls failf if unsuccessful */
 
1197
      if(rc) {
 
1198
        OPENSSL_free(peer_CN);
 
1199
        return rc;
 
1200
      }
 
1201
    }
 
1202
 
 
1203
    if(res)
 
1204
      /* error already detected, pass through */
 
1205
      ;
 
1206
    else if(!peer_CN) {
 
1207
      failf(data,
 
1208
            "SSL: unable to obtain common name from peer certificate");
 
1209
      res = CURLE_PEER_FAILED_VERIFICATION;
 
1210
    }
 
1211
    else if(!Curl_cert_hostcheck((const char *)peer_CN, conn->host.name)) {
 
1212
      failf(data, "SSL: certificate subject name '%s' does not match "
 
1213
            "target host name '%s'", peer_CN, conn->host.dispname);
 
1214
      res = CURLE_PEER_FAILED_VERIFICATION;
 
1215
    }
 
1216
    else {
 
1217
      infof(data, "\t common name: %s (matched)\n", peer_CN);
 
1218
    }
 
1219
    if(peer_CN)
 
1220
      OPENSSL_free(peer_CN);
 
1221
  }
 
1222
  return res;
 
1223
}
 
1224
#endif /* USE_SSLEAY */
 
1225
 
 
1226
/* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
 
1227
   and thus this cannot be done there. */
 
1228
#ifdef SSL_CTRL_SET_MSG_CALLBACK
 
1229
 
 
1230
static const char *ssl_msg_type(int ssl_ver, int msg)
 
1231
{
 
1232
  if(ssl_ver == SSL2_VERSION_MAJOR) {
 
1233
    switch (msg) {
 
1234
      case SSL2_MT_ERROR:
 
1235
        return "Error";
 
1236
      case SSL2_MT_CLIENT_HELLO:
 
1237
        return "Client hello";
 
1238
      case SSL2_MT_CLIENT_MASTER_KEY:
 
1239
        return "Client key";
 
1240
      case SSL2_MT_CLIENT_FINISHED:
 
1241
        return "Client finished";
 
1242
      case SSL2_MT_SERVER_HELLO:
 
1243
        return "Server hello";
 
1244
      case SSL2_MT_SERVER_VERIFY:
 
1245
        return "Server verify";
 
1246
      case SSL2_MT_SERVER_FINISHED:
 
1247
        return "Server finished";
 
1248
      case SSL2_MT_REQUEST_CERTIFICATE:
 
1249
        return "Request CERT";
 
1250
      case SSL2_MT_CLIENT_CERTIFICATE:
 
1251
        return "Client CERT";
 
1252
    }
 
1253
  }
 
1254
  else if(ssl_ver == SSL3_VERSION_MAJOR) {
 
1255
    switch (msg) {
 
1256
      case SSL3_MT_HELLO_REQUEST:
 
1257
        return "Hello request";
 
1258
      case SSL3_MT_CLIENT_HELLO:
 
1259
        return "Client hello";
 
1260
      case SSL3_MT_SERVER_HELLO:
 
1261
        return "Server hello";
 
1262
      case SSL3_MT_CERTIFICATE:
 
1263
        return "CERT";
 
1264
      case SSL3_MT_SERVER_KEY_EXCHANGE:
 
1265
        return "Server key exchange";
 
1266
      case SSL3_MT_CLIENT_KEY_EXCHANGE:
 
1267
        return "Client key exchange";
 
1268
      case SSL3_MT_CERTIFICATE_REQUEST:
 
1269
        return "Request CERT";
 
1270
      case SSL3_MT_SERVER_DONE:
 
1271
        return "Server finished";
 
1272
      case SSL3_MT_CERTIFICATE_VERIFY:
 
1273
        return "CERT verify";
 
1274
      case SSL3_MT_FINISHED:
 
1275
        return "Finished";
 
1276
    }
 
1277
  }
 
1278
  return "Unknown";
 
1279
}
 
1280
 
 
1281
static const char *tls_rt_type(int type)
 
1282
{
 
1283
  return (
 
1284
    type == SSL3_RT_CHANGE_CIPHER_SPEC ? "TLS change cipher, " :
 
1285
    type == SSL3_RT_ALERT              ? "TLS alert, "         :
 
1286
    type == SSL3_RT_HANDSHAKE          ? "TLS handshake, "     :
 
1287
    type == SSL3_RT_APPLICATION_DATA   ? "TLS app data, "      :
 
1288
                                         "TLS Unknown, ");
 
1289
}
 
1290
 
 
1291
 
 
1292
/*
 
1293
 * Our callback from the SSL/TLS layers.
 
1294
 */
 
1295
static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
 
1296
                          const void *buf, size_t len, const SSL *ssl,
 
1297
                          struct connectdata *conn)
 
1298
{
 
1299
  struct SessionHandle *data;
 
1300
  const char *msg_name, *tls_rt_name;
 
1301
  char ssl_buf[1024];
 
1302
  int  ver, msg_type, txt_len;
 
1303
 
 
1304
  if(!conn || !conn->data || !conn->data->set.fdebug ||
 
1305
     (direction != 0 && direction != 1))
 
1306
    return;
 
1307
 
 
1308
  data = conn->data;
 
1309
  ssl_ver >>= 8;
 
1310
  ver = (ssl_ver == SSL2_VERSION_MAJOR ? '2' :
 
1311
         ssl_ver == SSL3_VERSION_MAJOR ? '3' : '?');
 
1312
 
 
1313
  /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
 
1314
   * always pass-up content-type as 0. But the interesting message-type
 
1315
   * is at 'buf[0]'.
 
1316
   */
 
1317
  if(ssl_ver == SSL3_VERSION_MAJOR && content_type != 0)
 
1318
    tls_rt_name = tls_rt_type(content_type);
 
1319
  else
 
1320
    tls_rt_name = "";
 
1321
 
 
1322
  msg_type = *(char*)buf;
 
1323
  msg_name = ssl_msg_type(ssl_ver, msg_type);
 
1324
 
 
1325
  txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "SSLv%c, %s%s (%d):\n",
 
1326
                     ver, tls_rt_name, msg_name, msg_type);
 
1327
  Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
 
1328
 
 
1329
  Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
 
1330
             CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
 
1331
  (void) ssl;
 
1332
}
 
1333
#endif
 
1334
 
 
1335
#ifdef USE_SSLEAY
 
1336
/* ====================================================== */
 
1337
 
 
1338
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
 
1339
#  define use_sni(x)  sni = (x)
 
1340
#else
 
1341
#  define use_sni(x)  Curl_nop_stmt
 
1342
#endif
 
1343
 
 
1344
static CURLcode
 
1345
ossl_connect_step1(struct connectdata *conn,
 
1346
                   int sockindex)
 
1347
{
 
1348
  CURLcode retcode = CURLE_OK;
 
1349
 
 
1350
  struct SessionHandle *data = conn->data;
 
1351
  SSL_METHOD_QUAL SSL_METHOD *req_method=NULL;
 
1352
  void *ssl_sessionid=NULL;
 
1353
  X509_LOOKUP *lookup=NULL;
 
1354
  curl_socket_t sockfd = conn->sock[sockindex];
 
1355
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
 
1356
  long ctx_options;
 
1357
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
 
1358
  bool sni;
 
1359
#ifdef ENABLE_IPV6
 
1360
  struct in6_addr addr;
 
1361
#else
 
1362
  struct in_addr addr;
 
1363
#endif
 
1364
#endif
 
1365
 
 
1366
  DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
 
1367
 
 
1368
  /* Make funny stuff to get random input */
 
1369
  Curl_ossl_seed(data);
 
1370
 
 
1371
  /* check to see if we've been told to use an explicit SSL/TLS version */
 
1372
 
 
1373
  switch(data->set.ssl.version) {
 
1374
  default:
 
1375
  case CURL_SSLVERSION_DEFAULT:
 
1376
#ifdef USE_TLS_SRP
 
1377
    if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
 
1378
      infof(data, "Set version TLSv1 for SRP authorisation\n");
 
1379
      req_method = TLSv1_client_method() ;
 
1380
    }
 
1381
    else
 
1382
#endif
 
1383
    /* we try to figure out version */
 
1384
    req_method = SSLv23_client_method();
 
1385
    use_sni(TRUE);
 
1386
    break;
 
1387
  case CURL_SSLVERSION_TLSv1:
 
1388
    req_method = TLSv1_client_method();
 
1389
    use_sni(TRUE);
 
1390
    break;
 
1391
  case CURL_SSLVERSION_SSLv2:
 
1392
#ifdef OPENSSL_NO_SSL2
 
1393
    failf(data, "OpenSSL was built without SSLv2 support");
 
1394
    return CURLE_NOT_BUILT_IN;
 
1395
#else
 
1396
#ifdef USE_TLS_SRP
 
1397
    if(data->set.ssl.authtype == CURL_TLSAUTH_SRP)
 
1398
      return CURLE_SSL_CONNECT_ERROR;
 
1399
#endif
 
1400
    req_method = SSLv2_client_method();
 
1401
    use_sni(FALSE);
 
1402
    break;
 
1403
#endif
 
1404
  case CURL_SSLVERSION_SSLv3:
 
1405
#ifdef USE_TLS_SRP
 
1406
    if(data->set.ssl.authtype == CURL_TLSAUTH_SRP)
 
1407
      return CURLE_SSL_CONNECT_ERROR;
 
1408
#endif
 
1409
    req_method = SSLv3_client_method();
 
1410
    use_sni(FALSE);
 
1411
    break;
 
1412
  }
 
1413
 
 
1414
  if(connssl->ctx)
 
1415
    SSL_CTX_free(connssl->ctx);
 
1416
  connssl->ctx = SSL_CTX_new(req_method);
 
1417
 
 
1418
  if(!connssl->ctx) {
 
1419
    failf(data, "SSL: couldn't create a context: %s",
 
1420
          ERR_error_string(ERR_peek_error(), NULL));
 
1421
    return CURLE_OUT_OF_MEMORY;
 
1422
  }
 
1423
 
 
1424
#ifdef SSL_MODE_RELEASE_BUFFERS
 
1425
  SSL_CTX_set_mode(connssl->ctx, SSL_MODE_RELEASE_BUFFERS);
 
1426
#endif
 
1427
 
 
1428
#ifdef SSL_CTRL_SET_MSG_CALLBACK
 
1429
  if(data->set.fdebug && data->set.verbose) {
 
1430
    /* the SSL trace callback is only used for verbose logging so we only
 
1431
       inform about failures of setting it */
 
1432
    if(!SSL_CTX_callback_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK,
 
1433
                               (void (*)(void))ssl_tls_trace)) {
 
1434
      infof(data, "SSL: couldn't set callback!\n");
 
1435
    }
 
1436
    else if(!SSL_CTX_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK_ARG, 0,
 
1437
                          conn)) {
 
1438
      infof(data, "SSL: couldn't set callback argument!\n");
 
1439
    }
 
1440
  }
 
1441
#endif
 
1442
 
 
1443
  /* OpenSSL contains code to work-around lots of bugs and flaws in various
 
1444
     SSL-implementations. SSL_CTX_set_options() is used to enabled those
 
1445
     work-arounds. The man page for this option states that SSL_OP_ALL enables
 
1446
     all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
 
1447
     enable the bug workaround options if compatibility with somewhat broken
 
1448
     implementations is desired."
 
1449
 
 
1450
     The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
 
1451
     disable "rfc4507bis session ticket support".  rfc4507bis was later turned
 
1452
     into the proper RFC5077 it seems: http://tools.ietf.org/html/rfc5077
 
1453
 
 
1454
     The enabled extension concerns the session management. I wonder how often
 
1455
     libcurl stops a connection and then resumes a TLS session. also, sending
 
1456
     the session data is some overhead. .I suggest that you just use your
 
1457
     proposed patch (which explicitly disables TICKET).
 
1458
 
 
1459
     If someone writes an application with libcurl and openssl who wants to
 
1460
     enable the feature, one can do this in the SSL callback.
 
1461
 
 
1462
     SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
 
1463
     interoperability with web server Netscape Enterprise Server 2.0.1 which
 
1464
     was released back in 1996.
 
1465
 
 
1466
     Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
 
1467
     become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
 
1468
     CVE-2010-4180 when using previous OpenSSL versions we no longer enable
 
1469
     this option regardless of OpenSSL version and SSL_OP_ALL definition.
 
1470
 
 
1471
     OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
 
1472
     (http://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
 
1473
     SSL_OP_ALL that _disables_ that work-around despite the fact that
 
1474
     SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
 
1475
     keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
 
1476
     must not be set.
 
1477
  */
 
1478
 
 
1479
  ctx_options = SSL_OP_ALL;
 
1480
 
 
1481
#ifdef SSL_OP_NO_TICKET
 
1482
  ctx_options |= SSL_OP_NO_TICKET;
 
1483
#endif
 
1484
 
 
1485
#ifdef SSL_OP_NO_COMPRESSION
 
1486
  ctx_options |= SSL_OP_NO_COMPRESSION;
 
1487
#endif
 
1488
 
 
1489
#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
 
1490
  /* mitigate CVE-2010-4180 */
 
1491
  ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
 
1492
#endif
 
1493
 
 
1494
#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
 
1495
  /* unless the user explicitly ask to allow the protocol vulnerability we
 
1496
     use the work-around */
 
1497
  if(!conn->data->set.ssl_enable_beast)
 
1498
    ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
 
1499
#endif
 
1500
 
 
1501
  /* disable SSLv2 in the default case (i.e. allow SSLv3 and TLSv1) */
 
1502
  if(data->set.ssl.version == CURL_SSLVERSION_DEFAULT)
 
1503
    ctx_options |= SSL_OP_NO_SSLv2;
 
1504
 
 
1505
  SSL_CTX_set_options(connssl->ctx, ctx_options);
 
1506
 
 
1507
  if(data->set.str[STRING_CERT] || data->set.str[STRING_CERT_TYPE]) {
 
1508
    if(!cert_stuff(conn,
 
1509
                   connssl->ctx,
 
1510
                   data->set.str[STRING_CERT],
 
1511
                   data->set.str[STRING_CERT_TYPE],
 
1512
                   data->set.str[STRING_KEY],
 
1513
                   data->set.str[STRING_KEY_TYPE])) {
 
1514
      /* failf() is already done in cert_stuff() */
 
1515
      return CURLE_SSL_CERTPROBLEM;
 
1516
    }
 
1517
  }
 
1518
 
 
1519
  if(data->set.str[STRING_SSL_CIPHER_LIST]) {
 
1520
    if(!SSL_CTX_set_cipher_list(connssl->ctx,
 
1521
                                data->set.str[STRING_SSL_CIPHER_LIST])) {
 
1522
      failf(data, "failed setting cipher list");
 
1523
      return CURLE_SSL_CIPHER;
 
1524
    }
 
1525
  }
 
1526
 
 
1527
#ifdef USE_TLS_SRP
 
1528
  if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
 
1529
    infof(data, "Using TLS-SRP username: %s\n", data->set.ssl.username);
 
1530
 
 
1531
    if(!SSL_CTX_set_srp_username(connssl->ctx, data->set.ssl.username)) {
 
1532
      failf(data, "Unable to set SRP user name");
 
1533
      return CURLE_BAD_FUNCTION_ARGUMENT;
 
1534
    }
 
1535
    if(!SSL_CTX_set_srp_password(connssl->ctx,data->set.ssl.password)) {
 
1536
      failf(data, "failed setting SRP password");
 
1537
      return CURLE_BAD_FUNCTION_ARGUMENT;
 
1538
    }
 
1539
    if(!data->set.str[STRING_SSL_CIPHER_LIST]) {
 
1540
      infof(data, "Setting cipher list SRP\n");
 
1541
 
 
1542
      if(!SSL_CTX_set_cipher_list(connssl->ctx, "SRP")) {
 
1543
        failf(data, "failed setting SRP cipher list");
 
1544
        return CURLE_SSL_CIPHER;
 
1545
      }
 
1546
    }
 
1547
  }
 
1548
#endif
 
1549
  if(data->set.str[STRING_SSL_CAFILE] || data->set.str[STRING_SSL_CAPATH]) {
 
1550
    /* tell SSL where to find CA certificates that are used to verify
 
1551
       the servers certificate. */
 
1552
    if(!SSL_CTX_load_verify_locations(connssl->ctx,
 
1553
                                       data->set.str[STRING_SSL_CAFILE],
 
1554
                                       data->set.str[STRING_SSL_CAPATH])) {
 
1555
      if(data->set.ssl.verifypeer) {
 
1556
        /* Fail if we insist on successfully verifying the server. */
 
1557
        failf(data,"error setting certificate verify locations:\n"
 
1558
              "  CAfile: %s\n  CApath: %s",
 
1559
              data->set.str[STRING_SSL_CAFILE]?
 
1560
              data->set.str[STRING_SSL_CAFILE]: "none",
 
1561
              data->set.str[STRING_SSL_CAPATH]?
 
1562
              data->set.str[STRING_SSL_CAPATH] : "none");
 
1563
        return CURLE_SSL_CACERT_BADFILE;
 
1564
      }
 
1565
      else {
 
1566
        /* Just continue with a warning if no strict  certificate verification
 
1567
           is required. */
 
1568
        infof(data, "error setting certificate verify locations,"
 
1569
              " continuing anyway:\n");
 
1570
      }
 
1571
    }
 
1572
    else {
 
1573
      /* Everything is fine. */
 
1574
      infof(data, "successfully set certificate verify locations:\n");
 
1575
    }
 
1576
    infof(data,
 
1577
          "  CAfile: %s\n"
 
1578
          "  CApath: %s\n",
 
1579
          data->set.str[STRING_SSL_CAFILE] ? data->set.str[STRING_SSL_CAFILE]:
 
1580
          "none",
 
1581
          data->set.str[STRING_SSL_CAPATH] ? data->set.str[STRING_SSL_CAPATH]:
 
1582
          "none");
 
1583
  }
 
1584
 
 
1585
  if(data->set.str[STRING_SSL_CRLFILE]) {
 
1586
    /* tell SSL where to find CRL file that is used to check certificate
 
1587
     * revocation */
 
1588
    lookup=X509_STORE_add_lookup(SSL_CTX_get_cert_store(connssl->ctx),
 
1589
                                 X509_LOOKUP_file());
 
1590
    if(!lookup ||
 
1591
       (!X509_load_crl_file(lookup,data->set.str[STRING_SSL_CRLFILE],
 
1592
                            X509_FILETYPE_PEM)) ) {
 
1593
      failf(data,"error loading CRL file: %s",
 
1594
            data->set.str[STRING_SSL_CRLFILE]);
 
1595
      return CURLE_SSL_CRL_BADFILE;
 
1596
    }
 
1597
    else {
 
1598
      /* Everything is fine. */
 
1599
      infof(data, "successfully load CRL file:\n");
 
1600
      X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
 
1601
                           X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
 
1602
    }
 
1603
    infof(data,
 
1604
          "  CRLfile: %s\n", data->set.str[STRING_SSL_CRLFILE] ?
 
1605
          data->set.str[STRING_SSL_CRLFILE]: "none");
 
1606
  }
 
1607
 
 
1608
  /* SSL always tries to verify the peer, this only says whether it should
 
1609
   * fail to connect if the verification fails, or if it should continue
 
1610
   * anyway. In the latter case the result of the verification is checked with
 
1611
   * SSL_get_verify_result() below. */
 
1612
  SSL_CTX_set_verify(connssl->ctx,
 
1613
                     data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE,
 
1614
                     cert_verify_callback);
 
1615
 
 
1616
  /* give application a chance to interfere with SSL set up. */
 
1617
  if(data->set.ssl.fsslctx) {
 
1618
    retcode = (*data->set.ssl.fsslctx)(data, connssl->ctx,
 
1619
                                       data->set.ssl.fsslctxp);
 
1620
    if(retcode) {
 
1621
      failf(data,"error signaled by ssl ctx callback");
 
1622
      return retcode;
 
1623
    }
 
1624
  }
 
1625
 
 
1626
  /* Lets make an SSL structure */
 
1627
  if(connssl->handle)
 
1628
    SSL_free(connssl->handle);
 
1629
  connssl->handle = SSL_new(connssl->ctx);
 
1630
  if(!connssl->handle) {
 
1631
    failf(data, "SSL: couldn't create a context (handle)!");
 
1632
    return CURLE_OUT_OF_MEMORY;
 
1633
  }
 
1634
  SSL_set_connect_state(connssl->handle);
 
1635
 
 
1636
  connssl->server_cert = 0x0;
 
1637
 
 
1638
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
 
1639
  if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
 
1640
#ifdef ENABLE_IPV6
 
1641
     (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
 
1642
#endif
 
1643
     sni &&
 
1644
     !SSL_set_tlsext_host_name(connssl->handle, conn->host.name))
 
1645
    infof(data, "WARNING: failed to configure server name indication (SNI) "
 
1646
          "TLS extension\n");
 
1647
#endif
 
1648
 
 
1649
  /* Check if there's a cached ID we can/should use here! */
 
1650
  if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
 
1651
    /* we got a session id, use it! */
 
1652
    if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
 
1653
      failf(data, "SSL: SSL_set_session failed: %s",
 
1654
            ERR_error_string(ERR_get_error(),NULL));
 
1655
      return CURLE_SSL_CONNECT_ERROR;
 
1656
    }
 
1657
    /* Informational message */
 
1658
    infof (data, "SSL re-using session ID\n");
 
1659
  }
 
1660
 
 
1661
  /* pass the raw socket into the SSL layers */
 
1662
  if(!SSL_set_fd(connssl->handle, (int)sockfd)) {
 
1663
    failf(data, "SSL: SSL_set_fd failed: %s",
 
1664
          ERR_error_string(ERR_get_error(),NULL));
 
1665
    return CURLE_SSL_CONNECT_ERROR;
 
1666
  }
 
1667
 
 
1668
  connssl->connecting_state = ssl_connect_2;
 
1669
  return CURLE_OK;
 
1670
}
 
1671
 
 
1672
static CURLcode
 
1673
ossl_connect_step2(struct connectdata *conn, int sockindex)
 
1674
{
 
1675
  struct SessionHandle *data = conn->data;
 
1676
  int err;
 
1677
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
 
1678
 
 
1679
  DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
 
1680
             || ssl_connect_2_reading == connssl->connecting_state
 
1681
             || ssl_connect_2_writing == connssl->connecting_state);
 
1682
 
 
1683
  ERR_clear_error();
 
1684
 
 
1685
  err = SSL_connect(connssl->handle);
 
1686
 
 
1687
  /* 1  is fine
 
1688
     0  is "not successful but was shut down controlled"
 
1689
     <0 is "handshake was not successful, because a fatal error occurred" */
 
1690
  if(1 != err) {
 
1691
    int detail = SSL_get_error(connssl->handle, err);
 
1692
 
 
1693
    if(SSL_ERROR_WANT_READ == detail) {
 
1694
      connssl->connecting_state = ssl_connect_2_reading;
 
1695
      return CURLE_OK;
 
1696
    }
 
1697
    else if(SSL_ERROR_WANT_WRITE == detail) {
 
1698
      connssl->connecting_state = ssl_connect_2_writing;
 
1699
      return CURLE_OK;
 
1700
    }
 
1701
    else {
 
1702
      /* untreated error */
 
1703
      unsigned long errdetail;
 
1704
      char error_buffer[256]; /* OpenSSL documents that this must be at least
 
1705
                                 256 bytes long. */
 
1706
      CURLcode rc;
 
1707
      const char *cert_problem = NULL;
 
1708
      long lerr;
 
1709
 
 
1710
      connssl->connecting_state = ssl_connect_2; /* the connection failed,
 
1711
                                                    we're not waiting for
 
1712
                                                    anything else. */
 
1713
 
 
1714
      errdetail = ERR_get_error(); /* Gets the earliest error code from the
 
1715
                                      thread's error queue and removes the
 
1716
                                      entry. */
 
1717
 
 
1718
      switch(errdetail) {
 
1719
      case 0x1407E086:
 
1720
        /* 1407E086:
 
1721
           SSL routines:
 
1722
           SSL2_SET_CERTIFICATE:
 
1723
           certificate verify failed */
 
1724
        /* fall-through */
 
1725
      case 0x14090086:
 
1726
        /* 14090086:
 
1727
           SSL routines:
 
1728
           SSL3_GET_SERVER_CERTIFICATE:
 
1729
           certificate verify failed */
 
1730
        rc = CURLE_SSL_CACERT;
 
1731
 
 
1732
        lerr = SSL_get_verify_result(connssl->handle);
 
1733
        if(lerr != X509_V_OK) {
 
1734
          snprintf(error_buffer, sizeof(error_buffer),
 
1735
                   "SSL certificate problem: %s",
 
1736
                   X509_verify_cert_error_string(lerr));
 
1737
        }
 
1738
        else
 
1739
          cert_problem = "SSL certificate problem, verify that the CA cert is"
 
1740
            " OK.";
 
1741
 
 
1742
        break;
 
1743
      default:
 
1744
        rc = CURLE_SSL_CONNECT_ERROR;
 
1745
        SSL_strerror(errdetail, error_buffer, sizeof(error_buffer));
 
1746
        break;
 
1747
      }
 
1748
 
 
1749
      /* detail is already set to the SSL error above */
 
1750
 
 
1751
      /* If we e.g. use SSLv2 request-method and the server doesn't like us
 
1752
       * (RST connection etc.), OpenSSL gives no explanation whatsoever and
 
1753
       * the SO_ERROR is also lost.
 
1754
       */
 
1755
      if(CURLE_SSL_CONNECT_ERROR == rc && errdetail == 0) {
 
1756
        failf(data, "Unknown SSL protocol error in connection to %s:%ld ",
 
1757
              conn->host.name, conn->port);
 
1758
        return rc;
 
1759
      }
 
1760
      /* Could be a CERT problem */
 
1761
 
 
1762
      failf(data, "%s%s", cert_problem ? cert_problem : "", error_buffer);
 
1763
      return rc;
 
1764
    }
 
1765
  }
 
1766
  else {
 
1767
    /* we have been connected fine, we're not waiting for anything else. */
 
1768
    connssl->connecting_state = ssl_connect_3;
 
1769
 
 
1770
    /* Informational message */
 
1771
    infof (data, "SSL connection using %s\n",
 
1772
           SSL_get_cipher(connssl->handle));
 
1773
 
 
1774
    return CURLE_OK;
 
1775
  }
 
1776
}
 
1777
 
 
1778
static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
 
1779
{
 
1780
  int i, ilen;
 
1781
 
 
1782
  if((ilen = (int)len) < 0)
 
1783
    return 1; /* buffer too big */
 
1784
 
 
1785
  i = i2t_ASN1_OBJECT(buf, ilen, a);
 
1786
 
 
1787
  if(i >= ilen)
 
1788
    return 1; /* buffer too small */
 
1789
 
 
1790
  return 0;
 
1791
}
 
1792
 
 
1793
static CURLcode push_certinfo_len(struct SessionHandle *data,
 
1794
                                  int certnum,
 
1795
                                  const char *label,
 
1796
                                  const char *value,
 
1797
                                  size_t valuelen)
 
1798
{
 
1799
  struct curl_certinfo *ci = &data->info.certs;
 
1800
  char *output;
 
1801
  struct curl_slist *nl;
 
1802
  CURLcode res = CURLE_OK;
 
1803
  size_t labellen = strlen(label);
 
1804
  size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */
 
1805
 
 
1806
  output = malloc(outlen);
 
1807
  if(!output)
 
1808
    return CURLE_OUT_OF_MEMORY;
 
1809
 
 
1810
  /* sprintf the label and colon */
 
1811
  snprintf(output, outlen, "%s:", label);
 
1812
 
 
1813
  /* memcpy the value (it might not be zero terminated) */
 
1814
  memcpy(&output[labellen+1], value, valuelen);
 
1815
 
 
1816
  /* zero terminate the output */
 
1817
  output[labellen + 1 + valuelen] = 0;
 
1818
 
 
1819
  /* TODO: we should rather introduce an internal API that can do the
 
1820
     equivalent of curl_slist_append but doesn't strdup() the given data as
 
1821
     like in this place the extra malloc/free is totally pointless */
 
1822
  nl = curl_slist_append(ci->certinfo[certnum], output);
 
1823
  free(output);
 
1824
  if(!nl) {
 
1825
    curl_slist_free_all(ci->certinfo[certnum]);
 
1826
    ci->certinfo[certnum] = NULL;
 
1827
    res = CURLE_OUT_OF_MEMORY;
 
1828
  }
 
1829
  else
 
1830
    ci->certinfo[certnum] = nl;
 
1831
 
 
1832
  return res;
 
1833
}
 
1834
 
 
1835
/* this is a convenience function for push_certinfo_len that takes a zero
 
1836
   terminated value */
 
1837
static CURLcode push_certinfo(struct SessionHandle *data,
 
1838
                              int certnum,
 
1839
                              const char *label,
 
1840
                              const char *value)
 
1841
{
 
1842
  size_t valuelen = strlen(value);
 
1843
 
 
1844
  return push_certinfo_len(data, certnum, label, value, valuelen);
 
1845
}
 
1846
 
 
1847
static void pubkey_show(struct SessionHandle *data,
 
1848
                        int num,
 
1849
                        const char *type,
 
1850
                        const char *name,
 
1851
                        unsigned char *raw,
 
1852
                        int len)
 
1853
{
 
1854
  size_t left;
 
1855
  int i;
 
1856
  char namebuf[32];
 
1857
  char *buffer;
 
1858
 
 
1859
  left = len*3 + 1;
 
1860
  buffer = malloc(left);
 
1861
  if(buffer) {
 
1862
    char *ptr=buffer;
 
1863
    snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
 
1864
    for(i=0; i< len; i++) {
 
1865
      snprintf(ptr, left, "%02x:", raw[i]);
 
1866
      ptr += 3;
 
1867
      left -= 3;
 
1868
    }
 
1869
    infof(data, "   %s: %s\n", namebuf, buffer);
 
1870
    push_certinfo(data, num, namebuf, buffer);
 
1871
    free(buffer);
 
1872
  }
 
1873
}
 
1874
 
 
1875
#define print_pubkey_BN(_type, _name, _num)    \
 
1876
do {                              \
 
1877
  if(pubkey->pkey._type->_name != NULL) { \
 
1878
    int len = BN_num_bytes(pubkey->pkey._type->_name);  \
 
1879
    if(len < CERTBUFFERSIZE) {                                    \
 
1880
      BN_bn2bin(pubkey->pkey._type->_name, (unsigned char*)bufp); \
 
1881
      bufp[len] = 0;                                                    \
 
1882
      pubkey_show(data, _num, #_type, #_name, (unsigned char*)bufp, len); \
 
1883
    } \
 
1884
  } \
 
1885
} WHILE_FALSE
 
1886
 
 
1887
static int X509V3_ext(struct SessionHandle *data,
 
1888
                      int certnum,
 
1889
                      STACK_OF(X509_EXTENSION) *exts)
 
1890
{
 
1891
  int i;
 
1892
  size_t j;
 
1893
 
 
1894
  if(sk_X509_EXTENSION_num(exts) <= 0)
 
1895
    /* no extensions, bail out */
 
1896
    return 1;
 
1897
 
 
1898
  for(i=0; i<sk_X509_EXTENSION_num(exts); i++) {
 
1899
    ASN1_OBJECT *obj;
 
1900
    X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
 
1901
    BUF_MEM *biomem;
 
1902
    char buf[512];
 
1903
    char *ptr=buf;
 
1904
    char namebuf[128];
 
1905
    BIO *bio_out = BIO_new(BIO_s_mem());
 
1906
 
 
1907
    if(!bio_out)
 
1908
      return 1;
 
1909
 
 
1910
    obj = X509_EXTENSION_get_object(ext);
 
1911
 
 
1912
    asn1_object_dump(obj, namebuf, sizeof(namebuf));
 
1913
 
 
1914
    infof(data, "%s: %s\n", namebuf,
 
1915
          X509_EXTENSION_get_critical(ext)?"(critical)":"");
 
1916
 
 
1917
    if(!X509V3_EXT_print(bio_out, ext, 0, 0))
 
1918
      M_ASN1_OCTET_STRING_print(bio_out, ext->value);
 
1919
 
 
1920
    BIO_get_mem_ptr(bio_out, &biomem);
 
1921
 
 
1922
    /* biomem->length bytes at biomem->data, this little loop here is only
 
1923
       done for the infof() call, we send the "raw" data to the certinfo
 
1924
       function */
 
1925
    for(j=0; j<(size_t)biomem->length; j++) {
 
1926
      const char *sep="";
 
1927
      if(biomem->data[j] == '\n') {
 
1928
        sep=", ";
 
1929
        j++; /* skip the newline */
 
1930
      };
 
1931
      while((biomem->data[j] == ' ') && (j<(size_t)biomem->length))
 
1932
        j++;
 
1933
      if(j<(size_t)biomem->length)
 
1934
        ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
 
1935
                      biomem->data[j]);
 
1936
    }
 
1937
    infof(data, "  %s\n", buf);
 
1938
 
 
1939
    push_certinfo(data, certnum, namebuf, buf);
 
1940
 
 
1941
    BIO_free(bio_out);
 
1942
 
 
1943
  }
 
1944
  return 0; /* all is fine */
 
1945
}
 
1946
 
 
1947
 
 
1948
static void X509_signature(struct SessionHandle *data,
 
1949
                           int numcert,
 
1950
                           ASN1_STRING *sig)
 
1951
{
 
1952
  char buf[1024];
 
1953
  char *ptr = buf;
 
1954
  int i;
 
1955
  for(i=0; i<sig->length; i++)
 
1956
    ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%02x:", sig->data[i]);
 
1957
 
 
1958
  infof(data, " Signature: %s\n", buf);
 
1959
  push_certinfo(data, numcert, "Signature", buf);
 
1960
}
 
1961
 
 
1962
static void dumpcert(struct SessionHandle *data, X509 *x, int numcert)
 
1963
{
 
1964
  BIO *bio_out = BIO_new(BIO_s_mem());
 
1965
  BUF_MEM *biomem;
 
1966
 
 
1967
  /* this outputs the cert in this 64 column wide style with newlines and
 
1968
     -----BEGIN CERTIFICATE----- texts and more */
 
1969
  PEM_write_bio_X509(bio_out, x);
 
1970
 
 
1971
  BIO_get_mem_ptr(bio_out, &biomem);
 
1972
 
 
1973
  infof(data, "%s\n", biomem->data);
 
1974
 
 
1975
  push_certinfo_len(data, numcert, "Cert", biomem->data, biomem->length);
 
1976
 
 
1977
  BIO_free(bio_out);
 
1978
 
 
1979
}
 
1980
 
 
1981
 
 
1982
static int init_certinfo(struct SessionHandle *data,
 
1983
                         int num)
 
1984
{
 
1985
  struct curl_certinfo *ci = &data->info.certs;
 
1986
  struct curl_slist **table;
 
1987
 
 
1988
  Curl_ssl_free_certinfo(data);
 
1989
 
 
1990
  ci->num_of_certs = num;
 
1991
  table = calloc((size_t)num, sizeof(struct curl_slist *));
 
1992
  if(!table)
 
1993
    return 1;
 
1994
 
 
1995
  ci->certinfo = table;
 
1996
  return 0;
 
1997
}
 
1998
 
 
1999
/*
 
2000
 * This size was previously 512 which has been reported "too small" without
 
2001
 * any specifics, so it was enlarged to allow more data to get shown uncut.
 
2002
 * The "perfect" size is yet to figure out.
 
2003
 */
 
2004
#define CERTBUFFERSIZE 8192
 
2005
 
 
2006
static CURLcode get_cert_chain(struct connectdata *conn,
 
2007
                               struct ssl_connect_data *connssl)
 
2008
 
 
2009
{
 
2010
  STACK_OF(X509) *sk;
 
2011
  int i;
 
2012
  char *bufp;
 
2013
  struct SessionHandle *data = conn->data;
 
2014
  int numcerts;
 
2015
 
 
2016
  bufp = malloc(CERTBUFFERSIZE);
 
2017
  if(!bufp)
 
2018
    return CURLE_OUT_OF_MEMORY;
 
2019
 
 
2020
  sk = SSL_get_peer_cert_chain(connssl->handle);
 
2021
  if(!sk) {
 
2022
    free(bufp);
 
2023
    return CURLE_OUT_OF_MEMORY;
 
2024
  }
 
2025
 
 
2026
  numcerts = sk_X509_num(sk);
 
2027
  if(init_certinfo(data, numcerts)) {
 
2028
    free(bufp);
 
2029
    return CURLE_OUT_OF_MEMORY;
 
2030
  }
 
2031
 
 
2032
  infof(data, "--- Certificate chain\n");
 
2033
  for(i=0; i<numcerts; i++) {
 
2034
    long value;
 
2035
    ASN1_INTEGER *num;
 
2036
    ASN1_TIME *certdate;
 
2037
 
 
2038
    /* get the certs in "importance order" */
 
2039
#if 0
 
2040
    X509 *x = sk_X509_value(sk, numcerts - i - 1);
 
2041
#else
 
2042
    X509 *x = sk_X509_value(sk, i);
 
2043
#endif
 
2044
 
 
2045
    X509_CINF *cinf;
 
2046
    EVP_PKEY *pubkey=NULL;
 
2047
    int j;
 
2048
    char *ptr;
 
2049
 
 
2050
    (void)x509_name_oneline(X509_get_subject_name(x), bufp, CERTBUFFERSIZE);
 
2051
    infof(data, "%2d Subject: %s\n", i, bufp);
 
2052
    push_certinfo(data, i, "Subject", bufp);
 
2053
 
 
2054
    (void)x509_name_oneline(X509_get_issuer_name(x), bufp, CERTBUFFERSIZE);
 
2055
    infof(data, "   Issuer: %s\n", bufp);
 
2056
    push_certinfo(data, i, "Issuer", bufp);
 
2057
 
 
2058
    value = X509_get_version(x);
 
2059
    infof(data, "   Version: %lu (0x%lx)\n", value+1, value);
 
2060
    snprintf(bufp, CERTBUFFERSIZE, "%lx", value);
 
2061
    push_certinfo(data, i, "Version", bufp); /* hex */
 
2062
 
 
2063
    num=X509_get_serialNumber(x);
 
2064
    if(num->length <= 4) {
 
2065
      value = ASN1_INTEGER_get(num);
 
2066
      infof(data,"   Serial Number: %ld (0x%lx)\n", value, value);
 
2067
      snprintf(bufp, CERTBUFFERSIZE, "%lx", value);
 
2068
    }
 
2069
    else {
 
2070
      int left = CERTBUFFERSIZE;
 
2071
 
 
2072
      ptr = bufp;
 
2073
      *ptr++ = 0;
 
2074
      if(num->type == V_ASN1_NEG_INTEGER)
 
2075
        *ptr++='-';
 
2076
 
 
2077
      for(j=0; (j<num->length) && (left>=4); j++) {
 
2078
        /* TODO: length restrictions */
 
2079
        snprintf(ptr, 3, "%02x%c",num->data[j],
 
2080
                 ((j+1 == num->length)?'\n':':'));
 
2081
        ptr += 3;
 
2082
        left-=4;
 
2083
      }
 
2084
      if(num->length)
 
2085
        infof(data,"   Serial Number: %s\n", bufp);
 
2086
      else
 
2087
        bufp[0]=0;
 
2088
    }
 
2089
    if(bufp[0])
 
2090
      push_certinfo(data, i, "Serial Number", bufp); /* hex */
 
2091
 
 
2092
    cinf = x->cert_info;
 
2093
 
 
2094
    j = asn1_object_dump(cinf->signature->algorithm, bufp, CERTBUFFERSIZE);
 
2095
    if(!j) {
 
2096
      infof(data, "   Signature Algorithm: %s\n", bufp);
 
2097
      push_certinfo(data, i, "Signature Algorithm", bufp);
 
2098
    }
 
2099
 
 
2100
    certdate = X509_get_notBefore(x);
 
2101
    asn1_output(certdate, bufp, CERTBUFFERSIZE);
 
2102
    infof(data, "   Start date: %s\n", bufp);
 
2103
    push_certinfo(data, i, "Start date", bufp);
 
2104
 
 
2105
    certdate = X509_get_notAfter(x);
 
2106
    asn1_output(certdate, bufp, CERTBUFFERSIZE);
 
2107
    infof(data, "   Expire date: %s\n", bufp);
 
2108
    push_certinfo(data, i, "Expire date", bufp);
 
2109
 
 
2110
    j = asn1_object_dump(cinf->key->algor->algorithm, bufp, CERTBUFFERSIZE);
 
2111
    if(!j) {
 
2112
      infof(data, "   Public Key Algorithm: %s\n", bufp);
 
2113
      push_certinfo(data, i, "Public Key Algorithm", bufp);
 
2114
    }
 
2115
 
 
2116
    pubkey = X509_get_pubkey(x);
 
2117
    if(!pubkey)
 
2118
      infof(data, "   Unable to load public key\n");
 
2119
    else {
 
2120
      switch(pubkey->type) {
 
2121
      case EVP_PKEY_RSA:
 
2122
        infof(data,  "   RSA Public Key (%d bits)\n",
 
2123
              BN_num_bits(pubkey->pkey.rsa->n));
 
2124
        snprintf(bufp, CERTBUFFERSIZE, "%d", BN_num_bits(pubkey->pkey.rsa->n));
 
2125
        push_certinfo(data, i, "RSA Public Key", bufp);
 
2126
 
 
2127
        print_pubkey_BN(rsa, n, i);
 
2128
        print_pubkey_BN(rsa, e, i);
 
2129
        print_pubkey_BN(rsa, d, i);
 
2130
        print_pubkey_BN(rsa, p, i);
 
2131
        print_pubkey_BN(rsa, q, i);
 
2132
        print_pubkey_BN(rsa, dmp1, i);
 
2133
        print_pubkey_BN(rsa, dmq1, i);
 
2134
        print_pubkey_BN(rsa, iqmp, i);
 
2135
        break;
 
2136
      case EVP_PKEY_DSA:
 
2137
        print_pubkey_BN(dsa, p, i);
 
2138
        print_pubkey_BN(dsa, q, i);
 
2139
        print_pubkey_BN(dsa, g, i);
 
2140
        print_pubkey_BN(dsa, priv_key, i);
 
2141
        print_pubkey_BN(dsa, pub_key, i);
 
2142
        break;
 
2143
      case EVP_PKEY_DH:
 
2144
        print_pubkey_BN(dh, p, i);
 
2145
        print_pubkey_BN(dh, g, i);
 
2146
        print_pubkey_BN(dh, priv_key, i);
 
2147
        print_pubkey_BN(dh, pub_key, i);
 
2148
        break;
 
2149
#if 0
 
2150
      case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
 
2151
        /* left TODO */
 
2152
        break;
 
2153
#endif
 
2154
      }
 
2155
      EVP_PKEY_free(pubkey);
 
2156
    }
 
2157
 
 
2158
    X509V3_ext(data, i, cinf->extensions);
 
2159
 
 
2160
    X509_signature(data, i, x->signature);
 
2161
 
 
2162
    dumpcert(data, x, i);
 
2163
  }
 
2164
 
 
2165
  free(bufp);
 
2166
 
 
2167
  return CURLE_OK;
 
2168
}
 
2169
 
 
2170
/*
 
2171
 * Get the server cert, verify it and show it etc, only call failf() if the
 
2172
 * 'strict' argument is TRUE as otherwise all this is for informational
 
2173
 * purposes only!
 
2174
 *
 
2175
 * We check certificates to authenticate the server; otherwise we risk
 
2176
 * man-in-the-middle attack.
 
2177
 */
 
2178
static CURLcode servercert(struct connectdata *conn,
 
2179
                           struct ssl_connect_data *connssl,
 
2180
                           bool strict)
 
2181
{
 
2182
  CURLcode retcode = CURLE_OK;
 
2183
  int rc;
 
2184
  long lerr;
 
2185
  ASN1_TIME *certdate;
 
2186
  struct SessionHandle *data = conn->data;
 
2187
  X509 *issuer;
 
2188
  FILE *fp;
 
2189
  char *buffer = data->state.buffer;
 
2190
 
 
2191
  if(data->set.ssl.certinfo)
 
2192
    /* we've been asked to gather certificate info! */
 
2193
    (void)get_cert_chain(conn, connssl);
 
2194
 
 
2195
  data->set.ssl.certverifyresult = !X509_V_OK;
 
2196
 
 
2197
  connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
 
2198
  if(!connssl->server_cert) {
 
2199
    if(strict)
 
2200
      failf(data, "SSL: couldn't get peer certificate!");
 
2201
    return CURLE_PEER_FAILED_VERIFICATION;
 
2202
  }
 
2203
  infof (data, "Server certificate:\n");
 
2204
 
 
2205
  rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
 
2206
                         buffer, BUFSIZE);
 
2207
  infof(data, "\t subject: %s\n", rc?"[NONE]":buffer);
 
2208
 
 
2209
  certdate = X509_get_notBefore(connssl->server_cert);
 
2210
  asn1_output(certdate, buffer, BUFSIZE);
 
2211
  infof(data, "\t start date: %s\n", buffer);
 
2212
 
 
2213
  certdate = X509_get_notAfter(connssl->server_cert);
 
2214
  asn1_output(certdate, buffer, BUFSIZE);
 
2215
  infof(data, "\t expire date: %s\n", buffer);
 
2216
 
 
2217
  if(data->set.ssl.verifyhost) {
 
2218
    retcode = verifyhost(conn, connssl->server_cert);
 
2219
    if(retcode) {
 
2220
      X509_free(connssl->server_cert);
 
2221
      connssl->server_cert = NULL;
 
2222
      return retcode;
 
2223
    }
 
2224
  }
 
2225
 
 
2226
  rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
 
2227
                         buffer, BUFSIZE);
 
2228
  if(rc) {
 
2229
    if(strict)
 
2230
      failf(data, "SSL: couldn't get X509-issuer name!");
 
2231
    retcode = CURLE_SSL_CONNECT_ERROR;
 
2232
  }
 
2233
  else {
 
2234
    infof(data, "\t issuer: %s\n", buffer);
 
2235
 
 
2236
    /* We could do all sorts of certificate verification stuff here before
 
2237
       deallocating the certificate. */
 
2238
 
 
2239
    /* e.g. match issuer name with provided issuer certificate */
 
2240
    if(data->set.str[STRING_SSL_ISSUERCERT]) {
 
2241
      fp=fopen(data->set.str[STRING_SSL_ISSUERCERT],"r");
 
2242
      if(!fp) {
 
2243
        if(strict)
 
2244
          failf(data, "SSL: Unable to open issuer cert (%s)",
 
2245
                data->set.str[STRING_SSL_ISSUERCERT]);
 
2246
        X509_free(connssl->server_cert);
 
2247
        connssl->server_cert = NULL;
 
2248
        return CURLE_SSL_ISSUER_ERROR;
 
2249
      }
 
2250
      issuer = PEM_read_X509(fp,NULL,ZERO_NULL,NULL);
 
2251
      if(!issuer) {
 
2252
        if(strict)
 
2253
          failf(data, "SSL: Unable to read issuer cert (%s)",
 
2254
                data->set.str[STRING_SSL_ISSUERCERT]);
 
2255
        X509_free(connssl->server_cert);
 
2256
        X509_free(issuer);
 
2257
        fclose(fp);
 
2258
        return CURLE_SSL_ISSUER_ERROR;
 
2259
      }
 
2260
      fclose(fp);
 
2261
      if(X509_check_issued(issuer,connssl->server_cert) != X509_V_OK) {
 
2262
        if(strict)
 
2263
          failf(data, "SSL: Certificate issuer check failed (%s)",
 
2264
                data->set.str[STRING_SSL_ISSUERCERT]);
 
2265
        X509_free(connssl->server_cert);
 
2266
        X509_free(issuer);
 
2267
        connssl->server_cert = NULL;
 
2268
        return CURLE_SSL_ISSUER_ERROR;
 
2269
      }
 
2270
      infof(data, "\t SSL certificate issuer check ok (%s)\n",
 
2271
            data->set.str[STRING_SSL_ISSUERCERT]);
 
2272
      X509_free(issuer);
 
2273
    }
 
2274
 
 
2275
    lerr = data->set.ssl.certverifyresult=
 
2276
      SSL_get_verify_result(connssl->handle);
 
2277
    if(data->set.ssl.certverifyresult != X509_V_OK) {
 
2278
      if(data->set.ssl.verifypeer) {
 
2279
        /* We probably never reach this, because SSL_connect() will fail
 
2280
           and we return earlier if verifypeer is set? */
 
2281
        if(strict)
 
2282
          failf(data, "SSL certificate verify result: %s (%ld)",
 
2283
                X509_verify_cert_error_string(lerr), lerr);
 
2284
        retcode = CURLE_PEER_FAILED_VERIFICATION;
 
2285
      }
 
2286
      else
 
2287
        infof(data, "\t SSL certificate verify result: %s (%ld),"
 
2288
              " continuing anyway.\n",
 
2289
              X509_verify_cert_error_string(lerr), lerr);
 
2290
    }
 
2291
    else
 
2292
      infof(data, "\t SSL certificate verify ok.\n");
 
2293
  }
 
2294
 
 
2295
  X509_free(connssl->server_cert);
 
2296
  connssl->server_cert = NULL;
 
2297
  connssl->connecting_state = ssl_connect_done;
 
2298
 
 
2299
  return retcode;
 
2300
}
 
2301
 
 
2302
 
 
2303
static CURLcode
 
2304
ossl_connect_step3(struct connectdata *conn,
 
2305
                   int sockindex)
 
2306
{
 
2307
  CURLcode retcode = CURLE_OK;
 
2308
  void *old_ssl_sessionid=NULL;
 
2309
  struct SessionHandle *data = conn->data;
 
2310
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
 
2311
  int incache;
 
2312
  SSL_SESSION *our_ssl_sessionid;
 
2313
 
 
2314
  DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
 
2315
 
 
2316
#ifdef HAVE_SSL_GET1_SESSION
 
2317
  our_ssl_sessionid = SSL_get1_session(connssl->handle);
 
2318
 
 
2319
  /* SSL_get1_session() will increment the reference
 
2320
     count and the session will stay in memory until explicitly freed with
 
2321
     SSL_SESSION_free(3), regardless of its state.
 
2322
     This function was introduced in openssl 0.9.5a. */
 
2323
#else
 
2324
  our_ssl_sessionid = SSL_get_session(connssl->handle);
 
2325
 
 
2326
  /* if SSL_get1_session() is unavailable, use SSL_get_session().
 
2327
     This is an inferior option because the session can be flushed
 
2328
     at any time by openssl. It is included only so curl compiles
 
2329
     under versions of openssl < 0.9.5a.
 
2330
 
 
2331
     WARNING: How curl behaves if it's session is flushed is
 
2332
     untested.
 
2333
  */
 
2334
#endif
 
2335
 
 
2336
  incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL));
 
2337
  if(incache) {
 
2338
    if(old_ssl_sessionid != our_ssl_sessionid) {
 
2339
      infof(data, "old SSL session ID is stale, removing\n");
 
2340
      Curl_ssl_delsessionid(conn, old_ssl_sessionid);
 
2341
      incache = FALSE;
 
2342
    }
 
2343
  }
 
2344
  if(!incache) {
 
2345
    retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
 
2346
                                    0 /* unknown size */);
 
2347
    if(retcode) {
 
2348
      failf(data, "failed to store ssl session");
 
2349
      return retcode;
 
2350
    }
 
2351
  }
 
2352
#ifdef HAVE_SSL_GET1_SESSION
 
2353
  else {
 
2354
    /* Session was incache, so refcount already incremented earlier.
 
2355
     * Avoid further increments with each SSL_get1_session() call.
 
2356
     * This does not free the session as refcount remains > 0
 
2357
     */
 
2358
    SSL_SESSION_free(our_ssl_sessionid);
 
2359
  }
 
2360
#endif
 
2361
 
 
2362
  /*
 
2363
   * We check certificates to authenticate the server; otherwise we risk
 
2364
   * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
 
2365
   * verify the peer ignore faults and failures from the server cert
 
2366
   * operations.
 
2367
   */
 
2368
 
 
2369
  if(!data->set.ssl.verifypeer)
 
2370
    (void)servercert(conn, connssl, FALSE);
 
2371
  else
 
2372
    retcode = servercert(conn, connssl, TRUE);
 
2373
 
 
2374
  if(CURLE_OK == retcode)
 
2375
    connssl->connecting_state = ssl_connect_done;
 
2376
  return retcode;
 
2377
}
 
2378
 
 
2379
static Curl_recv ossl_recv;
 
2380
static Curl_send ossl_send;
 
2381
 
 
2382
static CURLcode
 
2383
ossl_connect_common(struct connectdata *conn,
 
2384
                    int sockindex,
 
2385
                    bool nonblocking,
 
2386
                    bool *done)
 
2387
{
 
2388
  CURLcode retcode;
 
2389
  struct SessionHandle *data = conn->data;
 
2390
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
 
2391
  curl_socket_t sockfd = conn->sock[sockindex];
 
2392
  long timeout_ms;
 
2393
  int what;
 
2394
 
 
2395
  /* check if the connection has already been established */
 
2396
  if(ssl_connection_complete == connssl->state) {
 
2397
    *done = TRUE;
 
2398
    return CURLE_OK;
 
2399
  }
 
2400
 
 
2401
  if(ssl_connect_1==connssl->connecting_state) {
 
2402
    /* Find out how much more time we're allowed */
 
2403
    timeout_ms = Curl_timeleft(data, NULL, TRUE);
 
2404
 
 
2405
    if(timeout_ms < 0) {
 
2406
      /* no need to continue if time already is up */
 
2407
      failf(data, "SSL connection timeout");
 
2408
      return CURLE_OPERATION_TIMEDOUT;
 
2409
    }
 
2410
    retcode = ossl_connect_step1(conn, sockindex);
 
2411
    if(retcode)
 
2412
      return retcode;
 
2413
  }
 
2414
 
 
2415
  while(ssl_connect_2 == connssl->connecting_state ||
 
2416
        ssl_connect_2_reading == connssl->connecting_state ||
 
2417
        ssl_connect_2_writing == connssl->connecting_state) {
 
2418
 
 
2419
    /* check allowed time left */
 
2420
    timeout_ms = Curl_timeleft(data, NULL, TRUE);
 
2421
 
 
2422
    if(timeout_ms < 0) {
 
2423
      /* no need to continue if time already is up */
 
2424
      failf(data, "SSL connection timeout");
 
2425
      return CURLE_OPERATION_TIMEDOUT;
 
2426
    }
 
2427
 
 
2428
    /* if ssl is expecting something, check if it's available. */
 
2429
    if(connssl->connecting_state == ssl_connect_2_reading
 
2430
        || connssl->connecting_state == ssl_connect_2_writing) {
 
2431
 
 
2432
      curl_socket_t writefd = ssl_connect_2_writing==
 
2433
        connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
 
2434
      curl_socket_t readfd = ssl_connect_2_reading==
 
2435
        connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
 
2436
 
 
2437
      what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms);
 
2438
      if(what < 0) {
 
2439
        /* fatal error */
 
2440
        failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
 
2441
        return CURLE_SSL_CONNECT_ERROR;
 
2442
      }
 
2443
      else if(0 == what) {
 
2444
        if(nonblocking) {
 
2445
          *done = FALSE;
 
2446
          return CURLE_OK;
 
2447
        }
 
2448
        else {
 
2449
          /* timeout */
 
2450
          failf(data, "SSL connection timeout");
 
2451
          return CURLE_OPERATION_TIMEDOUT;
 
2452
        }
 
2453
      }
 
2454
      /* socket is readable or writable */
 
2455
    }
 
2456
 
 
2457
    /* Run transaction, and return to the caller if it failed or if this
 
2458
     * connection is done nonblocking and this loop would execute again. This
 
2459
     * permits the owner of a multi handle to abort a connection attempt
 
2460
     * before step2 has completed while ensuring that a client using select()
 
2461
     * or epoll() will always have a valid fdset to wait on.
 
2462
     */
 
2463
    retcode = ossl_connect_step2(conn, sockindex);
 
2464
    if(retcode || (nonblocking &&
 
2465
                   (ssl_connect_2 == connssl->connecting_state ||
 
2466
                    ssl_connect_2_reading == connssl->connecting_state ||
 
2467
                    ssl_connect_2_writing == connssl->connecting_state)))
 
2468
      return retcode;
 
2469
 
 
2470
  } /* repeat step2 until all transactions are done. */
 
2471
 
 
2472
 
 
2473
  if(ssl_connect_3==connssl->connecting_state) {
 
2474
    retcode = ossl_connect_step3(conn, sockindex);
 
2475
    if(retcode)
 
2476
      return retcode;
 
2477
  }
 
2478
 
 
2479
  if(ssl_connect_done==connssl->connecting_state) {
 
2480
    connssl->state = ssl_connection_complete;
 
2481
    conn->recv[sockindex] = ossl_recv;
 
2482
    conn->send[sockindex] = ossl_send;
 
2483
    *done = TRUE;
 
2484
  }
 
2485
  else
 
2486
    *done = FALSE;
 
2487
 
 
2488
  /* Reset our connect state machine */
 
2489
  connssl->connecting_state = ssl_connect_1;
 
2490
 
 
2491
  return CURLE_OK;
 
2492
}
 
2493
 
 
2494
CURLcode
 
2495
Curl_ossl_connect_nonblocking(struct connectdata *conn,
 
2496
                              int sockindex,
 
2497
                              bool *done)
 
2498
{
 
2499
  return ossl_connect_common(conn, sockindex, TRUE, done);
 
2500
}
 
2501
 
 
2502
CURLcode
 
2503
Curl_ossl_connect(struct connectdata *conn,
 
2504
                  int sockindex)
 
2505
{
 
2506
  CURLcode retcode;
 
2507
  bool done = FALSE;
 
2508
 
 
2509
  retcode = ossl_connect_common(conn, sockindex, FALSE, &done);
 
2510
  if(retcode)
 
2511
    return retcode;
 
2512
 
 
2513
  DEBUGASSERT(done);
 
2514
 
 
2515
  return CURLE_OK;
 
2516
}
 
2517
 
 
2518
bool Curl_ossl_data_pending(const struct connectdata *conn,
 
2519
                            int connindex)
 
2520
{
 
2521
  if(conn->ssl[connindex].handle)
 
2522
    /* SSL is in use */
 
2523
    return (0 != SSL_pending(conn->ssl[connindex].handle)) ? TRUE : FALSE;
 
2524
  else
 
2525
    return FALSE;
 
2526
}
 
2527
 
 
2528
static ssize_t ossl_send(struct connectdata *conn,
 
2529
                         int sockindex,
 
2530
                         const void *mem,
 
2531
                         size_t len,
 
2532
                         CURLcode *curlcode)
 
2533
{
 
2534
  /* SSL_write() is said to return 'int' while write() and send() returns
 
2535
     'size_t' */
 
2536
  int err;
 
2537
  char error_buffer[120]; /* OpenSSL documents that this must be at least 120
 
2538
                             bytes long. */
 
2539
  unsigned long sslerror;
 
2540
  int memlen;
 
2541
  int rc;
 
2542
 
 
2543
  ERR_clear_error();
 
2544
 
 
2545
  memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
 
2546
  rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
 
2547
 
 
2548
  if(rc <= 0) {
 
2549
    err = SSL_get_error(conn->ssl[sockindex].handle, rc);
 
2550
 
 
2551
    switch(err) {
 
2552
    case SSL_ERROR_WANT_READ:
 
2553
    case SSL_ERROR_WANT_WRITE:
 
2554
      /* The operation did not complete; the same TLS/SSL I/O function
 
2555
         should be called again later. This is basically an EWOULDBLOCK
 
2556
         equivalent. */
 
2557
      *curlcode = CURLE_AGAIN;
 
2558
      return -1;
 
2559
    case SSL_ERROR_SYSCALL:
 
2560
      failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
 
2561
            SOCKERRNO);
 
2562
      *curlcode = CURLE_SEND_ERROR;
 
2563
      return -1;
 
2564
    case SSL_ERROR_SSL:
 
2565
      /*  A failure in the SSL library occurred, usually a protocol error.
 
2566
          The OpenSSL error queue contains more information on the error. */
 
2567
      sslerror = ERR_get_error();
 
2568
      failf(conn->data, "SSL_write() error: %s",
 
2569
            ERR_error_string(sslerror, error_buffer));
 
2570
      *curlcode = CURLE_SEND_ERROR;
 
2571
      return -1;
 
2572
    }
 
2573
    /* a true error */
 
2574
    failf(conn->data, "SSL_write() return error %d", err);
 
2575
    *curlcode = CURLE_SEND_ERROR;
 
2576
    return -1;
 
2577
  }
 
2578
  return (ssize_t)rc; /* number of bytes */
 
2579
}
 
2580
 
 
2581
static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
 
2582
                         int num,                  /* socketindex */
 
2583
                         char *buf,                /* store read data here */
 
2584
                         size_t buffersize,        /* max amount to read */
 
2585
                         CURLcode *curlcode)
 
2586
{
 
2587
  char error_buffer[120]; /* OpenSSL documents that this must be at
 
2588
                             least 120 bytes long. */
 
2589
  unsigned long sslerror;
 
2590
  ssize_t nread;
 
2591
  int buffsize;
 
2592
 
 
2593
  ERR_clear_error();
 
2594
 
 
2595
  buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
 
2596
  nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize);
 
2597
  if(nread <= 0) {
 
2598
    /* failed SSL_read */
 
2599
    int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
 
2600
 
 
2601
    switch(err) {
 
2602
    case SSL_ERROR_NONE: /* this is not an error */
 
2603
    case SSL_ERROR_ZERO_RETURN: /* no more data */
 
2604
      break;
 
2605
    case SSL_ERROR_WANT_READ:
 
2606
    case SSL_ERROR_WANT_WRITE:
 
2607
      /* there's data pending, re-invoke SSL_read() */
 
2608
      *curlcode = CURLE_AGAIN;
 
2609
      return -1;
 
2610
    default:
 
2611
      /* openssl/ssl.h says "look at error stack/return value/errno" */
 
2612
      sslerror = ERR_get_error();
 
2613
      failf(conn->data, "SSL read: %s, errno %d",
 
2614
            ERR_error_string(sslerror, error_buffer),
 
2615
            SOCKERRNO);
 
2616
      *curlcode = CURLE_RECV_ERROR;
 
2617
      return -1;
 
2618
    }
 
2619
  }
 
2620
  return nread;
 
2621
}
 
2622
 
 
2623
size_t Curl_ossl_version(char *buffer, size_t size)
 
2624
{
 
2625
#ifdef YASSL_VERSION
 
2626
  /* yassl provides an OpenSSL API compatibility layer so it looks identical
 
2627
     to OpenSSL in all other aspects */
 
2628
  return snprintf(buffer, size, "yassl/%s", YASSL_VERSION);
 
2629
#else /* YASSL_VERSION */
 
2630
 
 
2631
#if(SSLEAY_VERSION_NUMBER >= 0x905000)
 
2632
  {
 
2633
    char sub[2];
 
2634
    unsigned long ssleay_value;
 
2635
    sub[1]='\0';
 
2636
    ssleay_value=SSLeay();
 
2637
    if(ssleay_value < 0x906000) {
 
2638
      ssleay_value=SSLEAY_VERSION_NUMBER;
 
2639
      sub[0]='\0';
 
2640
    }
 
2641
    else {
 
2642
      if(ssleay_value&0xff0) {
 
2643
        sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1);
 
2644
      }
 
2645
      else
 
2646
        sub[0]='\0';
 
2647
    }
 
2648
 
 
2649
    return snprintf(buffer, size, "OpenSSL/%lx.%lx.%lx%s",
 
2650
                    (ssleay_value>>28)&0xf,
 
2651
                    (ssleay_value>>20)&0xff,
 
2652
                    (ssleay_value>>12)&0xff,
 
2653
                    sub);
 
2654
  }
 
2655
 
 
2656
#else /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
 
2657
 
 
2658
#if(SSLEAY_VERSION_NUMBER >= 0x900000)
 
2659
  return snprintf(buffer, size, "OpenSSL/%lx.%lx.%lx",
 
2660
                  (SSLEAY_VERSION_NUMBER>>28)&0xff,
 
2661
                  (SSLEAY_VERSION_NUMBER>>20)&0xff,
 
2662
                  (SSLEAY_VERSION_NUMBER>>12)&0xf);
 
2663
 
 
2664
#else /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
 
2665
  {
 
2666
    char sub[2];
 
2667
    sub[1]='\0';
 
2668
    if(SSLEAY_VERSION_NUMBER&0x0f) {
 
2669
      sub[0]=(SSLEAY_VERSION_NUMBER&0x0f) + 'a' -1;
 
2670
    }
 
2671
    else
 
2672
      sub[0]='\0';
 
2673
 
 
2674
    return snprintf(buffer, size, "SSL/%x.%x.%x%s",
 
2675
                    (SSLEAY_VERSION_NUMBER>>12)&0xff,
 
2676
                    (SSLEAY_VERSION_NUMBER>>8)&0xf,
 
2677
                    (SSLEAY_VERSION_NUMBER>>4)&0xf, sub);
 
2678
  }
 
2679
#endif /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
 
2680
#endif /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
 
2681
 
 
2682
#endif /* YASSL_VERSION */
 
2683
}
 
2684
 
 
2685
void Curl_ossl_random(struct SessionHandle *data, unsigned char *entropy,
 
2686
                      size_t length)
 
2687
{
 
2688
  Curl_ossl_seed(data); /* Initiate the seed if not already done */
 
2689
  RAND_bytes(entropy, curlx_uztosi(length));
 
2690
}
 
2691
 
 
2692
void Curl_ossl_md5sum(unsigned char *tmp, /* input */
 
2693
                      size_t tmplen,
 
2694
                      unsigned char *md5sum /* output */,
 
2695
                      size_t unused)
 
2696
{
 
2697
  MD5_CTX MD5pw;
 
2698
  (void)unused;
 
2699
  MD5_Init(&MD5pw);
 
2700
  MD5_Update(&MD5pw, tmp, tmplen);
 
2701
  MD5_Final(md5sum, &MD5pw);
 
2702
}
 
2703
#endif /* USE_SSLEAY */