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
62 static int c_debug = 0;
63 static int c_showcerts = 0;
64 static char *keymatexportlabel = NULL;
65 static int keymatexportlen = 20;
66 static BIO *bio_c_out = NULL;
67 static int c_quiet = 0;
68 static char *sess_out = NULL;
69 static SSL_SESSION *psksess = NULL;
71 static void print_stuff(BIO *berr, SSL *con, int full);
72 #ifndef OPENSSL_NO_OCSP
73 static int ocsp_resp_cb(SSL *s, void *arg);
75 static int ldap_ExtendedResponse_parse(const char *buf, long rem);
76 static int is_dNS_name(const char *host);
78 static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
79 static int enable_server_rpk = 0;
81 static int saved_errno;
83 static void save_errno(void)
89 static int restore_errno(void)
96 /* Default PSK identity and key */
97 static char *psk_identity = "Client_identity";
99 #ifndef OPENSSL_NO_PSK
100 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
101 unsigned int max_identity_len,
103 unsigned int max_psk_len)
110 BIO_printf(bio_c_out, "psk_client_cb\n");
112 /* no ServerKeyExchange message */
114 BIO_printf(bio_c_out,
115 "NULL received PSK identity hint, continuing anyway\n");
116 } else if (c_debug) {
117 BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
121 * lookup PSK identity and PSK key based on the given identity hint here
123 ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
124 if (ret < 0 || (unsigned int)ret > max_identity_len)
127 BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
130 /* convert the PSK key to binary */
131 key = OPENSSL_hexstr2buf(psk_key, &key_len);
133 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
137 if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
139 "psk buffer of callback is too small (%d) for key (%ld)\n",
140 max_psk_len, key_len);
145 memcpy(psk, key, key_len);
149 BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
154 BIO_printf(bio_err, "Error in PSK client callback\n");
159 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
160 const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
162 static int psk_use_session_cb(SSL *s, const EVP_MD *md,
163 const unsigned char **id, size_t *idlen,
166 SSL_SESSION *usesess = NULL;
167 const SSL_CIPHER *cipher = NULL;
169 if (psksess != NULL) {
170 SSL_SESSION_up_ref(psksess);
174 unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
177 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
182 /* We default to SHA-256 */
183 cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
184 if (cipher == NULL) {
185 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
190 usesess = SSL_SESSION_new();
192 || !SSL_SESSION_set1_master_key(usesess, key, key_len)
193 || !SSL_SESSION_set_cipher(usesess, cipher)
194 || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
201 cipher = SSL_SESSION_get0_cipher(usesess);
205 if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
206 /* PSK not usable, ignore it */
210 SSL_SESSION_free(usesess);
213 *id = (unsigned char *)psk_identity;
214 *idlen = strlen(psk_identity);
220 SSL_SESSION_free(usesess);
224 /* This is a context that we pass to callbacks */
225 typedef struct tlsextctx_st {
230 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
232 tlsextctx *p = (tlsextctx *) arg;
233 const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
234 if (SSL_get_servername_type(s) != -1)
235 p->ack = !SSL_session_reused(s) && hn != NULL;
237 BIO_printf(bio_err, "Can't use SSL_get_servername\n");
239 return SSL_TLSEXT_ERR_OK;
242 #ifndef OPENSSL_NO_NEXTPROTONEG
243 /* This the context that we pass to next_proto_cb */
244 typedef struct tlsextnextprotoctx_st {
248 } tlsextnextprotoctx;
250 static tlsextnextprotoctx next_proto;
252 static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
253 const unsigned char *in, unsigned int inlen,
256 tlsextnextprotoctx *ctx = arg;
259 /* We can assume that |in| is syntactically valid. */
261 BIO_printf(bio_c_out, "Protocols advertised by server: ");
262 for (i = 0; i < inlen;) {
264 BIO_write(bio_c_out, ", ", 2);
265 BIO_write(bio_c_out, &in[i + 1], in[i]);
268 BIO_write(bio_c_out, "\n", 1);
272 SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
273 return SSL_TLSEXT_ERR_OK;
275 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
277 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
278 const unsigned char *in, size_t inlen,
282 unsigned char ext_buf[4 + 65536];
284 /* Reconstruct the type/len fields prior to extension data */
285 inlen &= 0xffff; /* for formal memcmpy correctness */
286 ext_buf[0] = (unsigned char)(ext_type >> 8);
287 ext_buf[1] = (unsigned char)(ext_type);
288 ext_buf[2] = (unsigned char)(inlen >> 8);
289 ext_buf[3] = (unsigned char)(inlen);
290 memcpy(ext_buf + 4, in, inlen);
292 BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
294 PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
299 * Hex decoder that tolerates optional whitespace. Returns number of bytes
300 * produced, advances inptr to end of input string.
302 static ossl_ssize_t hexdecode(const char **inptr, void *result)
304 unsigned char **out = (unsigned char **)result;
305 const char *in = *inptr;
306 unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
307 unsigned char *cp = ret;
314 for (byte = 0; *in; ++in) {
317 if (isspace(_UC(*in)))
319 x = OPENSSL_hexchar2int(*in);
325 if ((nibble ^= 1) == 0) {
338 return cp - (*out = ret);
342 * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
343 * inptr to next field skipping leading whitespace.
345 static ossl_ssize_t checked_uint8(const char **inptr, void *out)
347 uint8_t *result = (uint8_t *)out;
348 const char *in = *inptr;
354 v = strtol(in, &endp, 10);
357 if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
358 endp == in || !isspace(_UC(*endp)) ||
359 v != (*result = (uint8_t) v)) {
362 for (in = endp; isspace(_UC(*in)); ++in)
372 ossl_ssize_t (*parser)(const char **, void *);
375 static int tlsa_import_rr(SSL *con, const char *rrdata)
377 /* Not necessary to re-init these values; the "parsers" do that. */
378 static uint8_t usage;
379 static uint8_t selector;
380 static uint8_t mtype;
381 static unsigned char *data;
382 static struct tlsa_field tlsa_fields[] = {
383 { &usage, "usage", checked_uint8 },
384 { &selector, "selector", checked_uint8 },
385 { &mtype, "mtype", checked_uint8 },
386 { &data, "data", hexdecode },
389 struct tlsa_field *f;
391 const char *cp = rrdata;
392 ossl_ssize_t len = 0;
394 for (f = tlsa_fields; f->var; ++f) {
395 /* Returns number of bytes produced, advances cp to next field */
396 if ((len = f->parser(&cp, f->var)) <= 0) {
397 BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
398 prog, f->name, rrdata);
402 /* The data field is last, so len is its length */
403 ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
407 ERR_print_errors(bio_err);
408 BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
413 ERR_print_errors(bio_err);
414 BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
421 static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
423 int num = sk_OPENSSL_STRING_num(rrset);
427 for (i = 0; i < num; ++i) {
428 char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
429 if (tlsa_import_rr(con, rrdata) > 0)
435 typedef enum OPTION_choice {
437 OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX,
438 OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT,
439 OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
440 OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
441 OPT_BRIEF, OPT_PREXIT, OPT_NO_INTERACTIVE, OPT_CRLF, OPT_QUIET, OPT_NBIO,
442 OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF,
443 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
444 OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
445 OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
446 OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS,
447 #ifndef OPENSSL_NO_SRP
448 OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER,
451 OPT_SSL3, OPT_SSL_CONFIG,
452 OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
453 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS,
454 OPT_CERT_CHAIN, OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN,
455 OPT_NEXTPROTONEG, OPT_ALPN,
456 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
457 OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE,
458 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
459 OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC,
460 OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST,
461 OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES,
462 OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE,
466 OPT_S_ENUM, OPT_IGNORE_UNEXPECTED_EOF,
467 OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_PROXY, OPT_PROXY_USER, OPT_PROXY_PASS,
468 OPT_DANE_TLSA_DOMAIN,
469 #ifndef OPENSSL_NO_CT
470 OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
472 OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME,
474 OPT_ENABLE_SERVER_RPK,
475 OPT_ENABLE_CLIENT_RPK,
478 OPT_R_ENUM, OPT_PROV_ENUM
481 const OPTIONS s_client_options[] = {
482 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [host:port]\n"},
484 OPT_SECTION("General"),
485 {"help", OPT_HELP, '-', "Display this summary"},
486 #ifndef OPENSSL_NO_ENGINE
487 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
488 {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
489 "Specify engine to be used for client certificate operations"},
491 {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified section for SSL_CTX configuration"},
492 #ifndef OPENSSL_NO_CT
493 {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
494 {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
495 {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
498 OPT_SECTION("Network"),
499 {"host", OPT_HOST, 's', "Use -connect instead"},
500 {"port", OPT_PORT, 'p', "Use -connect instead"},
501 {"connect", OPT_CONNECT, 's',
502 "TCP/IP where to connect; default: " PORT ")"},
503 {"bind", OPT_BIND, 's', "bind local address for connection"},
504 {"proxy", OPT_PROXY, 's',
505 "Connect to via specified proxy to the real server"},
506 {"proxy_user", OPT_PROXY_USER, 's', "UserID for proxy authentication"},
507 {"proxy_pass", OPT_PROXY_PASS, 's', "Proxy authentication password source"},
509 {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"},
511 {"4", OPT_4, '-', "Use IPv4 only"},
513 {"6", OPT_6, '-', "Use IPv6 only"},
515 {"maxfraglen", OPT_MAXFRAGLEN, 'p',
516 "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
517 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
518 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
519 "Size used to split data for encrypt pipelines"},
520 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
521 "Maximum number of encrypt/decrypt pipelines to be used"},
522 {"read_buf", OPT_READ_BUF, 'p',
523 "Default read buffer size to be used for connections"},
524 {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
526 OPT_SECTION("Identity"),
527 {"cert", OPT_CERT, '<', "Client certificate file to use"},
528 {"certform", OPT_CERTFORM, 'F',
529 "Client certificate file format (PEM/DER/P12); has no effect"},
530 {"cert_chain", OPT_CERT_CHAIN, '<',
531 "Client certificate chain file (in PEM format)"},
532 {"build_chain", OPT_BUILD_CHAIN, '-', "Build client certificate chain"},
533 {"key", OPT_KEY, 's', "Private key file to use; default: -cert file"},
534 {"keyform", OPT_KEYFORM, 'E', "Key format (ENGINE, other values ignored)"},
535 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
536 {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
537 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
538 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
539 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
540 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
541 {"no-CAfile", OPT_NOCAFILE, '-',
542 "Do not load the default certificates file"},
543 {"no-CApath", OPT_NOCAPATH, '-',
544 "Do not load certificates from the default certificates directory"},
545 {"no-CAstore", OPT_NOCASTORE, '-',
546 "Do not load certificates from the default certificates store"},
547 {"requestCAfile", OPT_REQCAFILE, '<',
548 "PEM format file of CA names to send to the server"},
549 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
550 {"tfo", OPT_TFO, '-', "Connect using TCP Fast Open"},
552 {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
553 {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
554 "DANE TLSA rrdata presentation form"},
555 {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
556 "Disable name checks when matching DANE-EE(3) TLSA records"},
557 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
558 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
559 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
560 {"name", OPT_PROTOHOST, 's',
561 "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
563 OPT_SECTION("Session"),
564 {"reconnect", OPT_RECONNECT, '-',
565 "Drop and re-make the connection with the same Session-ID"},
566 {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
567 {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
569 OPT_SECTION("Input/Output"),
570 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
571 {"quiet", OPT_QUIET, '-', "No s_client output"},
572 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
573 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
574 {"starttls", OPT_STARTTLS, 's',
575 "Use the appropriate STARTTLS command before starting TLS"},
576 {"xmpphost", OPT_XMPPHOST, 's',
577 "Alias of -name option for \"-starttls xmpp[-server]\""},
578 {"brief", OPT_BRIEF, '-',
579 "Restrict output to brief summary of connection parameters"},
580 {"prexit", OPT_PREXIT, '-',
581 "Print session information when the program exits"},
582 {"no-interactive", OPT_NO_INTERACTIVE, '-',
583 "Don't run the client in the interactive mode"},
585 OPT_SECTION("Debug"),
586 {"showcerts", OPT_SHOWCERTS, '-',
587 "Show all certificates sent by the server"},
588 {"debug", OPT_DEBUG, '-', "Extra output"},
589 {"msg", OPT_MSG, '-', "Show protocol messages"},
590 {"msgfile", OPT_MSGFILE, '>',
591 "File to send output of -msg or -trace, instead of stdout"},
592 {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
593 {"state", OPT_STATE, '-', "Print the ssl states"},
594 {"keymatexport", OPT_KEYMATEXPORT, 's',
595 "Export keying material using label"},
596 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
597 "Export len bytes of keying material; default 20"},
598 {"security_debug", OPT_SECURITY_DEBUG, '-',
599 "Enable security debug messages"},
600 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
601 "Output more security debug output"},
602 #ifndef OPENSSL_NO_SSL_TRACE
603 {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
606 {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
608 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
609 {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
610 {"servername", OPT_SERVERNAME, 's',
611 "Set TLS extension servername (SNI) in ClientHello (default)"},
612 {"noservername", OPT_NOSERVERNAME, '-',
613 "Do not send the server name (SNI) extension in the ClientHello"},
614 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
615 "Hex dump of all TLS extensions received"},
616 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
617 "Do not treat lack of close_notify from a peer as an error"},
618 #ifndef OPENSSL_NO_OCSP
619 {"status", OPT_STATUS, '-', "Request certificate status from server"},
621 {"serverinfo", OPT_SERVERINFO, 's',
622 "types Send empty ClientHello extensions (comma-separated numbers)"},
623 {"alpn", OPT_ALPN, 's',
624 "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
625 {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
626 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
628 OPT_SECTION("Protocol and version"),
629 #ifndef OPENSSL_NO_SSL3
630 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
632 #ifndef OPENSSL_NO_TLS1
633 {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
635 #ifndef OPENSSL_NO_TLS1_1
636 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
638 #ifndef OPENSSL_NO_TLS1_2
639 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
641 #ifndef OPENSSL_NO_TLS1_3
642 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
644 #ifndef OPENSSL_NO_DTLS
645 {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
646 {"timeout", OPT_TIMEOUT, '-',
647 "Enable send/receive timeout on DTLS connections"},
648 {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
650 #ifndef OPENSSL_NO_DTLS1
651 {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
653 #ifndef OPENSSL_NO_DTLS1_2
654 {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
656 #ifndef OPENSSL_NO_SCTP
657 {"sctp", OPT_SCTP, '-', "Use SCTP"},
658 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
660 #ifndef OPENSSL_NO_NEXTPROTONEG
661 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
662 "Enable NPN extension, considering named protocols supported (comma-separated list)"},
664 {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"},
665 {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"},
666 {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"},
667 {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"},
668 #ifndef OPENSSL_NO_SRTP
669 {"use_srtp", OPT_USE_SRTP, 's',
670 "Offer SRTP key management with a colon-separated profile list"},
672 #ifndef OPENSSL_NO_SRP
673 {"srpuser", OPT_SRPUSER, 's', "(deprecated) SRP authentication for 'user'"},
674 {"srppass", OPT_SRPPASS, 's', "(deprecated) Password for 'user'"},
675 {"srp_lateuser", OPT_SRP_LATEUSER, '-',
676 "(deprecated) SRP username into second ClientHello message"},
677 {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
678 "(deprecated) Tolerate other than the known g N values."},
679 {"srp_strength", OPT_SRP_STRENGTH, 'p',
680 "(deprecated) Minimal length in bits for N"},
682 #ifndef OPENSSL_NO_KTLS
683 {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"},
689 {"CRL", OPT_CRL, '<', "CRL file to use"},
690 {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
691 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER); default PEM"},
692 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
693 "Close connection on verification error"},
694 {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
695 {"chainCAfile", OPT_CHAINCAFILE, '<',
696 "CA file for certificate chain (PEM format)"},
697 {"chainCApath", OPT_CHAINCAPATH, '/',
698 "Use dir as certificate store path to build CA certificate chain"},
699 {"chainCAstore", OPT_CHAINCASTORE, ':',
700 "CA store URI for certificate chain"},
701 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
702 "CA file for certificate verification (PEM format)"},
703 {"verifyCApath", OPT_VERIFYCAPATH, '/',
704 "Use dir as certificate store path to verify CA certificate"},
705 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
706 "CA store URI for certificate verification"},
711 {"host:port", 0, 0, "Where to connect; same as -connect option"},
715 typedef enum PROTOCOL_choice {
733 static const OPT_PAIR services[] = {
734 {"smtp", PROTO_SMTP},
735 {"pop3", PROTO_POP3},
736 {"imap", PROTO_IMAP},
738 {"xmpp", PROTO_XMPP},
739 {"xmpp-server", PROTO_XMPP_SERVER},
740 {"telnet", PROTO_TELNET},
742 {"mysql", PROTO_MYSQL},
743 {"postgres", PROTO_POSTGRES},
744 {"lmtp", PROTO_LMTP},
745 {"nntp", PROTO_NNTP},
746 {"sieve", PROTO_SIEVE},
747 {"ldap", PROTO_LDAP},
751 #define IS_INET_FLAG(o) \
752 (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
753 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
755 #define IS_PROT_FLAG(o) \
756 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
757 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
759 /* Free |*dest| and optionally set it to a copy of |source|. */
760 static void freeandcopy(char **dest, const char *source)
765 *dest = OPENSSL_strdup(source);
768 static int new_session_cb(SSL *s, SSL_SESSION *sess)
771 if (sess_out != NULL) {
772 BIO *stmp = BIO_new_file(sess_out, "w");
775 BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
777 PEM_write_bio_SSL_SESSION(stmp, sess);
783 * Session data gets dumped on connection for TLSv1.2 and below, and on
784 * arrival of the NewSessionTicket for TLSv1.3.
786 if (SSL_version(s) == TLS1_3_VERSION) {
787 BIO_printf(bio_c_out,
788 "---\nPost-Handshake New Session Ticket arrived:\n");
789 SSL_SESSION_print(bio_c_out, sess);
790 BIO_printf(bio_c_out, "---\n");
794 * We always return a "fail" response so that the session gets freed again
795 * because we haven't used the reference.
800 int s_client_main(int argc, char **argv)
803 EVP_PKEY *key = NULL;
806 STACK_OF(X509) *chain = NULL;
808 X509_VERIFY_PARAM *vpm = NULL;
809 SSL_EXCERT *exc = NULL;
810 SSL_CONF_CTX *cctx = NULL;
811 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
812 char *dane_tlsa_domain = NULL;
813 STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
814 int dane_ee_no_name = 0;
815 STACK_OF(X509_CRL) *crls = NULL;
816 const SSL_METHOD *meth = TLS_client_method();
817 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
818 char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
819 char *proxystr = NULL, *proxyuser = NULL;
820 char *proxypassarg = NULL, *proxypass = NULL;
821 char *connectstr = NULL, *bindstr = NULL;
822 char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
823 char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL, *host = NULL;
824 char *thost = NULL, *tport = NULL;
826 char *bindhost = NULL, *bindport = NULL;
827 char *passarg = NULL, *pass = NULL;
828 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
829 char *ReqCAfile = NULL;
830 char *sess_in = NULL, *crl_file = NULL, *p;
831 const char *protohost = NULL;
832 struct timeval timeout, *timeoutp;
833 fd_set readfds, writefds;
834 int noCApath = 0, noCAfile = 0, noCAstore = 0;
835 int build_chain = 0, cbuf_len, cbuf_off, cert_format = FORMAT_UNDEF;
836 int key_format = FORMAT_UNDEF, crlf = 0, full_log = 1, mbuf_len = 0;
838 int nointeractive = 0;
840 int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
841 int ret = 1, in_init = 1, i, nbio_test = 0, sock = -1, k, width, state = 0;
842 int sbuf_len, sbuf_off, cmdletters = 1;
843 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
844 int starttls_proto = PROTO_OFF, crl_format = FORMAT_UNDEF, crl_download = 0;
845 int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
846 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
849 int read_buf_len = 0;
850 int fallback_scsv = 0;
852 #ifndef OPENSSL_NO_DTLS
853 int enable_timeouts = 0;
856 #ifndef OPENSSL_NO_ENGINE
857 ENGINE *ssl_client_engine = NULL;
860 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
863 const char *servername = NULL;
864 char *sname_alloc = NULL;
865 int noservername = 0;
866 const char *alpn_in = NULL;
867 tlsextctx tlsextcbp = { NULL, 0 };
868 const char *ssl_config = NULL;
869 #define MAX_SI_TYPES 100
870 unsigned short serverinfo_types[MAX_SI_TYPES];
871 int serverinfo_count = 0, start = 0, len;
872 #ifndef OPENSSL_NO_NEXTPROTONEG
873 const char *next_proto_neg_in = NULL;
875 #ifndef OPENSSL_NO_SRP
876 char *srppass = NULL;
877 int srp_lateuser = 0;
878 SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
880 #ifndef OPENSSL_NO_SRTP
881 char *srtp_profiles = NULL;
883 #ifndef OPENSSL_NO_CT
884 char *ctlog_file = NULL;
885 int ct_validation = 0;
887 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
889 unsigned int max_send_fragment = 0;
890 unsigned int split_send_fragment = 0, max_pipelines = 0;
891 enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
893 uint8_t maxfraglen = 0;
894 int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
895 int c_tlsextdebug = 0;
896 #ifndef OPENSSL_NO_OCSP
897 int c_status_req = 0;
899 BIO *bio_c_msg = NULL;
900 const char *keylog_file = NULL, *early_data_file = NULL;
901 #ifndef OPENSSL_NO_DTLS
904 char *psksessf = NULL;
906 int enable_client_rpk = 0;
907 #ifndef OPENSSL_NO_SCTP
908 int sctp_label_bug = 0;
910 int ignore_unexpected_eof = 0;
911 #ifndef OPENSSL_NO_KTLS
915 BIO_ADDR *tfo_addr = NULL;
919 /* Known false-positive of MemorySanitizer. */
920 #if defined(__has_feature)
921 # if __has_feature(memory_sanitizer)
922 __msan_unpoison(&readfds, sizeof(readfds));
923 __msan_unpoison(&writefds, sizeof(writefds));
931 port = OPENSSL_strdup(PORT);
932 vpm = X509_VERIFY_PARAM_new();
933 cctx = SSL_CONF_CTX_new();
935 if (port == NULL || vpm == NULL || cctx == NULL) {
936 BIO_printf(bio_err, "%s: out of memory\n", opt_getprog());
940 cbuf = app_malloc(BUFSIZZ, "cbuf");
941 sbuf = app_malloc(BUFSIZZ, "sbuf");
942 mbuf = app_malloc(BUFSIZZ, "mbuf");
944 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
946 prog = opt_init(argc, argv, s_client_options);
947 while ((o = opt_next()) != OPT_EOF) {
948 /* Check for intermixing flags. */
949 if (connect_type == use_unix && IS_INET_FLAG(o)) {
951 "%s: Intermixed protocol flags (unix and internet domains)\n",
955 if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
957 "%s: Intermixed protocol flags (internet and unix domains)\n",
962 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
963 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
966 if (IS_NO_PROT_FLAG(o))
968 if (prot_opt == 1 && no_prot_opt) {
970 "Cannot supply both a protocol flag and '-no_<prot>'\n");
978 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
981 opt_help(s_client_options);
985 connect_type = use_inet;
986 socket_family = AF_INET;
991 connect_type = use_inet;
992 socket_family = AF_INET6;
997 connect_type = use_inet;
998 freeandcopy(&host, opt_arg());
1001 connect_type = use_inet;
1002 freeandcopy(&port, opt_arg());
1005 connect_type = use_inet;
1006 freeandcopy(&connectstr, opt_arg());
1009 freeandcopy(&bindstr, opt_arg());
1012 proxystr = opt_arg();
1014 case OPT_PROXY_USER:
1015 proxyuser = opt_arg();
1017 case OPT_PROXY_PASS:
1018 proxypassarg = opt_arg();
1022 connect_type = use_unix;
1023 socket_family = AF_UNIX;
1024 freeandcopy(&host, opt_arg());
1028 /* fall through, since this is an alias */
1030 protohost = opt_arg();
1033 verify = SSL_VERIFY_PEER;
1034 verify_args.depth = atoi(opt_arg());
1036 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1039 cert_file = opt_arg();
1042 if (!set_nameopt(opt_arg()))
1046 crl_file = opt_arg();
1048 case OPT_CRL_DOWNLOAD:
1052 sess_out = opt_arg();
1055 sess_in = opt_arg();
1058 if (!opt_format(opt_arg(), OPT_FMT_ANY, &cert_format))
1062 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1065 case OPT_VERIFY_RET_ERROR:
1066 verify = SSL_VERIFY_PEER;
1067 verify_args.return_error = 1;
1069 case OPT_VERIFY_QUIET:
1070 verify_args.quiet = 1;
1073 c_brief = verify_args.quiet = c_quiet = 1;
1076 if (ssl_args == NULL)
1077 ssl_args = sk_OPENSSL_STRING_new_null();
1078 if (ssl_args == NULL
1079 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1080 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1081 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1086 if (!opt_verify(o, vpm))
1091 if (!args_excert(o, &exc))
1094 case OPT_IGNORE_UNEXPECTED_EOF:
1095 ignore_unexpected_eof = 1;
1100 case OPT_NO_INTERACTIVE:
1107 c_quiet = c_ign_eof = 1;
1116 e = setup_engine(opt_arg(), 1);
1118 case OPT_SSL_CLIENT_ENGINE:
1119 #ifndef OPENSSL_NO_ENGINE
1120 ssl_client_engine = setup_engine(opt_arg(), 0);
1121 if (ssl_client_engine == NULL) {
1122 BIO_printf(bio_err, "Error getting client auth engine\n");
1131 case OPT_PROV_CASES:
1132 if (!opt_provider(o))
1138 case OPT_NO_IGN_EOF:
1144 case OPT_TLSEXTDEBUG:
1148 #ifndef OPENSSL_NO_OCSP
1161 bio_c_msg = BIO_new_file(opt_arg(), "w");
1162 if (bio_c_msg == NULL) {
1163 BIO_printf(bio_err, "Error writing file %s\n", opt_arg());
1168 #ifndef OPENSSL_NO_SSL_TRACE
1172 case OPT_SECURITY_DEBUG:
1175 case OPT_SECURITY_DEBUG_VERBOSE:
1187 case OPT_PSK_IDENTITY:
1188 psk_identity = opt_arg();
1191 for (p = psk_key = opt_arg(); *p; p++) {
1192 if (isxdigit(_UC(*p)))
1194 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1199 psksessf = opt_arg();
1201 #ifndef OPENSSL_NO_SRP
1203 srp_arg.srplogin = opt_arg();
1204 if (min_version < TLS1_VERSION)
1205 min_version = TLS1_VERSION;
1208 srppass = opt_arg();
1209 if (min_version < TLS1_VERSION)
1210 min_version = TLS1_VERSION;
1212 case OPT_SRP_STRENGTH:
1213 srp_arg.strength = atoi(opt_arg());
1214 BIO_printf(bio_err, "SRP minimal length for N is %d\n",
1216 if (min_version < TLS1_VERSION)
1217 min_version = TLS1_VERSION;
1219 case OPT_SRP_LATEUSER:
1221 if (min_version < TLS1_VERSION)
1222 min_version = TLS1_VERSION;
1224 case OPT_SRP_MOREGROUPS:
1226 if (min_version < TLS1_VERSION)
1227 min_version = TLS1_VERSION;
1230 case OPT_SSL_CONFIG:
1231 ssl_config = opt_arg();
1234 min_version = SSL3_VERSION;
1235 max_version = SSL3_VERSION;
1236 socket_type = SOCK_STREAM;
1237 #ifndef OPENSSL_NO_DTLS
1242 min_version = TLS1_3_VERSION;
1243 max_version = TLS1_3_VERSION;
1244 socket_type = SOCK_STREAM;
1245 #ifndef OPENSSL_NO_DTLS
1250 min_version = TLS1_2_VERSION;
1251 max_version = TLS1_2_VERSION;
1252 socket_type = SOCK_STREAM;
1253 #ifndef OPENSSL_NO_DTLS
1258 min_version = TLS1_1_VERSION;
1259 max_version = TLS1_1_VERSION;
1260 socket_type = SOCK_STREAM;
1261 #ifndef OPENSSL_NO_DTLS
1266 min_version = TLS1_VERSION;
1267 max_version = TLS1_VERSION;
1268 socket_type = SOCK_STREAM;
1269 #ifndef OPENSSL_NO_DTLS
1274 #ifndef OPENSSL_NO_DTLS
1275 meth = DTLS_client_method();
1276 socket_type = SOCK_DGRAM;
1281 #ifndef OPENSSL_NO_DTLS1
1282 meth = DTLS_client_method();
1283 min_version = DTLS1_VERSION;
1284 max_version = DTLS1_VERSION;
1285 socket_type = SOCK_DGRAM;
1290 #ifndef OPENSSL_NO_DTLS1_2
1291 meth = DTLS_client_method();
1292 min_version = DTLS1_2_VERSION;
1293 max_version = DTLS1_2_VERSION;
1294 socket_type = SOCK_DGRAM;
1299 #ifndef OPENSSL_NO_SCTP
1300 protocol = IPPROTO_SCTP;
1303 case OPT_SCTP_LABEL_BUG:
1304 #ifndef OPENSSL_NO_SCTP
1309 #ifndef OPENSSL_NO_DTLS
1310 enable_timeouts = 1;
1314 #ifndef OPENSSL_NO_DTLS
1315 socket_mtu = atol(opt_arg());
1318 case OPT_FALLBACKSCSV:
1322 if (!opt_format(opt_arg(), OPT_FMT_ANY, &key_format))
1326 passarg = opt_arg();
1328 case OPT_CERT_CHAIN:
1329 chain_file = opt_arg();
1332 key_file = opt_arg();
1343 case OPT_CHAINCAPATH:
1344 chCApath = opt_arg();
1346 case OPT_VERIFYCAPATH:
1347 vfyCApath = opt_arg();
1349 case OPT_BUILD_CHAIN:
1353 ReqCAfile = opt_arg();
1361 #ifndef OPENSSL_NO_CT
1368 case OPT_CTLOG_FILE:
1369 ctlog_file = opt_arg();
1372 case OPT_CHAINCAFILE:
1373 chCAfile = opt_arg();
1375 case OPT_VERIFYCAFILE:
1376 vfyCAfile = opt_arg();
1379 CAstore = opt_arg();
1384 case OPT_CHAINCASTORE:
1385 chCAstore = opt_arg();
1387 case OPT_VERIFYCASTORE:
1388 vfyCAstore = opt_arg();
1390 case OPT_DANE_TLSA_DOMAIN:
1391 dane_tlsa_domain = opt_arg();
1393 case OPT_DANE_TLSA_RRDATA:
1394 if (dane_tlsa_rrset == NULL)
1395 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1396 if (dane_tlsa_rrset == NULL ||
1397 !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1398 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1402 case OPT_DANE_EE_NO_NAME:
1403 dane_ee_no_name = 1;
1405 case OPT_NEXTPROTONEG:
1406 #ifndef OPENSSL_NO_NEXTPROTONEG
1407 next_proto_neg_in = opt_arg();
1411 alpn_in = opt_arg();
1413 case OPT_SERVERINFO:
1416 for (start = 0, i = 0; i <= len; ++i) {
1417 if (i == len || p[i] == ',') {
1418 serverinfo_types[serverinfo_count] = atoi(p + start);
1419 if (++serverinfo_count == MAX_SI_TYPES)
1426 if (!opt_pair(opt_arg(), services, &starttls_proto))
1432 case OPT_SERVERNAME:
1433 servername = opt_arg();
1435 case OPT_NOSERVERNAME:
1439 #ifndef OPENSSL_NO_SRTP
1440 srtp_profiles = opt_arg();
1443 case OPT_KEYMATEXPORT:
1444 keymatexportlabel = opt_arg();
1446 case OPT_KEYMATEXPORTLEN:
1447 keymatexportlen = atoi(opt_arg());
1452 case OPT_MAXFRAGLEN:
1453 len = atoi(opt_arg());
1456 maxfraglen = TLSEXT_max_fragment_length_512;
1459 maxfraglen = TLSEXT_max_fragment_length_1024;
1462 maxfraglen = TLSEXT_max_fragment_length_2048;
1465 maxfraglen = TLSEXT_max_fragment_length_4096;
1469 "%s: Max Fragment Len %u is out of permitted values",
1474 case OPT_MAX_SEND_FRAG:
1475 max_send_fragment = atoi(opt_arg());
1477 case OPT_SPLIT_SEND_FRAG:
1478 split_send_fragment = atoi(opt_arg());
1480 case OPT_MAX_PIPELINES:
1481 max_pipelines = atoi(opt_arg());
1484 read_buf_len = atoi(opt_arg());
1486 case OPT_KEYLOG_FILE:
1487 keylog_file = opt_arg();
1489 case OPT_EARLY_DATA:
1490 early_data_file = opt_arg();
1492 case OPT_ENABLE_PHA:
1496 #ifndef OPENSSL_NO_KTLS
1500 case OPT_ENABLE_SERVER_RPK:
1501 enable_server_rpk = 1;
1503 case OPT_ENABLE_CLIENT_RPK:
1504 enable_client_rpk = 1;
1509 /* Optional argument is connect string if -connect not used. */
1510 if (opt_num_rest() == 1) {
1511 /* Don't allow -connect and a separate argument. */
1512 if (connectstr != NULL) {
1514 "%s: cannot provide both -connect option and target parameter\n",
1518 connect_type = use_inet;
1519 freeandcopy(&connectstr, *opt_rest());
1520 } else if (!opt_check_rest_arg(NULL)) {
1523 if (!app_RAND_load())
1526 if (count4or6 >= 2) {
1527 BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1531 if (servername != NULL) {
1533 "%s: Can't use -servername and -noservername together\n",
1537 if (dane_tlsa_domain != NULL) {
1539 "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1545 #ifndef OPENSSL_NO_NEXTPROTONEG
1546 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1547 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1552 if (connectstr != NULL) {
1554 char *tmp_host = host, *tmp_port = port;
1556 res = BIO_parse_hostserv(connectstr, &host, &port, BIO_PARSE_PRIO_HOST);
1557 if (tmp_host != host)
1558 OPENSSL_free(tmp_host);
1559 if (tmp_port != port)
1560 OPENSSL_free(tmp_port);
1563 "%s: -connect argument or target parameter malformed or ambiguous\n",
1569 if (proxystr != NULL) {
1571 char *tmp_host = host, *tmp_port = port;
1573 if (host == NULL || port == NULL) {
1574 BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
1578 if (servername == NULL && !noservername) {
1579 servername = sname_alloc = OPENSSL_strdup(host);
1580 if (sname_alloc == NULL) {
1581 BIO_printf(bio_err, "%s: out of memory\n", prog);
1586 /* Retain the original target host:port for use in the HTTP proxy connect string */
1587 thost = OPENSSL_strdup(host);
1588 tport = OPENSSL_strdup(port);
1589 if (thost == NULL || tport == NULL) {
1590 BIO_printf(bio_err, "%s: out of memory\n", prog);
1594 res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1595 if (tmp_host != host)
1596 OPENSSL_free(tmp_host);
1597 if (tmp_port != port)
1598 OPENSSL_free(tmp_port);
1601 "%s: -proxy argument malformed or ambiguous\n", prog);
1606 if (bindstr != NULL) {
1608 res = BIO_parse_hostserv(bindstr, &bindhost, &bindport,
1609 BIO_PARSE_PRIO_HOST);
1612 "%s: -bind argument parameter malformed or ambiguous\n",
1619 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1621 "Can't use unix sockets and datagrams together\n");
1626 #ifndef OPENSSL_NO_SCTP
1627 if (protocol == IPPROTO_SCTP) {
1628 if (socket_type != SOCK_DGRAM) {
1629 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1632 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1633 socket_type = SOCK_STREAM;
1637 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1638 next_proto.status = -1;
1639 if (next_proto_neg_in) {
1641 next_protos_parse(&next_proto.len, next_proto_neg_in);
1642 if (next_proto.data == NULL) {
1643 BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1647 next_proto.data = NULL;
1650 if (!app_passwd(passarg, NULL, &pass, NULL)) {
1651 BIO_printf(bio_err, "Error getting private key password\n");
1655 if (!app_passwd(proxypassarg, NULL, &proxypass, NULL)) {
1656 BIO_printf(bio_err, "Error getting proxy password\n");
1660 if (proxypass != NULL && proxyuser == NULL) {
1661 BIO_printf(bio_err, "Error: Must specify proxy_user with proxy_pass\n");
1665 if (key_file == NULL)
1666 key_file = cert_file;
1668 if (key_file != NULL) {
1669 key = load_key(key_file, key_format, 0, pass, e,
1670 "client certificate private key");
1675 if (cert_file != NULL) {
1676 cert = load_cert_pass(cert_file, cert_format, 1, pass,
1677 "client certificate");
1682 if (chain_file != NULL) {
1683 if (!load_certs(chain_file, 0, &chain, pass, "client certificate chain"))
1687 if (crl_file != NULL) {
1689 crl = load_crl(crl_file, crl_format, 0, "CRL");
1692 crls = sk_X509_CRL_new_null();
1693 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1694 BIO_puts(bio_err, "Error adding CRL\n");
1695 ERR_print_errors(bio_err);
1701 if (!load_excert(&exc))
1704 if (bio_c_out == NULL) {
1705 if (c_quiet && !c_debug) {
1706 bio_c_out = BIO_new(BIO_s_null());
1707 if (c_msg && bio_c_msg == NULL) {
1708 bio_c_msg = dup_bio_out(FORMAT_TEXT);
1709 if (bio_c_msg == NULL) {
1710 BIO_printf(bio_err, "Out of memory\n");
1715 bio_c_out = dup_bio_out(FORMAT_TEXT);
1718 if (bio_c_out == NULL) {
1719 BIO_printf(bio_err, "Unable to create BIO\n");
1723 #ifndef OPENSSL_NO_SRP
1724 if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1725 BIO_printf(bio_err, "Error getting password\n");
1730 ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1732 ERR_print_errors(bio_err);
1736 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1739 ssl_ctx_security_debug(ctx, sdebug);
1741 if (!config_ctx(cctx, ssl_args, ctx))
1744 if (ssl_config != NULL) {
1745 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1746 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1748 ERR_print_errors(bio_err);
1753 #ifndef OPENSSL_NO_SCTP
1754 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1755 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1758 if (min_version != 0
1759 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1761 if (max_version != 0
1762 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1765 if (ignore_unexpected_eof)
1766 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1767 #ifndef OPENSSL_NO_KTLS
1769 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
1772 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1773 BIO_printf(bio_err, "Error setting verify params\n");
1774 ERR_print_errors(bio_err);
1779 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1782 if (max_send_fragment > 0
1783 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1784 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1785 prog, max_send_fragment);
1789 if (split_send_fragment > 0
1790 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1791 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1792 prog, split_send_fragment);
1796 if (max_pipelines > 0
1797 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1798 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1799 prog, max_pipelines);
1803 if (read_buf_len > 0) {
1804 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1808 && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
1810 "%s: Max Fragment Length code %u is out of permitted values"
1811 "\n", prog, maxfraglen);
1815 if (!ssl_load_stores(ctx,
1816 vfyCApath, vfyCAfile, vfyCAstore,
1817 chCApath, chCAfile, chCAstore,
1818 crls, crl_download)) {
1819 BIO_printf(bio_err, "Error loading store locations\n");
1820 ERR_print_errors(bio_err);
1823 if (ReqCAfile != NULL) {
1824 STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
1826 if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
1827 sk_X509_NAME_pop_free(nm, X509_NAME_free);
1828 BIO_printf(bio_err, "Error loading CA names\n");
1829 ERR_print_errors(bio_err);
1832 SSL_CTX_set0_CA_list(ctx, nm);
1834 #ifndef OPENSSL_NO_ENGINE
1835 if (ssl_client_engine) {
1836 if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1837 BIO_puts(bio_err, "Error setting client auth engine\n");
1838 ERR_print_errors(bio_err);
1839 release_engine(ssl_client_engine);
1842 release_engine(ssl_client_engine);
1846 #ifndef OPENSSL_NO_PSK
1847 if (psk_key != NULL) {
1849 BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1850 SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1853 if (psksessf != NULL) {
1854 BIO *stmp = BIO_new_file(psksessf, "r");
1857 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
1858 ERR_print_errors(bio_err);
1861 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1863 if (psksess == NULL) {
1864 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
1865 ERR_print_errors(bio_err);
1869 if (psk_key != NULL || psksess != NULL)
1870 SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
1872 #ifndef OPENSSL_NO_SRTP
1873 if (srtp_profiles != NULL) {
1874 /* Returns 0 on success! */
1875 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1876 BIO_printf(bio_err, "Error setting SRTP profile\n");
1877 ERR_print_errors(bio_err);
1884 ssl_ctx_set_excert(ctx, exc);
1886 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1887 if (next_proto.data != NULL)
1888 SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1892 unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1895 BIO_printf(bio_err, "Error parsing -alpn argument\n");
1898 /* Returns 0 on success! */
1899 if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1900 BIO_printf(bio_err, "Error setting ALPN\n");
1906 for (i = 0; i < serverinfo_count; i++) {
1907 if (!SSL_CTX_add_client_custom_ext(ctx,
1908 serverinfo_types[i],
1910 serverinfo_cli_parse_cb, NULL)) {
1912 "Warning: Unable to add custom extension %u, skipping\n",
1913 serverinfo_types[i]);
1918 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1920 #ifndef OPENSSL_NO_CT
1921 /* Enable SCT processing, without early connection termination */
1922 if (ct_validation &&
1923 !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
1924 ERR_print_errors(bio_err);
1928 if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
1929 if (ct_validation) {
1930 ERR_print_errors(bio_err);
1935 * If CT validation is not enabled, the log list isn't needed so don't
1936 * show errors or abort. We try to load it regardless because then we
1937 * can show the names of the logs any SCTs came from (SCTs may be seen
1938 * even with validation disabled).
1944 SSL_CTX_set_verify(ctx, verify, verify_callback);
1946 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1947 CAstore, noCAstore)) {
1948 ERR_print_errors(bio_err);
1952 ssl_ctx_add_crls(ctx, crls, crl_download);
1954 if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
1957 if (!noservername) {
1958 tlsextcbp.biodebug = bio_err;
1959 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1960 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1962 #ifndef OPENSSL_NO_SRP
1963 if (srp_arg.srplogin != NULL
1964 && !set_up_srp_arg(ctx, &srp_arg, srp_lateuser, c_msg, c_debug))
1968 if (dane_tlsa_domain != NULL) {
1969 if (SSL_CTX_dane_enable(ctx) <= 0) {
1971 "%s: Error enabling DANE TLSA authentication.\n",
1973 ERR_print_errors(bio_err);
1979 * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
1980 * come at any time. Therefore, we use a callback to write out the session
1981 * when we know about it. This approach works for < TLSv1.3 as well.
1983 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT
1984 | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1985 SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
1987 if (set_keylog_file(ctx, keylog_file))
1995 SSL_set_post_handshake_auth(con, 1);
1997 if (enable_client_rpk)
1998 if (!SSL_set1_client_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
1999 BIO_printf(bio_err, "Error setting client certificate types\n");
2002 if (enable_server_rpk) {
2003 if (!SSL_set1_server_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
2004 BIO_printf(bio_err, "Error setting server certificate types\n");
2009 if (sess_in != NULL) {
2011 BIO *stmp = BIO_new_file(sess_in, "r");
2013 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2014 ERR_print_errors(bio_err);
2017 sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2020 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2021 ERR_print_errors(bio_err);
2024 if (!SSL_set_session(con, sess)) {
2025 BIO_printf(bio_err, "Can't set session\n");
2026 ERR_print_errors(bio_err);
2030 SSL_SESSION_free(sess);
2034 SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
2036 if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
2037 if (servername == NULL) {
2038 if (host == NULL || is_dNS_name(host))
2039 servername = (host == NULL) ? "localhost" : host;
2041 if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) {
2042 BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
2043 ERR_print_errors(bio_err);
2048 if (dane_tlsa_domain != NULL) {
2049 if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
2050 BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
2051 "authentication.\n", prog);
2052 ERR_print_errors(bio_err);
2055 if (dane_tlsa_rrset == NULL) {
2056 BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
2057 "least one -dane_tlsa_rrdata option.\n", prog);
2060 if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
2061 BIO_printf(bio_err, "%s: Failed to import any TLSA "
2062 "records.\n", prog);
2065 if (dane_ee_no_name)
2066 SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
2067 } else if (dane_tlsa_rrset != NULL) {
2068 BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
2069 "-dane_tlsa_domain option.\n", prog);
2072 #ifndef OPENSSL_NO_DTLS
2073 if (isdtls && tfo) {
2074 BIO_printf(bio_err, "%s: DTLS does not support the -tfo option\n", prog);
2080 BIO_printf(bio_c_out, "Connecting via TFO\n");
2082 if (init_client(&sock, host, port, bindhost, bindport, socket_family,
2083 socket_type, protocol, tfo, &tfo_addr) == 0) {
2084 BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
2085 BIO_closesocket(sock);
2088 BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock);
2091 if (!BIO_socket_nbio(sock, 1)) {
2092 ERR_print_errors(bio_err);
2095 BIO_printf(bio_c_out, "Turned on non blocking io\n");
2097 #ifndef OPENSSL_NO_DTLS
2099 union BIO_sock_info_u peer_info;
2101 #ifndef OPENSSL_NO_SCTP
2102 if (protocol == IPPROTO_SCTP)
2103 sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
2106 sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
2108 if (sbio == NULL || (peer_info.addr = BIO_ADDR_new()) == NULL) {
2109 BIO_printf(bio_err, "memory allocation failure\n");
2111 BIO_closesocket(sock);
2114 if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
2115 BIO_printf(bio_err, "getsockname:errno=%d\n",
2116 get_last_socket_error());
2118 BIO_ADDR_free(peer_info.addr);
2119 BIO_closesocket(sock);
2123 (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
2124 BIO_ADDR_free(peer_info.addr);
2125 peer_info.addr = NULL;
2127 if (enable_timeouts) {
2129 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2130 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2133 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2134 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2138 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2139 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2140 DTLS_get_link_min_mtu(con));
2144 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2145 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2146 BIO_printf(bio_err, "Failed to set MTU\n");
2151 /* want to do MTU discovery */
2152 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2155 #endif /* OPENSSL_NO_DTLS */
2156 sbio = BIO_new_socket(sock, BIO_NOCLOSE);
2159 BIO_printf(bio_err, "Unable to create BIO\n");
2160 ERR_print_errors(bio_err);
2161 BIO_closesocket(sock);
2165 /* Now that we're using a BIO... */
2166 if (tfo_addr != NULL)
2167 (void)BIO_set_conn_address(sbio, tfo_addr);
2169 (void)BIO_set_tfo(sbio, 1);
2174 test = BIO_new(BIO_f_nbio_test());
2176 BIO_printf(bio_err, "Unable to create BIO\n");
2180 sbio = BIO_push(test, sbio);
2184 BIO_set_callback_ex(sbio, bio_dump_callback);
2185 BIO_set_callback_arg(sbio, (char *)bio_c_out);
2188 #ifndef OPENSSL_NO_SSL_TRACE
2190 SSL_set_msg_callback(con, SSL_trace);
2193 SSL_set_msg_callback(con, msg_cb);
2194 SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
2197 if (c_tlsextdebug) {
2198 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2199 SSL_set_tlsext_debug_arg(con, bio_c_out);
2201 #ifndef OPENSSL_NO_OCSP
2203 SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
2204 SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
2205 SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
2209 SSL_set_bio(con, sbio, sbio);
2210 SSL_set_connect_state(con);
2212 /* ok, lets connect */
2213 if (fileno_stdin() > SSL_get_fd(con))
2214 width = fileno_stdin() + 1;
2216 width = SSL_get_fd(con) + 1;
2229 if (proxystr != NULL) {
2230 /* Here we must use the connect string target host & port */
2231 if (!OSSL_HTTP_proxy_connect(sbio, thost, tport, proxyuser, proxypass,
2232 0 /* no timeout */, bio_err, prog))
2236 switch ((PROTOCOL_CHOICE) starttls_proto) {
2243 * This is an ugly hack that does a lot of assumptions. We do
2244 * have to handle multi-line responses which may come in a single
2245 * packet or not. We therefore have to use BIO_gets() which does
2246 * need a buffering BIO. So during the initial chitchat we do
2247 * push a buffering BIO into the chain that is removed again
2248 * later on to not disturb the rest of the s_client operation.
2251 BIO *fbio = BIO_new(BIO_f_buffer());
2254 BIO_printf(bio_err, "Unable to create BIO\n");
2257 BIO_push(fbio, sbio);
2258 /* Wait for multi-line response to end from LMTP or SMTP */
2260 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2261 } while (mbuf_len > 3 && mbuf[3] == '-');
2262 if (protohost == NULL)
2263 protohost = "mail.example.com";
2264 if (starttls_proto == (int)PROTO_LMTP)
2265 BIO_printf(fbio, "LHLO %s\r\n", protohost);
2267 BIO_printf(fbio, "EHLO %s\r\n", protohost);
2268 (void)BIO_flush(fbio);
2270 * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2274 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2275 if (strstr(mbuf, "STARTTLS"))
2277 } while (mbuf_len > 3 && mbuf[3] == '-');
2278 (void)BIO_flush(fbio);
2283 "Didn't find STARTTLS in server response,"
2284 " trying anyway...\n");
2285 BIO_printf(sbio, "STARTTLS\r\n");
2286 BIO_read(sbio, sbuf, BUFSIZZ);
2291 BIO_read(sbio, mbuf, BUFSIZZ);
2292 BIO_printf(sbio, "STLS\r\n");
2293 mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
2295 BIO_printf(bio_err, "BIO_read failed\n");
2303 BIO *fbio = BIO_new(BIO_f_buffer());
2306 BIO_printf(bio_err, "Unable to create BIO\n");
2309 BIO_push(fbio, sbio);
2310 BIO_gets(fbio, mbuf, BUFSIZZ);
2311 /* STARTTLS command requires CAPABILITY... */
2312 BIO_printf(fbio, ". CAPABILITY\r\n");
2313 (void)BIO_flush(fbio);
2314 /* wait for multi-line CAPABILITY response */
2316 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2317 if (strstr(mbuf, "STARTTLS"))
2320 while (mbuf_len > 3 && mbuf[0] != '.');
2321 (void)BIO_flush(fbio);
2326 "Didn't find STARTTLS in server response,"
2327 " trying anyway...\n");
2328 BIO_printf(sbio, ". STARTTLS\r\n");
2329 BIO_read(sbio, sbuf, BUFSIZZ);
2334 BIO *fbio = BIO_new(BIO_f_buffer());
2337 BIO_printf(bio_err, "Unable to create BIO\n");
2340 BIO_push(fbio, sbio);
2341 /* wait for multi-line response to end from FTP */
2343 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2345 while (mbuf_len > 3 && (!isdigit(mbuf[0]) || !isdigit(mbuf[1]) || !isdigit(mbuf[2]) || mbuf[3] != ' '));
2346 (void)BIO_flush(fbio);
2349 BIO_printf(sbio, "AUTH TLS\r\n");
2350 BIO_read(sbio, sbuf, BUFSIZZ);
2354 case PROTO_XMPP_SERVER:
2357 BIO_printf(sbio, "<stream:stream "
2358 "xmlns:stream='http://etherx.jabber.org/streams' "
2359 "xmlns='jabber:%s' to='%s' version='1.0'>",
2360 starttls_proto == PROTO_XMPP ? "client" : "server",
2361 protohost ? protohost : host);
2362 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2364 BIO_printf(bio_err, "BIO_read failed\n");
2369 (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2371 "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2373 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2381 "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2382 seen = BIO_read(sbio, sbuf, BUFSIZZ);
2384 BIO_printf(bio_err, "BIO_read failed\n");
2388 if (!strstr(sbuf, "<proceed"))
2395 static const unsigned char tls_do[] = {
2396 /* IAC DO START_TLS */
2399 static const unsigned char tls_will[] = {
2400 /* IAC WILL START_TLS */
2403 static const unsigned char tls_follows[] = {
2404 /* IAC SB START_TLS FOLLOWS IAC SE */
2405 255, 250, 46, 1, 255, 240
2409 /* Telnet server should demand we issue START_TLS */
2410 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2411 if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
2413 /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2414 BIO_write(sbio, tls_will, 3);
2415 BIO_write(sbio, tls_follows, 6);
2416 (void)BIO_flush(sbio);
2417 /* Telnet server also sent the FOLLOWS sub-command */
2418 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2419 if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2426 BIO *fbio = BIO_new(BIO_f_buffer());
2429 BIO_printf(bio_err, "Unable to create BIO\n");
2432 BIO_push(fbio, sbio);
2433 BIO_printf(fbio, "STARTTLS\r\n");
2434 (void)BIO_flush(fbio);
2435 width = SSL_get_fd(con) + 1;
2441 openssl_fdset(SSL_get_fd(con), &readfds);
2442 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2443 timeout.tv_usec = 0;
2445 * If the IRCd doesn't respond within
2446 * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2447 * it doesn't support STARTTLS. Many IRCds
2448 * will not give _any_ sort of response to a
2449 * STARTTLS command when it's not supported.
2451 if (!BIO_get_buffer_num_lines(fbio)
2452 && !BIO_pending(fbio)
2453 && !BIO_pending(sbio)
2454 && select(width, (void *)&readfds, NULL, NULL,
2457 "Timeout waiting for response (%d seconds).\n",
2458 S_CLIENT_IRC_READ_TIMEOUT);
2462 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2463 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2465 /* :example.net 451 STARTTLS :You have not registered */
2466 /* :example.net 421 STARTTLS :Unknown command */
2467 if ((numeric == 451 || numeric == 421)
2468 && strstr(mbuf, "STARTTLS") != NULL) {
2469 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2472 if (numeric == 691) {
2473 BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2474 ERR_print_errors(bio_err);
2477 } while (numeric != 670);
2479 (void)BIO_flush(fbio);
2482 if (numeric != 670) {
2483 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2491 /* SSL request packet */
2492 static const unsigned char ssl_req[] = {
2493 /* payload_length, sequence_id */
2494 0x20, 0x00, 0x00, 0x01,
2496 /* capability flags, CLIENT_SSL always set */
2497 0x85, 0xae, 0x7f, 0x00,
2498 /* max-packet size */
2499 0x00, 0x00, 0x00, 0x01,
2502 /* string[23] reserved (all [0]) */
2503 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2504 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2505 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2508 int ssl_flg = 0x800;
2510 const unsigned char *packet = (const unsigned char *)sbuf;
2512 /* Receiving Initial Handshake packet. */
2513 bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
2515 BIO_printf(bio_err, "BIO_read failed\n");
2517 /* Packet length[3], Packet number[1] + minimum payload[17] */
2518 } else if (bytes < 21) {
2519 BIO_printf(bio_err, "MySQL packet too short.\n");
2521 } else if (bytes != (4 + packet[0] +
2523 (packet[2] << 16))) {
2524 BIO_printf(bio_err, "MySQL packet length does not match.\n");
2526 /* protocol version[1] */
2527 } else if (packet[4] != 0xA) {
2529 "Only MySQL protocol version 10 is supported.\n");
2534 /* server version[string+NULL] */
2537 BIO_printf(bio_err, "Cannot confirm server version. ");
2539 } else if (packet[pos++] == '\0') {
2544 /* make sure we have at least 15 bytes left in the packet */
2545 if (pos + 15 > bytes) {
2547 "MySQL server handshake packet is broken.\n");
2551 pos += 12; /* skip over conn id[4] + SALT[8] */
2552 if (packet[pos++] != '\0') { /* verify filler */
2554 "MySQL packet is broken.\n");
2558 /* capability flags[2] */
2559 if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
2560 BIO_printf(bio_err, "MySQL server does not support SSL.\n");
2564 /* Sending SSL Handshake packet. */
2565 BIO_write(sbio, ssl_req, sizeof(ssl_req));
2566 (void)BIO_flush(sbio);
2569 case PROTO_POSTGRES:
2571 static const unsigned char ssl_request[] = {
2572 /* Length SSLRequest */
2573 0, 0, 0, 8, 4, 210, 22, 47
2577 /* Send SSLRequest packet */
2578 BIO_write(sbio, ssl_request, 8);
2579 (void)BIO_flush(sbio);
2581 /* Reply will be a single S if SSL is enabled */
2582 bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2583 if (bytes != 1 || sbuf[0] != 'S')
2590 BIO *fbio = BIO_new(BIO_f_buffer());
2593 BIO_printf(bio_err, "Unable to create BIO\n");
2596 BIO_push(fbio, sbio);
2597 BIO_gets(fbio, mbuf, BUFSIZZ);
2598 /* STARTTLS command requires CAPABILITIES... */
2599 BIO_printf(fbio, "CAPABILITIES\r\n");
2600 (void)BIO_flush(fbio);
2601 BIO_gets(fbio, mbuf, BUFSIZZ);
2602 /* no point in trying to parse the CAPABILITIES response if there is none */
2603 if (strstr(mbuf, "101") != NULL) {
2604 /* wait for multi-line CAPABILITIES response */
2606 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2607 if (strstr(mbuf, "STARTTLS"))
2609 } while (mbuf_len > 1 && mbuf[0] != '.');
2611 (void)BIO_flush(fbio);
2616 "Didn't find STARTTLS in server response,"
2617 " trying anyway...\n");
2618 BIO_printf(sbio, "STARTTLS\r\n");
2619 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2621 BIO_printf(bio_err, "BIO_read failed\n");
2624 mbuf[mbuf_len] = '\0';
2625 if (strstr(mbuf, "382") == NULL) {
2626 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2634 BIO *fbio = BIO_new(BIO_f_buffer());
2637 BIO_printf(bio_err, "Unable to create BIO\n");
2640 BIO_push(fbio, sbio);
2641 /* wait for multi-line response to end from Sieve */
2643 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2645 * According to RFC 5804 § 1.7, capability
2646 * is case-insensitive, make it uppercase
2648 if (mbuf_len > 1 && mbuf[0] == '"') {
2649 make_uppercase(mbuf);
2650 if (HAS_PREFIX(mbuf, "\"STARTTLS\""))
2653 } while (mbuf_len > 1 && mbuf[0] == '"');
2654 (void)BIO_flush(fbio);
2659 "Didn't find STARTTLS in server response,"
2660 " trying anyway...\n");
2661 BIO_printf(sbio, "STARTTLS\r\n");
2662 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2664 BIO_printf(bio_err, "BIO_read failed\n");
2667 mbuf[mbuf_len] = '\0';
2669 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2673 * According to RFC 5804 § 2.2, response codes are case-
2674 * insensitive, make it uppercase but preserve the response.
2676 strncpy(sbuf, mbuf, 2);
2677 make_uppercase(sbuf);
2678 if (!HAS_PREFIX(sbuf, "OK")) {
2679 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2686 /* StartTLS Operation according to RFC 4511 */
2687 static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
2689 "messageID=INTEGER:1\n"
2690 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2691 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2693 char *genstr = NULL;
2695 ASN1_TYPE *atyp = NULL;
2696 BIO *ldapbio = BIO_new(BIO_s_mem());
2697 CONF *cnf = NCONF_new(NULL);
2699 if (ldapbio == NULL || cnf == NULL) {
2704 BIO_puts(ldapbio, ldap_tls_genconf);
2705 if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
2709 BIO_printf(bio_err, "NCONF_load_bio failed\n");
2712 BIO_printf(bio_err, "Error on line %ld\n", errline);
2717 genstr = NCONF_get_string(cnf, "default", "asn1");
2718 if (genstr == NULL) {
2720 BIO_printf(bio_err, "NCONF_get_string failed\n");
2723 atyp = ASN1_generate_nconf(genstr, cnf);
2726 BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
2731 /* Send SSLRequest packet */
2732 BIO_write(sbio, atyp->value.sequence->data,
2733 atyp->value.sequence->length);
2734 (void)BIO_flush(sbio);
2735 ASN1_TYPE_free(atyp);
2737 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2739 BIO_printf(bio_err, "BIO_read failed\n");
2742 result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
2744 BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
2746 } else if (result > 0) {
2747 BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
2756 if (early_data_file != NULL
2757 && ((SSL_get0_session(con) != NULL
2758 && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
2760 && SSL_SESSION_get_max_early_data(psksess) > 0))) {
2761 BIO *edfile = BIO_new_file(early_data_file, "r");
2762 size_t readbytes, writtenbytes;
2765 if (edfile == NULL) {
2766 BIO_printf(bio_err, "Cannot open early data file\n");
2771 if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
2774 while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
2775 switch (SSL_get_error(con, 0)) {
2776 case SSL_ERROR_WANT_WRITE:
2777 case SSL_ERROR_WANT_ASYNC:
2778 case SSL_ERROR_WANT_READ:
2779 /* Just keep trying - busy waiting */
2782 BIO_printf(bio_err, "Error writing early data\n");
2784 ERR_print_errors(bio_err);
2797 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2798 timeoutp = &timeout;
2802 if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
2803 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
2811 BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2812 print_ssl_summary(con);
2815 print_stuff(bio_c_out, con, full_log);
2819 if (starttls_proto) {
2820 BIO_write(bio_err, mbuf, mbuf_len);
2821 /* We don't need to know any more */
2823 starttls_proto = PROTO_OFF;
2828 BIO_printf(bio_c_out,
2829 "drop connection and then reconnect\n");
2830 do_ssl_shutdown(con);
2831 SSL_set_connect_state(con);
2832 BIO_closesocket(SSL_get_fd(con));
2838 ssl_pending = read_ssl && SSL_has_pending(con);
2841 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2844 * Note that select() returns when read _would not block_,
2845 * and EOF satisfies that. To avoid a CPU-hogging loop,
2846 * set the flag so we exit.
2848 if (read_tty && !at_eof)
2849 openssl_fdset(fileno_stdin(), &readfds);
2850 #if !defined(OPENSSL_SYS_VMS)
2852 openssl_fdset(fileno_stdout(), &writefds);
2856 openssl_fdset(SSL_get_fd(con), &readfds);
2858 openssl_fdset(SSL_get_fd(con), &writefds);
2860 if (!tty_on || !write_tty) {
2862 openssl_fdset(SSL_get_fd(con), &readfds);
2864 openssl_fdset(SSL_get_fd(con), &writefds);
2869 * Note: under VMS with SOCKETSHR the second parameter is
2870 * currently of type (int *) whereas under other systems it is
2871 * (void *) if you don't have a cast it will choke the compiler:
2872 * if you do have a cast then you can either go for (int *) or
2875 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2877 * Under Windows/DOS we make the assumption that we can always
2878 * write to the tty: therefore, if we need to write to the tty we
2879 * just fall through. Otherwise we timeout the select every
2880 * second and see if there are any keypresses. Note: this is a
2881 * hack, in a proper Windows application we wouldn't do this.
2888 i = select(width, (void *)&readfds, (void *)&writefds,
2890 if (!i && (!has_stdin_waiting() || !read_tty))
2893 i = select(width, (void *)&readfds, (void *)&writefds,
2897 i = select(width, (void *)&readfds, (void *)&writefds,
2901 BIO_printf(bio_err, "bad select %d\n",
2902 get_last_socket_error());
2907 if (SSL_is_dtls(con) && DTLSv1_handle_timeout(con) > 0)
2908 BIO_printf(bio_err, "TIMEOUT occurred\n");
2910 if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
2911 k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
2912 switch (SSL_get_error(con, k)) {
2913 case SSL_ERROR_NONE:
2918 /* we have done a write(con,NULL,0); */
2919 if (cbuf_len <= 0) {
2922 } else { /* if (cbuf_len > 0) */
2928 case SSL_ERROR_WANT_WRITE:
2929 BIO_printf(bio_c_out, "write W BLOCK\n");
2933 case SSL_ERROR_WANT_ASYNC:
2934 BIO_printf(bio_c_out, "write A BLOCK\n");
2935 wait_for_async(con);
2939 case SSL_ERROR_WANT_READ:
2940 BIO_printf(bio_c_out, "write R BLOCK\n");
2945 case SSL_ERROR_WANT_X509_LOOKUP:
2946 BIO_printf(bio_c_out, "write X BLOCK\n");
2948 case SSL_ERROR_ZERO_RETURN:
2949 if (cbuf_len != 0) {
2950 BIO_printf(bio_c_out, "shutdown\n");
2959 case SSL_ERROR_SYSCALL:
2960 if ((k != 0) || (cbuf_len != 0)) {
2961 int sockerr = get_last_socket_error();
2963 if (!tfo || sockerr != EISCONN) {
2964 BIO_printf(bio_err, "write:errno=%d\n", sockerr);
2972 case SSL_ERROR_WANT_ASYNC_JOB:
2973 /* This shouldn't ever happen in s_client - treat as an error */
2975 ERR_print_errors(bio_err);
2979 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
2980 /* Assume Windows/DOS/BeOS can always write */
2981 else if (!ssl_pending && write_tty)
2983 else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
2986 #ifdef CHARSET_EBCDIC
2987 ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
2989 i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
2992 BIO_printf(bio_c_out, "DONE\n");
2999 if (sbuf_len <= 0) {
3003 } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
3008 SSL_renegotiate(con);
3013 k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
3015 switch (SSL_get_error(con, k)) {
3016 case SSL_ERROR_NONE:
3025 case SSL_ERROR_WANT_ASYNC:
3026 BIO_printf(bio_c_out, "read A BLOCK\n");
3027 wait_for_async(con);
3030 if ((read_tty == 0) && (write_ssl == 0))
3033 case SSL_ERROR_WANT_WRITE:
3034 BIO_printf(bio_c_out, "read W BLOCK\n");
3038 case SSL_ERROR_WANT_READ:
3039 BIO_printf(bio_c_out, "read R BLOCK\n");
3042 if ((read_tty == 0) && (write_ssl == 0))
3045 case SSL_ERROR_WANT_X509_LOOKUP:
3046 BIO_printf(bio_c_out, "read X BLOCK\n");
3048 case SSL_ERROR_SYSCALL:
3049 ret = get_last_socket_error();
3051 BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
3053 BIO_printf(bio_err, "read:errno=%d\n", ret);
3055 case SSL_ERROR_ZERO_RETURN:
3056 BIO_printf(bio_c_out, "closed\n");
3059 case SSL_ERROR_WANT_ASYNC_JOB:
3060 /* This shouldn't ever happen in s_client. Treat as an error */
3062 ERR_print_errors(bio_err);
3067 /* don't wait for client input in the non-interactive mode */
3068 else if (nointeractive) {
3073 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
3074 #if defined(OPENSSL_SYS_MSDOS)
3075 else if (has_stdin_waiting())
3077 else if (FD_ISSET(fileno_stdin(), &readfds))
3083 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
3085 /* both loops are skipped when i <= 0 */
3086 for (j = 0; j < i; j++)
3087 if (cbuf[j] == '\n')
3089 for (j = i - 1; j >= 0; j--) {
3090 cbuf[j + lf_num] = cbuf[j];
3091 if (cbuf[j] == '\n') {
3094 cbuf[j + lf_num] = '\r';
3097 assert(lf_num == 0);
3099 i = raw_read_stdin(cbuf, BUFSIZZ);
3100 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3105 if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q' && cmdletters))) {
3106 BIO_printf(bio_err, "DONE\n");
3111 if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'C' && cmdletters))) {
3113 BIO_printf(bio_c_out,
3115 do_ssl_shutdown(con);
3116 SSL_set_connect_state(con);
3117 BIO_closesocket(SSL_get_fd(con));
3121 if ((!c_ign_eof) && (cbuf[0] == 'R' && cmdletters)) {
3122 BIO_printf(bio_err, "RENEGOTIATING\n");
3123 SSL_renegotiate(con);
3125 } else if (!c_ign_eof && (cbuf[0] == 'K' || cbuf[0] == 'k')
3127 BIO_printf(bio_err, "KEYUPDATE\n");
3129 cbuf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED
3130 : SSL_KEY_UPDATE_NOT_REQUESTED);
3135 #ifdef CHARSET_EBCDIC
3136 ebcdic2ascii(cbuf, cbuf, i);
3147 print_stuff(bio_c_out, con, full_log);
3148 do_ssl_shutdown(con);
3151 * If we ended with an alert being sent, but still with data in the
3152 * network buffer to be read, then calling BIO_closesocket() will
3153 * result in a TCP-RST being sent. On some platforms (notably
3154 * Windows) then this will result in the peer immediately abandoning
3155 * the connection including any buffered alert data before it has
3156 * had a chance to be read. Shutting down the sending side first,
3157 * and then closing the socket sends TCP-FIN first followed by
3158 * TCP-RST. This seems to allow the peer to read the alert data.
3160 shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
3162 * We just said we have nothing else to say, but it doesn't mean that
3163 * the other side has nothing. It's even recommended to consume incoming
3164 * data. [In testing context this ensures that alerts are passed on...]
3167 timeout.tv_usec = 500000; /* some extreme round-trip */
3170 openssl_fdset(sock, &readfds);
3171 } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
3172 && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
3174 BIO_closesocket(SSL_get_fd(con));
3178 print_stuff(bio_c_out, con, 1);
3181 SSL_SESSION_free(psksess);
3182 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3183 OPENSSL_free(next_proto.data);
3186 set_keylog_file(NULL, NULL);
3188 sk_X509_CRL_pop_free(crls, X509_CRL_free);
3190 OSSL_STACK_OF_X509_free(chain);
3192 #ifndef OPENSSL_NO_SRP
3193 OPENSSL_free(srp_arg.srppassin);
3195 OPENSSL_free(sname_alloc);
3196 BIO_ADDR_free(tfo_addr);
3197 OPENSSL_free(connectstr);
3198 OPENSSL_free(bindstr);
3199 OPENSSL_free(bindhost);
3200 OPENSSL_free(bindport);
3203 OPENSSL_free(thost);
3204 OPENSSL_free(tport);
3205 X509_VERIFY_PARAM_free(vpm);
3206 ssl_excert_free(exc);
3207 sk_OPENSSL_STRING_free(ssl_args);
3208 sk_OPENSSL_STRING_free(dane_tlsa_rrset);
3209 SSL_CONF_CTX_free(cctx);
3210 OPENSSL_clear_free(cbuf, BUFSIZZ);
3211 OPENSSL_clear_free(sbuf, BUFSIZZ);
3212 OPENSSL_clear_free(mbuf, BUFSIZZ);
3213 clear_free(proxypass);
3215 BIO_free(bio_c_out);
3217 BIO_free(bio_c_msg);
3222 static void print_stuff(BIO *bio, SSL *s, int full)
3226 const SSL_CIPHER *c;
3227 EVP_PKEY *public_key;
3228 int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
3230 #ifndef OPENSSL_NO_COMP
3231 const COMP_METHOD *comp, *expansion;
3233 unsigned char *exportedkeymat;
3234 #ifndef OPENSSL_NO_CT
3235 const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
3239 int got_a_chain = 0;
3241 sk = SSL_get_peer_cert_chain(s);
3245 BIO_printf(bio, "---\nCertificate chain\n");
3246 for (i = 0; i < sk_X509_num(sk); i++) {
3247 BIO_printf(bio, "%2d s:", i);
3248 X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
3249 BIO_puts(bio, "\n");
3250 BIO_printf(bio, " i:");
3251 X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
3252 BIO_puts(bio, "\n");
3253 public_key = X509_get_pubkey(sk_X509_value(sk, i));
3254 if (public_key != NULL) {
3255 BIO_printf(bio, " a:PKEY: %s, %d (bit); sigalg: %s\n",
3256 OBJ_nid2sn(EVP_PKEY_get_base_id(public_key)),
3257 EVP_PKEY_get_bits(public_key),
3258 OBJ_nid2sn(X509_get_signature_nid(sk_X509_value(sk, i))));
3259 EVP_PKEY_free(public_key);
3261 BIO_printf(bio, " v:NotBefore: ");
3262 ASN1_TIME_print(bio, X509_get0_notBefore(sk_X509_value(sk, i)));
3263 BIO_printf(bio, "; NotAfter: ");
3264 ASN1_TIME_print(bio, X509_get0_notAfter(sk_X509_value(sk, i)));
3265 BIO_puts(bio, "\n");
3267 PEM_write_bio_X509(bio, sk_X509_value(sk, i));
3271 BIO_printf(bio, "---\n");
3272 peer = SSL_get0_peer_certificate(s);
3274 BIO_printf(bio, "Server certificate\n");
3276 /* Redundant if we showed the whole chain */
3277 if (!(c_showcerts && got_a_chain))
3278 PEM_write_bio_X509(bio, peer);
3279 dump_cert_text(bio, peer);
3281 BIO_printf(bio, "no peer certificate available\n");
3284 /* Only display RPK information if configured */
3285 if (SSL_get_negotiated_client_cert_type(s) == TLSEXT_cert_type_rpk)
3286 BIO_printf(bio, "Client-to-server raw public key negotiated\n");
3287 if (SSL_get_negotiated_server_cert_type(s) == TLSEXT_cert_type_rpk)
3288 BIO_printf(bio, "Server-to-client raw public key negotiated\n");
3289 if (enable_server_rpk) {
3290 EVP_PKEY *peer_rpk = SSL_get0_peer_rpk(s);
3292 if (peer_rpk != NULL) {
3293 BIO_printf(bio, "Server raw public key\n");
3294 EVP_PKEY_print_public(bio, peer_rpk, 2, NULL);
3296 BIO_printf(bio, "no peer rpk available\n");
3300 print_ca_names(bio, s);
3302 ssl_print_sigalgs(bio, s);
3303 ssl_print_tmp_key(bio, s);
3305 #ifndef OPENSSL_NO_CT
3307 * When the SSL session is anonymous, or resumed via an abbreviated
3308 * handshake, no SCTs are provided as part of the handshake. While in
3309 * a resumed session SCTs may be present in the session's certificate,
3310 * no callbacks are invoked to revalidate these, and in any case that
3311 * set of SCTs may be incomplete. Thus it makes little sense to
3312 * attempt to display SCTs from a resumed session's certificate, and of
3313 * course none are associated with an anonymous peer.
3315 if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
3316 const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
3317 int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
3319 BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
3320 if (sct_count > 0) {
3321 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
3323 BIO_printf(bio, "---\n");
3324 for (i = 0; i < sct_count; ++i) {
3325 SCT *sct = sk_SCT_value(scts, i);
3327 BIO_printf(bio, "SCT validation status: %s\n",
3328 SCT_validation_status_string(sct));
3329 SCT_print(sct, bio, 0, log_store);
3330 if (i < sct_count - 1)
3331 BIO_printf(bio, "\n---\n");
3333 BIO_printf(bio, "\n");
3339 "---\nSSL handshake has read %ju bytes "
3340 "and written %ju bytes\n",
3341 BIO_number_read(SSL_get_rbio(s)),
3342 BIO_number_written(SSL_get_wbio(s)));
3344 print_verify_detail(s, bio);
3345 BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
3346 c = SSL_get_current_cipher(s);
3347 BIO_printf(bio, "%s, Cipher is %s\n",
3348 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3352 pktmp = X509_get0_pubkey(peer);
3353 BIO_printf(bio, "Server public key is %d bit\n",
3354 EVP_PKEY_get_bits(pktmp));
3357 ssl_print_secure_renegotiation_notes(bio, s);
3359 #ifndef OPENSSL_NO_COMP
3360 comp = SSL_get_current_compression(s);
3361 expansion = SSL_get_current_expansion(s);
3362 BIO_printf(bio, "Compression: %s\n",
3363 comp ? SSL_COMP_get_name(comp) : "NONE");
3364 BIO_printf(bio, "Expansion: %s\n",
3365 expansion ? SSL_COMP_get_name(expansion) : "NONE");
3367 #ifndef OPENSSL_NO_KTLS
3368 if (BIO_get_ktls_send(SSL_get_wbio(s)))
3369 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3370 if (BIO_get_ktls_recv(SSL_get_rbio(s)))
3371 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3374 if (OSSL_TRACE_ENABLED(TLS)) {
3375 /* Print out local port of connection: useful for debugging */
3377 union BIO_sock_info_u info;
3379 sock = SSL_get_fd(s);
3380 if ((info.addr = BIO_ADDR_new()) != NULL
3381 && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
3382 BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
3383 ntohs(BIO_ADDR_rawport(info.addr)));
3385 BIO_ADDR_free(info.addr);
3388 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3389 if (next_proto.status != -1) {
3390 const unsigned char *proto;
3391 unsigned int proto_len;
3392 SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
3393 BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
3394 BIO_write(bio, proto, proto_len);
3395 BIO_write(bio, "\n", 1);
3399 const unsigned char *proto;
3400 unsigned int proto_len;
3401 SSL_get0_alpn_selected(s, &proto, &proto_len);
3402 if (proto_len > 0) {
3403 BIO_printf(bio, "ALPN protocol: ");
3404 BIO_write(bio, proto, proto_len);
3405 BIO_write(bio, "\n", 1);
3407 BIO_printf(bio, "No ALPN negotiated\n");
3410 #ifndef OPENSSL_NO_SRTP
3412 SRTP_PROTECTION_PROFILE *srtp_profile =
3413 SSL_get_selected_srtp_profile(s);
3416 BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
3417 srtp_profile->name);
3422 switch (SSL_get_early_data_status(s)) {
3423 case SSL_EARLY_DATA_NOT_SENT:
3424 BIO_printf(bio, "Early data was not sent\n");
3427 case SSL_EARLY_DATA_REJECTED:
3428 BIO_printf(bio, "Early data was rejected\n");
3431 case SSL_EARLY_DATA_ACCEPTED:
3432 BIO_printf(bio, "Early data was accepted\n");
3438 * We also print the verify results when we dump session information,
3439 * but in TLSv1.3 we may not get that right away (or at all) depending
3440 * on when we get a NewSessionTicket. Therefore, we print it now as well.
3442 verify_result = SSL_get_verify_result(s);
3443 BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
3444 X509_verify_cert_error_string(verify_result));
3446 /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3447 SSL_SESSION_print(bio, SSL_get_session(s));
3450 if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
3451 BIO_printf(bio, "Keying material exporter:\n");
3452 BIO_printf(bio, " Label: '%s'\n", keymatexportlabel);
3453 BIO_printf(bio, " Length: %i bytes\n", keymatexportlen);
3454 exportedkeymat = app_malloc(keymatexportlen, "export key");
3455 if (SSL_export_keying_material(s, exportedkeymat,
3458 strlen(keymatexportlabel),
3460 BIO_printf(bio, " Error\n");
3462 BIO_printf(bio, " Keying material: ");
3463 for (i = 0; i < keymatexportlen; i++)
3464 BIO_printf(bio, "%02X", exportedkeymat[i]);
3465 BIO_printf(bio, "\n");
3467 OPENSSL_free(exportedkeymat);
3469 BIO_printf(bio, "---\n");
3470 /* flush, or debugging output gets mixed with http response */
3471 (void)BIO_flush(bio);
3474 # ifndef OPENSSL_NO_OCSP
3475 static int ocsp_resp_cb(SSL *s, void *arg)
3477 const unsigned char *p;
3480 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3481 BIO_puts(arg, "OCSP response: ");
3483 BIO_puts(arg, "no response sent\n");
3486 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3488 BIO_puts(arg, "response parse error\n");
3489 BIO_dump_indent(arg, (char *)p, len, 4);
3492 BIO_puts(arg, "\n======================================\n");
3493 OCSP_RESPONSE_print(arg, rsp, 0);
3494 BIO_puts(arg, "======================================\n");
3495 OCSP_RESPONSE_free(rsp);
3500 static int ldap_ExtendedResponse_parse(const char *buf, long rem)
3502 const unsigned char *cur, *end;
3504 int tag, xclass, inf, ret = -1;
3506 cur = (const unsigned char *)buf;
3512 * LDAPMessage ::= SEQUENCE {
3513 * messageID MessageID,
3514 * protocolOp CHOICE {
3516 * extendedResp ExtendedResponse,
3518 * controls [0] Controls OPTIONAL }
3520 * ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3521 * COMPONENTS OF LDAPResult,
3522 * responseName [10] LDAPOID OPTIONAL,
3523 * responseValue [11] OCTET STRING OPTIONAL }
3525 * LDAPResult ::= SEQUENCE {
3526 * resultCode ENUMERATED {
3532 * diagnosticMessage LDAPString,
3533 * referral [3] Referral OPTIONAL }
3537 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3538 if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
3539 (rem = end - cur, len > rem)) {
3540 BIO_printf(bio_err, "Unexpected LDAP response\n");
3544 rem = len; /* ensure that we don't overstep the SEQUENCE */
3546 /* pull MessageID */
3547 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3548 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
3549 (rem = end - cur, len > rem)) {
3550 BIO_printf(bio_err, "No MessageID\n");
3554 cur += len; /* shall we check for MessageId match or just skip? */
3556 /* pull [APPLICATION 24] */
3558 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3559 if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
3561 BIO_printf(bio_err, "Not ExtendedResponse\n");
3565 /* pull resultCode */
3567 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3568 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
3569 (rem = end - cur, len > rem)) {
3570 BIO_printf(bio_err, "Not LDAPResult\n");
3574 /* len should always be one, but just in case... */
3575 for (ret = 0, inf = 0; inf < len; inf++) {
3579 /* There is more data, but we don't care... */
3585 * Host dNS Name verifier: used for checking that the hostname is in dNS format
3586 * before setting it as SNI
3588 static int is_dNS_name(const char *host)
3590 const size_t MAX_LABEL_LENGTH = 63;
3593 size_t length = strlen(host);
3594 size_t label_length = 0;
3595 int all_numeric = 1;
3598 * Deviation from strict DNS name syntax, also check names with '_'
3599 * Check DNS name syntax, any '-' or '.' must be internal,
3600 * and on either side of each '.' we can't have a '-' or '.'.
3602 * If the name has just one label, we don't consider it a DNS name.
3604 for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) {
3607 if ((c >= 'a' && c <= 'z')
3608 || (c >= 'A' && c <= 'Z')
3615 if (c >= '0' && c <= '9') {
3620 /* Dot and hyphen cannot be first or last. */
3621 if (i > 0 && i < length - 1) {
3627 * Next to a dot the preceding and following characters must not be
3628 * another dot or a hyphen. Otherwise, record that the name is
3629 * plausible, since it has two or more labels.
3632 && host[i + 1] != '.'
3633 && host[i - 1] != '-'
3634 && host[i + 1] != '-') {
3644 /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
3645 isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH);
3649 #endif /* OPENSSL_NO_SOCK */