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