2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright 2005 Nokia. All rights reserved.
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
17 #include <openssl/e_os2.h>
19 #ifndef OPENSSL_NO_SOCK
22 * With IPv6, it looks like Digital has mixed up the proper order of
23 * recursive header file inclusion, resulting in the compiler complaining
24 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
25 * needed to have fileno() declared correctly... So let's define u_int
27 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
29 typedef unsigned int u_int;
34 #include <openssl/x509.h>
35 #include <openssl/ssl.h>
36 #include <openssl/err.h>
37 #include <openssl/pem.h>
38 #include <openssl/rand.h>
39 #include <openssl/ocsp.h>
40 #include <openssl/bn.h>
41 #include <openssl/trace.h>
42 #include <openssl/async.h>
43 #ifndef OPENSSL_NO_SRP
44 # include <openssl/srp.h>
47 # include <openssl/ct.h>
51 #include "internal/sockets.h"
53 #if defined(__has_feature)
54 # if __has_feature(memory_sanitizer)
55 # include <sanitizer/msan_interface.h>
60 DEFINE_STACK_OF(X509_CRL)
61 DEFINE_STACK_OF(X509_NAME)
63 DEFINE_STACK_OF_STRING()
66 #define BUFSIZZ 1024*8
67 #define S_CLIENT_IRC_READ_TIMEOUT 8
70 static int c_debug = 0;
71 static int c_showcerts = 0;
72 static char *keymatexportlabel = NULL;
73 static int keymatexportlen = 20;
74 static BIO *bio_c_out = NULL;
75 static int c_quiet = 0;
76 static char *sess_out = NULL;
77 static SSL_SESSION *psksess = NULL;
79 static void print_stuff(BIO *berr, SSL *con, int full);
80 #ifndef OPENSSL_NO_OCSP
81 static int ocsp_resp_cb(SSL *s, void *arg);
83 static int ldap_ExtendedResponse_parse(const char *buf, long rem);
84 static int is_dNS_name(const char *host);
86 static int saved_errno;
88 static void save_errno(void)
94 static int restore_errno(void)
101 static void do_ssl_shutdown(SSL *ssl)
106 /* We only do unidirectional shutdown */
107 ret = SSL_shutdown(ssl);
109 switch (SSL_get_error(ssl, ret)) {
110 case SSL_ERROR_WANT_READ:
111 case SSL_ERROR_WANT_WRITE:
112 case SSL_ERROR_WANT_ASYNC:
113 case SSL_ERROR_WANT_ASYNC_JOB:
114 /* We just do busy waiting. Nothing clever */
122 /* Default PSK identity and key */
123 static char *psk_identity = "Client_identity";
125 #ifndef OPENSSL_NO_PSK
126 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
127 unsigned int max_identity_len,
129 unsigned int max_psk_len)
136 BIO_printf(bio_c_out, "psk_client_cb\n");
138 /* no ServerKeyExchange message */
140 BIO_printf(bio_c_out,
141 "NULL received PSK identity hint, continuing anyway\n");
142 } else if (c_debug) {
143 BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
147 * lookup PSK identity and PSK key based on the given identity hint here
149 ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
150 if (ret < 0 || (unsigned int)ret > max_identity_len)
153 BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
156 /* convert the PSK key to binary */
157 key = OPENSSL_hexstr2buf(psk_key, &key_len);
159 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
163 if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
165 "psk buffer of callback is too small (%d) for key (%ld)\n",
166 max_psk_len, key_len);
171 memcpy(psk, key, key_len);
175 BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
180 BIO_printf(bio_err, "Error in PSK client callback\n");
185 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
186 const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
188 static int psk_use_session_cb(SSL *s, const EVP_MD *md,
189 const unsigned char **id, size_t *idlen,
192 SSL_SESSION *usesess = NULL;
193 const SSL_CIPHER *cipher = NULL;
195 if (psksess != NULL) {
196 SSL_SESSION_up_ref(psksess);
200 unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
203 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
208 /* We default to SHA-256 */
209 cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
210 if (cipher == NULL) {
211 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
216 usesess = SSL_SESSION_new();
218 || !SSL_SESSION_set1_master_key(usesess, key, key_len)
219 || !SSL_SESSION_set_cipher(usesess, cipher)
220 || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
227 cipher = SSL_SESSION_get0_cipher(usesess);
231 if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
232 /* PSK not usable, ignore it */
236 SSL_SESSION_free(usesess);
239 *id = (unsigned char *)psk_identity;
240 *idlen = strlen(psk_identity);
246 SSL_SESSION_free(usesess);
250 /* This is a context that we pass to callbacks */
251 typedef struct tlsextctx_st {
256 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
258 tlsextctx *p = (tlsextctx *) arg;
259 const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
260 if (SSL_get_servername_type(s) != -1)
261 p->ack = !SSL_session_reused(s) && hn != NULL;
263 BIO_printf(bio_err, "Can't use SSL_get_servername\n");
265 return SSL_TLSEXT_ERR_OK;
268 #ifndef OPENSSL_NO_SRP
270 /* This is a context that we pass to all callbacks */
271 typedef struct srp_arg_st {
274 int msg; /* copy from c_msg */
275 int debug; /* copy from c_debug */
276 int amp; /* allow more groups */
277 int strength; /* minimal size for N */
280 static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g)
282 BN_CTX *bn_ctx = BN_CTX_new();
283 BIGNUM *p = BN_new();
284 BIGNUM *r = BN_new();
286 g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
287 BN_check_prime(N, bn_ctx, NULL) == 1 &&
288 p != NULL && BN_rshift1(p, N) &&
290 BN_check_prime(p, bn_ctx, NULL) == 1 &&
292 /* verify g^((N-1)/2) == -1 (mod N) */
293 BN_mod_exp(r, g, p, N, bn_ctx) &&
294 BN_add_word(r, 1) && BN_cmp(r, N) == 0;
303 * This callback is used here for two purposes:
304 * - extended debugging
305 * - making some primality tests for unknown groups
306 * The callback is only called for a non default group.
308 * An application does not need the call back at all if
309 * only the standard groups are used. In real life situations,
310 * client and server already share well known groups,
311 * thus there is no need to verify them.
312 * Furthermore, in case that a server actually proposes a group that
313 * is not one of those defined in RFC 5054, it is more appropriate
314 * to add the group to a static list and then compare since
315 * primality tests are rather cpu consuming.
318 static int ssl_srp_verify_param_cb(SSL *s, void *arg)
320 SRP_ARG *srp_arg = (SRP_ARG *)arg;
321 BIGNUM *N = NULL, *g = NULL;
323 if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL))
325 if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
326 BIO_printf(bio_err, "SRP parameters:\n");
327 BIO_printf(bio_err, "\tN=");
328 BN_print(bio_err, N);
329 BIO_printf(bio_err, "\n\tg=");
330 BN_print(bio_err, g);
331 BIO_printf(bio_err, "\n");
334 if (SRP_check_known_gN_param(g, N))
337 if (srp_arg->amp == 1) {
340 "SRP param N and g are not known params, going to check deeper.\n");
343 * The srp_moregroups is a real debugging feature. Implementors
344 * should rather add the value to the known ones. The minimal size
345 * has already been tested.
347 if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
350 BIO_printf(bio_err, "SRP param N and g rejected.\n");
354 # define PWD_STRLEN 1024
356 static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
358 SRP_ARG *srp_arg = (SRP_ARG *)arg;
359 char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer");
363 cb_tmp.password = (char *)srp_arg->srppassin;
364 cb_tmp.prompt_info = "SRP user";
365 if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
366 BIO_printf(bio_err, "Can't read Password\n");
377 #ifndef OPENSSL_NO_NEXTPROTONEG
378 /* This the context that we pass to next_proto_cb */
379 typedef struct tlsextnextprotoctx_st {
383 } tlsextnextprotoctx;
385 static tlsextnextprotoctx next_proto;
387 static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
388 const unsigned char *in, unsigned int inlen,
391 tlsextnextprotoctx *ctx = arg;
394 /* We can assume that |in| is syntactically valid. */
396 BIO_printf(bio_c_out, "Protocols advertised by server: ");
397 for (i = 0; i < inlen;) {
399 BIO_write(bio_c_out, ", ", 2);
400 BIO_write(bio_c_out, &in[i + 1], in[i]);
403 BIO_write(bio_c_out, "\n", 1);
407 SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
408 return SSL_TLSEXT_ERR_OK;
410 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
412 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
413 const unsigned char *in, size_t inlen,
417 unsigned char ext_buf[4 + 65536];
419 /* Reconstruct the type/len fields prior to extension data */
420 inlen &= 0xffff; /* for formal memcmpy correctness */
421 ext_buf[0] = (unsigned char)(ext_type >> 8);
422 ext_buf[1] = (unsigned char)(ext_type);
423 ext_buf[2] = (unsigned char)(inlen >> 8);
424 ext_buf[3] = (unsigned char)(inlen);
425 memcpy(ext_buf + 4, in, inlen);
427 BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
429 PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
434 * Hex decoder that tolerates optional whitespace. Returns number of bytes
435 * produced, advances inptr to end of input string.
437 static ossl_ssize_t hexdecode(const char **inptr, void *result)
439 unsigned char **out = (unsigned char **)result;
440 const char *in = *inptr;
441 unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
442 unsigned char *cp = ret;
449 for (byte = 0; *in; ++in) {
452 if (isspace(_UC(*in)))
454 x = OPENSSL_hexchar2int(*in);
460 if ((nibble ^= 1) == 0) {
473 return cp - (*out = ret);
477 * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
478 * inptr to next field skipping leading whitespace.
480 static ossl_ssize_t checked_uint8(const char **inptr, void *out)
482 uint8_t *result = (uint8_t *)out;
483 const char *in = *inptr;
489 v = strtol(in, &endp, 10);
492 if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
493 endp == in || !isspace(_UC(*endp)) ||
494 v != (*result = (uint8_t) v)) {
497 for (in = endp; isspace(_UC(*in)); ++in)
507 ossl_ssize_t (*parser)(const char **, void *);
510 static int tlsa_import_rr(SSL *con, const char *rrdata)
512 /* Not necessary to re-init these values; the "parsers" do that. */
513 static uint8_t usage;
514 static uint8_t selector;
515 static uint8_t mtype;
516 static unsigned char *data;
517 static struct tlsa_field tlsa_fields[] = {
518 { &usage, "usage", checked_uint8 },
519 { &selector, "selector", checked_uint8 },
520 { &mtype, "mtype", checked_uint8 },
521 { &data, "data", hexdecode },
524 struct tlsa_field *f;
526 const char *cp = rrdata;
527 ossl_ssize_t len = 0;
529 for (f = tlsa_fields; f->var; ++f) {
530 /* Returns number of bytes produced, advances cp to next field */
531 if ((len = f->parser(&cp, f->var)) <= 0) {
532 BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
533 prog, f->name, rrdata);
537 /* The data field is last, so len is its length */
538 ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
542 ERR_print_errors(bio_err);
543 BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
548 ERR_print_errors(bio_err);
549 BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
556 static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
558 int num = sk_OPENSSL_STRING_num(rrset);
562 for (i = 0; i < num; ++i) {
563 char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
564 if (tlsa_import_rr(con, rrdata) > 0)
570 typedef enum OPTION_choice {
571 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
572 OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX,
573 OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT,
574 OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
575 OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
576 OPT_BRIEF, OPT_PREXIT, OPT_CRLF, OPT_QUIET, OPT_NBIO,
577 OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF,
578 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
579 OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
580 OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
581 OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS,
582 #ifndef OPENSSL_NO_SRP
583 OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER,
586 OPT_SSL3, OPT_SSL_CONFIG,
587 OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
588 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS,
589 OPT_CERT_CHAIN, OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN,
590 OPT_NEXTPROTONEG, OPT_ALPN,
591 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
592 OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE,
593 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
594 OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC,
595 OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST,
596 OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES,
597 OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE,
601 OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_PROXY, OPT_PROXY_USER, OPT_PROXY_PASS,
602 OPT_DANE_TLSA_DOMAIN,
603 #ifndef OPENSSL_NO_CT
604 OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
606 OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME,
609 OPT_R_ENUM, OPT_PROV_ENUM
612 const OPTIONS s_client_options[] = {
613 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [host:port]\n"},
615 OPT_SECTION("General"),
616 {"help", OPT_HELP, '-', "Display this summary"},
617 #ifndef OPENSSL_NO_ENGINE
618 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
619 {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
620 "Specify engine to be used for client certificate operations"},
622 {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified section for SSL_CTX configuration"},
623 #ifndef OPENSSL_NO_CT
624 {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
625 {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
626 {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
629 OPT_SECTION("Network"),
630 {"host", OPT_HOST, 's', "Use -connect instead"},
631 {"port", OPT_PORT, 'p', "Use -connect instead"},
632 {"connect", OPT_CONNECT, 's',
633 "TCP/IP where to connect (default is :" PORT ")"},
634 {"bind", OPT_BIND, 's', "bind local address for connection"},
635 {"proxy", OPT_PROXY, 's',
636 "Connect to via specified proxy to the real server"},
637 {"proxy_user", OPT_PROXY_USER, 's', "UserID for proxy authentication"},
638 {"proxy_pass", OPT_PROXY_PASS, 's', "Proxy authentication password source"},
640 {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"},
642 {"4", OPT_4, '-', "Use IPv4 only"},
644 {"6", OPT_6, '-', "Use IPv6 only"},
646 {"maxfraglen", OPT_MAXFRAGLEN, 'p',
647 "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
648 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
649 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
650 "Size used to split data for encrypt pipelines"},
651 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
652 "Maximum number of encrypt/decrypt pipelines to be used"},
653 {"read_buf", OPT_READ_BUF, 'p',
654 "Default read buffer size to be used for connections"},
655 {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
657 OPT_SECTION("Identity"),
658 {"cert", OPT_CERT, '<', "Client certificate file to use"},
659 {"certform", OPT_CERTFORM, 'F',
660 "Client certificate file format (PEM or DER) PEM default"},
661 {"cert_chain", OPT_CERT_CHAIN, '<',
662 "Client certificate chain file (in PEM format)"},
663 {"build_chain", OPT_BUILD_CHAIN, '-', "Build client certificate chain"},
664 {"key", OPT_KEY, 's', "Private key file to use; default is: -cert file"},
665 {"keyform", OPT_KEYFORM, 'E', "Key format (PEM, DER or engine) PEM default"},
666 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
667 {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
668 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
669 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
670 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
671 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
672 {"no-CAfile", OPT_NOCAFILE, '-',
673 "Do not load the default certificates file"},
674 {"no-CApath", OPT_NOCAPATH, '-',
675 "Do not load certificates from the default certificates directory"},
676 {"no-CAstore", OPT_NOCASTORE, '-',
677 "Do not load certificates from the default certificates store"},
678 {"requestCAfile", OPT_REQCAFILE, '<',
679 "PEM format file of CA names to send to the server"},
680 {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
681 {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
682 "DANE TLSA rrdata presentation form"},
683 {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
684 "Disable name checks when matching DANE-EE(3) TLSA records"},
685 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
686 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
687 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
688 {"name", OPT_PROTOHOST, 's',
689 "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
691 OPT_SECTION("Session"),
692 {"reconnect", OPT_RECONNECT, '-',
693 "Drop and re-make the connection with the same Session-ID"},
694 {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
695 {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
697 OPT_SECTION("Input/Output"),
698 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
699 {"quiet", OPT_QUIET, '-', "No s_client output"},
700 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
701 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
702 {"starttls", OPT_STARTTLS, 's',
703 "Use the appropriate STARTTLS command before starting TLS"},
704 {"xmpphost", OPT_XMPPHOST, 's',
705 "Alias of -name option for \"-starttls xmpp[-server]\""},
706 {"brief", OPT_BRIEF, '-',
707 "Restrict output to brief summary of connection parameters"},
708 {"prexit", OPT_PREXIT, '-',
709 "Print session information when the program exits"},
711 OPT_SECTION("Debug"),
712 {"showcerts", OPT_SHOWCERTS, '-',
713 "Show all certificates sent by the server"},
714 {"debug", OPT_DEBUG, '-', "Extra output"},
715 {"msg", OPT_MSG, '-', "Show protocol messages"},
716 {"msgfile", OPT_MSGFILE, '>',
717 "File to send output of -msg or -trace, instead of stdout"},
718 {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
719 {"state", OPT_STATE, '-', "Print the ssl states"},
720 {"keymatexport", OPT_KEYMATEXPORT, 's',
721 "Export keying material using label"},
722 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
723 "Export len bytes of keying material (default 20)"},
724 {"security_debug", OPT_SECURITY_DEBUG, '-',
725 "Enable security debug messages"},
726 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
727 "Output more security debug output"},
728 #ifndef OPENSSL_NO_SSL_TRACE
729 {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
732 {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
734 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
735 {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
736 {"servername", OPT_SERVERNAME, 's',
737 "Set TLS extension servername (SNI) in ClientHello (default)"},
738 {"noservername", OPT_NOSERVERNAME, '-',
739 "Do not send the server name (SNI) extension in the ClientHello"},
740 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
741 "Hex dump of all TLS extensions received"},
742 #ifndef OPENSSL_NO_OCSP
743 {"status", OPT_STATUS, '-', "Request certificate status from server"},
745 {"serverinfo", OPT_SERVERINFO, 's',
746 "types Send empty ClientHello extensions (comma-separated numbers)"},
747 {"alpn", OPT_ALPN, 's',
748 "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
749 {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
750 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
752 OPT_SECTION("Protocol and version"),
753 #ifndef OPENSSL_NO_SSL3
754 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
756 #ifndef OPENSSL_NO_TLS1
757 {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
759 #ifndef OPENSSL_NO_TLS1_1
760 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
762 #ifndef OPENSSL_NO_TLS1_2
763 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
765 #ifndef OPENSSL_NO_TLS1_3
766 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
768 #ifndef OPENSSL_NO_DTLS
769 {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
770 {"timeout", OPT_TIMEOUT, '-',
771 "Enable send/receive timeout on DTLS connections"},
772 {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
774 #ifndef OPENSSL_NO_DTLS1
775 {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
777 #ifndef OPENSSL_NO_DTLS1_2
778 {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
780 #ifndef OPENSSL_NO_SCTP
781 {"sctp", OPT_SCTP, '-', "Use SCTP"},
782 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
784 #ifndef OPENSSL_NO_NEXTPROTONEG
785 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
786 "Enable NPN extension, considering named protocols supported (comma-separated list)"},
788 {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"},
789 {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"},
790 #ifndef OPENSSL_NO_SRTP
791 {"use_srtp", OPT_USE_SRTP, 's',
792 "Offer SRTP key management with a colon-separated profile list"},
794 #ifndef OPENSSL_NO_SRP
795 {"srpuser", OPT_SRPUSER, 's', "SRP authentication for 'user'"},
796 {"srppass", OPT_SRPPASS, 's', "Password for 'user'"},
797 {"srp_lateuser", OPT_SRP_LATEUSER, '-',
798 "SRP username into second ClientHello message"},
799 {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
800 "Tolerate other than the known g N values."},
801 {"srp_strength", OPT_SRP_STRENGTH, 'p', "Minimal length in bits for N"},
807 {"CRL", OPT_CRL, '<', "CRL file to use"},
808 {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
809 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
810 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
811 "Close connection on verification error"},
812 {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
813 {"chainCAfile", OPT_CHAINCAFILE, '<',
814 "CA file for certificate chain (PEM format)"},
815 {"chainCApath", OPT_CHAINCAPATH, '/',
816 "Use dir as certificate store path to build CA certificate chain"},
817 {"chainCAstore", OPT_CHAINCASTORE, ':',
818 "CA store URI for certificate chain"},
819 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
820 "CA file for certificate verification (PEM format)"},
821 {"verifyCApath", OPT_VERIFYCAPATH, '/',
822 "Use dir as certificate store path to verify CA certificate"},
823 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
824 "CA store URI for certificate verification"},
829 {"host:port", 0, 0, "Where to connect; same as -connect option"},
833 typedef enum PROTOCOL_choice {
852 static const OPT_PAIR services[] = {
853 {"smtp", PROTO_SMTP},
854 {"pop3", PROTO_POP3},
855 {"imap", PROTO_IMAP},
857 {"xmpp", PROTO_XMPP},
858 {"xmpp-server", PROTO_XMPP_SERVER},
859 {"telnet", PROTO_TELNET},
861 {"mysql", PROTO_MYSQL},
862 {"postgres", PROTO_POSTGRES},
863 {"lmtp", PROTO_LMTP},
864 {"nntp", PROTO_NNTP},
865 {"sieve", PROTO_SIEVE},
866 {"ldap", PROTO_LDAP},
870 #define IS_INET_FLAG(o) \
871 (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
872 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
874 #define IS_PROT_FLAG(o) \
875 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
876 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
878 /* Free |*dest| and optionally set it to a copy of |source|. */
879 static void freeandcopy(char **dest, const char *source)
884 *dest = OPENSSL_strdup(source);
887 static int new_session_cb(SSL *s, SSL_SESSION *sess)
890 if (sess_out != NULL) {
891 BIO *stmp = BIO_new_file(sess_out, "w");
894 BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
896 PEM_write_bio_SSL_SESSION(stmp, sess);
902 * Session data gets dumped on connection for TLSv1.2 and below, and on
903 * arrival of the NewSessionTicket for TLSv1.3.
905 if (SSL_version(s) == TLS1_3_VERSION) {
906 BIO_printf(bio_c_out,
907 "---\nPost-Handshake New Session Ticket arrived:\n");
908 SSL_SESSION_print(bio_c_out, sess);
909 BIO_printf(bio_c_out, "---\n");
913 * We always return a "fail" response so that the session gets freed again
914 * because we haven't used the reference.
919 int s_client_main(int argc, char **argv)
922 EVP_PKEY *key = NULL;
925 STACK_OF(X509) *chain = NULL;
927 X509_VERIFY_PARAM *vpm = NULL;
928 SSL_EXCERT *exc = NULL;
929 SSL_CONF_CTX *cctx = NULL;
930 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
931 char *dane_tlsa_domain = NULL;
932 STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
933 int dane_ee_no_name = 0;
934 STACK_OF(X509_CRL) *crls = NULL;
935 const SSL_METHOD *meth = TLS_client_method();
936 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
937 char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
938 char *proxystr = NULL, *proxyuser = NULL;
939 char *proxypassarg = NULL, *proxypass = NULL;
940 char *connectstr = NULL, *bindstr = NULL;
941 char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
942 char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL, *host = NULL;
943 char *port = OPENSSL_strdup(PORT);
944 char *bindhost = NULL, *bindport = NULL;
945 char *passarg = NULL, *pass = NULL;
946 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
947 char *ReqCAfile = NULL;
948 char *sess_in = NULL, *crl_file = NULL, *p;
949 const char *protohost = NULL;
950 struct timeval timeout, *timeoutp;
951 fd_set readfds, writefds;
952 int noCApath = 0, noCAfile = 0, noCAstore = 0;
953 int build_chain = 0, cbuf_len, cbuf_off, cert_format = FORMAT_PEM;
954 int key_format = FORMAT_PEM, crlf = 0, full_log = 1, mbuf_len = 0;
957 int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
958 int ret = 1, in_init = 1, i, nbio_test = 0, sock = -1, k, width, state = 0;
959 int sbuf_len, sbuf_off, cmdletters = 1;
960 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
961 int starttls_proto = PROTO_OFF, crl_format = FORMAT_PEM, crl_download = 0;
962 int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
963 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
966 int read_buf_len = 0;
967 int fallback_scsv = 0;
969 #ifndef OPENSSL_NO_DTLS
970 int enable_timeouts = 0;
973 #ifndef OPENSSL_NO_ENGINE
974 ENGINE *ssl_client_engine = NULL;
977 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
980 const char *servername = NULL;
981 int noservername = 0;
982 const char *alpn_in = NULL;
983 tlsextctx tlsextcbp = { NULL, 0 };
984 const char *ssl_config = NULL;
985 #define MAX_SI_TYPES 100
986 unsigned short serverinfo_types[MAX_SI_TYPES];
987 int serverinfo_count = 0, start = 0, len;
988 #ifndef OPENSSL_NO_NEXTPROTONEG
989 const char *next_proto_neg_in = NULL;
991 #ifndef OPENSSL_NO_SRP
992 char *srppass = NULL;
993 int srp_lateuser = 0;
994 SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
996 #ifndef OPENSSL_NO_SRTP
997 char *srtp_profiles = NULL;
999 #ifndef OPENSSL_NO_CT
1000 char *ctlog_file = NULL;
1001 int ct_validation = 0;
1003 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1005 unsigned int max_send_fragment = 0;
1006 unsigned int split_send_fragment = 0, max_pipelines = 0;
1007 enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
1009 uint8_t maxfraglen = 0;
1010 int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
1011 int c_tlsextdebug = 0;
1012 #ifndef OPENSSL_NO_OCSP
1013 int c_status_req = 0;
1015 BIO *bio_c_msg = NULL;
1016 const char *keylog_file = NULL, *early_data_file = NULL;
1017 #ifndef OPENSSL_NO_DTLS
1020 char *psksessf = NULL;
1022 #ifndef OPENSSL_NO_SCTP
1023 int sctp_label_bug = 0;
1028 /* Known false-positive of MemorySanitizer. */
1029 #if defined(__has_feature)
1030 # if __has_feature(memory_sanitizer)
1031 __msan_unpoison(&readfds, sizeof(readfds));
1032 __msan_unpoison(&writefds, sizeof(writefds));
1036 prog = opt_progname(argv[0]);
1041 vpm = X509_VERIFY_PARAM_new();
1042 cctx = SSL_CONF_CTX_new();
1044 if (vpm == NULL || cctx == NULL) {
1045 BIO_printf(bio_err, "%s: out of memory\n", prog);
1049 cbuf = app_malloc(BUFSIZZ, "cbuf");
1050 sbuf = app_malloc(BUFSIZZ, "sbuf");
1051 mbuf = app_malloc(BUFSIZZ, "mbuf");
1053 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
1055 prog = opt_init(argc, argv, s_client_options);
1056 while ((o = opt_next()) != OPT_EOF) {
1057 /* Check for intermixing flags. */
1058 if (connect_type == use_unix && IS_INET_FLAG(o)) {
1060 "%s: Intermixed protocol flags (unix and internet domains)\n",
1064 if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
1066 "%s: Intermixed protocol flags (internet and unix domains)\n",
1071 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1072 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1075 if (IS_NO_PROT_FLAG(o))
1077 if (prot_opt == 1 && no_prot_opt) {
1079 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1087 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1090 opt_help(s_client_options);
1094 connect_type = use_inet;
1095 socket_family = AF_INET;
1100 connect_type = use_inet;
1101 socket_family = AF_INET6;
1106 connect_type = use_inet;
1107 freeandcopy(&host, opt_arg());
1110 connect_type = use_inet;
1111 freeandcopy(&port, opt_arg());
1114 connect_type = use_inet;
1115 freeandcopy(&connectstr, opt_arg());
1118 freeandcopy(&bindstr, opt_arg());
1121 proxystr = opt_arg();
1122 starttls_proto = PROTO_CONNECT;
1124 case OPT_PROXY_USER:
1125 proxyuser = opt_arg();
1127 case OPT_PROXY_PASS:
1128 proxypassarg = opt_arg();
1132 connect_type = use_unix;
1133 socket_family = AF_UNIX;
1134 freeandcopy(&host, opt_arg());
1138 /* fall through, since this is an alias */
1140 protohost = opt_arg();
1143 verify = SSL_VERIFY_PEER;
1144 verify_args.depth = atoi(opt_arg());
1146 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1149 cert_file = opt_arg();
1152 if (!set_nameopt(opt_arg()))
1156 crl_file = opt_arg();
1158 case OPT_CRL_DOWNLOAD:
1162 sess_out = opt_arg();
1165 sess_in = opt_arg();
1168 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &cert_format))
1172 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1175 case OPT_VERIFY_RET_ERROR:
1176 verify = SSL_VERIFY_PEER;
1177 verify_args.return_error = 1;
1179 case OPT_VERIFY_QUIET:
1180 verify_args.quiet = 1;
1183 c_brief = verify_args.quiet = c_quiet = 1;
1186 if (ssl_args == NULL)
1187 ssl_args = sk_OPENSSL_STRING_new_null();
1188 if (ssl_args == NULL
1189 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1190 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1191 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1196 if (!opt_verify(o, vpm))
1201 if (!args_excert(o, &exc))
1211 c_quiet = c_ign_eof = 1;
1220 e = setup_engine(opt_arg(), 1);
1222 case OPT_SSL_CLIENT_ENGINE:
1223 #ifndef OPENSSL_NO_ENGINE
1224 ssl_client_engine = ENGINE_by_id(opt_arg());
1225 if (ssl_client_engine == NULL) {
1226 BIO_printf(bio_err, "Error getting client auth engine\n");
1235 case OPT_PROV_CASES:
1236 if (!opt_provider(o))
1242 case OPT_NO_IGN_EOF:
1248 case OPT_TLSEXTDEBUG:
1252 #ifndef OPENSSL_NO_OCSP
1265 bio_c_msg = BIO_new_file(opt_arg(), "w");
1268 #ifndef OPENSSL_NO_SSL_TRACE
1272 case OPT_SECURITY_DEBUG:
1275 case OPT_SECURITY_DEBUG_VERBOSE:
1287 case OPT_PSK_IDENTITY:
1288 psk_identity = opt_arg();
1291 for (p = psk_key = opt_arg(); *p; p++) {
1292 if (isxdigit(_UC(*p)))
1294 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1299 psksessf = opt_arg();
1301 #ifndef OPENSSL_NO_SRP
1303 srp_arg.srplogin = opt_arg();
1304 if (min_version < TLS1_VERSION)
1305 min_version = TLS1_VERSION;
1308 srppass = opt_arg();
1309 if (min_version < TLS1_VERSION)
1310 min_version = TLS1_VERSION;
1312 case OPT_SRP_STRENGTH:
1313 srp_arg.strength = atoi(opt_arg());
1314 BIO_printf(bio_err, "SRP minimal length for N is %d\n",
1316 if (min_version < TLS1_VERSION)
1317 min_version = TLS1_VERSION;
1319 case OPT_SRP_LATEUSER:
1321 if (min_version < TLS1_VERSION)
1322 min_version = TLS1_VERSION;
1324 case OPT_SRP_MOREGROUPS:
1326 if (min_version < TLS1_VERSION)
1327 min_version = TLS1_VERSION;
1330 case OPT_SSL_CONFIG:
1331 ssl_config = opt_arg();
1334 min_version = SSL3_VERSION;
1335 max_version = SSL3_VERSION;
1338 min_version = TLS1_3_VERSION;
1339 max_version = TLS1_3_VERSION;
1342 min_version = TLS1_2_VERSION;
1343 max_version = TLS1_2_VERSION;
1346 min_version = TLS1_1_VERSION;
1347 max_version = TLS1_1_VERSION;
1350 min_version = TLS1_VERSION;
1351 max_version = TLS1_VERSION;
1354 #ifndef OPENSSL_NO_DTLS
1355 meth = DTLS_client_method();
1356 socket_type = SOCK_DGRAM;
1361 #ifndef OPENSSL_NO_DTLS1
1362 meth = DTLS_client_method();
1363 min_version = DTLS1_VERSION;
1364 max_version = DTLS1_VERSION;
1365 socket_type = SOCK_DGRAM;
1370 #ifndef OPENSSL_NO_DTLS1_2
1371 meth = DTLS_client_method();
1372 min_version = DTLS1_2_VERSION;
1373 max_version = DTLS1_2_VERSION;
1374 socket_type = SOCK_DGRAM;
1379 #ifndef OPENSSL_NO_SCTP
1380 protocol = IPPROTO_SCTP;
1383 case OPT_SCTP_LABEL_BUG:
1384 #ifndef OPENSSL_NO_SCTP
1389 #ifndef OPENSSL_NO_DTLS
1390 enable_timeouts = 1;
1394 #ifndef OPENSSL_NO_DTLS
1395 socket_mtu = atol(opt_arg());
1398 case OPT_FALLBACKSCSV:
1402 if (!opt_format(opt_arg(), OPT_FMT_PDE, &key_format))
1406 passarg = opt_arg();
1408 case OPT_CERT_CHAIN:
1409 chain_file = opt_arg();
1412 key_file = opt_arg();
1423 case OPT_CHAINCAPATH:
1424 chCApath = opt_arg();
1426 case OPT_VERIFYCAPATH:
1427 vfyCApath = opt_arg();
1429 case OPT_BUILD_CHAIN:
1433 ReqCAfile = opt_arg();
1441 #ifndef OPENSSL_NO_CT
1448 case OPT_CTLOG_FILE:
1449 ctlog_file = opt_arg();
1452 case OPT_CHAINCAFILE:
1453 chCAfile = opt_arg();
1455 case OPT_VERIFYCAFILE:
1456 vfyCAfile = opt_arg();
1459 CAstore = opt_arg();
1464 case OPT_CHAINCASTORE:
1465 chCAstore = opt_arg();
1467 case OPT_VERIFYCASTORE:
1468 vfyCAstore = opt_arg();
1470 case OPT_DANE_TLSA_DOMAIN:
1471 dane_tlsa_domain = opt_arg();
1473 case OPT_DANE_TLSA_RRDATA:
1474 if (dane_tlsa_rrset == NULL)
1475 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1476 if (dane_tlsa_rrset == NULL ||
1477 !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1478 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1482 case OPT_DANE_EE_NO_NAME:
1483 dane_ee_no_name = 1;
1485 case OPT_NEXTPROTONEG:
1486 #ifndef OPENSSL_NO_NEXTPROTONEG
1487 next_proto_neg_in = opt_arg();
1491 alpn_in = opt_arg();
1493 case OPT_SERVERINFO:
1496 for (start = 0, i = 0; i <= len; ++i) {
1497 if (i == len || p[i] == ',') {
1498 serverinfo_types[serverinfo_count] = atoi(p + start);
1499 if (++serverinfo_count == MAX_SI_TYPES)
1506 if (!opt_pair(opt_arg(), services, &starttls_proto))
1509 case OPT_SERVERNAME:
1510 servername = opt_arg();
1512 case OPT_NOSERVERNAME:
1516 #ifndef OPENSSL_NO_SRTP
1517 srtp_profiles = opt_arg();
1520 case OPT_KEYMATEXPORT:
1521 keymatexportlabel = opt_arg();
1523 case OPT_KEYMATEXPORTLEN:
1524 keymatexportlen = atoi(opt_arg());
1529 case OPT_MAXFRAGLEN:
1530 len = atoi(opt_arg());
1533 maxfraglen = TLSEXT_max_fragment_length_512;
1536 maxfraglen = TLSEXT_max_fragment_length_1024;
1539 maxfraglen = TLSEXT_max_fragment_length_2048;
1542 maxfraglen = TLSEXT_max_fragment_length_4096;
1546 "%s: Max Fragment Len %u is out of permitted values",
1551 case OPT_MAX_SEND_FRAG:
1552 max_send_fragment = atoi(opt_arg());
1554 case OPT_SPLIT_SEND_FRAG:
1555 split_send_fragment = atoi(opt_arg());
1557 case OPT_MAX_PIPELINES:
1558 max_pipelines = atoi(opt_arg());
1561 read_buf_len = atoi(opt_arg());
1563 case OPT_KEYLOG_FILE:
1564 keylog_file = opt_arg();
1566 case OPT_EARLY_DATA:
1567 early_data_file = opt_arg();
1569 case OPT_ENABLE_PHA:
1575 if (count4or6 >= 2) {
1576 BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1580 if (servername != NULL) {
1582 "%s: Can't use -servername and -noservername together\n",
1586 if (dane_tlsa_domain != NULL) {
1588 "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1593 argc = opt_num_rest();
1595 /* If there's a positional argument, it's the equivalent of
1597 * Don't allow -connect and a separate argument.
1599 if (connectstr != NULL) {
1601 "%s: must not provide both -connect option and target parameter\n",
1605 connect_type = use_inet;
1606 freeandcopy(&connectstr, *opt_rest());
1607 } else if (argc != 0) {
1611 #ifndef OPENSSL_NO_NEXTPROTONEG
1612 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1613 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1617 if (proxystr != NULL) {
1619 char *tmp_host = host, *tmp_port = port;
1620 if (connectstr == NULL) {
1621 BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
1624 res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1625 if (tmp_host != host)
1626 OPENSSL_free(tmp_host);
1627 if (tmp_port != port)
1628 OPENSSL_free(tmp_port);
1631 "%s: -proxy argument malformed or ambiguous\n", prog);
1636 char *tmp_host = host, *tmp_port = port;
1637 if (connectstr != NULL)
1638 res = BIO_parse_hostserv(connectstr, &host, &port,
1639 BIO_PARSE_PRIO_HOST);
1640 if (tmp_host != host)
1641 OPENSSL_free(tmp_host);
1642 if (tmp_port != port)
1643 OPENSSL_free(tmp_port);
1646 "%s: -connect argument or target parameter malformed or ambiguous\n",
1652 if (bindstr != NULL) {
1654 res = BIO_parse_hostserv(bindstr, &bindhost, &bindport,
1655 BIO_PARSE_PRIO_HOST);
1658 "%s: -bind argument parameter malformed or ambiguous\n",
1665 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1667 "Can't use unix sockets and datagrams together\n");
1672 #ifndef OPENSSL_NO_SCTP
1673 if (protocol == IPPROTO_SCTP) {
1674 if (socket_type != SOCK_DGRAM) {
1675 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1678 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1679 socket_type = SOCK_STREAM;
1683 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1684 next_proto.status = -1;
1685 if (next_proto_neg_in) {
1687 next_protos_parse(&next_proto.len, next_proto_neg_in);
1688 if (next_proto.data == NULL) {
1689 BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1693 next_proto.data = NULL;
1696 if (!app_passwd(passarg, NULL, &pass, NULL)) {
1697 BIO_printf(bio_err, "Error getting private key password\n");
1701 if (!app_passwd(proxypassarg, NULL, &proxypass, NULL)) {
1702 BIO_printf(bio_err, "Error getting proxy password\n");
1706 if (proxypass != NULL && proxyuser == NULL) {
1707 BIO_printf(bio_err, "Error: Must specify proxy_user with proxy_pass\n");
1711 if (key_file == NULL)
1712 key_file = cert_file;
1714 if (key_file != NULL) {
1715 key = load_key(key_file, key_format, 0, pass, e,
1716 "client certificate private key file");
1718 ERR_print_errors(bio_err);
1723 if (cert_file != NULL) {
1724 cert = load_cert(cert_file, cert_format, "client certificate file");
1726 ERR_print_errors(bio_err);
1731 if (chain_file != NULL) {
1732 if (!load_certs(chain_file, &chain, FORMAT_PEM, NULL,
1733 "client certificate chain"))
1737 if (crl_file != NULL) {
1739 crl = load_crl(crl_file, crl_format);
1741 BIO_puts(bio_err, "Error loading CRL\n");
1742 ERR_print_errors(bio_err);
1745 crls = sk_X509_CRL_new_null();
1746 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1747 BIO_puts(bio_err, "Error adding CRL\n");
1748 ERR_print_errors(bio_err);
1754 if (!load_excert(&exc))
1757 if (bio_c_out == NULL) {
1758 if (c_quiet && !c_debug) {
1759 bio_c_out = BIO_new(BIO_s_null());
1760 if (c_msg && bio_c_msg == NULL)
1761 bio_c_msg = dup_bio_out(FORMAT_TEXT);
1762 } else if (bio_c_out == NULL)
1763 bio_c_out = dup_bio_out(FORMAT_TEXT);
1765 #ifndef OPENSSL_NO_SRP
1766 if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1767 BIO_printf(bio_err, "Error getting password\n");
1772 ctx = SSL_CTX_new(meth);
1774 ERR_print_errors(bio_err);
1778 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1781 ssl_ctx_security_debug(ctx, sdebug);
1783 if (!config_ctx(cctx, ssl_args, ctx))
1786 if (ssl_config != NULL) {
1787 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1788 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1790 ERR_print_errors(bio_err);
1795 #ifndef OPENSSL_NO_SCTP
1796 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1797 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1800 if (min_version != 0
1801 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1803 if (max_version != 0
1804 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1807 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1808 BIO_printf(bio_err, "Error setting verify params\n");
1809 ERR_print_errors(bio_err);
1814 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1817 if (max_send_fragment > 0
1818 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1819 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1820 prog, max_send_fragment);
1824 if (split_send_fragment > 0
1825 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1826 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1827 prog, split_send_fragment);
1831 if (max_pipelines > 0
1832 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1833 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1834 prog, max_pipelines);
1838 if (read_buf_len > 0) {
1839 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1843 && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
1845 "%s: Max Fragment Length code %u is out of permitted values"
1846 "\n", prog, maxfraglen);
1850 if (!ssl_load_stores(ctx,
1851 vfyCApath, vfyCAfile, vfyCAstore,
1852 chCApath, chCAfile, chCAstore,
1853 crls, crl_download)) {
1854 BIO_printf(bio_err, "Error loading store locations\n");
1855 ERR_print_errors(bio_err);
1858 if (ReqCAfile != NULL) {
1859 STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
1861 if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
1862 sk_X509_NAME_pop_free(nm, X509_NAME_free);
1863 BIO_printf(bio_err, "Error loading CA names\n");
1864 ERR_print_errors(bio_err);
1867 SSL_CTX_set0_CA_list(ctx, nm);
1869 #ifndef OPENSSL_NO_ENGINE
1870 if (ssl_client_engine) {
1871 if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1872 BIO_puts(bio_err, "Error setting client auth engine\n");
1873 ERR_print_errors(bio_err);
1874 ENGINE_free(ssl_client_engine);
1877 ENGINE_free(ssl_client_engine);
1881 #ifndef OPENSSL_NO_PSK
1882 if (psk_key != NULL) {
1884 BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1885 SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1888 if (psksessf != NULL) {
1889 BIO *stmp = BIO_new_file(psksessf, "r");
1892 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
1893 ERR_print_errors(bio_err);
1896 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1898 if (psksess == NULL) {
1899 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
1900 ERR_print_errors(bio_err);
1904 if (psk_key != NULL || psksess != NULL)
1905 SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
1907 #ifndef OPENSSL_NO_SRTP
1908 if (srtp_profiles != NULL) {
1909 /* Returns 0 on success! */
1910 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1911 BIO_printf(bio_err, "Error setting SRTP profile\n");
1912 ERR_print_errors(bio_err);
1919 ssl_ctx_set_excert(ctx, exc);
1921 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1922 if (next_proto.data != NULL)
1923 SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1927 unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1930 BIO_printf(bio_err, "Error parsing -alpn argument\n");
1933 /* Returns 0 on success! */
1934 if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1935 BIO_printf(bio_err, "Error setting ALPN\n");
1941 for (i = 0; i < serverinfo_count; i++) {
1942 if (!SSL_CTX_add_client_custom_ext(ctx,
1943 serverinfo_types[i],
1945 serverinfo_cli_parse_cb, NULL)) {
1947 "Warning: Unable to add custom extension %u, skipping\n",
1948 serverinfo_types[i]);
1953 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1955 #ifndef OPENSSL_NO_CT
1956 /* Enable SCT processing, without early connection termination */
1957 if (ct_validation &&
1958 !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
1959 ERR_print_errors(bio_err);
1963 if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
1964 if (ct_validation) {
1965 ERR_print_errors(bio_err);
1970 * If CT validation is not enabled, the log list isn't needed so don't
1971 * show errors or abort. We try to load it regardless because then we
1972 * can show the names of the logs any SCTs came from (SCTs may be seen
1973 * even with validation disabled).
1979 SSL_CTX_set_verify(ctx, verify, verify_callback);
1981 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1982 CAstore, noCAstore)) {
1983 ERR_print_errors(bio_err);
1987 ssl_ctx_add_crls(ctx, crls, crl_download);
1989 if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
1992 if (!noservername) {
1993 tlsextcbp.biodebug = bio_err;
1994 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1995 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1997 # ifndef OPENSSL_NO_SRP
1998 if (srp_arg.srplogin) {
1999 if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) {
2000 BIO_printf(bio_err, "Unable to set SRP username\n");
2003 srp_arg.msg = c_msg;
2004 srp_arg.debug = c_debug;
2005 SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
2006 SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
2007 SSL_CTX_set_srp_strength(ctx, srp_arg.strength);
2008 if (c_msg || c_debug || srp_arg.amp == 0)
2009 SSL_CTX_set_srp_verify_param_callback(ctx,
2010 ssl_srp_verify_param_cb);
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 (sess_in != NULL) {
2045 BIO *stmp = BIO_new_file(sess_in, "r");
2047 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2048 ERR_print_errors(bio_err);
2051 sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2054 BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2055 ERR_print_errors(bio_err);
2058 if (!SSL_set_session(con, sess)) {
2059 BIO_printf(bio_err, "Can't set session\n");
2060 ERR_print_errors(bio_err);
2064 SSL_SESSION_free(sess);
2068 SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
2070 if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
2071 if (servername == NULL) {
2072 if(host == NULL || is_dNS_name(host))
2073 servername = (host == NULL) ? "localhost" : host;
2075 if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) {
2076 BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
2077 ERR_print_errors(bio_err);
2082 if (dane_tlsa_domain != NULL) {
2083 if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
2084 BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
2085 "authentication.\n", prog);
2086 ERR_print_errors(bio_err);
2089 if (dane_tlsa_rrset == NULL) {
2090 BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
2091 "least one -dane_tlsa_rrdata option.\n", prog);
2094 if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
2095 BIO_printf(bio_err, "%s: Failed to import any TLSA "
2096 "records.\n", prog);
2099 if (dane_ee_no_name)
2100 SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
2101 } else if (dane_tlsa_rrset != NULL) {
2102 BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
2103 "-dane_tlsa_domain option.\n", prog);
2108 if (init_client(&sock, host, port, bindhost, bindport, socket_family,
2109 socket_type, protocol) == 0) {
2110 BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
2111 BIO_closesocket(sock);
2114 BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock);
2117 if (!BIO_socket_nbio(sock, 1)) {
2118 ERR_print_errors(bio_err);
2121 BIO_printf(bio_c_out, "Turned on non blocking io\n");
2123 #ifndef OPENSSL_NO_DTLS
2125 union BIO_sock_info_u peer_info;
2127 #ifndef OPENSSL_NO_SCTP
2128 if (protocol == IPPROTO_SCTP)
2129 sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
2132 sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
2134 if ((peer_info.addr = BIO_ADDR_new()) == NULL) {
2135 BIO_printf(bio_err, "memory allocation failure\n");
2136 BIO_closesocket(sock);
2139 if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
2140 BIO_printf(bio_err, "getsockname:errno=%d\n",
2141 get_last_socket_error());
2142 BIO_ADDR_free(peer_info.addr);
2143 BIO_closesocket(sock);
2147 (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
2148 BIO_ADDR_free(peer_info.addr);
2149 peer_info.addr = NULL;
2151 if (enable_timeouts) {
2153 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2154 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2157 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2158 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2162 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2163 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2164 DTLS_get_link_min_mtu(con));
2168 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2169 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2170 BIO_printf(bio_err, "Failed to set MTU\n");
2175 /* want to do MTU discovery */
2176 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2179 #endif /* OPENSSL_NO_DTLS */
2180 sbio = BIO_new_socket(sock, BIO_NOCLOSE);
2185 test = BIO_new(BIO_f_nbio_test());
2186 sbio = BIO_push(test, sbio);
2190 BIO_set_callback(sbio, bio_dump_callback);
2191 BIO_set_callback_arg(sbio, (char *)bio_c_out);
2194 #ifndef OPENSSL_NO_SSL_TRACE
2196 SSL_set_msg_callback(con, SSL_trace);
2199 SSL_set_msg_callback(con, msg_cb);
2200 SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
2203 if (c_tlsextdebug) {
2204 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2205 SSL_set_tlsext_debug_arg(con, bio_c_out);
2207 #ifndef OPENSSL_NO_OCSP
2209 SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
2210 SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
2211 SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
2215 SSL_set_bio(con, sbio, sbio);
2216 SSL_set_connect_state(con);
2218 /* ok, lets connect */
2219 if (fileno_stdin() > SSL_get_fd(con))
2220 width = fileno_stdin() + 1;
2222 width = SSL_get_fd(con) + 1;
2235 switch ((PROTOCOL_CHOICE) starttls_proto) {
2242 * This is an ugly hack that does a lot of assumptions. We do
2243 * have to handle multi-line responses which may come in a single
2244 * packet or not. We therefore have to use BIO_gets() which does
2245 * need a buffering BIO. So during the initial chitchat we do
2246 * push a buffering BIO into the chain that is removed again
2247 * later on to not disturb the rest of the s_client operation.
2250 BIO *fbio = BIO_new(BIO_f_buffer());
2252 BIO_push(fbio, sbio);
2253 /* Wait for multi-line response to end from LMTP or SMTP */
2255 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2256 } while (mbuf_len > 3 && mbuf[3] == '-');
2257 if (protohost == NULL)
2258 protohost = "mail.example.com";
2259 if (starttls_proto == (int)PROTO_LMTP)
2260 BIO_printf(fbio, "LHLO %s\r\n", protohost);
2262 BIO_printf(fbio, "EHLO %s\r\n", protohost);
2263 (void)BIO_flush(fbio);
2265 * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2269 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2270 if (strstr(mbuf, "STARTTLS"))
2272 } while (mbuf_len > 3 && mbuf[3] == '-');
2273 (void)BIO_flush(fbio);
2278 "Didn't find STARTTLS in server response,"
2279 " trying anyway...\n");
2280 BIO_printf(sbio, "STARTTLS\r\n");
2281 BIO_read(sbio, sbuf, BUFSIZZ);
2286 BIO_read(sbio, mbuf, BUFSIZZ);
2287 BIO_printf(sbio, "STLS\r\n");
2288 mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
2290 BIO_printf(bio_err, "BIO_read failed\n");
2298 BIO *fbio = BIO_new(BIO_f_buffer());
2300 BIO_push(fbio, sbio);
2301 BIO_gets(fbio, mbuf, BUFSIZZ);
2302 /* STARTTLS command requires CAPABILITY... */
2303 BIO_printf(fbio, ". CAPABILITY\r\n");
2304 (void)BIO_flush(fbio);
2305 /* wait for multi-line CAPABILITY response */
2307 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2308 if (strstr(mbuf, "STARTTLS"))
2311 while (mbuf_len > 3 && mbuf[0] != '.');
2312 (void)BIO_flush(fbio);
2317 "Didn't find STARTTLS in server response,"
2318 " trying anyway...\n");
2319 BIO_printf(sbio, ". STARTTLS\r\n");
2320 BIO_read(sbio, sbuf, BUFSIZZ);
2325 BIO *fbio = BIO_new(BIO_f_buffer());
2327 BIO_push(fbio, sbio);
2328 /* wait for multi-line response to end from FTP */
2330 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2332 while (mbuf_len > 3 && (!isdigit(mbuf[0]) || !isdigit(mbuf[1]) || !isdigit(mbuf[2]) || mbuf[3] != ' '));
2333 (void)BIO_flush(fbio);
2336 BIO_printf(sbio, "AUTH TLS\r\n");
2337 BIO_read(sbio, sbuf, BUFSIZZ);
2341 case PROTO_XMPP_SERVER:
2344 BIO_printf(sbio, "<stream:stream "
2345 "xmlns:stream='http://etherx.jabber.org/streams' "
2346 "xmlns='jabber:%s' to='%s' version='1.0'>",
2347 starttls_proto == PROTO_XMPP ? "client" : "server",
2348 protohost ? protohost : host);
2349 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2351 BIO_printf(bio_err, "BIO_read failed\n");
2356 (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2358 "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2360 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2368 "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2369 seen = BIO_read(sbio, sbuf, BUFSIZZ);
2371 BIO_printf(bio_err, "BIO_read failed\n");
2375 if (!strstr(sbuf, "<proceed"))
2382 static const unsigned char tls_do[] = {
2383 /* IAC DO START_TLS */
2386 static const unsigned char tls_will[] = {
2387 /* IAC WILL START_TLS */
2390 static const unsigned char tls_follows[] = {
2391 /* IAC SB START_TLS FOLLOWS IAC SE */
2392 255, 250, 46, 1, 255, 240
2396 /* Telnet server should demand we issue START_TLS */
2397 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2398 if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
2400 /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2401 BIO_write(sbio, tls_will, 3);
2402 BIO_write(sbio, tls_follows, 6);
2403 (void)BIO_flush(sbio);
2404 /* Telnet server also sent the FOLLOWS sub-command */
2405 bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2406 if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2411 if (!OSSL_HTTP_proxy_connect(sbio, host, port, proxyuser, proxypass,
2412 0 /* no timeout */, bio_err, prog))
2418 BIO *fbio = BIO_new(BIO_f_buffer());
2420 BIO_push(fbio, sbio);
2421 BIO_printf(fbio, "STARTTLS\r\n");
2422 (void)BIO_flush(fbio);
2423 width = SSL_get_fd(con) + 1;
2429 openssl_fdset(SSL_get_fd(con), &readfds);
2430 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2431 timeout.tv_usec = 0;
2433 * If the IRCd doesn't respond within
2434 * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2435 * it doesn't support STARTTLS. Many IRCds
2436 * will not give _any_ sort of response to a
2437 * STARTTLS command when it's not supported.
2439 if (!BIO_get_buffer_num_lines(fbio)
2440 && !BIO_pending(fbio)
2441 && !BIO_pending(sbio)
2442 && select(width, (void *)&readfds, NULL, NULL,
2445 "Timeout waiting for response (%d seconds).\n",
2446 S_CLIENT_IRC_READ_TIMEOUT);
2450 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2451 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2453 /* :example.net 451 STARTTLS :You have not registered */
2454 /* :example.net 421 STARTTLS :Unknown command */
2455 if ((numeric == 451 || numeric == 421)
2456 && strstr(mbuf, "STARTTLS") != NULL) {
2457 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2460 if (numeric == 691) {
2461 BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2462 ERR_print_errors(bio_err);
2465 } while (numeric != 670);
2467 (void)BIO_flush(fbio);
2470 if (numeric != 670) {
2471 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2479 /* SSL request packet */
2480 static const unsigned char ssl_req[] = {
2481 /* payload_length, sequence_id */
2482 0x20, 0x00, 0x00, 0x01,
2484 /* capability flags, CLIENT_SSL always set */
2485 0x85, 0xae, 0x7f, 0x00,
2486 /* max-packet size */
2487 0x00, 0x00, 0x00, 0x01,
2490 /* string[23] reserved (all [0]) */
2491 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2492 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2493 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2496 int ssl_flg = 0x800;
2498 const unsigned char *packet = (const unsigned char *)sbuf;
2500 /* Receiving Initial Handshake packet. */
2501 bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
2503 BIO_printf(bio_err, "BIO_read failed\n");
2505 /* Packet length[3], Packet number[1] + minimum payload[17] */
2506 } else if (bytes < 21) {
2507 BIO_printf(bio_err, "MySQL packet too short.\n");
2509 } else if (bytes != (4 + packet[0] +
2511 (packet[2] << 16))) {
2512 BIO_printf(bio_err, "MySQL packet length does not match.\n");
2514 /* protocol version[1] */
2515 } else if (packet[4] != 0xA) {
2517 "Only MySQL protocol version 10 is supported.\n");
2522 /* server version[string+NULL] */
2525 BIO_printf(bio_err, "Cannot confirm server version. ");
2527 } else if (packet[pos++] == '\0') {
2532 /* make sure we have at least 15 bytes left in the packet */
2533 if (pos + 15 > bytes) {
2535 "MySQL server handshake packet is broken.\n");
2539 pos += 12; /* skip over conn id[4] + SALT[8] */
2540 if (packet[pos++] != '\0') { /* verify filler */
2542 "MySQL packet is broken.\n");
2546 /* capability flags[2] */
2547 if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
2548 BIO_printf(bio_err, "MySQL server does not support SSL.\n");
2552 /* Sending SSL Handshake packet. */
2553 BIO_write(sbio, ssl_req, sizeof(ssl_req));
2554 (void)BIO_flush(sbio);
2557 case PROTO_POSTGRES:
2559 static const unsigned char ssl_request[] = {
2560 /* Length SSLRequest */
2561 0, 0, 0, 8, 4, 210, 22, 47
2565 /* Send SSLRequest packet */
2566 BIO_write(sbio, ssl_request, 8);
2567 (void)BIO_flush(sbio);
2569 /* Reply will be a single S if SSL is enabled */
2570 bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2571 if (bytes != 1 || sbuf[0] != 'S')
2578 BIO *fbio = BIO_new(BIO_f_buffer());
2580 BIO_push(fbio, sbio);
2581 BIO_gets(fbio, mbuf, BUFSIZZ);
2582 /* STARTTLS command requires CAPABILITIES... */
2583 BIO_printf(fbio, "CAPABILITIES\r\n");
2584 (void)BIO_flush(fbio);
2585 BIO_gets(fbio, mbuf, BUFSIZZ);
2586 /* no point in trying to parse the CAPABILITIES response if there is none */
2587 if (strstr(mbuf, "101") != NULL) {
2588 /* wait for multi-line CAPABILITIES response */
2590 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2591 if (strstr(mbuf, "STARTTLS"))
2593 } while (mbuf_len > 1 && mbuf[0] != '.');
2595 (void)BIO_flush(fbio);
2600 "Didn't find STARTTLS in server response,"
2601 " trying anyway...\n");
2602 BIO_printf(sbio, "STARTTLS\r\n");
2603 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2605 BIO_printf(bio_err, "BIO_read failed\n");
2608 mbuf[mbuf_len] = '\0';
2609 if (strstr(mbuf, "382") == NULL) {
2610 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2618 BIO *fbio = BIO_new(BIO_f_buffer());
2620 BIO_push(fbio, sbio);
2621 /* wait for multi-line response to end from Sieve */
2623 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2625 * According to RFC 5804 § 1.7, capability
2626 * is case-insensitive, make it uppercase
2628 if (mbuf_len > 1 && mbuf[0] == '"') {
2629 make_uppercase(mbuf);
2630 if (strncmp(mbuf, "\"STARTTLS\"", 10) == 0)
2633 } while (mbuf_len > 1 && mbuf[0] == '"');
2634 (void)BIO_flush(fbio);
2639 "Didn't find STARTTLS in server response,"
2640 " trying anyway...\n");
2641 BIO_printf(sbio, "STARTTLS\r\n");
2642 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2644 BIO_printf(bio_err, "BIO_read failed\n");
2647 mbuf[mbuf_len] = '\0';
2649 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2653 * According to RFC 5804 § 2.2, response codes are case-
2654 * insensitive, make it uppercase but preserve the response.
2656 strncpy(sbuf, mbuf, 2);
2657 make_uppercase(sbuf);
2658 if (strncmp(sbuf, "OK", 2) != 0) {
2659 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2666 /* StartTLS Operation according to RFC 4511 */
2667 static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
2669 "messageID=INTEGER:1\n"
2670 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2671 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2673 char *genstr = NULL;
2675 ASN1_TYPE *atyp = NULL;
2676 BIO *ldapbio = BIO_new(BIO_s_mem());
2677 CONF *cnf = NCONF_new(NULL);
2683 BIO_puts(ldapbio, ldap_tls_genconf);
2684 if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
2688 BIO_printf(bio_err, "NCONF_load_bio failed\n");
2691 BIO_printf(bio_err, "Error on line %ld\n", errline);
2696 genstr = NCONF_get_string(cnf, "default", "asn1");
2697 if (genstr == NULL) {
2699 BIO_printf(bio_err, "NCONF_get_string failed\n");
2702 atyp = ASN1_generate_nconf(genstr, cnf);
2705 BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
2710 /* Send SSLRequest packet */
2711 BIO_write(sbio, atyp->value.sequence->data,
2712 atyp->value.sequence->length);
2713 (void)BIO_flush(sbio);
2714 ASN1_TYPE_free(atyp);
2716 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2718 BIO_printf(bio_err, "BIO_read failed\n");
2721 result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
2723 BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
2725 } else if (result > 0) {
2726 BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
2735 if (early_data_file != NULL
2736 && ((SSL_get0_session(con) != NULL
2737 && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
2739 && SSL_SESSION_get_max_early_data(psksess) > 0))) {
2740 BIO *edfile = BIO_new_file(early_data_file, "r");
2741 size_t readbytes, writtenbytes;
2744 if (edfile == NULL) {
2745 BIO_printf(bio_err, "Cannot open early data file\n");
2750 if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
2753 while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
2754 switch (SSL_get_error(con, 0)) {
2755 case SSL_ERROR_WANT_WRITE:
2756 case SSL_ERROR_WANT_ASYNC:
2757 case SSL_ERROR_WANT_READ:
2758 /* Just keep trying - busy waiting */
2761 BIO_printf(bio_err, "Error writing early data\n");
2763 ERR_print_errors(bio_err);
2776 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2777 timeoutp = &timeout;
2781 if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
2782 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
2791 BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2792 print_ssl_summary(con);
2795 print_stuff(bio_c_out, con, full_log);
2799 if (starttls_proto) {
2800 BIO_write(bio_err, mbuf, mbuf_len);
2801 /* We don't need to know any more */
2803 starttls_proto = PROTO_OFF;
2808 BIO_printf(bio_c_out,
2809 "drop connection and then reconnect\n");
2810 do_ssl_shutdown(con);
2811 SSL_set_connect_state(con);
2812 BIO_closesocket(SSL_get_fd(con));
2818 ssl_pending = read_ssl && SSL_has_pending(con);
2821 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2824 * Note that select() returns when read _would not block_,
2825 * and EOF satisfies that. To avoid a CPU-hogging loop,
2826 * set the flag so we exit.
2828 if (read_tty && !at_eof)
2829 openssl_fdset(fileno_stdin(), &readfds);
2830 #if !defined(OPENSSL_SYS_VMS)
2832 openssl_fdset(fileno_stdout(), &writefds);
2836 openssl_fdset(SSL_get_fd(con), &readfds);
2838 openssl_fdset(SSL_get_fd(con), &writefds);
2840 if (!tty_on || !write_tty) {
2842 openssl_fdset(SSL_get_fd(con), &readfds);
2844 openssl_fdset(SSL_get_fd(con), &writefds);
2849 * Note: under VMS with SOCKETSHR the second parameter is
2850 * currently of type (int *) whereas under other systems it is
2851 * (void *) if you don't have a cast it will choke the compiler:
2852 * if you do have a cast then you can either go for (int *) or
2855 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2857 * Under Windows/DOS we make the assumption that we can always
2858 * write to the tty: therefore if we need to write to the tty we
2859 * just fall through. Otherwise we timeout the select every
2860 * second and see if there are any keypresses. Note: this is a
2861 * hack, in a proper Windows application we wouldn't do this.
2868 i = select(width, (void *)&readfds, (void *)&writefds,
2870 if (!i && (!has_stdin_waiting() || !read_tty))
2873 i = select(width, (void *)&readfds, (void *)&writefds,
2877 i = select(width, (void *)&readfds, (void *)&writefds,
2881 BIO_printf(bio_err, "bad select %d\n",
2882 get_last_socket_error());
2887 if (SSL_is_dtls(con) && DTLSv1_handle_timeout(con) > 0)
2888 BIO_printf(bio_err, "TIMEOUT occurred\n");
2890 if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
2891 k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
2892 switch (SSL_get_error(con, k)) {
2893 case SSL_ERROR_NONE:
2898 /* we have done a write(con,NULL,0); */
2899 if (cbuf_len <= 0) {
2902 } else { /* if (cbuf_len > 0) */
2908 case SSL_ERROR_WANT_WRITE:
2909 BIO_printf(bio_c_out, "write W BLOCK\n");
2913 case SSL_ERROR_WANT_ASYNC:
2914 BIO_printf(bio_c_out, "write A BLOCK\n");
2915 wait_for_async(con);
2919 case SSL_ERROR_WANT_READ:
2920 BIO_printf(bio_c_out, "write R BLOCK\n");
2925 case SSL_ERROR_WANT_X509_LOOKUP:
2926 BIO_printf(bio_c_out, "write X BLOCK\n");
2928 case SSL_ERROR_ZERO_RETURN:
2929 if (cbuf_len != 0) {
2930 BIO_printf(bio_c_out, "shutdown\n");
2939 case SSL_ERROR_SYSCALL:
2940 if ((k != 0) || (cbuf_len != 0)) {
2941 BIO_printf(bio_err, "write:errno=%d\n",
2942 get_last_socket_error());
2949 case SSL_ERROR_WANT_ASYNC_JOB:
2950 /* This shouldn't ever happen in s_client - treat as an error */
2952 ERR_print_errors(bio_err);
2956 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
2957 /* Assume Windows/DOS/BeOS can always write */
2958 else if (!ssl_pending && write_tty)
2960 else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
2963 #ifdef CHARSET_EBCDIC
2964 ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
2966 i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
2969 BIO_printf(bio_c_out, "DONE\n");
2976 if (sbuf_len <= 0) {
2980 } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
2985 SSL_renegotiate(con);
2990 k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
2992 switch (SSL_get_error(con, k)) {
2993 case SSL_ERROR_NONE:
3002 case SSL_ERROR_WANT_ASYNC:
3003 BIO_printf(bio_c_out, "read A BLOCK\n");
3004 wait_for_async(con);
3007 if ((read_tty == 0) && (write_ssl == 0))
3010 case SSL_ERROR_WANT_WRITE:
3011 BIO_printf(bio_c_out, "read W BLOCK\n");
3015 case SSL_ERROR_WANT_READ:
3016 BIO_printf(bio_c_out, "read R BLOCK\n");
3019 if ((read_tty == 0) && (write_ssl == 0))
3022 case SSL_ERROR_WANT_X509_LOOKUP:
3023 BIO_printf(bio_c_out, "read X BLOCK\n");
3025 case SSL_ERROR_SYSCALL:
3026 ret = get_last_socket_error();
3028 BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
3030 BIO_printf(bio_err, "read:errno=%d\n", ret);
3032 case SSL_ERROR_ZERO_RETURN:
3033 BIO_printf(bio_c_out, "closed\n");
3036 case SSL_ERROR_WANT_ASYNC_JOB:
3037 /* This shouldn't ever happen in s_client. Treat as an error */
3039 ERR_print_errors(bio_err);
3043 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
3044 #if defined(OPENSSL_SYS_MSDOS)
3045 else if (has_stdin_waiting())
3047 else if (FD_ISSET(fileno_stdin(), &readfds))
3053 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
3055 /* both loops are skipped when i <= 0 */
3056 for (j = 0; j < i; j++)
3057 if (cbuf[j] == '\n')
3059 for (j = i - 1; j >= 0; j--) {
3060 cbuf[j + lf_num] = cbuf[j];
3061 if (cbuf[j] == '\n') {
3064 cbuf[j + lf_num] = '\r';
3067 assert(lf_num == 0);
3069 i = raw_read_stdin(cbuf, BUFSIZZ);
3070 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3075 if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q' && cmdletters))) {
3076 BIO_printf(bio_err, "DONE\n");
3081 if ((!c_ign_eof) && (cbuf[0] == 'R' && cmdletters)) {
3082 BIO_printf(bio_err, "RENEGOTIATING\n");
3083 SSL_renegotiate(con);
3085 } else if (!c_ign_eof && (cbuf[0] == 'K' || cbuf[0] == 'k' )
3087 BIO_printf(bio_err, "KEYUPDATE\n");
3089 cbuf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED
3090 : SSL_KEY_UPDATE_NOT_REQUESTED);
3095 #ifdef CHARSET_EBCDIC
3096 ebcdic2ascii(cbuf, cbuf, i);
3108 print_stuff(bio_c_out, con, full_log);
3109 do_ssl_shutdown(con);
3112 * If we ended with an alert being sent, but still with data in the
3113 * network buffer to be read, then calling BIO_closesocket() will
3114 * result in a TCP-RST being sent. On some platforms (notably
3115 * Windows) then this will result in the peer immediately abandoning
3116 * the connection including any buffered alert data before it has
3117 * had a chance to be read. Shutting down the sending side first,
3118 * and then closing the socket sends TCP-FIN first followed by
3119 * TCP-RST. This seems to allow the peer to read the alert data.
3121 shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
3123 * We just said we have nothing else to say, but it doesn't mean that
3124 * the other side has nothing. It's even recommended to consume incoming
3125 * data. [In testing context this ensures that alerts are passed on...]
3128 timeout.tv_usec = 500000; /* some extreme round-trip */
3131 openssl_fdset(sock, &readfds);
3132 } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
3133 && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
3135 BIO_closesocket(SSL_get_fd(con));
3139 print_stuff(bio_c_out, con, 1);
3142 SSL_SESSION_free(psksess);
3143 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3144 OPENSSL_free(next_proto.data);
3147 set_keylog_file(NULL, NULL);
3149 sk_X509_CRL_pop_free(crls, X509_CRL_free);
3151 sk_X509_pop_free(chain, X509_free);
3153 #ifndef OPENSSL_NO_SRP
3154 OPENSSL_free(srp_arg.srppassin);
3156 OPENSSL_free(connectstr);
3157 OPENSSL_free(bindstr);
3160 X509_VERIFY_PARAM_free(vpm);
3161 ssl_excert_free(exc);
3162 sk_OPENSSL_STRING_free(ssl_args);
3163 sk_OPENSSL_STRING_free(dane_tlsa_rrset);
3164 SSL_CONF_CTX_free(cctx);
3165 OPENSSL_clear_free(cbuf, BUFSIZZ);
3166 OPENSSL_clear_free(sbuf, BUFSIZZ);
3167 OPENSSL_clear_free(mbuf, BUFSIZZ);
3168 if (proxypass != NULL)
3169 OPENSSL_clear_free(proxypass, strlen(proxypass));
3171 BIO_free(bio_c_out);
3173 BIO_free(bio_c_msg);
3178 static void print_stuff(BIO *bio, SSL *s, int full)
3182 const SSL_CIPHER *c;
3183 int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
3185 #ifndef OPENSSL_NO_COMP
3186 const COMP_METHOD *comp, *expansion;
3188 unsigned char *exportedkeymat;
3189 #ifndef OPENSSL_NO_CT
3190 const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
3194 int got_a_chain = 0;
3196 sk = SSL_get_peer_cert_chain(s);
3200 BIO_printf(bio, "---\nCertificate chain\n");
3201 for (i = 0; i < sk_X509_num(sk); i++) {
3202 BIO_printf(bio, "%2d s:", i);
3203 X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
3204 BIO_puts(bio, "\n");
3205 BIO_printf(bio, " i:");
3206 X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
3207 BIO_puts(bio, "\n");
3209 PEM_write_bio_X509(bio, sk_X509_value(sk, i));
3213 BIO_printf(bio, "---\n");
3214 peer = SSL_get_peer_certificate(s);
3216 BIO_printf(bio, "Server certificate\n");
3218 /* Redundant if we showed the whole chain */
3219 if (!(c_showcerts && got_a_chain))
3220 PEM_write_bio_X509(bio, peer);
3221 dump_cert_text(bio, peer);
3223 BIO_printf(bio, "no peer certificate available\n");
3225 print_ca_names(bio, s);
3227 ssl_print_sigalgs(bio, s);
3228 ssl_print_tmp_key(bio, s);
3230 #ifndef OPENSSL_NO_CT
3232 * When the SSL session is anonymous, or resumed via an abbreviated
3233 * handshake, no SCTs are provided as part of the handshake. While in
3234 * a resumed session SCTs may be present in the session's certificate,
3235 * no callbacks are invoked to revalidate these, and in any case that
3236 * set of SCTs may be incomplete. Thus it makes little sense to
3237 * attempt to display SCTs from a resumed session's certificate, and of
3238 * course none are associated with an anonymous peer.
3240 if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
3241 const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
3242 int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
3244 BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
3245 if (sct_count > 0) {
3246 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
3248 BIO_printf(bio, "---\n");
3249 for (i = 0; i < sct_count; ++i) {
3250 SCT *sct = sk_SCT_value(scts, i);
3252 BIO_printf(bio, "SCT validation status: %s\n",
3253 SCT_validation_status_string(sct));
3254 SCT_print(sct, bio, 0, log_store);
3255 if (i < sct_count - 1)
3256 BIO_printf(bio, "\n---\n");
3258 BIO_printf(bio, "\n");
3264 "---\nSSL handshake has read %ju bytes "
3265 "and written %ju bytes\n",
3266 BIO_number_read(SSL_get_rbio(s)),
3267 BIO_number_written(SSL_get_wbio(s)));
3269 print_verify_detail(s, bio);
3270 BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
3271 c = SSL_get_current_cipher(s);
3272 BIO_printf(bio, "%s, Cipher is %s\n",
3273 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3277 pktmp = X509_get0_pubkey(peer);
3278 BIO_printf(bio, "Server public key is %d bit\n",
3279 EVP_PKEY_bits(pktmp));
3281 BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
3282 SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
3283 #ifndef OPENSSL_NO_COMP
3284 comp = SSL_get_current_compression(s);
3285 expansion = SSL_get_current_expansion(s);
3286 BIO_printf(bio, "Compression: %s\n",
3287 comp ? SSL_COMP_get_name(comp) : "NONE");
3288 BIO_printf(bio, "Expansion: %s\n",
3289 expansion ? SSL_COMP_get_name(expansion) : "NONE");
3291 #ifndef OPENSSL_NO_KTLS
3292 if (BIO_get_ktls_send(SSL_get_wbio(s)))
3293 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3294 if (BIO_get_ktls_recv(SSL_get_rbio(s)))
3295 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3298 if (OSSL_TRACE_ENABLED(TLS)) {
3299 /* Print out local port of connection: useful for debugging */
3301 union BIO_sock_info_u info;
3303 sock = SSL_get_fd(s);
3304 if ((info.addr = BIO_ADDR_new()) != NULL
3305 && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
3306 BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
3307 ntohs(BIO_ADDR_rawport(info.addr)));
3309 BIO_ADDR_free(info.addr);
3312 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3313 if (next_proto.status != -1) {
3314 const unsigned char *proto;
3315 unsigned int proto_len;
3316 SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
3317 BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
3318 BIO_write(bio, proto, proto_len);
3319 BIO_write(bio, "\n", 1);
3323 const unsigned char *proto;
3324 unsigned int proto_len;
3325 SSL_get0_alpn_selected(s, &proto, &proto_len);
3326 if (proto_len > 0) {
3327 BIO_printf(bio, "ALPN protocol: ");
3328 BIO_write(bio, proto, proto_len);
3329 BIO_write(bio, "\n", 1);
3331 BIO_printf(bio, "No ALPN negotiated\n");
3334 #ifndef OPENSSL_NO_SRTP
3336 SRTP_PROTECTION_PROFILE *srtp_profile =
3337 SSL_get_selected_srtp_profile(s);
3340 BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
3341 srtp_profile->name);
3346 switch (SSL_get_early_data_status(s)) {
3347 case SSL_EARLY_DATA_NOT_SENT:
3348 BIO_printf(bio, "Early data was not sent\n");
3351 case SSL_EARLY_DATA_REJECTED:
3352 BIO_printf(bio, "Early data was rejected\n");
3355 case SSL_EARLY_DATA_ACCEPTED:
3356 BIO_printf(bio, "Early data was accepted\n");
3362 * We also print the verify results when we dump session information,
3363 * but in TLSv1.3 we may not get that right away (or at all) depending
3364 * on when we get a NewSessionTicket. Therefore we print it now as well.
3366 verify_result = SSL_get_verify_result(s);
3367 BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
3368 X509_verify_cert_error_string(verify_result));
3370 /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3371 SSL_SESSION_print(bio, SSL_get_session(s));
3374 if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
3375 BIO_printf(bio, "Keying material exporter:\n");
3376 BIO_printf(bio, " Label: '%s'\n", keymatexportlabel);
3377 BIO_printf(bio, " Length: %i bytes\n", keymatexportlen);
3378 exportedkeymat = app_malloc(keymatexportlen, "export key");
3379 if (!SSL_export_keying_material(s, exportedkeymat,
3382 strlen(keymatexportlabel),
3384 BIO_printf(bio, " Error\n");
3386 BIO_printf(bio, " Keying material: ");
3387 for (i = 0; i < keymatexportlen; i++)
3388 BIO_printf(bio, "%02X", exportedkeymat[i]);
3389 BIO_printf(bio, "\n");
3391 OPENSSL_free(exportedkeymat);
3393 BIO_printf(bio, "---\n");
3395 /* flush, or debugging output gets mixed with http response */
3396 (void)BIO_flush(bio);
3399 # ifndef OPENSSL_NO_OCSP
3400 static int ocsp_resp_cb(SSL *s, void *arg)
3402 const unsigned char *p;
3405 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3406 BIO_puts(arg, "OCSP response: ");
3408 BIO_puts(arg, "no response sent\n");
3411 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3413 BIO_puts(arg, "response parse error\n");
3414 BIO_dump_indent(arg, (char *)p, len, 4);
3417 BIO_puts(arg, "\n======================================\n");
3418 OCSP_RESPONSE_print(arg, rsp, 0);
3419 BIO_puts(arg, "======================================\n");
3420 OCSP_RESPONSE_free(rsp);
3425 static int ldap_ExtendedResponse_parse(const char *buf, long rem)
3427 const unsigned char *cur, *end;
3429 int tag, xclass, inf, ret = -1;
3431 cur = (const unsigned char *)buf;
3437 * LDAPMessage ::= SEQUENCE {
3438 * messageID MessageID,
3439 * protocolOp CHOICE {
3441 * extendedResp ExtendedResponse,
3443 * controls [0] Controls OPTIONAL }
3445 * ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3446 * COMPONENTS OF LDAPResult,
3447 * responseName [10] LDAPOID OPTIONAL,
3448 * responseValue [11] OCTET STRING OPTIONAL }
3450 * LDAPResult ::= SEQUENCE {
3451 * resultCode ENUMERATED {
3457 * diagnosticMessage LDAPString,
3458 * referral [3] Referral OPTIONAL }
3462 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3463 if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
3464 (rem = end - cur, len > rem)) {
3465 BIO_printf(bio_err, "Unexpected LDAP response\n");
3469 rem = len; /* ensure that we don't overstep the SEQUENCE */
3471 /* pull MessageID */
3472 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3473 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
3474 (rem = end - cur, len > rem)) {
3475 BIO_printf(bio_err, "No MessageID\n");
3479 cur += len; /* shall we check for MessageId match or just skip? */
3481 /* pull [APPLICATION 24] */
3483 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3484 if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
3486 BIO_printf(bio_err, "Not ExtendedResponse\n");
3490 /* pull resultCode */
3492 inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3493 if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
3494 (rem = end - cur, len > rem)) {
3495 BIO_printf(bio_err, "Not LDAPResult\n");
3499 /* len should always be one, but just in case... */
3500 for (ret = 0, inf = 0; inf < len; inf++) {
3504 /* There is more data, but we don't care... */
3510 * Host dNS Name verifier: used for checking that the hostname is in dNS format
3511 * before setting it as SNI
3513 static int is_dNS_name(const char *host)
3515 const size_t MAX_LABEL_LENGTH = 63;
3518 size_t length = strlen(host);
3519 size_t label_length = 0;
3520 int all_numeric = 1;
3523 * Deviation from strict DNS name syntax, also check names with '_'
3524 * Check DNS name syntax, any '-' or '.' must be internal,
3525 * and on either side of each '.' we can't have a '-' or '.'.
3527 * If the name has just one label, we don't consider it a DNS name.
3529 for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) {
3532 if ((c >= 'a' && c <= 'z')
3533 || (c >= 'A' && c <= 'Z')
3540 if (c >= '0' && c <= '9') {
3545 /* Dot and hyphen cannot be first or last. */
3546 if (i > 0 && i < length - 1) {
3552 * Next to a dot the preceding and following characters must not be
3553 * another dot or a hyphen. Otherwise, record that the name is
3554 * plausible, since it has two or more labels.
3557 && host[i + 1] != '.'
3558 && host[i - 1] != '-'
3559 && host[i + 1] != '-') {
3569 /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
3570 isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH);
3574 #endif /* OPENSSL_NO_SOCK */