source: azure_iot_hub/trunk/curl-7.57.0/lib/vtls/openssl.c@ 388

Last change on this file since 388 was 388, checked in by coas-nagasima, 5 years ago

Azure IoT Hub Device C SDK を使ったサンプルの追加

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
  • Property svn:mime-type set to text/x-csrc
File size: 107.5 KB
Line 
1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2017, 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 https://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 vtls.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 USE_OPENSSL
36
37#ifdef HAVE_LIMITS_H
38#include <limits.h>
39#endif
40
41#include "urldata.h"
42#include "sendf.h"
43#include "formdata.h" /* for the boundary function */
44#include "url.h" /* for the ssl config check function */
45#include "inet_pton.h"
46#include "openssl.h"
47#include "connect.h"
48#include "slist.h"
49#include "select.h"
50#include "vtls.h"
51#include "strcase.h"
52#include "hostcheck.h"
53#include "curl_printf.h"
54#include <openssl/ssl.h>
55#ifdef HAVE_OPENSSL_ENGINE_H
56#include <openssl/engine.h>
57#endif
58#include <openssl/rand.h>
59#include <openssl/x509v3.h>
60#ifndef OPENSSL_NO_DSA
61#include <openssl/dsa.h>
62#endif
63#include <openssl/dh.h>
64#include <openssl/err.h>
65#include <openssl/md5.h>
66#include <openssl/conf.h>
67#include <openssl/bn.h>
68#include <openssl/rsa.h>
69#include <openssl/bio.h>
70#include <openssl/buffer.h>
71
72#ifndef OPENSSL_IS_BORINGSSL
73/* BoringSSL does not support PKCS12 */
74#define HAVE_PKCS12_SUPPORT 1
75#include <openssl/pkcs12.h>
76#endif
77
78#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
79#include <openssl/ocsp.h>
80#endif
81
82#include "warnless.h"
83#include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
84
85/* The last #include files should be: */
86#include "curl_memory.h"
87#include "memdebug.h"
88
89#ifndef OPENSSL_VERSION_NUMBER
90#error "OPENSSL_VERSION_NUMBER not defined"
91#endif
92
93#if defined(HAVE_OPENSSL_ENGINE_H)
94#include <openssl/ui.h>
95#endif
96
97#if OPENSSL_VERSION_NUMBER >= 0x00909000L
98#define SSL_METHOD_QUAL const
99#else
100#define SSL_METHOD_QUAL
101#endif
102
103#if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
104#define HAVE_ERR_REMOVE_THREAD_STATE 1
105#endif
106
107#if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
108 OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */
109#undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
110#define OPENSSL_NO_SSL2
111#endif
112
113#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
114 !defined(LIBRESSL_VERSION_NUMBER)
115#define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
116#define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
117#define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
118#define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
119#define CONST_EXTS const
120#define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
121#else
122/* For OpenSSL before 1.1.0 */
123#define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
124#define X509_get0_notBefore(x) X509_get_notBefore(x)
125#define X509_get0_notAfter(x) X509_get_notAfter(x)
126#define CONST_EXTS /* nope */
127#ifdef LIBRESSL_VERSION_NUMBER
128static unsigned long OpenSSL_version_num(void)
129{
130 return LIBRESSL_VERSION_NUMBER;
131}
132#else
133#define OpenSSL_version_num() SSLeay()
134#endif
135#endif
136
137#if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
138 !defined(LIBRESSL_VERSION_NUMBER)
139#define HAVE_X509_GET0_SIGNATURE 1
140#endif
141
142#if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
143 OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
144 !defined(OPENSSL_NO_COMP)
145#define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
146#endif
147
148#if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
149/* not present in older OpenSSL */
150#define OPENSSL_load_builtin_modules(x)
151#endif
152
153/*
154 * Whether SSL_CTX_set_keylog_callback is available.
155 * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287
156 * BoringSSL: supported since d28f59c27bac (committed 2015-11-19)
157 * LibreSSL: unsupported in at least 2.5.1 (explicitly check for it since it
158 * lies and pretends to be OpenSSL 2.0.0).
159 */
160#if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \
161 !defined(LIBRESSL_VERSION_NUMBER)) || \
162 defined(OPENSSL_IS_BORINGSSL)
163#define HAVE_KEYLOG_CALLBACK
164#endif
165
166#if defined(LIBRESSL_VERSION_NUMBER)
167#define OSSL_PACKAGE "LibreSSL"
168#elif defined(OPENSSL_IS_BORINGSSL)
169#define OSSL_PACKAGE "BoringSSL"
170#else
171#define OSSL_PACKAGE "OpenSSL"
172#endif
173
174#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
175/* up2date versions of OpenSSL maintain the default reasonably secure without
176 * breaking compatibility, so it is better not to override the default by curl
177 */
178#define DEFAULT_CIPHER_SELECTION NULL
179#else
180/* ... but it is not the case with old versions of OpenSSL */
181#define DEFAULT_CIPHER_SELECTION \
182 "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
183#endif
184
185#ifdef ENABLE_SSLKEYLOGFILE
186typedef struct ssl_tap_state {
187 int master_key_length;
188 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
189 unsigned char client_random[SSL3_RANDOM_SIZE];
190} ssl_tap_state_t;
191#endif /* ENABLE_SSLKEYLOGFILE */
192
193struct ssl_backend_data {
194 /* these ones requires specific SSL-types */
195 SSL_CTX* ctx;
196 SSL* handle;
197 X509* server_cert;
198#ifdef ENABLE_SSLKEYLOGFILE
199 /* tap_state holds the last seen master key if we're logging them */
200 ssl_tap_state_t tap_state;
201#endif
202};
203
204#define BACKEND connssl->backend
205
206/*
207 * Number of bytes to read from the random number seed file. This must be
208 * a finite value (because some entropy "files" like /dev/urandom have
209 * an infinite length), but must be large enough to provide enough
210 * entropy to properly seed OpenSSL's PRNG.
211 */
212#define RAND_LOAD_LENGTH 1024
213
214#ifdef ENABLE_SSLKEYLOGFILE
215/* The fp for the open SSLKEYLOGFILE, or NULL if not open */
216static FILE *keylog_file_fp;
217
218#ifdef HAVE_KEYLOG_CALLBACK
219static void ossl_keylog_callback(const SSL *ssl, const char *line)
220{
221 (void)ssl;
222
223 /* Using fputs here instead of fprintf since libcurl's fprintf replacement
224 may not be thread-safe. */
225 if(keylog_file_fp && line && *line) {
226 char stackbuf[256];
227 char *buf;
228 size_t linelen = strlen(line);
229
230 if(linelen <= sizeof(stackbuf) - 2)
231 buf = stackbuf;
232 else {
233 buf = malloc(linelen + 2);
234 if(!buf)
235 return;
236 }
237 strncpy(buf, line, linelen);
238 buf[linelen] = '\n';
239 buf[linelen + 1] = '\0';
240
241 fputs(buf, keylog_file_fp);
242 if(buf != stackbuf)
243 free(buf);
244 }
245}
246#else
247#define KEYLOG_PREFIX "CLIENT_RANDOM "
248#define KEYLOG_PREFIX_LEN (sizeof(KEYLOG_PREFIX) - 1)
249/*
250 * tap_ssl_key is called by libcurl to make the CLIENT_RANDOMs if the OpenSSL
251 * being used doesn't have native support for doing that.
252 */
253static void tap_ssl_key(const SSL *ssl, ssl_tap_state_t *state)
254{
255 const char *hex = "0123456789ABCDEF";
256 int pos, i;
257 char line[KEYLOG_PREFIX_LEN + 2 * SSL3_RANDOM_SIZE + 1 +
258 2 * SSL_MAX_MASTER_KEY_LENGTH + 1 + 1];
259 const SSL_SESSION *session = SSL_get_session(ssl);
260 unsigned char client_random[SSL3_RANDOM_SIZE];
261 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
262 int master_key_length = 0;
263
264 if(!session || !keylog_file_fp)
265 return;
266
267#if OPENSSL_VERSION_NUMBER >= 0x10100000L
268 /* ssl->s3 is not checked in openssl 1.1.0-pre6, but let's assume that
269 * we have a valid SSL context if we have a non-NULL session. */
270 SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
271 master_key_length =
272 SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
273#else
274 if(ssl->s3 && session->master_key_length > 0) {
275 master_key_length = session->master_key_length;
276 memcpy(master_key, session->master_key, session->master_key_length);
277 memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE);
278 }
279#endif
280
281 if(master_key_length <= 0)
282 return;
283
284 /* Skip writing keys if there is no key or it did not change. */
285 if(state->master_key_length == master_key_length &&
286 !memcmp(state->master_key, master_key, master_key_length) &&
287 !memcmp(state->client_random, client_random, SSL3_RANDOM_SIZE)) {
288 return;
289 }
290
291 state->master_key_length = master_key_length;
292 memcpy(state->master_key, master_key, master_key_length);
293 memcpy(state->client_random, client_random, SSL3_RANDOM_SIZE);
294
295 memcpy(line, KEYLOG_PREFIX, KEYLOG_PREFIX_LEN);
296 pos = KEYLOG_PREFIX_LEN;
297
298 /* Client Random for SSLv3/TLS */
299 for(i = 0; i < SSL3_RANDOM_SIZE; i++) {
300 line[pos++] = hex[client_random[i] >> 4];
301 line[pos++] = hex[client_random[i] & 0xF];
302 }
303 line[pos++] = ' ';
304
305 /* Master Secret (size is at most SSL_MAX_MASTER_KEY_LENGTH) */
306 for(i = 0; i < master_key_length; i++) {
307 line[pos++] = hex[master_key[i] >> 4];
308 line[pos++] = hex[master_key[i] & 0xF];
309 }
310 line[pos++] = '\n';
311 line[pos] = '\0';
312
313 /* Using fputs here instead of fprintf since libcurl's fprintf replacement
314 may not be thread-safe. */
315 fputs(line, keylog_file_fp);
316}
317#endif /* !HAVE_KEYLOG_CALLBACK */
318#endif /* ENABLE_SSLKEYLOGFILE */
319
320static const char *SSL_ERROR_to_str(int err)
321{
322 switch(err) {
323 case SSL_ERROR_NONE:
324 return "SSL_ERROR_NONE";
325 case SSL_ERROR_SSL:
326 return "SSL_ERROR_SSL";
327 case SSL_ERROR_WANT_READ:
328 return "SSL_ERROR_WANT_READ";
329 case SSL_ERROR_WANT_WRITE:
330 return "SSL_ERROR_WANT_WRITE";
331 case SSL_ERROR_WANT_X509_LOOKUP:
332 return "SSL_ERROR_WANT_X509_LOOKUP";
333 case SSL_ERROR_SYSCALL:
334 return "SSL_ERROR_SYSCALL";
335 case SSL_ERROR_ZERO_RETURN:
336 return "SSL_ERROR_ZERO_RETURN";
337 case SSL_ERROR_WANT_CONNECT:
338 return "SSL_ERROR_WANT_CONNECT";
339 case SSL_ERROR_WANT_ACCEPT:
340 return "SSL_ERROR_WANT_ACCEPT";
341#if defined(SSL_ERROR_WANT_ASYNC)
342 case SSL_ERROR_WANT_ASYNC:
343 return "SSL_ERROR_WANT_ASYNC";
344#endif
345#if defined(SSL_ERROR_WANT_ASYNC_JOB)
346 case SSL_ERROR_WANT_ASYNC_JOB:
347 return "SSL_ERROR_WANT_ASYNC_JOB";
348#endif
349#if defined(SSL_ERROR_WANT_EARLY)
350 case SSL_ERROR_WANT_EARLY:
351 return "SSL_ERROR_WANT_EARLY";
352#endif
353 default:
354 return "SSL_ERROR unknown";
355 }
356}
357
358/* Return error string for last OpenSSL error
359 */
360static char *ossl_strerror(unsigned long error, char *buf, size_t size)
361{
362 ERR_error_string_n(error, buf, size);
363 return buf;
364}
365
366static int passwd_callback(char *buf, int num, int encrypting,
367 void *global_passwd)
368{
369 DEBUGASSERT(0 == encrypting);
370
371 if(!encrypting) {
372 int klen = curlx_uztosi(strlen((char *)global_passwd));
373 if(num > klen) {
374 memcpy(buf, global_passwd, klen + 1);
375 return klen;
376 }
377 }
378 return 0;
379}
380
381/*
382 * rand_enough() returns TRUE if we have seeded the random engine properly.
383 */
384static bool rand_enough(void)
385{
386 return (0 != RAND_status()) ? TRUE : FALSE;
387}
388
389static CURLcode Curl_ossl_seed(struct Curl_easy *data)
390{
391 /* we have the "SSL is seeded" boolean static to prevent multiple
392 time-consuming seedings in vain */
393 static bool ssl_seeded = FALSE;
394 char fname[256];
395
396 if(ssl_seeded)
397 return CURLE_OK;
398
399 if(rand_enough()) {
400 /* OpenSSL 1.1.0+ will return here */
401 ssl_seeded = TRUE;
402 return CURLE_OK;
403 }
404
405#ifndef RANDOM_FILE
406 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
407 us to! */
408 if(data->set.str[STRING_SSL_RANDOM_FILE])
409#define RANDOM_FILE "" /* doesn't matter won't be used */
410#endif
411 {
412 /* let the option override the define */
413 RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
414 data->set.str[STRING_SSL_RANDOM_FILE]:
415 RANDOM_FILE),
416 RAND_LOAD_LENGTH);
417 if(rand_enough())
418 return CURLE_OK;
419 }
420
421#if defined(HAVE_RAND_EGD)
422 /* only available in OpenSSL 0.9.5 and later */
423 /* EGD_SOCKET is set at configure time or not at all */
424#ifndef EGD_SOCKET
425 /* If we don't have the define set, we only do this if the egd-option
426 is set */
427 if(data->set.str[STRING_SSL_EGDSOCKET])
428#define EGD_SOCKET "" /* doesn't matter won't be used */
429#endif
430 {
431 /* If there's an option and a define, the option overrides the
432 define */
433 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
434 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
435 if(-1 != ret) {
436 if(rand_enough())
437 return CURLE_OK;
438 }
439 }
440#endif
441
442 /* fallback to a custom seeding of the PRNG using a hash based on a current
443 time */
444 do {
445 unsigned char randb[64];
446 size_t len = sizeof(randb);
447 size_t i, i_max;
448 for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) {
449 struct curltime tv = Curl_now();
450 Curl_wait_ms(1);
451 tv.tv_sec *= i + 1;
452 tv.tv_usec *= (unsigned int)i + 2;
453 tv.tv_sec ^= ((Curl_now().tv_sec + Curl_now().tv_usec) *
454 (i + 3)) << 8;
455 tv.tv_usec ^= (unsigned int) ((Curl_now().tv_sec +
456 Curl_now().tv_usec) *
457 (i + 4)) << 16;
458 memcpy(&randb[i * sizeof(struct curltime)], &tv,
459 sizeof(struct curltime));
460 }
461 RAND_add(randb, (int)len, (double)len/2);
462 } while(!rand_enough());
463
464 /* generates a default path for the random seed file */
465 fname[0] = 0; /* blank it first */
466 RAND_file_name(fname, sizeof(fname));
467 if(fname[0]) {
468 /* we got a file name to try */
469 RAND_load_file(fname, RAND_LOAD_LENGTH);
470 if(rand_enough())
471 return CURLE_OK;
472 }
473
474 infof(data, "libcurl is now using a weak random seed!\n");
475 return (rand_enough() ? CURLE_OK :
476 CURLE_SSL_CONNECT_ERROR /* confusing error code */);
477}
478
479#ifndef SSL_FILETYPE_ENGINE
480#define SSL_FILETYPE_ENGINE 42
481#endif
482#ifndef SSL_FILETYPE_PKCS12
483#define SSL_FILETYPE_PKCS12 43
484#endif
485static int do_file_type(const char *type)
486{
487 if(!type || !type[0])
488 return SSL_FILETYPE_PEM;
489 if(strcasecompare(type, "PEM"))
490 return SSL_FILETYPE_PEM;
491 if(strcasecompare(type, "DER"))
492 return SSL_FILETYPE_ASN1;
493 if(strcasecompare(type, "ENG"))
494 return SSL_FILETYPE_ENGINE;
495 if(strcasecompare(type, "P12"))
496 return SSL_FILETYPE_PKCS12;
497 return -1;
498}
499
500#if defined(HAVE_OPENSSL_ENGINE_H) && !defined(OPENSSL_NO_UI)
501/*
502 * Supply default password to the engine user interface conversation.
503 * The password is passed by OpenSSL engine from ENGINE_load_private_key()
504 * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
505 */
506static int ssl_ui_reader(UI *ui, UI_STRING *uis)
507{
508 const char *password;
509 switch(UI_get_string_type(uis)) {
510 case UIT_PROMPT:
511 case UIT_VERIFY:
512 password = (const char *)UI_get0_user_data(ui);
513 if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
514 UI_set_result(ui, uis, password);
515 return 1;
516 }
517 default:
518 break;
519 }
520 return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
521}
522
523/*
524 * Suppress interactive request for a default password if available.
525 */
526static int ssl_ui_writer(UI *ui, UI_STRING *uis)
527{
528 switch(UI_get_string_type(uis)) {
529 case UIT_PROMPT:
530 case UIT_VERIFY:
531 if(UI_get0_user_data(ui) &&
532 (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
533 return 1;
534 }
535 default:
536 break;
537 }
538 return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
539}
540#endif
541
542static
543int cert_stuff(struct connectdata *conn,
544 SSL_CTX* ctx,
545 char *cert_file,
546 const char *cert_type,
547 char *key_file,
548 const char *key_type,
549 char *key_passwd)
550{
551 struct Curl_easy *data = conn->data;
552 char error_buffer[256];
553 bool check_privkey = TRUE;
554
555 int file_type = do_file_type(cert_type);
556
557 if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
558 SSL *ssl;
559 X509 *x509;
560 int cert_done = 0;
561
562 if(key_passwd) {
563 /* set the password in the callback userdata */
564 SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
565 /* Set passwd callback: */
566 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
567 }
568
569
570 switch(file_type) {
571 case SSL_FILETYPE_PEM:
572 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
573 if(SSL_CTX_use_certificate_chain_file(ctx,
574 cert_file) != 1) {
575 failf(data,
576 "could not load PEM client certificate, " OSSL_PACKAGE
577 " error %s, "
578 "(no key found, wrong pass phrase, or wrong file format?)",
579 ossl_strerror(ERR_get_error(), error_buffer,
580 sizeof(error_buffer)) );
581 return 0;
582 }
583 break;
584
585 case SSL_FILETYPE_ASN1:
586 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
587 we use the case above for PEM so this can only be performed with
588 ASN1 files. */
589 if(SSL_CTX_use_certificate_file(ctx,
590 cert_file,
591 file_type) != 1) {
592 failf(data,
593 "could not load ASN1 client certificate, " OSSL_PACKAGE
594 " error %s, "
595 "(no key found, wrong pass phrase, or wrong file format?)",
596 ossl_strerror(ERR_get_error(), error_buffer,
597 sizeof(error_buffer)) );
598 return 0;
599 }
600 break;
601 case SSL_FILETYPE_ENGINE:
602#if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
603 {
604 if(data->state.engine) {
605 const char *cmd_name = "LOAD_CERT_CTRL";
606 struct {
607 const char *cert_id;
608 X509 *cert;
609 } params;
610
611 params.cert_id = cert_file;
612 params.cert = NULL;
613
614 /* Does the engine supports LOAD_CERT_CTRL ? */
615 if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
616 0, (void *)cmd_name, NULL)) {
617 failf(data, "ssl engine does not support loading certificates");
618 return 0;
619 }
620
621 /* Load the certificate from the engine */
622 if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
623 0, &params, NULL, 1)) {
624 failf(data, "ssl engine cannot load client cert with id"
625 " '%s' [%s]", cert_file,
626 ossl_strerror(ERR_get_error(), error_buffer,
627 sizeof(error_buffer)));
628 return 0;
629 }
630
631 if(!params.cert) {
632 failf(data, "ssl engine didn't initialized the certificate "
633 "properly.");
634 return 0;
635 }
636
637 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
638 failf(data, "unable to set client certificate");
639 X509_free(params.cert);
640 return 0;
641 }
642 X509_free(params.cert); /* we don't need the handle any more... */
643 }
644 else {
645 failf(data, "crypto engine not set, can't load certificate");
646 return 0;
647 }
648 }
649 break;
650#else
651 failf(data, "file type ENG for certificate not implemented");
652 return 0;
653#endif
654
655 case SSL_FILETYPE_PKCS12:
656 {
657#ifdef HAVE_PKCS12_SUPPORT
658 FILE *f;
659 PKCS12 *p12;
660 EVP_PKEY *pri;
661 STACK_OF(X509) *ca = NULL;
662
663 f = fopen(cert_file, "rb");
664 if(!f) {
665 failf(data, "could not open PKCS12 file '%s'", cert_file);
666 return 0;
667 }
668 p12 = d2i_PKCS12_fp(f, NULL);
669 fclose(f);
670
671 if(!p12) {
672 failf(data, "error reading PKCS12 file '%s'", cert_file);
673 return 0;
674 }
675
676 PKCS12_PBE_add();
677
678 if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
679 &ca)) {
680 failf(data,
681 "could not parse PKCS12 file, check password, " OSSL_PACKAGE
682 " error %s",
683 ossl_strerror(ERR_get_error(), error_buffer,
684 sizeof(error_buffer)) );
685 PKCS12_free(p12);
686 return 0;
687 }
688
689 PKCS12_free(p12);
690
691 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
692 failf(data,
693 "could not load PKCS12 client certificate, " OSSL_PACKAGE
694 " error %s",
695 ossl_strerror(ERR_get_error(), error_buffer,
696 sizeof(error_buffer)) );
697 goto fail;
698 }
699
700 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
701 failf(data, "unable to use private key from PKCS12 file '%s'",
702 cert_file);
703 goto fail;
704 }
705
706 if(!SSL_CTX_check_private_key (ctx)) {
707 failf(data, "private key from PKCS12 file '%s' "
708 "does not match certificate in same file", cert_file);
709 goto fail;
710 }
711 /* Set Certificate Verification chain */
712 if(ca) {
713 while(sk_X509_num(ca)) {
714 /*
715 * Note that sk_X509_pop() is used below to make sure the cert is
716 * removed from the stack properly before getting passed to
717 * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
718 * we used sk_X509_value() instead, but then we'd clean it in the
719 * subsequent sk_X509_pop_free() call.
720 */
721 X509 *x = sk_X509_pop(ca);
722 if(!SSL_CTX_add_client_CA(ctx, x)) {
723 X509_free(x);
724 failf(data, "cannot add certificate to client CA list");
725 goto fail;
726 }
727 if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
728 X509_free(x);
729 failf(data, "cannot add certificate to certificate chain");
730 goto fail;
731 }
732 }
733 }
734
735 cert_done = 1;
736 fail:
737 EVP_PKEY_free(pri);
738 X509_free(x509);
739 sk_X509_pop_free(ca, X509_free);
740
741 if(!cert_done)
742 return 0; /* failure! */
743 break;
744#else
745 failf(data, "file type P12 for certificate not supported");
746 return 0;
747#endif
748 }
749 default:
750 failf(data, "not supported file type '%s' for certificate", cert_type);
751 return 0;
752 }
753
754 file_type = do_file_type(key_type);
755
756 switch(file_type) {
757 case SSL_FILETYPE_PEM:
758 if(cert_done)
759 break;
760 if(!key_file)
761 /* cert & key can only be in PEM case in the same file */
762 key_file = cert_file;
763 /* FALLTHROUGH */
764 case SSL_FILETYPE_ASN1:
765 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
766 failf(data, "unable to set private key file: '%s' type %s",
767 key_file, key_type?key_type:"PEM");
768 return 0;
769 }
770 break;
771 case SSL_FILETYPE_ENGINE:
772#if defined(HAVE_OPENSSL_ENGINE_H) && !defined(OPENSSL_NO_UI)
773 { /* XXXX still needs some work */
774 EVP_PKEY *priv_key = NULL;
775 if(data->state.engine) {
776 UI_METHOD *ui_method =
777 UI_create_method((char *)"curl user interface");
778 if(!ui_method) {
779 failf(data, "unable do create " OSSL_PACKAGE
780 " user-interface method");
781 return 0;
782 }
783 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
784 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
785 UI_method_set_reader(ui_method, ssl_ui_reader);
786 UI_method_set_writer(ui_method, ssl_ui_writer);
787 /* the typecast below was added to please mingw32 */
788 priv_key = (EVP_PKEY *)
789 ENGINE_load_private_key(data->state.engine, key_file,
790 ui_method,
791 key_passwd);
792 UI_destroy_method(ui_method);
793 if(!priv_key) {
794 failf(data, "failed to load private key from crypto engine");
795 return 0;
796 }
797 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
798 failf(data, "unable to set private key");
799 EVP_PKEY_free(priv_key);
800 return 0;
801 }
802 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
803 }
804 else {
805 failf(data, "crypto engine not set, can't load private key");
806 return 0;
807 }
808 }
809 break;
810#else
811 failf(data, "file type ENG for private key not supported");
812 return 0;
813#endif
814 case SSL_FILETYPE_PKCS12:
815 if(!cert_done) {
816 failf(data, "file type P12 for private key not supported");
817 return 0;
818 }
819 break;
820 default:
821 failf(data, "not supported file type for private key");
822 return 0;
823 }
824
825 ssl = SSL_new(ctx);
826 if(!ssl) {
827 failf(data, "unable to create an SSL structure");
828 return 0;
829 }
830
831 x509 = SSL_get_certificate(ssl);
832
833 /* This version was provided by Evan Jordan and is supposed to not
834 leak memory as the previous version: */
835 if(x509) {
836 EVP_PKEY *pktmp = X509_get_pubkey(x509);
837 EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
838 EVP_PKEY_free(pktmp);
839 }
840
841#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL)
842 {
843 /* If RSA is used, don't check the private key if its flags indicate
844 * it doesn't support it. */
845 EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
846 int pktype;
847#ifdef HAVE_OPAQUE_EVP_PKEY
848 pktype = EVP_PKEY_id(priv_key);
849#else
850 pktype = priv_key->type;
851#endif
852 if(pktype == EVP_PKEY_RSA) {
853 RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
854 if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
855 check_privkey = FALSE;
856 RSA_free(rsa); /* Decrement reference count */
857 }
858 }
859#endif
860
861 SSL_free(ssl);
862
863 /* If we are using DSA, we can copy the parameters from
864 * the private key */
865
866 if(check_privkey == TRUE) {
867 /* Now we know that a key and cert have been set against
868 * the SSL context */
869 if(!SSL_CTX_check_private_key(ctx)) {
870 failf(data, "Private key does not match the certificate public key");
871 return 0;
872 }
873 }
874 }
875 return 1;
876}
877
878/* returns non-zero on failure */
879static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
880{
881#if 0
882 return X509_NAME_oneline(a, buf, size);
883#else
884 BIO *bio_out = BIO_new(BIO_s_mem());
885 BUF_MEM *biomem;
886 int rc;
887
888 if(!bio_out)
889 return 1; /* alloc failed! */
890
891 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
892 BIO_get_mem_ptr(bio_out, &biomem);
893
894 if((size_t)biomem->length < size)
895 size = biomem->length;
896 else
897 size--; /* don't overwrite the buffer end */
898
899 memcpy(buf, biomem->data, size);
900 buf[size] = 0;
901
902 BIO_free(bio_out);
903
904 return !rc;
905#endif
906}
907
908/**
909 * Global SSL init
910 *
911 * @retval 0 error initializing SSL
912 * @retval 1 SSL initialized successfully
913 */
914static int Curl_ossl_init(void)
915{
916#ifdef ENABLE_SSLKEYLOGFILE
917 const char *keylog_file_name;
918#endif
919
920 OPENSSL_load_builtin_modules();
921
922#ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
923 ENGINE_load_builtin_engines();
924#endif
925
926 /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately
927 that function makes an exit() call on wrongly formatted config files
928 which makes it hard to use in some situations. OPENSSL_config() itself
929 calls CONF_modules_load_file() and we use that instead and we ignore
930 its return code! */
931
932 /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and
933 0.9.8e */
934#ifndef CONF_MFLAGS_DEFAULT_SECTION
935#define CONF_MFLAGS_DEFAULT_SECTION 0x0
936#endif
937
938 CONF_modules_load_file(NULL, NULL,
939 CONF_MFLAGS_DEFAULT_SECTION|
940 CONF_MFLAGS_IGNORE_MISSING_FILE);
941
942#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
943 !defined(LIBRESSL_VERSION_NUMBER)
944 /* OpenSSL 1.1.0+ takes care of initialization itself */
945#else
946 /* Lets get nice error messages */
947 SSL_load_error_strings();
948
949 /* Init the global ciphers and digests */
950 if(!SSLeay_add_ssl_algorithms())
951 return 0;
952
953 OpenSSL_add_all_algorithms();
954#endif
955
956#ifdef ENABLE_SSLKEYLOGFILE
957 keylog_file_name = curl_getenv("SSLKEYLOGFILE");
958 if(keylog_file_name && !keylog_file_fp) {
959 keylog_file_fp = fopen(keylog_file_name, FOPEN_APPENDTEXT);
960 if(keylog_file_fp) {
961 if(setvbuf(keylog_file_fp, NULL, _IOLBF, 4096)) {
962 fclose(keylog_file_fp);
963 keylog_file_fp = NULL;
964 }
965 }
966 }
967#endif
968
969 return 1;
970}
971
972/* Global cleanup */
973static void Curl_ossl_cleanup(void)
974{
975#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
976 !defined(LIBRESSL_VERSION_NUMBER)
977 /* OpenSSL 1.1 deprecates all these cleanup functions and
978 turns them into no-ops in OpenSSL 1.0 compatibility mode */
979#else
980 /* Free ciphers and digests lists */
981 EVP_cleanup();
982
983#ifdef HAVE_ENGINE_CLEANUP
984 /* Free engine list */
985 ENGINE_cleanup();
986#endif
987
988 /* Free OpenSSL error strings */
989 ERR_free_strings();
990
991 /* Free thread local error state, destroying hash upon zero refcount */
992#ifdef HAVE_ERR_REMOVE_THREAD_STATE
993 ERR_remove_thread_state(NULL);
994#else
995 ERR_remove_state(0);
996#endif
997
998 /* Free all memory allocated by all configuration modules */
999 CONF_modules_free();
1000
1001#ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
1002 SSL_COMP_free_compression_methods();
1003#endif
1004#endif
1005
1006#ifdef ENABLE_SSLKEYLOGFILE
1007 if(keylog_file_fp) {
1008 fclose(keylog_file_fp);
1009 keylog_file_fp = NULL;
1010 }
1011#endif
1012}
1013
1014/*
1015 * This function is used to determine connection status.
1016 *
1017 * Return codes:
1018 * 1 means the connection is still in place
1019 * 0 means the connection has been closed
1020 * -1 means the connection status is unknown
1021 */
1022static int Curl_ossl_check_cxn(struct connectdata *conn)
1023{
1024 /* SSL_peek takes data out of the raw recv buffer without peeking so we use
1025 recv MSG_PEEK instead. Bug #795 */
1026#ifdef MSG_PEEK
1027 char buf;
1028 ssize_t nread;
1029 nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
1030 (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
1031 if(nread == 0)
1032 return 0; /* connection has been closed */
1033 if(nread == 1)
1034 return 1; /* connection still in place */
1035 else if(nread == -1) {
1036 int err = SOCKERRNO;
1037 if(err == EINPROGRESS ||
1038#if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
1039 err == EAGAIN ||
1040#endif
1041 err == EWOULDBLOCK)
1042 return 1; /* connection still in place */
1043 if(err == ECONNRESET ||
1044#ifdef ECONNABORTED
1045 err == ECONNABORTED ||
1046#endif
1047#ifdef ENETDOWN
1048 err == ENETDOWN ||
1049#endif
1050#ifdef ENETRESET
1051 err == ENETRESET ||
1052#endif
1053#ifdef ESHUTDOWN
1054 err == ESHUTDOWN ||
1055#endif
1056#ifdef ETIMEDOUT
1057 err == ETIMEDOUT ||
1058#endif
1059 err == ENOTCONN)
1060 return 0; /* connection has been closed */
1061 }
1062#endif
1063 return -1; /* connection status unknown */
1064}
1065
1066/* Selects an OpenSSL crypto engine
1067 */
1068static CURLcode Curl_ossl_set_engine(struct Curl_easy *data,
1069 const char *engine)
1070{
1071#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
1072 ENGINE *e;
1073
1074#if OPENSSL_VERSION_NUMBER >= 0x00909000L
1075 e = ENGINE_by_id(engine);
1076#else
1077 /* avoid memory leak */
1078 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1079 const char *e_id = ENGINE_get_id(e);
1080 if(!strcmp(engine, e_id))
1081 break;
1082 }
1083#endif
1084
1085 if(!e) {
1086 failf(data, "SSL Engine '%s' not found", engine);
1087 return CURLE_SSL_ENGINE_NOTFOUND;
1088 }
1089
1090 if(data->state.engine) {
1091 ENGINE_finish(data->state.engine);
1092 ENGINE_free(data->state.engine);
1093 data->state.engine = NULL;
1094 }
1095 if(!ENGINE_init(e)) {
1096 char buf[256];
1097
1098 ENGINE_free(e);
1099 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
1100 engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
1101 return CURLE_SSL_ENGINE_INITFAILED;
1102 }
1103 data->state.engine = e;
1104 return CURLE_OK;
1105#else
1106 (void)engine;
1107 failf(data, "SSL Engine not supported");
1108 return CURLE_SSL_ENGINE_NOTFOUND;
1109#endif
1110}
1111
1112/* Sets engine as default for all SSL operations
1113 */
1114static CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
1115{
1116#ifdef HAVE_OPENSSL_ENGINE_H
1117 if(data->state.engine) {
1118 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
1119 infof(data, "set default crypto engine '%s'\n",
1120 ENGINE_get_id(data->state.engine));
1121 }
1122 else {
1123 failf(data, "set default crypto engine '%s' failed",
1124 ENGINE_get_id(data->state.engine));
1125 return CURLE_SSL_ENGINE_SETFAILED;
1126 }
1127 }
1128#else
1129 (void) data;
1130#endif
1131 return CURLE_OK;
1132}
1133
1134/* Return list of OpenSSL crypto engine names.
1135 */
1136static struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
1137{
1138 struct curl_slist *list = NULL;
1139#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
1140 struct curl_slist *beg;
1141 ENGINE *e;
1142
1143 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1144 beg = curl_slist_append(list, ENGINE_get_id(e));
1145 if(!beg) {
1146 curl_slist_free_all(list);
1147 return NULL;
1148 }
1149 list = beg;
1150 }
1151#endif
1152 (void) data;
1153 return list;
1154}
1155
1156
1157static void ossl_close(struct ssl_connect_data *connssl)
1158{
1159 if(BACKEND->handle) {
1160 (void)SSL_shutdown(BACKEND->handle);
1161 SSL_set_connect_state(BACKEND->handle);
1162
1163 SSL_free(BACKEND->handle);
1164 BACKEND->handle = NULL;
1165 }
1166 if(BACKEND->ctx) {
1167 SSL_CTX_free(BACKEND->ctx);
1168 BACKEND->ctx = NULL;
1169 }
1170}
1171
1172/*
1173 * This function is called when an SSL connection is closed.
1174 */
1175static void Curl_ossl_close(struct connectdata *conn, int sockindex)
1176{
1177 ossl_close(&conn->ssl[sockindex]);
1178 ossl_close(&conn->proxy_ssl[sockindex]);
1179}
1180
1181/*
1182 * This function is called to shut down the SSL layer but keep the
1183 * socket open (CCC - Clear Command Channel)
1184 */
1185static int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
1186{
1187 int retval = 0;
1188 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1189 struct Curl_easy *data = conn->data;
1190 char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
1191 to be at least 256 bytes long. */
1192 unsigned long sslerror;
1193 ssize_t nread;
1194 int buffsize;
1195 int err;
1196 int done = 0;
1197
1198 /* This has only been tested on the proftpd server, and the mod_tls code
1199 sends a close notify alert without waiting for a close notify alert in
1200 response. Thus we wait for a close notify alert from the server, but
1201 we do not send one. Let's hope other servers do the same... */
1202
1203 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
1204 (void)SSL_shutdown(BACKEND->handle);
1205
1206 if(BACKEND->handle) {
1207 buffsize = (int)sizeof(buf);
1208 while(!done) {
1209 int what = SOCKET_READABLE(conn->sock[sockindex],
1210 SSL_SHUTDOWN_TIMEOUT);
1211 if(what > 0) {
1212 ERR_clear_error();
1213
1214 /* Something to read, let's do it and hope that it is the close
1215 notify alert from the server */
1216 nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
1217 err = SSL_get_error(BACKEND->handle, (int)nread);
1218
1219 switch(err) {
1220 case SSL_ERROR_NONE: /* this is not an error */
1221 case SSL_ERROR_ZERO_RETURN: /* no more data */
1222 /* This is the expected response. There was no data but only
1223 the close notify alert */
1224 done = 1;
1225 break;
1226 case SSL_ERROR_WANT_READ:
1227 /* there's data pending, re-invoke SSL_read() */
1228 infof(data, "SSL_ERROR_WANT_READ\n");
1229 break;
1230 case SSL_ERROR_WANT_WRITE:
1231 /* SSL wants a write. Really odd. Let's bail out. */
1232 infof(data, "SSL_ERROR_WANT_WRITE\n");
1233 done = 1;
1234 break;
1235 default:
1236 /* openssl/ssl.h says "look at error stack/return value/errno" */
1237 sslerror = ERR_get_error();
1238 failf(conn->data, OSSL_PACKAGE " SSL_read on shutdown: %s, errno %d",
1239 (sslerror ?
1240 ossl_strerror(sslerror, buf, sizeof(buf)) :
1241 SSL_ERROR_to_str(err)),
1242 SOCKERRNO);
1243 done = 1;
1244 break;
1245 }
1246 }
1247 else if(0 == what) {
1248 /* timeout */
1249 failf(data, "SSL shutdown timeout");
1250 done = 1;
1251 }
1252 else {
1253 /* anything that gets here is fatally bad */
1254 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1255 retval = -1;
1256 done = 1;
1257 }
1258 } /* while()-loop for the select() */
1259
1260 if(data->set.verbose) {
1261#ifdef HAVE_SSL_GET_SHUTDOWN
1262 switch(SSL_get_shutdown(BACKEND->handle)) {
1263 case SSL_SENT_SHUTDOWN:
1264 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
1265 break;
1266 case SSL_RECEIVED_SHUTDOWN:
1267 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
1268 break;
1269 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
1270 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
1271 "SSL_RECEIVED__SHUTDOWN\n");
1272 break;
1273 }
1274#endif
1275 }
1276
1277 SSL_free(BACKEND->handle);
1278 BACKEND->handle = NULL;
1279 }
1280 return retval;
1281}
1282
1283static void Curl_ossl_session_free(void *ptr)
1284{
1285 /* free the ID */
1286 SSL_SESSION_free(ptr);
1287}
1288
1289/*
1290 * This function is called when the 'data' struct is going away. Close
1291 * down everything and free all resources!
1292 */
1293static void Curl_ossl_close_all(struct Curl_easy *data)
1294{
1295#ifdef HAVE_OPENSSL_ENGINE_H
1296 if(data->state.engine) {
1297 ENGINE_finish(data->state.engine);
1298 ENGINE_free(data->state.engine);
1299 data->state.engine = NULL;
1300 }
1301#else
1302 (void)data;
1303#endif
1304#if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
1305 defined(HAVE_ERR_REMOVE_THREAD_STATE)
1306 /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
1307 so we need to clean it here in case the thread will be killed. All OpenSSL
1308 code should extract the error in association with the error so clearing
1309 this queue here should be harmless at worst. */
1310 ERR_remove_thread_state(NULL);
1311#endif
1312}
1313
1314/* ====================================================== */
1315
1316
1317/* Quote from RFC2818 section 3.1 "Server Identity"
1318
1319 If a subjectAltName extension of type dNSName is present, that MUST
1320 be used as the identity. Otherwise, the (most specific) Common Name
1321 field in the Subject field of the certificate MUST be used. Although
1322 the use of the Common Name is existing practice, it is deprecated and
1323 Certification Authorities are encouraged to use the dNSName instead.
1324
1325 Matching is performed using the matching rules specified by
1326 [RFC2459]. If more than one identity of a given type is present in
1327 the certificate (e.g., more than one dNSName name, a match in any one
1328 of the set is considered acceptable.) Names may contain the wildcard
1329 character * which is considered to match any single domain name
1330 component or component fragment. E.g., *.a.com matches foo.a.com but
1331 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1332
1333 In some cases, the URI is specified as an IP address rather than a
1334 hostname. In this case, the iPAddress subjectAltName must be present
1335 in the certificate and must exactly match the IP in the URI.
1336
1337*/
1338static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
1339{
1340 bool matched = FALSE;
1341 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1342 size_t addrlen = 0;
1343 struct Curl_easy *data = conn->data;
1344 STACK_OF(GENERAL_NAME) *altnames;
1345#ifdef ENABLE_IPV6
1346 struct in6_addr addr;
1347#else
1348 struct in_addr addr;
1349#endif
1350 CURLcode result = CURLE_OK;
1351 bool dNSName = FALSE; /* if a dNSName field exists in the cert */
1352 bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
1353 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
1354 conn->host.name;
1355 const char * const dispname = SSL_IS_PROXY() ?
1356 conn->http_proxy.host.dispname : conn->host.dispname;
1357
1358#ifdef ENABLE_IPV6
1359 if(conn->bits.ipv6_ip &&
1360 Curl_inet_pton(AF_INET6, hostname, &addr)) {
1361 target = GEN_IPADD;
1362 addrlen = sizeof(struct in6_addr);
1363 }
1364 else
1365#endif
1366 if(Curl_inet_pton(AF_INET, hostname, &addr)) {
1367 target = GEN_IPADD;
1368 addrlen = sizeof(struct in_addr);
1369 }
1370
1371 /* get a "list" of alternative names */
1372 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1373
1374 if(altnames) {
1375 int numalts;
1376 int i;
1377 bool dnsmatched = FALSE;
1378 bool ipmatched = FALSE;
1379
1380 /* get amount of alternatives, RFC2459 claims there MUST be at least
1381 one, but we don't depend on it... */
1382 numalts = sk_GENERAL_NAME_num(altnames);
1383
1384 /* loop through all alternatives - until a dnsmatch */
1385 for(i = 0; (i < numalts) && !dnsmatched; i++) {
1386 /* get a handle to alternative name number i */
1387 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1388
1389 if(check->type == GEN_DNS)
1390 dNSName = TRUE;
1391 else if(check->type == GEN_IPADD)
1392 iPAddress = TRUE;
1393
1394 /* only check alternatives of the same type the target is */
1395 if(check->type == target) {
1396 /* get data and length */
1397 const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
1398 size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
1399
1400 switch(target) {
1401 case GEN_DNS: /* name/pattern comparison */
1402 /* The OpenSSL man page explicitly says: "In general it cannot be
1403 assumed that the data returned by ASN1_STRING_data() is null
1404 terminated or does not contain embedded nulls." But also that
1405 "The actual format of the data will depend on the actual string
1406 type itself: for example for and IA5String the data will be ASCII"
1407
1408 Gisle researched the OpenSSL sources:
1409 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1410 it always 0-terminates an IA5String."
1411 */
1412 if((altlen == strlen(altptr)) &&
1413 /* if this isn't true, there was an embedded zero in the name
1414 string and we cannot match it. */
1415 Curl_cert_hostcheck(altptr, hostname)) {
1416 dnsmatched = TRUE;
1417 infof(data,
1418 " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
1419 dispname, altptr);
1420 }
1421 break;
1422
1423 case GEN_IPADD: /* IP address comparison */
1424 /* compare alternative IP address if the data chunk is the same size
1425 our server IP address is */
1426 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
1427 ipmatched = TRUE;
1428 infof(data,
1429 " subjectAltName: host \"%s\" matched cert's IP address!\n",
1430 dispname);
1431 }
1432 break;
1433 }
1434 }
1435 }
1436 GENERAL_NAMES_free(altnames);
1437
1438 if(dnsmatched || ipmatched)
1439 matched = TRUE;
1440 }
1441
1442 if(matched)
1443 /* an alternative name matched */
1444 ;
1445 else if(dNSName || iPAddress) {
1446 infof(data, " subjectAltName does not match %s\n", dispname);
1447 failf(data, "SSL: no alternative certificate subject name matches "
1448 "target host name '%s'", dispname);
1449 result = CURLE_PEER_FAILED_VERIFICATION;
1450 }
1451 else {
1452 /* we have to look to the last occurrence of a commonName in the
1453 distinguished one to get the most significant one. */
1454 int j, i = -1;
1455
1456 /* The following is done because of a bug in 0.9.6b */
1457
1458 unsigned char *nulstr = (unsigned char *)"";
1459 unsigned char *peer_CN = nulstr;
1460
1461 X509_NAME *name = X509_get_subject_name(server_cert);
1462 if(name)
1463 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
1464 i = j;
1465
1466 /* we have the name entry and we will now convert this to a string
1467 that we can use for comparison. Doing this we support BMPstring,
1468 UTF8 etc. */
1469
1470 if(i >= 0) {
1471 ASN1_STRING *tmp =
1472 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
1473
1474 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1475 is already UTF-8 encoded. We check for this case and copy the raw
1476 string manually to avoid the problem. This code can be made
1477 conditional in the future when OpenSSL has been fixed. Work-around
1478 brought by Alexis S. L. Carvalho. */
1479 if(tmp) {
1480 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1481 j = ASN1_STRING_length(tmp);
1482 if(j >= 0) {
1483 peer_CN = OPENSSL_malloc(j + 1);
1484 if(peer_CN) {
1485 memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
1486 peer_CN[j] = '\0';
1487 }
1488 }
1489 }
1490 else /* not a UTF8 name */
1491 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1492
1493 if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
1494 /* there was a terminating zero before the end of string, this
1495 cannot match and we return failure! */
1496 failf(data, "SSL: illegal cert name field");
1497 result = CURLE_PEER_FAILED_VERIFICATION;
1498 }
1499 }
1500 }
1501
1502 if(peer_CN == nulstr)
1503 peer_CN = NULL;
1504 else {
1505 /* convert peer_CN from UTF8 */
1506 CURLcode rc = Curl_convert_from_utf8(data, (char *)peer_CN,
1507 strlen((char *)peer_CN));
1508 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1509 if(rc) {
1510 OPENSSL_free(peer_CN);
1511 return rc;
1512 }
1513 }
1514
1515 if(result)
1516 /* error already detected, pass through */
1517 ;
1518 else if(!peer_CN) {
1519 failf(data,
1520 "SSL: unable to obtain common name from peer certificate");
1521 result = CURLE_PEER_FAILED_VERIFICATION;
1522 }
1523 else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
1524 failf(data, "SSL: certificate subject name '%s' does not match "
1525 "target host name '%s'", peer_CN, dispname);
1526 result = CURLE_PEER_FAILED_VERIFICATION;
1527 }
1528 else {
1529 infof(data, " common name: %s (matched)\n", peer_CN);
1530 }
1531 if(peer_CN)
1532 OPENSSL_free(peer_CN);
1533 }
1534
1535 return result;
1536}
1537
1538#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
1539 !defined(OPENSSL_NO_OCSP)
1540static CURLcode verifystatus(struct connectdata *conn,
1541 struct ssl_connect_data *connssl)
1542{
1543 int i, ocsp_status;
1544 const unsigned char *p;
1545 CURLcode result = CURLE_OK;
1546 struct Curl_easy *data = conn->data;
1547
1548 OCSP_RESPONSE *rsp = NULL;
1549 OCSP_BASICRESP *br = NULL;
1550 X509_STORE *st = NULL;
1551 STACK_OF(X509) *ch = NULL;
1552
1553 long len = SSL_get_tlsext_status_ocsp_resp(BACKEND->handle, &p);
1554
1555 if(!p) {
1556 failf(data, "No OCSP response received");
1557 result = CURLE_SSL_INVALIDCERTSTATUS;
1558 goto end;
1559 }
1560
1561 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1562 if(!rsp) {
1563 failf(data, "Invalid OCSP response");
1564 result = CURLE_SSL_INVALIDCERTSTATUS;
1565 goto end;
1566 }
1567
1568 ocsp_status = OCSP_response_status(rsp);
1569 if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1570 failf(data, "Invalid OCSP response status: %s (%d)",
1571 OCSP_response_status_str(ocsp_status), ocsp_status);
1572 result = CURLE_SSL_INVALIDCERTSTATUS;
1573 goto end;
1574 }
1575
1576 br = OCSP_response_get1_basic(rsp);
1577 if(!br) {
1578 failf(data, "Invalid OCSP response");
1579 result = CURLE_SSL_INVALIDCERTSTATUS;
1580 goto end;
1581 }
1582
1583 ch = SSL_get_peer_cert_chain(BACKEND->handle);
1584 st = SSL_CTX_get_cert_store(BACKEND->ctx);
1585
1586#if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
1587 (defined(LIBRESSL_VERSION_NUMBER) && \
1588 LIBRESSL_VERSION_NUMBER <= 0x2040200fL))
1589 /* The authorized responder cert in the OCSP response MUST be signed by the
1590 peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
1591 no problem, but if it's an intermediate cert OpenSSL has a bug where it
1592 expects this issuer to be present in the chain embedded in the OCSP
1593 response. So we add it if necessary. */
1594
1595 /* First make sure the peer cert chain includes both a peer and an issuer,
1596 and the OCSP response contains a responder cert. */
1597 if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
1598 X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
1599
1600 /* Find issuer of responder cert and add it to the OCSP response chain */
1601 for(i = 0; i < sk_X509_num(ch); i++) {
1602 X509 *issuer = sk_X509_value(ch, i);
1603 if(X509_check_issued(issuer, responder) == X509_V_OK) {
1604 if(!OCSP_basic_add1_cert(br, issuer)) {
1605 failf(data, "Could not add issuer cert to OCSP response");
1606 result = CURLE_SSL_INVALIDCERTSTATUS;
1607 goto end;
1608 }
1609 }
1610 }
1611 }
1612#endif
1613
1614 if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
1615 failf(data, "OCSP response verification failed");
1616 result = CURLE_SSL_INVALIDCERTSTATUS;
1617 goto end;
1618 }
1619
1620 for(i = 0; i < OCSP_resp_count(br); i++) {
1621 int cert_status, crl_reason;
1622 OCSP_SINGLERESP *single = NULL;
1623
1624 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1625
1626 single = OCSP_resp_get0(br, i);
1627 if(!single)
1628 continue;
1629
1630 cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
1631 &thisupd, &nextupd);
1632
1633 if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
1634 failf(data, "OCSP response has expired");
1635 result = CURLE_SSL_INVALIDCERTSTATUS;
1636 goto end;
1637 }
1638
1639 infof(data, "SSL certificate status: %s (%d)\n",
1640 OCSP_cert_status_str(cert_status), cert_status);
1641
1642 switch(cert_status) {
1643 case V_OCSP_CERTSTATUS_GOOD:
1644 break;
1645
1646 case V_OCSP_CERTSTATUS_REVOKED:
1647 result = CURLE_SSL_INVALIDCERTSTATUS;
1648
1649 failf(data, "SSL certificate revocation reason: %s (%d)",
1650 OCSP_crl_reason_str(crl_reason), crl_reason);
1651 goto end;
1652
1653 case V_OCSP_CERTSTATUS_UNKNOWN:
1654 result = CURLE_SSL_INVALIDCERTSTATUS;
1655 goto end;
1656 }
1657 }
1658
1659end:
1660 if(br) OCSP_BASICRESP_free(br);
1661 OCSP_RESPONSE_free(rsp);
1662
1663 return result;
1664}
1665#endif
1666
1667#endif /* USE_OPENSSL */
1668
1669/* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1670 and thus this cannot be done there. */
1671#ifdef SSL_CTRL_SET_MSG_CALLBACK
1672
1673static const char *ssl_msg_type(int ssl_ver, int msg)
1674{
1675#ifdef SSL2_VERSION_MAJOR
1676 if(ssl_ver == SSL2_VERSION_MAJOR) {
1677 switch(msg) {
1678 case SSL2_MT_ERROR:
1679 return "Error";
1680 case SSL2_MT_CLIENT_HELLO:
1681 return "Client hello";
1682 case SSL2_MT_CLIENT_MASTER_KEY:
1683 return "Client key";
1684 case SSL2_MT_CLIENT_FINISHED:
1685 return "Client finished";
1686 case SSL2_MT_SERVER_HELLO:
1687 return "Server hello";
1688 case SSL2_MT_SERVER_VERIFY:
1689 return "Server verify";
1690 case SSL2_MT_SERVER_FINISHED:
1691 return "Server finished";
1692 case SSL2_MT_REQUEST_CERTIFICATE:
1693 return "Request CERT";
1694 case SSL2_MT_CLIENT_CERTIFICATE:
1695 return "Client CERT";
1696 }
1697 }
1698 else
1699#endif
1700 if(ssl_ver == SSL3_VERSION_MAJOR) {
1701 switch(msg) {
1702 case SSL3_MT_HELLO_REQUEST:
1703 return "Hello request";
1704 case SSL3_MT_CLIENT_HELLO:
1705 return "Client hello";
1706 case SSL3_MT_SERVER_HELLO:
1707 return "Server hello";
1708#ifdef SSL3_MT_NEWSESSION_TICKET
1709 case SSL3_MT_NEWSESSION_TICKET:
1710 return "Newsession Ticket";
1711#endif
1712 case SSL3_MT_CERTIFICATE:
1713 return "Certificate";
1714 case SSL3_MT_SERVER_KEY_EXCHANGE:
1715 return "Server key exchange";
1716 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1717 return "Client key exchange";
1718 case SSL3_MT_CERTIFICATE_REQUEST:
1719 return "Request CERT";
1720 case SSL3_MT_SERVER_DONE:
1721 return "Server finished";
1722 case SSL3_MT_CERTIFICATE_VERIFY:
1723 return "CERT verify";
1724 case SSL3_MT_FINISHED:
1725 return "Finished";
1726#ifdef SSL3_MT_CERTIFICATE_STATUS
1727 case SSL3_MT_CERTIFICATE_STATUS:
1728 return "Certificate Status";
1729#endif
1730 }
1731 }
1732 return "Unknown";
1733}
1734
1735static const char *tls_rt_type(int type)
1736{
1737 switch(type) {
1738#ifdef SSL3_RT_HEADER
1739 case SSL3_RT_HEADER:
1740 return "TLS header";
1741#endif
1742 case SSL3_RT_CHANGE_CIPHER_SPEC:
1743 return "TLS change cipher";
1744 case SSL3_RT_ALERT:
1745 return "TLS alert";
1746 case SSL3_RT_HANDSHAKE:
1747 return "TLS handshake";
1748 case SSL3_RT_APPLICATION_DATA:
1749 return "TLS app data";
1750 default:
1751 return "TLS Unknown";
1752 }
1753}
1754
1755
1756/*
1757 * Our callback from the SSL/TLS layers.
1758 */
1759static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1760 const void *buf, size_t len, SSL *ssl,
1761 void *userp)
1762{
1763 struct Curl_easy *data;
1764 const char *msg_name, *tls_rt_name;
1765 char ssl_buf[1024];
1766 char unknown[32];
1767 int msg_type, txt_len;
1768 const char *verstr = NULL;
1769 struct connectdata *conn = userp;
1770
1771 if(!conn || !conn->data || !conn->data->set.fdebug ||
1772 (direction != 0 && direction != 1))
1773 return;
1774
1775 data = conn->data;
1776
1777 switch(ssl_ver) {
1778#ifdef SSL2_VERSION /* removed in recent versions */
1779 case SSL2_VERSION:
1780 verstr = "SSLv2";
1781 break;
1782#endif
1783#ifdef SSL3_VERSION
1784 case SSL3_VERSION:
1785 verstr = "SSLv3";
1786 break;
1787#endif
1788 case TLS1_VERSION:
1789 verstr = "TLSv1.0";
1790 break;
1791#ifdef TLS1_1_VERSION
1792 case TLS1_1_VERSION:
1793 verstr = "TLSv1.1";
1794 break;
1795#endif
1796#ifdef TLS1_2_VERSION
1797 case TLS1_2_VERSION:
1798 verstr = "TLSv1.2";
1799 break;
1800#endif
1801#ifdef TLS1_3_VERSION
1802 case TLS1_3_VERSION:
1803 verstr = "TLSv1.3";
1804 break;
1805#endif
1806 case 0:
1807 break;
1808 default:
1809 snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
1810 verstr = unknown;
1811 break;
1812 }
1813
1814 if(ssl_ver) {
1815 /* the info given when the version is zero is not that useful for us */
1816
1817 ssl_ver >>= 8; /* check the upper 8 bits only below */
1818
1819 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1820 * always pass-up content-type as 0. But the interesting message-type
1821 * is at 'buf[0]'.
1822 */
1823 if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
1824 tls_rt_name = tls_rt_type(content_type);
1825 else
1826 tls_rt_name = "";
1827
1828 msg_type = *(char *)buf;
1829 msg_name = ssl_msg_type(ssl_ver, msg_type);
1830
1831 txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
1832 verstr, direction?"OUT":"IN",
1833 tls_rt_name, msg_name, msg_type);
1834 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
1835 }
1836
1837 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1838 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1839 (void) ssl;
1840}
1841#endif
1842
1843#ifdef USE_OPENSSL
1844/* ====================================================== */
1845
1846#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1847# define use_sni(x) sni = (x)
1848#else
1849# define use_sni(x) Curl_nop_stmt
1850#endif
1851
1852/* Check for OpenSSL 1.0.2 which has ALPN support. */
1853#undef HAS_ALPN
1854#if OPENSSL_VERSION_NUMBER >= 0x10002000L \
1855 && !defined(OPENSSL_NO_TLSEXT)
1856# define HAS_ALPN 1
1857#endif
1858
1859/* Check for OpenSSL 1.0.1 which has NPN support. */
1860#undef HAS_NPN
1861#if OPENSSL_VERSION_NUMBER >= 0x10001000L \
1862 && !defined(OPENSSL_NO_TLSEXT) \
1863 && !defined(OPENSSL_NO_NEXTPROTONEG)
1864# define HAS_NPN 1
1865#endif
1866
1867#ifdef HAS_NPN
1868
1869/*
1870 * in is a list of length prefixed strings. this function has to select
1871 * the protocol we want to use from the list and write its string into out.
1872 */
1873
1874static int
1875select_next_protocol(unsigned char **out, unsigned char *outlen,
1876 const unsigned char *in, unsigned int inlen,
1877 const char *key, unsigned int keylen)
1878{
1879 unsigned int i;
1880 for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
1881 if(memcmp(&in[i + 1], key, keylen) == 0) {
1882 *out = (unsigned char *) &in[i + 1];
1883 *outlen = in[i];
1884 return 0;
1885 }
1886 }
1887 return -1;
1888}
1889
1890static int
1891select_next_proto_cb(SSL *ssl,
1892 unsigned char **out, unsigned char *outlen,
1893 const unsigned char *in, unsigned int inlen,
1894 void *arg)
1895{
1896 struct connectdata *conn = (struct connectdata*) arg;
1897
1898 (void)ssl;
1899
1900#ifdef USE_NGHTTP2
1901 if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
1902 !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
1903 NGHTTP2_PROTO_VERSION_ID_LEN)) {
1904 infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
1905 NGHTTP2_PROTO_VERSION_ID);
1906 conn->negnpn = CURL_HTTP_VERSION_2;
1907 return SSL_TLSEXT_ERR_OK;
1908 }
1909#endif
1910
1911 if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
1912 ALPN_HTTP_1_1_LENGTH)) {
1913 infof(conn->data, "NPN, negotiated HTTP1.1\n");
1914 conn->negnpn = CURL_HTTP_VERSION_1_1;
1915 return SSL_TLSEXT_ERR_OK;
1916 }
1917
1918 infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
1919 *out = (unsigned char *)ALPN_HTTP_1_1;
1920 *outlen = ALPN_HTTP_1_1_LENGTH;
1921 conn->negnpn = CURL_HTTP_VERSION_1_1;
1922
1923 return SSL_TLSEXT_ERR_OK;
1924}
1925#endif /* HAS_NPN */
1926
1927static const char *
1928get_ssl_version_txt(SSL *ssl)
1929{
1930 if(!ssl)
1931 return "";
1932
1933 switch(SSL_version(ssl)) {
1934#ifdef TLS1_3_VERSION
1935 case TLS1_3_VERSION:
1936 return "TLSv1.3";
1937#endif
1938#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1939 case TLS1_2_VERSION:
1940 return "TLSv1.2";
1941 case TLS1_1_VERSION:
1942 return "TLSv1.1";
1943#endif
1944 case TLS1_VERSION:
1945 return "TLSv1.0";
1946 case SSL3_VERSION:
1947 return "SSLv3";
1948 case SSL2_VERSION:
1949 return "SSLv2";
1950 }
1951 return "unknown";
1952}
1953
1954static CURLcode
1955set_ssl_version_min_max(long *ctx_options, struct connectdata *conn,
1956 int sockindex)
1957{
1958#if (OPENSSL_VERSION_NUMBER < 0x1000100FL) || !defined(TLS1_3_VERSION)
1959 /* convoluted #if condition just to avoid compiler warnings on unused
1960 variable */
1961 struct Curl_easy *data = conn->data;
1962#endif
1963 long ssl_version = SSL_CONN_CONFIG(version);
1964 long ssl_version_max = SSL_CONN_CONFIG(version_max);
1965
1966 if(ssl_version_max == CURL_SSLVERSION_MAX_NONE) {
1967 ssl_version_max = ssl_version << 16;
1968 }
1969
1970 switch(ssl_version) {
1971 case CURL_SSLVERSION_TLSv1_3:
1972#ifdef TLS1_3_VERSION
1973 {
1974 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1975 SSL_CTX_set_max_proto_version(BACKEND->ctx, TLS1_3_VERSION);
1976 *ctx_options |= SSL_OP_NO_TLSv1_2;
1977 }
1978#else
1979 (void)sockindex;
1980 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
1981 return CURLE_NOT_BUILT_IN;
1982#endif
1983 /* FALLTHROUGH */
1984 case CURL_SSLVERSION_TLSv1_2:
1985#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1986 *ctx_options |= SSL_OP_NO_TLSv1_1;
1987#else
1988 failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
1989 return CURLE_NOT_BUILT_IN;
1990#endif
1991 /* FALLTHROUGH */
1992 case CURL_SSLVERSION_TLSv1_1:
1993#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1994 *ctx_options |= SSL_OP_NO_TLSv1;
1995#else
1996 failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
1997 return CURLE_NOT_BUILT_IN;
1998#endif
1999 /* FALLTHROUGH */
2000 case CURL_SSLVERSION_TLSv1_0:
2001 *ctx_options |= SSL_OP_NO_SSLv2;
2002 *ctx_options |= SSL_OP_NO_SSLv3;
2003 break;
2004 }
2005
2006 switch(ssl_version_max) {
2007 case CURL_SSLVERSION_MAX_TLSv1_0:
2008#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2009 *ctx_options |= SSL_OP_NO_TLSv1_1;
2010#endif
2011 /* FALLTHROUGH */
2012 case CURL_SSLVERSION_MAX_TLSv1_1:
2013#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2014 *ctx_options |= SSL_OP_NO_TLSv1_2;
2015#endif
2016 /* FALLTHROUGH */
2017 case CURL_SSLVERSION_MAX_TLSv1_2:
2018 case CURL_SSLVERSION_MAX_DEFAULT:
2019#ifdef TLS1_3_VERSION
2020 *ctx_options |= SSL_OP_NO_TLSv1_3;
2021#endif
2022 break;
2023 case CURL_SSLVERSION_MAX_TLSv1_3:
2024#ifdef TLS1_3_VERSION
2025 break;
2026#else
2027 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
2028 return CURLE_NOT_BUILT_IN;
2029#endif
2030 }
2031 return CURLE_OK;
2032}
2033
2034static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
2035{
2036 CURLcode result = CURLE_OK;
2037 char *ciphers;
2038 struct Curl_easy *data = conn->data;
2039 SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
2040 X509_LOOKUP *lookup = NULL;
2041 curl_socket_t sockfd = conn->sock[sockindex];
2042 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2043 long ctx_options = 0;
2044#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2045 bool sni;
2046 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
2047 conn->host.name;
2048#ifdef ENABLE_IPV6
2049 struct in6_addr addr;
2050#else
2051 struct in_addr addr;
2052#endif
2053#endif
2054 long * const certverifyresult = SSL_IS_PROXY() ?
2055 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2056 const long int ssl_version = SSL_CONN_CONFIG(version);
2057#ifdef USE_TLS_SRP
2058 const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
2059#endif
2060 char * const ssl_cert = SSL_SET_OPTION(cert);
2061 const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
2062 const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
2063 const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
2064 const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
2065 const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
2066 char error_buffer[256];
2067
2068 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
2069
2070 /* Make funny stuff to get random input */
2071 result = Curl_ossl_seed(data);
2072 if(result)
2073 return result;
2074
2075 *certverifyresult = !X509_V_OK;
2076
2077 /* check to see if we've been told to use an explicit SSL/TLS version */
2078
2079 switch(ssl_version) {
2080 case CURL_SSLVERSION_DEFAULT:
2081 case CURL_SSLVERSION_TLSv1:
2082 case CURL_SSLVERSION_TLSv1_0:
2083 case CURL_SSLVERSION_TLSv1_1:
2084 case CURL_SSLVERSION_TLSv1_2:
2085 case CURL_SSLVERSION_TLSv1_3:
2086 /* it will be handled later with the context options */
2087#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
2088 !defined(LIBRESSL_VERSION_NUMBER)
2089 req_method = TLS_client_method();
2090#else
2091 req_method = SSLv23_client_method();
2092#endif
2093 use_sni(TRUE);
2094 break;
2095 case CURL_SSLVERSION_SSLv2:
2096#ifdef OPENSSL_NO_SSL2
2097 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
2098 return CURLE_NOT_BUILT_IN;
2099#else
2100#ifdef USE_TLS_SRP
2101 if(ssl_authtype == CURL_TLSAUTH_SRP)
2102 return CURLE_SSL_CONNECT_ERROR;
2103#endif
2104 req_method = SSLv2_client_method();
2105 use_sni(FALSE);
2106 break;
2107#endif
2108 case CURL_SSLVERSION_SSLv3:
2109#ifdef OPENSSL_NO_SSL3_METHOD
2110 failf(data, OSSL_PACKAGE " was built without SSLv3 support");
2111 return CURLE_NOT_BUILT_IN;
2112#else
2113#ifdef USE_TLS_SRP
2114 if(ssl_authtype == CURL_TLSAUTH_SRP)
2115 return CURLE_SSL_CONNECT_ERROR;
2116#endif
2117 req_method = SSLv3_client_method();
2118 use_sni(FALSE);
2119 break;
2120#endif
2121 default:
2122 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2123 return CURLE_SSL_CONNECT_ERROR;
2124 }
2125
2126 if(BACKEND->ctx)
2127 SSL_CTX_free(BACKEND->ctx);
2128 BACKEND->ctx = SSL_CTX_new(req_method);
2129
2130 if(!BACKEND->ctx) {
2131 failf(data, "SSL: couldn't create a context: %s",
2132 ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
2133 return CURLE_OUT_OF_MEMORY;
2134 }
2135
2136#ifdef SSL_MODE_RELEASE_BUFFERS
2137 SSL_CTX_set_mode(BACKEND->ctx, SSL_MODE_RELEASE_BUFFERS);
2138#endif
2139
2140#ifdef SSL_CTRL_SET_MSG_CALLBACK
2141 if(data->set.fdebug && data->set.verbose) {
2142 /* the SSL trace callback is only used for verbose logging */
2143 SSL_CTX_set_msg_callback(BACKEND->ctx, ssl_tls_trace);
2144 SSL_CTX_set_msg_callback_arg(BACKEND->ctx, conn);
2145 }
2146#endif
2147
2148 /* OpenSSL contains code to work-around lots of bugs and flaws in various
2149 SSL-implementations. SSL_CTX_set_options() is used to enabled those
2150 work-arounds. The man page for this option states that SSL_OP_ALL enables
2151 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
2152 enable the bug workaround options if compatibility with somewhat broken
2153 implementations is desired."
2154
2155 The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
2156 disable "rfc4507bis session ticket support". rfc4507bis was later turned
2157 into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
2158
2159 The enabled extension concerns the session management. I wonder how often
2160 libcurl stops a connection and then resumes a TLS session. also, sending
2161 the session data is some overhead. .I suggest that you just use your
2162 proposed patch (which explicitly disables TICKET).
2163
2164 If someone writes an application with libcurl and openssl who wants to
2165 enable the feature, one can do this in the SSL callback.
2166
2167 SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
2168 interoperability with web server Netscape Enterprise Server 2.0.1 which
2169 was released back in 1996.
2170
2171 Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
2172 become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
2173 CVE-2010-4180 when using previous OpenSSL versions we no longer enable
2174 this option regardless of OpenSSL version and SSL_OP_ALL definition.
2175
2176 OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
2177 (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
2178 SSL_OP_ALL that _disables_ that work-around despite the fact that
2179 SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
2180 keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
2181 must not be set.
2182 */
2183
2184 ctx_options = SSL_OP_ALL;
2185
2186#ifdef SSL_OP_NO_TICKET
2187 ctx_options |= SSL_OP_NO_TICKET;
2188#endif
2189
2190#ifdef SSL_OP_NO_COMPRESSION
2191 ctx_options |= SSL_OP_NO_COMPRESSION;
2192#endif
2193
2194#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
2195 /* mitigate CVE-2010-4180 */
2196 ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
2197#endif
2198
2199#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
2200 /* unless the user explicitly ask to allow the protocol vulnerability we
2201 use the work-around */
2202 if(!SSL_SET_OPTION(enable_beast))
2203 ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2204#endif
2205
2206 switch(ssl_version) {
2207 case CURL_SSLVERSION_SSLv3:
2208#ifdef USE_TLS_SRP
2209 if(ssl_authtype == CURL_TLSAUTH_SRP) {
2210 infof(data, "Set version TLSv1.x for SRP authorisation\n");
2211 }
2212#endif
2213 ctx_options |= SSL_OP_NO_SSLv2;
2214 ctx_options |= SSL_OP_NO_TLSv1;
2215#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2216 ctx_options |= SSL_OP_NO_TLSv1_1;
2217 ctx_options |= SSL_OP_NO_TLSv1_2;
2218#ifdef TLS1_3_VERSION
2219 ctx_options |= SSL_OP_NO_TLSv1_3;
2220#endif
2221#endif
2222 break;
2223
2224 case CURL_SSLVERSION_DEFAULT:
2225 case CURL_SSLVERSION_TLSv1:
2226 ctx_options |= SSL_OP_NO_SSLv2;
2227 ctx_options |= SSL_OP_NO_SSLv3;
2228 break;
2229
2230 case CURL_SSLVERSION_TLSv1_0:
2231 case CURL_SSLVERSION_TLSv1_1:
2232 case CURL_SSLVERSION_TLSv1_2:
2233 case CURL_SSLVERSION_TLSv1_3:
2234 result = set_ssl_version_min_max(&ctx_options, conn, sockindex);
2235 if(result != CURLE_OK)
2236 return result;
2237 break;
2238
2239 case CURL_SSLVERSION_SSLv2:
2240#ifndef OPENSSL_NO_SSL2
2241 ctx_options |= SSL_OP_NO_SSLv3;
2242 ctx_options |= SSL_OP_NO_TLSv1;
2243#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2244 ctx_options |= SSL_OP_NO_TLSv1_1;
2245 ctx_options |= SSL_OP_NO_TLSv1_2;
2246#ifdef TLS1_3_VERSION
2247 ctx_options |= SSL_OP_NO_TLSv1_3;
2248#endif
2249#endif
2250 break;
2251#else
2252 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
2253 return CURLE_NOT_BUILT_IN;
2254#endif
2255
2256 default:
2257 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2258 return CURLE_SSL_CONNECT_ERROR;
2259 }
2260
2261 SSL_CTX_set_options(BACKEND->ctx, ctx_options);
2262
2263#ifdef HAS_NPN
2264 if(conn->bits.tls_enable_npn)
2265 SSL_CTX_set_next_proto_select_cb(BACKEND->ctx, select_next_proto_cb, conn);
2266#endif
2267
2268#ifdef HAS_ALPN
2269 if(conn->bits.tls_enable_alpn) {
2270 int cur = 0;
2271 unsigned char protocols[128];
2272
2273#ifdef USE_NGHTTP2
2274 if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
2275 (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
2276 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
2277
2278 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
2279 NGHTTP2_PROTO_VERSION_ID_LEN);
2280 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
2281 infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
2282 }
2283#endif
2284
2285 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
2286 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
2287 cur += ALPN_HTTP_1_1_LENGTH;
2288 infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
2289
2290 /* expects length prefixed preference ordered list of protocols in wire
2291 * format
2292 */
2293 SSL_CTX_set_alpn_protos(BACKEND->ctx, protocols, cur);
2294 }
2295#endif
2296
2297 if(ssl_cert || ssl_cert_type) {
2298 if(!cert_stuff(conn, BACKEND->ctx, ssl_cert, ssl_cert_type,
2299 SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
2300 SSL_SET_OPTION(key_passwd))) {
2301 /* failf() is already done in cert_stuff() */
2302 return CURLE_SSL_CERTPROBLEM;
2303 }
2304 }
2305
2306 ciphers = SSL_CONN_CONFIG(cipher_list);
2307 if(!ciphers)
2308 ciphers = (char *)DEFAULT_CIPHER_SELECTION;
2309 if(ciphers) {
2310 if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) {
2311 failf(data, "failed setting cipher list: %s", ciphers);
2312 return CURLE_SSL_CIPHER;
2313 }
2314 infof(data, "Cipher selection: %s\n", ciphers);
2315 }
2316
2317#ifdef USE_TLS_SRP
2318 if(ssl_authtype == CURL_TLSAUTH_SRP) {
2319 char * const ssl_username = SSL_SET_OPTION(username);
2320
2321 infof(data, "Using TLS-SRP username: %s\n", ssl_username);
2322
2323 if(!SSL_CTX_set_srp_username(BACKEND->ctx, ssl_username)) {
2324 failf(data, "Unable to set SRP user name");
2325 return CURLE_BAD_FUNCTION_ARGUMENT;
2326 }
2327 if(!SSL_CTX_set_srp_password(BACKEND->ctx, SSL_SET_OPTION(password))) {
2328 failf(data, "failed setting SRP password");
2329 return CURLE_BAD_FUNCTION_ARGUMENT;
2330 }
2331 if(!SSL_CONN_CONFIG(cipher_list)) {
2332 infof(data, "Setting cipher list SRP\n");
2333
2334 if(!SSL_CTX_set_cipher_list(BACKEND->ctx, "SRP")) {
2335 failf(data, "failed setting SRP cipher list");
2336 return CURLE_SSL_CIPHER;
2337 }
2338 }
2339 }
2340#endif
2341
2342 if(ssl_cafile || ssl_capath) {
2343 /* tell SSL where to find CA certificates that are used to verify
2344 the servers certificate. */
2345 if(!SSL_CTX_load_verify_locations(BACKEND->ctx, ssl_cafile, ssl_capath)) {
2346 if(verifypeer) {
2347 /* Fail if we insist on successfully verifying the server. */
2348 failf(data, "error setting certificate verify locations:\n"
2349 " CAfile: %s\n CApath: %s",
2350 ssl_cafile ? ssl_cafile : "none",
2351 ssl_capath ? ssl_capath : "none");
2352 return CURLE_SSL_CACERT_BADFILE;
2353 }
2354 /* Just continue with a warning if no strict certificate verification
2355 is required. */
2356 infof(data, "error setting certificate verify locations,"
2357 " continuing anyway:\n");
2358 }
2359 else {
2360 /* Everything is fine. */
2361 infof(data, "successfully set certificate verify locations:\n");
2362 }
2363 infof(data,
2364 " CAfile: %s\n"
2365 " CApath: %s\n",
2366 ssl_cafile ? ssl_cafile : "none",
2367 ssl_capath ? ssl_capath : "none");
2368 }
2369#ifdef CURL_CA_FALLBACK
2370 else if(verifypeer) {
2371 /* verfying the peer without any CA certificates won't
2372 work so use openssl's built in default as fallback */
2373 SSL_CTX_set_default_verify_paths(BACKEND->ctx);
2374 }
2375#endif
2376
2377 if(ssl_crlfile) {
2378 /* tell SSL where to find CRL file that is used to check certificate
2379 * revocation */
2380 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(BACKEND->ctx),
2381 X509_LOOKUP_file());
2382 if(!lookup ||
2383 (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
2384 failf(data, "error loading CRL file: %s", ssl_crlfile);
2385 return CURLE_SSL_CRL_BADFILE;
2386 }
2387 /* Everything is fine. */
2388 infof(data, "successfully load CRL file:\n");
2389 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2390 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2391
2392 infof(data, " CRLfile: %s\n", ssl_crlfile);
2393 }
2394
2395 /* Try building a chain using issuers in the trusted store first to avoid
2396 problems with server-sent legacy intermediates.
2397 Newer versions of OpenSSL do alternate chain checking by default which
2398 gives us the same fix without as much of a performance hit (slight), so we
2399 prefer that if available.
2400 https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
2401 */
2402#if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
2403 if(verifypeer) {
2404 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2405 X509_V_FLAG_TRUSTED_FIRST);
2406 }
2407#endif
2408
2409 /* SSL always tries to verify the peer, this only says whether it should
2410 * fail to connect if the verification fails, or if it should continue
2411 * anyway. In the latter case the result of the verification is checked with
2412 * SSL_get_verify_result() below. */
2413 SSL_CTX_set_verify(BACKEND->ctx,
2414 verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
2415
2416 /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
2417#if defined(ENABLE_SSLKEYLOGFILE) && defined(HAVE_KEYLOG_CALLBACK)
2418 if(keylog_file) {
2419 SSL_CTX_set_keylog_callback(connssl->ctx, ossl_keylog_callback);
2420 }
2421#endif
2422
2423 /* give application a chance to interfere with SSL set up. */
2424 if(data->set.ssl.fsslctx) {
2425 result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx,
2426 data->set.ssl.fsslctxp);
2427 if(result) {
2428 failf(data, "error signaled by ssl ctx callback");
2429 return result;
2430 }
2431 }
2432
2433 /* Lets make an SSL structure */
2434 if(BACKEND->handle)
2435 SSL_free(BACKEND->handle);
2436 BACKEND->handle = SSL_new(BACKEND->ctx);
2437 if(!BACKEND->handle) {
2438 failf(data, "SSL: couldn't create a context (handle)!");
2439 return CURLE_OUT_OF_MEMORY;
2440 }
2441
2442#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
2443 !defined(OPENSSL_NO_OCSP)
2444 if(SSL_CONN_CONFIG(verifystatus))
2445 SSL_set_tlsext_status_type(BACKEND->handle, TLSEXT_STATUSTYPE_ocsp);
2446#endif
2447
2448 SSL_set_connect_state(BACKEND->handle);
2449
2450 BACKEND->server_cert = 0x0;
2451#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2452 if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
2453#ifdef ENABLE_IPV6
2454 (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
2455#endif
2456 sni &&
2457 !SSL_set_tlsext_host_name(BACKEND->handle, hostname))
2458 infof(data, "WARNING: failed to configure server name indication (SNI) "
2459 "TLS extension\n");
2460#endif
2461
2462 /* Check if there's a cached ID we can/should use here! */
2463 if(SSL_SET_OPTION(primary.sessionid)) {
2464 void *ssl_sessionid = NULL;
2465
2466 Curl_ssl_sessionid_lock(conn);
2467 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
2468 /* we got a session id, use it! */
2469 if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {
2470 Curl_ssl_sessionid_unlock(conn);
2471 failf(data, "SSL: SSL_set_session failed: %s",
2472 ossl_strerror(ERR_get_error(), error_buffer,
2473 sizeof(error_buffer)));
2474 return CURLE_SSL_CONNECT_ERROR;
2475 }
2476 /* Informational message */
2477 infof(data, "SSL re-using session ID\n");
2478 }
2479 Curl_ssl_sessionid_unlock(conn);
2480 }
2481
2482 if(conn->proxy_ssl[sockindex].use) {
2483 BIO *const bio = BIO_new(BIO_f_ssl());
2484 SSL *handle = conn->proxy_ssl[sockindex].backend->handle;
2485 DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
2486 DEBUGASSERT(handle != NULL);
2487 DEBUGASSERT(bio != NULL);
2488 BIO_set_ssl(bio, handle, FALSE);
2489 SSL_set_bio(BACKEND->handle, bio, bio);
2490 }
2491 else if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) {
2492 /* pass the raw socket into the SSL layers */
2493 failf(data, "SSL: SSL_set_fd failed: %s",
2494 ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
2495 return CURLE_SSL_CONNECT_ERROR;
2496 }
2497
2498 connssl->connecting_state = ssl_connect_2;
2499
2500 return CURLE_OK;
2501}
2502
2503static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
2504{
2505 struct Curl_easy *data = conn->data;
2506 int err;
2507 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2508 long * const certverifyresult = SSL_IS_PROXY() ?
2509 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2510 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
2511 || ssl_connect_2_reading == connssl->connecting_state
2512 || ssl_connect_2_writing == connssl->connecting_state);
2513
2514 ERR_clear_error();
2515
2516 err = SSL_connect(BACKEND->handle);
2517 /* If keylogging is enabled but the keylog callback is not supported then log
2518 secrets here, immediately after SSL_connect by using tap_ssl_key. */
2519#if defined(ENABLE_SSLKEYLOGFILE) && !defined(HAVE_KEYLOG_CALLBACK)
2520 tap_ssl_key(BACKEND->handle, &BACKEND->tap_state);
2521#endif
2522
2523 /* 1 is fine
2524 0 is "not successful but was shut down controlled"
2525 <0 is "handshake was not successful, because a fatal error occurred" */
2526 if(1 != err) {
2527 int detail = SSL_get_error(BACKEND->handle, err);
2528
2529 if(SSL_ERROR_WANT_READ == detail) {
2530 connssl->connecting_state = ssl_connect_2_reading;
2531 return CURLE_OK;
2532 }
2533 if(SSL_ERROR_WANT_WRITE == detail) {
2534 connssl->connecting_state = ssl_connect_2_writing;
2535 return CURLE_OK;
2536 }
2537 else {
2538 /* untreated error */
2539 unsigned long errdetail;
2540 char error_buffer[256]="";
2541 CURLcode result;
2542 long lerr;
2543 int lib;
2544 int reason;
2545
2546 /* the connection failed, we're not waiting for anything else. */
2547 connssl->connecting_state = ssl_connect_2;
2548
2549 /* Get the earliest error code from the thread's error queue and removes
2550 the entry. */
2551 errdetail = ERR_get_error();
2552
2553 /* Extract which lib and reason */
2554 lib = ERR_GET_LIB(errdetail);
2555 reason = ERR_GET_REASON(errdetail);
2556
2557 if((lib == ERR_LIB_SSL) &&
2558 (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
2559 result = CURLE_SSL_CACERT;
2560
2561 lerr = SSL_get_verify_result(BACKEND->handle);
2562 if(lerr != X509_V_OK) {
2563 *certverifyresult = lerr;
2564 snprintf(error_buffer, sizeof(error_buffer),
2565 "SSL certificate problem: %s",
2566 X509_verify_cert_error_string(lerr));
2567 }
2568 else
2569 /* strcpy() is fine here as long as the string fits within
2570 error_buffer */
2571 strcpy(error_buffer, "SSL certificate verification failed");
2572 }
2573 else {
2574 result = CURLE_SSL_CONNECT_ERROR;
2575 ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
2576 }
2577
2578 /* detail is already set to the SSL error above */
2579
2580 /* If we e.g. use SSLv2 request-method and the server doesn't like us
2581 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
2582 * the SO_ERROR is also lost.
2583 */
2584 if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
2585 const char * const hostname = SSL_IS_PROXY() ?
2586 conn->http_proxy.host.name : conn->host.name;
2587 const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
2588 failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%ld ",
2589 SSL_ERROR_to_str(detail), hostname, port);
2590 return result;
2591 }
2592
2593 /* Could be a CERT problem */
2594 failf(data, "%s", error_buffer);
2595
2596 return result;
2597 }
2598 }
2599 else {
2600 /* we have been connected fine, we're not waiting for anything else. */
2601 connssl->connecting_state = ssl_connect_3;
2602
2603 /* Informational message */
2604 infof(data, "SSL connection using %s / %s\n",
2605 get_ssl_version_txt(BACKEND->handle),
2606 SSL_get_cipher(BACKEND->handle));
2607
2608#ifdef HAS_ALPN
2609 /* Sets data and len to negotiated protocol, len is 0 if no protocol was
2610 * negotiated
2611 */
2612 if(conn->bits.tls_enable_alpn) {
2613 const unsigned char *neg_protocol;
2614 unsigned int len;
2615 SSL_get0_alpn_selected(BACKEND->handle, &neg_protocol, &len);
2616 if(len != 0) {
2617 infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
2618
2619#ifdef USE_NGHTTP2
2620 if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
2621 !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
2622 conn->negnpn = CURL_HTTP_VERSION_2;
2623 }
2624 else
2625#endif
2626 if(len == ALPN_HTTP_1_1_LENGTH &&
2627 !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
2628 conn->negnpn = CURL_HTTP_VERSION_1_1;
2629 }
2630 }
2631 else
2632 infof(data, "ALPN, server did not agree to a protocol\n");
2633 }
2634#endif
2635
2636 return CURLE_OK;
2637 }
2638}
2639
2640static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
2641{
2642 int i, ilen;
2643
2644 ilen = (int)len;
2645 if(ilen < 0)
2646 return 1; /* buffer too big */
2647
2648 i = i2t_ASN1_OBJECT(buf, ilen, a);
2649
2650 if(i >= ilen)
2651 return 1; /* buffer too small */
2652
2653 return 0;
2654}
2655
2656#define push_certinfo(_label, _num) \
2657do { \
2658 long info_len = BIO_get_mem_data(mem, &ptr); \
2659 Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
2660 if(1 != BIO_reset(mem)) \
2661 break; \
2662} WHILE_FALSE
2663
2664static void pubkey_show(struct Curl_easy *data,
2665 BIO *mem,
2666 int num,
2667 const char *type,
2668 const char *name,
2669#ifdef HAVE_OPAQUE_RSA_DSA_DH
2670 const
2671#endif
2672 BIGNUM *bn)
2673{
2674 char *ptr;
2675 char namebuf[32];
2676
2677 snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
2678
2679 if(bn)
2680 BN_print(mem, bn);
2681 push_certinfo(namebuf, num);
2682}
2683
2684#ifdef HAVE_OPAQUE_RSA_DSA_DH
2685#define print_pubkey_BN(_type, _name, _num) \
2686 pubkey_show(data, mem, _num, #_type, #_name, _name)
2687
2688#else
2689#define print_pubkey_BN(_type, _name, _num) \
2690do { \
2691 if(_type->_name) { \
2692 pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
2693 } \
2694} WHILE_FALSE
2695#endif
2696
2697static int X509V3_ext(struct Curl_easy *data,
2698 int certnum,
2699 CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
2700{
2701 int i;
2702 size_t j;
2703
2704 if((int)sk_X509_EXTENSION_num(exts) <= 0)
2705 /* no extensions, bail out */
2706 return 1;
2707
2708 for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
2709 ASN1_OBJECT *obj;
2710 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
2711 BUF_MEM *biomem;
2712 char buf[512];
2713 char *ptr = buf;
2714 char namebuf[128];
2715 BIO *bio_out = BIO_new(BIO_s_mem());
2716
2717 if(!bio_out)
2718 return 1;
2719
2720 obj = X509_EXTENSION_get_object(ext);
2721
2722 asn1_object_dump(obj, namebuf, sizeof(namebuf));
2723
2724 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
2725 ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
2726
2727 BIO_get_mem_ptr(bio_out, &biomem);
2728
2729 for(j = 0; j < (size_t)biomem->length; j++) {
2730 const char *sep = "";
2731 if(biomem->data[j] == '\n') {
2732 sep = ", ";
2733 j++; /* skip the newline */
2734 };
2735 while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
2736 j++;
2737 if(j<(size_t)biomem->length)
2738 ptr += snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
2739 biomem->data[j]);
2740 }
2741
2742 Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
2743
2744 BIO_free(bio_out);
2745
2746 }
2747 return 0; /* all is fine */
2748}
2749
2750static CURLcode get_cert_chain(struct connectdata *conn,
2751 struct ssl_connect_data *connssl)
2752
2753{
2754 CURLcode result;
2755 STACK_OF(X509) *sk;
2756 int i;
2757 struct Curl_easy *data = conn->data;
2758 int numcerts;
2759 BIO *mem;
2760
2761 sk = SSL_get_peer_cert_chain(BACKEND->handle);
2762 if(!sk) {
2763 return CURLE_OUT_OF_MEMORY;
2764 }
2765
2766 numcerts = sk_X509_num(sk);
2767
2768 result = Curl_ssl_init_certinfo(data, numcerts);
2769 if(result) {
2770 return result;
2771 }
2772
2773 mem = BIO_new(BIO_s_mem());
2774
2775 for(i = 0; i < numcerts; i++) {
2776 ASN1_INTEGER *num;
2777 X509 *x = sk_X509_value(sk, i);
2778 EVP_PKEY *pubkey = NULL;
2779 int j;
2780 char *ptr;
2781 const ASN1_BIT_STRING *psig = NULL;
2782
2783 X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
2784 push_certinfo("Subject", i);
2785
2786 X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
2787 push_certinfo("Issuer", i);
2788
2789 BIO_printf(mem, "%lx", X509_get_version(x));
2790 push_certinfo("Version", i);
2791
2792 num = X509_get_serialNumber(x);
2793 if(num->type == V_ASN1_NEG_INTEGER)
2794 BIO_puts(mem, "-");
2795 for(j = 0; j < num->length; j++)
2796 BIO_printf(mem, "%02x", num->data[j]);
2797 push_certinfo("Serial Number", i);
2798
2799#if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
2800 {
2801 const X509_ALGOR *palg = NULL;
2802 ASN1_STRING *a = ASN1_STRING_new();
2803 if(a) {
2804 X509_get0_signature(&psig, &palg, x);
2805 X509_signature_print(mem, palg, a);
2806 ASN1_STRING_free(a);
2807
2808 if(palg) {
2809 i2a_ASN1_OBJECT(mem, palg->algorithm);
2810 push_certinfo("Public Key Algorithm", i);
2811 }
2812 }
2813 X509V3_ext(data, i, X509_get0_extensions(x));
2814 }
2815#else
2816 {
2817 /* before OpenSSL 1.0.2 */
2818 X509_CINF *cinf = x->cert_info;
2819
2820 i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
2821 push_certinfo("Signature Algorithm", i);
2822
2823 i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
2824 push_certinfo("Public Key Algorithm", i);
2825
2826 X509V3_ext(data, i, cinf->extensions);
2827
2828 psig = x->signature;
2829 }
2830#endif
2831
2832 ASN1_TIME_print(mem, X509_get0_notBefore(x));
2833 push_certinfo("Start date", i);
2834
2835 ASN1_TIME_print(mem, X509_get0_notAfter(x));
2836 push_certinfo("Expire date", i);
2837
2838 pubkey = X509_get_pubkey(x);
2839 if(!pubkey)
2840 infof(data, " Unable to load public key\n");
2841 else {
2842 int pktype;
2843#ifdef HAVE_OPAQUE_EVP_PKEY
2844 pktype = EVP_PKEY_id(pubkey);
2845#else
2846 pktype = pubkey->type;
2847#endif
2848 switch(pktype) {
2849 case EVP_PKEY_RSA:
2850 {
2851 RSA *rsa;
2852#ifdef HAVE_OPAQUE_EVP_PKEY
2853 rsa = EVP_PKEY_get0_RSA(pubkey);
2854#else
2855 rsa = pubkey->pkey.rsa;
2856#endif
2857
2858#ifdef HAVE_OPAQUE_RSA_DSA_DH
2859 {
2860 const BIGNUM *n;
2861 const BIGNUM *e;
2862
2863 RSA_get0_key(rsa, &n, &e, NULL);
2864 BN_print(mem, n);
2865 push_certinfo("RSA Public Key", i);
2866 print_pubkey_BN(rsa, n, i);
2867 print_pubkey_BN(rsa, e, i);
2868 }
2869#else
2870 BIO_printf(mem, "%d", BN_num_bits(rsa->n));
2871 push_certinfo("RSA Public Key", i);
2872 print_pubkey_BN(rsa, n, i);
2873 print_pubkey_BN(rsa, e, i);
2874#endif
2875
2876 break;
2877 }
2878 case EVP_PKEY_DSA:
2879 {
2880#ifndef OPENSSL_NO_DSA
2881 DSA *dsa;
2882#ifdef HAVE_OPAQUE_EVP_PKEY
2883 dsa = EVP_PKEY_get0_DSA(pubkey);
2884#else
2885 dsa = pubkey->pkey.dsa;
2886#endif
2887#ifdef HAVE_OPAQUE_RSA_DSA_DH
2888 {
2889 const BIGNUM *p;
2890 const BIGNUM *q;
2891 const BIGNUM *g;
2892 const BIGNUM *pub_key;
2893
2894 DSA_get0_pqg(dsa, &p, &q, &g);
2895 DSA_get0_key(dsa, &pub_key, NULL);
2896
2897 print_pubkey_BN(dsa, p, i);
2898 print_pubkey_BN(dsa, q, i);
2899 print_pubkey_BN(dsa, g, i);
2900 print_pubkey_BN(dsa, pub_key, i);
2901 }
2902#else
2903 print_pubkey_BN(dsa, p, i);
2904 print_pubkey_BN(dsa, q, i);
2905 print_pubkey_BN(dsa, g, i);
2906 print_pubkey_BN(dsa, pub_key, i);
2907#endif
2908#endif /* !OPENSSL_NO_DSA */
2909 break;
2910 }
2911 case EVP_PKEY_DH:
2912 {
2913 DH *dh;
2914#ifdef HAVE_OPAQUE_EVP_PKEY
2915 dh = EVP_PKEY_get0_DH(pubkey);
2916#else
2917 dh = pubkey->pkey.dh;
2918#endif
2919#ifdef HAVE_OPAQUE_RSA_DSA_DH
2920 {
2921 const BIGNUM *p;
2922 const BIGNUM *q;
2923 const BIGNUM *g;
2924 const BIGNUM *pub_key;
2925 DH_get0_pqg(dh, &p, &q, &g);
2926 DH_get0_key(dh, &pub_key, NULL);
2927 print_pubkey_BN(dh, p, i);
2928 print_pubkey_BN(dh, q, i);
2929 print_pubkey_BN(dh, g, i);
2930 print_pubkey_BN(dh, pub_key, i);
2931 }
2932#else
2933 print_pubkey_BN(dh, p, i);
2934 print_pubkey_BN(dh, g, i);
2935 print_pubkey_BN(dh, pub_key, i);
2936#endif
2937 break;
2938 }
2939#if 0
2940 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
2941 /* left TODO */
2942 break;
2943#endif
2944 }
2945 EVP_PKEY_free(pubkey);
2946 }
2947
2948 if(psig) {
2949 for(j = 0; j < psig->length; j++)
2950 BIO_printf(mem, "%02x:", psig->data[j]);
2951 push_certinfo("Signature", i);
2952 }
2953
2954 PEM_write_bio_X509(mem, x);
2955 push_certinfo("Cert", i);
2956 }
2957
2958 BIO_free(mem);
2959
2960 return CURLE_OK;
2961}
2962
2963/*
2964 * Heavily modified from:
2965 * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
2966 */
2967static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
2968 const char *pinnedpubkey)
2969{
2970 /* Scratch */
2971 int len1 = 0, len2 = 0;
2972 unsigned char *buff1 = NULL, *temp = NULL;
2973
2974 /* Result is returned to caller */
2975 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
2976
2977 /* if a path wasn't specified, don't pin */
2978 if(!pinnedpubkey)
2979 return CURLE_OK;
2980
2981 if(!cert)
2982 return result;
2983
2984 do {
2985 /* Begin Gyrations to get the subjectPublicKeyInfo */
2986 /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
2987
2988 /* https://groups.google.com/group/mailing.openssl.users/browse_thread
2989 /thread/d61858dae102c6c7 */
2990 len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
2991 if(len1 < 1)
2992 break; /* failed */
2993
2994 /* https://www.openssl.org/docs/crypto/buffer.html */
2995 buff1 = temp = malloc(len1);
2996 if(!buff1)
2997 break; /* failed */
2998
2999 /* https://www.openssl.org/docs/crypto/d2i_X509.html */
3000 len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
3001
3002 /*
3003 * These checks are verifying we got back the same values as when we
3004 * sized the buffer. It's pretty weak since they should always be the
3005 * same. But it gives us something to test.
3006 */
3007 if((len1 != len2) || !temp || ((temp - buff1) != len1))
3008 break; /* failed */
3009
3010 /* End Gyrations */
3011
3012 /* The one good exit point */
3013 result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
3014 } while(0);
3015
3016 /* https://www.openssl.org/docs/crypto/buffer.html */
3017 if(buff1)
3018 free(buff1);
3019
3020 return result;
3021}
3022
3023/*
3024 * Get the server cert, verify it and show it etc, only call failf() if the
3025 * 'strict' argument is TRUE as otherwise all this is for informational
3026 * purposes only!
3027 *
3028 * We check certificates to authenticate the server; otherwise we risk
3029 * man-in-the-middle attack.
3030 */
3031static CURLcode servercert(struct connectdata *conn,
3032 struct ssl_connect_data *connssl,
3033 bool strict)
3034{
3035 CURLcode result = CURLE_OK;
3036 int rc;
3037 long lerr, len;
3038 struct Curl_easy *data = conn->data;
3039 X509 *issuer;
3040 FILE *fp;
3041 char buffer[2048];
3042 const char *ptr;
3043 long * const certverifyresult = SSL_IS_PROXY() ?
3044 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
3045 BIO *mem = BIO_new(BIO_s_mem());
3046
3047 if(data->set.ssl.certinfo)
3048 /* we've been asked to gather certificate info! */
3049 (void)get_cert_chain(conn, connssl);
3050
3051 BACKEND->server_cert = SSL_get_peer_certificate(BACKEND->handle);
3052 if(!BACKEND->server_cert) {
3053 BIO_free(mem);
3054 if(!strict)
3055 return CURLE_OK;
3056
3057 failf(data, "SSL: couldn't get peer certificate!");
3058 return CURLE_PEER_FAILED_VERIFICATION;
3059 }
3060
3061 infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
3062
3063 rc = x509_name_oneline(X509_get_subject_name(BACKEND->server_cert),
3064 buffer, sizeof(buffer));
3065 infof(data, " subject: %s\n", rc?"[NONE]":buffer);
3066
3067 ASN1_TIME_print(mem, X509_get0_notBefore(BACKEND->server_cert));
3068 len = BIO_get_mem_data(mem, (char **) &ptr);
3069 infof(data, " start date: %.*s\n", len, ptr);
3070 (void)BIO_reset(mem);
3071
3072 ASN1_TIME_print(mem, X509_get0_notAfter(BACKEND->server_cert));
3073 len = BIO_get_mem_data(mem, (char **) &ptr);
3074 infof(data, " expire date: %.*s\n", len, ptr);
3075 (void)BIO_reset(mem);
3076
3077 BIO_free(mem);
3078
3079 if(SSL_CONN_CONFIG(verifyhost)) {
3080 result = verifyhost(conn, BACKEND->server_cert);
3081 if(result) {
3082 X509_free(BACKEND->server_cert);
3083 BACKEND->server_cert = NULL;
3084 return result;
3085 }
3086 }
3087
3088 rc = x509_name_oneline(X509_get_issuer_name(BACKEND->server_cert),
3089 buffer, sizeof(buffer));
3090 if(rc) {
3091 if(strict)
3092 failf(data, "SSL: couldn't get X509-issuer name!");
3093 result = CURLE_SSL_CONNECT_ERROR;
3094 }
3095 else {
3096 infof(data, " issuer: %s\n", buffer);
3097
3098 /* We could do all sorts of certificate verification stuff here before
3099 deallocating the certificate. */
3100
3101 /* e.g. match issuer name with provided issuer certificate */
3102 if(SSL_SET_OPTION(issuercert)) {
3103 fp = fopen(SSL_SET_OPTION(issuercert), FOPEN_READTEXT);
3104 if(!fp) {
3105 if(strict)
3106 failf(data, "SSL: Unable to open issuer cert (%s)",
3107 SSL_SET_OPTION(issuercert));
3108 X509_free(BACKEND->server_cert);
3109 BACKEND->server_cert = NULL;
3110 return CURLE_SSL_ISSUER_ERROR;
3111 }
3112
3113 issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL);
3114 if(!issuer) {
3115 if(strict)
3116 failf(data, "SSL: Unable to read issuer cert (%s)",
3117 SSL_SET_OPTION(issuercert));
3118 X509_free(BACKEND->server_cert);
3119 X509_free(issuer);
3120 fclose(fp);
3121 return CURLE_SSL_ISSUER_ERROR;
3122 }
3123
3124 fclose(fp);
3125
3126 if(X509_check_issued(issuer, BACKEND->server_cert) != X509_V_OK) {
3127 if(strict)
3128 failf(data, "SSL: Certificate issuer check failed (%s)",
3129 SSL_SET_OPTION(issuercert));
3130 X509_free(BACKEND->server_cert);
3131 X509_free(issuer);
3132 BACKEND->server_cert = NULL;
3133 return CURLE_SSL_ISSUER_ERROR;
3134 }
3135
3136 infof(data, " SSL certificate issuer check ok (%s)\n",
3137 SSL_SET_OPTION(issuercert));
3138 X509_free(issuer);
3139 }
3140
3141 lerr = *certverifyresult = SSL_get_verify_result(BACKEND->handle);
3142
3143 if(*certverifyresult != X509_V_OK) {
3144 if(SSL_CONN_CONFIG(verifypeer)) {
3145 /* We probably never reach this, because SSL_connect() will fail
3146 and we return earlier if verifypeer is set? */
3147 if(strict)
3148 failf(data, "SSL certificate verify result: %s (%ld)",
3149 X509_verify_cert_error_string(lerr), lerr);
3150 result = CURLE_PEER_FAILED_VERIFICATION;
3151 }
3152 else
3153 infof(data, " SSL certificate verify result: %s (%ld),"
3154 " continuing anyway.\n",
3155 X509_verify_cert_error_string(lerr), lerr);
3156 }
3157 else
3158 infof(data, " SSL certificate verify ok.\n");
3159 }
3160
3161#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3162 !defined(OPENSSL_NO_OCSP)
3163 if(SSL_CONN_CONFIG(verifystatus)) {
3164 result = verifystatus(conn, connssl);
3165 if(result) {
3166 X509_free(BACKEND->server_cert);
3167 BACKEND->server_cert = NULL;
3168 return result;
3169 }
3170 }
3171#endif
3172
3173 if(!strict)
3174 /* when not strict, we don't bother about the verify cert problems */
3175 result = CURLE_OK;
3176
3177 ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
3178 data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
3179 if(!result && ptr) {
3180 result = pkp_pin_peer_pubkey(data, BACKEND->server_cert, ptr);
3181 if(result)
3182 failf(data, "SSL: public key does not match pinned public key!");
3183 }
3184
3185 X509_free(BACKEND->server_cert);
3186 BACKEND->server_cert = NULL;
3187 connssl->connecting_state = ssl_connect_done;
3188
3189 return result;
3190}
3191
3192static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
3193{
3194 CURLcode result = CURLE_OK;
3195 struct Curl_easy *data = conn->data;
3196 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3197
3198 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
3199
3200 if(SSL_SET_OPTION(primary.sessionid)) {
3201 bool incache;
3202 SSL_SESSION *our_ssl_sessionid;
3203 void *old_ssl_sessionid = NULL;
3204
3205 our_ssl_sessionid = SSL_get1_session(BACKEND->handle);
3206
3207 /* SSL_get1_session() will increment the reference count and the session
3208 will stay in memory until explicitly freed with SSL_SESSION_free(3),
3209 regardless of its state. */
3210
3211 Curl_ssl_sessionid_lock(conn);
3212 incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
3213 sockindex));
3214 if(incache) {
3215 if(old_ssl_sessionid != our_ssl_sessionid) {
3216 infof(data, "old SSL session ID is stale, removing\n");
3217 Curl_ssl_delsessionid(conn, old_ssl_sessionid);
3218 incache = FALSE;
3219 }
3220 }
3221
3222 if(!incache) {
3223 result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
3224 0 /* unknown size */, sockindex);
3225 if(result) {
3226 Curl_ssl_sessionid_unlock(conn);
3227 failf(data, "failed to store ssl session");
3228 return result;
3229 }
3230 }
3231 else {
3232 /* Session was incache, so refcount already incremented earlier.
3233 * Avoid further increments with each SSL_get1_session() call.
3234 * This does not free the session as refcount remains > 0
3235 */
3236 SSL_SESSION_free(our_ssl_sessionid);
3237 }
3238 Curl_ssl_sessionid_unlock(conn);
3239 }
3240
3241 /*
3242 * We check certificates to authenticate the server; otherwise we risk
3243 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
3244 * verify the peer ignore faults and failures from the server cert
3245 * operations.
3246 */
3247
3248 result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
3249 SSL_CONN_CONFIG(verifyhost)));
3250
3251 if(!result)
3252 connssl->connecting_state = ssl_connect_done;
3253
3254 return result;
3255}
3256
3257static Curl_recv ossl_recv;
3258static Curl_send ossl_send;
3259
3260static CURLcode ossl_connect_common(struct connectdata *conn,
3261 int sockindex,
3262 bool nonblocking,
3263 bool *done)
3264{
3265 CURLcode result;
3266 struct Curl_easy *data = conn->data;
3267 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3268 curl_socket_t sockfd = conn->sock[sockindex];
3269 time_t timeout_ms;
3270 int what;
3271
3272 /* check if the connection has already been established */
3273 if(ssl_connection_complete == connssl->state) {
3274 *done = TRUE;
3275 return CURLE_OK;
3276 }
3277
3278 if(ssl_connect_1 == connssl->connecting_state) {
3279 /* Find out how much more time we're allowed */
3280 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3281
3282 if(timeout_ms < 0) {
3283 /* no need to continue if time already is up */
3284 failf(data, "SSL connection timeout");
3285 return CURLE_OPERATION_TIMEDOUT;
3286 }
3287
3288 result = ossl_connect_step1(conn, sockindex);
3289 if(result)
3290 return result;
3291 }
3292
3293 while(ssl_connect_2 == connssl->connecting_state ||
3294 ssl_connect_2_reading == connssl->connecting_state ||
3295 ssl_connect_2_writing == connssl->connecting_state) {
3296
3297 /* check allowed time left */
3298 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3299
3300 if(timeout_ms < 0) {
3301 /* no need to continue if time already is up */
3302 failf(data, "SSL connection timeout");
3303 return CURLE_OPERATION_TIMEDOUT;
3304 }
3305
3306 /* if ssl is expecting something, check if it's available. */
3307 if(connssl->connecting_state == ssl_connect_2_reading ||
3308 connssl->connecting_state == ssl_connect_2_writing) {
3309
3310 curl_socket_t writefd = ssl_connect_2_writing ==
3311 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3312 curl_socket_t readfd = ssl_connect_2_reading ==
3313 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3314
3315 what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
3316 nonblocking?0:timeout_ms);
3317 if(what < 0) {
3318 /* fatal error */
3319 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
3320 return CURLE_SSL_CONNECT_ERROR;
3321 }
3322 if(0 == what) {
3323 if(nonblocking) {
3324 *done = FALSE;
3325 return CURLE_OK;
3326 }
3327 /* timeout */
3328 failf(data, "SSL connection timeout");
3329 return CURLE_OPERATION_TIMEDOUT;
3330 }
3331 /* socket is readable or writable */
3332 }
3333
3334 /* Run transaction, and return to the caller if it failed or if this
3335 * connection is done nonblocking and this loop would execute again. This
3336 * permits the owner of a multi handle to abort a connection attempt
3337 * before step2 has completed while ensuring that a client using select()
3338 * or epoll() will always have a valid fdset to wait on.
3339 */
3340 result = ossl_connect_step2(conn, sockindex);
3341 if(result || (nonblocking &&
3342 (ssl_connect_2 == connssl->connecting_state ||
3343 ssl_connect_2_reading == connssl->connecting_state ||
3344 ssl_connect_2_writing == connssl->connecting_state)))
3345 return result;
3346
3347 } /* repeat step2 until all transactions are done. */
3348
3349 if(ssl_connect_3 == connssl->connecting_state) {
3350 result = ossl_connect_step3(conn, sockindex);
3351 if(result)
3352 return result;
3353 }
3354
3355 if(ssl_connect_done == connssl->connecting_state) {
3356 connssl->state = ssl_connection_complete;
3357 conn->recv[sockindex] = ossl_recv;
3358 conn->send[sockindex] = ossl_send;
3359 *done = TRUE;
3360 }
3361 else
3362 *done = FALSE;
3363
3364 /* Reset our connect state machine */
3365 connssl->connecting_state = ssl_connect_1;
3366
3367 return CURLE_OK;
3368}
3369
3370static CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
3371 int sockindex,
3372 bool *done)
3373{
3374 return ossl_connect_common(conn, sockindex, TRUE, done);
3375}
3376
3377static CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
3378{
3379 CURLcode result;
3380 bool done = FALSE;
3381
3382 result = ossl_connect_common(conn, sockindex, FALSE, &done);
3383 if(result)
3384 return result;
3385
3386 DEBUGASSERT(done);
3387
3388 return CURLE_OK;
3389}
3390
3391static bool Curl_ossl_data_pending(const struct connectdata *conn,
3392 int connindex)
3393{
3394 const struct ssl_connect_data *connssl = &conn->ssl[connindex];
3395 const struct ssl_connect_data *proxyssl = &conn->proxy_ssl[connindex];
3396 if(BACKEND->handle)
3397 /* SSL is in use */
3398 return (0 != SSL_pending(BACKEND->handle) ||
3399 (proxyssl->backend->handle &&
3400 0 != SSL_pending(proxyssl->backend->handle))) ?
3401 TRUE : FALSE;
3402 return FALSE;
3403}
3404
3405static size_t Curl_ossl_version(char *buffer, size_t size);
3406
3407static ssize_t ossl_send(struct connectdata *conn,
3408 int sockindex,
3409 const void *mem,
3410 size_t len,
3411 CURLcode *curlcode)
3412{
3413 /* SSL_write() is said to return 'int' while write() and send() returns
3414 'size_t' */
3415 int err;
3416 char error_buffer[256];
3417 unsigned long sslerror;
3418 int memlen;
3419 int rc;
3420 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3421
3422 ERR_clear_error();
3423
3424 memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
3425 rc = SSL_write(BACKEND->handle, mem, memlen);
3426
3427 if(rc <= 0) {
3428 err = SSL_get_error(BACKEND->handle, rc);
3429
3430 switch(err) {
3431 case SSL_ERROR_WANT_READ:
3432 case SSL_ERROR_WANT_WRITE:
3433 /* The operation did not complete; the same TLS/SSL I/O function
3434 should be called again later. This is basically an EWOULDBLOCK
3435 equivalent. */
3436 *curlcode = CURLE_AGAIN;
3437 return -1;
3438 case SSL_ERROR_SYSCALL:
3439 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
3440 SOCKERRNO);
3441 *curlcode = CURLE_SEND_ERROR;
3442 return -1;
3443 case SSL_ERROR_SSL:
3444 /* A failure in the SSL library occurred, usually a protocol error.
3445 The OpenSSL error queue contains more information on the error. */
3446 sslerror = ERR_get_error();
3447 if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
3448 ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
3449 conn->ssl[sockindex].state == ssl_connection_complete &&
3450 conn->proxy_ssl[sockindex].state == ssl_connection_complete) {
3451 char ver[120];
3452 Curl_ossl_version(ver, 120);
3453 failf(conn->data, "Error: %s does not support double SSL tunneling.",
3454 ver);
3455 }
3456 else
3457 failf(conn->data, "SSL_write() error: %s",
3458 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
3459 *curlcode = CURLE_SEND_ERROR;
3460 return -1;
3461 }
3462 /* a true error */
3463 failf(conn->data, OSSL_PACKAGE " SSL_write: %s, errno %d",
3464 SSL_ERROR_to_str(err), SOCKERRNO);
3465 *curlcode = CURLE_SEND_ERROR;
3466 return -1;
3467 }
3468 *curlcode = CURLE_OK;
3469 return (ssize_t)rc; /* number of bytes */
3470}
3471
3472static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
3473 int num, /* socketindex */
3474 char *buf, /* store read data here */
3475 size_t buffersize, /* max amount to read */
3476 CURLcode *curlcode)
3477{
3478 char error_buffer[256];
3479 unsigned long sslerror;
3480 ssize_t nread;
3481 int buffsize;
3482 struct ssl_connect_data *connssl = &conn->ssl[num];
3483
3484 ERR_clear_error();
3485
3486 buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
3487 nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
3488 if(nread <= 0) {
3489 /* failed SSL_read */
3490 int err = SSL_get_error(BACKEND->handle, (int)nread);
3491
3492 switch(err) {
3493 case SSL_ERROR_NONE: /* this is not an error */
3494 case SSL_ERROR_ZERO_RETURN: /* no more data */
3495 break;
3496 case SSL_ERROR_WANT_READ:
3497 case SSL_ERROR_WANT_WRITE:
3498 /* there's data pending, re-invoke SSL_read() */
3499 *curlcode = CURLE_AGAIN;
3500 return -1;
3501 default:
3502 /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
3503 value/errno" */
3504 /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
3505 sslerror = ERR_get_error();
3506 if((nread < 0) || sslerror) {
3507 /* If the return code was negative or there actually is an error in the
3508 queue */
3509 failf(conn->data, OSSL_PACKAGE " SSL_read: %s, errno %d",
3510 (sslerror ?
3511 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)) :
3512 SSL_ERROR_to_str(err)),
3513 SOCKERRNO);
3514 *curlcode = CURLE_RECV_ERROR;
3515 return -1;
3516 }
3517 }
3518 }
3519 return nread;
3520}
3521
3522static size_t Curl_ossl_version(char *buffer, size_t size)
3523{
3524#ifdef OPENSSL_IS_BORINGSSL
3525 return snprintf(buffer, size, OSSL_PACKAGE);
3526#else /* OPENSSL_IS_BORINGSSL */
3527 char sub[3];
3528 unsigned long ssleay_value;
3529 sub[2]='\0';
3530 sub[1]='\0';
3531 ssleay_value = OpenSSL_version_num();
3532 if(ssleay_value < 0x906000) {
3533 ssleay_value = SSLEAY_VERSION_NUMBER;
3534 sub[0]='\0';
3535 }
3536 else {
3537 if(ssleay_value&0xff0) {
3538 int minor_ver = (ssleay_value >> 4) & 0xff;
3539 if(minor_ver > 26) {
3540 /* handle extended version introduced for 0.9.8za */
3541 sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
3542 sub[0] = 'z';
3543 }
3544 else {
3545 sub[0] = (char) (minor_ver + 'a' - 1);
3546 }
3547 }
3548 else
3549 sub[0]='\0';
3550 }
3551
3552 return snprintf(buffer, size, "%s/%lx.%lx.%lx%s",
3553 OSSL_PACKAGE,
3554 (ssleay_value>>28)&0xf,
3555 (ssleay_value>>20)&0xff,
3556 (ssleay_value>>12)&0xff,
3557 sub);
3558#endif /* OPENSSL_IS_BORINGSSL */
3559}
3560
3561/* can be called with data == NULL */
3562static CURLcode Curl_ossl_random(struct Curl_easy *data,
3563 unsigned char *entropy, size_t length)
3564{
3565 int rc;
3566 if(data) {
3567 if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */
3568 return CURLE_FAILED_INIT; /* couldn't seed for some reason */
3569 }
3570 else {
3571 if(!rand_enough())
3572 return CURLE_FAILED_INIT;
3573 }
3574 /* RAND_bytes() returns 1 on success, 0 otherwise. */
3575 rc = RAND_bytes(entropy, curlx_uztosi(length));
3576 return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
3577}
3578
3579static CURLcode Curl_ossl_md5sum(unsigned char *tmp, /* input */
3580 size_t tmplen,
3581 unsigned char *md5sum /* output */,
3582 size_t unused)
3583{
3584 MD5_CTX MD5pw;
3585 (void)unused;
3586 MD5_Init(&MD5pw);
3587 MD5_Update(&MD5pw, tmp, tmplen);
3588 MD5_Final(md5sum, &MD5pw);
3589 return CURLE_OK;
3590}
3591
3592#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3593static void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
3594 size_t tmplen,
3595 unsigned char *sha256sum /* output */,
3596 size_t unused)
3597{
3598 SHA256_CTX SHA256pw;
3599 (void)unused;
3600 SHA256_Init(&SHA256pw);
3601 SHA256_Update(&SHA256pw, tmp, tmplen);
3602 SHA256_Final(sha256sum, &SHA256pw);
3603}
3604#endif
3605
3606static bool Curl_ossl_cert_status_request(void)
3607{
3608#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3609 !defined(OPENSSL_NO_OCSP)
3610 return TRUE;
3611#else
3612 return FALSE;
3613#endif
3614}
3615
3616static void *Curl_ossl_get_internals(struct ssl_connect_data *connssl,
3617 CURLINFO info)
3618{
3619 /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
3620 return info == CURLINFO_TLS_SESSION ?
3621 (void *)BACKEND->ctx : (void *)BACKEND->handle;
3622}
3623
3624const struct Curl_ssl Curl_ssl_openssl = {
3625 { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
3626
3627 1, /* have_ca_path */
3628 1, /* have_certinfo */
3629 1, /* have_pinnedpubkey */
3630 1, /* have_ssl_ctx */
3631 1, /* support_https_proxy */
3632
3633 sizeof(struct ssl_backend_data),
3634
3635 Curl_ossl_init, /* init */
3636 Curl_ossl_cleanup, /* cleanup */
3637 Curl_ossl_version, /* version */
3638 Curl_ossl_check_cxn, /* check_cxn */
3639 Curl_ossl_shutdown, /* shutdown */
3640 Curl_ossl_data_pending, /* data_pending */
3641 Curl_ossl_random, /* random */
3642 Curl_ossl_cert_status_request, /* cert_status_request */
3643 Curl_ossl_connect, /* connect */
3644 Curl_ossl_connect_nonblocking, /* connect_nonblocking */
3645 Curl_ossl_get_internals, /* get_internals */
3646 Curl_ossl_close, /* close_one */
3647 Curl_ossl_close_all, /* close_all */
3648 Curl_ossl_session_free, /* session_free */
3649 Curl_ossl_set_engine, /* set_engine */
3650 Curl_ossl_set_engine_default, /* set_engine_default */
3651 Curl_ossl_engines_list, /* engines_list */
3652 Curl_none_false_start, /* false_start */
3653 Curl_ossl_md5sum, /* md5sum */
3654#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3655 Curl_ossl_sha256sum /* sha256sum */
3656#else
3657 NULL /* sha256sum */
3658#endif
3659};
3660
3661#endif /* USE_OPENSSL */
Note: See TracBrowser for help on using the repository browser.