2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright 2005 Nokia. All rights reserved.
5 * Licensed under the Apache License 2.0 (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;
34 #include <openssl/x509.h>
35 #include <openssl/ssl.h>
36 #include <openssl/err.h>
37 #include <openssl/pem.h>
38 #include <openssl/rand.h>
39 #include <openssl/ocsp.h>
40 #include <openssl/bn.h>
41 #include <openssl/trace.h>
42 #include <openssl/async.h>
43 #ifndef OPENSSL_NO_SRP
44 # include <openssl/srp.h>
47 # include <openssl/ct.h>
51 #include "internal/sockets.h"
53 #if defined(__has_feature)
54 # if __has_feature(memory_sanitizer)
55 # include <sanitizer/msan_interface.h>
60 DEFINE_STACK_OF(X509_CRL)
61 DEFINE_STACK_OF(X509_NAME)
63 DEFINE_STACK_OF_STRING()
66 #define BUFSIZZ 1024*8
67 #define S_CLIENT_IRC_READ_TIMEOUT 8
70 static int c_debug = 0;
71 static int c_showcerts = 0;
72 static char *keymatexportlabel = NULL;
73 static int keymatexportlen = 20;
74 static BIO *bio_c_out = NULL;
75 static int c_quiet = 0;
76 static char *sess_out = NULL;
77 static SSL_SESSION *psksess = NULL;
79 static void print_stuff(BIO *berr, SSL *con, int full);
80 #ifndef OPENSSL_NO_OCSP
81 static int ocsp_resp_cb(SSL *s, void *arg);
83 static int ldap_ExtendedResponse_parse(const char *buf, long rem);
84 static int is_dNS_name(const char *host);
86 static int saved_errno;
88 static void save_errno(void)
94 static int restore_errno(void)
101 static void do_ssl_shutdown(SSL *ssl)
106 /* We only do unidirectional shutdown */
107 ret = SSL_shutdown(ssl);
109 switch (SSL_get_error(ssl, ret)) {
110 case SSL_ERROR_WANT_READ:
111 case SSL_ERROR_WANT_WRITE:
112 case SSL_ERROR_WANT_ASYNC:
113 case SSL_ERROR_WANT_ASYNC_JOB:
114 /* We just do busy waiting. Nothing clever */
122 /* Default PSK identity and key */
123 static char *psk_identity = "Client_identity";
125 #ifndef OPENSSL_NO_PSK
126 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
127 unsigned int max_identity_len,
129 unsigned int max_psk_len)
136 BIO_printf(bio_c_out, "psk_client_cb\n");
138 /* no ServerKeyExchange message */
140 BIO_printf(bio_c_out,
141 "NULL received PSK identity hint, continuing anyway\n");
142 } else if (c_debug) {
143 BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
147 * lookup PSK identity and PSK key based on the given identity hint here
149 ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
150 if (ret < 0 || (unsigned int)ret > max_identity_len)
153 BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
156 /* convert the PSK key to binary */
157 key = OPENSSL_hexstr2buf(psk_key, &key_len);
159 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
163 if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
165 "psk buffer of callback is too small (%d) for key (%ld)\n",
166 max_psk_len, key_len);
171 memcpy(psk, key, key_len);
175 BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
180 BIO_printf(bio_err, "Error in PSK client callback\n");
185 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
186 const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
188 static int psk_use_session_cb(SSL *s, const EVP_MD *md,
189 const unsigned char **id, size_t *idlen,
192 SSL_SESSION *usesess = NULL;
193 const SSL_CIPHER *cipher = NULL;
195 if (psksess != NULL) {
196 SSL_SESSION_up_ref(psksess);
200 unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
203 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
208 /* We default to SHA-256 */
209 cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
210 if (cipher == NULL) {
211 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
216 usesess = SSL_SESSION_new();
218 || !SSL_SESSION_set1_master_key(usesess, key, key_len)
219 || !SSL_SESSION_set_cipher(usesess, cipher)
220 || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
227 cipher = SSL_SESSION_get0_cipher(usesess);
231 if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
232 /* PSK not usable, ignore it */
236 SSL_SESSION_free(usesess);
239 *id = (unsigned char *)psk_identity;
240 *idlen = strlen(psk_identity);
246 SSL_SESSION_free(usesess);
250 /* This is a context that we pass to callbacks */
251 typedef struct tlsextctx_st {
256 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
258 tlsextctx *p = (tlsextctx *) arg;
259 const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
260 if (SSL_get_servername_type(s) != -1)
261 p->ack = !SSL_session_reused(s) && hn != NULL;
263 BIO_printf(bio_err, "Can't use SSL_get_servername\n");
265 return SSL_TLSEXT_ERR_OK;
268 #ifndef OPENSSL_NO_SRP
270 /* This is a context that we pass to all callbacks */
271 typedef struct srp_arg_st {
274 int msg; /* copy from c_msg */
275 int debug; /* copy from c_debug */
276 int amp; /* allow more groups */
277 int strength; /* minimal size for N */
280 static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g)
282 BN_CTX *bn_ctx = BN_CTX_new();
283 BIGNUM *p = BN_new();
284 BIGNUM *r = BN_new();
286 g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
287 BN_check_prime(N, bn_ctx, NULL) == 1 &&
288 p != NULL && BN_rshift1(p, N) &&
290 BN_check_prime(p, bn_ctx, NULL) == 1 &&
292 /* verify g^((N-1)/2) == -1 (mod N) */
293 BN_mod_exp(r, g, p, N, bn_ctx) &&
294 BN_add_word(r, 1) && BN_cmp(r, N) == 0;
303 * This callback is used here for two purposes:
304 * - extended debugging
305 * - making some primality tests for unknown groups
306 * The callback is only called for a non default group.
308 * An application does not need the call back at all if
309 * only the standard groups are used. In real life situations,
310 * client and server already share well known groups,
311 * thus there is no need to verify them.
312 * Furthermore, in case that a server actually proposes a group that
313 * is not one of those defined in RFC 5054, it is more appropriate
314 * to add the group to a static list and then compare since
315 * primality tests are rather cpu consuming.
318 static int ssl_srp_verify_param_cb(SSL *s, void *arg)
320 SRP_ARG *srp_arg = (SRP_ARG *)arg;
321 BIGNUM *N = NULL, *g = NULL;
323 if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL))
325 if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
326 BIO_printf(bio_err, "SRP parameters:\n");
327 BIO_printf(bio_err, "\tN=");
328 BN_print(bio_err, N);
329 BIO_printf(bio_err, "\n\tg=");
330 BN_print(bio_err, g);
331 BIO_printf(bio_err, "\n");
334 if (SRP_check_known_gN_param(g, N))
337 if (srp_arg->amp == 1) {
340 "SRP param N and g are not known params, going to check deeper.\n");
343 * The srp_moregroups is a real debugging feature. Implementors
344 * should rather add the value to the known ones. The minimal size
345 * has already been tested.
347 if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
350 BIO_printf(bio_err, "SRP param N and g rejected.\n");
354 # define PWD_STRLEN 1024
356 static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
358 SRP_ARG *srp_arg = (SRP_ARG *)arg;
359 char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer");
363 cb_tmp.password = (char *)srp_arg->srppassin;
364 cb_tmp.prompt_info = "SRP user";
365 if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
366 BIO_printf(bio_err, "Can't read Password\n");
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_BIND, 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_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN,
590 OPT_NEXTPROTONEG, OPT_ALPN,
591 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
592 OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE,
593 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
594 OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC,
595 OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST,
596 OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES,
597 OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE,
601 OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_PROXY, OPT_PROXY_USER, OPT_PROXY_PASS,
602 OPT_DANE_TLSA_DOMAIN,
603 #ifndef OPENSSL_NO_CT
604 OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
606 OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME,
609 OPT_R_ENUM, OPT_PROV_ENUM
612 const OPTIONS s_client_options[] = {
613 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [host:port]\n"},
615 OPT_SECTION("General"),
616 {"help", OPT_HELP, '-', "Display this summary"},
617 #ifndef OPENSSL_NO_ENGINE
618 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
619 {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
620 "Specify engine to be used for client certificate operations"},
622 {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified section for SSL_CTX configuration"},
623 #ifndef OPENSSL_NO_CT
624 {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
625 {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
626 {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
629 OPT_SECTION("Network"),
630 {"host", OPT_HOST, 's', "Use -connect instead"},
631 {"port", OPT_PORT, 'p', "Use -connect instead"},
632 {"connect", OPT_CONNECT, 's',
633 "TCP/IP where to connect (default is :" PORT ")"},
634 {"bind", OPT_BIND, 's', "bind local address for connection"},
635 {"proxy", OPT_PROXY, 's',
636 "Connect to via specified proxy to the real server"},
637 {"proxy_user", OPT_PROXY_USER, 's', "UserID for proxy authentication"},
638 {"proxy_pass", OPT_PROXY_PASS, 's', "Proxy authentication password source"},
640 {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"},
642 {"4", OPT_4, '-', "Use IPv4 only"},
644 {"6", OPT_6, '-', "Use IPv6 only"},
646 {"maxfraglen", OPT_MAXFRAGLEN, 'p',
647 "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
648 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
649 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
650 "Size used to split data for encrypt pipelines"},
651 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
652 "Maximum number of encrypt/decrypt pipelines to be used"},
653 {"read_buf", OPT_READ_BUF, 'p',
654 "Default read buffer size to be used for connections"},
655 {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
657 OPT_SECTION("Identity"),
658 {"cert", OPT_CERT, '<', "Client certificate file to use"},
659 {"certform", OPT_CERTFORM, 'F',
660 "Client certificate file format (PEM or DER) PEM default"},
661 {"cert_chain", OPT_CERT_CHAIN, '<',
662 "Client certificate chain file (in PEM format)"},
663 {"build_chain", OPT_BUILD_CHAIN, '-', "Build client certificate chain"},
664 {"key", OPT_KEY, 's', "Private key file to use; default is: -cert file"},
665 {"keyform", OPT_KEYFORM, 'E', "Key format (PEM, DER or engine) PEM default"},
666 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
667 {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
668 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
669 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
670 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
671 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
672 {"no-CAfile", OPT_NOCAFILE, '-',
673 "Do not load the default certificates file"},
674 {"no-CApath", OPT_NOCAPATH, '-',
675 "Do not load certificates from the default certificates directory"},
676 {"no-CAstore", OPT_NOCASTORE, '-',
677 "Do not load certificates from the default certificates store"},
678 {"requestCAfile", OPT_REQCAFILE, '<',
679 "PEM format file of CA names to send to the server"},
680 {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
681 {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
682 "DANE TLSA rrdata presentation form"},
683 {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
684 "Disable name checks when matching DANE-EE(3) TLSA records"},
685 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
686 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
687 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
688 {"name", OPT_PROTOHOST, 's',
689 "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
691 OPT_SECTION("Session"),
692 {"reconnect", OPT_RECONNECT, '-',
693 "Drop and re-make the connection with the same Session-ID"},
694 {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
695 {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
697 OPT_SECTION("Input/Output"),
698 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
699 {"quiet", OPT_QUIET, '-', "No s_client output"},
700 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
701 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
702 {"starttls", OPT_STARTTLS, 's',
703 "Use the appropriate STARTTLS command before starting TLS"},
704 {"xmpphost", OPT_XMPPHOST, 's',
705 "Alias of -name option for \"-starttls xmpp[-server]\""},
706 {"brief", OPT_BRIEF, '-',
707 "Restrict output to brief summary of connection parameters"},
708 {"prexit", OPT_PREXIT, '-',
709 "Print session information when the program exits"},
711 OPT_SECTION("Debug"),
712 {"showcerts", OPT_SHOWCERTS, '-',
713 "Show all certificates sent by the server"},
714 {"debug", OPT_DEBUG, '-', "Extra output"},
715 {"msg", OPT_MSG, '-', "Show protocol messages"},
716 {"msgfile", OPT_MSGFILE, '>',
717 "File to send output of -msg or -trace, instead of stdout"},
718 {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
719 {"state", OPT_STATE, '-', "Print the ssl states"},
720 {"keymatexport", OPT_KEYMATEXPORT, 's',
721 "Export keying material using label"},
722 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
723 "Export len bytes of keying material (default 20)"},
724 {"security_debug", OPT_SECURITY_DEBUG, '-',
725 "Enable security debug messages"},
726 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
727 "Output more security debug output"},
728 #ifndef OPENSSL_NO_SSL_TRACE
729 {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
732 {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
734 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
735 {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
736 {"servername", OPT_SERVERNAME, 's',
737 "Set TLS extension servername (SNI) in ClientHello (default)"},
738 {"noservername", OPT_NOSERVERNAME, '-',
739 "Do not send the server name (SNI) extension in the ClientHello"},
740 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
741 "Hex dump of all TLS extensions received"},
742 #ifndef OPENSSL_NO_OCSP
743 {"status", OPT_STATUS, '-', "Request certificate status from server"},
745 {"serverinfo", OPT_SERVERINFO, 's',
746 "types Send empty ClientHello extensions (comma-separated numbers)"},
747 {"alpn", OPT_ALPN, 's',
748 "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
749 {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
750 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
752 OPT_SECTION("Protocol and version"),
753 #ifndef OPENSSL_NO_SSL3
754 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
756 #ifndef OPENSSL_NO_TLS1
757 {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
759 #ifndef OPENSSL_NO_TLS1_1
760 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
762 #ifndef OPENSSL_NO_TLS1_2
763 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
765 #ifndef OPENSSL_NO_TLS1_3
766 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
768 #ifndef OPENSSL_NO_DTLS
769 {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
770 {"timeout", OPT_TIMEOUT, '-',
771 "Enable send/receive timeout on DTLS connections"},
772 {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
774 #ifndef OPENSSL_NO_DTLS1
775 {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
777 #ifndef OPENSSL_NO_DTLS1_2
778 {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
780 #ifndef OPENSSL_NO_SCTP
781 {"sctp", OPT_SCTP, '-', "Use SCTP"},
782 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
784 #ifndef OPENSSL_NO_NEXTPROTONEG
785 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
786 "Enable NPN extension, considering named protocols supported (comma-separated list)"},
788 {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"},
789 {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"},
790 #ifndef OPENSSL_NO_SRTP
791 {"use_srtp", OPT_USE_SRTP, 's',
792 "Offer SRTP key management with a colon-separated profile list"},
794 #ifndef OPENSSL_NO_SRP
795 {"srpuser", OPT_SRPUSER, 's', "SRP authentication for 'user'"},
796 {"srppass", OPT_SRPPASS, 's', "Password for 'user'"},
797 {"srp_lateuser", OPT_SRP_LATEUSER, '-',
798 "SRP username into second ClientHello message"},
799 {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
800 "Tolerate other than the known g N values."},
801 {"srp_strength", OPT_SRP_STRENGTH, 'p', "Minimal length in bits for N"},
807 {"CRL", OPT_CRL, '<', "CRL file to use"},
808 {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
809 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
810 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
811 "Close connection on verification error"},
812 {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
813 {"chainCAfile", OPT_CHAINCAFILE, '<',
814 "CA file for certificate chain (PEM format)"},
815 {"chainCApath", OPT_CHAINCAPATH, '/',
816 "Use dir as certificate store path to build CA certificate chain"},
817 {"chainCAstore", OPT_CHAINCASTORE, ':',
818 "CA store URI for certificate chain"},
819 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
820 "CA file for certificate verification (PEM format)"},
821 {"verifyCApath", OPT_VERIFYCAPATH, '/',
822 "Use dir as certificate store path to verify CA certificate"},
823 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
824 "CA store URI for certificate verification"},
829 {"host:port", 0, 0, "Where to connect; same as -connect option"},
833 typedef enum PROTOCOL_choice {
852 static const OPT_PAIR services[] = {
853 {"smtp", PROTO_SMTP},
854 {"pop3", PROTO_POP3},
855 {"imap", PROTO_IMAP},
857 {"xmpp", PROTO_XMPP},
858 {"xmpp-server", PROTO_XMPP_SERVER},
859 {"telnet", PROTO_TELNET},
861 {"mysql", PROTO_MYSQL},
862 {"postgres", PROTO_POSTGRES},
863 {"lmtp", PROTO_LMTP},
864 {"nntp", PROTO_NNTP},
865 {"sieve", PROTO_SIEVE},
866 {"ldap", PROTO_LDAP},
870 #define IS_INET_FLAG(o) \
871 (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
872 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
874 #define IS_PROT_FLAG(o) \
875 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
876 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
878 /* Free |*dest| and optionally set it to a copy of |source|. */
879 static void freeandcopy(char **dest, const char *source)
884 *dest = OPENSSL_strdup(source);
887 static int new_session_cb(SSL *s, SSL_SESSION *sess)
890 if (sess_out != NULL) {
891 BIO *stmp = BIO_new_file(sess_out, "w");
894 BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
896 PEM_write_bio_SSL_SESSION(stmp, sess);
902 * Session data gets dumped on connection for TLSv1.2 and below, and on
903 * arrival of the NewSessionTicket for TLSv1.3.
905 if (SSL_version(s) == TLS1_3_VERSION) {
906 BIO_printf(bio_c_out,
907 "---\nPost-Handshake New Session Ticket arrived:\n");
908 SSL_SESSION_print(bio_c_out, sess);
909 BIO_printf(bio_c_out, "---\n");
913 * We always return a "fail" response so that the session gets freed again
914 * because we haven't used the reference.
919 int s_client_main(int argc, char **argv)
922 EVP_PKEY *key = NULL;
925 STACK_OF(X509) *chain = NULL;
927 X509_VERIFY_PARAM *vpm = NULL;
928 SSL_EXCERT *exc = NULL;
929 SSL_CONF_CTX *cctx = NULL;
930 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
931 char *dane_tlsa_domain = NULL;
932 STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
933 int dane_ee_no_name = 0;
934 STACK_OF(X509_CRL) *crls = NULL;
935 const SSL_METHOD *meth = TLS_client_method();
936 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
937 char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
938 char *proxystr = NULL, *proxyuser = NULL;
939 char *proxypassarg = NULL, *proxypass = NULL;
940 char *connectstr = NULL, *bindstr = NULL;
941 char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
942 char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL, *host = NULL;
943 char *port = OPENSSL_strdup(PORT);
944 char *bindhost = NULL, *bindport = NULL;
945 char *passarg = NULL, *pass = NULL;
946 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
947 char *ReqCAfile = NULL;
948 char *sess_in = NULL, *crl_file = NULL, *p;
949 const char *protohost = NULL;
950 struct timeval timeout, *timeoutp;
951 fd_set readfds, writefds;
952 int noCApath = 0, noCAfile = 0, noCAstore = 0;
953 int build_chain = 0, cbuf_len, cbuf_off, cert_format = FORMAT_PEM;
954 int key_format = FORMAT_PEM, crlf = 0, full_log = 1, mbuf_len = 0;
957 int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
958 int ret = 1, in_init = 1, i, nbio_test = 0, sock = -1, k, width, state = 0;
959 int sbuf_len, sbuf_off, cmdletters = 1;
960 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
961 int starttls_proto = PROTO_OFF, crl_format = FORMAT_PEM, crl_download = 0;
962 int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
963 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
966 int read_buf_len = 0;
967 int fallback_scsv = 0;
969 #ifndef OPENSSL_NO_DTLS
970 int enable_timeouts = 0;
973 #ifndef OPENSSL_NO_ENGINE
974 ENGINE *ssl_client_engine = NULL;
977 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
980 const char *servername = NULL;
981 int noservername = 0;
982 const char *alpn_in = NULL;
983 tlsextctx tlsextcbp = { NULL, 0 };
984 const char *ssl_config = NULL;
985 #define MAX_SI_TYPES 100
986 unsigned short serverinfo_types[MAX_SI_TYPES];
987 int serverinfo_count = 0, start = 0, len;
988 #ifndef OPENSSL_NO_NEXTPROTONEG
989 const char *next_proto_neg_in = NULL;
991 #ifndef OPENSSL_NO_SRP
992 char *srppass = NULL;
993 int srp_lateuser = 0;
994 SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
996 #ifndef OPENSSL_NO_SRTP
997 char *srtp_profiles = NULL;
999 #ifndef OPENSSL_NO_CT
1000 char *ctlog_file = NULL;
1001 int ct_validation = 0;
1003 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1005 unsigned int max_send_fragment = 0;
1006 unsigned int split_send_fragment = 0, max_pipelines = 0;
1007 enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
1009 uint8_t maxfraglen = 0;
1010 int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
1011 int c_tlsextdebug = 0;
1012 #ifndef OPENSSL_NO_OCSP
1013 int c_status_req = 0;
1015 BIO *bio_c_msg = NULL;
1016 const char *keylog_file = NULL, *early_data_file = NULL;
1017 #ifndef OPENSSL_NO_DTLS
1020 char *psksessf = NULL;
1022 #ifndef OPENSSL_NO_SCTP
1023 int sctp_label_bug = 0;
1028 /* Known false-positive of MemorySanitizer. */
1029 #if defined(__has_feature)
1030 # if __has_feature(memory_sanitizer)
1031 __msan_unpoison(&readfds, sizeof(readfds));
1032 __msan_unpoison(&writefds, sizeof(writefds));
1036 prog = opt_progname(argv[0]);
1041 vpm = X509_VERIFY_PARAM_new();
1042 cctx = SSL_CONF_CTX_new();
1044 if (vpm == NULL || cctx == NULL) {
1045 BIO_printf(bio_err, "%s: out of memory\n", prog);
1049 cbuf = app_malloc(BUFSIZZ, "cbuf");
1050 sbuf = app_malloc(BUFSIZZ, "sbuf");
1051 mbuf = app_malloc(BUFSIZZ, "mbuf");
1053 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
1055 prog = opt_init(argc, argv, s_client_options);
1056 while ((o = opt_next()) != OPT_EOF) {
1057 /* Check for intermixing flags. */
1058 if (connect_type == use_unix && IS_INET_FLAG(o)) {
1060 "%s: Intermixed protocol flags (unix and internet domains)\n",
1064 if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
1066 "%s: Intermixed protocol flags (internet and unix domains)\n",
1071 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1072 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1075 if (IS_NO_PROT_FLAG(o))
1077 if (prot_opt == 1 && no_prot_opt) {
1079 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1087 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1090 opt_help(s_client_options);
1094 connect_type = use_inet;
1095 socket_family = AF_INET;
1100 connect_type = use_inet;
1101 socket_family = AF_INET6;
1106 connect_type = use_inet;
1107 freeandcopy(&host, opt_arg());
1110 connect_type = use_inet;
1111 freeandcopy(&port, opt_arg());
1114 connect_type = use_inet;
1115 freeandcopy(&connectstr, opt_arg());
1118 freeandcopy(&bindstr, opt_arg());
1121 proxystr = opt_arg();
1122 starttls_proto = PROTO_CONNECT;
1124 case OPT_PROXY_USER:
1125 proxyuser = opt_arg();
1127 case OPT_PROXY_PASS:
1128 proxypassarg = opt_arg();
1132 connect_type = use_unix;
1133 socket_family = AF_UNIX;
1134 freeandcopy(&host, opt_arg());
1138 /* fall through, since this is an alias */
1140 protohost = opt_arg();
1143 verify = SSL_VERIFY_PEER;
1144 verify_args.depth = atoi(opt_arg());
1146 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1149 cert_file = opt_arg();
1152 if (!set_nameopt(opt_arg()))
1156 crl_file = opt_arg();
1158 case OPT_CRL_DOWNLOAD:
1162 sess_out = opt_arg();
1165 sess_in = opt_arg();
1168 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &cert_format))
1172 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1175 case OPT_VERIFY_RET_ERROR:
1176 verify = SSL_VERIFY_PEER;
1177 verify_args.return_error = 1;
1179 case OPT_VERIFY_QUIET:
1180 verify_args.quiet = 1;
1183 c_brief = verify_args.quiet = c_quiet = 1;
1186 if (ssl_args == NULL)
1187 ssl_args = sk_OPENSSL_STRING_new_null();
1188 if (ssl_args == NULL
1189 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1190 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1191 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1196 if (!opt_verify(o, vpm))
1201 if (!args_excert(o, &exc))
1211 c_quiet = c_ign_eof = 1;
1220 e = setup_engine(opt_arg(), 1);
1222 case OPT_SSL_CLIENT_ENGINE:
1223 #ifndef OPENSSL_NO_ENGINE
1224 ssl_client_engine = ENGINE_by_id(opt_arg());
1225 if (ssl_client_engine == NULL) {
1226 BIO_printf(bio_err, "Error getting client auth engine\n");
1235 case OPT_PROV_CASES:
1236 if (!opt_provider(o))
1242 case OPT_NO_IGN_EOF:
1248 case OPT_TLSEXTDEBUG:
1252 #ifndef OPENSSL_NO_OCSP
1265 bio_c_msg = BIO_new_file(opt_arg(), "w");
1268 #ifndef OPENSSL_NO_SSL_TRACE
1272 case OPT_SECURITY_DEBUG:
1275 case OPT_SECURITY_DEBUG_VERBOSE:
1287 case OPT_PSK_IDENTITY:
1288 psk_identity = opt_arg();
1291 for (p = psk_key = opt_arg(); *p; p++) {
1292 if (isxdigit(_UC(*p)))
1294 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1299 psksessf = opt_arg();
1301 #ifndef OPENSSL_NO_SRP
1303 srp_arg.srplogin = opt_arg();
1304 if (min_version < TLS1_VERSION)
1305 min_version = TLS1_VERSION;
1308 srppass = opt_arg();
1309 if (min_version < TLS1_VERSION)
1310 min_version = TLS1_VERSION;
1312 case OPT_SRP_STRENGTH:
1313 srp_arg.strength = atoi(opt_arg());
1314 BIO_printf(bio_err, "SRP minimal length for N is %d\n",
1316 if (min_version < TLS1_VERSION)
1317 min_version = TLS1_VERSION;
1319 case OPT_SRP_LATEUSER:
1321 if (min_version < TLS1_VERSION)
1322 min_version = TLS1_VERSION;
1324 case OPT_SRP_MOREGROUPS:
1326 if (min_version < TLS1_VERSION)
1327 min_version = TLS1_VERSION;
1330 case OPT_SSL_CONFIG:
1331 ssl_config = opt_arg();
1334 min_version = SSL3_VERSION;
1335 max_version = SSL3_VERSION;
1338 min_version = TLS1_3_VERSION;
1339 max_version = TLS1_3_VERSION;
1342 min_version = TLS1_2_VERSION;
1343 max_version = TLS1_2_VERSION;
1346 min_version = TLS1_1_VERSION;
1347 max_version = TLS1_1_VERSION;
1350 min_version = TLS1_VERSION;
1351 max_version = TLS1_VERSION;
1354 #ifndef OPENSSL_NO_DTLS
1355 meth = DTLS_client_method();
1356 socket_type = SOCK_DGRAM;
1361 #ifndef OPENSSL_NO_DTLS1
1362 meth = DTLS_client_method();
1363 min_version = DTLS1_VERSION;
1364 max_version = DTLS1_VERSION;
1365 socket_type = SOCK_DGRAM;
1370 #ifndef OPENSSL_NO_DTLS1_2
1371 meth = DTLS_client_method();
1372 min_version = DTLS1_2_VERSION;
1373 max_version = DTLS1_2_VERSION;
1374 socket_type = SOCK_DGRAM;
1379 #ifndef OPENSSL_NO_SCTP
1380 protocol = IPPROTO_SCTP;
1383 case OPT_SCTP_LABEL_BUG:
1384 #ifndef OPENSSL_NO_SCTP
1389 #ifndef OPENSSL_NO_DTLS
1390 enable_timeouts = 1;
1394 #ifndef OPENSSL_NO_DTLS
1395 socket_mtu = atol(opt_arg());
1398 case OPT_FALLBACKSCSV:
1402 if (!opt_format(opt_arg(), OPT_FMT_PDE, &key_format))
1406 passarg = opt_arg();
1408 case OPT_CERT_CHAIN:
1409 chain_file = opt_arg();
1412 key_file = opt_arg();
1423 case OPT_CHAINCAPATH:
1424 chCApath = opt_arg();
1426 case OPT_VERIFYCAPATH:
1427 vfyCApath = opt_arg();
1429 case OPT_BUILD_CHAIN:
1433 ReqCAfile = opt_arg();
1441 #ifndef OPENSSL_NO_CT
1448 case OPT_CTLOG_FILE:
1449 ctlog_file = opt_arg();
1452 case OPT_CHAINCAFILE:
1453 chCAfile = opt_arg();
1455 case OPT_VERIFYCAFILE:
1456 vfyCAfile = opt_arg();
1459 CAstore = opt_arg();
1464 case OPT_CHAINCASTORE:
1465 chCAstore = opt_arg();
1467 case OPT_VERIFYCASTORE:
1468 vfyCAstore = opt_arg();
1470 case OPT_DANE_TLSA_DOMAIN:
1471 dane_tlsa_domain = opt_arg();
1473 case OPT_DANE_TLSA_RRDATA:
1474 if (dane_tlsa_rrset == NULL)
1475 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1476 if (dane_tlsa_rrset == NULL ||
1477 !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1478 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1482 case OPT_DANE_EE_NO_NAME:
1483 dane_ee_no_name = 1;
1485 case OPT_NEXTPROTONEG:
1486 #ifndef OPENSSL_NO_NEXTPROTONEG
1487 next_proto_neg_in = opt_arg();
1491 alpn_in = opt_arg();
1493 case OPT_SERVERINFO:
1496 for (start = 0, i = 0; i <= len; ++i) {
1497 if (i == len || p[i] == ',') {
1498 serverinfo_types[serverinfo_count] = atoi(p + start);
1499 if (++serverinfo_count == MAX_SI_TYPES)
1506 if (!opt_pair(opt_arg(), services, &starttls_proto))
1509 case OPT_SERVERNAME:
1510 servername = opt_arg();
1512 case OPT_NOSERVERNAME:
1516 #ifndef OPENSSL_NO_SRTP
1517 srtp_profiles = opt_arg();
1520 case OPT_KEYMATEXPORT:
1521 keymatexportlabel = opt_arg();
1523 case OPT_KEYMATEXPORTLEN:
1524 keymatexportlen = atoi(opt_arg());
1529 case OPT_MAXFRAGLEN:
1530 len = atoi(opt_arg());
1533 maxfraglen = TLSEXT_max_fragment_length_512;
1536 maxfraglen = TLSEXT_max_fragment_length_1024;
1539 maxfraglen = TLSEXT_max_fragment_length_2048;
1542 maxfraglen = TLSEXT_max_fragment_length_4096;
1546 "%s: Max Fragment Len %u is out of permitted values",
1551 case OPT_MAX_SEND_FRAG:
1552 max_send_fragment = atoi(opt_arg());
1554 case OPT_SPLIT_SEND_FRAG:
1555 split_send_fragment = atoi(opt_arg());
1557 case OPT_MAX_PIPELINES:
1558 max_pipelines = atoi(opt_arg());
1561 read_buf_len = atoi(opt_arg());
1563 case OPT_KEYLOG_FILE:
1564 keylog_file = opt_arg();
1566 case OPT_EARLY_DATA:
1567 early_data_file = opt_arg();
1569 case OPT_ENABLE_PHA:
1575 if (count4or6 >= 2) {
1576 BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1580 if (servername != NULL) {
1582 "%s: Can't use -servername and -noservername together\n",
1586 if (dane_tlsa_domain != NULL) {
1588 "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1593 argc = opt_num_rest();
1595 /* If there's a positional argument, it's the equivalent of
1597 * Don't allow -connect and a separate argument.
1599 if (connectstr != NULL) {
1601 "%s: must not provide both -connect option and target parameter\n",
1605 connect_type = use_inet;
1606 freeandcopy(&connectstr, *opt_rest());
1607 } else if (argc != 0) {
1611 #ifndef OPENSSL_NO_NEXTPROTONEG
1612 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1613 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1617 if (proxystr != NULL) {
1619 char *tmp_host = host, *tmp_port = port;
1620 if (connectstr == NULL) {
1621 BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
1624 res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1625 if (tmp_host != host)
1626 OPENSSL_free(tmp_host);
1627 if (tmp_port != port)
1628 OPENSSL_free(tmp_port);
1631 "%s: -proxy argument malformed or ambiguous\n", prog);
1636 char *tmp_host = host, *tmp_port = port;
1637 if (connectstr != NULL)
1638 res = BIO_parse_hostserv(connectstr, &host, &port,
1639 BIO_PARSE_PRIO_HOST);
1640 if (tmp_host != host)
1641 OPENSSL_free(tmp_host);
1642 if (tmp_port != port)
1643 OPENSSL_free(tmp_port);
1646 "%s: -connect argument or target parameter malformed or ambiguous\n",
1652 if (bindstr != NULL) {
1654 res = BIO_parse_hostserv(bindstr, &bindhost, &bindport,
1655 BIO_PARSE_PRIO_HOST);
1658 "%s: -bind argument parameter malformed or ambiguous\n",
1665 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1667 "Can't use unix sockets and datagrams together\n");
1672 #ifndef OPENSSL_NO_SCTP
1673 if (protocol == IPPROTO_SCTP) {
1674 if (socket_type != SOCK_DGRAM) {
1675 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1678 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1679 socket_type = SOCK_STREAM;
1683 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1684 next_proto.status = -1;
1685 if (next_proto_neg_in) {
1687 next_protos_parse(&next_proto.len, next_proto_neg_in);
1688 if (next_proto.data == NULL) {
1689 BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1693 next_proto.data = NULL;
1696 if (!app_passwd(passarg, NULL, &pass, NULL)) {
1697 BIO_printf(bio_err, "Error getting private key password\n");
1701 if (!app_passwd(proxypassarg, NULL, &proxypass, NULL)) {
1702 BIO_printf(bio_err, "Error getting proxy password\n");
1706 if (proxypass != NULL && proxyuser == NULL) {
1707 BIO_printf(bio_err, "Error: Must specify proxy_user with proxy_pass\n");
1711 if (key_file == NULL)
1712 key_file = cert_file;
1714 if (key_file != NULL) {
1715 key = load_key(key_file, key_format, 0, pass, e,
1716 "client certificate private key file");
1721 if (cert_file != NULL) {
1722 cert = load_cert(cert_file, cert_format, "client certificate file");
1727 if (chain_file != NULL) {
1728 if (!load_certs(chain_file, &chain, FORMAT_PEM, NULL,
1729 "client certificate chain"))
1733 if (crl_file != NULL) {
1735 crl = load_crl(crl_file, crl_format, "CRL");
1738 crls = sk_X509_CRL_new_null();
1739 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1740 BIO_puts(bio_err, "Error adding CRL\n");
1741 ERR_print_errors(bio_err);
1747 if (!load_excert(&exc))
1750 if (bio_c_out == NULL) {
1751 if (c_quiet && !c_debug) {
1752 bio_c_out = BIO_new(BIO_s_null());
1753 if (c_msg && bio_c_msg == NULL)
1754 bio_c_msg = dup_bio_out(FORMAT_TEXT);
1755 } else if (bio_c_out == NULL)
1756 bio_c_out = dup_bio_out(FORMAT_TEXT);
1758 #ifndef OPENSSL_NO_SRP
1759 if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1760 BIO_printf(bio_err, "Error getting password\n");
1765 ctx = SSL_CTX_new(meth);
1767 ERR_print_errors(bio_err);
1771 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1774 ssl_ctx_security_debug(ctx, sdebug);
1776 if (!config_ctx(cctx, ssl_args, ctx))
1779 if (ssl_config != NULL) {
1780 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1781 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1783 ERR_print_errors(bio_err);
1788 #ifndef OPENSSL_NO_SCTP
1789 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1790 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1793 if (min_version != 0
1794 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1796 if (max_version != 0
1797 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1800 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1801 BIO_printf(bio_err, "Error setting verify params\n");
1802 ERR_print_errors(bio_err);
1807 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1810 if (max_send_fragment > 0
1811 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1812 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1813 prog, max_send_fragment);
1817 if (split_send_fragment > 0
1818 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1819 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1820 prog, split_send_fragment);
1824 if (max_pipelines > 0
1825 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1826 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1827 prog, max_pipelines);
1831 if (read_buf_len > 0) {
1832 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1836 && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
1838 "%s: Max Fragment Length code %u is out of permitted values"
1839 "\n", prog, maxfraglen);
1843 if (!ssl_load_stores(ctx,
1844 vfyCApath, vfyCAfile, vfyCAstore,
1845 chCApath, chCAfile, chCAstore,
1846 crls, crl_download)) {
1847 BIO_printf(bio_err, "Error loading store locations\n");
1848 ERR_print_errors(bio_err);
1851 if (ReqCAfile != NULL) {
1852 STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
1854 if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
1855 sk_X509_NAME_pop_free(nm, X509_NAME_free);
1856 BIO_printf(bio_err, "Error loading CA names\n");
1857 ERR_print_errors(bio_err);
1860 SSL_CTX_set0_CA_list(ctx, nm);
1862 #ifndef OPENSSL_NO_ENGINE
1863 if (ssl_client_engine) {
1864 if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1865 BIO_puts(bio_err, "Error setting client auth engine\n");
1866 ERR_print_errors(bio_err);
1867 ENGINE_free(ssl_client_engine);
1870 ENGINE_free(ssl_client_engine);
1874 #ifndef OPENSSL_NO_PSK
1875 if (psk_key != NULL) {
1877 BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1878 SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1881 if (psksessf != NULL) {
1882 BIO *stmp = BIO_new_file(psksessf, "r");
1885 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
1886 ERR_print_errors(bio_err);
1889 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1891 if (psksess == NULL) {
1892 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
1893 ERR_print_errors(bio_err);
1897 if (psk_key != NULL || psksess != NULL)
1898 SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
1900 #ifndef OPENSSL_NO_SRTP
1901 if (srtp_profiles != NULL) {
1902 /* Returns 0 on success! */
1903 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1904 BIO_printf(bio_err, "Error setting SRTP profile\n");
1905 ERR_print_errors(bio_err);
1912 ssl_ctx_set_excert(ctx, exc);
1914 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1915 if (next_proto.data != NULL)
1916 SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1920 unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1923 BIO_printf(bio_err, "Error parsing -alpn argument\n");
1926 /* Returns 0 on success! */
1927 if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1928 BIO_printf(bio_err, "Error setting ALPN\n");
1934 for (i = 0; i < serverinfo_count; i++) {
1935 if (!SSL_CTX_add_client_custom_ext(ctx,
1936 serverinfo_types[i],
1938 serverinfo_cli_parse_cb, NULL)) {
1940 "Warning: Unable to add custom extension %u, skipping\n",
1941 serverinfo_types[i]);
1946 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1948 #ifndef OPENSSL_NO_CT
1949 /* Enable SCT processing, without early connection termination */
1950 if (ct_validation &&
1951 !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
1952 ERR_print_errors(bio_err);
1956 if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
1957 if (ct_validation) {
1958 ERR_print_errors(bio_err);
1963 * If CT validation is not enabled, the log list isn't needed so don't
1964 * show errors or abort. We try to load it regardless because then we
1965 * can show the names of the logs any SCTs came from (SCTs may be seen
1966 * even with validation disabled).
1972 SSL_CTX_set_verify(ctx, verify, verify_callback);
1974 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1975 CAstore, noCAstore)) {
1976 ERR_print_errors(bio_err);
1980 ssl_ctx_add_crls(ctx, crls, crl_download);
1982 if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
1985 if (!noservername) {
1986 tlsextcbp.biodebug = bio_err;
1987 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1988 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1990 # ifndef OPENSSL_NO_SRP
1991 if (srp_arg.srplogin) {
1992 if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) {
1993 BIO_printf(bio_err, "Unable to set SRP username\n");
1996 srp_arg.msg = c_msg;
1997 srp_arg.debug = c_debug;
1998 SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
1999 SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
2000 SSL_CTX_set_srp_strength(ctx, srp_arg.strength);
2001 if (c_msg || c_debug || srp_arg.amp == 0)
2002 SSL_CTX_set_srp_verify_param_callback(ctx,
2003 ssl_srp_verify_param_cb);
2007 if (dane_tlsa_domain != NULL) {
2008 if (SSL_CTX_dane_enable(ctx) <= 0) {
2010 "%s: Error enabling DANE TLSA authentication.\n",
2012 ERR_print_errors(bio_err);
2018 * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
2019 * come at any time. Therefore we use a callback to write out the session
2020 * when we know about it. This approach works for < TLSv1.3 as well.
2022 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT
2023 | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2024 SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
2026 if (set_keylog_file(ctx, keylog_file))
2034 SSL_set_post_handshake_auth(con, 1);
2036 if (sess_in != NULL) {
2038 BIO *stmp = BIO_new_file(sess_in, "r");
2040 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2041 ERR_print_errors(bio_err);
2044 sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2047 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2048 ERR_print_errors(bio_err);
2051 if (!SSL_set_session(con, sess)) {
2052 BIO_printf(bio_err, "Can't set session\n");
2053 ERR_print_errors(bio_err);
2057 SSL_SESSION_free(sess);
2061 SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
2063 if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
2064 if (servername == NULL) {
2065 if(host == NULL || is_dNS_name(host))
2066 servername = (host == NULL) ? "localhost" : host;
2068 if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) {
2069 BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
2070 ERR_print_errors(bio_err);
2075 if (dane_tlsa_domain != NULL) {
2076 if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
2077 BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
2078 "authentication.\n", prog);
2079 ERR_print_errors(bio_err);
2082 if (dane_tlsa_rrset == NULL) {
2083 BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
2084 "least one -dane_tlsa_rrdata option.\n", prog);
2087 if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
2088 BIO_printf(bio_err, "%s: Failed to import any TLSA "
2089 "records.\n", prog);
2092 if (dane_ee_no_name)
2093 SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
2094 } else if (dane_tlsa_rrset != NULL) {
2095 BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
2096 "-dane_tlsa_domain option.\n", prog);
2101 if (init_client(&sock, host, port, bindhost, bindport, socket_family,
2102 socket_type, protocol) == 0) {
2103 BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
2104 BIO_closesocket(sock);
2107 BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock);
2110 if (!BIO_socket_nbio(sock, 1)) {
2111 ERR_print_errors(bio_err);
2114 BIO_printf(bio_c_out, "Turned on non blocking io\n");
2116 #ifndef OPENSSL_NO_DTLS
2118 union BIO_sock_info_u peer_info;
2120 #ifndef OPENSSL_NO_SCTP
2121 if (protocol == IPPROTO_SCTP)
2122 sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
2125 sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
2127 if ((peer_info.addr = BIO_ADDR_new()) == NULL) {
2128 BIO_printf(bio_err, "memory allocation failure\n");
2129 BIO_closesocket(sock);
2132 if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
2133 BIO_printf(bio_err, "getsockname:errno=%d\n",
2134 get_last_socket_error());
2135 BIO_ADDR_free(peer_info.addr);
2136 BIO_closesocket(sock);
2140 (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
2141 BIO_ADDR_free(peer_info.addr);
2142 peer_info.addr = NULL;
2144 if (enable_timeouts) {
2146 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2147 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2150 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2151 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2155 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2156 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2157 DTLS_get_link_min_mtu(con));
2161 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2162 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2163 BIO_printf(bio_err, "Failed to set MTU\n");
2168 /* want to do MTU discovery */
2169 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2172 #endif /* OPENSSL_NO_DTLS */
2173 sbio = BIO_new_socket(sock, BIO_NOCLOSE);
2178 test = BIO_new(BIO_f_nbio_test());
2179 sbio = BIO_push(test, sbio);
2183 BIO_set_callback(sbio, bio_dump_callback);
2184 BIO_set_callback_arg(sbio, (char *)bio_c_out);
2187 #ifndef OPENSSL_NO_SSL_TRACE
2189 SSL_set_msg_callback(con, SSL_trace);
2192 SSL_set_msg_callback(con, msg_cb);
2193 SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
2196 if (c_tlsextdebug) {
2197 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2198 SSL_set_tlsext_debug_arg(con, bio_c_out);
2200 #ifndef OPENSSL_NO_OCSP
2202 SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
2203 SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
2204 SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
2208 SSL_set_bio(con, sbio, sbio);
2209 SSL_set_connect_state(con);
2211 /* ok, lets connect */
2212 if (fileno_stdin() > SSL_get_fd(con))
2213 width = fileno_stdin() + 1;
2215 width = SSL_get_fd(con) + 1;
2228 switch ((PROTOCOL_CHOICE) starttls_proto) {
2235 * This is an ugly hack that does a lot of assumptions. We do
2236 * have to handle multi-line responses which may come in a single
2237 * packet or not. We therefore have to use BIO_gets() which does
2238 * need a buffering BIO. So during the initial chitchat we do
2239 * push a buffering BIO into the chain that is removed again
2240 * later on to not disturb the rest of the s_client operation.
2243 BIO *fbio = BIO_new(BIO_f_buffer());
2245 BIO_push(fbio, sbio);
2246 /* Wait for multi-line response to end from LMTP or SMTP */
2248 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2249 } while (mbuf_len > 3 && mbuf[3] == '-');
2250 if (protohost == NULL)
2251 protohost = "mail.example.com";
2252 if (starttls_proto == (int)PROTO_LMTP)
2253 BIO_printf(fbio, "LHLO %s\r\n", protohost);
2255 BIO_printf(fbio, "EHLO %s\r\n", protohost);
2256 (void)BIO_flush(fbio);
2258 * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2262 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2263 if (strstr(mbuf, "STARTTLS"))
2265 } while (mbuf_len > 3 && mbuf[3] == '-');
2266 (void)BIO_flush(fbio);
2271 "Didn't find STARTTLS in server response,"
2272 " trying anyway...\n");
2273 BIO_printf(sbio, "STARTTLS\r\n");
2274 BIO_read(sbio, sbuf, BUFSIZZ);
2279 BIO_read(sbio, mbuf, BUFSIZZ);
2280 BIO_printf(sbio, "STLS\r\n");
2281 mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
2283 BIO_printf(bio_err, "BIO_read failed\n");
2291 BIO *fbio = BIO_new(BIO_f_buffer());
2293 BIO_push(fbio, sbio);
2294 BIO_gets(fbio, mbuf, BUFSIZZ);
2295 /* STARTTLS command requires CAPABILITY... */
2296 BIO_printf(fbio, ". CAPABILITY\r\n");
2297 (void)BIO_flush(fbio);
2298 /* wait for multi-line CAPABILITY response */
2300 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2301 if (strstr(mbuf, "STARTTLS"))
2304 while (mbuf_len > 3 && mbuf[0] != '.');
2305 (void)BIO_flush(fbio);
2310 "Didn't find STARTTLS in server response,"
2311 " trying anyway...\n");
2312 BIO_printf(sbio, ". STARTTLS\r\n");
2313 BIO_read(sbio, sbuf, BUFSIZZ);
2318 BIO *fbio = BIO_new(BIO_f_buffer());
2320 BIO_push(fbio, sbio);
2321 /* wait for multi-line response to end from FTP */
2323 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2325 while (mbuf_len > 3 && (!isdigit(mbuf[0]) || !isdigit(mbuf[1]) || !isdigit(mbuf[2]) || mbuf[3] != ' '));
2326 (void)BIO_flush(fbio);
2329 BIO_printf(sbio, "AUTH TLS\r\n");
2330 BIO_read(sbio, sbuf, BUFSIZZ);
2334 case PROTO_XMPP_SERVER:
2337 BIO_printf(sbio, "<stream:stream "
2338 "xmlns:stream='http://etherx.jabber.org/streams' "
2339 "xmlns='jabber:%s' to='%s' version='1.0'>",
2340 starttls_proto == PROTO_XMPP ? "client" : "server",
2341 protohost ? protohost : host);
2342 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2344 BIO_printf(bio_err, "BIO_read failed\n");
2349 (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2351 "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2353 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2361 "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2362 seen = BIO_read(sbio, sbuf, BUFSIZZ);
2364 BIO_printf(bio_err, "BIO_read failed\n");
2368 if (!strstr(sbuf, "<proceed"))
2375 static const unsigned char tls_do[] = {
2376 /* IAC DO START_TLS */
2379 static const unsigned char tls_will[] = {
2380 /* IAC WILL START_TLS */
2383 static const unsigned char tls_follows[] = {
2384 /* IAC SB START_TLS FOLLOWS IAC SE */
2385 255, 250, 46, 1, 255, 240
2389 /* Telnet server should demand we issue START_TLS */
2390 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2391 if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
2393 /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2394 BIO_write(sbio, tls_will, 3);
2395 BIO_write(sbio, tls_follows, 6);
2396 (void)BIO_flush(sbio);
2397 /* Telnet server also sent the FOLLOWS sub-command */
2398 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2399 if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2404 if (!OSSL_HTTP_proxy_connect(sbio, host, port, proxyuser, proxypass,
2405 0 /* no timeout */, bio_err, prog))
2411 BIO *fbio = BIO_new(BIO_f_buffer());
2413 BIO_push(fbio, sbio);
2414 BIO_printf(fbio, "STARTTLS\r\n");
2415 (void)BIO_flush(fbio);
2416 width = SSL_get_fd(con) + 1;
2422 openssl_fdset(SSL_get_fd(con), &readfds);
2423 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2424 timeout.tv_usec = 0;
2426 * If the IRCd doesn't respond within
2427 * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2428 * it doesn't support STARTTLS. Many IRCds
2429 * will not give _any_ sort of response to a
2430 * STARTTLS command when it's not supported.
2432 if (!BIO_get_buffer_num_lines(fbio)
2433 && !BIO_pending(fbio)
2434 && !BIO_pending(sbio)
2435 && select(width, (void *)&readfds, NULL, NULL,
2438 "Timeout waiting for response (%d seconds).\n",
2439 S_CLIENT_IRC_READ_TIMEOUT);
2443 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2444 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2446 /* :example.net 451 STARTTLS :You have not registered */
2447 /* :example.net 421 STARTTLS :Unknown command */
2448 if ((numeric == 451 || numeric == 421)
2449 && strstr(mbuf, "STARTTLS") != NULL) {
2450 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2453 if (numeric == 691) {
2454 BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2455 ERR_print_errors(bio_err);
2458 } while (numeric != 670);
2460 (void)BIO_flush(fbio);
2463 if (numeric != 670) {
2464 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2472 /* SSL request packet */
2473 static const unsigned char ssl_req[] = {
2474 /* payload_length, sequence_id */
2475 0x20, 0x00, 0x00, 0x01,
2477 /* capability flags, CLIENT_SSL always set */
2478 0x85, 0xae, 0x7f, 0x00,
2479 /* max-packet size */
2480 0x00, 0x00, 0x00, 0x01,
2483 /* string[23] reserved (all [0]) */
2484 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2485 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2486 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2489 int ssl_flg = 0x800;
2491 const unsigned char *packet = (const unsigned char *)sbuf;
2493 /* Receiving Initial Handshake packet. */
2494 bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
2496 BIO_printf(bio_err, "BIO_read failed\n");
2498 /* Packet length[3], Packet number[1] + minimum payload[17] */
2499 } else if (bytes < 21) {
2500 BIO_printf(bio_err, "MySQL packet too short.\n");
2502 } else if (bytes != (4 + packet[0] +
2504 (packet[2] << 16))) {
2505 BIO_printf(bio_err, "MySQL packet length does not match.\n");
2507 /* protocol version[1] */
2508 } else if (packet[4] != 0xA) {
2510 "Only MySQL protocol version 10 is supported.\n");
2515 /* server version[string+NULL] */
2518 BIO_printf(bio_err, "Cannot confirm server version. ");
2520 } else if (packet[pos++] == '\0') {
2525 /* make sure we have at least 15 bytes left in the packet */
2526 if (pos + 15 > bytes) {
2528 "MySQL server handshake packet is broken.\n");
2532 pos += 12; /* skip over conn id[4] + SALT[8] */
2533 if (packet[pos++] != '\0') { /* verify filler */
2535 "MySQL packet is broken.\n");
2539 /* capability flags[2] */
2540 if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
2541 BIO_printf(bio_err, "MySQL server does not support SSL.\n");
2545 /* Sending SSL Handshake packet. */
2546 BIO_write(sbio, ssl_req, sizeof(ssl_req));
2547 (void)BIO_flush(sbio);
2550 case PROTO_POSTGRES:
2552 static const unsigned char ssl_request[] = {
2553 /* Length SSLRequest */
2554 0, 0, 0, 8, 4, 210, 22, 47
2558 /* Send SSLRequest packet */
2559 BIO_write(sbio, ssl_request, 8);
2560 (void)BIO_flush(sbio);
2562 /* Reply will be a single S if SSL is enabled */
2563 bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2564 if (bytes != 1 || sbuf[0] != 'S')
2571 BIO *fbio = BIO_new(BIO_f_buffer());
2573 BIO_push(fbio, sbio);
2574 BIO_gets(fbio, mbuf, BUFSIZZ);
2575 /* STARTTLS command requires CAPABILITIES... */
2576 BIO_printf(fbio, "CAPABILITIES\r\n");
2577 (void)BIO_flush(fbio);
2578 BIO_gets(fbio, mbuf, BUFSIZZ);
2579 /* no point in trying to parse the CAPABILITIES response if there is none */
2580 if (strstr(mbuf, "101") != NULL) {
2581 /* wait for multi-line CAPABILITIES response */
2583 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2584 if (strstr(mbuf, "STARTTLS"))
2586 } while (mbuf_len > 1 && mbuf[0] != '.');
2588 (void)BIO_flush(fbio);
2593 "Didn't find STARTTLS in server response,"
2594 " trying anyway...\n");
2595 BIO_printf(sbio, "STARTTLS\r\n");
2596 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2598 BIO_printf(bio_err, "BIO_read failed\n");
2601 mbuf[mbuf_len] = '\0';
2602 if (strstr(mbuf, "382") == NULL) {
2603 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2611 BIO *fbio = BIO_new(BIO_f_buffer());
2613 BIO_push(fbio, sbio);
2614 /* wait for multi-line response to end from Sieve */
2616 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2618 * According to RFC 5804 § 1.7, capability
2619 * is case-insensitive, make it uppercase
2621 if (mbuf_len > 1 && mbuf[0] == '"') {
2622 make_uppercase(mbuf);
2623 if (strncmp(mbuf, "\"STARTTLS\"", 10) == 0)
2626 } while (mbuf_len > 1 && mbuf[0] == '"');
2627 (void)BIO_flush(fbio);
2632 "Didn't find STARTTLS in server response,"
2633 " trying anyway...\n");
2634 BIO_printf(sbio, "STARTTLS\r\n");
2635 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2637 BIO_printf(bio_err, "BIO_read failed\n");
2640 mbuf[mbuf_len] = '\0';
2642 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2646 * According to RFC 5804 § 2.2, response codes are case-
2647 * insensitive, make it uppercase but preserve the response.
2649 strncpy(sbuf, mbuf, 2);
2650 make_uppercase(sbuf);
2651 if (strncmp(sbuf, "OK", 2) != 0) {
2652 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2659 /* StartTLS Operation according to RFC 4511 */
2660 static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
2662 "messageID=INTEGER:1\n"
2663 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2664 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2666 char *genstr = NULL;
2668 ASN1_TYPE *atyp = NULL;
2669 BIO *ldapbio = BIO_new(BIO_s_mem());
2670 CONF *cnf = NCONF_new(NULL);
2676 BIO_puts(ldapbio, ldap_tls_genconf);
2677 if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
2681 BIO_printf(bio_err, "NCONF_load_bio failed\n");
2684 BIO_printf(bio_err, "Error on line %ld\n", errline);
2689 genstr = NCONF_get_string(cnf, "default", "asn1");
2690 if (genstr == NULL) {
2692 BIO_printf(bio_err, "NCONF_get_string failed\n");
2695 atyp = ASN1_generate_nconf(genstr, cnf);
2698 BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
2703 /* Send SSLRequest packet */
2704 BIO_write(sbio, atyp->value.sequence->data,
2705 atyp->value.sequence->length);
2706 (void)BIO_flush(sbio);
2707 ASN1_TYPE_free(atyp);
2709 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2711 BIO_printf(bio_err, "BIO_read failed\n");
2714 result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
2716 BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
2718 } else if (result > 0) {
2719 BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
2728 if (early_data_file != NULL
2729 && ((SSL_get0_session(con) != NULL
2730 && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
2732 && SSL_SESSION_get_max_early_data(psksess) > 0))) {
2733 BIO *edfile = BIO_new_file(early_data_file, "r");
2734 size_t readbytes, writtenbytes;
2737 if (edfile == NULL) {
2738 BIO_printf(bio_err, "Cannot open early data file\n");
2743 if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
2746 while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
2747 switch (SSL_get_error(con, 0)) {
2748 case SSL_ERROR_WANT_WRITE:
2749 case SSL_ERROR_WANT_ASYNC:
2750 case SSL_ERROR_WANT_READ:
2751 /* Just keep trying - busy waiting */
2754 BIO_printf(bio_err, "Error writing early data\n");
2756 ERR_print_errors(bio_err);
2769 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2770 timeoutp = &timeout;
2774 if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
2775 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
2784 BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2785 print_ssl_summary(con);
2788 print_stuff(bio_c_out, con, full_log);
2792 if (starttls_proto) {
2793 BIO_write(bio_err, mbuf, mbuf_len);
2794 /* We don't need to know any more */
2796 starttls_proto = PROTO_OFF;
2801 BIO_printf(bio_c_out,
2802 "drop connection and then reconnect\n");
2803 do_ssl_shutdown(con);
2804 SSL_set_connect_state(con);
2805 BIO_closesocket(SSL_get_fd(con));
2811 ssl_pending = read_ssl && SSL_has_pending(con);
2814 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2817 * Note that select() returns when read _would not block_,
2818 * and EOF satisfies that. To avoid a CPU-hogging loop,
2819 * set the flag so we exit.
2821 if (read_tty && !at_eof)
2822 openssl_fdset(fileno_stdin(), &readfds);
2823 #if !defined(OPENSSL_SYS_VMS)
2825 openssl_fdset(fileno_stdout(), &writefds);
2829 openssl_fdset(SSL_get_fd(con), &readfds);
2831 openssl_fdset(SSL_get_fd(con), &writefds);
2833 if (!tty_on || !write_tty) {
2835 openssl_fdset(SSL_get_fd(con), &readfds);
2837 openssl_fdset(SSL_get_fd(con), &writefds);
2842 * Note: under VMS with SOCKETSHR the second parameter is
2843 * currently of type (int *) whereas under other systems it is
2844 * (void *) if you don't have a cast it will choke the compiler:
2845 * if you do have a cast then you can either go for (int *) or
2848 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2850 * Under Windows/DOS we make the assumption that we can always
2851 * write to the tty: therefore if we need to write to the tty we
2852 * just fall through. Otherwise we timeout the select every
2853 * second and see if there are any keypresses. Note: this is a
2854 * hack, in a proper Windows application we wouldn't do this.
2861 i = select(width, (void *)&readfds, (void *)&writefds,
2863 if (!i && (!has_stdin_waiting() || !read_tty))
2866 i = select(width, (void *)&readfds, (void *)&writefds,
2870 i = select(width, (void *)&readfds, (void *)&writefds,
2874 BIO_printf(bio_err, "bad select %d\n",
2875 get_last_socket_error());
2880 if (SSL_is_dtls(con) && DTLSv1_handle_timeout(con) > 0)
2881 BIO_printf(bio_err, "TIMEOUT occurred\n");
2883 if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
2884 k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
2885 switch (SSL_get_error(con, k)) {
2886 case SSL_ERROR_NONE:
2891 /* we have done a write(con,NULL,0); */
2892 if (cbuf_len <= 0) {
2895 } else { /* if (cbuf_len > 0) */
2901 case SSL_ERROR_WANT_WRITE:
2902 BIO_printf(bio_c_out, "write W BLOCK\n");
2906 case SSL_ERROR_WANT_ASYNC:
2907 BIO_printf(bio_c_out, "write A BLOCK\n");
2908 wait_for_async(con);
2912 case SSL_ERROR_WANT_READ:
2913 BIO_printf(bio_c_out, "write R BLOCK\n");
2918 case SSL_ERROR_WANT_X509_LOOKUP:
2919 BIO_printf(bio_c_out, "write X BLOCK\n");
2921 case SSL_ERROR_ZERO_RETURN:
2922 if (cbuf_len != 0) {
2923 BIO_printf(bio_c_out, "shutdown\n");
2932 case SSL_ERROR_SYSCALL:
2933 if ((k != 0) || (cbuf_len != 0)) {
2934 BIO_printf(bio_err, "write:errno=%d\n",
2935 get_last_socket_error());
2942 case SSL_ERROR_WANT_ASYNC_JOB:
2943 /* This shouldn't ever happen in s_client - treat as an error */
2945 ERR_print_errors(bio_err);
2949 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
2950 /* Assume Windows/DOS/BeOS can always write */
2951 else if (!ssl_pending && write_tty)
2953 else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
2956 #ifdef CHARSET_EBCDIC
2957 ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
2959 i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
2962 BIO_printf(bio_c_out, "DONE\n");
2969 if (sbuf_len <= 0) {
2973 } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
2978 SSL_renegotiate(con);
2983 k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
2985 switch (SSL_get_error(con, k)) {
2986 case SSL_ERROR_NONE:
2995 case SSL_ERROR_WANT_ASYNC:
2996 BIO_printf(bio_c_out, "read A BLOCK\n");
2997 wait_for_async(con);
3000 if ((read_tty == 0) && (write_ssl == 0))
3003 case SSL_ERROR_WANT_WRITE:
3004 BIO_printf(bio_c_out, "read W BLOCK\n");
3008 case SSL_ERROR_WANT_READ:
3009 BIO_printf(bio_c_out, "read R BLOCK\n");
3012 if ((read_tty == 0) && (write_ssl == 0))
3015 case SSL_ERROR_WANT_X509_LOOKUP:
3016 BIO_printf(bio_c_out, "read X BLOCK\n");
3018 case SSL_ERROR_SYSCALL:
3019 ret = get_last_socket_error();
3021 BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
3023 BIO_printf(bio_err, "read:errno=%d\n", ret);
3025 case SSL_ERROR_ZERO_RETURN:
3026 BIO_printf(bio_c_out, "closed\n");
3029 case SSL_ERROR_WANT_ASYNC_JOB:
3030 /* This shouldn't ever happen in s_client. Treat as an error */
3032 ERR_print_errors(bio_err);
3036 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
3037 #if defined(OPENSSL_SYS_MSDOS)
3038 else if (has_stdin_waiting())
3040 else if (FD_ISSET(fileno_stdin(), &readfds))
3046 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
3048 /* both loops are skipped when i <= 0 */
3049 for (j = 0; j < i; j++)
3050 if (cbuf[j] == '\n')
3052 for (j = i - 1; j >= 0; j--) {
3053 cbuf[j + lf_num] = cbuf[j];
3054 if (cbuf[j] == '\n') {
3057 cbuf[j + lf_num] = '\r';
3060 assert(lf_num == 0);
3062 i = raw_read_stdin(cbuf, BUFSIZZ);
3063 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3068 if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q' && cmdletters))) {
3069 BIO_printf(bio_err, "DONE\n");
3074 if ((!c_ign_eof) && (cbuf[0] == 'R' && cmdletters)) {
3075 BIO_printf(bio_err, "RENEGOTIATING\n");
3076 SSL_renegotiate(con);
3078 } else if (!c_ign_eof && (cbuf[0] == 'K' || cbuf[0] == 'k' )
3080 BIO_printf(bio_err, "KEYUPDATE\n");
3082 cbuf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED
3083 : SSL_KEY_UPDATE_NOT_REQUESTED);
3088 #ifdef CHARSET_EBCDIC
3089 ebcdic2ascii(cbuf, cbuf, i);
3101 print_stuff(bio_c_out, con, full_log);
3102 do_ssl_shutdown(con);
3105 * If we ended with an alert being sent, but still with data in the
3106 * network buffer to be read, then calling BIO_closesocket() will
3107 * result in a TCP-RST being sent. On some platforms (notably
3108 * Windows) then this will result in the peer immediately abandoning
3109 * the connection including any buffered alert data before it has
3110 * had a chance to be read. Shutting down the sending side first,
3111 * and then closing the socket sends TCP-FIN first followed by
3112 * TCP-RST. This seems to allow the peer to read the alert data.
3114 shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
3116 * We just said we have nothing else to say, but it doesn't mean that
3117 * the other side has nothing. It's even recommended to consume incoming
3118 * data. [In testing context this ensures that alerts are passed on...]
3121 timeout.tv_usec = 500000; /* some extreme round-trip */
3124 openssl_fdset(sock, &readfds);
3125 } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
3126 && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
3128 BIO_closesocket(SSL_get_fd(con));
3132 print_stuff(bio_c_out, con, 1);
3135 SSL_SESSION_free(psksess);
3136 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3137 OPENSSL_free(next_proto.data);
3140 set_keylog_file(NULL, NULL);
3142 sk_X509_CRL_pop_free(crls, X509_CRL_free);
3144 sk_X509_pop_free(chain, X509_free);
3146 #ifndef OPENSSL_NO_SRP
3147 OPENSSL_free(srp_arg.srppassin);
3149 OPENSSL_free(connectstr);
3150 OPENSSL_free(bindstr);
3153 X509_VERIFY_PARAM_free(vpm);
3154 ssl_excert_free(exc);
3155 sk_OPENSSL_STRING_free(ssl_args);
3156 sk_OPENSSL_STRING_free(dane_tlsa_rrset);
3157 SSL_CONF_CTX_free(cctx);
3158 OPENSSL_clear_free(cbuf, BUFSIZZ);
3159 OPENSSL_clear_free(sbuf, BUFSIZZ);
3160 OPENSSL_clear_free(mbuf, BUFSIZZ);
3161 if (proxypass != NULL)
3162 OPENSSL_clear_free(proxypass, strlen(proxypass));
3164 BIO_free(bio_c_out);
3166 BIO_free(bio_c_msg);
3171 static void print_stuff(BIO *bio, SSL *s, int full)
3175 const SSL_CIPHER *c;
3176 int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
3178 #ifndef OPENSSL_NO_COMP
3179 const COMP_METHOD *comp, *expansion;
3181 unsigned char *exportedkeymat;
3182 #ifndef OPENSSL_NO_CT
3183 const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
3187 int got_a_chain = 0;
3189 sk = SSL_get_peer_cert_chain(s);
3193 BIO_printf(bio, "---\nCertificate chain\n");
3194 for (i = 0; i < sk_X509_num(sk); i++) {
3195 BIO_printf(bio, "%2d s:", i);
3196 X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
3197 BIO_puts(bio, "\n");
3198 BIO_printf(bio, " i:");
3199 X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
3200 BIO_puts(bio, "\n");
3202 PEM_write_bio_X509(bio, sk_X509_value(sk, i));
3206 BIO_printf(bio, "---\n");
3207 peer = SSL_get_peer_certificate(s);
3209 BIO_printf(bio, "Server certificate\n");
3211 /* Redundant if we showed the whole chain */
3212 if (!(c_showcerts && got_a_chain))
3213 PEM_write_bio_X509(bio, peer);
3214 dump_cert_text(bio, peer);
3216 BIO_printf(bio, "no peer certificate available\n");
3218 print_ca_names(bio, s);
3220 ssl_print_sigalgs(bio, s);
3221 ssl_print_tmp_key(bio, s);
3223 #ifndef OPENSSL_NO_CT
3225 * When the SSL session is anonymous, or resumed via an abbreviated
3226 * handshake, no SCTs are provided as part of the handshake. While in
3227 * a resumed session SCTs may be present in the session's certificate,
3228 * no callbacks are invoked to revalidate these, and in any case that
3229 * set of SCTs may be incomplete. Thus it makes little sense to
3230 * attempt to display SCTs from a resumed session's certificate, and of
3231 * course none are associated with an anonymous peer.
3233 if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
3234 const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
3235 int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
3237 BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
3238 if (sct_count > 0) {
3239 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
3241 BIO_printf(bio, "---\n");
3242 for (i = 0; i < sct_count; ++i) {
3243 SCT *sct = sk_SCT_value(scts, i);
3245 BIO_printf(bio, "SCT validation status: %s\n",
3246 SCT_validation_status_string(sct));
3247 SCT_print(sct, bio, 0, log_store);
3248 if (i < sct_count - 1)
3249 BIO_printf(bio, "\n---\n");
3251 BIO_printf(bio, "\n");
3257 "---\nSSL handshake has read %ju bytes "
3258 "and written %ju bytes\n",
3259 BIO_number_read(SSL_get_rbio(s)),
3260 BIO_number_written(SSL_get_wbio(s)));
3262 print_verify_detail(s, bio);
3263 BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
3264 c = SSL_get_current_cipher(s);
3265 BIO_printf(bio, "%s, Cipher is %s\n",
3266 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3270 pktmp = X509_get0_pubkey(peer);
3271 BIO_printf(bio, "Server public key is %d bit\n",
3272 EVP_PKEY_bits(pktmp));
3274 BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
3275 SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
3276 #ifndef OPENSSL_NO_COMP
3277 comp = SSL_get_current_compression(s);
3278 expansion = SSL_get_current_expansion(s);
3279 BIO_printf(bio, "Compression: %s\n",
3280 comp ? SSL_COMP_get_name(comp) : "NONE");
3281 BIO_printf(bio, "Expansion: %s\n",
3282 expansion ? SSL_COMP_get_name(expansion) : "NONE");
3284 #ifndef OPENSSL_NO_KTLS
3285 if (BIO_get_ktls_send(SSL_get_wbio(s)))
3286 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3287 if (BIO_get_ktls_recv(SSL_get_rbio(s)))
3288 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3291 if (OSSL_TRACE_ENABLED(TLS)) {
3292 /* Print out local port of connection: useful for debugging */
3294 union BIO_sock_info_u info;
3296 sock = SSL_get_fd(s);
3297 if ((info.addr = BIO_ADDR_new()) != NULL
3298 && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
3299 BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
3300 ntohs(BIO_ADDR_rawport(info.addr)));
3302 BIO_ADDR_free(info.addr);
3305 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3306 if (next_proto.status != -1) {
3307 const unsigned char *proto;
3308 unsigned int proto_len;
3309 SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
3310 BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
3311 BIO_write(bio, proto, proto_len);
3312 BIO_write(bio, "\n", 1);
3316 const unsigned char *proto;
3317 unsigned int proto_len;
3318 SSL_get0_alpn_selected(s, &proto, &proto_len);
3319 if (proto_len > 0) {
3320 BIO_printf(bio, "ALPN protocol: ");
3321 BIO_write(bio, proto, proto_len);
3322 BIO_write(bio, "\n", 1);
3324 BIO_printf(bio, "No ALPN negotiated\n");
3327 #ifndef OPENSSL_NO_SRTP
3329 SRTP_PROTECTION_PROFILE *srtp_profile =
3330 SSL_get_selected_srtp_profile(s);
3333 BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
3334 srtp_profile->name);
3339 switch (SSL_get_early_data_status(s)) {
3340 case SSL_EARLY_DATA_NOT_SENT:
3341 BIO_printf(bio, "Early data was not sent\n");
3344 case SSL_EARLY_DATA_REJECTED:
3345 BIO_printf(bio, "Early data was rejected\n");
3348 case SSL_EARLY_DATA_ACCEPTED:
3349 BIO_printf(bio, "Early data was accepted\n");
3355 * We also print the verify results when we dump session information,
3356 * but in TLSv1.3 we may not get that right away (or at all) depending
3357 * on when we get a NewSessionTicket. Therefore we print it now as well.
3359 verify_result = SSL_get_verify_result(s);
3360 BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
3361 X509_verify_cert_error_string(verify_result));
3363 /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3364 SSL_SESSION_print(bio, SSL_get_session(s));
3367 if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
3368 BIO_printf(bio, "Keying material exporter:\n");
3369 BIO_printf(bio, " Label: '%s'\n", keymatexportlabel);
3370 BIO_printf(bio, " Length: %i bytes\n", keymatexportlen);
3371 exportedkeymat = app_malloc(keymatexportlen, "export key");
3372 if (!SSL_export_keying_material(s, exportedkeymat,
3375 strlen(keymatexportlabel),
3377 BIO_printf(bio, " Error\n");
3379 BIO_printf(bio, " Keying material: ");
3380 for (i = 0; i < keymatexportlen; i++)
3381 BIO_printf(bio, "%02X", exportedkeymat[i]);
3382 BIO_printf(bio, "\n");
3384 OPENSSL_free(exportedkeymat);
3386 BIO_printf(bio, "---\n");
3388 /* flush, or debugging output gets mixed with http response */
3389 (void)BIO_flush(bio);
3392 # ifndef OPENSSL_NO_OCSP
3393 static int ocsp_resp_cb(SSL *s, void *arg)
3395 const unsigned char *p;
3398 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3399 BIO_puts(arg, "OCSP response: ");
3401 BIO_puts(arg, "no response sent\n");
3404 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3406 BIO_puts(arg, "response parse error\n");
3407 BIO_dump_indent(arg, (char *)p, len, 4);
3410 BIO_puts(arg, "\n======================================\n");
3411 OCSP_RESPONSE_print(arg, rsp, 0);
3412 BIO_puts(arg, "======================================\n");
3413 OCSP_RESPONSE_free(rsp);
3418 static int ldap_ExtendedResponse_parse(const char *buf, long rem)
3420 const unsigned char *cur, *end;
3422 int tag, xclass, inf, ret = -1;
3424 cur = (const unsigned char *)buf;
3430 * LDAPMessage ::= SEQUENCE {
3431 * messageID MessageID,
3432 * protocolOp CHOICE {
3434 * extendedResp ExtendedResponse,
3436 * controls [0] Controls OPTIONAL }
3438 * ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3439 * COMPONENTS OF LDAPResult,
3440 * responseName [10] LDAPOID OPTIONAL,
3441 * responseValue [11] OCTET STRING OPTIONAL }
3443 * LDAPResult ::= SEQUENCE {
3444 * resultCode ENUMERATED {
3450 * diagnosticMessage LDAPString,
3451 * referral [3] Referral OPTIONAL }
3455 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3456 if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
3457 (rem = end - cur, len > rem)) {
3458 BIO_printf(bio_err, "Unexpected LDAP response\n");
3462 rem = len; /* ensure that we don't overstep the SEQUENCE */
3464 /* pull MessageID */
3465 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3466 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
3467 (rem = end - cur, len > rem)) {
3468 BIO_printf(bio_err, "No MessageID\n");
3472 cur += len; /* shall we check for MessageId match or just skip? */
3474 /* pull [APPLICATION 24] */
3476 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3477 if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
3479 BIO_printf(bio_err, "Not ExtendedResponse\n");
3483 /* pull resultCode */
3485 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3486 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
3487 (rem = end - cur, len > rem)) {
3488 BIO_printf(bio_err, "Not LDAPResult\n");
3492 /* len should always be one, but just in case... */
3493 for (ret = 0, inf = 0; inf < len; inf++) {
3497 /* There is more data, but we don't care... */
3503 * Host dNS Name verifier: used for checking that the hostname is in dNS format
3504 * before setting it as SNI
3506 static int is_dNS_name(const char *host)
3508 const size_t MAX_LABEL_LENGTH = 63;
3511 size_t length = strlen(host);
3512 size_t label_length = 0;
3513 int all_numeric = 1;
3516 * Deviation from strict DNS name syntax, also check names with '_'
3517 * Check DNS name syntax, any '-' or '.' must be internal,
3518 * and on either side of each '.' we can't have a '-' or '.'.
3520 * If the name has just one label, we don't consider it a DNS name.
3522 for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) {
3525 if ((c >= 'a' && c <= 'z')
3526 || (c >= 'A' && c <= 'Z')
3533 if (c >= '0' && c <= '9') {
3538 /* Dot and hyphen cannot be first or last. */
3539 if (i > 0 && i < length - 1) {
3545 * Next to a dot the preceding and following characters must not be
3546 * another dot or a hyphen. Otherwise, record that the name is
3547 * plausible, since it has two or more labels.
3550 && host[i + 1] != '.'
3551 && host[i - 1] != '-'
3552 && host[i + 1] != '-') {
3562 /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
3563 isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH);
3567 #endif /* OPENSSL_NO_SOCK */