libcurl: updated to 7.49.1
[tomato.git] / release / src / router / libcurl / lib / vtls / openssl.c
blob3a4bde5b34c5254812f5024d756f318d2f52843e
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
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.
29 * The original SSLeay-using code for curl was written by Linas Vepstas and
30 * Sampo Kellomaki 1998.
33 #include "curl_setup.h"
35 #ifdef USE_OPENSSL
37 #ifdef HAVE_LIMITS_H
38 #include <limits.h>
39 #endif
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"
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>
67 #ifdef HAVE_OPENSSL_PKCS12_H
68 #include <openssl/pkcs12.h>
69 #endif
71 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
72 #include <openssl/ocsp.h>
73 #endif
75 #include "warnless.h"
76 #include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
78 /* The last #include files should be: */
79 #include "curl_memory.h"
80 #include "memdebug.h"
82 #ifndef OPENSSL_VERSION_NUMBER
83 #error "OPENSSL_VERSION_NUMBER not defined"
84 #endif
86 #if defined(HAVE_OPENSSL_ENGINE_H)
87 #include <openssl/ui.h>
88 #endif
90 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
91 #define SSL_METHOD_QUAL const
92 #else
93 #define SSL_METHOD_QUAL
94 #endif
96 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
97 #define HAVE_ERR_REMOVE_THREAD_STATE 1
98 #if (OPENSSL_VERSION_NUMBER >= 0x10100004L) && \
99 !defined(LIBRESSL_VERSION_NUMBER)
100 /* OpenSSL 1.1.0 deprecates the function */
101 #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
102 #endif
103 #endif
105 #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
106 OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */
107 #undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
108 #define OPENSSL_NO_SSL2
109 #endif
111 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
112 !defined(LIBRESSL_VERSION_NUMBER)
113 #define SSLeay_add_ssl_algorithms() SSL_library_init()
114 #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
115 #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
116 #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
117 #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
118 #endif
120 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
121 !defined(LIBRESSL_VERSION_NUMBER)
122 #define HAVE_X509_GET0_SIGNATURE 1
123 #endif
125 #if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
126 /* not present in older OpenSSL */
127 #define OPENSSL_load_builtin_modules(x)
128 #endif
130 #if defined(LIBRESSL_VERSION_NUMBER)
131 #define OSSL_PACKAGE "LibreSSL"
132 #elif defined(OPENSSL_IS_BORINGSSL)
133 #define OSSL_PACKAGE "BoringSSL"
134 #else
135 #define OSSL_PACKAGE "OpenSSL"
136 #endif
139 * Number of bytes to read from the random number seed file. This must be
140 * a finite value (because some entropy "files" like /dev/urandom have
141 * an infinite length), but must be large enough to provide enough
142 * entopy to properly seed OpenSSL's PRNG.
144 #define RAND_LOAD_LENGTH 1024
146 static int passwd_callback(char *buf, int num, int encrypting,
147 void *global_passwd)
149 DEBUGASSERT(0 == encrypting);
151 if(!encrypting) {
152 int klen = curlx_uztosi(strlen((char *)global_passwd));
153 if(num > klen) {
154 memcpy(buf, global_passwd, klen+1);
155 return klen;
158 return 0;
162 * rand_enough() is a function that returns TRUE if we have seeded the random
163 * engine properly. We use some preprocessor magic to provide a seed_enough()
164 * macro to use, just to prevent a compiler warning on this function if we
165 * pass in an argument that is never used.
168 #ifdef HAVE_RAND_STATUS
169 #define seed_enough(x) rand_enough()
170 static bool rand_enough(void)
172 return (0 != RAND_status()) ? TRUE : FALSE;
174 #else
175 #define seed_enough(x) rand_enough(x)
176 static bool rand_enough(int nread)
178 /* this is a very silly decision to make */
179 return (nread > 500) ? TRUE : FALSE;
181 #endif
183 static int ossl_seed(struct SessionHandle *data)
185 char *buf = data->state.buffer; /* point to the big buffer */
186 int nread=0;
188 /* Q: should we add support for a random file name as a libcurl option?
189 A: Yes, it is here */
191 #ifndef RANDOM_FILE
192 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
193 us to! */
194 if(data->set.ssl.random_file)
195 #define RANDOM_FILE "" /* doesn't matter won't be used */
196 #endif
198 /* let the option override the define */
199 nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
200 data->set.str[STRING_SSL_RANDOM_FILE]:
201 RANDOM_FILE),
202 RAND_LOAD_LENGTH);
203 if(seed_enough(nread))
204 return nread;
207 #if defined(HAVE_RAND_EGD)
208 /* only available in OpenSSL 0.9.5 and later */
209 /* EGD_SOCKET is set at configure time or not at all */
210 #ifndef EGD_SOCKET
211 /* If we don't have the define set, we only do this if the egd-option
212 is set */
213 if(data->set.str[STRING_SSL_EGDSOCKET])
214 #define EGD_SOCKET "" /* doesn't matter won't be used */
215 #endif
217 /* If there's an option and a define, the option overrides the
218 define */
219 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
220 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
221 if(-1 != ret) {
222 nread += ret;
223 if(seed_enough(nread))
224 return nread;
227 #endif
229 /* If we get here, it means we need to seed the PRNG using a "silly"
230 approach! */
231 do {
232 unsigned char randb[64];
233 int len = sizeof(randb);
234 RAND_bytes(randb, len);
235 RAND_add(randb, len, (len >> 1));
236 } while(!RAND_status());
238 /* generates a default path for the random seed file */
239 buf[0]=0; /* blank it first */
240 RAND_file_name(buf, BUFSIZE);
241 if(buf[0]) {
242 /* we got a file name to try */
243 nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
244 if(seed_enough(nread))
245 return nread;
248 infof(data, "libcurl is now using a weak random seed!\n");
249 return nread;
252 static void Curl_ossl_seed(struct SessionHandle *data)
254 /* we have the "SSL is seeded" boolean static to prevent multiple
255 time-consuming seedings in vain */
256 static bool ssl_seeded = FALSE;
258 if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
259 data->set.str[STRING_SSL_EGDSOCKET]) {
260 ossl_seed(data);
261 ssl_seeded = TRUE;
265 #ifndef SSL_FILETYPE_ENGINE
266 #define SSL_FILETYPE_ENGINE 42
267 #endif
268 #ifndef SSL_FILETYPE_PKCS12
269 #define SSL_FILETYPE_PKCS12 43
270 #endif
271 static int do_file_type(const char *type)
273 if(!type || !type[0])
274 return SSL_FILETYPE_PEM;
275 if(Curl_raw_equal(type, "PEM"))
276 return SSL_FILETYPE_PEM;
277 if(Curl_raw_equal(type, "DER"))
278 return SSL_FILETYPE_ASN1;
279 if(Curl_raw_equal(type, "ENG"))
280 return SSL_FILETYPE_ENGINE;
281 if(Curl_raw_equal(type, "P12"))
282 return SSL_FILETYPE_PKCS12;
283 return -1;
286 #if defined(HAVE_OPENSSL_ENGINE_H)
288 * Supply default password to the engine user interface conversation.
289 * The password is passed by OpenSSL engine from ENGINE_load_private_key()
290 * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
292 static int ssl_ui_reader(UI *ui, UI_STRING *uis)
294 const char *password;
295 switch(UI_get_string_type(uis)) {
296 case UIT_PROMPT:
297 case UIT_VERIFY:
298 password = (const char*)UI_get0_user_data(ui);
299 if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
300 UI_set_result(ui, uis, password);
301 return 1;
303 default:
304 break;
306 return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
310 * Suppress interactive request for a default password if available.
312 static int ssl_ui_writer(UI *ui, UI_STRING *uis)
314 switch(UI_get_string_type(uis)) {
315 case UIT_PROMPT:
316 case UIT_VERIFY:
317 if(UI_get0_user_data(ui) &&
318 (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
319 return 1;
321 default:
322 break;
324 return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
326 #endif
328 static
329 int cert_stuff(struct connectdata *conn,
330 SSL_CTX* ctx,
331 char *cert_file,
332 const char *cert_type,
333 char *key_file,
334 const char *key_type)
336 struct SessionHandle *data = conn->data;
338 int file_type = do_file_type(cert_type);
340 if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
341 SSL *ssl;
342 X509 *x509;
343 int cert_done = 0;
345 if(data->set.str[STRING_KEY_PASSWD]) {
346 /* set the password in the callback userdata */
347 SSL_CTX_set_default_passwd_cb_userdata(ctx,
348 data->set.str[STRING_KEY_PASSWD]);
349 /* Set passwd callback: */
350 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
354 switch(file_type) {
355 case SSL_FILETYPE_PEM:
356 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
357 if(SSL_CTX_use_certificate_chain_file(ctx,
358 cert_file) != 1) {
359 failf(data,
360 "could not load PEM client certificate, " OSSL_PACKAGE
361 " error %s, "
362 "(no key found, wrong pass phrase, or wrong file format?)",
363 ERR_error_string(ERR_get_error(), NULL) );
364 return 0;
366 break;
368 case SSL_FILETYPE_ASN1:
369 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
370 we use the case above for PEM so this can only be performed with
371 ASN1 files. */
372 if(SSL_CTX_use_certificate_file(ctx,
373 cert_file,
374 file_type) != 1) {
375 failf(data,
376 "could not load ASN1 client certificate, " OSSL_PACKAGE
377 " error %s, "
378 "(no key found, wrong pass phrase, or wrong file format?)",
379 ERR_error_string(ERR_get_error(), NULL) );
380 return 0;
382 break;
383 case SSL_FILETYPE_ENGINE:
384 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
386 if(data->state.engine) {
387 const char *cmd_name = "LOAD_CERT_CTRL";
388 struct {
389 const char *cert_id;
390 X509 *cert;
391 } params;
393 params.cert_id = cert_file;
394 params.cert = NULL;
396 /* Does the engine supports LOAD_CERT_CTRL ? */
397 if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
398 0, (void *)cmd_name, NULL)) {
399 failf(data, "ssl engine does not support loading certificates");
400 return 0;
403 /* Load the certificate from the engine */
404 if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
405 0, &params, NULL, 1)) {
406 failf(data, "ssl engine cannot load client cert with id"
407 " '%s' [%s]", cert_file,
408 ERR_error_string(ERR_get_error(), NULL));
409 return 0;
412 if(!params.cert) {
413 failf(data, "ssl engine didn't initialized the certificate "
414 "properly.");
415 return 0;
418 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
419 failf(data, "unable to set client certificate");
420 X509_free(params.cert);
421 return 0;
423 X509_free(params.cert); /* we don't need the handle any more... */
425 else {
426 failf(data, "crypto engine not set, can't load certificate");
427 return 0;
430 break;
431 #else
432 failf(data, "file type ENG for certificate not implemented");
433 return 0;
434 #endif
436 case SSL_FILETYPE_PKCS12:
438 #ifdef HAVE_OPENSSL_PKCS12_H
439 FILE *f;
440 PKCS12 *p12;
441 EVP_PKEY *pri;
442 STACK_OF(X509) *ca = NULL;
444 f = fopen(cert_file, "rb");
445 if(!f) {
446 failf(data, "could not open PKCS12 file '%s'", cert_file);
447 return 0;
449 p12 = d2i_PKCS12_fp(f, NULL);
450 fclose(f);
452 if(!p12) {
453 failf(data, "error reading PKCS12 file '%s'", cert_file);
454 return 0;
457 PKCS12_PBE_add();
459 if(!PKCS12_parse(p12, data->set.str[STRING_KEY_PASSWD], &pri, &x509,
460 &ca)) {
461 failf(data,
462 "could not parse PKCS12 file, check password, " OSSL_PACKAGE
463 " error %s",
464 ERR_error_string(ERR_get_error(), NULL) );
465 PKCS12_free(p12);
466 return 0;
469 PKCS12_free(p12);
471 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
472 failf(data,
473 "could not load PKCS12 client certificate, " OSSL_PACKAGE
474 " error %s",
475 ERR_error_string(ERR_get_error(), NULL) );
476 goto fail;
479 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
480 failf(data, "unable to use private key from PKCS12 file '%s'",
481 cert_file);
482 goto fail;
485 if(!SSL_CTX_check_private_key (ctx)) {
486 failf(data, "private key from PKCS12 file '%s' "
487 "does not match certificate in same file", cert_file);
488 goto fail;
490 /* Set Certificate Verification chain */
491 if(ca) {
492 while(sk_X509_num(ca)) {
494 * Note that sk_X509_pop() is used below to make sure the cert is
495 * removed from the stack properly before getting passed to
496 * SSL_CTX_add_extra_chain_cert(). Previously we used
497 * sk_X509_value() instead, but then we'd clean it in the subsequent
498 * sk_X509_pop_free() call.
500 X509 *x = sk_X509_pop(ca);
501 if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
502 X509_free(x);
503 failf(data, "cannot add certificate to certificate chain");
504 goto fail;
506 /* SSL_CTX_add_client_CA() seems to work with either sk_* function,
507 * presumably because it duplicates what we pass to it.
509 if(!SSL_CTX_add_client_CA(ctx, x)) {
510 failf(data, "cannot add certificate to client CA list");
511 goto fail;
516 cert_done = 1;
517 fail:
518 EVP_PKEY_free(pri);
519 X509_free(x509);
520 sk_X509_pop_free(ca, X509_free);
522 if(!cert_done)
523 return 0; /* failure! */
524 break;
525 #else
526 failf(data, "file type P12 for certificate not supported");
527 return 0;
528 #endif
530 default:
531 failf(data, "not supported file type '%s' for certificate", cert_type);
532 return 0;
535 file_type = do_file_type(key_type);
537 switch(file_type) {
538 case SSL_FILETYPE_PEM:
539 if(cert_done)
540 break;
541 if(!key_file)
542 /* cert & key can only be in PEM case in the same file */
543 key_file=cert_file;
544 case SSL_FILETYPE_ASN1:
545 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
546 failf(data, "unable to set private key file: '%s' type %s",
547 key_file, key_type?key_type:"PEM");
548 return 0;
550 break;
551 case SSL_FILETYPE_ENGINE:
552 #ifdef HAVE_OPENSSL_ENGINE_H
553 { /* XXXX still needs some work */
554 EVP_PKEY *priv_key = NULL;
555 if(data->state.engine) {
556 UI_METHOD *ui_method =
557 UI_create_method((char *)"cURL user interface");
558 if(!ui_method) {
559 failf(data, "unable do create " OSSL_PACKAGE
560 " user-interface method");
561 return 0;
563 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
564 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
565 UI_method_set_reader(ui_method, ssl_ui_reader);
566 UI_method_set_writer(ui_method, ssl_ui_writer);
567 /* the typecast below was added to please mingw32 */
568 priv_key = (EVP_PKEY *)
569 ENGINE_load_private_key(data->state.engine, key_file,
570 ui_method,
571 data->set.str[STRING_KEY_PASSWD]);
572 UI_destroy_method(ui_method);
573 if(!priv_key) {
574 failf(data, "failed to load private key from crypto engine");
575 return 0;
577 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
578 failf(data, "unable to set private key");
579 EVP_PKEY_free(priv_key);
580 return 0;
582 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
584 else {
585 failf(data, "crypto engine not set, can't load private key");
586 return 0;
589 break;
590 #else
591 failf(data, "file type ENG for private key not supported");
592 return 0;
593 #endif
594 case SSL_FILETYPE_PKCS12:
595 if(!cert_done) {
596 failf(data, "file type P12 for private key not supported");
597 return 0;
599 break;
600 default:
601 failf(data, "not supported file type for private key");
602 return 0;
605 ssl=SSL_new(ctx);
606 if(!ssl) {
607 failf(data, "unable to create an SSL structure");
608 return 0;
611 x509=SSL_get_certificate(ssl);
613 /* This version was provided by Evan Jordan and is supposed to not
614 leak memory as the previous version: */
615 if(x509) {
616 EVP_PKEY *pktmp = X509_get_pubkey(x509);
617 EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
618 EVP_PKEY_free(pktmp);
621 SSL_free(ssl);
623 /* If we are using DSA, we can copy the parameters from
624 * the private key */
627 /* Now we know that a key and cert have been set against
628 * the SSL context */
629 if(!SSL_CTX_check_private_key(ctx)) {
630 failf(data, "Private key does not match the certificate public key");
631 return 0;
634 return 1;
637 /* returns non-zero on failure */
638 static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
640 #if 0
641 return X509_NAME_oneline(a, buf, size);
642 #else
643 BIO *bio_out = BIO_new(BIO_s_mem());
644 BUF_MEM *biomem;
645 int rc;
647 if(!bio_out)
648 return 1; /* alloc failed! */
650 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
651 BIO_get_mem_ptr(bio_out, &biomem);
653 if((size_t)biomem->length < size)
654 size = biomem->length;
655 else
656 size--; /* don't overwrite the buffer end */
658 memcpy(buf, biomem->data, size);
659 buf[size]=0;
661 BIO_free(bio_out);
663 return !rc;
664 #endif
667 /* Return error string for last OpenSSL error
669 static char *SSL_strerror(unsigned long error, char *buf, size_t size)
671 /* OpenSSL 0.9.6 and later has a function named
672 ERR_error_string_n() that takes the size of the buffer as a
673 third argument */
674 ERR_error_string_n(error, buf, size);
675 return buf;
679 * Global SSL init
681 * @retval 0 error initializing SSL
682 * @retval 1 SSL initialized successfully
684 int Curl_ossl_init(void)
686 OPENSSL_load_builtin_modules();
688 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
689 ENGINE_load_builtin_engines();
690 #endif
692 /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately
693 that function makes an exit() call on wrongly formatted config files
694 which makes it hard to use in some situations. OPENSSL_config() itself
695 calls CONF_modules_load_file() and we use that instead and we ignore
696 its return code! */
698 /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and
699 0.9.8e */
700 #ifndef CONF_MFLAGS_DEFAULT_SECTION
701 #define CONF_MFLAGS_DEFAULT_SECTION 0x0
702 #endif
704 CONF_modules_load_file(NULL, NULL,
705 CONF_MFLAGS_DEFAULT_SECTION|
706 CONF_MFLAGS_IGNORE_MISSING_FILE);
708 /* Lets get nice error messages */
709 SSL_load_error_strings();
711 /* Init the global ciphers and digests */
712 if(!SSLeay_add_ssl_algorithms())
713 return 0;
715 OpenSSL_add_all_algorithms();
717 return 1;
720 /* Global cleanup */
721 void Curl_ossl_cleanup(void)
723 /* Free ciphers and digests lists */
724 EVP_cleanup();
726 #ifdef HAVE_ENGINE_CLEANUP
727 /* Free engine list */
728 ENGINE_cleanup();
729 #endif
731 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
732 /* Free OpenSSL ex_data table */
733 CRYPTO_cleanup_all_ex_data();
734 #endif
736 /* Free OpenSSL error strings */
737 ERR_free_strings();
739 /* Free thread local error state, destroying hash upon zero refcount */
740 #ifdef HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED
742 #elif defined(HAVE_ERR_REMOVE_THREAD_STATE)
743 ERR_remove_thread_state(NULL);
744 #else
745 ERR_remove_state(0);
746 #endif
748 /* Free all memory allocated by all configuration modules */
749 CONF_modules_free();
751 #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
752 OPENSSL_VERSION_NUMBER <= 0x10002FFFL
753 SSL_COMP_free_compression_methods();
754 #endif
758 * This function is used to determine connection status.
760 * Return codes:
761 * 1 means the connection is still in place
762 * 0 means the connection has been closed
763 * -1 means the connection status is unknown
765 int Curl_ossl_check_cxn(struct connectdata *conn)
767 /* SSL_peek takes data out of the raw recv buffer without peeking so we use
768 recv MSG_PEEK instead. Bug #795 */
769 #ifdef MSG_PEEK
770 char buf;
771 ssize_t nread;
772 nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
773 (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
774 if(nread == 0)
775 return 0; /* connection has been closed */
776 else if(nread == 1)
777 return 1; /* connection still in place */
778 else if(nread == -1) {
779 int err = SOCKERRNO;
780 if(err == EINPROGRESS ||
781 #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
782 err == EAGAIN ||
783 #endif
784 err == EWOULDBLOCK)
785 return 1; /* connection still in place */
786 if(err == ECONNRESET ||
787 #ifdef ECONNABORTED
788 err == ECONNABORTED ||
789 #endif
790 #ifdef ENETDOWN
791 err == ENETDOWN ||
792 #endif
793 #ifdef ENETRESET
794 err == ENETRESET ||
795 #endif
796 #ifdef ESHUTDOWN
797 err == ESHUTDOWN ||
798 #endif
799 #ifdef ETIMEDOUT
800 err == ETIMEDOUT ||
801 #endif
802 err == ENOTCONN)
803 return 0; /* connection has been closed */
805 #endif
806 return -1; /* connection status unknown */
809 /* Selects an OpenSSL crypto engine
811 CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine)
813 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
814 ENGINE *e;
816 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
817 e = ENGINE_by_id(engine);
818 #else
819 /* avoid memory leak */
820 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
821 const char *e_id = ENGINE_get_id(e);
822 if(!strcmp(engine, e_id))
823 break;
825 #endif
827 if(!e) {
828 failf(data, "SSL Engine '%s' not found", engine);
829 return CURLE_SSL_ENGINE_NOTFOUND;
832 if(data->state.engine) {
833 ENGINE_finish(data->state.engine);
834 ENGINE_free(data->state.engine);
835 data->state.engine = NULL;
837 if(!ENGINE_init(e)) {
838 char buf[256];
840 ENGINE_free(e);
841 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
842 engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf)));
843 return CURLE_SSL_ENGINE_INITFAILED;
845 data->state.engine = e;
846 return CURLE_OK;
847 #else
848 (void)engine;
849 failf(data, "SSL Engine not supported");
850 return CURLE_SSL_ENGINE_NOTFOUND;
851 #endif
854 /* Sets engine as default for all SSL operations
856 CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data)
858 #ifdef HAVE_OPENSSL_ENGINE_H
859 if(data->state.engine) {
860 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
861 infof(data, "set default crypto engine '%s'\n",
862 ENGINE_get_id(data->state.engine));
864 else {
865 failf(data, "set default crypto engine '%s' failed",
866 ENGINE_get_id(data->state.engine));
867 return CURLE_SSL_ENGINE_SETFAILED;
870 #else
871 (void) data;
872 #endif
873 return CURLE_OK;
876 /* Return list of OpenSSL crypto engine names.
878 struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data)
880 struct curl_slist *list = NULL;
881 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
882 struct curl_slist *beg;
883 ENGINE *e;
885 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
886 beg = curl_slist_append(list, ENGINE_get_id(e));
887 if(!beg) {
888 curl_slist_free_all(list);
889 return NULL;
891 list = beg;
893 #endif
894 (void) data;
895 return list;
900 * This function is called when an SSL connection is closed.
902 void Curl_ossl_close(struct connectdata *conn, int sockindex)
904 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
906 if(connssl->handle) {
907 (void)SSL_shutdown(connssl->handle);
908 SSL_set_connect_state(connssl->handle);
910 SSL_free (connssl->handle);
911 connssl->handle = NULL;
913 if(connssl->ctx) {
914 SSL_CTX_free (connssl->ctx);
915 connssl->ctx = NULL;
920 * This function is called to shut down the SSL layer but keep the
921 * socket open (CCC - Clear Command Channel)
923 int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
925 int retval = 0;
926 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
927 struct SessionHandle *data = conn->data;
928 char buf[120]; /* We will use this for the OpenSSL error buffer, so it has
929 to be at least 120 bytes long. */
930 unsigned long sslerror;
931 ssize_t nread;
932 int buffsize;
933 int err;
934 int done = 0;
936 /* This has only been tested on the proftpd server, and the mod_tls code
937 sends a close notify alert without waiting for a close notify alert in
938 response. Thus we wait for a close notify alert from the server, but
939 we do not send one. Let's hope other servers do the same... */
941 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
942 (void)SSL_shutdown(connssl->handle);
944 if(connssl->handle) {
945 buffsize = (int)sizeof(buf);
946 while(!done) {
947 int what = Curl_socket_ready(conn->sock[sockindex],
948 CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
949 if(what > 0) {
950 ERR_clear_error();
952 /* Something to read, let's do it and hope that it is the close
953 notify alert from the server */
954 nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
955 buffsize);
956 err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
958 switch(err) {
959 case SSL_ERROR_NONE: /* this is not an error */
960 case SSL_ERROR_ZERO_RETURN: /* no more data */
961 /* This is the expected response. There was no data but only
962 the close notify alert */
963 done = 1;
964 break;
965 case SSL_ERROR_WANT_READ:
966 /* there's data pending, re-invoke SSL_read() */
967 infof(data, "SSL_ERROR_WANT_READ\n");
968 break;
969 case SSL_ERROR_WANT_WRITE:
970 /* SSL wants a write. Really odd. Let's bail out. */
971 infof(data, "SSL_ERROR_WANT_WRITE\n");
972 done = 1;
973 break;
974 default:
975 /* openssl/ssl.h says "look at error stack/return value/errno" */
976 sslerror = ERR_get_error();
977 failf(conn->data, OSSL_PACKAGE " SSL read: %s, errno %d",
978 ERR_error_string(sslerror, buf),
979 SOCKERRNO);
980 done = 1;
981 break;
984 else if(0 == what) {
985 /* timeout */
986 failf(data, "SSL shutdown timeout");
987 done = 1;
989 else {
990 /* anything that gets here is fatally bad */
991 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
992 retval = -1;
993 done = 1;
995 } /* while()-loop for the select() */
997 if(data->set.verbose) {
998 #ifdef HAVE_SSL_GET_SHUTDOWN
999 switch(SSL_get_shutdown(connssl->handle)) {
1000 case SSL_SENT_SHUTDOWN:
1001 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
1002 break;
1003 case SSL_RECEIVED_SHUTDOWN:
1004 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
1005 break;
1006 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
1007 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
1008 "SSL_RECEIVED__SHUTDOWN\n");
1009 break;
1011 #endif
1014 SSL_free (connssl->handle);
1015 connssl->handle = NULL;
1017 return retval;
1020 void Curl_ossl_session_free(void *ptr)
1022 /* free the ID */
1023 SSL_SESSION_free(ptr);
1027 * This function is called when the 'data' struct is going away. Close
1028 * down everything and free all resources!
1030 void Curl_ossl_close_all(struct SessionHandle *data)
1032 #ifdef HAVE_OPENSSL_ENGINE_H
1033 if(data->state.engine) {
1034 ENGINE_finish(data->state.engine);
1035 ENGINE_free(data->state.engine);
1036 data->state.engine = NULL;
1038 #else
1039 (void)data;
1040 #endif
1043 /* ====================================================== */
1046 /* Quote from RFC2818 section 3.1 "Server Identity"
1048 If a subjectAltName extension of type dNSName is present, that MUST
1049 be used as the identity. Otherwise, the (most specific) Common Name
1050 field in the Subject field of the certificate MUST be used. Although
1051 the use of the Common Name is existing practice, it is deprecated and
1052 Certification Authorities are encouraged to use the dNSName instead.
1054 Matching is performed using the matching rules specified by
1055 [RFC2459]. If more than one identity of a given type is present in
1056 the certificate (e.g., more than one dNSName name, a match in any one
1057 of the set is considered acceptable.) Names may contain the wildcard
1058 character * which is considered to match any single domain name
1059 component or component fragment. E.g., *.a.com matches foo.a.com but
1060 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1062 In some cases, the URI is specified as an IP address rather than a
1063 hostname. In this case, the iPAddress subjectAltName must be present
1064 in the certificate and must exactly match the IP in the URI.
1067 static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
1069 bool matched = FALSE;
1070 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1071 size_t addrlen = 0;
1072 struct SessionHandle *data = conn->data;
1073 STACK_OF(GENERAL_NAME) *altnames;
1074 #ifdef ENABLE_IPV6
1075 struct in6_addr addr;
1076 #else
1077 struct in_addr addr;
1078 #endif
1079 CURLcode result = CURLE_OK;
1081 #ifdef ENABLE_IPV6
1082 if(conn->bits.ipv6_ip &&
1083 Curl_inet_pton(AF_INET6, conn->host.name, &addr)) {
1084 target = GEN_IPADD;
1085 addrlen = sizeof(struct in6_addr);
1087 else
1088 #endif
1089 if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) {
1090 target = GEN_IPADD;
1091 addrlen = sizeof(struct in_addr);
1094 /* get a "list" of alternative names */
1095 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1097 if(altnames) {
1098 int numalts;
1099 int i;
1101 /* get amount of alternatives, RFC2459 claims there MUST be at least
1102 one, but we don't depend on it... */
1103 numalts = sk_GENERAL_NAME_num(altnames);
1105 /* loop through all alternatives while none has matched */
1106 for(i=0; (i<numalts) && !matched; i++) {
1107 /* get a handle to alternative name number i */
1108 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1110 /* only check alternatives of the same type the target is */
1111 if(check->type == target) {
1112 /* get data and length */
1113 const char *altptr = (char *)ASN1_STRING_data(check->d.ia5);
1114 size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
1116 switch(target) {
1117 case GEN_DNS: /* name/pattern comparison */
1118 /* The OpenSSL man page explicitly says: "In general it cannot be
1119 assumed that the data returned by ASN1_STRING_data() is null
1120 terminated or does not contain embedded nulls." But also that
1121 "The actual format of the data will depend on the actual string
1122 type itself: for example for and IA5String the data will be ASCII"
1124 Gisle researched the OpenSSL sources:
1125 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1126 it always 0-terminates an IA5String."
1128 if((altlen == strlen(altptr)) &&
1129 /* if this isn't true, there was an embedded zero in the name
1130 string and we cannot match it. */
1131 Curl_cert_hostcheck(altptr, conn->host.name)) {
1132 matched = TRUE;
1133 infof(data,
1134 " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
1135 conn->host.dispname, altptr);
1137 break;
1139 case GEN_IPADD: /* IP address comparison */
1140 /* compare alternative IP address if the data chunk is the same size
1141 our server IP address is */
1142 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
1143 matched = TRUE;
1144 infof(data,
1145 " subjectAltName: host \"%s\" matched cert's IP address!\n",
1146 conn->host.dispname);
1148 break;
1152 GENERAL_NAMES_free(altnames);
1155 if(matched)
1156 /* an alternative name matched */
1158 else if(altnames) {
1159 /* an alternative name field existed, but didn't match and then we MUST
1160 fail */
1161 infof(data, " subjectAltName does not match %s\n", conn->host.dispname);
1162 failf(data, "SSL: no alternative certificate subject name matches "
1163 "target host name '%s'", conn->host.dispname);
1164 result = CURLE_PEER_FAILED_VERIFICATION;
1166 else {
1167 /* we have to look to the last occurrence of a commonName in the
1168 distinguished one to get the most significant one. */
1169 int j, i=-1;
1171 /* The following is done because of a bug in 0.9.6b */
1173 unsigned char *nulstr = (unsigned char *)"";
1174 unsigned char *peer_CN = nulstr;
1176 X509_NAME *name = X509_get_subject_name(server_cert);
1177 if(name)
1178 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0)
1179 i=j;
1181 /* we have the name entry and we will now convert this to a string
1182 that we can use for comparison. Doing this we support BMPstring,
1183 UTF8 etc. */
1185 if(i>=0) {
1186 ASN1_STRING *tmp =
1187 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
1189 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1190 is already UTF-8 encoded. We check for this case and copy the raw
1191 string manually to avoid the problem. This code can be made
1192 conditional in the future when OpenSSL has been fixed. Work-around
1193 brought by Alexis S. L. Carvalho. */
1194 if(tmp) {
1195 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1196 j = ASN1_STRING_length(tmp);
1197 if(j >= 0) {
1198 peer_CN = OPENSSL_malloc(j+1);
1199 if(peer_CN) {
1200 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
1201 peer_CN[j] = '\0';
1205 else /* not a UTF8 name */
1206 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1208 if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
1209 /* there was a terminating zero before the end of string, this
1210 cannot match and we return failure! */
1211 failf(data, "SSL: illegal cert name field");
1212 result = CURLE_PEER_FAILED_VERIFICATION;
1217 if(peer_CN == nulstr)
1218 peer_CN = NULL;
1219 else {
1220 /* convert peer_CN from UTF8 */
1221 CURLcode rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
1222 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1223 if(rc) {
1224 OPENSSL_free(peer_CN);
1225 return rc;
1229 if(result)
1230 /* error already detected, pass through */
1232 else if(!peer_CN) {
1233 failf(data,
1234 "SSL: unable to obtain common name from peer certificate");
1235 result = CURLE_PEER_FAILED_VERIFICATION;
1237 else if(!Curl_cert_hostcheck((const char *)peer_CN, conn->host.name)) {
1238 failf(data, "SSL: certificate subject name '%s' does not match "
1239 "target host name '%s'", peer_CN, conn->host.dispname);
1240 result = CURLE_PEER_FAILED_VERIFICATION;
1242 else {
1243 infof(data, " common name: %s (matched)\n", peer_CN);
1245 if(peer_CN)
1246 OPENSSL_free(peer_CN);
1249 return result;
1252 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
1253 !defined(OPENSSL_NO_OCSP)
1254 static CURLcode verifystatus(struct connectdata *conn,
1255 struct ssl_connect_data *connssl)
1257 int i, ocsp_status;
1258 const unsigned char *p;
1259 CURLcode result = CURLE_OK;
1260 struct SessionHandle *data = conn->data;
1262 OCSP_RESPONSE *rsp = NULL;
1263 OCSP_BASICRESP *br = NULL;
1264 X509_STORE *st = NULL;
1265 STACK_OF(X509) *ch = NULL;
1267 long len = SSL_get_tlsext_status_ocsp_resp(connssl->handle, &p);
1269 if(!p) {
1270 failf(data, "No OCSP response received");
1271 result = CURLE_SSL_INVALIDCERTSTATUS;
1272 goto end;
1275 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1276 if(!rsp) {
1277 failf(data, "Invalid OCSP response");
1278 result = CURLE_SSL_INVALIDCERTSTATUS;
1279 goto end;
1282 ocsp_status = OCSP_response_status(rsp);
1283 if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1284 failf(data, "Invalid OCSP response status: %s (%d)",
1285 OCSP_response_status_str(ocsp_status), ocsp_status);
1286 result = CURLE_SSL_INVALIDCERTSTATUS;
1287 goto end;
1290 br = OCSP_response_get1_basic(rsp);
1291 if(!br) {
1292 failf(data, "Invalid OCSP response");
1293 result = CURLE_SSL_INVALIDCERTSTATUS;
1294 goto end;
1297 ch = SSL_get_peer_cert_chain(connssl->handle);
1298 st = SSL_CTX_get_cert_store(connssl->ctx);
1300 #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
1301 defined(LIBRESSL_VERSION_NUMBER))
1302 /* The authorized responder cert in the OCSP response MUST be signed by the
1303 peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
1304 no problem, but if it's an intermediate cert OpenSSL has a bug where it
1305 expects this issuer to be present in the chain embedded in the OCSP
1306 response. So we add it if necessary. */
1308 /* First make sure the peer cert chain includes both a peer and an issuer,
1309 and the OCSP response contains a responder cert. */
1310 if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
1311 X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
1313 /* Find issuer of responder cert and add it to the OCSP response chain */
1314 for(i = 0; i < sk_X509_num(ch); i++) {
1315 X509 *issuer = sk_X509_value(ch, i);
1316 if(X509_check_issued(issuer, responder) == X509_V_OK) {
1317 if(!OCSP_basic_add1_cert(br, issuer)) {
1318 failf(data, "Could not add issuer cert to OCSP response");
1319 result = CURLE_SSL_INVALIDCERTSTATUS;
1320 goto end;
1325 #endif
1327 if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
1328 failf(data, "OCSP response verification failed");
1329 result = CURLE_SSL_INVALIDCERTSTATUS;
1330 goto end;
1333 for(i = 0; i < OCSP_resp_count(br); i++) {
1334 int cert_status, crl_reason;
1335 OCSP_SINGLERESP *single = NULL;
1337 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1339 single = OCSP_resp_get0(br, i);
1340 if(!single)
1341 continue;
1343 cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
1344 &thisupd, &nextupd);
1346 if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
1347 failf(data, "OCSP response has expired");
1348 result = CURLE_SSL_INVALIDCERTSTATUS;
1349 goto end;
1352 infof(data, "SSL certificate status: %s (%d)\n",
1353 OCSP_cert_status_str(cert_status), cert_status);
1355 switch(cert_status) {
1356 case V_OCSP_CERTSTATUS_GOOD:
1357 break;
1359 case V_OCSP_CERTSTATUS_REVOKED:
1360 result = CURLE_SSL_INVALIDCERTSTATUS;
1362 failf(data, "SSL certificate revocation reason: %s (%d)",
1363 OCSP_crl_reason_str(crl_reason), crl_reason);
1364 goto end;
1366 case V_OCSP_CERTSTATUS_UNKNOWN:
1367 result = CURLE_SSL_INVALIDCERTSTATUS;
1368 goto end;
1372 end:
1373 if(br) OCSP_BASICRESP_free(br);
1374 OCSP_RESPONSE_free(rsp);
1376 return result;
1378 #endif
1380 #endif /* USE_OPENSSL */
1382 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1383 and thus this cannot be done there. */
1384 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1386 static const char *ssl_msg_type(int ssl_ver, int msg)
1388 #ifdef SSL2_VERSION_MAJOR
1389 if(ssl_ver == SSL2_VERSION_MAJOR) {
1390 switch (msg) {
1391 case SSL2_MT_ERROR:
1392 return "Error";
1393 case SSL2_MT_CLIENT_HELLO:
1394 return "Client hello";
1395 case SSL2_MT_CLIENT_MASTER_KEY:
1396 return "Client key";
1397 case SSL2_MT_CLIENT_FINISHED:
1398 return "Client finished";
1399 case SSL2_MT_SERVER_HELLO:
1400 return "Server hello";
1401 case SSL2_MT_SERVER_VERIFY:
1402 return "Server verify";
1403 case SSL2_MT_SERVER_FINISHED:
1404 return "Server finished";
1405 case SSL2_MT_REQUEST_CERTIFICATE:
1406 return "Request CERT";
1407 case SSL2_MT_CLIENT_CERTIFICATE:
1408 return "Client CERT";
1411 else
1412 #endif
1413 if(ssl_ver == SSL3_VERSION_MAJOR) {
1414 switch (msg) {
1415 case SSL3_MT_HELLO_REQUEST:
1416 return "Hello request";
1417 case SSL3_MT_CLIENT_HELLO:
1418 return "Client hello";
1419 case SSL3_MT_SERVER_HELLO:
1420 return "Server hello";
1421 #ifdef SSL3_MT_NEWSESSION_TICKET
1422 case SSL3_MT_NEWSESSION_TICKET:
1423 return "Newsession Ticket";
1424 #endif
1425 case SSL3_MT_CERTIFICATE:
1426 return "Certificate";
1427 case SSL3_MT_SERVER_KEY_EXCHANGE:
1428 return "Server key exchange";
1429 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1430 return "Client key exchange";
1431 case SSL3_MT_CERTIFICATE_REQUEST:
1432 return "Request CERT";
1433 case SSL3_MT_SERVER_DONE:
1434 return "Server finished";
1435 case SSL3_MT_CERTIFICATE_VERIFY:
1436 return "CERT verify";
1437 case SSL3_MT_FINISHED:
1438 return "Finished";
1439 #ifdef SSL3_MT_CERTIFICATE_STATUS
1440 case SSL3_MT_CERTIFICATE_STATUS:
1441 return "Certificate Status";
1442 #endif
1445 return "Unknown";
1448 static const char *tls_rt_type(int type)
1450 switch(type) {
1451 #ifdef SSL3_RT_HEADER
1452 case SSL3_RT_HEADER:
1453 return "TLS header";
1454 #endif
1455 case SSL3_RT_CHANGE_CIPHER_SPEC:
1456 return "TLS change cipher";
1457 case SSL3_RT_ALERT:
1458 return "TLS alert";
1459 case SSL3_RT_HANDSHAKE:
1460 return "TLS handshake";
1461 case SSL3_RT_APPLICATION_DATA:
1462 return "TLS app data";
1463 default:
1464 return "TLS Unknown";
1470 * Our callback from the SSL/TLS layers.
1472 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1473 const void *buf, size_t len, SSL *ssl,
1474 void *userp)
1476 struct SessionHandle *data;
1477 const char *msg_name, *tls_rt_name;
1478 char ssl_buf[1024];
1479 char unknown[32];
1480 int msg_type, txt_len;
1481 const char *verstr = NULL;
1482 struct connectdata *conn = userp;
1484 if(!conn || !conn->data || !conn->data->set.fdebug ||
1485 (direction != 0 && direction != 1))
1486 return;
1488 data = conn->data;
1490 switch(ssl_ver) {
1491 #ifdef SSL2_VERSION /* removed in recent versions */
1492 case SSL2_VERSION:
1493 verstr = "SSLv2";
1494 break;
1495 #endif
1496 #ifdef SSL3_VERSION
1497 case SSL3_VERSION:
1498 verstr = "SSLv3";
1499 break;
1500 #endif
1501 case TLS1_VERSION:
1502 verstr = "TLSv1.0";
1503 break;
1504 #ifdef TLS1_1_VERSION
1505 case TLS1_1_VERSION:
1506 verstr = "TLSv1.1";
1507 break;
1508 #endif
1509 #ifdef TLS1_2_VERSION
1510 case TLS1_2_VERSION:
1511 verstr = "TLSv1.2";
1512 break;
1513 #endif
1514 case 0:
1515 break;
1516 default:
1517 snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
1518 verstr = unknown;
1519 break;
1522 if(ssl_ver) {
1523 /* the info given when the version is zero is not that useful for us */
1525 ssl_ver >>= 8; /* check the upper 8 bits only below */
1527 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1528 * always pass-up content-type as 0. But the interesting message-type
1529 * is at 'buf[0]'.
1531 if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
1532 tls_rt_name = tls_rt_type(content_type);
1533 else
1534 tls_rt_name = "";
1536 msg_type = *(char*)buf;
1537 msg_name = ssl_msg_type(ssl_ver, msg_type);
1539 txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
1540 verstr, direction?"OUT":"IN",
1541 tls_rt_name, msg_name, msg_type);
1542 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
1545 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1546 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1547 (void) ssl;
1549 #endif
1551 #ifdef USE_OPENSSL
1552 /* ====================================================== */
1554 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1555 # define use_sni(x) sni = (x)
1556 #else
1557 # define use_sni(x) Curl_nop_stmt
1558 #endif
1560 /* Check for OpenSSL 1.0.2 which has ALPN support. */
1561 #undef HAS_ALPN
1562 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
1563 && !defined(OPENSSL_NO_TLSEXT)
1564 # define HAS_ALPN 1
1565 #endif
1567 /* Check for OpenSSL 1.0.1 which has NPN support. */
1568 #undef HAS_NPN
1569 #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
1570 && !defined(OPENSSL_NO_TLSEXT) \
1571 && !defined(OPENSSL_NO_NEXTPROTONEG)
1572 # define HAS_NPN 1
1573 #endif
1575 #ifdef HAS_NPN
1578 * in is a list of lenght prefixed strings. this function has to select
1579 * the protocol we want to use from the list and write its string into out.
1582 static int
1583 select_next_protocol(unsigned char **out, unsigned char *outlen,
1584 const unsigned char *in, unsigned int inlen,
1585 const char *key, unsigned int keylen)
1587 unsigned int i;
1588 for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
1589 if(memcmp(&in[i + 1], key, keylen) == 0) {
1590 *out = (unsigned char *) &in[i + 1];
1591 *outlen = in[i];
1592 return 0;
1595 return -1;
1598 static int
1599 select_next_proto_cb(SSL *ssl,
1600 unsigned char **out, unsigned char *outlen,
1601 const unsigned char *in, unsigned int inlen,
1602 void *arg)
1604 struct connectdata *conn = (struct connectdata*) arg;
1606 (void)ssl;
1608 #ifdef USE_NGHTTP2
1609 if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
1610 !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
1611 NGHTTP2_PROTO_VERSION_ID_LEN)) {
1612 infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
1613 NGHTTP2_PROTO_VERSION_ID);
1614 conn->negnpn = CURL_HTTP_VERSION_2;
1615 return SSL_TLSEXT_ERR_OK;
1617 #endif
1619 if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
1620 ALPN_HTTP_1_1_LENGTH)) {
1621 infof(conn->data, "NPN, negotiated HTTP1.1\n");
1622 conn->negnpn = CURL_HTTP_VERSION_1_1;
1623 return SSL_TLSEXT_ERR_OK;
1626 infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
1627 *out = (unsigned char *)ALPN_HTTP_1_1;
1628 *outlen = ALPN_HTTP_1_1_LENGTH;
1629 conn->negnpn = CURL_HTTP_VERSION_1_1;
1631 return SSL_TLSEXT_ERR_OK;
1633 #endif /* HAS_NPN */
1635 static const char *
1636 get_ssl_version_txt(SSL *ssl)
1638 if(!ssl)
1639 return "";
1641 switch(SSL_version(ssl)) {
1642 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1643 case TLS1_2_VERSION:
1644 return "TLSv1.2";
1645 case TLS1_1_VERSION:
1646 return "TLSv1.1";
1647 #endif
1648 case TLS1_VERSION:
1649 return "TLSv1.0";
1650 case SSL3_VERSION:
1651 return "SSLv3";
1652 case SSL2_VERSION:
1653 return "SSLv2";
1655 return "unknown";
1658 static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
1660 CURLcode result = CURLE_OK;
1661 char *ciphers;
1662 struct SessionHandle *data = conn->data;
1663 SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
1664 void *ssl_sessionid = NULL;
1665 X509_LOOKUP *lookup = NULL;
1666 curl_socket_t sockfd = conn->sock[sockindex];
1667 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1668 long ctx_options;
1669 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1670 bool sni;
1671 #ifdef ENABLE_IPV6
1672 struct in6_addr addr;
1673 #else
1674 struct in_addr addr;
1675 #endif
1676 #endif
1678 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
1680 /* Make funny stuff to get random input */
1681 Curl_ossl_seed(data);
1683 data->set.ssl.certverifyresult = !X509_V_OK;
1685 /* check to see if we've been told to use an explicit SSL/TLS version */
1687 switch(data->set.ssl.version) {
1688 default:
1689 case CURL_SSLVERSION_DEFAULT:
1690 case CURL_SSLVERSION_TLSv1:
1691 case CURL_SSLVERSION_TLSv1_0:
1692 case CURL_SSLVERSION_TLSv1_1:
1693 case CURL_SSLVERSION_TLSv1_2:
1694 /* it will be handled later with the context options */
1695 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
1696 !defined(LIBRESSL_VERSION_NUMBER)
1697 req_method = TLS_client_method();
1698 #else
1699 req_method = SSLv23_client_method();
1700 #endif
1701 use_sni(TRUE);
1702 break;
1703 case CURL_SSLVERSION_SSLv2:
1704 #ifdef OPENSSL_NO_SSL2
1705 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
1706 return CURLE_NOT_BUILT_IN;
1707 #else
1708 #ifdef USE_TLS_SRP
1709 if(data->set.ssl.authtype == CURL_TLSAUTH_SRP)
1710 return CURLE_SSL_CONNECT_ERROR;
1711 #endif
1712 req_method = SSLv2_client_method();
1713 use_sni(FALSE);
1714 break;
1715 #endif
1716 case CURL_SSLVERSION_SSLv3:
1717 #ifdef OPENSSL_NO_SSL3_METHOD
1718 failf(data, OSSL_PACKAGE " was built without SSLv3 support");
1719 return CURLE_NOT_BUILT_IN;
1720 #else
1721 #ifdef USE_TLS_SRP
1722 if(data->set.ssl.authtype == CURL_TLSAUTH_SRP)
1723 return CURLE_SSL_CONNECT_ERROR;
1724 #endif
1725 req_method = SSLv3_client_method();
1726 use_sni(FALSE);
1727 break;
1728 #endif
1731 if(connssl->ctx)
1732 SSL_CTX_free(connssl->ctx);
1733 connssl->ctx = SSL_CTX_new(req_method);
1735 if(!connssl->ctx) {
1736 failf(data, "SSL: couldn't create a context: %s",
1737 ERR_error_string(ERR_peek_error(), NULL));
1738 return CURLE_OUT_OF_MEMORY;
1741 #ifdef SSL_MODE_RELEASE_BUFFERS
1742 SSL_CTX_set_mode(connssl->ctx, SSL_MODE_RELEASE_BUFFERS);
1743 #endif
1745 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1746 if(data->set.fdebug && data->set.verbose) {
1747 /* the SSL trace callback is only used for verbose logging */
1748 SSL_CTX_set_msg_callback(connssl->ctx, ssl_tls_trace);
1749 SSL_CTX_set_msg_callback_arg(connssl->ctx, conn);
1751 #endif
1753 /* OpenSSL contains code to work-around lots of bugs and flaws in various
1754 SSL-implementations. SSL_CTX_set_options() is used to enabled those
1755 work-arounds. The man page for this option states that SSL_OP_ALL enables
1756 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
1757 enable the bug workaround options if compatibility with somewhat broken
1758 implementations is desired."
1760 The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
1761 disable "rfc4507bis session ticket support". rfc4507bis was later turned
1762 into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
1764 The enabled extension concerns the session management. I wonder how often
1765 libcurl stops a connection and then resumes a TLS session. also, sending
1766 the session data is some overhead. .I suggest that you just use your
1767 proposed patch (which explicitly disables TICKET).
1769 If someone writes an application with libcurl and openssl who wants to
1770 enable the feature, one can do this in the SSL callback.
1772 SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
1773 interoperability with web server Netscape Enterprise Server 2.0.1 which
1774 was released back in 1996.
1776 Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
1777 become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
1778 CVE-2010-4180 when using previous OpenSSL versions we no longer enable
1779 this option regardless of OpenSSL version and SSL_OP_ALL definition.
1781 OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
1782 (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
1783 SSL_OP_ALL that _disables_ that work-around despite the fact that
1784 SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
1785 keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
1786 must not be set.
1789 ctx_options = SSL_OP_ALL;
1791 #ifdef SSL_OP_NO_TICKET
1792 ctx_options |= SSL_OP_NO_TICKET;
1793 #endif
1795 #ifdef SSL_OP_NO_COMPRESSION
1796 ctx_options |= SSL_OP_NO_COMPRESSION;
1797 #endif
1799 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
1800 /* mitigate CVE-2010-4180 */
1801 ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
1802 #endif
1804 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
1805 /* unless the user explicitly ask to allow the protocol vulnerability we
1806 use the work-around */
1807 if(!conn->data->set.ssl_enable_beast)
1808 ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1809 #endif
1811 switch(data->set.ssl.version) {
1812 case CURL_SSLVERSION_SSLv3:
1813 #ifdef USE_TLS_SRP
1814 if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
1815 infof(data, "Set version TLSv1.x for SRP authorisation\n");
1817 #endif
1818 ctx_options |= SSL_OP_NO_SSLv2;
1819 ctx_options |= SSL_OP_NO_TLSv1;
1820 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1821 ctx_options |= SSL_OP_NO_TLSv1_1;
1822 ctx_options |= SSL_OP_NO_TLSv1_2;
1823 #endif
1824 break;
1826 case CURL_SSLVERSION_DEFAULT:
1827 case CURL_SSLVERSION_TLSv1:
1828 ctx_options |= SSL_OP_NO_SSLv2;
1829 ctx_options |= SSL_OP_NO_SSLv3;
1830 break;
1832 case CURL_SSLVERSION_TLSv1_0:
1833 ctx_options |= SSL_OP_NO_SSLv2;
1834 ctx_options |= SSL_OP_NO_SSLv3;
1835 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1836 ctx_options |= SSL_OP_NO_TLSv1_1;
1837 ctx_options |= SSL_OP_NO_TLSv1_2;
1838 #endif
1839 break;
1841 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1842 case CURL_SSLVERSION_TLSv1_1:
1843 ctx_options |= SSL_OP_NO_SSLv2;
1844 ctx_options |= SSL_OP_NO_SSLv3;
1845 ctx_options |= SSL_OP_NO_TLSv1;
1846 ctx_options |= SSL_OP_NO_TLSv1_2;
1847 break;
1849 case CURL_SSLVERSION_TLSv1_2:
1850 ctx_options |= SSL_OP_NO_SSLv2;
1851 ctx_options |= SSL_OP_NO_SSLv3;
1852 ctx_options |= SSL_OP_NO_TLSv1;
1853 ctx_options |= SSL_OP_NO_TLSv1_1;
1854 break;
1855 #endif
1857 #ifndef OPENSSL_NO_SSL2
1858 case CURL_SSLVERSION_SSLv2:
1859 ctx_options |= SSL_OP_NO_SSLv3;
1860 ctx_options |= SSL_OP_NO_TLSv1;
1861 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1862 ctx_options |= SSL_OP_NO_TLSv1_1;
1863 ctx_options |= SSL_OP_NO_TLSv1_2;
1864 #endif
1865 break;
1866 #endif
1868 default:
1869 failf(data, "Unsupported SSL protocol version");
1870 return CURLE_SSL_CONNECT_ERROR;
1873 SSL_CTX_set_options(connssl->ctx, ctx_options);
1875 #ifdef HAS_NPN
1876 if(conn->bits.tls_enable_npn)
1877 SSL_CTX_set_next_proto_select_cb(connssl->ctx, select_next_proto_cb, conn);
1878 #endif
1880 #ifdef HAS_ALPN
1881 if(conn->bits.tls_enable_alpn) {
1882 int cur = 0;
1883 unsigned char protocols[128];
1885 #ifdef USE_NGHTTP2
1886 if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
1887 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
1889 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
1890 NGHTTP2_PROTO_VERSION_ID_LEN);
1891 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
1892 infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
1894 #endif
1896 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
1897 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
1898 cur += ALPN_HTTP_1_1_LENGTH;
1899 infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
1901 /* expects length prefixed preference ordered list of protocols in wire
1902 * format
1904 SSL_CTX_set_alpn_protos(connssl->ctx, protocols, cur);
1906 #endif
1908 if(data->set.str[STRING_CERT] || data->set.str[STRING_CERT_TYPE]) {
1909 if(!cert_stuff(conn,
1910 connssl->ctx,
1911 data->set.str[STRING_CERT],
1912 data->set.str[STRING_CERT_TYPE],
1913 data->set.str[STRING_KEY],
1914 data->set.str[STRING_KEY_TYPE])) {
1915 /* failf() is already done in cert_stuff() */
1916 return CURLE_SSL_CERTPROBLEM;
1920 ciphers = data->set.str[STRING_SSL_CIPHER_LIST];
1921 if(!ciphers)
1922 ciphers = (char *)DEFAULT_CIPHER_SELECTION;
1923 if(!SSL_CTX_set_cipher_list(connssl->ctx, ciphers)) {
1924 failf(data, "failed setting cipher list: %s", ciphers);
1925 return CURLE_SSL_CIPHER;
1927 infof(data, "Cipher selection: %s\n", ciphers);
1929 #ifdef USE_TLS_SRP
1930 if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
1931 infof(data, "Using TLS-SRP username: %s\n", data->set.ssl.username);
1933 if(!SSL_CTX_set_srp_username(connssl->ctx, data->set.ssl.username)) {
1934 failf(data, "Unable to set SRP user name");
1935 return CURLE_BAD_FUNCTION_ARGUMENT;
1937 if(!SSL_CTX_set_srp_password(connssl->ctx, data->set.ssl.password)) {
1938 failf(data, "failed setting SRP password");
1939 return CURLE_BAD_FUNCTION_ARGUMENT;
1941 if(!data->set.str[STRING_SSL_CIPHER_LIST]) {
1942 infof(data, "Setting cipher list SRP\n");
1944 if(!SSL_CTX_set_cipher_list(connssl->ctx, "SRP")) {
1945 failf(data, "failed setting SRP cipher list");
1946 return CURLE_SSL_CIPHER;
1950 #endif
1951 if(data->set.str[STRING_SSL_CAFILE] || data->set.str[STRING_SSL_CAPATH]) {
1952 /* tell SSL where to find CA certificates that are used to verify
1953 the servers certificate. */
1954 if(!SSL_CTX_load_verify_locations(connssl->ctx,
1955 data->set.str[STRING_SSL_CAFILE],
1956 data->set.str[STRING_SSL_CAPATH])) {
1957 if(data->set.ssl.verifypeer) {
1958 /* Fail if we insist on successfully verifying the server. */
1959 failf(data, "error setting certificate verify locations:\n"
1960 " CAfile: %s\n CApath: %s",
1961 data->set.str[STRING_SSL_CAFILE]?
1962 data->set.str[STRING_SSL_CAFILE]: "none",
1963 data->set.str[STRING_SSL_CAPATH]?
1964 data->set.str[STRING_SSL_CAPATH] : "none");
1965 return CURLE_SSL_CACERT_BADFILE;
1967 else {
1968 /* Just continue with a warning if no strict certificate verification
1969 is required. */
1970 infof(data, "error setting certificate verify locations,"
1971 " continuing anyway:\n");
1974 else {
1975 /* Everything is fine. */
1976 infof(data, "successfully set certificate verify locations:\n");
1978 infof(data,
1979 " CAfile: %s\n"
1980 " CApath: %s\n",
1981 data->set.str[STRING_SSL_CAFILE] ? data->set.str[STRING_SSL_CAFILE]:
1982 "none",
1983 data->set.str[STRING_SSL_CAPATH] ? data->set.str[STRING_SSL_CAPATH]:
1984 "none");
1986 #ifdef CURL_CA_FALLBACK
1987 else if(data->set.ssl.verifypeer) {
1988 /* verfying the peer without any CA certificates won't
1989 work so use openssl's built in default as fallback */
1990 SSL_CTX_set_default_verify_paths(connssl->ctx);
1992 #endif
1994 if(data->set.str[STRING_SSL_CRLFILE]) {
1995 /* tell SSL where to find CRL file that is used to check certificate
1996 * revocation */
1997 lookup=X509_STORE_add_lookup(SSL_CTX_get_cert_store(connssl->ctx),
1998 X509_LOOKUP_file());
1999 if(!lookup ||
2000 (!X509_load_crl_file(lookup, data->set.str[STRING_SSL_CRLFILE],
2001 X509_FILETYPE_PEM)) ) {
2002 failf(data, "error loading CRL file: %s",
2003 data->set.str[STRING_SSL_CRLFILE]);
2004 return CURLE_SSL_CRL_BADFILE;
2006 else {
2007 /* Everything is fine. */
2008 infof(data, "successfully load CRL file:\n");
2009 X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
2010 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2012 infof(data,
2013 " CRLfile: %s\n", data->set.str[STRING_SSL_CRLFILE] ?
2014 data->set.str[STRING_SSL_CRLFILE]: "none");
2017 /* Try building a chain using issuers in the trusted store first to avoid
2018 problems with server-sent legacy intermediates.
2019 Newer versions of OpenSSL do alternate chain checking by default which
2020 gives us the same fix without as much of a performance hit (slight), so we
2021 prefer that if available.
2022 https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
2024 #if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
2025 if(data->set.ssl.verifypeer) {
2026 X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
2027 X509_V_FLAG_TRUSTED_FIRST);
2029 #endif
2031 /* SSL always tries to verify the peer, this only says whether it should
2032 * fail to connect if the verification fails, or if it should continue
2033 * anyway. In the latter case the result of the verification is checked with
2034 * SSL_get_verify_result() below. */
2035 SSL_CTX_set_verify(connssl->ctx,
2036 data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE,
2037 NULL);
2039 /* give application a chance to interfere with SSL set up. */
2040 if(data->set.ssl.fsslctx) {
2041 result = (*data->set.ssl.fsslctx)(data, connssl->ctx,
2042 data->set.ssl.fsslctxp);
2043 if(result) {
2044 failf(data, "error signaled by ssl ctx callback");
2045 return result;
2049 /* Lets make an SSL structure */
2050 if(connssl->handle)
2051 SSL_free(connssl->handle);
2052 connssl->handle = SSL_new(connssl->ctx);
2053 if(!connssl->handle) {
2054 failf(data, "SSL: couldn't create a context (handle)!");
2055 return CURLE_OUT_OF_MEMORY;
2058 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
2059 !defined(OPENSSL_NO_OCSP)
2060 if(data->set.ssl.verifystatus)
2061 SSL_set_tlsext_status_type(connssl->handle, TLSEXT_STATUSTYPE_ocsp);
2062 #endif
2064 SSL_set_connect_state(connssl->handle);
2066 connssl->server_cert = 0x0;
2068 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2069 if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
2070 #ifdef ENABLE_IPV6
2071 (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
2072 #endif
2073 sni &&
2074 !SSL_set_tlsext_host_name(connssl->handle, conn->host.name))
2075 infof(data, "WARNING: failed to configure server name indication (SNI) "
2076 "TLS extension\n");
2077 #endif
2079 /* Check if there's a cached ID we can/should use here! */
2080 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
2081 /* we got a session id, use it! */
2082 if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
2083 failf(data, "SSL: SSL_set_session failed: %s",
2084 ERR_error_string(ERR_get_error(), NULL));
2085 return CURLE_SSL_CONNECT_ERROR;
2087 /* Informational message */
2088 infof (data, "SSL re-using session ID\n");
2091 /* pass the raw socket into the SSL layers */
2092 if(!SSL_set_fd(connssl->handle, (int)sockfd)) {
2093 failf(data, "SSL: SSL_set_fd failed: %s",
2094 ERR_error_string(ERR_get_error(), NULL));
2095 return CURLE_SSL_CONNECT_ERROR;
2098 connssl->connecting_state = ssl_connect_2;
2100 return CURLE_OK;
2103 static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
2105 struct SessionHandle *data = conn->data;
2106 int err;
2107 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2108 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
2109 || ssl_connect_2_reading == connssl->connecting_state
2110 || ssl_connect_2_writing == connssl->connecting_state);
2112 ERR_clear_error();
2114 err = SSL_connect(connssl->handle);
2116 /* 1 is fine
2117 0 is "not successful but was shut down controlled"
2118 <0 is "handshake was not successful, because a fatal error occurred" */
2119 if(1 != err) {
2120 int detail = SSL_get_error(connssl->handle, err);
2122 if(SSL_ERROR_WANT_READ == detail) {
2123 connssl->connecting_state = ssl_connect_2_reading;
2124 return CURLE_OK;
2126 else if(SSL_ERROR_WANT_WRITE == detail) {
2127 connssl->connecting_state = ssl_connect_2_writing;
2128 return CURLE_OK;
2130 else {
2131 /* untreated error */
2132 unsigned long errdetail;
2133 char error_buffer[256]=""; /* OpenSSL documents that this must be at
2134 least 256 bytes long. */
2135 CURLcode result;
2136 long lerr;
2137 int lib;
2138 int reason;
2140 /* the connection failed, we're not waiting for anything else. */
2141 connssl->connecting_state = ssl_connect_2;
2143 /* Get the earliest error code from the thread's error queue and removes
2144 the entry. */
2145 errdetail = ERR_get_error();
2147 /* Extract which lib and reason */
2148 lib = ERR_GET_LIB(errdetail);
2149 reason = ERR_GET_REASON(errdetail);
2151 if((lib == ERR_LIB_SSL) &&
2152 (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
2153 result = CURLE_SSL_CACERT;
2155 lerr = SSL_get_verify_result(connssl->handle);
2156 if(lerr != X509_V_OK) {
2157 snprintf(error_buffer, sizeof(error_buffer),
2158 "SSL certificate problem: %s",
2159 X509_verify_cert_error_string(lerr));
2161 else
2162 /* strcpy() is fine here as long as the string fits within
2163 error_buffer */
2164 strcpy(error_buffer, "SSL certificate verification failed");
2166 else {
2167 result = CURLE_SSL_CONNECT_ERROR;
2168 SSL_strerror(errdetail, error_buffer, sizeof(error_buffer));
2171 /* detail is already set to the SSL error above */
2173 /* If we e.g. use SSLv2 request-method and the server doesn't like us
2174 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
2175 * the SO_ERROR is also lost.
2177 if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
2178 failf(data, "Unknown SSL protocol error in connection to %s:%ld ",
2179 conn->host.name, conn->remote_port);
2180 return result;
2183 /* Could be a CERT problem */
2184 failf(data, "%s", error_buffer);
2186 return result;
2189 else {
2190 /* we have been connected fine, we're not waiting for anything else. */
2191 connssl->connecting_state = ssl_connect_3;
2193 /* Informational message */
2194 infof(data, "SSL connection using %s / %s\n",
2195 get_ssl_version_txt(connssl->handle),
2196 SSL_get_cipher(connssl->handle));
2198 #ifdef HAS_ALPN
2199 /* Sets data and len to negotiated protocol, len is 0 if no protocol was
2200 * negotiated
2202 if(conn->bits.tls_enable_alpn) {
2203 const unsigned char* neg_protocol;
2204 unsigned int len;
2205 SSL_get0_alpn_selected(connssl->handle, &neg_protocol, &len);
2206 if(len != 0) {
2207 infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
2209 #ifdef USE_NGHTTP2
2210 if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
2211 !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
2212 conn->negnpn = CURL_HTTP_VERSION_2;
2214 else
2215 #endif
2216 if(len == ALPN_HTTP_1_1_LENGTH &&
2217 !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
2218 conn->negnpn = CURL_HTTP_VERSION_1_1;
2221 else
2222 infof(data, "ALPN, server did not agree to a protocol\n");
2224 #endif
2226 return CURLE_OK;
2230 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
2232 int i, ilen;
2234 if((ilen = (int)len) < 0)
2235 return 1; /* buffer too big */
2237 i = i2t_ASN1_OBJECT(buf, ilen, a);
2239 if(i >= ilen)
2240 return 1; /* buffer too small */
2242 return 0;
2245 #define push_certinfo(_label, _num) \
2246 do { \
2247 long info_len = BIO_get_mem_data(mem, &ptr); \
2248 Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
2249 if(1!=BIO_reset(mem)) \
2250 break; \
2251 } WHILE_FALSE
2253 static void pubkey_show(struct SessionHandle *data,
2254 BIO *mem,
2255 int num,
2256 const char *type,
2257 const char *name,
2258 BIGNUM *bn)
2260 char *ptr;
2261 char namebuf[32];
2263 snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
2265 if(bn)
2266 BN_print(mem, bn);
2267 push_certinfo(namebuf, num);
2270 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2271 #define print_pubkey_BN(_type, _name, _num) \
2272 pubkey_show(data, mem, _num, #_type, #_name, _name)
2274 #else
2275 #define print_pubkey_BN(_type, _name, _num) \
2276 do { \
2277 if(_type->_name) { \
2278 pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
2280 } WHILE_FALSE
2281 #endif
2283 static int X509V3_ext(struct SessionHandle *data,
2284 int certnum,
2285 STACK_OF(X509_EXTENSION) *exts)
2287 int i;
2288 size_t j;
2290 if((int)sk_X509_EXTENSION_num(exts) <= 0)
2291 /* no extensions, bail out */
2292 return 1;
2294 for(i=0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
2295 ASN1_OBJECT *obj;
2296 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
2297 BUF_MEM *biomem;
2298 char buf[512];
2299 char *ptr=buf;
2300 char namebuf[128];
2301 BIO *bio_out = BIO_new(BIO_s_mem());
2303 if(!bio_out)
2304 return 1;
2306 obj = X509_EXTENSION_get_object(ext);
2308 asn1_object_dump(obj, namebuf, sizeof(namebuf));
2310 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
2311 ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
2313 BIO_get_mem_ptr(bio_out, &biomem);
2315 for(j = 0; j < (size_t)biomem->length; j++) {
2316 const char *sep="";
2317 if(biomem->data[j] == '\n') {
2318 sep=", ";
2319 j++; /* skip the newline */
2321 while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
2322 j++;
2323 if(j<(size_t)biomem->length)
2324 ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
2325 biomem->data[j]);
2328 Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
2330 BIO_free(bio_out);
2333 return 0; /* all is fine */
2336 static CURLcode get_cert_chain(struct connectdata *conn,
2337 struct ssl_connect_data *connssl)
2340 CURLcode result;
2341 STACK_OF(X509) *sk;
2342 int i;
2343 struct SessionHandle *data = conn->data;
2344 int numcerts;
2345 BIO *mem;
2347 sk = SSL_get_peer_cert_chain(connssl->handle);
2348 if(!sk) {
2349 return CURLE_OUT_OF_MEMORY;
2352 numcerts = sk_X509_num(sk);
2354 result = Curl_ssl_init_certinfo(data, numcerts);
2355 if(result) {
2356 return result;
2359 mem = BIO_new(BIO_s_mem());
2361 for(i = 0; i < numcerts; i++) {
2362 ASN1_INTEGER *num;
2363 X509 *x = sk_X509_value(sk, i);
2364 EVP_PKEY *pubkey=NULL;
2365 int j;
2366 char *ptr;
2367 ASN1_BIT_STRING *psig = NULL;
2369 X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
2370 push_certinfo("Subject", i);
2372 X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
2373 push_certinfo("Issuer", i);
2375 BIO_printf(mem, "%lx", X509_get_version(x));
2376 push_certinfo("Version", i);
2378 num = X509_get_serialNumber(x);
2379 if(num->type == V_ASN1_NEG_INTEGER)
2380 BIO_puts(mem, "-");
2381 for(j = 0; j < num->length; j++)
2382 BIO_printf(mem, "%02x", num->data[j]);
2383 push_certinfo("Serial Number", i);
2385 #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
2387 X509_ALGOR *palg = NULL;
2388 ASN1_STRING *a = ASN1_STRING_new();
2389 if(a) {
2390 X509_get0_signature(&psig, &palg, x);
2391 X509_signature_print(mem, palg, a);
2392 ASN1_STRING_free(a);
2394 if(palg) {
2395 i2a_ASN1_OBJECT(mem, palg->algorithm);
2396 push_certinfo("Public Key Algorithm", i);
2399 X509V3_ext(data, i, X509_get0_extensions(x));
2401 #else
2403 /* before OpenSSL 1.0.2 */
2404 X509_CINF *cinf = x->cert_info;
2406 i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
2407 push_certinfo("Signature Algorithm", i);
2409 i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
2410 push_certinfo("Public Key Algorithm", i);
2412 X509V3_ext(data, i, cinf->extensions);
2414 psig = x->signature;
2416 #endif
2418 ASN1_TIME_print(mem, X509_get_notBefore(x));
2419 push_certinfo("Start date", i);
2421 ASN1_TIME_print(mem, X509_get_notAfter(x));
2422 push_certinfo("Expire date", i);
2424 pubkey = X509_get_pubkey(x);
2425 if(!pubkey)
2426 infof(data, " Unable to load public key\n");
2427 else {
2428 int pktype;
2429 #ifdef HAVE_OPAQUE_EVP_PKEY
2430 pktype = EVP_PKEY_id(pubkey);
2431 #else
2432 pktype = pubkey->type;
2433 #endif
2434 switch(pktype) {
2435 case EVP_PKEY_RSA:
2437 RSA *rsa;
2438 #ifdef HAVE_OPAQUE_EVP_PKEY
2439 rsa = EVP_PKEY_get0_RSA(pubkey);
2440 #else
2441 rsa = pubkey->pkey.rsa;
2442 #endif
2444 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2446 BIGNUM *n;
2447 BIGNUM *e;
2448 BIGNUM *d;
2449 BIGNUM *p;
2450 BIGNUM *q;
2451 BIGNUM *dmp1;
2452 BIGNUM *dmq1;
2453 BIGNUM *iqmp;
2455 RSA_get0_key(rsa, &n, &e, &d);
2456 RSA_get0_factors(rsa, &p, &q);
2457 RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
2458 BN_print(mem, n);
2459 push_certinfo("RSA Public Key", i);
2460 print_pubkey_BN(rsa, n, i);
2461 print_pubkey_BN(rsa, e, i);
2462 print_pubkey_BN(rsa, d, i);
2463 print_pubkey_BN(rsa, p, i);
2464 print_pubkey_BN(rsa, q, i);
2465 print_pubkey_BN(rsa, dmp1, i);
2466 print_pubkey_BN(rsa, dmq1, i);
2467 print_pubkey_BN(rsa, iqmp, i);
2469 #else
2470 BIO_printf(mem, "%d", BN_num_bits(rsa->n));
2471 push_certinfo("RSA Public Key", i);
2472 print_pubkey_BN(rsa, n, i);
2473 print_pubkey_BN(rsa, e, i);
2474 print_pubkey_BN(rsa, d, i);
2475 print_pubkey_BN(rsa, p, i);
2476 print_pubkey_BN(rsa, q, i);
2477 print_pubkey_BN(rsa, dmp1, i);
2478 print_pubkey_BN(rsa, dmq1, i);
2479 print_pubkey_BN(rsa, iqmp, i);
2480 #endif
2482 break;
2484 case EVP_PKEY_DSA:
2486 DSA *dsa;
2487 #ifdef HAVE_OPAQUE_EVP_PKEY
2488 dsa = EVP_PKEY_get0_DSA(pubkey);
2489 #else
2490 dsa = pubkey->pkey.dsa;
2491 #endif
2492 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2494 BIGNUM *p;
2495 BIGNUM *q;
2496 BIGNUM *g;
2497 BIGNUM *priv_key;
2498 BIGNUM *pub_key;
2500 DSA_get0_pqg(dsa, &p, &q, &g);
2501 DSA_get0_key(dsa, &pub_key, &priv_key);
2503 print_pubkey_BN(dsa, p, i);
2504 print_pubkey_BN(dsa, q, i);
2505 print_pubkey_BN(dsa, g, i);
2506 print_pubkey_BN(dsa, priv_key, i);
2507 print_pubkey_BN(dsa, pub_key, i);
2509 #else
2510 print_pubkey_BN(dsa, p, i);
2511 print_pubkey_BN(dsa, q, i);
2512 print_pubkey_BN(dsa, g, i);
2513 print_pubkey_BN(dsa, priv_key, i);
2514 print_pubkey_BN(dsa, pub_key, i);
2515 #endif
2516 break;
2518 case EVP_PKEY_DH:
2520 DH *dh;
2521 #ifdef HAVE_OPAQUE_EVP_PKEY
2522 dh = EVP_PKEY_get0_DH(pubkey);
2523 #else
2524 dh = pubkey->pkey.dh;
2525 #endif
2526 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2528 BIGNUM *p;
2529 BIGNUM *q;
2530 BIGNUM *g;
2531 BIGNUM *priv_key;
2532 BIGNUM *pub_key;
2533 DH_get0_pqg(dh, &p, &q, &g);
2534 DH_get0_key(dh, &pub_key, &priv_key);
2535 print_pubkey_BN(dh, p, i);
2536 print_pubkey_BN(dh, q, i);
2537 print_pubkey_BN(dh, g, i);
2538 print_pubkey_BN(dh, priv_key, i);
2539 print_pubkey_BN(dh, pub_key, i);
2541 #else
2542 print_pubkey_BN(dh, p, i);
2543 print_pubkey_BN(dh, g, i);
2544 print_pubkey_BN(dh, priv_key, i);
2545 print_pubkey_BN(dh, pub_key, i);
2546 #endif
2547 break;
2549 #if 0
2550 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
2551 /* left TODO */
2552 break;
2553 #endif
2555 EVP_PKEY_free(pubkey);
2558 if(psig) {
2559 for(j = 0; j < psig->length; j++)
2560 BIO_printf(mem, "%02x:", psig->data[j]);
2561 push_certinfo("Signature", i);
2564 PEM_write_bio_X509(mem, x);
2565 push_certinfo("Cert", i);
2568 BIO_free(mem);
2570 return CURLE_OK;
2574 * Heavily modified from:
2575 * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
2577 static CURLcode pkp_pin_peer_pubkey(struct SessionHandle *data, X509* cert,
2578 const char *pinnedpubkey)
2580 /* Scratch */
2581 int len1 = 0, len2 = 0;
2582 unsigned char *buff1 = NULL, *temp = NULL;
2584 /* Result is returned to caller */
2585 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
2587 /* if a path wasn't specified, don't pin */
2588 if(!pinnedpubkey)
2589 return CURLE_OK;
2591 if(!cert)
2592 return result;
2594 do {
2595 /* Begin Gyrations to get the subjectPublicKeyInfo */
2596 /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
2598 /* https://groups.google.com/group/mailing.openssl.users/browse_thread
2599 /thread/d61858dae102c6c7 */
2600 len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
2601 if(len1 < 1)
2602 break; /* failed */
2604 /* https://www.openssl.org/docs/crypto/buffer.html */
2605 buff1 = temp = OPENSSL_malloc(len1);
2606 if(!buff1)
2607 break; /* failed */
2609 /* https://www.openssl.org/docs/crypto/d2i_X509.html */
2610 len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
2613 * These checks are verifying we got back the same values as when we
2614 * sized the buffer. It's pretty weak since they should always be the
2615 * same. But it gives us something to test.
2617 if((len1 != len2) || !temp || ((temp - buff1) != len1))
2618 break; /* failed */
2620 /* End Gyrations */
2622 /* The one good exit point */
2623 result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
2624 } while(0);
2626 /* https://www.openssl.org/docs/crypto/buffer.html */
2627 if(buff1)
2628 OPENSSL_free(buff1);
2630 return result;
2634 * Get the server cert, verify it and show it etc, only call failf() if the
2635 * 'strict' argument is TRUE as otherwise all this is for informational
2636 * purposes only!
2638 * We check certificates to authenticate the server; otherwise we risk
2639 * man-in-the-middle attack.
2641 static CURLcode servercert(struct connectdata *conn,
2642 struct ssl_connect_data *connssl,
2643 bool strict)
2645 CURLcode result = CURLE_OK;
2646 int rc;
2647 long lerr, len;
2648 struct SessionHandle *data = conn->data;
2649 X509 *issuer;
2650 FILE *fp;
2651 char *buffer = data->state.buffer;
2652 const char *ptr;
2653 BIO *mem = BIO_new(BIO_s_mem());
2655 if(data->set.ssl.certinfo)
2656 /* we've been asked to gather certificate info! */
2657 (void)get_cert_chain(conn, connssl);
2659 connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
2660 if(!connssl->server_cert) {
2661 if(!strict)
2662 return CURLE_OK;
2664 failf(data, "SSL: couldn't get peer certificate!");
2665 return CURLE_PEER_FAILED_VERIFICATION;
2668 infof(data, "Server certificate:\n");
2670 rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
2671 buffer, BUFSIZE);
2672 infof(data, " subject: %s\n", rc?"[NONE]":buffer);
2674 ASN1_TIME_print(mem, X509_get_notBefore(connssl->server_cert));
2675 len = BIO_get_mem_data(mem, (char **) &ptr);
2676 infof(data, " start date: %.*s\n", len, ptr);
2677 rc = BIO_reset(mem);
2679 ASN1_TIME_print(mem, X509_get_notAfter(connssl->server_cert));
2680 len = BIO_get_mem_data(mem, (char **) &ptr);
2681 infof(data, " expire date: %.*s\n", len, ptr);
2682 rc = BIO_reset(mem);
2684 BIO_free(mem);
2686 if(data->set.ssl.verifyhost) {
2687 result = verifyhost(conn, connssl->server_cert);
2688 if(result) {
2689 X509_free(connssl->server_cert);
2690 connssl->server_cert = NULL;
2691 return result;
2695 rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
2696 buffer, BUFSIZE);
2697 if(rc) {
2698 if(strict)
2699 failf(data, "SSL: couldn't get X509-issuer name!");
2700 result = CURLE_SSL_CONNECT_ERROR;
2702 else {
2703 infof(data, " issuer: %s\n", buffer);
2705 /* We could do all sorts of certificate verification stuff here before
2706 deallocating the certificate. */
2708 /* e.g. match issuer name with provided issuer certificate */
2709 if(data->set.str[STRING_SSL_ISSUERCERT]) {
2710 fp = fopen(data->set.str[STRING_SSL_ISSUERCERT], FOPEN_READTEXT);
2711 if(!fp) {
2712 if(strict)
2713 failf(data, "SSL: Unable to open issuer cert (%s)",
2714 data->set.str[STRING_SSL_ISSUERCERT]);
2715 X509_free(connssl->server_cert);
2716 connssl->server_cert = NULL;
2717 return CURLE_SSL_ISSUER_ERROR;
2720 issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL);
2721 if(!issuer) {
2722 if(strict)
2723 failf(data, "SSL: Unable to read issuer cert (%s)",
2724 data->set.str[STRING_SSL_ISSUERCERT]);
2725 X509_free(connssl->server_cert);
2726 X509_free(issuer);
2727 fclose(fp);
2728 return CURLE_SSL_ISSUER_ERROR;
2731 fclose(fp);
2733 if(X509_check_issued(issuer, connssl->server_cert) != X509_V_OK) {
2734 if(strict)
2735 failf(data, "SSL: Certificate issuer check failed (%s)",
2736 data->set.str[STRING_SSL_ISSUERCERT]);
2737 X509_free(connssl->server_cert);
2738 X509_free(issuer);
2739 connssl->server_cert = NULL;
2740 return CURLE_SSL_ISSUER_ERROR;
2743 infof(data, " SSL certificate issuer check ok (%s)\n",
2744 data->set.str[STRING_SSL_ISSUERCERT]);
2745 X509_free(issuer);
2748 lerr = data->set.ssl.certverifyresult =
2749 SSL_get_verify_result(connssl->handle);
2751 if(data->set.ssl.certverifyresult != X509_V_OK) {
2752 if(data->set.ssl.verifypeer) {
2753 /* We probably never reach this, because SSL_connect() will fail
2754 and we return earlier if verifypeer is set? */
2755 if(strict)
2756 failf(data, "SSL certificate verify result: %s (%ld)",
2757 X509_verify_cert_error_string(lerr), lerr);
2758 result = CURLE_PEER_FAILED_VERIFICATION;
2760 else
2761 infof(data, " SSL certificate verify result: %s (%ld),"
2762 " continuing anyway.\n",
2763 X509_verify_cert_error_string(lerr), lerr);
2765 else
2766 infof(data, " SSL certificate verify ok.\n");
2769 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
2770 !defined(OPENSSL_NO_OCSP)
2771 if(data->set.ssl.verifystatus) {
2772 result = verifystatus(conn, connssl);
2773 if(result) {
2774 X509_free(connssl->server_cert);
2775 connssl->server_cert = NULL;
2776 return result;
2779 #endif
2781 if(!strict)
2782 /* when not strict, we don't bother about the verify cert problems */
2783 result = CURLE_OK;
2785 ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
2786 if(!result && ptr) {
2787 result = pkp_pin_peer_pubkey(data, connssl->server_cert, ptr);
2788 if(result)
2789 failf(data, "SSL: public key does not match pinned public key!");
2792 X509_free(connssl->server_cert);
2793 connssl->server_cert = NULL;
2794 connssl->connecting_state = ssl_connect_done;
2796 return result;
2799 static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
2801 CURLcode result = CURLE_OK;
2802 void *old_ssl_sessionid = NULL;
2803 struct SessionHandle *data = conn->data;
2804 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2805 bool incache;
2806 SSL_SESSION *our_ssl_sessionid;
2808 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
2810 our_ssl_sessionid = SSL_get1_session(connssl->handle);
2812 /* SSL_get1_session() will increment the reference count and the session
2813 will stay in memory until explicitly freed with SSL_SESSION_free(3),
2814 regardless of its state. */
2816 incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL));
2817 if(incache) {
2818 if(old_ssl_sessionid != our_ssl_sessionid) {
2819 infof(data, "old SSL session ID is stale, removing\n");
2820 Curl_ssl_delsessionid(conn, old_ssl_sessionid);
2821 incache = FALSE;
2825 if(!incache) {
2826 result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
2827 0 /* unknown size */);
2828 if(result) {
2829 failf(data, "failed to store ssl session");
2830 return result;
2833 else {
2834 /* Session was incache, so refcount already incremented earlier.
2835 * Avoid further increments with each SSL_get1_session() call.
2836 * This does not free the session as refcount remains > 0
2838 SSL_SESSION_free(our_ssl_sessionid);
2842 * We check certificates to authenticate the server; otherwise we risk
2843 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
2844 * verify the peer ignore faults and failures from the server cert
2845 * operations.
2848 result = servercert(conn, connssl,
2849 (data->set.ssl.verifypeer || data->set.ssl.verifyhost));
2851 if(!result)
2852 connssl->connecting_state = ssl_connect_done;
2854 return result;
2857 static Curl_recv ossl_recv;
2858 static Curl_send ossl_send;
2860 static CURLcode ossl_connect_common(struct connectdata *conn,
2861 int sockindex,
2862 bool nonblocking,
2863 bool *done)
2865 CURLcode result;
2866 struct SessionHandle *data = conn->data;
2867 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2868 curl_socket_t sockfd = conn->sock[sockindex];
2869 long timeout_ms;
2870 int what;
2872 /* check if the connection has already been established */
2873 if(ssl_connection_complete == connssl->state) {
2874 *done = TRUE;
2875 return CURLE_OK;
2878 if(ssl_connect_1 == connssl->connecting_state) {
2879 /* Find out how much more time we're allowed */
2880 timeout_ms = Curl_timeleft(data, NULL, TRUE);
2882 if(timeout_ms < 0) {
2883 /* no need to continue if time already is up */
2884 failf(data, "SSL connection timeout");
2885 return CURLE_OPERATION_TIMEDOUT;
2888 result = ossl_connect_step1(conn, sockindex);
2889 if(result)
2890 return result;
2893 while(ssl_connect_2 == connssl->connecting_state ||
2894 ssl_connect_2_reading == connssl->connecting_state ||
2895 ssl_connect_2_writing == connssl->connecting_state) {
2897 /* check allowed time left */
2898 timeout_ms = Curl_timeleft(data, NULL, TRUE);
2900 if(timeout_ms < 0) {
2901 /* no need to continue if time already is up */
2902 failf(data, "SSL connection timeout");
2903 return CURLE_OPERATION_TIMEDOUT;
2906 /* if ssl is expecting something, check if it's available. */
2907 if(connssl->connecting_state == ssl_connect_2_reading ||
2908 connssl->connecting_state == ssl_connect_2_writing) {
2910 curl_socket_t writefd = ssl_connect_2_writing==
2911 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
2912 curl_socket_t readfd = ssl_connect_2_reading==
2913 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
2915 what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms);
2916 if(what < 0) {
2917 /* fatal error */
2918 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
2919 return CURLE_SSL_CONNECT_ERROR;
2921 else if(0 == what) {
2922 if(nonblocking) {
2923 *done = FALSE;
2924 return CURLE_OK;
2926 else {
2927 /* timeout */
2928 failf(data, "SSL connection timeout");
2929 return CURLE_OPERATION_TIMEDOUT;
2932 /* socket is readable or writable */
2935 /* Run transaction, and return to the caller if it failed or if this
2936 * connection is done nonblocking and this loop would execute again. This
2937 * permits the owner of a multi handle to abort a connection attempt
2938 * before step2 has completed while ensuring that a client using select()
2939 * or epoll() will always have a valid fdset to wait on.
2941 result = ossl_connect_step2(conn, sockindex);
2942 if(result || (nonblocking &&
2943 (ssl_connect_2 == connssl->connecting_state ||
2944 ssl_connect_2_reading == connssl->connecting_state ||
2945 ssl_connect_2_writing == connssl->connecting_state)))
2946 return result;
2948 } /* repeat step2 until all transactions are done. */
2950 if(ssl_connect_3 == connssl->connecting_state) {
2951 result = ossl_connect_step3(conn, sockindex);
2952 if(result)
2953 return result;
2956 if(ssl_connect_done == connssl->connecting_state) {
2957 connssl->state = ssl_connection_complete;
2958 conn->recv[sockindex] = ossl_recv;
2959 conn->send[sockindex] = ossl_send;
2960 *done = TRUE;
2962 else
2963 *done = FALSE;
2965 /* Reset our connect state machine */
2966 connssl->connecting_state = ssl_connect_1;
2968 return CURLE_OK;
2971 CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
2972 int sockindex,
2973 bool *done)
2975 return ossl_connect_common(conn, sockindex, TRUE, done);
2978 CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
2980 CURLcode result;
2981 bool done = FALSE;
2983 result = ossl_connect_common(conn, sockindex, FALSE, &done);
2984 if(result)
2985 return result;
2987 DEBUGASSERT(done);
2989 return CURLE_OK;
2992 bool Curl_ossl_data_pending(const struct connectdata *conn, int connindex)
2994 if(conn->ssl[connindex].handle)
2995 /* SSL is in use */
2996 return (0 != SSL_pending(conn->ssl[connindex].handle)) ? TRUE : FALSE;
2997 else
2998 return FALSE;
3001 static ssize_t ossl_send(struct connectdata *conn,
3002 int sockindex,
3003 const void *mem,
3004 size_t len,
3005 CURLcode *curlcode)
3007 /* SSL_write() is said to return 'int' while write() and send() returns
3008 'size_t' */
3009 int err;
3010 char error_buffer[120]; /* OpenSSL documents that this must be at least 120
3011 bytes long. */
3012 unsigned long sslerror;
3013 int memlen;
3014 int rc;
3016 ERR_clear_error();
3018 memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
3019 rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
3021 if(rc <= 0) {
3022 err = SSL_get_error(conn->ssl[sockindex].handle, rc);
3024 switch(err) {
3025 case SSL_ERROR_WANT_READ:
3026 case SSL_ERROR_WANT_WRITE:
3027 /* The operation did not complete; the same TLS/SSL I/O function
3028 should be called again later. This is basically an EWOULDBLOCK
3029 equivalent. */
3030 *curlcode = CURLE_AGAIN;
3031 return -1;
3032 case SSL_ERROR_SYSCALL:
3033 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
3034 SOCKERRNO);
3035 *curlcode = CURLE_SEND_ERROR;
3036 return -1;
3037 case SSL_ERROR_SSL:
3038 /* A failure in the SSL library occurred, usually a protocol error.
3039 The OpenSSL error queue contains more information on the error. */
3040 sslerror = ERR_get_error();
3041 failf(conn->data, "SSL_write() error: %s",
3042 ERR_error_string(sslerror, error_buffer));
3043 *curlcode = CURLE_SEND_ERROR;
3044 return -1;
3046 /* a true error */
3047 failf(conn->data, "SSL_write() return error %d", err);
3048 *curlcode = CURLE_SEND_ERROR;
3049 return -1;
3051 *curlcode = CURLE_OK;
3052 return (ssize_t)rc; /* number of bytes */
3055 static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
3056 int num, /* socketindex */
3057 char *buf, /* store read data here */
3058 size_t buffersize, /* max amount to read */
3059 CURLcode *curlcode)
3061 char error_buffer[120]; /* OpenSSL documents that this must be at
3062 least 120 bytes long. */
3063 unsigned long sslerror;
3064 ssize_t nread;
3065 int buffsize;
3067 ERR_clear_error();
3069 buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
3070 nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize);
3071 if(nread <= 0) {
3072 /* failed SSL_read */
3073 int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
3075 switch(err) {
3076 case SSL_ERROR_NONE: /* this is not an error */
3077 case SSL_ERROR_ZERO_RETURN: /* no more data */
3078 break;
3079 case SSL_ERROR_WANT_READ:
3080 case SSL_ERROR_WANT_WRITE:
3081 /* there's data pending, re-invoke SSL_read() */
3082 *curlcode = CURLE_AGAIN;
3083 return -1;
3084 default:
3085 /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
3086 value/errno" */
3087 /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
3088 sslerror = ERR_get_error();
3089 if((nread < 0) || sslerror) {
3090 /* If the return code was negative or there actually is an error in the
3091 queue */
3092 failf(conn->data, "SSL read: %s, errno %d",
3093 ERR_error_string(sslerror, error_buffer),
3094 SOCKERRNO);
3095 *curlcode = CURLE_RECV_ERROR;
3096 return -1;
3100 return nread;
3103 size_t Curl_ossl_version(char *buffer, size_t size)
3105 #ifdef OPENSSL_IS_BORINGSSL
3106 return snprintf(buffer, size, OSSL_PACKAGE);
3107 #else /* OPENSSL_IS_BORINGSSL */
3108 char sub[3];
3109 unsigned long ssleay_value;
3110 sub[2]='\0';
3111 sub[1]='\0';
3112 ssleay_value=SSLeay();
3113 if(ssleay_value < 0x906000) {
3114 ssleay_value=SSLEAY_VERSION_NUMBER;
3115 sub[0]='\0';
3117 else {
3118 if(ssleay_value&0xff0) {
3119 int minor_ver = (ssleay_value >> 4) & 0xff;
3120 if(minor_ver > 26) {
3121 /* handle extended version introduced for 0.9.8za */
3122 sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
3123 sub[0] = 'z';
3125 else {
3126 sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1);
3129 else
3130 sub[0]='\0';
3133 return snprintf(buffer, size, "%s/%lx.%lx.%lx%s",
3134 OSSL_PACKAGE,
3135 (ssleay_value>>28)&0xf,
3136 (ssleay_value>>20)&0xff,
3137 (ssleay_value>>12)&0xff,
3138 sub);
3139 #endif /* OPENSSL_IS_BORINGSSL */
3142 /* can be called with data == NULL */
3143 int Curl_ossl_random(struct SessionHandle *data, unsigned char *entropy,
3144 size_t length)
3146 if(data) {
3147 Curl_ossl_seed(data); /* Initiate the seed if not already done */
3149 RAND_bytes(entropy, curlx_uztosi(length));
3150 return 0; /* 0 as in no problem */
3153 void Curl_ossl_md5sum(unsigned char *tmp, /* input */
3154 size_t tmplen,
3155 unsigned char *md5sum /* output */,
3156 size_t unused)
3158 MD5_CTX MD5pw;
3159 (void)unused;
3160 MD5_Init(&MD5pw);
3161 MD5_Update(&MD5pw, tmp, tmplen);
3162 MD5_Final(md5sum, &MD5pw);
3165 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3166 void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
3167 size_t tmplen,
3168 unsigned char *sha256sum /* output */,
3169 size_t unused)
3171 SHA256_CTX SHA256pw;
3172 (void)unused;
3173 SHA256_Init(&SHA256pw);
3174 SHA256_Update(&SHA256pw, tmp, tmplen);
3175 SHA256_Final(sha256sum, &SHA256pw);
3177 #endif
3179 bool Curl_ossl_cert_status_request(void)
3181 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3182 !defined(OPENSSL_NO_OCSP)
3183 return TRUE;
3184 #else
3185 return FALSE;
3186 #endif
3188 #endif /* USE_OPENSSL */