2 * Copyright 1995-2023 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
11 #include "internal/e_os.h"
17 #include <openssl/e_os2.h>
18 #include "internal/nelem.h"
20 #ifndef OPENSSL_NO_SOCK
23 * With IPv6, it looks like Digital has mixed up the proper order of
24 * recursive header file inclusion, resulting in the compiler complaining
25 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
26 * needed to have fileno() declared correctly... So let's define u_int
28 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
30 typedef unsigned int u_int;
35 #include <openssl/x509.h>
36 #include <openssl/ssl.h>
37 #include <openssl/err.h>
38 #include <openssl/pem.h>
39 #include <openssl/rand.h>
40 #include <openssl/ocsp.h>
41 #include <openssl/bn.h>
42 #include <openssl/trace.h>
43 #include <openssl/async.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
61 #define USER_DATA_MODE_NONE 0
62 #define USER_DATA_MODE_BASIC 1
63 #define USER_DATA_MODE_ADVANCED 2
65 #define USER_DATA_PROCESS_BAD_ARGUMENT 0
66 #define USER_DATA_PROCESS_SHUT 1
67 #define USER_DATA_PROCESS_RESTART 2
68 #define USER_DATA_PROCESS_NO_DATA 3
69 #define USER_DATA_PROCESS_CONTINUE 4
72 /* SSL connection we are processing commands for */
75 /* Buffer where we are storing data supplied by the user */
78 /* Allocated size of the buffer */
81 /* Amount of the buffer actually used */
84 /* Current location in the buffer where we will read from next*/
87 /* The mode we are using for processing commands */
91 static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf,
92 size_t bufmax, int mode);
93 static int user_data_add(struct user_data_st *user_data, size_t i);
94 static int user_data_process(struct user_data_st *user_data, size_t *len,
96 static int user_data_has_data(struct user_data_st *user_data);
99 static int c_debug = 0;
100 static int c_showcerts = 0;
101 static char *keymatexportlabel = NULL;
102 static int keymatexportlen = 20;
103 static BIO *bio_c_out = NULL;
104 static int c_quiet = 0;
105 static char *sess_out = NULL;
106 static SSL_SESSION *psksess = NULL;
108 static void print_stuff(BIO *berr, SSL *con, int full);
109 #ifndef OPENSSL_NO_OCSP
110 static int ocsp_resp_cb(SSL *s, void *arg);
112 static int ldap_ExtendedResponse_parse(const char *buf, long rem);
113 static int is_dNS_name(const char *host);
115 static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
116 static int enable_server_rpk = 0;
118 static int saved_errno;
120 static void save_errno(void)
126 static int restore_errno(void)
133 /* Default PSK identity and key */
134 static char *psk_identity = "Client_identity";
136 #ifndef OPENSSL_NO_PSK
137 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
138 unsigned int max_identity_len,
140 unsigned int max_psk_len)
147 BIO_printf(bio_c_out, "psk_client_cb\n");
149 /* no ServerKeyExchange message */
151 BIO_printf(bio_c_out,
152 "NULL received PSK identity hint, continuing anyway\n");
153 } else if (c_debug) {
154 BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
158 * lookup PSK identity and PSK key based on the given identity hint here
160 ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
161 if (ret < 0 || (unsigned int)ret > max_identity_len)
164 BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
167 /* convert the PSK key to binary */
168 key = OPENSSL_hexstr2buf(psk_key, &key_len);
170 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
174 if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
176 "psk buffer of callback is too small (%d) for key (%ld)\n",
177 max_psk_len, key_len);
182 memcpy(psk, key, key_len);
186 BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
191 BIO_printf(bio_err, "Error in PSK client callback\n");
196 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
197 const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
199 static int psk_use_session_cb(SSL *s, const EVP_MD *md,
200 const unsigned char **id, size_t *idlen,
203 SSL_SESSION *usesess = NULL;
204 const SSL_CIPHER *cipher = NULL;
206 if (psksess != NULL) {
207 SSL_SESSION_up_ref(psksess);
211 unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
214 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
219 /* We default to SHA-256 */
220 cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
221 if (cipher == NULL) {
222 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
227 usesess = SSL_SESSION_new();
229 || !SSL_SESSION_set1_master_key(usesess, key, key_len)
230 || !SSL_SESSION_set_cipher(usesess, cipher)
231 || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
238 cipher = SSL_SESSION_get0_cipher(usesess);
242 if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
243 /* PSK not usable, ignore it */
247 SSL_SESSION_free(usesess);
250 *id = (unsigned char *)psk_identity;
251 *idlen = strlen(psk_identity);
257 SSL_SESSION_free(usesess);
261 /* This is a context that we pass to callbacks */
262 typedef struct tlsextctx_st {
267 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
269 tlsextctx *p = (tlsextctx *) arg;
270 const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
271 if (SSL_get_servername_type(s) != -1)
272 p->ack = !SSL_session_reused(s) && hn != NULL;
274 BIO_printf(bio_err, "Can't use SSL_get_servername\n");
276 return SSL_TLSEXT_ERR_OK;
279 #ifndef OPENSSL_NO_NEXTPROTONEG
280 /* This the context that we pass to next_proto_cb */
281 typedef struct tlsextnextprotoctx_st {
285 } tlsextnextprotoctx;
287 static tlsextnextprotoctx next_proto;
289 static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
290 const unsigned char *in, unsigned int inlen,
293 tlsextnextprotoctx *ctx = arg;
296 /* We can assume that |in| is syntactically valid. */
298 BIO_printf(bio_c_out, "Protocols advertised by server: ");
299 for (i = 0; i < inlen;) {
301 BIO_write(bio_c_out, ", ", 2);
302 BIO_write(bio_c_out, &in[i + 1], in[i]);
305 BIO_write(bio_c_out, "\n", 1);
309 SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
310 return SSL_TLSEXT_ERR_OK;
312 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
314 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
315 const unsigned char *in, size_t inlen,
319 unsigned char ext_buf[4 + 65536];
321 /* Reconstruct the type/len fields prior to extension data */
322 inlen &= 0xffff; /* for formal memcmpy correctness */
323 ext_buf[0] = (unsigned char)(ext_type >> 8);
324 ext_buf[1] = (unsigned char)(ext_type);
325 ext_buf[2] = (unsigned char)(inlen >> 8);
326 ext_buf[3] = (unsigned char)(inlen);
327 memcpy(ext_buf + 4, in, inlen);
329 BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
331 PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
336 * Hex decoder that tolerates optional whitespace. Returns number of bytes
337 * produced, advances inptr to end of input string.
339 static ossl_ssize_t hexdecode(const char **inptr, void *result)
341 unsigned char **out = (unsigned char **)result;
342 const char *in = *inptr;
343 unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
344 unsigned char *cp = ret;
351 for (byte = 0; *in; ++in) {
354 if (isspace(_UC(*in)))
356 x = OPENSSL_hexchar2int(*in);
362 if ((nibble ^= 1) == 0) {
375 return cp - (*out = ret);
379 * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
380 * inptr to next field skipping leading whitespace.
382 static ossl_ssize_t checked_uint8(const char **inptr, void *out)
384 uint8_t *result = (uint8_t *)out;
385 const char *in = *inptr;
391 v = strtol(in, &endp, 10);
394 if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
395 endp == in || !isspace(_UC(*endp)) ||
396 v != (*result = (uint8_t) v)) {
399 for (in = endp; isspace(_UC(*in)); ++in)
409 ossl_ssize_t (*parser)(const char **, void *);
412 static int tlsa_import_rr(SSL *con, const char *rrdata)
414 /* Not necessary to re-init these values; the "parsers" do that. */
415 static uint8_t usage;
416 static uint8_t selector;
417 static uint8_t mtype;
418 static unsigned char *data;
419 static struct tlsa_field tlsa_fields[] = {
420 { &usage, "usage", checked_uint8 },
421 { &selector, "selector", checked_uint8 },
422 { &mtype, "mtype", checked_uint8 },
423 { &data, "data", hexdecode },
426 struct tlsa_field *f;
428 const char *cp = rrdata;
429 ossl_ssize_t len = 0;
431 for (f = tlsa_fields; f->var; ++f) {
432 /* Returns number of bytes produced, advances cp to next field */
433 if ((len = f->parser(&cp, f->var)) <= 0) {
434 BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
435 prog, f->name, rrdata);
439 /* The data field is last, so len is its length */
440 ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
444 ERR_print_errors(bio_err);
445 BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
450 ERR_print_errors(bio_err);
451 BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
458 static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
460 int num = sk_OPENSSL_STRING_num(rrset);
464 for (i = 0; i < num; ++i) {
465 char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
466 if (tlsa_import_rr(con, rrdata) > 0)
472 typedef enum OPTION_choice {
474 OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX,
475 OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT,
476 OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
477 OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
478 OPT_BRIEF, OPT_PREXIT, OPT_NO_INTERACTIVE, OPT_CRLF, OPT_QUIET, OPT_NBIO,
479 OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF,
480 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
481 OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
482 OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
483 OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS,
484 #ifndef OPENSSL_NO_SRP
485 OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER,
488 OPT_SSL3, OPT_SSL_CONFIG,
489 OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
490 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS,
491 OPT_CERT_CHAIN, OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN,
492 OPT_NEXTPROTONEG, OPT_ALPN,
493 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
494 OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE,
495 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
496 OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC,
497 OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST,
498 OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES,
499 OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE,
503 OPT_S_ENUM, OPT_IGNORE_UNEXPECTED_EOF,
504 OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_ADV, OPT_PROXY, OPT_PROXY_USER,
505 OPT_PROXY_PASS, OPT_DANE_TLSA_DOMAIN,
506 #ifndef OPENSSL_NO_CT
507 OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
509 OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME,
511 OPT_ENABLE_SERVER_RPK,
512 OPT_ENABLE_CLIENT_RPK,
515 OPT_R_ENUM, OPT_PROV_ENUM
518 const OPTIONS s_client_options[] = {
519 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [host:port]\n"},
521 OPT_SECTION("General"),
522 {"help", OPT_HELP, '-', "Display this summary"},
523 #ifndef OPENSSL_NO_ENGINE
524 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
525 {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
526 "Specify engine to be used for client certificate operations"},
528 {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified section for SSL_CTX configuration"},
529 #ifndef OPENSSL_NO_CT
530 {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
531 {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
532 {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
535 OPT_SECTION("Network"),
536 {"host", OPT_HOST, 's', "Use -connect instead"},
537 {"port", OPT_PORT, 'p', "Use -connect instead"},
538 {"connect", OPT_CONNECT, 's',
539 "TCP/IP where to connect; default: " PORT ")"},
540 {"bind", OPT_BIND, 's', "bind local address for connection"},
541 {"proxy", OPT_PROXY, 's',
542 "Connect to via specified proxy to the real server"},
543 {"proxy_user", OPT_PROXY_USER, 's', "UserID for proxy authentication"},
544 {"proxy_pass", OPT_PROXY_PASS, 's', "Proxy authentication password source"},
546 {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"},
548 {"4", OPT_4, '-', "Use IPv4 only"},
550 {"6", OPT_6, '-', "Use IPv6 only"},
552 {"maxfraglen", OPT_MAXFRAGLEN, 'p',
553 "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
554 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
555 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
556 "Size used to split data for encrypt pipelines"},
557 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
558 "Maximum number of encrypt/decrypt pipelines to be used"},
559 {"read_buf", OPT_READ_BUF, 'p',
560 "Default read buffer size to be used for connections"},
561 {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
563 OPT_SECTION("Identity"),
564 {"cert", OPT_CERT, '<', "Client certificate file to use"},
565 {"certform", OPT_CERTFORM, 'F',
566 "Client certificate file format (PEM/DER/P12); has no effect"},
567 {"cert_chain", OPT_CERT_CHAIN, '<',
568 "Client certificate chain file (in PEM format)"},
569 {"build_chain", OPT_BUILD_CHAIN, '-', "Build client certificate chain"},
570 {"key", OPT_KEY, 's', "Private key file to use; default: -cert file"},
571 {"keyform", OPT_KEYFORM, 'E', "Key format (ENGINE, other values ignored)"},
572 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
573 {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
574 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
575 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
576 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
577 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
578 {"no-CAfile", OPT_NOCAFILE, '-',
579 "Do not load the default certificates file"},
580 {"no-CApath", OPT_NOCAPATH, '-',
581 "Do not load certificates from the default certificates directory"},
582 {"no-CAstore", OPT_NOCASTORE, '-',
583 "Do not load certificates from the default certificates store"},
584 {"requestCAfile", OPT_REQCAFILE, '<',
585 "PEM format file of CA names to send to the server"},
586 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
587 {"tfo", OPT_TFO, '-', "Connect using TCP Fast Open"},
589 {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
590 {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
591 "DANE TLSA rrdata presentation form"},
592 {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
593 "Disable name checks when matching DANE-EE(3) TLSA records"},
594 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
595 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
596 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
597 {"name", OPT_PROTOHOST, 's',
598 "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
600 OPT_SECTION("Session"),
601 {"reconnect", OPT_RECONNECT, '-',
602 "Drop and re-make the connection with the same Session-ID"},
603 {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
604 {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
606 OPT_SECTION("Input/Output"),
607 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
608 {"quiet", OPT_QUIET, '-', "No s_client output"},
609 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
610 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
611 {"starttls", OPT_STARTTLS, 's',
612 "Use the appropriate STARTTLS command before starting TLS"},
613 {"xmpphost", OPT_XMPPHOST, 's',
614 "Alias of -name option for \"-starttls xmpp[-server]\""},
615 {"brief", OPT_BRIEF, '-',
616 "Restrict output to brief summary of connection parameters"},
617 {"prexit", OPT_PREXIT, '-',
618 "Print session information when the program exits"},
619 {"no-interactive", OPT_NO_INTERACTIVE, '-',
620 "Don't run the client in the interactive mode"},
622 OPT_SECTION("Debug"),
623 {"showcerts", OPT_SHOWCERTS, '-',
624 "Show all certificates sent by the server"},
625 {"debug", OPT_DEBUG, '-', "Extra output"},
626 {"msg", OPT_MSG, '-', "Show protocol messages"},
627 {"msgfile", OPT_MSGFILE, '>',
628 "File to send output of -msg or -trace, instead of stdout"},
629 {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
630 {"state", OPT_STATE, '-', "Print the ssl states"},
631 {"keymatexport", OPT_KEYMATEXPORT, 's',
632 "Export keying material using label"},
633 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
634 "Export len bytes of keying material; default 20"},
635 {"security_debug", OPT_SECURITY_DEBUG, '-',
636 "Enable security debug messages"},
637 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
638 "Output more security debug output"},
639 #ifndef OPENSSL_NO_SSL_TRACE
640 {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
643 {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
645 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
646 {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
647 {"adv", OPT_ADV, '-', "Advanced command mode"},
648 {"servername", OPT_SERVERNAME, 's',
649 "Set TLS extension servername (SNI) in ClientHello (default)"},
650 {"noservername", OPT_NOSERVERNAME, '-',
651 "Do not send the server name (SNI) extension in the ClientHello"},
652 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
653 "Hex dump of all TLS extensions received"},
654 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
655 "Do not treat lack of close_notify from a peer as an error"},
656 #ifndef OPENSSL_NO_OCSP
657 {"status", OPT_STATUS, '-', "Request certificate status from server"},
659 {"serverinfo", OPT_SERVERINFO, 's',
660 "types Send empty ClientHello extensions (comma-separated numbers)"},
661 {"alpn", OPT_ALPN, 's',
662 "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
663 {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
664 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
666 OPT_SECTION("Protocol and version"),
667 #ifndef OPENSSL_NO_SSL3
668 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
670 #ifndef OPENSSL_NO_TLS1
671 {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
673 #ifndef OPENSSL_NO_TLS1_1
674 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
676 #ifndef OPENSSL_NO_TLS1_2
677 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
679 #ifndef OPENSSL_NO_TLS1_3
680 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
682 #ifndef OPENSSL_NO_DTLS
683 {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
684 {"timeout", OPT_TIMEOUT, '-',
685 "Enable send/receive timeout on DTLS connections"},
686 {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
688 #ifndef OPENSSL_NO_DTLS1
689 {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
691 #ifndef OPENSSL_NO_DTLS1_2
692 {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
694 #ifndef OPENSSL_NO_SCTP
695 {"sctp", OPT_SCTP, '-', "Use SCTP"},
696 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
698 #ifndef OPENSSL_NO_NEXTPROTONEG
699 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
700 "Enable NPN extension, considering named protocols supported (comma-separated list)"},
702 {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"},
703 {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"},
704 {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"},
705 {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"},
706 #ifndef OPENSSL_NO_SRTP
707 {"use_srtp", OPT_USE_SRTP, 's',
708 "Offer SRTP key management with a colon-separated profile list"},
710 #ifndef OPENSSL_NO_SRP
711 {"srpuser", OPT_SRPUSER, 's', "(deprecated) SRP authentication for 'user'"},
712 {"srppass", OPT_SRPPASS, 's', "(deprecated) Password for 'user'"},
713 {"srp_lateuser", OPT_SRP_LATEUSER, '-',
714 "(deprecated) SRP username into second ClientHello message"},
715 {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
716 "(deprecated) Tolerate other than the known g N values."},
717 {"srp_strength", OPT_SRP_STRENGTH, 'p',
718 "(deprecated) Minimal length in bits for N"},
720 #ifndef OPENSSL_NO_KTLS
721 {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"},
727 {"CRL", OPT_CRL, '<', "CRL file to use"},
728 {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
729 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER); default PEM"},
730 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
731 "Close connection on verification error"},
732 {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
733 {"chainCAfile", OPT_CHAINCAFILE, '<',
734 "CA file for certificate chain (PEM format)"},
735 {"chainCApath", OPT_CHAINCAPATH, '/',
736 "Use dir as certificate store path to build CA certificate chain"},
737 {"chainCAstore", OPT_CHAINCASTORE, ':',
738 "CA store URI for certificate chain"},
739 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
740 "CA file for certificate verification (PEM format)"},
741 {"verifyCApath", OPT_VERIFYCAPATH, '/',
742 "Use dir as certificate store path to verify CA certificate"},
743 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
744 "CA store URI for certificate verification"},
749 {"host:port", 0, 0, "Where to connect; same as -connect option"},
753 typedef enum PROTOCOL_choice {
771 static const OPT_PAIR services[] = {
772 {"smtp", PROTO_SMTP},
773 {"pop3", PROTO_POP3},
774 {"imap", PROTO_IMAP},
776 {"xmpp", PROTO_XMPP},
777 {"xmpp-server", PROTO_XMPP_SERVER},
778 {"telnet", PROTO_TELNET},
780 {"mysql", PROTO_MYSQL},
781 {"postgres", PROTO_POSTGRES},
782 {"lmtp", PROTO_LMTP},
783 {"nntp", PROTO_NNTP},
784 {"sieve", PROTO_SIEVE},
785 {"ldap", PROTO_LDAP},
789 #define IS_INET_FLAG(o) \
790 (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
791 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
793 #define IS_PROT_FLAG(o) \
794 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
795 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
797 /* Free |*dest| and optionally set it to a copy of |source|. */
798 static void freeandcopy(char **dest, const char *source)
803 *dest = OPENSSL_strdup(source);
806 static int new_session_cb(SSL *s, SSL_SESSION *sess)
809 if (sess_out != NULL) {
810 BIO *stmp = BIO_new_file(sess_out, "w");
813 BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
815 PEM_write_bio_SSL_SESSION(stmp, sess);
821 * Session data gets dumped on connection for TLSv1.2 and below, and on
822 * arrival of the NewSessionTicket for TLSv1.3.
824 if (SSL_version(s) == TLS1_3_VERSION) {
825 BIO_printf(bio_c_out,
826 "---\nPost-Handshake New Session Ticket arrived:\n");
827 SSL_SESSION_print(bio_c_out, sess);
828 BIO_printf(bio_c_out, "---\n");
832 * We always return a "fail" response so that the session gets freed again
833 * because we haven't used the reference.
838 int s_client_main(int argc, char **argv)
841 EVP_PKEY *key = NULL;
844 STACK_OF(X509) *chain = NULL;
846 X509_VERIFY_PARAM *vpm = NULL;
847 SSL_EXCERT *exc = NULL;
848 SSL_CONF_CTX *cctx = NULL;
849 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
850 char *dane_tlsa_domain = NULL;
851 STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
852 int dane_ee_no_name = 0;
853 STACK_OF(X509_CRL) *crls = NULL;
854 const SSL_METHOD *meth = TLS_client_method();
855 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
856 char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
857 char *proxystr = NULL, *proxyuser = NULL;
858 char *proxypassarg = NULL, *proxypass = NULL;
859 char *connectstr = NULL, *bindstr = NULL;
860 char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
861 char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL, *host = NULL;
862 char *thost = NULL, *tport = NULL;
864 char *bindhost = NULL, *bindport = NULL;
865 char *passarg = NULL, *pass = NULL;
866 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
867 char *ReqCAfile = NULL;
868 char *sess_in = NULL, *crl_file = NULL, *p;
869 const char *protohost = NULL;
870 struct timeval timeout, *timeoutp;
871 fd_set readfds, writefds;
872 int noCApath = 0, noCAfile = 0, noCAstore = 0;
873 int build_chain = 0, cert_format = FORMAT_UNDEF;
874 size_t cbuf_len, cbuf_off;
875 int key_format = FORMAT_UNDEF, crlf = 0, full_log = 1, mbuf_len = 0;
877 int nointeractive = 0;
879 int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
880 int ret = 1, in_init = 1, i, nbio_test = 0, sock = -1, k, width, state = 0;
881 int sbuf_len, sbuf_off, cmdmode = USER_DATA_MODE_BASIC;
882 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
883 int starttls_proto = PROTO_OFF, crl_format = FORMAT_UNDEF, crl_download = 0;
884 int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
885 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
888 int read_buf_len = 0;
889 int fallback_scsv = 0;
891 #ifndef OPENSSL_NO_DTLS
892 int enable_timeouts = 0;
895 #ifndef OPENSSL_NO_ENGINE
896 ENGINE *ssl_client_engine = NULL;
899 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
902 const char *servername = NULL;
903 char *sname_alloc = NULL;
904 int noservername = 0;
905 const char *alpn_in = NULL;
906 tlsextctx tlsextcbp = { NULL, 0 };
907 const char *ssl_config = NULL;
908 #define MAX_SI_TYPES 100
909 unsigned short serverinfo_types[MAX_SI_TYPES];
910 int serverinfo_count = 0, start = 0, len;
911 #ifndef OPENSSL_NO_NEXTPROTONEG
912 const char *next_proto_neg_in = NULL;
914 #ifndef OPENSSL_NO_SRP
915 char *srppass = NULL;
916 int srp_lateuser = 0;
917 SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
919 #ifndef OPENSSL_NO_SRTP
920 char *srtp_profiles = NULL;
922 #ifndef OPENSSL_NO_CT
923 char *ctlog_file = NULL;
924 int ct_validation = 0;
926 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
928 unsigned int max_send_fragment = 0;
929 unsigned int split_send_fragment = 0, max_pipelines = 0;
930 enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
932 uint8_t maxfraglen = 0;
933 int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
934 int c_tlsextdebug = 0;
935 #ifndef OPENSSL_NO_OCSP
936 int c_status_req = 0;
938 BIO *bio_c_msg = NULL;
939 const char *keylog_file = NULL, *early_data_file = NULL;
940 #ifndef OPENSSL_NO_DTLS
943 char *psksessf = NULL;
945 int enable_client_rpk = 0;
946 #ifndef OPENSSL_NO_SCTP
947 int sctp_label_bug = 0;
949 int ignore_unexpected_eof = 0;
950 #ifndef OPENSSL_NO_KTLS
954 BIO_ADDR *tfo_addr = NULL;
955 struct user_data_st user_data;
959 /* Known false-positive of MemorySanitizer. */
960 #if defined(__has_feature)
961 # if __has_feature(memory_sanitizer)
962 __msan_unpoison(&readfds, sizeof(readfds));
963 __msan_unpoison(&writefds, sizeof(writefds));
971 port = OPENSSL_strdup(PORT);
972 vpm = X509_VERIFY_PARAM_new();
973 cctx = SSL_CONF_CTX_new();
975 if (port == NULL || vpm == NULL || cctx == NULL) {
976 BIO_printf(bio_err, "%s: out of memory\n", opt_getprog());
980 cbuf = app_malloc(BUFSIZZ, "cbuf");
981 sbuf = app_malloc(BUFSIZZ, "sbuf");
982 mbuf = app_malloc(BUFSIZZ, "mbuf");
984 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
986 prog = opt_init(argc, argv, s_client_options);
987 while ((o = opt_next()) != OPT_EOF) {
988 /* Check for intermixing flags. */
989 if (connect_type == use_unix && IS_INET_FLAG(o)) {
991 "%s: Intermixed protocol flags (unix and internet domains)\n",
995 if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
997 "%s: Intermixed protocol flags (internet and unix domains)\n",
1002 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1003 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1006 if (IS_NO_PROT_FLAG(o))
1008 if (prot_opt == 1 && no_prot_opt) {
1010 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1018 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1021 opt_help(s_client_options);
1025 connect_type = use_inet;
1026 socket_family = AF_INET;
1031 connect_type = use_inet;
1032 socket_family = AF_INET6;
1037 connect_type = use_inet;
1038 freeandcopy(&host, opt_arg());
1041 connect_type = use_inet;
1042 freeandcopy(&port, opt_arg());
1045 connect_type = use_inet;
1046 freeandcopy(&connectstr, opt_arg());
1049 freeandcopy(&bindstr, opt_arg());
1052 proxystr = opt_arg();
1054 case OPT_PROXY_USER:
1055 proxyuser = opt_arg();
1057 case OPT_PROXY_PASS:
1058 proxypassarg = opt_arg();
1062 connect_type = use_unix;
1063 socket_family = AF_UNIX;
1064 freeandcopy(&host, opt_arg());
1068 /* fall through, since this is an alias */
1070 protohost = opt_arg();
1073 verify = SSL_VERIFY_PEER;
1074 verify_args.depth = atoi(opt_arg());
1076 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1079 cert_file = opt_arg();
1082 if (!set_nameopt(opt_arg()))
1086 crl_file = opt_arg();
1088 case OPT_CRL_DOWNLOAD:
1092 sess_out = opt_arg();
1095 sess_in = opt_arg();
1098 if (!opt_format(opt_arg(), OPT_FMT_ANY, &cert_format))
1102 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1105 case OPT_VERIFY_RET_ERROR:
1106 verify = SSL_VERIFY_PEER;
1107 verify_args.return_error = 1;
1109 case OPT_VERIFY_QUIET:
1110 verify_args.quiet = 1;
1113 c_brief = verify_args.quiet = c_quiet = 1;
1116 if (ssl_args == NULL)
1117 ssl_args = sk_OPENSSL_STRING_new_null();
1118 if (ssl_args == NULL
1119 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1120 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1121 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1126 if (!opt_verify(o, vpm))
1131 if (!args_excert(o, &exc))
1134 case OPT_IGNORE_UNEXPECTED_EOF:
1135 ignore_unexpected_eof = 1;
1140 case OPT_NO_INTERACTIVE:
1147 c_quiet = c_ign_eof = 1;
1153 cmdmode = USER_DATA_MODE_NONE;
1156 cmdmode = USER_DATA_MODE_ADVANCED;
1159 e = setup_engine(opt_arg(), 1);
1161 case OPT_SSL_CLIENT_ENGINE:
1162 #ifndef OPENSSL_NO_ENGINE
1163 ssl_client_engine = setup_engine(opt_arg(), 0);
1164 if (ssl_client_engine == NULL) {
1165 BIO_printf(bio_err, "Error getting client auth engine\n");
1174 case OPT_PROV_CASES:
1175 if (!opt_provider(o))
1181 case OPT_NO_IGN_EOF:
1187 case OPT_TLSEXTDEBUG:
1191 #ifndef OPENSSL_NO_OCSP
1204 bio_c_msg = BIO_new_file(opt_arg(), "w");
1205 if (bio_c_msg == NULL) {
1206 BIO_printf(bio_err, "Error writing file %s\n", opt_arg());
1211 #ifndef OPENSSL_NO_SSL_TRACE
1215 case OPT_SECURITY_DEBUG:
1218 case OPT_SECURITY_DEBUG_VERBOSE:
1230 case OPT_PSK_IDENTITY:
1231 psk_identity = opt_arg();
1234 for (p = psk_key = opt_arg(); *p; p++) {
1235 if (isxdigit(_UC(*p)))
1237 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1242 psksessf = opt_arg();
1244 #ifndef OPENSSL_NO_SRP
1246 srp_arg.srplogin = opt_arg();
1247 if (min_version < TLS1_VERSION)
1248 min_version = TLS1_VERSION;
1251 srppass = opt_arg();
1252 if (min_version < TLS1_VERSION)
1253 min_version = TLS1_VERSION;
1255 case OPT_SRP_STRENGTH:
1256 srp_arg.strength = atoi(opt_arg());
1257 BIO_printf(bio_err, "SRP minimal length for N is %d\n",
1259 if (min_version < TLS1_VERSION)
1260 min_version = TLS1_VERSION;
1262 case OPT_SRP_LATEUSER:
1264 if (min_version < TLS1_VERSION)
1265 min_version = TLS1_VERSION;
1267 case OPT_SRP_MOREGROUPS:
1269 if (min_version < TLS1_VERSION)
1270 min_version = TLS1_VERSION;
1273 case OPT_SSL_CONFIG:
1274 ssl_config = opt_arg();
1277 min_version = SSL3_VERSION;
1278 max_version = SSL3_VERSION;
1279 socket_type = SOCK_STREAM;
1280 #ifndef OPENSSL_NO_DTLS
1285 min_version = TLS1_3_VERSION;
1286 max_version = TLS1_3_VERSION;
1287 socket_type = SOCK_STREAM;
1288 #ifndef OPENSSL_NO_DTLS
1293 min_version = TLS1_2_VERSION;
1294 max_version = TLS1_2_VERSION;
1295 socket_type = SOCK_STREAM;
1296 #ifndef OPENSSL_NO_DTLS
1301 min_version = TLS1_1_VERSION;
1302 max_version = TLS1_1_VERSION;
1303 socket_type = SOCK_STREAM;
1304 #ifndef OPENSSL_NO_DTLS
1309 min_version = TLS1_VERSION;
1310 max_version = TLS1_VERSION;
1311 socket_type = SOCK_STREAM;
1312 #ifndef OPENSSL_NO_DTLS
1317 #ifndef OPENSSL_NO_DTLS
1318 meth = DTLS_client_method();
1319 socket_type = SOCK_DGRAM;
1324 #ifndef OPENSSL_NO_DTLS1
1325 meth = DTLS_client_method();
1326 min_version = DTLS1_VERSION;
1327 max_version = DTLS1_VERSION;
1328 socket_type = SOCK_DGRAM;
1333 #ifndef OPENSSL_NO_DTLS1_2
1334 meth = DTLS_client_method();
1335 min_version = DTLS1_2_VERSION;
1336 max_version = DTLS1_2_VERSION;
1337 socket_type = SOCK_DGRAM;
1342 #ifndef OPENSSL_NO_SCTP
1343 protocol = IPPROTO_SCTP;
1346 case OPT_SCTP_LABEL_BUG:
1347 #ifndef OPENSSL_NO_SCTP
1352 #ifndef OPENSSL_NO_DTLS
1353 enable_timeouts = 1;
1357 #ifndef OPENSSL_NO_DTLS
1358 socket_mtu = atol(opt_arg());
1361 case OPT_FALLBACKSCSV:
1365 if (!opt_format(opt_arg(), OPT_FMT_ANY, &key_format))
1369 passarg = opt_arg();
1371 case OPT_CERT_CHAIN:
1372 chain_file = opt_arg();
1375 key_file = opt_arg();
1386 case OPT_CHAINCAPATH:
1387 chCApath = opt_arg();
1389 case OPT_VERIFYCAPATH:
1390 vfyCApath = opt_arg();
1392 case OPT_BUILD_CHAIN:
1396 ReqCAfile = opt_arg();
1404 #ifndef OPENSSL_NO_CT
1411 case OPT_CTLOG_FILE:
1412 ctlog_file = opt_arg();
1415 case OPT_CHAINCAFILE:
1416 chCAfile = opt_arg();
1418 case OPT_VERIFYCAFILE:
1419 vfyCAfile = opt_arg();
1422 CAstore = opt_arg();
1427 case OPT_CHAINCASTORE:
1428 chCAstore = opt_arg();
1430 case OPT_VERIFYCASTORE:
1431 vfyCAstore = opt_arg();
1433 case OPT_DANE_TLSA_DOMAIN:
1434 dane_tlsa_domain = opt_arg();
1436 case OPT_DANE_TLSA_RRDATA:
1437 if (dane_tlsa_rrset == NULL)
1438 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1439 if (dane_tlsa_rrset == NULL ||
1440 !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1441 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1445 case OPT_DANE_EE_NO_NAME:
1446 dane_ee_no_name = 1;
1448 case OPT_NEXTPROTONEG:
1449 #ifndef OPENSSL_NO_NEXTPROTONEG
1450 next_proto_neg_in = opt_arg();
1454 alpn_in = opt_arg();
1456 case OPT_SERVERINFO:
1459 for (start = 0, i = 0; i <= len; ++i) {
1460 if (i == len || p[i] == ',') {
1461 serverinfo_types[serverinfo_count] = atoi(p + start);
1462 if (++serverinfo_count == MAX_SI_TYPES)
1469 if (!opt_pair(opt_arg(), services, &starttls_proto))
1475 case OPT_SERVERNAME:
1476 servername = opt_arg();
1478 case OPT_NOSERVERNAME:
1482 #ifndef OPENSSL_NO_SRTP
1483 srtp_profiles = opt_arg();
1486 case OPT_KEYMATEXPORT:
1487 keymatexportlabel = opt_arg();
1489 case OPT_KEYMATEXPORTLEN:
1490 keymatexportlen = atoi(opt_arg());
1495 case OPT_MAXFRAGLEN:
1496 len = atoi(opt_arg());
1499 maxfraglen = TLSEXT_max_fragment_length_512;
1502 maxfraglen = TLSEXT_max_fragment_length_1024;
1505 maxfraglen = TLSEXT_max_fragment_length_2048;
1508 maxfraglen = TLSEXT_max_fragment_length_4096;
1512 "%s: Max Fragment Len %u is out of permitted values",
1517 case OPT_MAX_SEND_FRAG:
1518 max_send_fragment = atoi(opt_arg());
1520 case OPT_SPLIT_SEND_FRAG:
1521 split_send_fragment = atoi(opt_arg());
1523 case OPT_MAX_PIPELINES:
1524 max_pipelines = atoi(opt_arg());
1527 read_buf_len = atoi(opt_arg());
1529 case OPT_KEYLOG_FILE:
1530 keylog_file = opt_arg();
1532 case OPT_EARLY_DATA:
1533 early_data_file = opt_arg();
1535 case OPT_ENABLE_PHA:
1539 #ifndef OPENSSL_NO_KTLS
1543 case OPT_ENABLE_SERVER_RPK:
1544 enable_server_rpk = 1;
1546 case OPT_ENABLE_CLIENT_RPK:
1547 enable_client_rpk = 1;
1552 /* Optional argument is connect string if -connect not used. */
1553 if (opt_num_rest() == 1) {
1554 /* Don't allow -connect and a separate argument. */
1555 if (connectstr != NULL) {
1557 "%s: cannot provide both -connect option and target parameter\n",
1561 connect_type = use_inet;
1562 freeandcopy(&connectstr, *opt_rest());
1563 } else if (!opt_check_rest_arg(NULL)) {
1566 if (!app_RAND_load())
1570 cmdmode = USER_DATA_MODE_NONE;
1572 if (count4or6 >= 2) {
1573 BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1577 if (servername != NULL) {
1579 "%s: Can't use -servername and -noservername together\n",
1583 if (dane_tlsa_domain != NULL) {
1585 "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1591 #ifndef OPENSSL_NO_NEXTPROTONEG
1592 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1593 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1598 if (connectstr != NULL) {
1600 char *tmp_host = host, *tmp_port = port;
1602 res = BIO_parse_hostserv(connectstr, &host, &port, BIO_PARSE_PRIO_HOST);
1603 if (tmp_host != host)
1604 OPENSSL_free(tmp_host);
1605 if (tmp_port != port)
1606 OPENSSL_free(tmp_port);
1609 "%s: -connect argument or target parameter malformed or ambiguous\n",
1615 if (proxystr != NULL) {
1617 char *tmp_host = host, *tmp_port = port;
1619 if (host == NULL || port == NULL) {
1620 BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
1624 if (servername == NULL && !noservername) {
1625 servername = sname_alloc = OPENSSL_strdup(host);
1626 if (sname_alloc == NULL) {
1627 BIO_printf(bio_err, "%s: out of memory\n", prog);
1632 /* Retain the original target host:port for use in the HTTP proxy connect string */
1633 thost = OPENSSL_strdup(host);
1634 tport = OPENSSL_strdup(port);
1635 if (thost == NULL || tport == NULL) {
1636 BIO_printf(bio_err, "%s: out of memory\n", prog);
1640 res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1641 if (tmp_host != host)
1642 OPENSSL_free(tmp_host);
1643 if (tmp_port != port)
1644 OPENSSL_free(tmp_port);
1647 "%s: -proxy argument malformed or ambiguous\n", prog);
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");
1721 if (cert_file != NULL) {
1722 cert = load_cert_pass(cert_file, cert_format, 1, pass,
1723 "client certificate");
1728 if (chain_file != NULL) {
1729 if (!load_certs(chain_file, 0, &chain, pass, "client certificate chain"))
1733 if (crl_file != NULL) {
1735 crl = load_crl(crl_file, crl_format, 0, "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 if (bio_c_msg == NULL) {
1756 BIO_printf(bio_err, "Out of memory\n");
1761 bio_c_out = dup_bio_out(FORMAT_TEXT);
1764 if (bio_c_out == NULL) {
1765 BIO_printf(bio_err, "Unable to create BIO\n");
1769 #ifndef OPENSSL_NO_SRP
1770 if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1771 BIO_printf(bio_err, "Error getting password\n");
1776 ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1778 ERR_print_errors(bio_err);
1782 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1785 ssl_ctx_security_debug(ctx, sdebug);
1787 if (!config_ctx(cctx, ssl_args, ctx))
1790 if (ssl_config != NULL) {
1791 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1792 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1794 ERR_print_errors(bio_err);
1799 #ifndef OPENSSL_NO_SCTP
1800 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1801 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1804 if (min_version != 0
1805 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1807 if (max_version != 0
1808 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1811 if (ignore_unexpected_eof)
1812 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1813 #ifndef OPENSSL_NO_KTLS
1815 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
1818 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1819 BIO_printf(bio_err, "Error setting verify params\n");
1820 ERR_print_errors(bio_err);
1825 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1828 if (max_send_fragment > 0
1829 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1830 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1831 prog, max_send_fragment);
1835 if (split_send_fragment > 0
1836 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1837 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1838 prog, split_send_fragment);
1842 if (max_pipelines > 0
1843 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1844 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1845 prog, max_pipelines);
1849 if (read_buf_len > 0) {
1850 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1854 && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
1856 "%s: Max Fragment Length code %u is out of permitted values"
1857 "\n", prog, maxfraglen);
1861 if (!ssl_load_stores(ctx,
1862 vfyCApath, vfyCAfile, vfyCAstore,
1863 chCApath, chCAfile, chCAstore,
1864 crls, crl_download)) {
1865 BIO_printf(bio_err, "Error loading store locations\n");
1866 ERR_print_errors(bio_err);
1869 if (ReqCAfile != NULL) {
1870 STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
1872 if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
1873 sk_X509_NAME_pop_free(nm, X509_NAME_free);
1874 BIO_printf(bio_err, "Error loading CA names\n");
1875 ERR_print_errors(bio_err);
1878 SSL_CTX_set0_CA_list(ctx, nm);
1880 #ifndef OPENSSL_NO_ENGINE
1881 if (ssl_client_engine) {
1882 if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1883 BIO_puts(bio_err, "Error setting client auth engine\n");
1884 ERR_print_errors(bio_err);
1885 release_engine(ssl_client_engine);
1888 release_engine(ssl_client_engine);
1892 #ifndef OPENSSL_NO_PSK
1893 if (psk_key != NULL) {
1895 BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1896 SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1899 if (psksessf != NULL) {
1900 BIO *stmp = BIO_new_file(psksessf, "r");
1903 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
1904 ERR_print_errors(bio_err);
1907 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1909 if (psksess == NULL) {
1910 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
1911 ERR_print_errors(bio_err);
1915 if (psk_key != NULL || psksess != NULL)
1916 SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
1918 #ifndef OPENSSL_NO_SRTP
1919 if (srtp_profiles != NULL) {
1920 /* Returns 0 on success! */
1921 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1922 BIO_printf(bio_err, "Error setting SRTP profile\n");
1923 ERR_print_errors(bio_err);
1930 ssl_ctx_set_excert(ctx, exc);
1932 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1933 if (next_proto.data != NULL)
1934 SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1938 unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1941 BIO_printf(bio_err, "Error parsing -alpn argument\n");
1944 /* Returns 0 on success! */
1945 if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1946 BIO_printf(bio_err, "Error setting ALPN\n");
1952 for (i = 0; i < serverinfo_count; i++) {
1953 if (!SSL_CTX_add_client_custom_ext(ctx,
1954 serverinfo_types[i],
1956 serverinfo_cli_parse_cb, NULL)) {
1958 "Warning: Unable to add custom extension %u, skipping\n",
1959 serverinfo_types[i]);
1964 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1966 #ifndef OPENSSL_NO_CT
1967 /* Enable SCT processing, without early connection termination */
1968 if (ct_validation &&
1969 !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
1970 ERR_print_errors(bio_err);
1974 if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
1975 if (ct_validation) {
1976 ERR_print_errors(bio_err);
1981 * If CT validation is not enabled, the log list isn't needed so don't
1982 * show errors or abort. We try to load it regardless because then we
1983 * can show the names of the logs any SCTs came from (SCTs may be seen
1984 * even with validation disabled).
1990 SSL_CTX_set_verify(ctx, verify, verify_callback);
1992 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1993 CAstore, noCAstore)) {
1994 ERR_print_errors(bio_err);
1998 ssl_ctx_add_crls(ctx, crls, crl_download);
2000 if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
2003 if (!noservername) {
2004 tlsextcbp.biodebug = bio_err;
2005 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2006 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2008 #ifndef OPENSSL_NO_SRP
2009 if (srp_arg.srplogin != NULL
2010 && !set_up_srp_arg(ctx, &srp_arg, srp_lateuser, c_msg, c_debug))
2014 if (dane_tlsa_domain != NULL) {
2015 if (SSL_CTX_dane_enable(ctx) <= 0) {
2017 "%s: Error enabling DANE TLSA authentication.\n",
2019 ERR_print_errors(bio_err);
2025 * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
2026 * come at any time. Therefore, we use a callback to write out the session
2027 * when we know about it. This approach works for < TLSv1.3 as well.
2029 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT
2030 | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2031 SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
2033 if (set_keylog_file(ctx, keylog_file))
2041 SSL_set_post_handshake_auth(con, 1);
2043 if (enable_client_rpk)
2044 if (!SSL_set1_client_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
2045 BIO_printf(bio_err, "Error setting client certificate types\n");
2048 if (enable_server_rpk) {
2049 if (!SSL_set1_server_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
2050 BIO_printf(bio_err, "Error setting server certificate types\n");
2055 if (sess_in != NULL) {
2057 BIO *stmp = BIO_new_file(sess_in, "r");
2059 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2060 ERR_print_errors(bio_err);
2063 sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2066 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2067 ERR_print_errors(bio_err);
2070 if (!SSL_set_session(con, sess)) {
2071 BIO_printf(bio_err, "Can't set session\n");
2072 ERR_print_errors(bio_err);
2076 SSL_SESSION_free(sess);
2080 SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
2082 if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
2083 if (servername == NULL) {
2084 if (host == NULL || is_dNS_name(host))
2085 servername = (host == NULL) ? "localhost" : host;
2087 if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) {
2088 BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
2089 ERR_print_errors(bio_err);
2094 if (dane_tlsa_domain != NULL) {
2095 if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
2096 BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
2097 "authentication.\n", prog);
2098 ERR_print_errors(bio_err);
2101 if (dane_tlsa_rrset == NULL) {
2102 BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
2103 "least one -dane_tlsa_rrdata option.\n", prog);
2106 if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
2107 BIO_printf(bio_err, "%s: Failed to import any TLSA "
2108 "records.\n", prog);
2111 if (dane_ee_no_name)
2112 SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
2113 } else if (dane_tlsa_rrset != NULL) {
2114 BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
2115 "-dane_tlsa_domain option.\n", prog);
2118 #ifndef OPENSSL_NO_DTLS
2119 if (isdtls && tfo) {
2120 BIO_printf(bio_err, "%s: DTLS does not support the -tfo option\n", prog);
2126 BIO_printf(bio_c_out, "Connecting via TFO\n");
2128 if (init_client(&sock, host, port, bindhost, bindport, socket_family,
2129 socket_type, protocol, tfo, &tfo_addr) == 0) {
2130 BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
2131 BIO_closesocket(sock);
2134 BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock);
2137 if (!BIO_socket_nbio(sock, 1)) {
2138 ERR_print_errors(bio_err);
2141 BIO_printf(bio_c_out, "Turned on non blocking io\n");
2143 #ifndef OPENSSL_NO_DTLS
2145 union BIO_sock_info_u peer_info;
2147 #ifndef OPENSSL_NO_SCTP
2148 if (protocol == IPPROTO_SCTP)
2149 sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
2152 sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
2154 if (sbio == NULL || (peer_info.addr = BIO_ADDR_new()) == NULL) {
2155 BIO_printf(bio_err, "memory allocation failure\n");
2157 BIO_closesocket(sock);
2160 if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
2161 BIO_printf(bio_err, "getsockname:errno=%d\n",
2162 get_last_socket_error());
2164 BIO_ADDR_free(peer_info.addr);
2165 BIO_closesocket(sock);
2169 (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
2170 BIO_ADDR_free(peer_info.addr);
2171 peer_info.addr = NULL;
2173 if (enable_timeouts) {
2175 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2176 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2179 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2180 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2184 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2185 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2186 DTLS_get_link_min_mtu(con));
2190 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2191 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2192 BIO_printf(bio_err, "Failed to set MTU\n");
2197 /* want to do MTU discovery */
2198 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2201 #endif /* OPENSSL_NO_DTLS */
2202 sbio = BIO_new_socket(sock, BIO_NOCLOSE);
2205 BIO_printf(bio_err, "Unable to create BIO\n");
2206 ERR_print_errors(bio_err);
2207 BIO_closesocket(sock);
2211 /* Now that we're using a BIO... */
2212 if (tfo_addr != NULL)
2213 (void)BIO_set_conn_address(sbio, tfo_addr);
2215 (void)BIO_set_tfo(sbio, 1);
2220 test = BIO_new(BIO_f_nbio_test());
2222 BIO_printf(bio_err, "Unable to create BIO\n");
2226 sbio = BIO_push(test, sbio);
2230 BIO_set_callback_ex(sbio, bio_dump_callback);
2231 BIO_set_callback_arg(sbio, (char *)bio_c_out);
2234 #ifndef OPENSSL_NO_SSL_TRACE
2236 SSL_set_msg_callback(con, SSL_trace);
2239 SSL_set_msg_callback(con, msg_cb);
2240 SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
2243 if (c_tlsextdebug) {
2244 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2245 SSL_set_tlsext_debug_arg(con, bio_c_out);
2247 #ifndef OPENSSL_NO_OCSP
2249 SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
2250 SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
2251 SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
2255 SSL_set_bio(con, sbio, sbio);
2256 SSL_set_connect_state(con);
2258 /* ok, lets connect */
2259 if (fileno_stdin() > SSL_get_fd(con))
2260 width = fileno_stdin() + 1;
2262 width = SSL_get_fd(con) + 1;
2275 if (proxystr != NULL) {
2276 /* Here we must use the connect string target host & port */
2277 if (!OSSL_HTTP_proxy_connect(sbio, thost, tport, proxyuser, proxypass,
2278 0 /* no timeout */, bio_err, prog))
2282 switch ((PROTOCOL_CHOICE) starttls_proto) {
2289 * This is an ugly hack that does a lot of assumptions. We do
2290 * have to handle multi-line responses which may come in a single
2291 * packet or not. We therefore have to use BIO_gets() which does
2292 * need a buffering BIO. So during the initial chitchat we do
2293 * push a buffering BIO into the chain that is removed again
2294 * later on to not disturb the rest of the s_client operation.
2297 BIO *fbio = BIO_new(BIO_f_buffer());
2300 BIO_printf(bio_err, "Unable to create BIO\n");
2303 BIO_push(fbio, sbio);
2304 /* Wait for multi-line response to end from LMTP or SMTP */
2306 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2307 } while (mbuf_len > 3 && mbuf[3] == '-');
2308 if (protohost == NULL)
2309 protohost = "mail.example.com";
2310 if (starttls_proto == (int)PROTO_LMTP)
2311 BIO_printf(fbio, "LHLO %s\r\n", protohost);
2313 BIO_printf(fbio, "EHLO %s\r\n", protohost);
2314 (void)BIO_flush(fbio);
2316 * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2320 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2321 if (strstr(mbuf, "STARTTLS"))
2323 } while (mbuf_len > 3 && mbuf[3] == '-');
2324 (void)BIO_flush(fbio);
2329 "Didn't find STARTTLS in server response,"
2330 " trying anyway...\n");
2331 BIO_printf(sbio, "STARTTLS\r\n");
2332 BIO_read(sbio, sbuf, BUFSIZZ);
2337 BIO_read(sbio, mbuf, BUFSIZZ);
2338 BIO_printf(sbio, "STLS\r\n");
2339 mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
2341 BIO_printf(bio_err, "BIO_read failed\n");
2349 BIO *fbio = BIO_new(BIO_f_buffer());
2352 BIO_printf(bio_err, "Unable to create BIO\n");
2355 BIO_push(fbio, sbio);
2356 BIO_gets(fbio, mbuf, BUFSIZZ);
2357 /* STARTTLS command requires CAPABILITY... */
2358 BIO_printf(fbio, ". CAPABILITY\r\n");
2359 (void)BIO_flush(fbio);
2360 /* wait for multi-line CAPABILITY response */
2362 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2363 if (strstr(mbuf, "STARTTLS"))
2366 while (mbuf_len > 3 && mbuf[0] != '.');
2367 (void)BIO_flush(fbio);
2372 "Didn't find STARTTLS in server response,"
2373 " trying anyway...\n");
2374 BIO_printf(sbio, ". STARTTLS\r\n");
2375 BIO_read(sbio, sbuf, BUFSIZZ);
2380 BIO *fbio = BIO_new(BIO_f_buffer());
2383 BIO_printf(bio_err, "Unable to create BIO\n");
2386 BIO_push(fbio, sbio);
2387 /* wait for multi-line response to end from FTP */
2389 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2391 while (mbuf_len > 3 && (!isdigit(mbuf[0]) || !isdigit(mbuf[1]) || !isdigit(mbuf[2]) || mbuf[3] != ' '));
2392 (void)BIO_flush(fbio);
2395 BIO_printf(sbio, "AUTH TLS\r\n");
2396 BIO_read(sbio, sbuf, BUFSIZZ);
2400 case PROTO_XMPP_SERVER:
2403 BIO_printf(sbio, "<stream:stream "
2404 "xmlns:stream='http://etherx.jabber.org/streams' "
2405 "xmlns='jabber:%s' to='%s' version='1.0'>",
2406 starttls_proto == PROTO_XMPP ? "client" : "server",
2407 protohost ? protohost : host);
2408 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2410 BIO_printf(bio_err, "BIO_read failed\n");
2415 (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2417 "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2419 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2427 "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2428 seen = BIO_read(sbio, sbuf, BUFSIZZ);
2430 BIO_printf(bio_err, "BIO_read failed\n");
2434 if (!strstr(sbuf, "<proceed"))
2441 static const unsigned char tls_do[] = {
2442 /* IAC DO START_TLS */
2445 static const unsigned char tls_will[] = {
2446 /* IAC WILL START_TLS */
2449 static const unsigned char tls_follows[] = {
2450 /* IAC SB START_TLS FOLLOWS IAC SE */
2451 255, 250, 46, 1, 255, 240
2455 /* Telnet server should demand we issue START_TLS */
2456 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2457 if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
2459 /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2460 BIO_write(sbio, tls_will, 3);
2461 BIO_write(sbio, tls_follows, 6);
2462 (void)BIO_flush(sbio);
2463 /* Telnet server also sent the FOLLOWS sub-command */
2464 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2465 if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2472 BIO *fbio = BIO_new(BIO_f_buffer());
2475 BIO_printf(bio_err, "Unable to create BIO\n");
2478 BIO_push(fbio, sbio);
2479 BIO_printf(fbio, "STARTTLS\r\n");
2480 (void)BIO_flush(fbio);
2481 width = SSL_get_fd(con) + 1;
2487 openssl_fdset(SSL_get_fd(con), &readfds);
2488 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2489 timeout.tv_usec = 0;
2491 * If the IRCd doesn't respond within
2492 * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2493 * it doesn't support STARTTLS. Many IRCds
2494 * will not give _any_ sort of response to a
2495 * STARTTLS command when it's not supported.
2497 if (!BIO_get_buffer_num_lines(fbio)
2498 && !BIO_pending(fbio)
2499 && !BIO_pending(sbio)
2500 && select(width, (void *)&readfds, NULL, NULL,
2503 "Timeout waiting for response (%d seconds).\n",
2504 S_CLIENT_IRC_READ_TIMEOUT);
2508 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2509 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2511 /* :example.net 451 STARTTLS :You have not registered */
2512 /* :example.net 421 STARTTLS :Unknown command */
2513 if ((numeric == 451 || numeric == 421)
2514 && strstr(mbuf, "STARTTLS") != NULL) {
2515 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2518 if (numeric == 691) {
2519 BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2520 ERR_print_errors(bio_err);
2523 } while (numeric != 670);
2525 (void)BIO_flush(fbio);
2528 if (numeric != 670) {
2529 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2537 /* SSL request packet */
2538 static const unsigned char ssl_req[] = {
2539 /* payload_length, sequence_id */
2540 0x20, 0x00, 0x00, 0x01,
2542 /* capability flags, CLIENT_SSL always set */
2543 0x85, 0xae, 0x7f, 0x00,
2544 /* max-packet size */
2545 0x00, 0x00, 0x00, 0x01,
2548 /* string[23] reserved (all [0]) */
2549 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2550 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2551 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2554 int ssl_flg = 0x800;
2556 const unsigned char *packet = (const unsigned char *)sbuf;
2558 /* Receiving Initial Handshake packet. */
2559 bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
2561 BIO_printf(bio_err, "BIO_read failed\n");
2563 /* Packet length[3], Packet number[1] + minimum payload[17] */
2564 } else if (bytes < 21) {
2565 BIO_printf(bio_err, "MySQL packet too short.\n");
2567 } else if (bytes != (4 + packet[0] +
2569 (packet[2] << 16))) {
2570 BIO_printf(bio_err, "MySQL packet length does not match.\n");
2572 /* protocol version[1] */
2573 } else if (packet[4] != 0xA) {
2575 "Only MySQL protocol version 10 is supported.\n");
2580 /* server version[string+NULL] */
2583 BIO_printf(bio_err, "Cannot confirm server version. ");
2585 } else if (packet[pos++] == '\0') {
2590 /* make sure we have at least 15 bytes left in the packet */
2591 if (pos + 15 > bytes) {
2593 "MySQL server handshake packet is broken.\n");
2597 pos += 12; /* skip over conn id[4] + SALT[8] */
2598 if (packet[pos++] != '\0') { /* verify filler */
2600 "MySQL packet is broken.\n");
2604 /* capability flags[2] */
2605 if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
2606 BIO_printf(bio_err, "MySQL server does not support SSL.\n");
2610 /* Sending SSL Handshake packet. */
2611 BIO_write(sbio, ssl_req, sizeof(ssl_req));
2612 (void)BIO_flush(sbio);
2615 case PROTO_POSTGRES:
2617 static const unsigned char ssl_request[] = {
2618 /* Length SSLRequest */
2619 0, 0, 0, 8, 4, 210, 22, 47
2623 /* Send SSLRequest packet */
2624 BIO_write(sbio, ssl_request, 8);
2625 (void)BIO_flush(sbio);
2627 /* Reply will be a single S if SSL is enabled */
2628 bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2629 if (bytes != 1 || sbuf[0] != 'S')
2636 BIO *fbio = BIO_new(BIO_f_buffer());
2639 BIO_printf(bio_err, "Unable to create BIO\n");
2642 BIO_push(fbio, sbio);
2643 BIO_gets(fbio, mbuf, BUFSIZZ);
2644 /* STARTTLS command requires CAPABILITIES... */
2645 BIO_printf(fbio, "CAPABILITIES\r\n");
2646 (void)BIO_flush(fbio);
2647 BIO_gets(fbio, mbuf, BUFSIZZ);
2648 /* no point in trying to parse the CAPABILITIES response if there is none */
2649 if (strstr(mbuf, "101") != NULL) {
2650 /* wait for multi-line CAPABILITIES response */
2652 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2653 if (strstr(mbuf, "STARTTLS"))
2655 } while (mbuf_len > 1 && mbuf[0] != '.');
2657 (void)BIO_flush(fbio);
2662 "Didn't find STARTTLS in server response,"
2663 " trying anyway...\n");
2664 BIO_printf(sbio, "STARTTLS\r\n");
2665 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2667 BIO_printf(bio_err, "BIO_read failed\n");
2670 mbuf[mbuf_len] = '\0';
2671 if (strstr(mbuf, "382") == NULL) {
2672 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2680 BIO *fbio = BIO_new(BIO_f_buffer());
2683 BIO_printf(bio_err, "Unable to create BIO\n");
2686 BIO_push(fbio, sbio);
2687 /* wait for multi-line response to end from Sieve */
2689 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2691 * According to RFC 5804 § 1.7, capability
2692 * is case-insensitive, make it uppercase
2694 if (mbuf_len > 1 && mbuf[0] == '"') {
2695 make_uppercase(mbuf);
2696 if (HAS_PREFIX(mbuf, "\"STARTTLS\""))
2699 } while (mbuf_len > 1 && mbuf[0] == '"');
2700 (void)BIO_flush(fbio);
2705 "Didn't find STARTTLS in server response,"
2706 " trying anyway...\n");
2707 BIO_printf(sbio, "STARTTLS\r\n");
2708 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2710 BIO_printf(bio_err, "BIO_read failed\n");
2713 mbuf[mbuf_len] = '\0';
2715 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2719 * According to RFC 5804 § 2.2, response codes are case-
2720 * insensitive, make it uppercase but preserve the response.
2722 strncpy(sbuf, mbuf, 2);
2723 make_uppercase(sbuf);
2724 if (!HAS_PREFIX(sbuf, "OK")) {
2725 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2732 /* StartTLS Operation according to RFC 4511 */
2733 static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
2735 "messageID=INTEGER:1\n"
2736 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2737 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2739 char *genstr = NULL;
2741 ASN1_TYPE *atyp = NULL;
2742 BIO *ldapbio = BIO_new(BIO_s_mem());
2743 CONF *cnf = NCONF_new(NULL);
2745 if (ldapbio == NULL || cnf == NULL) {
2750 BIO_puts(ldapbio, ldap_tls_genconf);
2751 if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
2755 BIO_printf(bio_err, "NCONF_load_bio failed\n");
2758 BIO_printf(bio_err, "Error on line %ld\n", errline);
2763 genstr = NCONF_get_string(cnf, "default", "asn1");
2764 if (genstr == NULL) {
2766 BIO_printf(bio_err, "NCONF_get_string failed\n");
2769 atyp = ASN1_generate_nconf(genstr, cnf);
2772 BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
2777 /* Send SSLRequest packet */
2778 BIO_write(sbio, atyp->value.sequence->data,
2779 atyp->value.sequence->length);
2780 (void)BIO_flush(sbio);
2781 ASN1_TYPE_free(atyp);
2783 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2785 BIO_printf(bio_err, "BIO_read failed\n");
2788 result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
2790 BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
2792 } else if (result > 0) {
2793 BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
2802 if (early_data_file != NULL
2803 && ((SSL_get0_session(con) != NULL
2804 && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
2806 && SSL_SESSION_get_max_early_data(psksess) > 0))) {
2807 BIO *edfile = BIO_new_file(early_data_file, "r");
2808 size_t readbytes, writtenbytes;
2811 if (edfile == NULL) {
2812 BIO_printf(bio_err, "Cannot open early data file\n");
2817 if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
2820 while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
2821 switch (SSL_get_error(con, 0)) {
2822 case SSL_ERROR_WANT_WRITE:
2823 case SSL_ERROR_WANT_ASYNC:
2824 case SSL_ERROR_WANT_READ:
2825 /* Just keep trying - busy waiting */
2828 BIO_printf(bio_err, "Error writing early data\n");
2830 ERR_print_errors(bio_err);
2839 user_data_init(&user_data, con, cbuf, BUFSIZZ, cmdmode);
2844 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2845 timeoutp = &timeout;
2849 if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
2850 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
2858 BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2859 print_ssl_summary(con);
2862 print_stuff(bio_c_out, con, full_log);
2866 if (starttls_proto) {
2867 BIO_write(bio_err, mbuf, mbuf_len);
2868 /* We don't need to know any more */
2870 starttls_proto = PROTO_OFF;
2875 BIO_printf(bio_c_out,
2876 "drop connection and then reconnect\n");
2877 do_ssl_shutdown(con);
2878 SSL_set_connect_state(con);
2879 BIO_closesocket(SSL_get_fd(con));
2887 switch (user_data_process(&user_data, &cbuf_len, &cbuf_off)) {
2889 BIO_printf(bio_err, "ERROR\n");
2891 case USER_DATA_PROCESS_SHUT:
2895 case USER_DATA_PROCESS_RESTART:
2898 case USER_DATA_PROCESS_NO_DATA:
2901 case USER_DATA_PROCESS_CONTINUE:
2907 && user_data_has_data(&user_data));
2914 ssl_pending = read_ssl && SSL_has_pending(con);
2917 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2920 * Note that select() returns when read _would not block_,
2921 * and EOF satisfies that. To avoid a CPU-hogging loop,
2922 * set the flag so we exit.
2924 if (read_tty && !at_eof)
2925 openssl_fdset(fileno_stdin(), &readfds);
2926 #if !defined(OPENSSL_SYS_VMS)
2928 openssl_fdset(fileno_stdout(), &writefds);
2932 openssl_fdset(SSL_get_fd(con), &readfds);
2934 openssl_fdset(SSL_get_fd(con), &writefds);
2936 if (!tty_on || !write_tty) {
2938 openssl_fdset(SSL_get_fd(con), &readfds);
2940 openssl_fdset(SSL_get_fd(con), &writefds);
2945 * Note: under VMS with SOCKETSHR the second parameter is
2946 * currently of type (int *) whereas under other systems it is
2947 * (void *) if you don't have a cast it will choke the compiler:
2948 * if you do have a cast then you can either go for (int *) or
2951 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2953 * Under Windows/DOS we make the assumption that we can always
2954 * write to the tty: therefore, if we need to write to the tty we
2955 * just fall through. Otherwise we timeout the select every
2956 * second and see if there are any keypresses. Note: this is a
2957 * hack, in a proper Windows application we wouldn't do this.
2964 i = select(width, (void *)&readfds, (void *)&writefds,
2966 if (!i && (!has_stdin_waiting() || !read_tty))
2969 i = select(width, (void *)&readfds, (void *)&writefds,
2973 i = select(width, (void *)&readfds, (void *)&writefds,
2977 BIO_printf(bio_err, "bad select %d\n",
2978 get_last_socket_error());
2983 if (SSL_is_dtls(con) && DTLSv1_handle_timeout(con) > 0)
2984 BIO_printf(bio_err, "TIMEOUT occurred\n");
2986 if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
2987 k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
2988 switch (SSL_get_error(con, k)) {
2989 case SSL_ERROR_NONE:
2994 /* we have done a write(con,NULL,0); */
2995 if (cbuf_len == 0) {
2998 } else { /* if (cbuf_len > 0) */
3004 case SSL_ERROR_WANT_WRITE:
3005 BIO_printf(bio_c_out, "write W BLOCK\n");
3009 case SSL_ERROR_WANT_ASYNC:
3010 BIO_printf(bio_c_out, "write A BLOCK\n");
3011 wait_for_async(con);
3015 case SSL_ERROR_WANT_READ:
3016 BIO_printf(bio_c_out, "write R BLOCK\n");
3021 case SSL_ERROR_WANT_X509_LOOKUP:
3022 BIO_printf(bio_c_out, "write X BLOCK\n");
3024 case SSL_ERROR_ZERO_RETURN:
3025 if (cbuf_len != 0) {
3026 BIO_printf(bio_c_out, "shutdown\n");
3035 case SSL_ERROR_SYSCALL:
3036 if ((k != 0) || (cbuf_len != 0)) {
3037 int sockerr = get_last_socket_error();
3039 if (!tfo || sockerr != EISCONN) {
3040 BIO_printf(bio_err, "write:errno=%d\n", sockerr);
3048 case SSL_ERROR_WANT_ASYNC_JOB:
3049 /* This shouldn't ever happen in s_client - treat as an error */
3051 ERR_print_errors(bio_err);
3055 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
3056 /* Assume Windows/DOS/BeOS can always write */
3057 else if (!ssl_pending && write_tty)
3059 else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
3062 #ifdef CHARSET_EBCDIC
3063 ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
3065 i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
3068 BIO_printf(bio_c_out, "DONE\n");
3075 if (sbuf_len <= 0) {
3079 } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
3084 SSL_renegotiate(con);
3089 k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
3091 switch (SSL_get_error(con, k)) {
3092 case SSL_ERROR_NONE:
3101 case SSL_ERROR_WANT_ASYNC:
3102 BIO_printf(bio_c_out, "read A BLOCK\n");
3103 wait_for_async(con);
3106 if ((read_tty == 0) && (write_ssl == 0))
3109 case SSL_ERROR_WANT_WRITE:
3110 BIO_printf(bio_c_out, "read W BLOCK\n");
3114 case SSL_ERROR_WANT_READ:
3115 BIO_printf(bio_c_out, "read R BLOCK\n");
3118 if ((read_tty == 0) && (write_ssl == 0))
3121 case SSL_ERROR_WANT_X509_LOOKUP:
3122 BIO_printf(bio_c_out, "read X BLOCK\n");
3124 case SSL_ERROR_SYSCALL:
3125 ret = get_last_socket_error();
3127 BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
3129 BIO_printf(bio_err, "read:errno=%d\n", ret);
3131 case SSL_ERROR_ZERO_RETURN:
3132 BIO_printf(bio_c_out, "closed\n");
3135 case SSL_ERROR_WANT_ASYNC_JOB:
3136 /* This shouldn't ever happen in s_client. Treat as an error */
3138 ERR_print_errors(bio_err);
3143 /* don't wait for client input in the non-interactive mode */
3144 else if (nointeractive) {
3149 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
3150 #if defined(OPENSSL_SYS_MSDOS)
3151 else if (has_stdin_waiting())
3153 else if (FD_ISSET(fileno_stdin(), &readfds))
3159 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
3161 /* both loops are skipped when i <= 0 */
3162 for (j = 0; j < i; j++)
3163 if (cbuf[j] == '\n')
3165 for (j = i - 1; j >= 0; j--) {
3166 cbuf[j + lf_num] = cbuf[j];
3167 if (cbuf[j] == '\n') {
3170 cbuf[j + lf_num] = '\r';
3173 assert(lf_num == 0);
3175 i = raw_read_stdin(cbuf, BUFSIZZ);
3176 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3181 if (!c_ign_eof && i <= 0) {
3182 BIO_printf(bio_err, "DONE\n");
3186 if (i > 0 && !user_data_add(&user_data, i)) {
3197 print_stuff(bio_c_out, con, full_log);
3198 do_ssl_shutdown(con);
3201 * If we ended with an alert being sent, but still with data in the
3202 * network buffer to be read, then calling BIO_closesocket() will
3203 * result in a TCP-RST being sent. On some platforms (notably
3204 * Windows) then this will result in the peer immediately abandoning
3205 * the connection including any buffered alert data before it has
3206 * had a chance to be read. Shutting down the sending side first,
3207 * and then closing the socket sends TCP-FIN first followed by
3208 * TCP-RST. This seems to allow the peer to read the alert data.
3210 shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
3212 * We just said we have nothing else to say, but it doesn't mean that
3213 * the other side has nothing. It's even recommended to consume incoming
3214 * data. [In testing context this ensures that alerts are passed on...]
3217 timeout.tv_usec = 500000; /* some extreme round-trip */
3220 openssl_fdset(sock, &readfds);
3221 } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
3222 && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
3224 BIO_closesocket(SSL_get_fd(con));
3228 print_stuff(bio_c_out, con, 1);
3231 SSL_SESSION_free(psksess);
3232 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3233 OPENSSL_free(next_proto.data);
3236 set_keylog_file(NULL, NULL);
3238 sk_X509_CRL_pop_free(crls, X509_CRL_free);
3240 OSSL_STACK_OF_X509_free(chain);
3242 #ifndef OPENSSL_NO_SRP
3243 OPENSSL_free(srp_arg.srppassin);
3245 OPENSSL_free(sname_alloc);
3246 BIO_ADDR_free(tfo_addr);
3247 OPENSSL_free(connectstr);
3248 OPENSSL_free(bindstr);
3249 OPENSSL_free(bindhost);
3250 OPENSSL_free(bindport);
3253 OPENSSL_free(thost);
3254 OPENSSL_free(tport);
3255 X509_VERIFY_PARAM_free(vpm);
3256 ssl_excert_free(exc);
3257 sk_OPENSSL_STRING_free(ssl_args);
3258 sk_OPENSSL_STRING_free(dane_tlsa_rrset);
3259 SSL_CONF_CTX_free(cctx);
3260 OPENSSL_clear_free(cbuf, BUFSIZZ);
3261 OPENSSL_clear_free(sbuf, BUFSIZZ);
3262 OPENSSL_clear_free(mbuf, BUFSIZZ);
3263 clear_free(proxypass);
3265 BIO_free(bio_c_out);
3267 BIO_free(bio_c_msg);
3272 static void print_stuff(BIO *bio, SSL *s, int full)
3276 const SSL_CIPHER *c;
3277 EVP_PKEY *public_key;
3278 int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
3280 #ifndef OPENSSL_NO_COMP
3281 const COMP_METHOD *comp, *expansion;
3283 unsigned char *exportedkeymat;
3284 #ifndef OPENSSL_NO_CT
3285 const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
3289 int got_a_chain = 0;
3291 sk = SSL_get_peer_cert_chain(s);
3295 BIO_printf(bio, "---\nCertificate chain\n");
3296 for (i = 0; i < sk_X509_num(sk); i++) {
3297 BIO_printf(bio, "%2d s:", i);
3298 X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
3299 BIO_puts(bio, "\n");
3300 BIO_printf(bio, " i:");
3301 X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
3302 BIO_puts(bio, "\n");
3303 public_key = X509_get_pubkey(sk_X509_value(sk, i));
3304 if (public_key != NULL) {
3305 BIO_printf(bio, " a:PKEY: %s, %d (bit); sigalg: %s\n",
3306 OBJ_nid2sn(EVP_PKEY_get_base_id(public_key)),
3307 EVP_PKEY_get_bits(public_key),
3308 OBJ_nid2sn(X509_get_signature_nid(sk_X509_value(sk, i))));
3309 EVP_PKEY_free(public_key);
3311 BIO_printf(bio, " v:NotBefore: ");
3312 ASN1_TIME_print(bio, X509_get0_notBefore(sk_X509_value(sk, i)));
3313 BIO_printf(bio, "; NotAfter: ");
3314 ASN1_TIME_print(bio, X509_get0_notAfter(sk_X509_value(sk, i)));
3315 BIO_puts(bio, "\n");
3317 PEM_write_bio_X509(bio, sk_X509_value(sk, i));
3321 BIO_printf(bio, "---\n");
3322 peer = SSL_get0_peer_certificate(s);
3324 BIO_printf(bio, "Server certificate\n");
3326 /* Redundant if we showed the whole chain */
3327 if (!(c_showcerts && got_a_chain))
3328 PEM_write_bio_X509(bio, peer);
3329 dump_cert_text(bio, peer);
3331 BIO_printf(bio, "no peer certificate available\n");
3334 /* Only display RPK information if configured */
3335 if (SSL_get_negotiated_client_cert_type(s) == TLSEXT_cert_type_rpk)
3336 BIO_printf(bio, "Client-to-server raw public key negotiated\n");
3337 if (SSL_get_negotiated_server_cert_type(s) == TLSEXT_cert_type_rpk)
3338 BIO_printf(bio, "Server-to-client raw public key negotiated\n");
3339 if (enable_server_rpk) {
3340 EVP_PKEY *peer_rpk = SSL_get0_peer_rpk(s);
3342 if (peer_rpk != NULL) {
3343 BIO_printf(bio, "Server raw public key\n");
3344 EVP_PKEY_print_public(bio, peer_rpk, 2, NULL);
3346 BIO_printf(bio, "no peer rpk available\n");
3350 print_ca_names(bio, s);
3352 ssl_print_sigalgs(bio, s);
3353 ssl_print_tmp_key(bio, s);
3355 #ifndef OPENSSL_NO_CT
3357 * When the SSL session is anonymous, or resumed via an abbreviated
3358 * handshake, no SCTs are provided as part of the handshake. While in
3359 * a resumed session SCTs may be present in the session's certificate,
3360 * no callbacks are invoked to revalidate these, and in any case that
3361 * set of SCTs may be incomplete. Thus it makes little sense to
3362 * attempt to display SCTs from a resumed session's certificate, and of
3363 * course none are associated with an anonymous peer.
3365 if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
3366 const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
3367 int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
3369 BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
3370 if (sct_count > 0) {
3371 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
3373 BIO_printf(bio, "---\n");
3374 for (i = 0; i < sct_count; ++i) {
3375 SCT *sct = sk_SCT_value(scts, i);
3377 BIO_printf(bio, "SCT validation status: %s\n",
3378 SCT_validation_status_string(sct));
3379 SCT_print(sct, bio, 0, log_store);
3380 if (i < sct_count - 1)
3381 BIO_printf(bio, "\n---\n");
3383 BIO_printf(bio, "\n");
3389 "---\nSSL handshake has read %ju bytes "
3390 "and written %ju bytes\n",
3391 BIO_number_read(SSL_get_rbio(s)),
3392 BIO_number_written(SSL_get_wbio(s)));
3394 print_verify_detail(s, bio);
3395 BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
3396 c = SSL_get_current_cipher(s);
3397 BIO_printf(bio, "%s, Cipher is %s\n",
3398 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3402 pktmp = X509_get0_pubkey(peer);
3403 BIO_printf(bio, "Server public key is %d bit\n",
3404 EVP_PKEY_get_bits(pktmp));
3407 ssl_print_secure_renegotiation_notes(bio, s);
3409 #ifndef OPENSSL_NO_COMP
3410 comp = SSL_get_current_compression(s);
3411 expansion = SSL_get_current_expansion(s);
3412 BIO_printf(bio, "Compression: %s\n",
3413 comp ? SSL_COMP_get_name(comp) : "NONE");
3414 BIO_printf(bio, "Expansion: %s\n",
3415 expansion ? SSL_COMP_get_name(expansion) : "NONE");
3417 #ifndef OPENSSL_NO_KTLS
3418 if (BIO_get_ktls_send(SSL_get_wbio(s)))
3419 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3420 if (BIO_get_ktls_recv(SSL_get_rbio(s)))
3421 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3424 if (OSSL_TRACE_ENABLED(TLS)) {
3425 /* Print out local port of connection: useful for debugging */
3427 union BIO_sock_info_u info;
3429 sock = SSL_get_fd(s);
3430 if ((info.addr = BIO_ADDR_new()) != NULL
3431 && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
3432 BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
3433 ntohs(BIO_ADDR_rawport(info.addr)));
3435 BIO_ADDR_free(info.addr);
3438 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3439 if (next_proto.status != -1) {
3440 const unsigned char *proto;
3441 unsigned int proto_len;
3442 SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
3443 BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
3444 BIO_write(bio, proto, proto_len);
3445 BIO_write(bio, "\n", 1);
3449 const unsigned char *proto;
3450 unsigned int proto_len;
3451 SSL_get0_alpn_selected(s, &proto, &proto_len);
3452 if (proto_len > 0) {
3453 BIO_printf(bio, "ALPN protocol: ");
3454 BIO_write(bio, proto, proto_len);
3455 BIO_write(bio, "\n", 1);
3457 BIO_printf(bio, "No ALPN negotiated\n");
3460 #ifndef OPENSSL_NO_SRTP
3462 SRTP_PROTECTION_PROFILE *srtp_profile =
3463 SSL_get_selected_srtp_profile(s);
3466 BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
3467 srtp_profile->name);
3472 switch (SSL_get_early_data_status(s)) {
3473 case SSL_EARLY_DATA_NOT_SENT:
3474 BIO_printf(bio, "Early data was not sent\n");
3477 case SSL_EARLY_DATA_REJECTED:
3478 BIO_printf(bio, "Early data was rejected\n");
3481 case SSL_EARLY_DATA_ACCEPTED:
3482 BIO_printf(bio, "Early data was accepted\n");
3488 * We also print the verify results when we dump session information,
3489 * but in TLSv1.3 we may not get that right away (or at all) depending
3490 * on when we get a NewSessionTicket. Therefore, we print it now as well.
3492 verify_result = SSL_get_verify_result(s);
3493 BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
3494 X509_verify_cert_error_string(verify_result));
3496 /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3497 SSL_SESSION_print(bio, SSL_get_session(s));
3500 if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
3501 BIO_printf(bio, "Keying material exporter:\n");
3502 BIO_printf(bio, " Label: '%s'\n", keymatexportlabel);
3503 BIO_printf(bio, " Length: %i bytes\n", keymatexportlen);
3504 exportedkeymat = app_malloc(keymatexportlen, "export key");
3505 if (SSL_export_keying_material(s, exportedkeymat,
3508 strlen(keymatexportlabel),
3510 BIO_printf(bio, " Error\n");
3512 BIO_printf(bio, " Keying material: ");
3513 for (i = 0; i < keymatexportlen; i++)
3514 BIO_printf(bio, "%02X", exportedkeymat[i]);
3515 BIO_printf(bio, "\n");
3517 OPENSSL_free(exportedkeymat);
3519 BIO_printf(bio, "---\n");
3520 /* flush, or debugging output gets mixed with http response */
3521 (void)BIO_flush(bio);
3524 # ifndef OPENSSL_NO_OCSP
3525 static int ocsp_resp_cb(SSL *s, void *arg)
3527 const unsigned char *p;
3530 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3531 BIO_puts(arg, "OCSP response: ");
3533 BIO_puts(arg, "no response sent\n");
3536 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3538 BIO_puts(arg, "response parse error\n");
3539 BIO_dump_indent(arg, (char *)p, len, 4);
3542 BIO_puts(arg, "\n======================================\n");
3543 OCSP_RESPONSE_print(arg, rsp, 0);
3544 BIO_puts(arg, "======================================\n");
3545 OCSP_RESPONSE_free(rsp);
3550 static int ldap_ExtendedResponse_parse(const char *buf, long rem)
3552 const unsigned char *cur, *end;
3554 int tag, xclass, inf, ret = -1;
3556 cur = (const unsigned char *)buf;
3562 * LDAPMessage ::= SEQUENCE {
3563 * messageID MessageID,
3564 * protocolOp CHOICE {
3566 * extendedResp ExtendedResponse,
3568 * controls [0] Controls OPTIONAL }
3570 * ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3571 * COMPONENTS OF LDAPResult,
3572 * responseName [10] LDAPOID OPTIONAL,
3573 * responseValue [11] OCTET STRING OPTIONAL }
3575 * LDAPResult ::= SEQUENCE {
3576 * resultCode ENUMERATED {
3582 * diagnosticMessage LDAPString,
3583 * referral [3] Referral OPTIONAL }
3587 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3588 if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
3589 (rem = end - cur, len > rem)) {
3590 BIO_printf(bio_err, "Unexpected LDAP response\n");
3594 rem = len; /* ensure that we don't overstep the SEQUENCE */
3596 /* pull MessageID */
3597 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3598 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
3599 (rem = end - cur, len > rem)) {
3600 BIO_printf(bio_err, "No MessageID\n");
3604 cur += len; /* shall we check for MessageId match or just skip? */
3606 /* pull [APPLICATION 24] */
3608 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3609 if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
3611 BIO_printf(bio_err, "Not ExtendedResponse\n");
3615 /* pull resultCode */
3617 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3618 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
3619 (rem = end - cur, len > rem)) {
3620 BIO_printf(bio_err, "Not LDAPResult\n");
3624 /* len should always be one, but just in case... */
3625 for (ret = 0, inf = 0; inf < len; inf++) {
3629 /* There is more data, but we don't care... */
3635 * Host dNS Name verifier: used for checking that the hostname is in dNS format
3636 * before setting it as SNI
3638 static int is_dNS_name(const char *host)
3640 const size_t MAX_LABEL_LENGTH = 63;
3643 size_t length = strlen(host);
3644 size_t label_length = 0;
3645 int all_numeric = 1;
3648 * Deviation from strict DNS name syntax, also check names with '_'
3649 * Check DNS name syntax, any '-' or '.' must be internal,
3650 * and on either side of each '.' we can't have a '-' or '.'.
3652 * If the name has just one label, we don't consider it a DNS name.
3654 for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) {
3657 if ((c >= 'a' && c <= 'z')
3658 || (c >= 'A' && c <= 'Z')
3665 if (c >= '0' && c <= '9') {
3670 /* Dot and hyphen cannot be first or last. */
3671 if (i > 0 && i < length - 1) {
3677 * Next to a dot the preceding and following characters must not be
3678 * another dot or a hyphen. Otherwise, record that the name is
3679 * plausible, since it has two or more labels.
3682 && host[i + 1] != '.'
3683 && host[i - 1] != '-'
3684 && host[i + 1] != '-') {
3694 /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
3695 isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH);
3700 static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf,
3701 size_t bufmax, int mode)
3703 user_data->con = con;
3704 user_data->buf = buf;
3705 user_data->bufmax = bufmax;
3706 user_data->buflen = 0;
3707 user_data->bufoff = 0;
3708 user_data->mode = mode;
3711 static int user_data_add(struct user_data_st *user_data, size_t i)
3713 if (user_data->buflen != 0 || i > user_data->bufmax - 1)
3716 user_data->buflen = i;
3717 user_data->bufoff = 0;
3722 #define USER_COMMAND_HELP 0
3723 #define USER_COMMAND_QUIT 1
3724 #define USER_COMMAND_RECONNECT 2
3725 #define USER_COMMAND_RENEGOTIATE 3
3726 #define USER_COMMAND_KEY_UPDATE 4
3728 static int user_data_execute(struct user_data_st *user_data, int cmd, char *arg)
3731 case USER_COMMAND_HELP:
3732 /* This only ever occurs in advanced mode, so just emit advanced help */
3733 BIO_printf(bio_err, "Enter text to send to the peer followed by <enter>\n");
3734 BIO_printf(bio_err, "To issue a command insert {cmd} or {cmd:arg} anywhere in the text\n");
3735 BIO_printf(bio_err, "Entering {{ will send { to the peer\n");
3736 BIO_printf(bio_err, "The following commands are available\n");
3737 BIO_printf(bio_err, " {help}: Get this help text\n");
3738 BIO_printf(bio_err, " {quit}: Close the connection to the peer\n");
3739 BIO_printf(bio_err, " {reconnect}: Reconnect to the peer\n");
3740 if (SSL_version(user_data->con) == TLS1_3_VERSION) {
3741 BIO_printf(bio_err, " {keyup:req|noreq}: Send a Key Update message\n");
3742 BIO_printf(bio_err, " Arguments:\n");
3743 BIO_printf(bio_err, " req = peer update requested (default)\n");
3744 BIO_printf(bio_err, " noreq = peer update not requested\n");
3746 BIO_printf(bio_err, " {reneg}: Attempt to renegotiate\n");
3748 BIO_printf(bio_err, "\n");
3749 return USER_DATA_PROCESS_NO_DATA;
3751 case USER_COMMAND_QUIT:
3752 BIO_printf(bio_err, "DONE\n");
3753 return USER_DATA_PROCESS_SHUT;
3755 case USER_COMMAND_RECONNECT:
3756 BIO_printf(bio_err, "RECONNECTING\n");
3757 do_ssl_shutdown(user_data->con);
3758 SSL_set_connect_state(user_data->con);
3759 BIO_closesocket(SSL_get_fd(user_data->con));
3760 return USER_DATA_PROCESS_RESTART;
3762 case USER_COMMAND_RENEGOTIATE:
3763 BIO_printf(bio_err, "RENEGOTIATING\n");
3764 if (!SSL_renegotiate(user_data->con))
3766 return USER_DATA_PROCESS_CONTINUE;
3768 case USER_COMMAND_KEY_UPDATE: {
3771 if (OPENSSL_strcasecmp(arg, "req") == 0)
3772 updatetype = SSL_KEY_UPDATE_REQUESTED;
3773 else if (OPENSSL_strcasecmp(arg, "noreq") == 0)
3774 updatetype = SSL_KEY_UPDATE_NOT_REQUESTED;
3776 return USER_DATA_PROCESS_BAD_ARGUMENT;
3777 BIO_printf(bio_err, "KEYUPDATE\n");
3778 if (!SSL_key_update(user_data->con, updatetype))
3780 return USER_DATA_PROCESS_CONTINUE;
3786 BIO_printf(bio_err, "ERROR\n");
3787 ERR_print_errors(bio_err);
3789 return USER_DATA_PROCESS_SHUT;
3792 static int user_data_process(struct user_data_st *user_data, size_t *len,
3795 char *buf_start = user_data->buf + user_data->bufoff;
3796 size_t outlen = user_data->buflen;
3798 if (user_data->buflen == 0) {
3801 return USER_DATA_PROCESS_NO_DATA;
3804 if (user_data->mode == USER_DATA_MODE_BASIC) {
3805 switch (buf_start[0]) {
3807 user_data->buflen = user_data->bufoff = *len = *off = 0;
3808 return user_data_execute(user_data, USER_COMMAND_QUIT, NULL);
3811 user_data->buflen = user_data->bufoff = *len = *off = 0;
3812 return user_data_execute(user_data, USER_COMMAND_RECONNECT, NULL);
3815 user_data->buflen = user_data->bufoff = *len = *off = 0;
3816 return user_data_execute(user_data, USER_COMMAND_RENEGOTIATE, NULL);
3820 user_data->buflen = user_data->bufoff = *len = *off = 0;
3821 return user_data_execute(user_data, USER_COMMAND_KEY_UPDATE,
3822 buf_start[0] == 'K' ? "req" : "noreq");
3826 } else if (user_data->mode == USER_DATA_MODE_ADVANCED) {
3827 char *cmd_start = buf_start;
3829 cmd_start[outlen] = '\0';
3831 cmd_start = strstr(cmd_start, "{");
3832 if (cmd_start == buf_start && *(cmd_start + 1) == '{') {
3833 /* The "{" is escaped, so skip it */
3836 user_data->bufoff++;
3837 user_data->buflen--;
3843 if (cmd_start == buf_start) {
3844 /* Command detected */
3845 char *cmd_end = strstr(cmd_start, "}");
3847 int cmd = -1, ret = USER_DATA_PROCESS_NO_DATA;
3850 if (cmd_end == NULL) {
3851 /* Malformed command */
3852 cmd_start[outlen - 1] = '\0';
3854 "ERROR PROCESSING COMMAND. REST OF LINE IGNORED: %s\n",
3856 user_data->buflen = user_data->bufoff = *len = *off = 0;
3857 return USER_DATA_PROCESS_NO_DATA;
3860 arg_start = strstr(cmd_start, ":");
3861 if (arg_start != NULL) {
3865 /* Skip over the { */
3868 * Now we have cmd_start pointing to a NUL terminated string for
3869 * the command, and arg_start either being NULL or pointing to a
3870 * NUL terminated string for the argument.
3872 if (OPENSSL_strcasecmp(cmd_start, "help") == 0) {
3873 cmd = USER_COMMAND_HELP;
3874 } else if (OPENSSL_strcasecmp(cmd_start, "quit") == 0) {
3875 cmd = USER_COMMAND_QUIT;
3876 } else if (OPENSSL_strcasecmp(cmd_start, "reconnect") == 0) {
3877 cmd = USER_COMMAND_RECONNECT;
3878 } else if (SSL_version(user_data->con) == TLS1_3_VERSION) {
3879 if (OPENSSL_strcasecmp(cmd_start, "keyup") == 0) {
3880 cmd = USER_COMMAND_KEY_UPDATE;
3881 if (arg_start == NULL)
3885 /* (D)TLSv1.2 or below */
3886 if (OPENSSL_strcasecmp(cmd_start, "reneg") == 0)
3887 cmd = USER_COMMAND_RENEGOTIATE;
3890 BIO_printf(bio_err, "UNRECOGNISED COMMAND (IGNORED): %s\n",
3893 ret = user_data_execute(user_data, cmd, arg_start);
3894 if (ret == USER_DATA_PROCESS_BAD_ARGUMENT) {
3895 BIO_printf(bio_err, "BAD ARGUMENT (COMMAND IGNORED): %s\n",
3897 ret = USER_DATA_PROCESS_NO_DATA;
3900 oldoff = user_data->bufoff;
3901 user_data->bufoff = (cmd_end - user_data->buf) + 1;
3902 user_data->buflen -= user_data->bufoff - oldoff;
3903 if (user_data->buf + 1 == cmd_start
3904 && user_data->buflen == 1
3905 && user_data->buf[user_data->bufoff] == '\n') {
3907 * This command was the only thing on the whole line. We
3908 * supress the final `\n`
3910 user_data->bufoff = 0;
3911 user_data->buflen = 0;
3915 } else if (cmd_start != NULL) {
3917 * There is a command on this line, but its not at the start. Output
3918 * the start of the line, and we'll process the command next time
3919 * we call this function
3921 outlen = cmd_start - buf_start;
3925 #ifdef CHARSET_EBCDIC
3926 ebcdic2ascii(buf_start, buf_start, outlen);
3929 *off = user_data->bufoff;
3930 user_data->buflen -= outlen;
3931 if (user_data->buflen == 0)
3932 user_data->bufoff = 0;
3934 user_data->bufoff += outlen;
3935 return USER_DATA_PROCESS_CONTINUE;
3938 static int user_data_has_data(struct user_data_st *user_data)
3940 return user_data->buflen > 0;
3942 #endif /* OPENSSL_NO_SOCK */