source: UsbWattMeter/trunk/curl-7.47.1/lib/vtls/openssl.c@ 164

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

TOPPERS/ECNLサンプルアプリ「USB充電器電力計」を追加

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