2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright 2005 Nokia. All rights reserved.
5 * Licensed under the OpenSSL license (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
17 #include <openssl/e_os2.h>
19 #ifndef OPENSSL_NO_SOCK
22 * With IPv6, it looks like Digital has mixed up the proper order of
23 * recursive header file inclusion, resulting in the compiler complaining
24 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
25 * needed to have fileno() declared correctly... So let's define u_int
27 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
29 typedef unsigned int u_int;
33 #include <openssl/x509.h>
34 #include <openssl/ssl.h>
35 #include <openssl/err.h>
36 #include <openssl/pem.h>
37 #include <openssl/rand.h>
38 #include <openssl/ocsp.h>
39 #include <openssl/bn.h>
40 #include <openssl/async.h>
41 #ifndef OPENSSL_NO_SRP
42 # include <openssl/srp.h>
45 # include <openssl/ct.h>
49 #include "internal/sockets.h"
51 #if defined(__has_feature)
52 # if __has_feature(memory_sanitizer)
53 # include <sanitizer/msan_interface.h>
58 #define BUFSIZZ 1024*8
59 #define S_CLIENT_IRC_READ_TIMEOUT 8
62 static int c_debug = 0;
63 static int c_showcerts = 0;
64 static char *keymatexportlabel = NULL;
65 static int keymatexportlen = 20;
66 static BIO *bio_c_out = NULL;
67 static int c_quiet = 0;
68 static char *sess_out = NULL;
69 static SSL_SESSION *psksess = NULL;
71 static void print_stuff(BIO *berr, SSL *con, int full);
72 #ifndef OPENSSL_NO_OCSP
73 static int ocsp_resp_cb(SSL *s, void *arg);
75 static int ldap_ExtendedResponse_parse(const char *buf, long rem);
77 static int saved_errno;
79 static void save_errno(void)
85 static int restore_errno(void)
92 static void do_ssl_shutdown(SSL *ssl)
97 /* We only do unidirectional shutdown */
98 ret = SSL_shutdown(ssl);
100 switch (SSL_get_error(ssl, ret)) {
101 case SSL_ERROR_WANT_READ:
102 case SSL_ERROR_WANT_WRITE:
103 case SSL_ERROR_WANT_ASYNC:
104 case SSL_ERROR_WANT_ASYNC_JOB:
105 /* We just do busy waiting. Nothing clever */
113 /* Default PSK identity and key */
114 static char *psk_identity = "Client_identity";
116 #ifndef OPENSSL_NO_PSK
117 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
118 unsigned int max_identity_len,
120 unsigned int max_psk_len)
127 BIO_printf(bio_c_out, "psk_client_cb\n");
129 /* no ServerKeyExchange message */
131 BIO_printf(bio_c_out,
132 "NULL received PSK identity hint, continuing anyway\n");
133 } else if (c_debug) {
134 BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
138 * lookup PSK identity and PSK key based on the given identity hint here
140 ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
141 if (ret < 0 || (unsigned int)ret > max_identity_len)
144 BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
147 /* convert the PSK key to binary */
148 key = OPENSSL_hexstr2buf(psk_key, &key_len);
150 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
154 if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
156 "psk buffer of callback is too small (%d) for key (%ld)\n",
157 max_psk_len, key_len);
162 memcpy(psk, key, key_len);
166 BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
171 BIO_printf(bio_err, "Error in PSK client callback\n");
176 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
177 const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
179 static int psk_use_session_cb(SSL *s, const EVP_MD *md,
180 const unsigned char **id, size_t *idlen,
183 SSL_SESSION *usesess = NULL;
184 const SSL_CIPHER *cipher = NULL;
186 if (psksess != NULL) {
187 SSL_SESSION_up_ref(psksess);
191 unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
194 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
199 if (key_len == EVP_MD_size(EVP_sha256()))
200 cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
201 else if (key_len == EVP_MD_size(EVP_sha384()))
202 cipher = SSL_CIPHER_find(s, tls13_aes256gcmsha384_id);
204 if (cipher == NULL) {
205 /* Doesn't look like a suitable TLSv1.3 key. Ignore it */
212 usesess = SSL_SESSION_new();
214 || !SSL_SESSION_set1_master_key(usesess, key, key_len)
215 || !SSL_SESSION_set_cipher(usesess, cipher)
216 || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
223 cipher = SSL_SESSION_get0_cipher(usesess);
227 if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
228 /* PSK not usable, ignore it */
232 SSL_SESSION_free(usesess);
235 *id = (unsigned char *)psk_identity;
236 *idlen = strlen(psk_identity);
242 SSL_SESSION_free(usesess);
246 /* This is a context that we pass to callbacks */
247 typedef struct tlsextctx_st {
252 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
254 tlsextctx *p = (tlsextctx *) arg;
255 const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
256 if (SSL_get_servername_type(s) != -1)
257 p->ack = !SSL_session_reused(s) && hn != NULL;
259 BIO_printf(bio_err, "Can't use SSL_get_servername\n");
261 return SSL_TLSEXT_ERR_OK;
264 #ifndef OPENSSL_NO_SRP
266 /* This is a context that we pass to all callbacks */
267 typedef struct srp_arg_st {
270 int msg; /* copy from c_msg */
271 int debug; /* copy from c_debug */
272 int amp; /* allow more groups */
273 int strength; /* minimal size for N */
276 # define SRP_NUMBER_ITERATIONS_FOR_PRIME 64
278 static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g)
280 BN_CTX *bn_ctx = BN_CTX_new();
281 BIGNUM *p = BN_new();
282 BIGNUM *r = BN_new();
284 g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
285 BN_is_prime_ex(N, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) == 1 &&
286 p != NULL && BN_rshift1(p, N) &&
288 BN_is_prime_ex(p, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) == 1 &&
290 /* verify g^((N-1)/2) == -1 (mod N) */
291 BN_mod_exp(r, g, p, N, bn_ctx) &&
292 BN_add_word(r, 1) && BN_cmp(r, N) == 0;
301 * This callback is used here for two purposes:
302 * - extended debugging
303 * - making some primality tests for unknown groups
304 * The callback is only called for a non default group.
306 * An application does not need the call back at all if
307 * only the standard groups are used. In real life situations,
308 * client and server already share well known groups,
309 * thus there is no need to verify them.
310 * Furthermore, in case that a server actually proposes a group that
311 * is not one of those defined in RFC 5054, it is more appropriate
312 * to add the group to a static list and then compare since
313 * primality tests are rather cpu consuming.
316 static int ssl_srp_verify_param_cb(SSL *s, void *arg)
318 SRP_ARG *srp_arg = (SRP_ARG *)arg;
319 BIGNUM *N = NULL, *g = NULL;
321 if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL))
323 if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
324 BIO_printf(bio_err, "SRP parameters:\n");
325 BIO_printf(bio_err, "\tN=");
326 BN_print(bio_err, N);
327 BIO_printf(bio_err, "\n\tg=");
328 BN_print(bio_err, g);
329 BIO_printf(bio_err, "\n");
332 if (SRP_check_known_gN_param(g, N))
335 if (srp_arg->amp == 1) {
338 "SRP param N and g are not known params, going to check deeper.\n");
341 * The srp_moregroups is a real debugging feature. Implementors
342 * should rather add the value to the known ones. The minimal size
343 * has already been tested.
345 if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
348 BIO_printf(bio_err, "SRP param N and g rejected.\n");
352 # define PWD_STRLEN 1024
354 static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
356 SRP_ARG *srp_arg = (SRP_ARG *)arg;
357 char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer");
361 cb_tmp.password = (char *)srp_arg->srppassin;
362 cb_tmp.prompt_info = "SRP user";
363 if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
364 BIO_printf(bio_err, "Can't read Password\n");
375 static char *srtp_profiles = NULL;
377 #ifndef OPENSSL_NO_NEXTPROTONEG
378 /* This the context that we pass to next_proto_cb */
379 typedef struct tlsextnextprotoctx_st {
383 } tlsextnextprotoctx;
385 static tlsextnextprotoctx next_proto;
387 static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
388 const unsigned char *in, unsigned int inlen,
391 tlsextnextprotoctx *ctx = arg;
394 /* We can assume that |in| is syntactically valid. */
396 BIO_printf(bio_c_out, "Protocols advertised by server: ");
397 for (i = 0; i < inlen;) {
399 BIO_write(bio_c_out, ", ", 2);
400 BIO_write(bio_c_out, &in[i + 1], in[i]);
403 BIO_write(bio_c_out, "\n", 1);
407 SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
408 return SSL_TLSEXT_ERR_OK;
410 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
412 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
413 const unsigned char *in, size_t inlen,
417 unsigned char ext_buf[4 + 65536];
419 /* Reconstruct the type/len fields prior to extension data */
420 inlen &= 0xffff; /* for formal memcmpy correctness */
421 ext_buf[0] = (unsigned char)(ext_type >> 8);
422 ext_buf[1] = (unsigned char)(ext_type);
423 ext_buf[2] = (unsigned char)(inlen >> 8);
424 ext_buf[3] = (unsigned char)(inlen);
425 memcpy(ext_buf + 4, in, inlen);
427 BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
429 PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
434 * Hex decoder that tolerates optional whitespace. Returns number of bytes
435 * produced, advances inptr to end of input string.
437 static ossl_ssize_t hexdecode(const char **inptr, void *result)
439 unsigned char **out = (unsigned char **)result;
440 const char *in = *inptr;
441 unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
442 unsigned char *cp = ret;
449 for (byte = 0; *in; ++in) {
452 if (isspace(_UC(*in)))
454 x = OPENSSL_hexchar2int(*in);
460 if ((nibble ^= 1) == 0) {
473 return cp - (*out = ret);
477 * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
478 * inptr to next field skipping leading whitespace.
480 static ossl_ssize_t checked_uint8(const char **inptr, void *out)
482 uint8_t *result = (uint8_t *)out;
483 const char *in = *inptr;
489 v = strtol(in, &endp, 10);
492 if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
493 endp == in || !isspace(_UC(*endp)) ||
494 v != (*result = (uint8_t) v)) {
497 for (in = endp; isspace(_UC(*in)); ++in)
507 ossl_ssize_t (*parser)(const char **, void *);
510 static int tlsa_import_rr(SSL *con, const char *rrdata)
512 /* Not necessary to re-init these values; the "parsers" do that. */
513 static uint8_t usage;
514 static uint8_t selector;
515 static uint8_t mtype;
516 static unsigned char *data;
517 static struct tlsa_field tlsa_fields[] = {
518 { &usage, "usage", checked_uint8 },
519 { &selector, "selector", checked_uint8 },
520 { &mtype, "mtype", checked_uint8 },
521 { &data, "data", hexdecode },
524 struct tlsa_field *f;
526 const char *cp = rrdata;
527 ossl_ssize_t len = 0;
529 for (f = tlsa_fields; f->var; ++f) {
530 /* Returns number of bytes produced, advances cp to next field */
531 if ((len = f->parser(&cp, f->var)) <= 0) {
532 BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
533 prog, f->name, rrdata);
537 /* The data field is last, so len is its length */
538 ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
542 ERR_print_errors(bio_err);
543 BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
548 ERR_print_errors(bio_err);
549 BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
556 static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
558 int num = sk_OPENSSL_STRING_num(rrset);
562 for (i = 0; i < num; ++i) {
563 char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
564 if (tlsa_import_rr(con, rrdata) > 0)
570 typedef enum OPTION_choice {
571 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
572 OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_UNIX,
573 OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT,
574 OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
575 OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
576 OPT_BRIEF, OPT_PREXIT, OPT_CRLF, OPT_QUIET, OPT_NBIO,
577 OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF,
578 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
579 OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
580 OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
581 OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS,
582 #ifndef OPENSSL_NO_SRP
583 OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER,
586 OPT_SSL3, OPT_SSL_CONFIG,
587 OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
588 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS,
589 OPT_CERT_CHAIN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
590 OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE,
591 OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_NEXTPROTONEG, OPT_ALPN,
592 OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC,
593 OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST,
594 OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES,
595 OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE,
599 OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_PROXY, OPT_DANE_TLSA_DOMAIN,
600 #ifndef OPENSSL_NO_CT
601 OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
603 OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME,
607 const OPTIONS s_client_options[] = {
608 {"help", OPT_HELP, '-', "Display this summary"},
609 {"host", OPT_HOST, 's', "Use -connect instead"},
610 {"port", OPT_PORT, 'p', "Use -connect instead"},
611 {"connect", OPT_CONNECT, 's',
612 "TCP/IP where to connect (default is :" PORT ")"},
613 {"proxy", OPT_PROXY, 's',
614 "Connect to via specified proxy to the real server"},
616 {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"},
618 {"4", OPT_4, '-', "Use IPv4 only"},
620 {"6", OPT_6, '-', "Use IPv6 only"},
622 {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
623 {"cert", OPT_CERT, '<', "Certificate file to use, PEM format assumed"},
624 {"certform", OPT_CERTFORM, 'F',
625 "Certificate format (PEM or DER) PEM default"},
626 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
627 {"key", OPT_KEY, 's', "Private key file to use, if not in -cert file"},
628 {"keyform", OPT_KEYFORM, 'E', "Key format (PEM, DER or engine) PEM default"},
629 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
630 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
631 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
632 {"no-CAfile", OPT_NOCAFILE, '-',
633 "Do not load the default certificates file"},
634 {"no-CApath", OPT_NOCAPATH, '-',
635 "Do not load certificates from the default certificates directory"},
636 {"requestCAfile", OPT_REQCAFILE, '<',
637 "PEM format file of CA names to send to the server"},
638 {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
639 {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
640 "DANE TLSA rrdata presentation form"},
641 {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
642 "Disable name checks when matching DANE-EE(3) TLSA records"},
643 {"reconnect", OPT_RECONNECT, '-',
644 "Drop and re-make the connection with the same Session-ID"},
645 {"showcerts", OPT_SHOWCERTS, '-', "Show all certificates in the chain"},
646 {"debug", OPT_DEBUG, '-', "Extra output"},
647 {"msg", OPT_MSG, '-', "Show protocol messages"},
648 {"msgfile", OPT_MSGFILE, '>',
649 "File to send output of -msg or -trace, instead of stdout"},
650 {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
651 {"state", OPT_STATE, '-', "Print the ssl states"},
652 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
653 {"quiet", OPT_QUIET, '-', "No s_client output"},
654 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
655 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
656 {"starttls", OPT_STARTTLS, 's',
657 "Use the appropriate STARTTLS command before starting TLS"},
658 {"xmpphost", OPT_XMPPHOST, 's',
659 "Alias of -name option for \"-starttls xmpp[-server]\""},
661 {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
662 {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
663 {"use_srtp", OPT_USE_SRTP, 's',
664 "Offer SRTP key management with a colon-separated profile list"},
665 {"keymatexport", OPT_KEYMATEXPORT, 's',
666 "Export keying material using label"},
667 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
668 "Export len bytes of keying material (default 20)"},
669 {"maxfraglen", OPT_MAXFRAGLEN, 'p',
670 "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
671 {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
672 {"name", OPT_PROTOHOST, 's',
673 "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
674 {"CRL", OPT_CRL, '<', "CRL file to use"},
675 {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
676 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
677 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
678 "Close connection on verification error"},
679 {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
680 {"brief", OPT_BRIEF, '-',
681 "Restrict output to brief summary of connection parameters"},
682 {"prexit", OPT_PREXIT, '-',
683 "Print session information when the program exits"},
684 {"security_debug", OPT_SECURITY_DEBUG, '-',
685 "Enable security debug messages"},
686 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
687 "Output more security debug output"},
688 {"cert_chain", OPT_CERT_CHAIN, '<',
689 "Certificate chain file (in PEM format)"},
690 {"chainCApath", OPT_CHAINCAPATH, '/',
691 "Use dir as certificate store path to build CA certificate chain"},
692 {"verifyCApath", OPT_VERIFYCAPATH, '/',
693 "Use dir as certificate store path to verify CA certificate"},
694 {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
695 {"chainCAfile", OPT_CHAINCAFILE, '<',
696 "CA file for certificate chain (PEM format)"},
697 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
698 "CA file for certificate verification (PEM format)"},
699 {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
700 {"servername", OPT_SERVERNAME, 's',
701 "Set TLS extension servername (SNI) in ClientHello (default)"},
702 {"noservername", OPT_NOSERVERNAME, '-',
703 "Do not send the server name (SNI) extension in the ClientHello"},
704 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
705 "Hex dump of all TLS extensions received"},
706 #ifndef OPENSSL_NO_OCSP
707 {"status", OPT_STATUS, '-', "Request certificate status from server"},
709 {"serverinfo", OPT_SERVERINFO, 's',
710 "types Send empty ClientHello extensions (comma-separated numbers)"},
711 {"alpn", OPT_ALPN, 's',
712 "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
713 {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
714 {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified configuration file"},
715 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
716 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
717 "Size used to split data for encrypt pipelines"},
718 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
719 "Maximum number of encrypt/decrypt pipelines to be used"},
720 {"read_buf", OPT_READ_BUF, 'p',
721 "Default read buffer size to be used for connections"},
725 #ifndef OPENSSL_NO_SSL3
726 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
728 #ifndef OPENSSL_NO_TLS1
729 {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
731 #ifndef OPENSSL_NO_TLS1_1
732 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
734 #ifndef OPENSSL_NO_TLS1_2
735 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
737 #ifndef OPENSSL_NO_TLS1_3
738 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
740 #ifndef OPENSSL_NO_DTLS
741 {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
742 {"timeout", OPT_TIMEOUT, '-',
743 "Enable send/receive timeout on DTLS connections"},
744 {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
746 #ifndef OPENSSL_NO_DTLS1
747 {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
749 #ifndef OPENSSL_NO_DTLS1_2
750 {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
752 #ifndef OPENSSL_NO_SCTP
753 {"sctp", OPT_SCTP, '-', "Use SCTP"},
755 #ifndef OPENSSL_NO_SSL_TRACE
756 {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
759 {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
761 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
762 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
763 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
764 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
765 #ifndef OPENSSL_NO_SRP
766 {"srpuser", OPT_SRPUSER, 's', "SRP authentication for 'user'"},
767 {"srppass", OPT_SRPPASS, 's', "Password for 'user'"},
768 {"srp_lateuser", OPT_SRP_LATEUSER, '-',
769 "SRP username into second ClientHello message"},
770 {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
771 "Tolerate other than the known g N values."},
772 {"srp_strength", OPT_SRP_STRENGTH, 'p', "Minimal length in bits for N"},
774 #ifndef OPENSSL_NO_NEXTPROTONEG
775 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
776 "Enable NPN extension, considering named protocols supported (comma-separated list)"},
778 #ifndef OPENSSL_NO_ENGINE
779 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
780 {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
781 "Specify engine to be used for client certificate operations"},
783 #ifndef OPENSSL_NO_CT
784 {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
785 {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
786 {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
788 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
789 {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"},
790 {NULL, OPT_EOF, 0x00, NULL}
793 typedef enum PROTOCOL_choice {
812 static const OPT_PAIR services[] = {
813 {"smtp", PROTO_SMTP},
814 {"pop3", PROTO_POP3},
815 {"imap", PROTO_IMAP},
817 {"xmpp", PROTO_XMPP},
818 {"xmpp-server", PROTO_XMPP_SERVER},
819 {"telnet", PROTO_TELNET},
821 {"mysql", PROTO_MYSQL},
822 {"postgres", PROTO_POSTGRES},
823 {"lmtp", PROTO_LMTP},
824 {"nntp", PROTO_NNTP},
825 {"sieve", PROTO_SIEVE},
826 {"ldap", PROTO_LDAP},
830 #define IS_INET_FLAG(o) \
831 (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
832 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
834 #define IS_PROT_FLAG(o) \
835 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
836 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
838 /* Free |*dest| and optionally set it to a copy of |source|. */
839 static void freeandcopy(char **dest, const char *source)
844 *dest = OPENSSL_strdup(source);
847 static int new_session_cb(SSL *S, SSL_SESSION *sess)
849 BIO *stmp = BIO_new_file(sess_out, "w");
852 BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
854 PEM_write_bio_SSL_SESSION(stmp, sess);
859 * We always return a "fail" response so that the session gets freed again
860 * because we haven't used the reference.
865 int s_client_main(int argc, char **argv)
868 EVP_PKEY *key = NULL;
871 STACK_OF(X509) *chain = NULL;
873 X509_VERIFY_PARAM *vpm = NULL;
874 SSL_EXCERT *exc = NULL;
875 SSL_CONF_CTX *cctx = NULL;
876 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
877 char *dane_tlsa_domain = NULL;
878 STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
879 int dane_ee_no_name = 0;
880 STACK_OF(X509_CRL) *crls = NULL;
881 const SSL_METHOD *meth = TLS_client_method();
882 const char *CApath = NULL, *CAfile = NULL;
883 char *cbuf = NULL, *sbuf = NULL;
884 char *mbuf = NULL, *proxystr = NULL, *connectstr = NULL;
885 char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
886 char *chCApath = NULL, *chCAfile = NULL, *host = NULL;
887 char *port = OPENSSL_strdup(PORT);
888 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
889 char *ReqCAfile = NULL;
890 char *sess_in = NULL, *crl_file = NULL, *p;
891 const char *protohost = NULL;
892 struct timeval timeout, *timeoutp;
893 fd_set readfds, writefds;
894 int noCApath = 0, noCAfile = 0;
895 int build_chain = 0, cbuf_len, cbuf_off, cert_format = FORMAT_PEM;
896 int key_format = FORMAT_PEM, crlf = 0, full_log = 1, mbuf_len = 0;
899 int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
900 int ret = 1, in_init = 1, i, nbio_test = 0, s = -1, k, width, state = 0;
901 int sbuf_len, sbuf_off, cmdletters = 1;
902 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
903 int starttls_proto = PROTO_OFF, crl_format = FORMAT_PEM, crl_download = 0;
904 int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
905 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
908 int read_buf_len = 0;
909 int fallback_scsv = 0;
911 #ifndef OPENSSL_NO_DTLS
912 int enable_timeouts = 0;
915 #ifndef OPENSSL_NO_ENGINE
916 ENGINE *ssl_client_engine = NULL;
919 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
922 const char *servername = NULL;
923 int noservername = 0;
924 const char *alpn_in = NULL;
925 tlsextctx tlsextcbp = { NULL, 0 };
926 const char *ssl_config = NULL;
927 #define MAX_SI_TYPES 100
928 unsigned short serverinfo_types[MAX_SI_TYPES];
929 int serverinfo_count = 0, start = 0, len;
930 #ifndef OPENSSL_NO_NEXTPROTONEG
931 const char *next_proto_neg_in = NULL;
933 #ifndef OPENSSL_NO_SRP
934 char *srppass = NULL;
935 int srp_lateuser = 0;
936 SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
938 #ifndef OPENSSL_NO_CT
939 char *ctlog_file = NULL;
940 int ct_validation = 0;
942 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
944 unsigned int max_send_fragment = 0;
945 unsigned int split_send_fragment = 0, max_pipelines = 0;
946 enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
948 uint8_t maxfraglen = 0;
949 int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
950 int c_tlsextdebug = 0;
951 #ifndef OPENSSL_NO_OCSP
952 int c_status_req = 0;
954 BIO *bio_c_msg = NULL;
955 const char *keylog_file = NULL, *early_data_file = NULL;
956 #ifndef OPENSSL_NO_DTLS
959 char *psksessf = NULL;
963 /* Known false-positive of MemorySanitizer. */
964 #if defined(__has_feature)
965 # if __has_feature(memory_sanitizer)
966 __msan_unpoison(&readfds, sizeof(readfds));
967 __msan_unpoison(&writefds, sizeof(writefds));
971 prog = opt_progname(argv[0]);
976 vpm = X509_VERIFY_PARAM_new();
977 cctx = SSL_CONF_CTX_new();
979 if (vpm == NULL || cctx == NULL) {
980 BIO_printf(bio_err, "%s: out of memory\n", prog);
984 cbuf = app_malloc(BUFSIZZ, "cbuf");
985 sbuf = app_malloc(BUFSIZZ, "sbuf");
986 mbuf = app_malloc(BUFSIZZ, "mbuf");
988 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
990 prog = opt_init(argc, argv, s_client_options);
991 while ((o = opt_next()) != OPT_EOF) {
992 /* Check for intermixing flags. */
993 if (connect_type == use_unix && IS_INET_FLAG(o)) {
995 "%s: Intermixed protocol flags (unix and internet domains)\n",
999 if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
1001 "%s: Intermixed protocol flags (internet and unix domains)\n",
1006 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1007 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1010 if (IS_NO_PROT_FLAG(o))
1012 if (prot_opt == 1 && no_prot_opt) {
1014 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1022 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1025 opt_help(s_client_options);
1029 connect_type = use_inet;
1030 socket_family = AF_INET;
1035 connect_type = use_inet;
1036 socket_family = AF_INET6;
1041 connect_type = use_inet;
1042 freeandcopy(&host, opt_arg());
1045 connect_type = use_inet;
1046 freeandcopy(&port, opt_arg());
1049 connect_type = use_inet;
1050 freeandcopy(&connectstr, opt_arg());
1053 proxystr = opt_arg();
1054 starttls_proto = PROTO_CONNECT;
1058 connect_type = use_unix;
1059 socket_family = AF_UNIX;
1060 freeandcopy(&host, opt_arg());
1064 /* fall through, since this is an alias */
1066 protohost = opt_arg();
1069 verify = SSL_VERIFY_PEER;
1070 verify_args.depth = atoi(opt_arg());
1072 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1075 cert_file = opt_arg();
1078 if (!set_nameopt(opt_arg()))
1082 crl_file = opt_arg();
1084 case OPT_CRL_DOWNLOAD:
1088 sess_out = opt_arg();
1091 sess_in = opt_arg();
1094 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &cert_format))
1098 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1101 case OPT_VERIFY_RET_ERROR:
1102 verify_args.return_error = 1;
1104 case OPT_VERIFY_QUIET:
1105 verify_args.quiet = 1;
1108 c_brief = verify_args.quiet = c_quiet = 1;
1111 if (ssl_args == NULL)
1112 ssl_args = sk_OPENSSL_STRING_new_null();
1113 if (ssl_args == NULL
1114 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1115 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1116 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1121 if (!opt_verify(o, vpm))
1126 if (!args_excert(o, &exc))
1136 c_quiet = c_ign_eof = 1;
1145 e = setup_engine(opt_arg(), 1);
1147 case OPT_SSL_CLIENT_ENGINE:
1148 #ifndef OPENSSL_NO_ENGINE
1149 ssl_client_engine = ENGINE_by_id(opt_arg());
1150 if (ssl_client_engine == NULL) {
1151 BIO_printf(bio_err, "Error getting client auth engine\n");
1163 case OPT_NO_IGN_EOF:
1169 case OPT_TLSEXTDEBUG:
1173 #ifndef OPENSSL_NO_OCSP
1186 bio_c_msg = BIO_new_file(opt_arg(), "w");
1189 #ifndef OPENSSL_NO_SSL_TRACE
1193 case OPT_SECURITY_DEBUG:
1196 case OPT_SECURITY_DEBUG_VERBOSE:
1208 case OPT_PSK_IDENTITY:
1209 psk_identity = opt_arg();
1212 for (p = psk_key = opt_arg(); *p; p++) {
1213 if (isxdigit(_UC(*p)))
1215 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1220 psksessf = opt_arg();
1222 #ifndef OPENSSL_NO_SRP
1224 srp_arg.srplogin = opt_arg();
1225 if (min_version < TLS1_VERSION)
1226 min_version = TLS1_VERSION;
1229 srppass = opt_arg();
1230 if (min_version < TLS1_VERSION)
1231 min_version = TLS1_VERSION;
1233 case OPT_SRP_STRENGTH:
1234 srp_arg.strength = atoi(opt_arg());
1235 BIO_printf(bio_err, "SRP minimal length for N is %d\n",
1237 if (min_version < TLS1_VERSION)
1238 min_version = TLS1_VERSION;
1240 case OPT_SRP_LATEUSER:
1242 if (min_version < TLS1_VERSION)
1243 min_version = TLS1_VERSION;
1245 case OPT_SRP_MOREGROUPS:
1247 if (min_version < TLS1_VERSION)
1248 min_version = TLS1_VERSION;
1251 case OPT_SSL_CONFIG:
1252 ssl_config = opt_arg();
1255 min_version = SSL3_VERSION;
1256 max_version = SSL3_VERSION;
1259 min_version = TLS1_3_VERSION;
1260 max_version = TLS1_3_VERSION;
1263 min_version = TLS1_2_VERSION;
1264 max_version = TLS1_2_VERSION;
1267 min_version = TLS1_1_VERSION;
1268 max_version = TLS1_1_VERSION;
1271 min_version = TLS1_VERSION;
1272 max_version = TLS1_VERSION;
1275 #ifndef OPENSSL_NO_DTLS
1276 meth = DTLS_client_method();
1277 socket_type = SOCK_DGRAM;
1282 #ifndef OPENSSL_NO_DTLS1
1283 meth = DTLS_client_method();
1284 min_version = DTLS1_VERSION;
1285 max_version = DTLS1_VERSION;
1286 socket_type = SOCK_DGRAM;
1291 #ifndef OPENSSL_NO_DTLS1_2
1292 meth = DTLS_client_method();
1293 min_version = DTLS1_2_VERSION;
1294 max_version = DTLS1_2_VERSION;
1295 socket_type = SOCK_DGRAM;
1300 #ifndef OPENSSL_NO_SCTP
1301 protocol = IPPROTO_SCTP;
1305 #ifndef OPENSSL_NO_DTLS
1306 enable_timeouts = 1;
1310 #ifndef OPENSSL_NO_DTLS
1311 socket_mtu = atol(opt_arg());
1314 case OPT_FALLBACKSCSV:
1318 if (!opt_format(opt_arg(), OPT_FMT_PDE, &key_format))
1322 passarg = opt_arg();
1324 case OPT_CERT_CHAIN:
1325 chain_file = opt_arg();
1328 key_file = opt_arg();
1339 case OPT_CHAINCAPATH:
1340 chCApath = opt_arg();
1342 case OPT_VERIFYCAPATH:
1343 vfyCApath = opt_arg();
1345 case OPT_BUILD_CHAIN:
1349 ReqCAfile = opt_arg();
1357 #ifndef OPENSSL_NO_CT
1364 case OPT_CTLOG_FILE:
1365 ctlog_file = opt_arg();
1368 case OPT_CHAINCAFILE:
1369 chCAfile = opt_arg();
1371 case OPT_VERIFYCAFILE:
1372 vfyCAfile = opt_arg();
1374 case OPT_DANE_TLSA_DOMAIN:
1375 dane_tlsa_domain = opt_arg();
1377 case OPT_DANE_TLSA_RRDATA:
1378 if (dane_tlsa_rrset == NULL)
1379 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1380 if (dane_tlsa_rrset == NULL ||
1381 !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1382 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1386 case OPT_DANE_EE_NO_NAME:
1387 dane_ee_no_name = 1;
1389 case OPT_NEXTPROTONEG:
1390 #ifndef OPENSSL_NO_NEXTPROTONEG
1391 next_proto_neg_in = opt_arg();
1395 alpn_in = opt_arg();
1397 case OPT_SERVERINFO:
1400 for (start = 0, i = 0; i <= len; ++i) {
1401 if (i == len || p[i] == ',') {
1402 serverinfo_types[serverinfo_count] = atoi(p + start);
1403 if (++serverinfo_count == MAX_SI_TYPES)
1410 if (!opt_pair(opt_arg(), services, &starttls_proto))
1413 case OPT_SERVERNAME:
1414 servername = opt_arg();
1416 case OPT_NOSERVERNAME:
1420 srtp_profiles = opt_arg();
1422 case OPT_KEYMATEXPORT:
1423 keymatexportlabel = opt_arg();
1425 case OPT_KEYMATEXPORTLEN:
1426 keymatexportlen = atoi(opt_arg());
1431 case OPT_MAXFRAGLEN:
1432 len = atoi(opt_arg());
1435 maxfraglen = TLSEXT_max_fragment_length_512;
1438 maxfraglen = TLSEXT_max_fragment_length_1024;
1441 maxfraglen = TLSEXT_max_fragment_length_2048;
1444 maxfraglen = TLSEXT_max_fragment_length_4096;
1448 "%s: Max Fragment Len %u is out of permitted values",
1453 case OPT_MAX_SEND_FRAG:
1454 max_send_fragment = atoi(opt_arg());
1456 case OPT_SPLIT_SEND_FRAG:
1457 split_send_fragment = atoi(opt_arg());
1459 case OPT_MAX_PIPELINES:
1460 max_pipelines = atoi(opt_arg());
1463 read_buf_len = atoi(opt_arg());
1465 case OPT_KEYLOG_FILE:
1466 keylog_file = opt_arg();
1468 case OPT_EARLY_DATA:
1469 early_data_file = opt_arg();
1473 if (count4or6 >= 2) {
1474 BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1478 if (servername != NULL) {
1480 "%s: Can't use -servername and -noservername together\n",
1484 if (dane_tlsa_domain != NULL) {
1486 "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1491 argc = opt_num_rest();
1493 /* If there's a positional argument, it's the equivalent of
1495 * Don't allow -connect and a separate argument.
1497 if (connectstr != NULL) {
1499 "%s: must not provide both -connect option and target parameter\n",
1503 connect_type = use_inet;
1504 freeandcopy(&connectstr, *opt_rest());
1505 } else if (argc != 0) {
1509 #ifndef OPENSSL_NO_NEXTPROTONEG
1510 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1511 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1515 if (proxystr != NULL) {
1517 char *tmp_host = host, *tmp_port = port;
1518 if (connectstr == NULL) {
1519 BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
1522 res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1523 if (tmp_host != host)
1524 OPENSSL_free(tmp_host);
1525 if (tmp_port != port)
1526 OPENSSL_free(tmp_port);
1529 "%s: -proxy argument malformed or ambiguous\n", prog);
1534 char *tmp_host = host, *tmp_port = port;
1535 if (connectstr != NULL)
1536 res = BIO_parse_hostserv(connectstr, &host, &port,
1537 BIO_PARSE_PRIO_HOST);
1538 if (tmp_host != host)
1539 OPENSSL_free(tmp_host);
1540 if (tmp_port != port)
1541 OPENSSL_free(tmp_port);
1544 "%s: -connect argument or target parameter malformed or ambiguous\n",
1551 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1553 "Can't use unix sockets and datagrams together\n");
1558 #ifndef OPENSSL_NO_SCTP
1559 if (protocol == IPPROTO_SCTP) {
1560 if (socket_type != SOCK_DGRAM) {
1561 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1564 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1565 socket_type = SOCK_STREAM;
1569 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1570 next_proto.status = -1;
1571 if (next_proto_neg_in) {
1573 next_protos_parse(&next_proto.len, next_proto_neg_in);
1574 if (next_proto.data == NULL) {
1575 BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1579 next_proto.data = NULL;
1582 if (!app_passwd(passarg, NULL, &pass, NULL)) {
1583 BIO_printf(bio_err, "Error getting password\n");
1587 if (key_file == NULL)
1588 key_file = cert_file;
1590 if (key_file != NULL) {
1591 key = load_key(key_file, key_format, 0, pass, e,
1592 "client certificate private key file");
1594 ERR_print_errors(bio_err);
1599 if (cert_file != NULL) {
1600 cert = load_cert(cert_file, cert_format, "client certificate file");
1602 ERR_print_errors(bio_err);
1607 if (chain_file != NULL) {
1608 if (!load_certs(chain_file, &chain, FORMAT_PEM, NULL,
1609 "client certificate chain"))
1613 if (crl_file != NULL) {
1615 crl = load_crl(crl_file, crl_format);
1617 BIO_puts(bio_err, "Error loading CRL\n");
1618 ERR_print_errors(bio_err);
1621 crls = sk_X509_CRL_new_null();
1622 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1623 BIO_puts(bio_err, "Error adding CRL\n");
1624 ERR_print_errors(bio_err);
1630 if (!load_excert(&exc))
1633 if (bio_c_out == NULL) {
1634 if (c_quiet && !c_debug) {
1635 bio_c_out = BIO_new(BIO_s_null());
1636 if (c_msg && bio_c_msg == NULL)
1637 bio_c_msg = dup_bio_out(FORMAT_TEXT);
1638 } else if (bio_c_out == NULL)
1639 bio_c_out = dup_bio_out(FORMAT_TEXT);
1641 #ifndef OPENSSL_NO_SRP
1642 if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1643 BIO_printf(bio_err, "Error getting password\n");
1648 ctx = SSL_CTX_new(meth);
1650 ERR_print_errors(bio_err);
1655 ssl_ctx_security_debug(ctx, sdebug);
1657 if (ssl_config != NULL) {
1658 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1659 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1661 ERR_print_errors(bio_err);
1666 if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1668 if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1671 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1672 BIO_printf(bio_err, "Error setting verify params\n");
1673 ERR_print_errors(bio_err);
1678 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1681 if (max_send_fragment > 0
1682 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1683 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1684 prog, max_send_fragment);
1688 if (split_send_fragment > 0
1689 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1690 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1691 prog, split_send_fragment);
1695 if (max_pipelines > 0
1696 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1697 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1698 prog, max_pipelines);
1702 if (read_buf_len > 0) {
1703 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1707 && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
1709 "%s: Max Fragment Length code %u is out of permitted values"
1710 "\n", prog, maxfraglen);
1714 if (!config_ctx(cctx, ssl_args, ctx))
1717 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1718 crls, crl_download)) {
1719 BIO_printf(bio_err, "Error loading store locations\n");
1720 ERR_print_errors(bio_err);
1723 if (ReqCAfile != NULL) {
1724 STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
1726 if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
1727 sk_X509_NAME_pop_free(nm, X509_NAME_free);
1728 BIO_printf(bio_err, "Error loading CA names\n");
1729 ERR_print_errors(bio_err);
1732 SSL_CTX_set0_CA_list(ctx, nm);
1734 #ifndef OPENSSL_NO_ENGINE
1735 if (ssl_client_engine) {
1736 if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1737 BIO_puts(bio_err, "Error setting client auth engine\n");
1738 ERR_print_errors(bio_err);
1739 ENGINE_free(ssl_client_engine);
1742 ENGINE_free(ssl_client_engine);
1746 #ifndef OPENSSL_NO_PSK
1747 if (psk_key != NULL) {
1749 BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1750 SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1753 if (psksessf != NULL) {
1754 BIO *stmp = BIO_new_file(psksessf, "r");
1757 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
1758 ERR_print_errors(bio_err);
1761 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1763 if (psksess == NULL) {
1764 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
1765 ERR_print_errors(bio_err);
1769 if (psk_key != NULL || psksess != NULL)
1770 SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
1772 #ifndef OPENSSL_NO_SRTP
1773 if (srtp_profiles != NULL) {
1774 /* Returns 0 on success! */
1775 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1776 BIO_printf(bio_err, "Error setting SRTP profile\n");
1777 ERR_print_errors(bio_err);
1784 ssl_ctx_set_excert(ctx, exc);
1786 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1787 if (next_proto.data != NULL)
1788 SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1792 unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1795 BIO_printf(bio_err, "Error parsing -alpn argument\n");
1798 /* Returns 0 on success! */
1799 if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1800 BIO_printf(bio_err, "Error setting ALPN\n");
1806 for (i = 0; i < serverinfo_count; i++) {
1807 if (!SSL_CTX_add_client_custom_ext(ctx,
1808 serverinfo_types[i],
1810 serverinfo_cli_parse_cb, NULL)) {
1812 "Warning: Unable to add custom extension %u, skipping\n",
1813 serverinfo_types[i]);
1818 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1820 #ifndef OPENSSL_NO_CT
1821 /* Enable SCT processing, without early connection termination */
1822 if (ct_validation &&
1823 !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
1824 ERR_print_errors(bio_err);
1828 if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
1829 if (ct_validation) {
1830 ERR_print_errors(bio_err);
1835 * If CT validation is not enabled, the log list isn't needed so don't
1836 * show errors or abort. We try to load it regardless because then we
1837 * can show the names of the logs any SCTs came from (SCTs may be seen
1838 * even with validation disabled).
1844 SSL_CTX_set_verify(ctx, verify, verify_callback);
1846 if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1847 ERR_print_errors(bio_err);
1851 ssl_ctx_add_crls(ctx, crls, crl_download);
1853 if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
1856 if (!noservername) {
1857 tlsextcbp.biodebug = bio_err;
1858 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1859 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1861 # ifndef OPENSSL_NO_SRP
1862 if (srp_arg.srplogin) {
1863 if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) {
1864 BIO_printf(bio_err, "Unable to set SRP username\n");
1867 srp_arg.msg = c_msg;
1868 srp_arg.debug = c_debug;
1869 SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
1870 SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
1871 SSL_CTX_set_srp_strength(ctx, srp_arg.strength);
1872 if (c_msg || c_debug || srp_arg.amp == 0)
1873 SSL_CTX_set_srp_verify_param_callback(ctx,
1874 ssl_srp_verify_param_cb);
1878 if (dane_tlsa_domain != NULL) {
1879 if (SSL_CTX_dane_enable(ctx) <= 0) {
1881 "%s: Error enabling DANE TLSA authentication.\n",
1883 ERR_print_errors(bio_err);
1889 * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
1890 * come at any time. Therefore we use a callback to write out the session
1891 * when we know about it. This approach works for < TLSv1.3 as well.
1893 if (sess_out != NULL) {
1894 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT
1895 | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1896 SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
1899 if (set_keylog_file(ctx, keylog_file))
1906 if (sess_in != NULL) {
1908 BIO *stmp = BIO_new_file(sess_in, "r");
1910 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
1911 ERR_print_errors(bio_err);
1914 sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1917 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
1918 ERR_print_errors(bio_err);
1921 if (!SSL_set_session(con, sess)) {
1922 BIO_printf(bio_err, "Can't set session\n");
1923 ERR_print_errors(bio_err);
1927 SSL_SESSION_free(sess);
1931 SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
1933 if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
1934 if (servername == NULL)
1935 servername = (host == NULL) ? "localhost" : host;
1936 if (!SSL_set_tlsext_host_name(con, servername)) {
1937 BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
1938 ERR_print_errors(bio_err);
1943 if (dane_tlsa_domain != NULL) {
1944 if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
1945 BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
1946 "authentication.\n", prog);
1947 ERR_print_errors(bio_err);
1950 if (dane_tlsa_rrset == NULL) {
1951 BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
1952 "least one -dane_tlsa_rrdata option.\n", prog);
1955 if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
1956 BIO_printf(bio_err, "%s: Failed to import any TLSA "
1957 "records.\n", prog);
1960 if (dane_ee_no_name)
1961 SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
1962 } else if (dane_tlsa_rrset != NULL) {
1963 BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
1964 "-dane_tlsa_domain option.\n", prog);
1969 if (init_client(&s, host, port, socket_family, socket_type, protocol)
1971 BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
1975 BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);
1978 if (!BIO_socket_nbio(s, 1)) {
1979 ERR_print_errors(bio_err);
1982 BIO_printf(bio_c_out, "Turned on non blocking io\n");
1984 #ifndef OPENSSL_NO_DTLS
1986 union BIO_sock_info_u peer_info;
1988 #ifndef OPENSSL_NO_SCTP
1989 if (protocol == IPPROTO_SCTP)
1990 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
1993 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
1995 if ((peer_info.addr = BIO_ADDR_new()) == NULL) {
1996 BIO_printf(bio_err, "memory allocation failure\n");
2000 if (!BIO_sock_info(s, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
2001 BIO_printf(bio_err, "getsockname:errno=%d\n",
2002 get_last_socket_error());
2003 BIO_ADDR_free(peer_info.addr);
2008 (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
2009 BIO_ADDR_free(peer_info.addr);
2010 peer_info.addr = NULL;
2012 if (enable_timeouts) {
2014 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2015 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2018 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2019 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2023 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2024 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2025 DTLS_get_link_min_mtu(con));
2029 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2030 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2031 BIO_printf(bio_err, "Failed to set MTU\n");
2036 /* want to do MTU discovery */
2037 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2040 #endif /* OPENSSL_NO_DTLS */
2041 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2046 test = BIO_new(BIO_f_nbio_test());
2047 sbio = BIO_push(test, sbio);
2051 BIO_set_callback(sbio, bio_dump_callback);
2052 BIO_set_callback_arg(sbio, (char *)bio_c_out);
2055 #ifndef OPENSSL_NO_SSL_TRACE
2057 SSL_set_msg_callback(con, SSL_trace);
2060 SSL_set_msg_callback(con, msg_cb);
2061 SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
2064 if (c_tlsextdebug) {
2065 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2066 SSL_set_tlsext_debug_arg(con, bio_c_out);
2068 #ifndef OPENSSL_NO_OCSP
2070 SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
2071 SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
2072 SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
2076 SSL_set_bio(con, sbio, sbio);
2077 SSL_set_connect_state(con);
2079 /* ok, lets connect */
2080 if (fileno_stdin() > SSL_get_fd(con))
2081 width = fileno_stdin() + 1;
2083 width = SSL_get_fd(con) + 1;
2096 switch ((PROTOCOL_CHOICE) starttls_proto) {
2103 * This is an ugly hack that does a lot of assumptions. We do
2104 * have to handle multi-line responses which may come in a single
2105 * packet or not. We therefore have to use BIO_gets() which does
2106 * need a buffering BIO. So during the initial chitchat we do
2107 * push a buffering BIO into the chain that is removed again
2108 * later on to not disturb the rest of the s_client operation.
2111 BIO *fbio = BIO_new(BIO_f_buffer());
2113 BIO_push(fbio, sbio);
2114 /* Wait for multi-line response to end from LMTP or SMTP */
2116 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2117 } while (mbuf_len > 3 && mbuf[3] == '-');
2118 if (protohost == NULL)
2119 protohost = "mail.example.com";
2120 if (starttls_proto == (int)PROTO_LMTP)
2121 BIO_printf(fbio, "LHLO %s\r\n", protohost);
2123 BIO_printf(fbio, "EHLO %s\r\n", protohost);
2124 (void)BIO_flush(fbio);
2126 * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2130 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2131 if (strstr(mbuf, "STARTTLS"))
2133 } while (mbuf_len > 3 && mbuf[3] == '-');
2134 (void)BIO_flush(fbio);
2139 "Didn't find STARTTLS in server response,"
2140 " trying anyway...\n");
2141 BIO_printf(sbio, "STARTTLS\r\n");
2142 BIO_read(sbio, sbuf, BUFSIZZ);
2147 BIO_read(sbio, mbuf, BUFSIZZ);
2148 BIO_printf(sbio, "STLS\r\n");
2149 mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
2151 BIO_printf(bio_err, "BIO_read failed\n");
2159 BIO *fbio = BIO_new(BIO_f_buffer());
2161 BIO_push(fbio, sbio);
2162 BIO_gets(fbio, mbuf, BUFSIZZ);
2163 /* STARTTLS command requires CAPABILITY... */
2164 BIO_printf(fbio, ". CAPABILITY\r\n");
2165 (void)BIO_flush(fbio);
2166 /* wait for multi-line CAPABILITY response */
2168 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2169 if (strstr(mbuf, "STARTTLS"))
2172 while (mbuf_len > 3 && mbuf[0] != '.');
2173 (void)BIO_flush(fbio);
2178 "Didn't find STARTTLS in server response,"
2179 " trying anyway...\n");
2180 BIO_printf(sbio, ". STARTTLS\r\n");
2181 BIO_read(sbio, sbuf, BUFSIZZ);
2186 BIO *fbio = BIO_new(BIO_f_buffer());
2188 BIO_push(fbio, sbio);
2189 /* wait for multi-line response to end from FTP */
2191 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2193 while (mbuf_len > 3 && mbuf[3] == '-');
2194 (void)BIO_flush(fbio);
2197 BIO_printf(sbio, "AUTH TLS\r\n");
2198 BIO_read(sbio, sbuf, BUFSIZZ);
2202 case PROTO_XMPP_SERVER:
2205 BIO_printf(sbio, "<stream:stream "
2206 "xmlns:stream='http://etherx.jabber.org/streams' "
2207 "xmlns='jabber:%s' to='%s' version='1.0'>",
2208 starttls_proto == PROTO_XMPP ? "client" : "server",
2209 protohost ? protohost : host);
2210 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2212 BIO_printf(bio_err, "BIO_read failed\n");
2217 (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2219 "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2221 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2229 "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2230 seen = BIO_read(sbio, sbuf, BUFSIZZ);
2232 BIO_printf(bio_err, "BIO_read failed\n");
2236 if (!strstr(sbuf, "<proceed"))
2243 static const unsigned char tls_do[] = {
2244 /* IAC DO START_TLS */
2247 static const unsigned char tls_will[] = {
2248 /* IAC WILL START_TLS */
2251 static const unsigned char tls_follows[] = {
2252 /* IAC SB START_TLS FOLLOWS IAC SE */
2253 255, 250, 46, 1, 255, 240
2257 /* Telnet server should demand we issue START_TLS */
2258 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2259 if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
2261 /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2262 BIO_write(sbio, tls_will, 3);
2263 BIO_write(sbio, tls_follows, 6);
2264 (void)BIO_flush(sbio);
2265 /* Telnet server also sent the FOLLOWS sub-command */
2266 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2267 if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2274 error_proto, /* Wrong protocol, not even HTTP */
2275 error_connect, /* CONNECT failed */
2277 } foundit = error_connect;
2278 BIO *fbio = BIO_new(BIO_f_buffer());
2280 BIO_push(fbio, sbio);
2281 BIO_printf(fbio, "CONNECT %s HTTP/1.0\r\n\r\n", connectstr);
2282 (void)BIO_flush(fbio);
2284 * The first line is the HTTP response. According to RFC 7230,
2285 * it's formated exactly like this:
2287 * HTTP/d.d ddd Reason text\r\n
2289 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2290 if (mbuf_len < (int)strlen("HTTP/1.0 200")) {
2292 "%s: HTTP CONNECT failed, insufficient response "
2293 "from proxy (got %d octets)\n", prog, mbuf_len);
2294 (void)BIO_flush(fbio);
2299 if (mbuf[8] != ' ') {
2301 "%s: HTTP CONNECT failed, incorrect response "
2302 "from proxy\n", prog);
2303 foundit = error_proto;
2304 } else if (mbuf[9] != '2') {
2305 BIO_printf(bio_err, "%s: HTTP CONNECT failed: %s ", prog,
2310 if (foundit != error_proto) {
2311 /* Read past all following headers */
2313 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2314 } while (mbuf_len > 2);
2316 (void)BIO_flush(fbio);
2319 if (foundit != success) {
2327 BIO *fbio = BIO_new(BIO_f_buffer());
2329 BIO_push(fbio, sbio);
2330 BIO_printf(fbio, "STARTTLS\r\n");
2331 (void)BIO_flush(fbio);
2332 width = SSL_get_fd(con) + 1;
2338 openssl_fdset(SSL_get_fd(con), &readfds);
2339 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2340 timeout.tv_usec = 0;
2342 * If the IRCd doesn't respond within
2343 * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2344 * it doesn't support STARTTLS. Many IRCds
2345 * will not give _any_ sort of response to a
2346 * STARTTLS command when it's not supported.
2348 if (!BIO_get_buffer_num_lines(fbio)
2349 && !BIO_pending(fbio)
2350 && !BIO_pending(sbio)
2351 && select(width, (void *)&readfds, NULL, NULL,
2354 "Timeout waiting for response (%d seconds).\n",
2355 S_CLIENT_IRC_READ_TIMEOUT);
2359 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2360 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2362 /* :example.net 451 STARTTLS :You have not registered */
2363 /* :example.net 421 STARTTLS :Unknown command */
2364 if ((numeric == 451 || numeric == 421)
2365 && strstr(mbuf, "STARTTLS") != NULL) {
2366 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2369 if (numeric == 691) {
2370 BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2371 ERR_print_errors(bio_err);
2374 } while (numeric != 670);
2376 (void)BIO_flush(fbio);
2379 if (numeric != 670) {
2380 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2388 /* SSL request packet */
2389 static const unsigned char ssl_req[] = {
2390 /* payload_length, sequence_id */
2391 0x20, 0x00, 0x00, 0x01,
2393 /* capability flags, CLIENT_SSL always set */
2394 0x85, 0xae, 0x7f, 0x00,
2395 /* max-packet size */
2396 0x00, 0x00, 0x00, 0x01,
2399 /* string[23] reserved (all [0]) */
2400 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2401 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2402 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2405 int ssl_flg = 0x800;
2407 const unsigned char *packet = (const unsigned char *)sbuf;
2409 /* Receiving Initial Handshake packet. */
2410 bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
2412 BIO_printf(bio_err, "BIO_read failed\n");
2414 /* Packet length[3], Packet number[1] + minimum payload[17] */
2415 } else if (bytes < 21) {
2416 BIO_printf(bio_err, "MySQL packet too short.\n");
2418 } else if (bytes != (4 + packet[0] +
2420 (packet[2] << 16))) {
2421 BIO_printf(bio_err, "MySQL packet length does not match.\n");
2423 /* protocol version[1] */
2424 } else if (packet[4] != 0xA) {
2426 "Only MySQL protocol version 10 is supported.\n");
2431 /* server version[string+NULL] */
2434 BIO_printf(bio_err, "Cannot confirm server version. ");
2436 } else if (packet[pos++] == '\0') {
2441 /* make sure we have at least 15 bytes left in the packet */
2442 if (pos + 15 > bytes) {
2444 "MySQL server handshake packet is broken.\n");
2448 pos += 12; /* skip over conn id[4] + SALT[8] */
2449 if (packet[pos++] != '\0') { /* verify filler */
2451 "MySQL packet is broken.\n");
2455 /* capability flags[2] */
2456 if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
2457 BIO_printf(bio_err, "MySQL server does not support SSL.\n");
2461 /* Sending SSL Handshake packet. */
2462 BIO_write(sbio, ssl_req, sizeof(ssl_req));
2463 (void)BIO_flush(sbio);
2466 case PROTO_POSTGRES:
2468 static const unsigned char ssl_request[] = {
2469 /* Length SSLRequest */
2470 0, 0, 0, 8, 4, 210, 22, 47
2474 /* Send SSLRequest packet */
2475 BIO_write(sbio, ssl_request, 8);
2476 (void)BIO_flush(sbio);
2478 /* Reply will be a single S if SSL is enabled */
2479 bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2480 if (bytes != 1 || sbuf[0] != 'S')
2487 BIO *fbio = BIO_new(BIO_f_buffer());
2489 BIO_push(fbio, sbio);
2490 BIO_gets(fbio, mbuf, BUFSIZZ);
2491 /* STARTTLS command requires CAPABILITIES... */
2492 BIO_printf(fbio, "CAPABILITIES\r\n");
2493 (void)BIO_flush(fbio);
2494 /* wait for multi-line CAPABILITIES response */
2496 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2497 if (strstr(mbuf, "STARTTLS"))
2499 } while (mbuf_len > 1 && mbuf[0] != '.');
2500 (void)BIO_flush(fbio);
2505 "Didn't find STARTTLS in server response,"
2506 " trying anyway...\n");
2507 BIO_printf(sbio, "STARTTLS\r\n");
2508 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2510 BIO_printf(bio_err, "BIO_read failed\n");
2513 mbuf[mbuf_len] = '\0';
2514 if (strstr(mbuf, "382") == NULL) {
2515 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2523 BIO *fbio = BIO_new(BIO_f_buffer());
2525 BIO_push(fbio, sbio);
2526 /* wait for multi-line response to end from Sieve */
2528 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2530 * According to RFC 5804 § 1.7, capability
2531 * is case-insensitive, make it uppercase
2533 if (mbuf_len > 1 && mbuf[0] == '"') {
2534 make_uppercase(mbuf);
2535 if (strncmp(mbuf, "\"STARTTLS\"", 10) == 0)
2538 } while (mbuf_len > 1 && mbuf[0] == '"');
2539 (void)BIO_flush(fbio);
2544 "Didn't find STARTTLS in server response,"
2545 " trying anyway...\n");
2546 BIO_printf(sbio, "STARTTLS\r\n");
2547 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2549 BIO_printf(bio_err, "BIO_read failed\n");
2552 mbuf[mbuf_len] = '\0';
2554 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2558 * According to RFC 5804 § 2.2, response codes are case-
2559 * insensitive, make it uppercase but preserve the response.
2561 strncpy(sbuf, mbuf, 2);
2562 make_uppercase(sbuf);
2563 if (strncmp(sbuf, "OK", 2) != 0) {
2564 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2571 /* StartTLS Operation according to RFC 4511 */
2572 static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
2574 "messageID=INTEGER:1\n"
2575 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2576 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2578 char *genstr = NULL;
2580 ASN1_TYPE *atyp = NULL;
2581 BIO *ldapbio = BIO_new(BIO_s_mem());
2582 CONF *cnf = NCONF_new(NULL);
2588 BIO_puts(ldapbio, ldap_tls_genconf);
2589 if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
2593 BIO_printf(bio_err, "NCONF_load_bio failed\n");
2596 BIO_printf(bio_err, "Error on line %ld\n", errline);
2601 genstr = NCONF_get_string(cnf, "default", "asn1");
2602 if (genstr == NULL) {
2604 BIO_printf(bio_err, "NCONF_get_string failed\n");
2607 atyp = ASN1_generate_nconf(genstr, cnf);
2610 BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
2615 /* Send SSLRequest packet */
2616 BIO_write(sbio, atyp->value.sequence->data,
2617 atyp->value.sequence->length);
2618 (void)BIO_flush(sbio);
2619 ASN1_TYPE_free(atyp);
2621 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2623 BIO_printf(bio_err, "BIO_read failed\n");
2626 result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
2628 BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
2630 } else if (result > 0) {
2631 BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
2640 if (early_data_file != NULL
2641 && ((SSL_get0_session(con) != NULL
2642 && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
2644 && SSL_SESSION_get_max_early_data(psksess) > 0))) {
2645 BIO *edfile = BIO_new_file(early_data_file, "r");
2646 size_t readbytes, writtenbytes;
2649 if (edfile == NULL) {
2650 BIO_printf(bio_err, "Cannot open early data file\n");
2655 if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
2658 while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
2659 switch (SSL_get_error(con, 0)) {
2660 case SSL_ERROR_WANT_WRITE:
2661 case SSL_ERROR_WANT_ASYNC:
2662 case SSL_ERROR_WANT_READ:
2663 /* Just keep trying - busy waiting */
2666 BIO_printf(bio_err, "Error writing early data\n");
2668 ERR_print_errors(bio_err);
2681 if ((SSL_version(con) == DTLS1_VERSION) &&
2682 DTLSv1_get_timeout(con, &timeout))
2683 timeoutp = &timeout;
2687 if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
2688 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
2697 BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2698 print_ssl_summary(con);
2701 print_stuff(bio_c_out, con, full_log);
2705 if (starttls_proto) {
2706 BIO_write(bio_err, mbuf, mbuf_len);
2707 /* We don't need to know any more */
2709 starttls_proto = PROTO_OFF;
2714 BIO_printf(bio_c_out,
2715 "drop connection and then reconnect\n");
2716 do_ssl_shutdown(con);
2717 SSL_set_connect_state(con);
2718 BIO_closesocket(SSL_get_fd(con));
2724 ssl_pending = read_ssl && SSL_has_pending(con);
2727 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2730 * Note that select() returns when read _would not block_,
2731 * and EOF satisfies that. To avoid a CPU-hogging loop,
2732 * set the flag so we exit.
2734 if (read_tty && !at_eof)
2735 openssl_fdset(fileno_stdin(), &readfds);
2736 #if !defined(OPENSSL_SYS_VMS)
2738 openssl_fdset(fileno_stdout(), &writefds);
2742 openssl_fdset(SSL_get_fd(con), &readfds);
2744 openssl_fdset(SSL_get_fd(con), &writefds);
2746 if (!tty_on || !write_tty) {
2748 openssl_fdset(SSL_get_fd(con), &readfds);
2750 openssl_fdset(SSL_get_fd(con), &writefds);
2755 * Note: under VMS with SOCKETSHR the second parameter is
2756 * currently of type (int *) whereas under other systems it is
2757 * (void *) if you don't have a cast it will choke the compiler:
2758 * if you do have a cast then you can either go for (int *) or
2761 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2763 * Under Windows/DOS we make the assumption that we can always
2764 * write to the tty: therefore if we need to write to the tty we
2765 * just fall through. Otherwise we timeout the select every
2766 * second and see if there are any keypresses. Note: this is a
2767 * hack, in a proper Windows application we wouldn't do this.
2774 i = select(width, (void *)&readfds, (void *)&writefds,
2776 if (!i && (!has_stdin_waiting() || !read_tty))
2779 i = select(width, (void *)&readfds, (void *)&writefds,
2783 i = select(width, (void *)&readfds, (void *)&writefds,
2787 BIO_printf(bio_err, "bad select %d\n",
2788 get_last_socket_error());
2793 if ((SSL_version(con) == DTLS1_VERSION)
2794 && DTLSv1_handle_timeout(con) > 0) {
2795 BIO_printf(bio_err, "TIMEOUT occurred\n");
2798 if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
2799 k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
2800 switch (SSL_get_error(con, k)) {
2801 case SSL_ERROR_NONE:
2806 /* we have done a write(con,NULL,0); */
2807 if (cbuf_len <= 0) {
2810 } else { /* if (cbuf_len > 0) */
2816 case SSL_ERROR_WANT_WRITE:
2817 BIO_printf(bio_c_out, "write W BLOCK\n");
2821 case SSL_ERROR_WANT_ASYNC:
2822 BIO_printf(bio_c_out, "write A BLOCK\n");
2823 wait_for_async(con);
2827 case SSL_ERROR_WANT_READ:
2828 BIO_printf(bio_c_out, "write R BLOCK\n");
2833 case SSL_ERROR_WANT_X509_LOOKUP:
2834 BIO_printf(bio_c_out, "write X BLOCK\n");
2836 case SSL_ERROR_ZERO_RETURN:
2837 if (cbuf_len != 0) {
2838 BIO_printf(bio_c_out, "shutdown\n");
2847 case SSL_ERROR_SYSCALL:
2848 if ((k != 0) || (cbuf_len != 0)) {
2849 BIO_printf(bio_err, "write:errno=%d\n",
2850 get_last_socket_error());
2857 case SSL_ERROR_WANT_ASYNC_JOB:
2858 /* This shouldn't ever happen in s_client - treat as an error */
2860 ERR_print_errors(bio_err);
2864 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
2865 /* Assume Windows/DOS/BeOS can always write */
2866 else if (!ssl_pending && write_tty)
2868 else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
2871 #ifdef CHARSET_EBCDIC
2872 ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
2874 i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
2877 BIO_printf(bio_c_out, "DONE\n");
2884 if (sbuf_len <= 0) {
2888 } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
2893 SSL_renegotiate(con);
2898 k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
2900 switch (SSL_get_error(con, k)) {
2901 case SSL_ERROR_NONE:
2910 case SSL_ERROR_WANT_ASYNC:
2911 BIO_printf(bio_c_out, "read A BLOCK\n");
2912 wait_for_async(con);
2915 if ((read_tty == 0) && (write_ssl == 0))
2918 case SSL_ERROR_WANT_WRITE:
2919 BIO_printf(bio_c_out, "read W BLOCK\n");
2923 case SSL_ERROR_WANT_READ:
2924 BIO_printf(bio_c_out, "read R BLOCK\n");
2927 if ((read_tty == 0) && (write_ssl == 0))
2930 case SSL_ERROR_WANT_X509_LOOKUP:
2931 BIO_printf(bio_c_out, "read X BLOCK\n");
2933 case SSL_ERROR_SYSCALL:
2934 ret = get_last_socket_error();
2936 BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
2938 BIO_printf(bio_err, "read:errno=%d\n", ret);
2940 case SSL_ERROR_ZERO_RETURN:
2941 BIO_printf(bio_c_out, "closed\n");
2944 case SSL_ERROR_WANT_ASYNC_JOB:
2945 /* This shouldn't ever happen in s_client. Treat as an error */
2947 ERR_print_errors(bio_err);
2951 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
2952 #if defined(OPENSSL_SYS_MSDOS)
2953 else if (has_stdin_waiting())
2955 else if (FD_ISSET(fileno_stdin(), &readfds))
2961 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
2963 /* both loops are skipped when i <= 0 */
2964 for (j = 0; j < i; j++)
2965 if (cbuf[j] == '\n')
2967 for (j = i - 1; j >= 0; j--) {
2968 cbuf[j + lf_num] = cbuf[j];
2969 if (cbuf[j] == '\n') {
2972 cbuf[j + lf_num] = '\r';
2975 assert(lf_num == 0);
2977 i = raw_read_stdin(cbuf, BUFSIZZ);
2978 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2983 if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q' && cmdletters))) {
2984 BIO_printf(bio_err, "DONE\n");
2989 if ((!c_ign_eof) && (cbuf[0] == 'R' && cmdletters)) {
2990 BIO_printf(bio_err, "RENEGOTIATING\n");
2991 SSL_renegotiate(con);
2995 if (!c_ign_eof && (cbuf[0] == 'K' || cbuf[0] == 'k' )
2997 BIO_printf(bio_err, "KEYUPDATE\n");
2999 cbuf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED
3000 : SSL_KEY_UPDATE_NOT_REQUESTED);
3003 #ifndef OPENSSL_NO_HEARTBEATS
3004 else if ((!c_ign_eof) && (cbuf[0] == 'B' && cmdletters)) {
3005 BIO_printf(bio_err, "HEARTBEATING\n");
3013 #ifdef CHARSET_EBCDIC
3014 ebcdic2ascii(cbuf, cbuf, i);
3026 print_stuff(bio_c_out, con, full_log);
3027 do_ssl_shutdown(con);
3028 #if defined(OPENSSL_SYS_WINDOWS)
3030 * Give the socket time to send its last data before we close it.
3031 * No amount of setting SO_LINGER etc on the socket seems to persuade
3032 * Windows to send the data before closing the socket...but sleeping
3033 * for a short time seems to do it (units in ms)
3034 * TODO: Find a better way to do this
3039 * If we ended with an alert being sent, but still with data in the
3040 * network buffer to be read, then calling BIO_closesocket() will
3041 * result in a TCP-RST being sent. On some platforms (notably
3042 * Windows) then this will result in the peer immediately abandoning
3043 * the connection including any buffered alert data before it has
3044 * had a chance to be read. Shutting down the sending side first,
3045 * and then closing the socket sends TCP-FIN first followed by
3046 * TCP-RST. This seems to allow the peer to read the alert data.
3048 shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
3049 BIO_closesocket(SSL_get_fd(con));
3053 print_stuff(bio_c_out, con, 1);
3056 SSL_SESSION_free(psksess);
3057 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3058 OPENSSL_free(next_proto.data);
3061 set_keylog_file(NULL, NULL);
3063 sk_X509_CRL_pop_free(crls, X509_CRL_free);
3065 sk_X509_pop_free(chain, X509_free);
3067 #ifndef OPENSSL_NO_SRP
3068 OPENSSL_free(srp_arg.srppassin);
3070 OPENSSL_free(connectstr);
3073 X509_VERIFY_PARAM_free(vpm);
3074 ssl_excert_free(exc);
3075 sk_OPENSSL_STRING_free(ssl_args);
3076 sk_OPENSSL_STRING_free(dane_tlsa_rrset);
3077 SSL_CONF_CTX_free(cctx);
3078 OPENSSL_clear_free(cbuf, BUFSIZZ);
3079 OPENSSL_clear_free(sbuf, BUFSIZZ);
3080 OPENSSL_clear_free(mbuf, BUFSIZZ);
3082 BIO_free(bio_c_out);
3084 BIO_free(bio_c_msg);
3089 static void print_stuff(BIO *bio, SSL *s, int full)
3093 const SSL_CIPHER *c;
3095 #ifndef OPENSSL_NO_COMP
3096 const COMP_METHOD *comp, *expansion;
3098 unsigned char *exportedkeymat;
3099 #ifndef OPENSSL_NO_CT
3100 const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
3104 int got_a_chain = 0;
3106 sk = SSL_get_peer_cert_chain(s);
3110 BIO_printf(bio, "---\nCertificate chain\n");
3111 for (i = 0; i < sk_X509_num(sk); i++) {
3112 BIO_printf(bio, "%2d s:", i);
3113 X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
3114 BIO_puts(bio, "\n");
3115 BIO_printf(bio, " i:");
3116 X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
3117 BIO_puts(bio, "\n");
3119 PEM_write_bio_X509(bio, sk_X509_value(sk, i));
3123 BIO_printf(bio, "---\n");
3124 peer = SSL_get_peer_certificate(s);
3126 BIO_printf(bio, "Server certificate\n");
3128 /* Redundant if we showed the whole chain */
3129 if (!(c_showcerts && got_a_chain))
3130 PEM_write_bio_X509(bio, peer);
3131 dump_cert_text(bio, peer);
3133 BIO_printf(bio, "no peer certificate available\n");
3135 print_ca_names(bio, s);
3137 ssl_print_sigalgs(bio, s);
3138 ssl_print_tmp_key(bio, s);
3140 #ifndef OPENSSL_NO_CT
3142 * When the SSL session is anonymous, or resumed via an abbreviated
3143 * handshake, no SCTs are provided as part of the handshake. While in
3144 * a resumed session SCTs may be present in the session's certificate,
3145 * no callbacks are invoked to revalidate these, and in any case that
3146 * set of SCTs may be incomplete. Thus it makes little sense to
3147 * attempt to display SCTs from a resumed session's certificate, and of
3148 * course none are associated with an anonymous peer.
3150 if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
3151 const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
3152 int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
3154 BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
3155 if (sct_count > 0) {
3156 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
3158 BIO_printf(bio, "---\n");
3159 for (i = 0; i < sct_count; ++i) {
3160 SCT *sct = sk_SCT_value(scts, i);
3162 BIO_printf(bio, "SCT validation status: %s\n",
3163 SCT_validation_status_string(sct));
3164 SCT_print(sct, bio, 0, log_store);
3165 if (i < sct_count - 1)
3166 BIO_printf(bio, "\n---\n");
3168 BIO_printf(bio, "\n");
3174 "---\nSSL handshake has read %ju bytes "
3175 "and written %ju bytes\n",
3176 BIO_number_read(SSL_get_rbio(s)),
3177 BIO_number_written(SSL_get_wbio(s)));
3179 print_verify_detail(s, bio);
3180 BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
3181 c = SSL_get_current_cipher(s);
3182 BIO_printf(bio, "%s, Cipher is %s\n",
3183 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3187 pktmp = X509_get0_pubkey(peer);
3188 BIO_printf(bio, "Server public key is %d bit\n",
3189 EVP_PKEY_bits(pktmp));
3191 BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
3192 SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
3193 #ifndef OPENSSL_NO_COMP
3194 comp = SSL_get_current_compression(s);
3195 expansion = SSL_get_current_expansion(s);
3196 BIO_printf(bio, "Compression: %s\n",
3197 comp ? SSL_COMP_get_name(comp) : "NONE");
3198 BIO_printf(bio, "Expansion: %s\n",
3199 expansion ? SSL_COMP_get_name(expansion) : "NONE");
3204 /* Print out local port of connection: useful for debugging */
3206 union BIO_sock_info_u info;
3208 sock = SSL_get_fd(s);
3209 if ((info.addr = BIO_ADDR_new()) != NULL
3210 && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
3211 BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
3212 ntohs(BIO_ADDR_rawport(info.addr)));
3214 BIO_ADDR_free(info.addr);
3218 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3219 if (next_proto.status != -1) {
3220 const unsigned char *proto;
3221 unsigned int proto_len;
3222 SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
3223 BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
3224 BIO_write(bio, proto, proto_len);
3225 BIO_write(bio, "\n", 1);
3229 const unsigned char *proto;
3230 unsigned int proto_len;
3231 SSL_get0_alpn_selected(s, &proto, &proto_len);
3232 if (proto_len > 0) {
3233 BIO_printf(bio, "ALPN protocol: ");
3234 BIO_write(bio, proto, proto_len);
3235 BIO_write(bio, "\n", 1);
3237 BIO_printf(bio, "No ALPN negotiated\n");
3240 #ifndef OPENSSL_NO_SRTP
3242 SRTP_PROTECTION_PROFILE *srtp_profile =
3243 SSL_get_selected_srtp_profile(s);
3246 BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
3247 srtp_profile->name);
3251 if (SSL_version(s) == TLS1_3_VERSION) {
3252 switch (SSL_get_early_data_status(s)) {
3253 case SSL_EARLY_DATA_NOT_SENT:
3254 BIO_printf(bio, "Early data was not sent\n");
3257 case SSL_EARLY_DATA_REJECTED:
3258 BIO_printf(bio, "Early data was rejected\n");
3261 case SSL_EARLY_DATA_ACCEPTED:
3262 BIO_printf(bio, "Early data was accepted\n");
3268 SSL_SESSION_print(bio, SSL_get_session(s));
3269 if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
3270 BIO_printf(bio, "Keying material exporter:\n");
3271 BIO_printf(bio, " Label: '%s'\n", keymatexportlabel);
3272 BIO_printf(bio, " Length: %i bytes\n", keymatexportlen);
3273 exportedkeymat = app_malloc(keymatexportlen, "export key");
3274 if (!SSL_export_keying_material(s, exportedkeymat,
3277 strlen(keymatexportlabel),
3279 BIO_printf(bio, " Error\n");
3281 BIO_printf(bio, " Keying material: ");
3282 for (i = 0; i < keymatexportlen; i++)
3283 BIO_printf(bio, "%02X", exportedkeymat[i]);
3284 BIO_printf(bio, "\n");
3286 OPENSSL_free(exportedkeymat);
3288 BIO_printf(bio, "---\n");
3290 /* flush, or debugging output gets mixed with http response */
3291 (void)BIO_flush(bio);
3294 # ifndef OPENSSL_NO_OCSP
3295 static int ocsp_resp_cb(SSL *s, void *arg)
3297 const unsigned char *p;
3300 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3301 BIO_puts(arg, "OCSP response: ");
3303 BIO_puts(arg, "no response sent\n");
3306 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3308 BIO_puts(arg, "response parse error\n");
3309 BIO_dump_indent(arg, (char *)p, len, 4);
3312 BIO_puts(arg, "\n======================================\n");
3313 OCSP_RESPONSE_print(arg, rsp, 0);
3314 BIO_puts(arg, "======================================\n");
3315 OCSP_RESPONSE_free(rsp);
3320 static int ldap_ExtendedResponse_parse(const char *buf, long rem)
3322 const unsigned char *cur, *end;
3324 int tag, xclass, inf, ret = -1;
3326 cur = (const unsigned char *)buf;
3332 * LDAPMessage ::= SEQUENCE {
3333 * messageID MessageID,
3334 * protocolOp CHOICE {
3336 * extendedResp ExtendedResponse,
3338 * controls [0] Controls OPTIONAL }
3340 * ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3341 * COMPONENTS OF LDAPResult,
3342 * responseName [10] LDAPOID OPTIONAL,
3343 * responseValue [11] OCTET STRING OPTIONAL }
3345 * LDAPResult ::= SEQUENCE {
3346 * resultCode ENUMERATED {
3352 * diagnosticMessage LDAPString,
3353 * referral [3] Referral OPTIONAL }
3357 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3358 if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
3359 (rem = end - cur, len > rem)) {
3360 BIO_printf(bio_err, "Unexpected LDAP response\n");
3364 rem = len; /* ensure that we don't overstep the SEQUENCE */
3366 /* pull MessageID */
3367 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3368 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
3369 (rem = end - cur, len > rem)) {
3370 BIO_printf(bio_err, "No MessageID\n");
3374 cur += len; /* shall we check for MessageId match or just skip? */
3376 /* pull [APPLICATION 24] */
3378 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3379 if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
3381 BIO_printf(bio_err, "Not ExtendedResponse\n");
3385 /* pull resultCode */
3387 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3388 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
3389 (rem = end - cur, len > rem)) {
3390 BIO_printf(bio_err, "Not LDAPResult\n");
3394 /* len should always be one, but just in case... */
3395 for (ret = 0, inf = 0; inf < len; inf++) {
3399 /* There is more data, but we don't care... */
3404 #endif /* OPENSSL_NO_SOCK */