2 * Copyright 1995-2025 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"
19 #include "internal/sockets.h" /* for openssl_fdset() */
21 #ifndef OPENSSL_NO_SOCK
24 * With IPv6, it looks like Digital has mixed up the proper order of
25 * recursive header file inclusion, resulting in the compiler complaining
26 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
27 * needed to have fileno() declared correctly... So let's define u_int
29 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
31 typedef unsigned int u_int
;
36 #include <openssl/x509.h>
37 #include <openssl/ssl.h>
38 #include <openssl/err.h>
39 #include <openssl/pem.h>
40 #include <openssl/rand.h>
41 #include <openssl/ocsp.h>
42 #include <openssl/bn.h>
43 #include <openssl/trace.h>
44 #include <openssl/async.h>
46 # include <openssl/ct.h>
50 #include "internal/sockets.h"
52 #if defined(__has_feature)
53 # if __has_feature(memory_sanitizer)
54 # include <sanitizer/msan_interface.h>
59 #define BUFSIZZ 1024*16
60 #define S_CLIENT_IRC_READ_TIMEOUT 8
62 #define USER_DATA_MODE_NONE 0
63 #define USER_DATA_MODE_BASIC 1
64 #define USER_DATA_MODE_ADVANCED 2
66 #define USER_DATA_PROCESS_BAD_ARGUMENT 0
67 #define USER_DATA_PROCESS_SHUT 1
68 #define USER_DATA_PROCESS_RESTART 2
69 #define USER_DATA_PROCESS_NO_DATA 3
70 #define USER_DATA_PROCESS_CONTINUE 4
73 /* SSL connection we are processing commands for */
76 /* Buffer where we are storing data supplied by the user */
79 /* Allocated size of the buffer */
82 /* Amount of the buffer actually used */
85 /* Current location in the buffer where we will read from next*/
88 /* The mode we are using for processing commands */
91 /* Whether FIN has ben sent on the stream */
95 static void user_data_init(struct user_data_st
*user_data
, SSL
*con
, char *buf
,
96 size_t bufmax
, int mode
);
97 static int user_data_add(struct user_data_st
*user_data
, size_t i
);
98 static int user_data_process(struct user_data_st
*user_data
, size_t *len
,
100 static int user_data_has_data(struct user_data_st
*user_data
);
103 static int c_debug
= 0;
104 static int c_showcerts
= 0;
105 static char *keymatexportlabel
= NULL
;
106 static int keymatexportlen
= 20;
107 static BIO
*bio_c_out
= NULL
;
108 static int c_quiet
= 0;
109 static char *sess_out
= NULL
;
110 static SSL_SESSION
*psksess
= NULL
;
112 static void print_stuff(BIO
*berr
, SSL
*con
, int full
);
113 #ifndef OPENSSL_NO_OCSP
114 static int ocsp_resp_cb(SSL
*s
, void *arg
);
116 static int ldap_ExtendedResponse_parse(const char *buf
, long rem
);
117 static int is_dNS_name(const char *host
);
119 static const unsigned char cert_type_rpk
[] = { TLSEXT_cert_type_rpk
, TLSEXT_cert_type_x509
};
120 static int enable_server_rpk
= 0;
122 static int saved_errno
;
124 static void save_errno(void)
130 static int restore_errno(void)
137 /* Default PSK identity and key */
138 static char *psk_identity
= "Client_identity";
140 #ifndef OPENSSL_NO_PSK
141 static unsigned int psk_client_cb(SSL
*ssl
, const char *hint
, char *identity
,
142 unsigned int max_identity_len
,
144 unsigned int max_psk_len
)
151 BIO_printf(bio_c_out
, "psk_client_cb\n");
153 /* no ServerKeyExchange message */
155 BIO_printf(bio_c_out
,
156 "NULL received PSK identity hint, continuing anyway\n");
157 } else if (c_debug
) {
158 BIO_printf(bio_c_out
, "Received PSK identity hint '%s'\n", hint
);
162 * lookup PSK identity and PSK key based on the given identity hint here
164 ret
= BIO_snprintf(identity
, max_identity_len
, "%s", psk_identity
);
165 if (ret
< 0 || (unsigned int)ret
> max_identity_len
)
168 BIO_printf(bio_c_out
, "created identity '%s' len=%d\n", identity
,
171 /* convert the PSK key to binary */
172 key
= OPENSSL_hexstr2buf(psk_key
, &key_len
);
174 BIO_printf(bio_err
, "Could not convert PSK key '%s' to buffer\n",
178 if (max_psk_len
> INT_MAX
|| key_len
> (long)max_psk_len
) {
180 "psk buffer of callback is too small (%d) for key (%ld)\n",
181 max_psk_len
, key_len
);
186 memcpy(psk
, key
, key_len
);
190 BIO_printf(bio_c_out
, "created PSK len=%ld\n", key_len
);
195 BIO_printf(bio_err
, "Error in PSK client callback\n");
200 const unsigned char tls13_aes128gcmsha256_id
[] = { 0x13, 0x01 };
201 const unsigned char tls13_aes256gcmsha384_id
[] = { 0x13, 0x02 };
203 static int psk_use_session_cb(SSL
*s
, const EVP_MD
*md
,
204 const unsigned char **id
, size_t *idlen
,
207 SSL_SESSION
*usesess
= NULL
;
208 const SSL_CIPHER
*cipher
= NULL
;
210 if (psksess
!= NULL
) {
211 if (!SSL_SESSION_up_ref(psksess
))
216 unsigned char *key
= OPENSSL_hexstr2buf(psk_key
, &key_len
);
219 BIO_printf(bio_err
, "Could not convert PSK key '%s' to buffer\n",
224 /* We default to SHA-256 */
225 cipher
= SSL_CIPHER_find(s
, tls13_aes128gcmsha256_id
);
226 if (cipher
== NULL
) {
227 BIO_printf(bio_err
, "Error finding suitable ciphersuite\n");
232 usesess
= SSL_SESSION_new();
234 || !SSL_SESSION_set1_master_key(usesess
, key
, key_len
)
235 || !SSL_SESSION_set_cipher(usesess
, cipher
)
236 || !SSL_SESSION_set_protocol_version(usesess
, TLS1_3_VERSION
)) {
243 cipher
= SSL_SESSION_get0_cipher(usesess
);
247 if (md
!= NULL
&& SSL_CIPHER_get_handshake_digest(cipher
) != md
) {
248 /* PSK not usable, ignore it */
252 SSL_SESSION_free(usesess
);
255 *id
= (unsigned char *)psk_identity
;
256 *idlen
= strlen(psk_identity
);
262 SSL_SESSION_free(usesess
);
266 /* This is a context that we pass to callbacks */
267 typedef struct tlsextctx_st
{
272 static int ssl_servername_cb(SSL
*s
, int *ad
, void *arg
)
274 tlsextctx
*p
= (tlsextctx
*) arg
;
275 const char *hn
= SSL_get_servername(s
, TLSEXT_NAMETYPE_host_name
);
276 if (SSL_get_servername_type(s
) != -1)
277 p
->ack
= !SSL_session_reused(s
) && hn
!= NULL
;
279 BIO_printf(bio_err
, "Can't use SSL_get_servername\n");
281 return SSL_TLSEXT_ERR_OK
;
284 #ifndef OPENSSL_NO_NEXTPROTONEG
285 /* This the context that we pass to next_proto_cb */
286 typedef struct tlsextnextprotoctx_st
{
290 } tlsextnextprotoctx
;
292 static tlsextnextprotoctx next_proto
;
294 static int next_proto_cb(SSL
*s
, unsigned char **out
, unsigned char *outlen
,
295 const unsigned char *in
, unsigned int inlen
,
298 tlsextnextprotoctx
*ctx
= arg
;
301 /* We can assume that |in| is syntactically valid. */
303 BIO_printf(bio_c_out
, "Protocols advertised by server: ");
304 for (i
= 0; i
< inlen
;) {
306 BIO_write(bio_c_out
, ", ", 2);
307 BIO_write(bio_c_out
, &in
[i
+ 1], in
[i
]);
310 BIO_write(bio_c_out
, "\n", 1);
314 SSL_select_next_proto(out
, outlen
, in
, inlen
,
315 ctx
->data
, (unsigned int)ctx
->len
);
316 return SSL_TLSEXT_ERR_OK
;
318 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
320 static int serverinfo_cli_parse_cb(SSL
*s
, unsigned int ext_type
,
321 const unsigned char *in
, size_t inlen
,
325 unsigned char ext_buf
[4 + 65536];
327 /* Reconstruct the type/len fields prior to extension data */
328 inlen
&= 0xffff; /* for formal memcmpy correctness */
329 ext_buf
[0] = (unsigned char)(ext_type
>> 8);
330 ext_buf
[1] = (unsigned char)(ext_type
);
331 ext_buf
[2] = (unsigned char)(inlen
>> 8);
332 ext_buf
[3] = (unsigned char)(inlen
);
333 memcpy(ext_buf
+ 4, in
, inlen
);
335 BIO_snprintf(pem_name
, sizeof(pem_name
), "SERVERINFO FOR EXTENSION %d",
337 PEM_write_bio(bio_c_out
, pem_name
, "", ext_buf
, (long)(4 + inlen
));
342 * Hex decoder that tolerates optional whitespace. Returns number of bytes
343 * produced, advances inptr to end of input string.
345 static ossl_ssize_t
hexdecode(const char **inptr
, void *result
)
347 unsigned char **out
= (unsigned char **)result
;
348 const char *in
= *inptr
;
349 unsigned char *ret
= app_malloc(strlen(in
) / 2, "hexdecode");
350 unsigned char *cp
= ret
;
357 for (byte
= 0; *in
; ++in
) {
360 if (isspace(_UC(*in
)))
362 x
= OPENSSL_hexchar2int(*in
);
368 if ((nibble
^= 1) == 0) {
381 return cp
- (*out
= ret
);
385 * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
386 * inptr to next field skipping leading whitespace.
388 static ossl_ssize_t
checked_uint8(const char **inptr
, void *out
)
390 uint8_t *result
= (uint8_t *)out
;
391 const char *in
= *inptr
;
397 v
= strtol(in
, &endp
, 10);
400 if (((v
== LONG_MIN
|| v
== LONG_MAX
) && e
== ERANGE
) ||
401 endp
== in
|| !isspace(_UC(*endp
)) ||
402 v
!= (*result
= (uint8_t) v
)) {
405 for (in
= endp
; isspace(_UC(*in
)); ++in
)
415 ossl_ssize_t (*parser
)(const char **, void *);
418 static int tlsa_import_rr(SSL
*con
, const char *rrdata
)
420 /* Not necessary to re-init these values; the "parsers" do that. */
421 static uint8_t usage
;
422 static uint8_t selector
;
423 static uint8_t mtype
;
424 static unsigned char *data
;
425 static struct tlsa_field tlsa_fields
[] = {
426 { &usage
, "usage", checked_uint8
},
427 { &selector
, "selector", checked_uint8
},
428 { &mtype
, "mtype", checked_uint8
},
429 { &data
, "data", hexdecode
},
432 struct tlsa_field
*f
;
434 const char *cp
= rrdata
;
435 ossl_ssize_t len
= 0;
437 for (f
= tlsa_fields
; f
->var
; ++f
) {
438 /* Returns number of bytes produced, advances cp to next field */
439 if ((len
= f
->parser(&cp
, f
->var
)) <= 0) {
440 BIO_printf(bio_err
, "%s: warning: bad TLSA %s field in: %s\n",
441 prog
, f
->name
, rrdata
);
445 /* The data field is last, so len is its length */
446 ret
= SSL_dane_tlsa_add(con
, usage
, selector
, mtype
, data
, len
);
450 ERR_print_errors(bio_err
);
451 BIO_printf(bio_err
, "%s: warning: unusable TLSA rrdata: %s\n",
456 ERR_print_errors(bio_err
);
457 BIO_printf(bio_err
, "%s: warning: error loading TLSA rrdata: %s\n",
464 static int tlsa_import_rrset(SSL
*con
, STACK_OF(OPENSSL_STRING
) *rrset
)
466 int num
= sk_OPENSSL_STRING_num(rrset
);
470 for (i
= 0; i
< num
; ++i
) {
471 char *rrdata
= sk_OPENSSL_STRING_value(rrset
, i
);
472 if (tlsa_import_rr(con
, rrdata
) > 0)
478 typedef enum OPTION_choice
{
480 OPT_4
, OPT_6
, OPT_HOST
, OPT_PORT
, OPT_CONNECT
, OPT_BIND
, OPT_UNIX
,
481 OPT_XMPPHOST
, OPT_VERIFY
, OPT_NAMEOPT
,
482 OPT_CERT
, OPT_CRL
, OPT_CRL_DOWNLOAD
, OPT_SESS_OUT
, OPT_SESS_IN
,
483 OPT_CERTFORM
, OPT_CRLFORM
, OPT_VERIFY_RET_ERROR
, OPT_VERIFY_QUIET
,
484 OPT_BRIEF
, OPT_PREXIT
, OPT_NO_INTERACTIVE
, OPT_CRLF
, OPT_QUIET
, OPT_NBIO
,
485 OPT_SSL_CLIENT_ENGINE
, OPT_IGN_EOF
, OPT_NO_IGN_EOF
,
486 OPT_DEBUG
, OPT_TLSEXTDEBUG
, OPT_STATUS
, OPT_WDEBUG
,
487 OPT_MSG
, OPT_MSGFILE
, OPT_ENGINE
, OPT_TRACE
, OPT_SECURITY_DEBUG
,
488 OPT_SECURITY_DEBUG_VERBOSE
, OPT_SHOWCERTS
, OPT_NBIO_TEST
, OPT_STATE
,
489 OPT_PSK_IDENTITY
, OPT_PSK
, OPT_PSK_SESS
,
490 #ifndef OPENSSL_NO_SRP
491 OPT_SRPUSER
, OPT_SRPPASS
, OPT_SRP_STRENGTH
, OPT_SRP_LATEUSER
,
494 OPT_SSL3
, OPT_SSL_CONFIG
,
495 OPT_TLS1_3
, OPT_TLS1_2
, OPT_TLS1_1
, OPT_TLS1
, OPT_DTLS
, OPT_DTLS1
,
496 OPT_DTLS1_2
, OPT_QUIC
, OPT_SCTP
, OPT_TIMEOUT
, OPT_MTU
, OPT_KEYFORM
,
497 OPT_PASS
, OPT_CERT_CHAIN
, OPT_KEY
, OPT_RECONNECT
, OPT_BUILD_CHAIN
,
498 OPT_NEXTPROTONEG
, OPT_ALPN
,
499 OPT_CAPATH
, OPT_NOCAPATH
, OPT_CHAINCAPATH
, OPT_VERIFYCAPATH
,
500 OPT_CAFILE
, OPT_NOCAFILE
, OPT_CHAINCAFILE
, OPT_VERIFYCAFILE
,
501 OPT_CASTORE
, OPT_NOCASTORE
, OPT_CHAINCASTORE
, OPT_VERIFYCASTORE
,
502 OPT_SERVERINFO
, OPT_STARTTLS
, OPT_SERVERNAME
, OPT_NOSERVERNAME
, OPT_ASYNC
,
503 OPT_USE_SRTP
, OPT_KEYMATEXPORT
, OPT_KEYMATEXPORTLEN
, OPT_PROTOHOST
,
504 OPT_MAXFRAGLEN
, OPT_MAX_SEND_FRAG
, OPT_SPLIT_SEND_FRAG
, OPT_MAX_PIPELINES
,
505 OPT_READ_BUF
, OPT_KEYLOG_FILE
, OPT_EARLY_DATA
, OPT_REQCAFILE
,
509 OPT_S_ENUM
, OPT_IGNORE_UNEXPECTED_EOF
,
510 OPT_FALLBACKSCSV
, OPT_NOCMDS
, OPT_ADV
, OPT_PROXY
, OPT_PROXY_USER
,
511 OPT_PROXY_PASS
, OPT_DANE_TLSA_DOMAIN
,
512 #ifndef OPENSSL_NO_CT
513 OPT_CT
, OPT_NOCT
, OPT_CTLOG_FILE
,
515 OPT_DANE_TLSA_RRDATA
, OPT_DANE_EE_NO_NAME
,
517 OPT_ENABLE_SERVER_RPK
,
518 OPT_ENABLE_CLIENT_RPK
,
521 OPT_R_ENUM
, OPT_PROV_ENUM
524 const OPTIONS s_client_options
[] = {
525 {OPT_HELP_STR
, 1, '-', "Usage: %s [options] [host:port]\n"},
527 OPT_SECTION("General"),
528 {"help", OPT_HELP
, '-', "Display this summary"},
529 #ifndef OPENSSL_NO_ENGINE
530 {"engine", OPT_ENGINE
, 's', "Use engine, possibly a hardware device"},
531 {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE
, 's',
532 "Specify engine to be used for client certificate operations"},
534 {"ssl_config", OPT_SSL_CONFIG
, 's', "Use specified section for SSL_CTX configuration"},
535 #ifndef OPENSSL_NO_CT
536 {"ct", OPT_CT
, '-', "Request and parse SCTs (also enables OCSP stapling)"},
537 {"noct", OPT_NOCT
, '-', "Do not request or parse SCTs (default)"},
538 {"ctlogfile", OPT_CTLOG_FILE
, '<', "CT log list CONF file"},
541 OPT_SECTION("Network"),
542 {"host", OPT_HOST
, 's', "Use -connect instead"},
543 {"port", OPT_PORT
, 'p', "Use -connect instead"},
544 {"connect", OPT_CONNECT
, 's',
545 "TCP/IP where to connect; default: " PORT
")"},
546 {"bind", OPT_BIND
, 's', "bind local address for connection"},
547 {"proxy", OPT_PROXY
, 's',
548 "Connect to via specified proxy to the real server"},
549 {"proxy_user", OPT_PROXY_USER
, 's', "UserID for proxy authentication"},
550 {"proxy_pass", OPT_PROXY_PASS
, 's', "Proxy authentication password source"},
552 {"unix", OPT_UNIX
, 's', "Connect over the specified Unix-domain socket"},
554 {"4", OPT_4
, '-', "Use IPv4 only"},
556 {"6", OPT_6
, '-', "Use IPv6 only"},
558 {"maxfraglen", OPT_MAXFRAGLEN
, 'p',
559 "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
560 {"max_send_frag", OPT_MAX_SEND_FRAG
, 'p', "Maximum Size of send frames "},
561 {"split_send_frag", OPT_SPLIT_SEND_FRAG
, 'p',
562 "Size used to split data for encrypt pipelines"},
563 {"max_pipelines", OPT_MAX_PIPELINES
, 'p',
564 "Maximum number of encrypt/decrypt pipelines to be used"},
565 {"read_buf", OPT_READ_BUF
, 'p',
566 "Default read buffer size to be used for connections"},
567 {"fallback_scsv", OPT_FALLBACKSCSV
, '-', "Send the fallback SCSV"},
569 OPT_SECTION("Identity"),
570 {"cert", OPT_CERT
, '<', "Client certificate file to use"},
571 {"certform", OPT_CERTFORM
, 'F',
572 "Client certificate file format (PEM/DER/P12); has no effect"},
573 {"cert_chain", OPT_CERT_CHAIN
, '<',
574 "Client certificate chain file (in PEM format)"},
575 {"build_chain", OPT_BUILD_CHAIN
, '-', "Build client certificate chain"},
576 {"key", OPT_KEY
, 's', "Private key file to use; default: -cert file"},
577 {"keyform", OPT_KEYFORM
, 'E', "Key format (ENGINE, other values ignored)"},
578 {"pass", OPT_PASS
, 's', "Private key and cert file pass phrase source"},
579 {"verify", OPT_VERIFY
, 'p', "Turn on peer certificate verification"},
580 {"nameopt", OPT_NAMEOPT
, 's', "Certificate subject/issuer name printing options"},
581 {"CApath", OPT_CAPATH
, '/', "PEM format directory of CA's"},
582 {"CAfile", OPT_CAFILE
, '<', "PEM format file of CA's"},
583 {"CAstore", OPT_CASTORE
, ':', "URI to store of CA's"},
584 {"no-CAfile", OPT_NOCAFILE
, '-',
585 "Do not load the default certificates file"},
586 {"no-CApath", OPT_NOCAPATH
, '-',
587 "Do not load certificates from the default certificates directory"},
588 {"no-CAstore", OPT_NOCASTORE
, '-',
589 "Do not load certificates from the default certificates store"},
590 {"requestCAfile", OPT_REQCAFILE
, '<',
591 "PEM format file of CA names to send to the server"},
592 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
593 {"tfo", OPT_TFO
, '-', "Connect using TCP Fast Open"},
595 {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN
, 's', "DANE TLSA base domain"},
596 {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA
, 's',
597 "DANE TLSA rrdata presentation form"},
598 {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME
, '-',
599 "Disable name checks when matching DANE-EE(3) TLSA records"},
600 {"psk_identity", OPT_PSK_IDENTITY
, 's', "PSK identity"},
601 {"psk", OPT_PSK
, 's', "PSK in hex (without 0x)"},
602 {"psk_session", OPT_PSK_SESS
, '<', "File to read PSK SSL session from"},
603 {"name", OPT_PROTOHOST
, 's',
604 "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
606 OPT_SECTION("Session"),
607 {"reconnect", OPT_RECONNECT
, '-',
608 "Drop and re-make the connection with the same Session-ID"},
609 {"sess_out", OPT_SESS_OUT
, '>', "File to write SSL session to"},
610 {"sess_in", OPT_SESS_IN
, '<', "File to read SSL session from"},
612 OPT_SECTION("Input/Output"),
613 {"crlf", OPT_CRLF
, '-', "Convert LF from terminal into CRLF"},
614 {"quiet", OPT_QUIET
, '-', "No s_client output"},
615 {"ign_eof", OPT_IGN_EOF
, '-', "Ignore input eof (default when -quiet)"},
616 {"no_ign_eof", OPT_NO_IGN_EOF
, '-', "Don't ignore input eof"},
617 {"starttls", OPT_STARTTLS
, 's',
618 "Use the appropriate STARTTLS command before starting TLS"},
619 {"xmpphost", OPT_XMPPHOST
, 's',
620 "Alias of -name option for \"-starttls xmpp[-server]\""},
621 {"brief", OPT_BRIEF
, '-',
622 "Restrict output to brief summary of connection parameters"},
623 {"prexit", OPT_PREXIT
, '-',
624 "Print session information when the program exits"},
625 {"no-interactive", OPT_NO_INTERACTIVE
, '-',
626 "Don't run the client in the interactive mode"},
628 OPT_SECTION("Debug"),
629 {"showcerts", OPT_SHOWCERTS
, '-',
630 "Show all certificates sent by the server"},
631 {"debug", OPT_DEBUG
, '-', "Extra output"},
632 {"msg", OPT_MSG
, '-', "Show protocol messages"},
633 {"msgfile", OPT_MSGFILE
, '>',
634 "File to send output of -msg or -trace, instead of stdout"},
635 {"nbio_test", OPT_NBIO_TEST
, '-', "More ssl protocol testing"},
636 {"state", OPT_STATE
, '-', "Print the ssl states"},
637 {"keymatexport", OPT_KEYMATEXPORT
, 's',
638 "Export keying material using label"},
639 {"keymatexportlen", OPT_KEYMATEXPORTLEN
, 'p',
640 "Export len bytes of keying material; default 20"},
641 {"security_debug", OPT_SECURITY_DEBUG
, '-',
642 "Enable security debug messages"},
643 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE
, '-',
644 "Output more security debug output"},
645 #ifndef OPENSSL_NO_SSL_TRACE
646 {"trace", OPT_TRACE
, '-', "Show trace output of protocol messages"},
649 {"wdebug", OPT_WDEBUG
, '-', "WATT-32 tcp debugging"},
651 {"keylogfile", OPT_KEYLOG_FILE
, '>', "Write TLS secrets to file"},
652 {"nocommands", OPT_NOCMDS
, '-', "Do not use interactive command letters"},
653 {"adv", OPT_ADV
, '-', "Advanced command mode"},
654 {"servername", OPT_SERVERNAME
, 's',
655 "Set TLS extension servername (SNI) in ClientHello (default)"},
656 {"noservername", OPT_NOSERVERNAME
, '-',
657 "Do not send the server name (SNI) extension in the ClientHello"},
658 {"tlsextdebug", OPT_TLSEXTDEBUG
, '-',
659 "Hex dump of all TLS extensions received"},
660 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF
, '-',
661 "Do not treat lack of close_notify from a peer as an error"},
662 #ifndef OPENSSL_NO_OCSP
663 {"status", OPT_STATUS
, '-', "Request certificate status from server"},
665 {"serverinfo", OPT_SERVERINFO
, 's',
666 "types Send empty ClientHello extensions (comma-separated numbers)"},
667 {"alpn", OPT_ALPN
, 's',
668 "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
669 {"async", OPT_ASYNC
, '-', "Support asynchronous operation"},
670 {"nbio", OPT_NBIO
, '-', "Use non-blocking IO"},
672 OPT_SECTION("Protocol and version"),
673 #ifndef OPENSSL_NO_SSL3
674 {"ssl3", OPT_SSL3
, '-', "Just use SSLv3"},
676 #ifndef OPENSSL_NO_TLS1
677 {"tls1", OPT_TLS1
, '-', "Just use TLSv1"},
679 #ifndef OPENSSL_NO_TLS1_1
680 {"tls1_1", OPT_TLS1_1
, '-', "Just use TLSv1.1"},
682 #ifndef OPENSSL_NO_TLS1_2
683 {"tls1_2", OPT_TLS1_2
, '-', "Just use TLSv1.2"},
685 #ifndef OPENSSL_NO_TLS1_3
686 {"tls1_3", OPT_TLS1_3
, '-', "Just use TLSv1.3"},
688 #ifndef OPENSSL_NO_DTLS
689 {"dtls", OPT_DTLS
, '-', "Use any version of DTLS"},
690 {"quic", OPT_QUIC
, '-', "Use QUIC"},
691 {"timeout", OPT_TIMEOUT
, '-',
692 "Enable send/receive timeout on DTLS connections"},
693 {"mtu", OPT_MTU
, 'p', "Set the link layer MTU"},
695 #ifndef OPENSSL_NO_DTLS1
696 {"dtls1", OPT_DTLS1
, '-', "Just use DTLSv1"},
698 #ifndef OPENSSL_NO_DTLS1_2
699 {"dtls1_2", OPT_DTLS1_2
, '-', "Just use DTLSv1.2"},
701 #ifndef OPENSSL_NO_SCTP
702 {"sctp", OPT_SCTP
, '-', "Use SCTP"},
703 {"sctp_label_bug", OPT_SCTP_LABEL_BUG
, '-', "Enable SCTP label length bug"},
705 #ifndef OPENSSL_NO_NEXTPROTONEG
706 {"nextprotoneg", OPT_NEXTPROTONEG
, 's',
707 "Enable NPN extension, considering named protocols supported (comma-separated list)"},
709 {"early_data", OPT_EARLY_DATA
, '<', "File to send as early data"},
710 {"enable_pha", OPT_ENABLE_PHA
, '-', "Enable post-handshake-authentication"},
711 {"enable_server_rpk", OPT_ENABLE_SERVER_RPK
, '-', "Enable raw public keys (RFC7250) from the server"},
712 {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK
, '-', "Enable raw public keys (RFC7250) from the client"},
713 #ifndef OPENSSL_NO_SRTP
714 {"use_srtp", OPT_USE_SRTP
, 's',
715 "Offer SRTP key management with a colon-separated profile list"},
717 #ifndef OPENSSL_NO_SRP
718 {"srpuser", OPT_SRPUSER
, 's', "(deprecated) SRP authentication for 'user'"},
719 {"srppass", OPT_SRPPASS
, 's', "(deprecated) Password for 'user'"},
720 {"srp_lateuser", OPT_SRP_LATEUSER
, '-',
721 "(deprecated) SRP username into second ClientHello message"},
722 {"srp_moregroups", OPT_SRP_MOREGROUPS
, '-',
723 "(deprecated) Tolerate other than the known g N values."},
724 {"srp_strength", OPT_SRP_STRENGTH
, 'p',
725 "(deprecated) Minimal length in bits for N"},
727 #ifndef OPENSSL_NO_KTLS
728 {"ktls", OPT_KTLS
, '-', "Enable Kernel TLS for sending and receiving"},
734 {"CRL", OPT_CRL
, '<', "CRL file to use"},
735 {"crl_download", OPT_CRL_DOWNLOAD
, '-', "Download CRL from distribution points"},
736 {"CRLform", OPT_CRLFORM
, 'F', "CRL format (PEM or DER); default PEM"},
737 {"verify_return_error", OPT_VERIFY_RET_ERROR
, '-',
738 "Close connection on verification error"},
739 {"verify_quiet", OPT_VERIFY_QUIET
, '-', "Restrict verify output to errors"},
740 {"chainCAfile", OPT_CHAINCAFILE
, '<',
741 "CA file for certificate chain (PEM format)"},
742 {"chainCApath", OPT_CHAINCAPATH
, '/',
743 "Use dir as certificate store path to build CA certificate chain"},
744 {"chainCAstore", OPT_CHAINCASTORE
, ':',
745 "CA store URI for certificate chain"},
746 {"verifyCAfile", OPT_VERIFYCAFILE
, '<',
747 "CA file for certificate verification (PEM format)"},
748 {"verifyCApath", OPT_VERIFYCAPATH
, '/',
749 "Use dir as certificate store path to verify CA certificate"},
750 {"verifyCAstore", OPT_VERIFYCASTORE
, ':',
751 "CA store URI for certificate verification"},
756 {"host:port", 0, 0, "Where to connect; same as -connect option"},
760 typedef enum PROTOCOL_choice
{
778 static const OPT_PAIR services
[] = {
779 {"smtp", PROTO_SMTP
},
780 {"pop3", PROTO_POP3
},
781 {"imap", PROTO_IMAP
},
783 {"xmpp", PROTO_XMPP
},
784 {"xmpp-server", PROTO_XMPP_SERVER
},
785 {"telnet", PROTO_TELNET
},
787 {"mysql", PROTO_MYSQL
},
788 {"postgres", PROTO_POSTGRES
},
789 {"lmtp", PROTO_LMTP
},
790 {"nntp", PROTO_NNTP
},
791 {"sieve", PROTO_SIEVE
},
792 {"ldap", PROTO_LDAP
},
796 #define IS_INET_FLAG(o) \
797 (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
798 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
800 #define IS_PROT_FLAG(o) \
801 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
802 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2 \
805 /* Free |*dest| and optionally set it to a copy of |source|. */
806 static void freeandcopy(char **dest
, const char *source
)
811 *dest
= OPENSSL_strdup(source
);
814 static int new_session_cb(SSL
*s
, SSL_SESSION
*sess
)
817 if (sess_out
!= NULL
) {
818 BIO
*stmp
= BIO_new_file(sess_out
, "w");
821 BIO_printf(bio_err
, "Error writing session file %s\n", sess_out
);
823 PEM_write_bio_SSL_SESSION(stmp
, sess
);
829 * Session data gets dumped on connection for TLSv1.2 and below, and on
830 * arrival of the NewSessionTicket for TLSv1.3.
832 if (SSL_version(s
) == TLS1_3_VERSION
) {
833 BIO_printf(bio_c_out
,
834 "---\nPost-Handshake New Session Ticket arrived:\n");
835 SSL_SESSION_print(bio_c_out
, sess
);
836 BIO_printf(bio_c_out
, "---\n");
840 * We always return a "fail" response so that the session gets freed again
841 * because we haven't used the reference.
846 int s_client_main(int argc
, char **argv
)
849 EVP_PKEY
*key
= NULL
;
852 STACK_OF(X509
) *chain
= NULL
;
854 X509_VERIFY_PARAM
*vpm
= NULL
;
855 SSL_EXCERT
*exc
= NULL
;
856 SSL_CONF_CTX
*cctx
= NULL
;
857 STACK_OF(OPENSSL_STRING
) *ssl_args
= NULL
;
858 char *dane_tlsa_domain
= NULL
;
859 STACK_OF(OPENSSL_STRING
) *dane_tlsa_rrset
= NULL
;
860 int dane_ee_no_name
= 0;
861 STACK_OF(X509_CRL
) *crls
= NULL
;
862 const SSL_METHOD
*meth
= TLS_client_method();
863 const char *CApath
= NULL
, *CAfile
= NULL
, *CAstore
= NULL
;
864 char *cbuf
= NULL
, *sbuf
= NULL
, *mbuf
= NULL
;
865 char *proxystr
= NULL
, *proxyuser
= NULL
;
866 char *proxypassarg
= NULL
, *proxypass
= NULL
;
867 char *connectstr
= NULL
, *bindstr
= NULL
;
868 char *cert_file
= NULL
, *key_file
= NULL
, *chain_file
= NULL
;
869 char *chCApath
= NULL
, *chCAfile
= NULL
, *chCAstore
= NULL
, *host
= NULL
;
870 char *thost
= NULL
, *tport
= NULL
;
872 char *bindhost
= NULL
, *bindport
= NULL
;
873 char *passarg
= NULL
, *pass
= NULL
;
874 char *vfyCApath
= NULL
, *vfyCAfile
= NULL
, *vfyCAstore
= NULL
;
875 char *ReqCAfile
= NULL
;
876 char *sess_in
= NULL
, *crl_file
= NULL
, *p
;
877 const char *protohost
= NULL
;
878 struct timeval timeout
, *timeoutp
;
879 fd_set readfds
, writefds
;
880 int noCApath
= 0, noCAfile
= 0, noCAstore
= 0;
881 int build_chain
= 0, cert_format
= FORMAT_UNDEF
;
882 size_t cbuf_len
, cbuf_off
;
883 int key_format
= FORMAT_UNDEF
, crlf
= 0, full_log
= 1, mbuf_len
= 0;
885 int nointeractive
= 0;
887 int reconnect
= 0, verify
= SSL_VERIFY_NONE
, vpmtouched
= 0;
888 int ret
= 1, in_init
= 1, i
, nbio_test
= 0, sock
= -1, k
, width
, state
= 0;
889 int sbuf_len
, sbuf_off
, cmdmode
= USER_DATA_MODE_BASIC
;
890 int socket_family
= AF_UNSPEC
, socket_type
= SOCK_STREAM
, protocol
= 0;
891 int starttls_proto
= PROTO_OFF
, crl_format
= FORMAT_UNDEF
, crl_download
= 0;
892 int write_tty
, read_tty
, write_ssl
, read_ssl
, tty_on
, ssl_pending
;
894 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
897 int read_buf_len
= 0;
898 int fallback_scsv
= 0;
900 #ifndef OPENSSL_NO_DTLS
901 int enable_timeouts
= 0;
904 #ifndef OPENSSL_NO_ENGINE
905 ENGINE
*ssl_client_engine
= NULL
;
908 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
911 const char *servername
= NULL
;
912 char *sname_alloc
= NULL
;
913 int noservername
= 0;
914 const char *alpn_in
= NULL
;
915 tlsextctx tlsextcbp
= { NULL
, 0 };
916 const char *ssl_config
= NULL
;
917 #define MAX_SI_TYPES 100
918 unsigned short serverinfo_types
[MAX_SI_TYPES
];
919 int serverinfo_count
= 0, start
= 0, len
;
920 #ifndef OPENSSL_NO_NEXTPROTONEG
921 const char *next_proto_neg_in
= NULL
;
923 #ifndef OPENSSL_NO_SRP
924 char *srppass
= NULL
;
925 int srp_lateuser
= 0;
926 SRP_ARG srp_arg
= { NULL
, NULL
, 0, 0, 0, 1024 };
928 #ifndef OPENSSL_NO_SRTP
929 char *srtp_profiles
= NULL
;
931 #ifndef OPENSSL_NO_CT
932 char *ctlog_file
= NULL
;
933 int ct_validation
= 0;
935 int min_version
= 0, max_version
= 0, prot_opt
= 0, no_prot_opt
= 0;
937 unsigned int max_send_fragment
= 0;
938 unsigned int split_send_fragment
= 0, max_pipelines
= 0;
939 enum { use_inet
, use_unix
, use_unknown
} connect_type
= use_unknown
;
941 uint8_t maxfraglen
= 0;
942 int c_nbio
= 0, c_msg
= 0, c_ign_eof
= 0, c_brief
= 0;
943 int c_tlsextdebug
= 0;
944 #ifndef OPENSSL_NO_OCSP
945 int c_status_req
= 0;
947 BIO
*bio_c_msg
= NULL
;
948 const char *keylog_file
= NULL
, *early_data_file
= NULL
;
949 int isdtls
= 0, isquic
= 0;
950 char *psksessf
= NULL
;
952 int enable_client_rpk
= 0;
953 #ifndef OPENSSL_NO_SCTP
954 int sctp_label_bug
= 0;
956 int ignore_unexpected_eof
= 0;
957 #ifndef OPENSSL_NO_KTLS
962 BIO_ADDR
*peer_addr
= NULL
;
963 struct user_data_st user_data
;
967 /* Known false-positive of MemorySanitizer. */
968 #if defined(__has_feature)
969 # if __has_feature(memory_sanitizer)
970 __msan_unpoison(&readfds
, sizeof(readfds
));
971 __msan_unpoison(&writefds
, sizeof(writefds
));
979 port
= OPENSSL_strdup(PORT
);
980 vpm
= X509_VERIFY_PARAM_new();
981 cctx
= SSL_CONF_CTX_new();
983 if (port
== NULL
|| vpm
== NULL
|| cctx
== NULL
) {
984 BIO_printf(bio_err
, "%s: out of memory\n", opt_getprog());
988 cbuf
= app_malloc(BUFSIZZ
, "cbuf");
989 sbuf
= app_malloc(BUFSIZZ
, "sbuf");
990 mbuf
= app_malloc(BUFSIZZ
, "mbuf");
992 SSL_CONF_CTX_set_flags(cctx
, SSL_CONF_FLAG_CLIENT
| SSL_CONF_FLAG_CMDLINE
);
994 prog
= opt_init(argc
, argv
, s_client_options
);
995 while ((o
= opt_next()) != OPT_EOF
) {
996 /* Check for intermixing flags. */
997 if (connect_type
== use_unix
&& IS_INET_FLAG(o
)) {
999 "%s: Intermixed protocol flags (unix and internet domains)\n",
1003 if (connect_type
== use_inet
&& IS_UNIX_FLAG(o
)) {
1005 "%s: Intermixed protocol flags (internet and unix domains)\n",
1010 if (IS_PROT_FLAG(o
) && ++prot_opt
> 1) {
1011 BIO_printf(bio_err
, "Cannot supply multiple protocol flags\n");
1014 if (IS_NO_PROT_FLAG(o
))
1016 if (prot_opt
== 1 && no_prot_opt
) {
1018 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1026 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
1029 opt_help(s_client_options
);
1033 connect_type
= use_inet
;
1034 socket_family
= AF_INET
;
1039 connect_type
= use_inet
;
1040 socket_family
= AF_INET6
;
1045 connect_type
= use_inet
;
1046 freeandcopy(&host
, opt_arg());
1049 connect_type
= use_inet
;
1050 freeandcopy(&port
, opt_arg());
1053 connect_type
= use_inet
;
1054 freeandcopy(&connectstr
, opt_arg());
1057 freeandcopy(&bindstr
, opt_arg());
1060 proxystr
= opt_arg();
1062 case OPT_PROXY_USER
:
1063 proxyuser
= opt_arg();
1065 case OPT_PROXY_PASS
:
1066 proxypassarg
= opt_arg();
1070 connect_type
= use_unix
;
1071 socket_family
= AF_UNIX
;
1072 freeandcopy(&host
, opt_arg());
1076 /* fall through, since this is an alias */
1078 protohost
= opt_arg();
1081 verify
= SSL_VERIFY_PEER
;
1082 verify_args
.depth
= atoi(opt_arg());
1084 BIO_printf(bio_err
, "verify depth is %d\n", verify_args
.depth
);
1087 cert_file
= opt_arg();
1090 if (!set_nameopt(opt_arg()))
1094 crl_file
= opt_arg();
1096 case OPT_CRL_DOWNLOAD
:
1100 sess_out
= opt_arg();
1103 sess_in
= opt_arg();
1106 if (!opt_format(opt_arg(), OPT_FMT_ANY
, &cert_format
))
1110 if (!opt_format(opt_arg(), OPT_FMT_PEMDER
, &crl_format
))
1113 case OPT_VERIFY_RET_ERROR
:
1114 verify
= SSL_VERIFY_PEER
;
1115 verify_args
.return_error
= 1;
1117 case OPT_VERIFY_QUIET
:
1118 verify_args
.quiet
= 1;
1121 c_brief
= verify_args
.quiet
= c_quiet
= 1;
1124 if (ssl_args
== NULL
)
1125 ssl_args
= sk_OPENSSL_STRING_new_null();
1126 if (ssl_args
== NULL
1127 || !sk_OPENSSL_STRING_push(ssl_args
, opt_flag())
1128 || !sk_OPENSSL_STRING_push(ssl_args
, opt_arg())) {
1129 BIO_printf(bio_err
, "%s: Memory allocation failure\n", prog
);
1134 if (!opt_verify(o
, vpm
))
1139 if (!args_excert(o
, &exc
))
1142 case OPT_IGNORE_UNEXPECTED_EOF
:
1143 ignore_unexpected_eof
= 1;
1148 case OPT_NO_INTERACTIVE
:
1155 c_quiet
= c_ign_eof
= 1;
1161 cmdmode
= USER_DATA_MODE_NONE
;
1164 cmdmode
= USER_DATA_MODE_ADVANCED
;
1167 e
= setup_engine(opt_arg(), 1);
1169 case OPT_SSL_CLIENT_ENGINE
:
1170 #ifndef OPENSSL_NO_ENGINE
1171 ssl_client_engine
= setup_engine(opt_arg(), 0);
1172 if (ssl_client_engine
== NULL
) {
1173 BIO_printf(bio_err
, "Error getting client auth engine\n");
1182 case OPT_PROV_CASES
:
1183 if (!opt_provider(o
))
1189 case OPT_NO_IGN_EOF
:
1195 case OPT_TLSEXTDEBUG
:
1199 #ifndef OPENSSL_NO_OCSP
1212 bio_c_msg
= BIO_new_file(opt_arg(), "w");
1213 if (bio_c_msg
== NULL
) {
1214 BIO_printf(bio_err
, "Error writing file %s\n", opt_arg());
1219 #ifndef OPENSSL_NO_SSL_TRACE
1223 case OPT_SECURITY_DEBUG
:
1226 case OPT_SECURITY_DEBUG_VERBOSE
:
1238 case OPT_PSK_IDENTITY
:
1239 psk_identity
= opt_arg();
1242 for (p
= psk_key
= opt_arg(); *p
; p
++) {
1243 if (isxdigit(_UC(*p
)))
1245 BIO_printf(bio_err
, "Not a hex number '%s'\n", psk_key
);
1250 psksessf
= opt_arg();
1252 #ifndef OPENSSL_NO_SRP
1254 srp_arg
.srplogin
= opt_arg();
1255 if (min_version
< TLS1_VERSION
)
1256 min_version
= TLS1_VERSION
;
1259 srppass
= opt_arg();
1260 if (min_version
< TLS1_VERSION
)
1261 min_version
= TLS1_VERSION
;
1263 case OPT_SRP_STRENGTH
:
1264 srp_arg
.strength
= atoi(opt_arg());
1265 BIO_printf(bio_err
, "SRP minimal length for N is %d\n",
1267 if (min_version
< TLS1_VERSION
)
1268 min_version
= TLS1_VERSION
;
1270 case OPT_SRP_LATEUSER
:
1272 if (min_version
< TLS1_VERSION
)
1273 min_version
= TLS1_VERSION
;
1275 case OPT_SRP_MOREGROUPS
:
1277 if (min_version
< TLS1_VERSION
)
1278 min_version
= TLS1_VERSION
;
1281 case OPT_SSL_CONFIG
:
1282 ssl_config
= opt_arg();
1285 min_version
= SSL3_VERSION
;
1286 max_version
= SSL3_VERSION
;
1287 socket_type
= SOCK_STREAM
;
1288 #ifndef OPENSSL_NO_DTLS
1294 min_version
= TLS1_3_VERSION
;
1295 max_version
= TLS1_3_VERSION
;
1296 socket_type
= SOCK_STREAM
;
1297 #ifndef OPENSSL_NO_DTLS
1303 min_version
= TLS1_2_VERSION
;
1304 max_version
= TLS1_2_VERSION
;
1305 socket_type
= SOCK_STREAM
;
1306 #ifndef OPENSSL_NO_DTLS
1312 min_version
= TLS1_1_VERSION
;
1313 max_version
= TLS1_1_VERSION
;
1314 socket_type
= SOCK_STREAM
;
1315 #ifndef OPENSSL_NO_DTLS
1321 min_version
= TLS1_VERSION
;
1322 max_version
= TLS1_VERSION
;
1323 socket_type
= SOCK_STREAM
;
1324 #ifndef OPENSSL_NO_DTLS
1330 #ifndef OPENSSL_NO_DTLS
1331 meth
= DTLS_client_method();
1332 socket_type
= SOCK_DGRAM
;
1338 #ifndef OPENSSL_NO_DTLS1
1339 meth
= DTLS_client_method();
1340 min_version
= DTLS1_VERSION
;
1341 max_version
= DTLS1_VERSION
;
1342 socket_type
= SOCK_DGRAM
;
1348 #ifndef OPENSSL_NO_DTLS1_2
1349 meth
= DTLS_client_method();
1350 min_version
= DTLS1_2_VERSION
;
1351 max_version
= DTLS1_2_VERSION
;
1352 socket_type
= SOCK_DGRAM
;
1358 #ifndef OPENSSL_NO_QUIC
1359 meth
= OSSL_QUIC_client_method();
1362 socket_type
= SOCK_DGRAM
;
1363 # ifndef OPENSSL_NO_DTLS
1370 #ifndef OPENSSL_NO_SCTP
1371 protocol
= IPPROTO_SCTP
;
1374 case OPT_SCTP_LABEL_BUG
:
1375 #ifndef OPENSSL_NO_SCTP
1380 #ifndef OPENSSL_NO_DTLS
1381 enable_timeouts
= 1;
1385 #ifndef OPENSSL_NO_DTLS
1386 socket_mtu
= atol(opt_arg());
1389 case OPT_FALLBACKSCSV
:
1393 if (!opt_format(opt_arg(), OPT_FMT_ANY
, &key_format
))
1397 passarg
= opt_arg();
1399 case OPT_CERT_CHAIN
:
1400 chain_file
= opt_arg();
1403 key_file
= opt_arg();
1414 case OPT_CHAINCAPATH
:
1415 chCApath
= opt_arg();
1417 case OPT_VERIFYCAPATH
:
1418 vfyCApath
= opt_arg();
1420 case OPT_BUILD_CHAIN
:
1424 ReqCAfile
= opt_arg();
1432 #ifndef OPENSSL_NO_CT
1439 case OPT_CTLOG_FILE
:
1440 ctlog_file
= opt_arg();
1443 case OPT_CHAINCAFILE
:
1444 chCAfile
= opt_arg();
1446 case OPT_VERIFYCAFILE
:
1447 vfyCAfile
= opt_arg();
1450 CAstore
= opt_arg();
1455 case OPT_CHAINCASTORE
:
1456 chCAstore
= opt_arg();
1458 case OPT_VERIFYCASTORE
:
1459 vfyCAstore
= opt_arg();
1461 case OPT_DANE_TLSA_DOMAIN
:
1462 dane_tlsa_domain
= opt_arg();
1464 case OPT_DANE_TLSA_RRDATA
:
1465 if (dane_tlsa_rrset
== NULL
)
1466 dane_tlsa_rrset
= sk_OPENSSL_STRING_new_null();
1467 if (dane_tlsa_rrset
== NULL
||
1468 !sk_OPENSSL_STRING_push(dane_tlsa_rrset
, opt_arg())) {
1469 BIO_printf(bio_err
, "%s: Memory allocation failure\n", prog
);
1473 case OPT_DANE_EE_NO_NAME
:
1474 dane_ee_no_name
= 1;
1476 case OPT_NEXTPROTONEG
:
1477 #ifndef OPENSSL_NO_NEXTPROTONEG
1478 next_proto_neg_in
= opt_arg();
1482 alpn_in
= opt_arg();
1484 case OPT_SERVERINFO
:
1486 len
= (int)strlen(p
);
1487 for (start
= 0, i
= 0; i
<= len
; ++i
) {
1488 if (i
== len
|| p
[i
] == ',') {
1489 serverinfo_types
[serverinfo_count
] = atoi(p
+ start
);
1490 if (++serverinfo_count
== MAX_SI_TYPES
)
1497 if (!opt_pair(opt_arg(), services
, &starttls_proto
))
1503 case OPT_SERVERNAME
:
1504 servername
= opt_arg();
1506 case OPT_NOSERVERNAME
:
1510 #ifndef OPENSSL_NO_SRTP
1511 srtp_profiles
= opt_arg();
1514 case OPT_KEYMATEXPORT
:
1515 keymatexportlabel
= opt_arg();
1517 case OPT_KEYMATEXPORTLEN
:
1518 keymatexportlen
= atoi(opt_arg());
1523 case OPT_MAXFRAGLEN
:
1524 len
= atoi(opt_arg());
1527 maxfraglen
= TLSEXT_max_fragment_length_512
;
1530 maxfraglen
= TLSEXT_max_fragment_length_1024
;
1533 maxfraglen
= TLSEXT_max_fragment_length_2048
;
1536 maxfraglen
= TLSEXT_max_fragment_length_4096
;
1540 "%s: Max Fragment Len %u is out of permitted values",
1545 case OPT_MAX_SEND_FRAG
:
1546 max_send_fragment
= atoi(opt_arg());
1548 case OPT_SPLIT_SEND_FRAG
:
1549 split_send_fragment
= atoi(opt_arg());
1551 case OPT_MAX_PIPELINES
:
1552 max_pipelines
= atoi(opt_arg());
1555 read_buf_len
= atoi(opt_arg());
1557 case OPT_KEYLOG_FILE
:
1558 keylog_file
= opt_arg();
1560 case OPT_EARLY_DATA
:
1561 early_data_file
= opt_arg();
1563 case OPT_ENABLE_PHA
:
1567 #ifndef OPENSSL_NO_KTLS
1571 case OPT_ENABLE_SERVER_RPK
:
1572 enable_server_rpk
= 1;
1574 case OPT_ENABLE_CLIENT_RPK
:
1575 enable_client_rpk
= 1;
1580 /* Optional argument is connect string if -connect not used. */
1581 if (opt_num_rest() == 1) {
1582 /* Don't allow -connect and a separate argument. */
1583 if (connectstr
!= NULL
) {
1585 "%s: cannot provide both -connect option and target parameter\n",
1589 connect_type
= use_inet
;
1590 freeandcopy(&connectstr
, *opt_rest());
1591 } else if (!opt_check_rest_arg(NULL
)) {
1594 if (!app_RAND_load())
1598 cmdmode
= USER_DATA_MODE_NONE
;
1600 if (count4or6
>= 2) {
1601 BIO_printf(bio_err
, "%s: Can't use both -4 and -6\n", prog
);
1605 if (servername
!= NULL
) {
1607 "%s: Can't use -servername and -noservername together\n",
1611 if (dane_tlsa_domain
!= NULL
) {
1613 "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1619 #ifndef OPENSSL_NO_NEXTPROTONEG
1620 if (min_version
== TLS1_3_VERSION
&& next_proto_neg_in
!= NULL
) {
1621 BIO_printf(bio_err
, "Cannot supply -nextprotoneg with TLSv1.3\n");
1626 if (connectstr
!= NULL
) {
1628 char *tmp_host
= host
, *tmp_port
= port
;
1630 res
= BIO_parse_hostserv(connectstr
, &host
, &port
, BIO_PARSE_PRIO_HOST
);
1631 if (tmp_host
!= host
)
1632 OPENSSL_free(tmp_host
);
1633 if (tmp_port
!= port
)
1634 OPENSSL_free(tmp_port
);
1637 "%s: -connect argument or target parameter malformed or ambiguous\n",
1643 if (proxystr
!= NULL
) {
1644 #ifndef OPENSSL_NO_HTTP
1646 char *tmp_host
= host
, *tmp_port
= port
;
1648 if (host
== NULL
|| port
== NULL
) {
1649 BIO_printf(bio_err
, "%s: -proxy requires use of -connect or target parameter\n", prog
);
1653 if (servername
== NULL
&& !noservername
) {
1654 servername
= sname_alloc
= OPENSSL_strdup(host
);
1655 if (sname_alloc
== NULL
) {
1656 BIO_printf(bio_err
, "%s: out of memory\n", prog
);
1661 /* Retain the original target host:port for use in the HTTP proxy connect string */
1662 thost
= OPENSSL_strdup(host
);
1663 tport
= OPENSSL_strdup(port
);
1664 if (thost
== NULL
|| tport
== NULL
) {
1665 BIO_printf(bio_err
, "%s: out of memory\n", prog
);
1669 res
= BIO_parse_hostserv(proxystr
, &host
, &port
, BIO_PARSE_PRIO_HOST
);
1670 if (tmp_host
!= host
)
1671 OPENSSL_free(tmp_host
);
1672 if (tmp_port
!= port
)
1673 OPENSSL_free(tmp_port
);
1676 "%s: -proxy argument malformed or ambiguous\n", prog
);
1681 "%s: -proxy not supported in no-http build\n", prog
);
1687 if (bindstr
!= NULL
) {
1689 res
= BIO_parse_hostserv(bindstr
, &bindhost
, &bindport
,
1690 BIO_PARSE_PRIO_HOST
);
1693 "%s: -bind argument parameter malformed or ambiguous\n",
1700 if (socket_family
== AF_UNIX
&& socket_type
!= SOCK_STREAM
) {
1702 "Can't use unix sockets and datagrams together\n");
1707 #ifndef OPENSSL_NO_SCTP
1708 if (protocol
== IPPROTO_SCTP
) {
1709 if (socket_type
!= SOCK_DGRAM
) {
1710 BIO_printf(bio_err
, "Can't use -sctp without DTLS\n");
1713 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1714 socket_type
= SOCK_STREAM
;
1718 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1719 next_proto
.status
= -1;
1720 if (next_proto_neg_in
) {
1722 next_protos_parse(&next_proto
.len
, next_proto_neg_in
);
1723 if (next_proto
.data
== NULL
) {
1724 BIO_printf(bio_err
, "Error parsing -nextprotoneg argument\n");
1728 next_proto
.data
= NULL
;
1731 if (!app_passwd(passarg
, NULL
, &pass
, NULL
)) {
1732 BIO_printf(bio_err
, "Error getting private key password\n");
1736 if (!app_passwd(proxypassarg
, NULL
, &proxypass
, NULL
)) {
1737 BIO_printf(bio_err
, "Error getting proxy password\n");
1741 if (proxypass
!= NULL
&& proxyuser
== NULL
) {
1742 BIO_printf(bio_err
, "Error: Must specify proxy_user with proxy_pass\n");
1746 if (key_file
== NULL
)
1747 key_file
= cert_file
;
1749 if (key_file
!= NULL
) {
1750 key
= load_key(key_file
, key_format
, 0, pass
, e
,
1751 "client certificate private key");
1756 if (cert_file
!= NULL
) {
1757 cert
= load_cert_pass(cert_file
, cert_format
, 1, pass
,
1758 "client certificate");
1763 if (chain_file
!= NULL
) {
1764 if (!load_certs(chain_file
, 0, &chain
, pass
, "client certificate chain"))
1768 if (crl_file
!= NULL
) {
1770 crl
= load_crl(crl_file
, crl_format
, 0, "CRL");
1773 crls
= sk_X509_CRL_new_null();
1774 if (crls
== NULL
|| !sk_X509_CRL_push(crls
, crl
)) {
1775 BIO_puts(bio_err
, "Error adding CRL\n");
1781 if (!load_excert(&exc
))
1784 if (bio_c_out
== NULL
) {
1785 if (c_quiet
&& !c_debug
) {
1786 bio_c_out
= BIO_new(BIO_s_null());
1787 if (c_msg
&& bio_c_msg
== NULL
) {
1788 bio_c_msg
= dup_bio_out(FORMAT_TEXT
);
1789 if (bio_c_msg
== NULL
) {
1790 BIO_printf(bio_err
, "Out of memory\n");
1795 bio_c_out
= dup_bio_out(FORMAT_TEXT
);
1798 if (bio_c_out
== NULL
) {
1799 BIO_printf(bio_err
, "Unable to create BIO\n");
1803 #ifndef OPENSSL_NO_SRP
1804 if (!app_passwd(srppass
, NULL
, &srp_arg
.srppassin
, NULL
)) {
1805 BIO_printf(bio_err
, "Error getting password\n");
1810 ctx
= SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth
);
1814 SSL_CTX_clear_mode(ctx
, SSL_MODE_AUTO_RETRY
);
1817 ssl_ctx_security_debug(ctx
, sdebug
);
1819 if (!config_ctx(cctx
, ssl_args
, ctx
))
1822 if (ssl_config
!= NULL
) {
1823 if (SSL_CTX_config(ctx
, ssl_config
) == 0) {
1824 BIO_printf(bio_err
, "Error using configuration \"%s\"\n",
1830 #ifndef OPENSSL_NO_SCTP
1831 if (protocol
== IPPROTO_SCTP
&& sctp_label_bug
== 1)
1832 SSL_CTX_set_mode(ctx
, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG
);
1835 if (min_version
!= 0
1836 && SSL_CTX_set_min_proto_version(ctx
, min_version
) == 0)
1838 if (max_version
!= 0
1839 && SSL_CTX_set_max_proto_version(ctx
, max_version
) == 0)
1842 if (ignore_unexpected_eof
)
1843 SSL_CTX_set_options(ctx
, SSL_OP_IGNORE_UNEXPECTED_EOF
);
1844 #ifndef OPENSSL_NO_KTLS
1846 SSL_CTX_set_options(ctx
, SSL_OP_ENABLE_KTLS
);
1849 if (vpmtouched
&& !SSL_CTX_set1_param(ctx
, vpm
)) {
1850 BIO_printf(bio_err
, "Error setting verify params\n");
1855 SSL_CTX_set_mode(ctx
, SSL_MODE_ASYNC
);
1858 if (max_send_fragment
> 0
1859 && !SSL_CTX_set_max_send_fragment(ctx
, max_send_fragment
)) {
1860 BIO_printf(bio_err
, "%s: Max send fragment size %u is out of permitted range\n",
1861 prog
, max_send_fragment
);
1865 if (split_send_fragment
> 0
1866 && !SSL_CTX_set_split_send_fragment(ctx
, split_send_fragment
)) {
1867 BIO_printf(bio_err
, "%s: Split send fragment size %u is out of permitted range\n",
1868 prog
, split_send_fragment
);
1872 if (max_pipelines
> 0
1873 && !SSL_CTX_set_max_pipelines(ctx
, max_pipelines
)) {
1874 BIO_printf(bio_err
, "%s: Max pipelines %u is out of permitted range\n",
1875 prog
, max_pipelines
);
1879 if (read_buf_len
> 0) {
1880 SSL_CTX_set_default_read_buffer_len(ctx
, read_buf_len
);
1884 && !SSL_CTX_set_tlsext_max_fragment_length(ctx
, maxfraglen
)) {
1886 "%s: Max Fragment Length code %u is out of permitted values"
1887 "\n", prog
, maxfraglen
);
1891 if (!ssl_load_stores(ctx
,
1892 vfyCApath
, vfyCAfile
, vfyCAstore
,
1893 chCApath
, chCAfile
, chCAstore
,
1894 crls
, crl_download
)) {
1895 BIO_printf(bio_err
, "Error loading store locations\n");
1898 if (ReqCAfile
!= NULL
) {
1899 STACK_OF(X509_NAME
) *nm
= sk_X509_NAME_new_null();
1901 if (nm
== NULL
|| !SSL_add_file_cert_subjects_to_stack(nm
, ReqCAfile
)) {
1902 sk_X509_NAME_pop_free(nm
, X509_NAME_free
);
1903 BIO_printf(bio_err
, "Error loading CA names\n");
1906 SSL_CTX_set0_CA_list(ctx
, nm
);
1908 #ifndef OPENSSL_NO_ENGINE
1909 if (ssl_client_engine
) {
1910 if (!SSL_CTX_set_client_cert_engine(ctx
, ssl_client_engine
)) {
1911 BIO_puts(bio_err
, "Error setting client auth engine\n");
1912 release_engine(ssl_client_engine
);
1915 release_engine(ssl_client_engine
);
1919 #ifndef OPENSSL_NO_PSK
1920 if (psk_key
!= NULL
) {
1922 BIO_printf(bio_c_out
, "PSK key given, setting client callback\n");
1923 SSL_CTX_set_psk_client_callback(ctx
, psk_client_cb
);
1926 if (psksessf
!= NULL
) {
1927 BIO
*stmp
= BIO_new_file(psksessf
, "r");
1930 BIO_printf(bio_err
, "Can't open PSK session file %s\n", psksessf
);
1933 psksess
= PEM_read_bio_SSL_SESSION(stmp
, NULL
, 0, NULL
);
1935 if (psksess
== NULL
) {
1936 BIO_printf(bio_err
, "Can't read PSK session file %s\n", psksessf
);
1940 if (psk_key
!= NULL
|| psksess
!= NULL
)
1941 SSL_CTX_set_psk_use_session_callback(ctx
, psk_use_session_cb
);
1943 #ifndef OPENSSL_NO_SRTP
1944 if (srtp_profiles
!= NULL
) {
1945 /* Returns 0 on success! */
1946 if (SSL_CTX_set_tlsext_use_srtp(ctx
, srtp_profiles
) != 0) {
1947 BIO_printf(bio_err
, "Error setting SRTP profile\n");
1954 ssl_ctx_set_excert(ctx
, exc
);
1956 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1957 if (next_proto
.data
!= NULL
)
1958 SSL_CTX_set_next_proto_select_cb(ctx
, next_proto_cb
, &next_proto
);
1962 unsigned char *alpn
= next_protos_parse(&alpn_len
, alpn_in
);
1965 BIO_printf(bio_err
, "Error parsing -alpn argument\n");
1968 /* Returns 0 on success! */
1969 if (SSL_CTX_set_alpn_protos(ctx
, alpn
, (unsigned int)alpn_len
) != 0) {
1970 BIO_printf(bio_err
, "Error setting ALPN\n");
1976 for (i
= 0; i
< serverinfo_count
; i
++) {
1977 if (!SSL_CTX_add_client_custom_ext(ctx
,
1978 serverinfo_types
[i
],
1980 serverinfo_cli_parse_cb
, NULL
)) {
1982 "Warning: Unable to add custom extension %u, skipping\n",
1983 serverinfo_types
[i
]);
1988 SSL_CTX_set_info_callback(ctx
, apps_ssl_info_callback
);
1990 #ifndef OPENSSL_NO_CT
1991 /* Enable SCT processing, without early connection termination */
1992 if (ct_validation
&&
1993 !SSL_CTX_enable_ct(ctx
, SSL_CT_VALIDATION_PERMISSIVE
)) {
1997 if (!ctx_set_ctlog_list_file(ctx
, ctlog_file
)) {
2002 * If CT validation is not enabled, the log list isn't needed so don't
2003 * show errors or abort. We try to load it regardless because then we
2004 * can show the names of the logs any SCTs came from (SCTs may be seen
2005 * even with validation disabled).
2011 SSL_CTX_set_verify(ctx
, verify
, verify_callback
);
2013 if (!ctx_set_verify_locations(ctx
, CAfile
, noCAfile
, CApath
, noCApath
,
2014 CAstore
, noCAstore
))
2017 ssl_ctx_add_crls(ctx
, crls
, crl_download
);
2019 if (!set_cert_key_stuff(ctx
, cert
, key
, chain
, build_chain
))
2022 if (!noservername
) {
2023 tlsextcbp
.biodebug
= bio_err
;
2024 SSL_CTX_set_tlsext_servername_callback(ctx
, ssl_servername_cb
);
2025 SSL_CTX_set_tlsext_servername_arg(ctx
, &tlsextcbp
);
2027 #ifndef OPENSSL_NO_SRP
2028 if (srp_arg
.srplogin
!= NULL
2029 && !set_up_srp_arg(ctx
, &srp_arg
, srp_lateuser
, c_msg
, c_debug
))
2033 if (dane_tlsa_domain
!= NULL
) {
2034 if (SSL_CTX_dane_enable(ctx
) <= 0) {
2036 "%s: Error enabling DANE TLSA authentication.\n",
2043 * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
2044 * come at any time. Therefore, we use a callback to write out the session
2045 * when we know about it. This approach works for < TLSv1.3 as well.
2047 SSL_CTX_set_session_cache_mode(ctx
, SSL_SESS_CACHE_CLIENT
2048 | SSL_SESS_CACHE_NO_INTERNAL_STORE
);
2049 SSL_CTX_sess_set_new_cb(ctx
, new_session_cb
);
2051 if (set_keylog_file(ctx
, keylog_file
))
2059 SSL_set_post_handshake_auth(con
, 1);
2061 if (enable_client_rpk
)
2062 if (!SSL_set1_client_cert_type(con
, cert_type_rpk
, sizeof(cert_type_rpk
))) {
2063 BIO_printf(bio_err
, "Error setting client certificate types\n");
2066 if (enable_server_rpk
) {
2067 if (!SSL_set1_server_cert_type(con
, cert_type_rpk
, sizeof(cert_type_rpk
))) {
2068 BIO_printf(bio_err
, "Error setting server certificate types\n");
2073 if (sess_in
!= NULL
) {
2075 BIO
*stmp
= BIO_new_file(sess_in
, "r");
2077 BIO_printf(bio_err
, "Can't open session file %s\n", sess_in
);
2080 sess
= PEM_read_bio_SSL_SESSION(stmp
, NULL
, 0, NULL
);
2083 BIO_printf(bio_err
, "Can't open session file %s\n", sess_in
);
2086 if (!SSL_set_session(con
, sess
)) {
2087 BIO_printf(bio_err
, "Can't set session\n");
2091 SSL_SESSION_free(sess
);
2095 SSL_set_mode(con
, SSL_MODE_SEND_FALLBACK_SCSV
);
2097 if (!noservername
&& (servername
!= NULL
|| dane_tlsa_domain
== NULL
)) {
2098 if (servername
== NULL
) {
2099 if (host
== NULL
|| is_dNS_name(host
))
2100 servername
= (host
== NULL
) ? "localhost" : host
;
2102 if (servername
!= NULL
&& !SSL_set_tlsext_host_name(con
, servername
)) {
2103 BIO_printf(bio_err
, "Unable to set TLS servername extension.\n");
2108 if (dane_tlsa_domain
!= NULL
) {
2109 if (SSL_dane_enable(con
, dane_tlsa_domain
) <= 0) {
2110 BIO_printf(bio_err
, "%s: Error enabling DANE TLSA "
2111 "authentication.\n", prog
);
2114 if (dane_tlsa_rrset
== NULL
) {
2115 BIO_printf(bio_err
, "%s: DANE TLSA authentication requires at "
2116 "least one -dane_tlsa_rrdata option.\n", prog
);
2119 if (tlsa_import_rrset(con
, dane_tlsa_rrset
) <= 0) {
2120 BIO_printf(bio_err
, "%s: Failed to import any TLSA "
2121 "records.\n", prog
);
2124 if (dane_ee_no_name
)
2125 SSL_dane_set_flags(con
, DANE_FLAG_NO_DANE_EE_NAMECHECKS
);
2126 } else if (dane_tlsa_rrset
!= NULL
) {
2127 BIO_printf(bio_err
, "%s: DANE TLSA authentication requires the "
2128 "-dane_tlsa_domain option.\n", prog
);
2131 #ifndef OPENSSL_NO_DTLS
2132 if (isdtls
&& tfo
) {
2133 BIO_printf(bio_err
, "%s: DTLS does not support the -tfo option\n", prog
);
2137 #ifndef OPENSSL_NO_QUIC
2138 if (isquic
&& tfo
) {
2139 BIO_printf(bio_err
, "%s: QUIC does not support the -tfo option\n", prog
);
2142 if (isquic
&& alpn_in
== NULL
) {
2143 BIO_printf(bio_err
, "%s: QUIC requires ALPN to be specified (e.g. \"h3\" for HTTP/3) via the -alpn option\n", prog
);
2149 BIO_printf(bio_c_out
, "Connecting via TFO\n");
2151 /* peer_addr might be set from previous connections */
2152 BIO_ADDR_free(peer_addr
);
2154 if (init_client(&sock
, host
, port
, bindhost
, bindport
, socket_family
,
2155 socket_type
, protocol
, tfo
, !isquic
, &peer_addr
) == 0) {
2156 BIO_printf(bio_err
, "connect:errno=%d\n", get_last_socket_error());
2157 BIO_closesocket(sock
);
2160 BIO_printf(bio_c_out
, "CONNECTED(%08X)\n", sock
);
2163 * QUIC always uses a non-blocking socket - and we have to switch on
2164 * non-blocking mode at the SSL level
2166 if (c_nbio
|| isquic
) {
2167 if (!BIO_socket_nbio(sock
, 1))
2170 if (isquic
&& !SSL_set_blocking_mode(con
, 0))
2172 BIO_printf(bio_c_out
, "Turned on non blocking io\n");
2175 #ifndef OPENSSL_NO_DTLS
2177 union BIO_sock_info_u peer_info
;
2179 #ifndef OPENSSL_NO_SCTP
2180 if (protocol
== IPPROTO_SCTP
)
2181 sbio
= BIO_new_dgram_sctp(sock
, BIO_NOCLOSE
);
2184 sbio
= BIO_new_dgram(sock
, BIO_NOCLOSE
);
2186 if (sbio
== NULL
|| (peer_info
.addr
= BIO_ADDR_new()) == NULL
) {
2187 BIO_printf(bio_err
, "memory allocation failure\n");
2189 BIO_closesocket(sock
);
2192 if (!BIO_sock_info(sock
, BIO_SOCK_INFO_ADDRESS
, &peer_info
)) {
2193 BIO_printf(bio_err
, "getsockname:errno=%d\n",
2194 get_last_socket_error());
2196 BIO_ADDR_free(peer_info
.addr
);
2197 BIO_closesocket(sock
);
2201 (void)BIO_ctrl_set_connected(sbio
, peer_info
.addr
);
2202 BIO_ADDR_free(peer_info
.addr
);
2203 peer_info
.addr
= NULL
;
2205 if (enable_timeouts
) {
2207 timeout
.tv_usec
= DGRAM_RCV_TIMEOUT
;
2208 BIO_ctrl(sbio
, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT
, 0, &timeout
);
2211 timeout
.tv_usec
= DGRAM_SND_TIMEOUT
;
2212 BIO_ctrl(sbio
, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT
, 0, &timeout
);
2216 if (socket_mtu
< DTLS_get_link_min_mtu(con
)) {
2217 BIO_printf(bio_err
, "MTU too small. Must be at least %ld\n",
2218 DTLS_get_link_min_mtu(con
));
2222 SSL_set_options(con
, SSL_OP_NO_QUERY_MTU
);
2223 if (!DTLS_set_link_mtu(con
, socket_mtu
)) {
2224 BIO_printf(bio_err
, "Failed to set MTU\n");
2229 /* want to do MTU discovery */
2230 BIO_ctrl(sbio
, BIO_CTRL_DGRAM_MTU_DISCOVER
, 0, NULL
);
2233 #endif /* OPENSSL_NO_DTLS */
2234 #ifndef OPENSSL_NO_QUIC
2236 sbio
= BIO_new_dgram(sock
, BIO_NOCLOSE
);
2237 if (!SSL_set1_initial_peer_addr(con
, peer_addr
)) {
2238 BIO_printf(bio_err
, "Failed to set the initial peer address\n");
2243 sbio
= BIO_new_socket(sock
, BIO_NOCLOSE
);
2246 BIO_printf(bio_err
, "Unable to create BIO\n");
2247 BIO_closesocket(sock
);
2251 /* Now that we're using a BIO... */
2253 (void)BIO_set_conn_address(sbio
, peer_addr
);
2254 (void)BIO_set_tfo(sbio
, 1);
2260 test
= BIO_new(BIO_f_nbio_test());
2262 BIO_printf(bio_err
, "Unable to create BIO\n");
2266 sbio
= BIO_push(test
, sbio
);
2270 BIO_set_callback_ex(sbio
, bio_dump_callback
);
2271 BIO_set_callback_arg(sbio
, (char *)bio_c_out
);
2274 #ifndef OPENSSL_NO_SSL_TRACE
2276 SSL_set_msg_callback(con
, SSL_trace
);
2279 SSL_set_msg_callback(con
, msg_cb
);
2280 SSL_set_msg_callback_arg(con
, bio_c_msg
? bio_c_msg
: bio_c_out
);
2283 if (c_tlsextdebug
) {
2284 SSL_set_tlsext_debug_callback(con
, tlsext_cb
);
2285 SSL_set_tlsext_debug_arg(con
, bio_c_out
);
2287 #ifndef OPENSSL_NO_OCSP
2289 SSL_set_tlsext_status_type(con
, TLSEXT_STATUSTYPE_ocsp
);
2290 SSL_CTX_set_tlsext_status_cb(ctx
, ocsp_resp_cb
);
2291 SSL_CTX_set_tlsext_status_arg(ctx
, bio_c_out
);
2295 SSL_set_bio(con
, sbio
, sbio
);
2296 SSL_set_connect_state(con
);
2298 /* ok, lets connect */
2299 if (fileno_stdin() > SSL_get_fd(con
))
2300 width
= fileno_stdin() + 1;
2302 width
= SSL_get_fd(con
) + 1;
2316 #ifndef OPENSSL_NO_HTTP
2317 if (proxystr
!= NULL
) {
2318 /* Here we must use the connect string target host & port */
2319 if (!OSSL_HTTP_proxy_connect(sbio
, thost
, tport
, proxyuser
, proxypass
,
2320 0 /* no timeout */, bio_err
, prog
))
2325 switch ((PROTOCOL_CHOICE
) starttls_proto
) {
2332 * This is an ugly hack that does a lot of assumptions. We do
2333 * have to handle multi-line responses which may come in a single
2334 * packet or not. We therefore have to use BIO_gets() which does
2335 * need a buffering BIO. So during the initial chitchat we do
2336 * push a buffering BIO into the chain that is removed again
2337 * later on to not disturb the rest of the s_client operation.
2340 BIO
*fbio
= BIO_new(BIO_f_buffer());
2343 BIO_printf(bio_err
, "Unable to create BIO\n");
2346 BIO_push(fbio
, sbio
);
2347 /* Wait for multi-line response to end from LMTP or SMTP */
2349 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2350 } while (mbuf_len
> 3 && mbuf
[3] == '-');
2351 if (protohost
== NULL
)
2352 protohost
= "mail.example.com";
2353 if (starttls_proto
== (int)PROTO_LMTP
)
2354 BIO_printf(fbio
, "LHLO %s\r\n", protohost
);
2356 BIO_printf(fbio
, "EHLO %s\r\n", protohost
);
2357 (void)BIO_flush(fbio
);
2359 * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2363 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2364 if (strstr(mbuf
, "STARTTLS"))
2366 } while (mbuf_len
> 3 && mbuf
[3] == '-');
2367 (void)BIO_flush(fbio
);
2372 "Didn't find STARTTLS in server response,"
2373 " trying anyway...\n");
2374 BIO_printf(sbio
, "STARTTLS\r\n");
2375 BIO_read(sbio
, sbuf
, BUFSIZZ
);
2380 BIO_read(sbio
, mbuf
, BUFSIZZ
);
2381 BIO_printf(sbio
, "STLS\r\n");
2382 mbuf_len
= BIO_read(sbio
, sbuf
, BUFSIZZ
);
2384 BIO_printf(bio_err
, "BIO_read failed\n");
2392 BIO
*fbio
= BIO_new(BIO_f_buffer());
2395 BIO_printf(bio_err
, "Unable to create BIO\n");
2398 BIO_push(fbio
, sbio
);
2399 BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2400 /* STARTTLS command requires CAPABILITY... */
2401 BIO_printf(fbio
, ". CAPABILITY\r\n");
2402 (void)BIO_flush(fbio
);
2403 /* wait for multi-line CAPABILITY response */
2405 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2406 if (strstr(mbuf
, "STARTTLS"))
2409 while (mbuf_len
> 3 && mbuf
[0] != '.');
2410 (void)BIO_flush(fbio
);
2415 "Didn't find STARTTLS in server response,"
2416 " trying anyway...\n");
2417 BIO_printf(sbio
, ". STARTTLS\r\n");
2418 BIO_read(sbio
, sbuf
, BUFSIZZ
);
2423 BIO
*fbio
= BIO_new(BIO_f_buffer());
2426 BIO_printf(bio_err
, "Unable to create BIO\n");
2429 BIO_push(fbio
, sbio
);
2430 /* wait for multi-line response to end from FTP */
2432 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2434 while (mbuf_len
> 3 && (!isdigit((unsigned char)mbuf
[0]) || !isdigit((unsigned char)mbuf
[1]) || !isdigit((unsigned char)mbuf
[2]) || mbuf
[3] != ' '));
2435 (void)BIO_flush(fbio
);
2438 BIO_printf(sbio
, "AUTH TLS\r\n");
2439 BIO_read(sbio
, sbuf
, BUFSIZZ
);
2443 case PROTO_XMPP_SERVER
:
2446 BIO_printf(sbio
, "<stream:stream "
2447 "xmlns:stream='http://etherx.jabber.org/streams' "
2448 "xmlns='jabber:%s' to='%s' version='1.0'>",
2449 starttls_proto
== PROTO_XMPP
? "client" : "server",
2450 protohost
? protohost
: host
);
2451 seen
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2453 BIO_printf(bio_err
, "BIO_read failed\n");
2458 (mbuf
, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2460 "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2462 seen
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2470 "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2471 seen
= BIO_read(sbio
, sbuf
, BUFSIZZ
);
2473 BIO_printf(bio_err
, "BIO_read failed\n");
2477 if (!strstr(sbuf
, "<proceed"))
2484 static const unsigned char tls_do
[] = {
2485 /* IAC DO START_TLS */
2488 static const unsigned char tls_will
[] = {
2489 /* IAC WILL START_TLS */
2492 static const unsigned char tls_follows
[] = {
2493 /* IAC SB START_TLS FOLLOWS IAC SE */
2494 255, 250, 46, 1, 255, 240
2498 /* Telnet server should demand we issue START_TLS */
2499 bytes
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2500 if (bytes
!= 3 || memcmp(mbuf
, tls_do
, 3) != 0)
2502 /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2503 BIO_write(sbio
, tls_will
, 3);
2504 BIO_write(sbio
, tls_follows
, 6);
2505 (void)BIO_flush(sbio
);
2506 /* Telnet server also sent the FOLLOWS sub-command */
2507 bytes
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2508 if (bytes
!= 6 || memcmp(mbuf
, tls_follows
, 6) != 0)
2515 BIO
*fbio
= BIO_new(BIO_f_buffer());
2518 BIO_printf(bio_err
, "Unable to create BIO\n");
2521 BIO_push(fbio
, sbio
);
2522 BIO_printf(fbio
, "STARTTLS\r\n");
2523 (void)BIO_flush(fbio
);
2524 width
= SSL_get_fd(con
) + 1;
2530 openssl_fdset(SSL_get_fd(con
), &readfds
);
2531 timeout
.tv_sec
= S_CLIENT_IRC_READ_TIMEOUT
;
2532 timeout
.tv_usec
= 0;
2534 * If the IRCd doesn't respond within
2535 * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2536 * it doesn't support STARTTLS. Many IRCds
2537 * will not give _any_ sort of response to a
2538 * STARTTLS command when it's not supported.
2540 if (!BIO_get_buffer_num_lines(fbio
)
2541 && !BIO_pending(fbio
)
2542 && !BIO_pending(sbio
)
2543 && select(width
, (void *)&readfds
, NULL
, NULL
,
2546 "Timeout waiting for response (%d seconds).\n",
2547 S_CLIENT_IRC_READ_TIMEOUT
);
2551 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2552 if (mbuf_len
< 1 || sscanf(mbuf
, "%*s %d", &numeric
) != 1)
2554 /* :example.net 451 STARTTLS :You have not registered */
2555 /* :example.net 421 STARTTLS :Unknown command */
2556 if ((numeric
== 451 || numeric
== 421)
2557 && strstr(mbuf
, "STARTTLS") != NULL
) {
2558 BIO_printf(bio_err
, "STARTTLS not supported: %s", mbuf
);
2561 if (numeric
== 691) {
2562 BIO_printf(bio_err
, "STARTTLS negotiation failed: ");
2565 } while (numeric
!= 670);
2567 (void)BIO_flush(fbio
);
2570 if (numeric
!= 670) {
2571 BIO_printf(bio_err
, "Server does not support STARTTLS.\n");
2579 /* SSL request packet */
2580 static const unsigned char ssl_req
[] = {
2581 /* payload_length, sequence_id */
2582 0x20, 0x00, 0x00, 0x01,
2584 /* capability flags, CLIENT_SSL always set */
2585 0x85, 0xae, 0x7f, 0x00,
2586 /* max-packet size */
2587 0x00, 0x00, 0x00, 0x01,
2590 /* string[23] reserved (all [0]) */
2591 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2592 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2593 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2596 int ssl_flg
= 0x800;
2598 const unsigned char *packet
= (const unsigned char *)sbuf
;
2600 /* Receiving Initial Handshake packet. */
2601 bytes
= BIO_read(sbio
, (void *)packet
, BUFSIZZ
);
2603 BIO_printf(bio_err
, "BIO_read failed\n");
2605 /* Packet length[3], Packet number[1] + minimum payload[17] */
2606 } else if (bytes
< 21) {
2607 BIO_printf(bio_err
, "MySQL packet too short.\n");
2609 } else if (bytes
!= (4 + packet
[0] +
2611 (packet
[2] << 16))) {
2612 BIO_printf(bio_err
, "MySQL packet length does not match.\n");
2614 /* protocol version[1] */
2615 } else if (packet
[4] != 0xA) {
2617 "Only MySQL protocol version 10 is supported.\n");
2622 /* server version[string+NULL] */
2625 BIO_printf(bio_err
, "Cannot confirm server version. ");
2627 } else if (packet
[pos
++] == '\0') {
2632 /* make sure we have at least 15 bytes left in the packet */
2633 if (pos
+ 15 > bytes
) {
2635 "MySQL server handshake packet is broken.\n");
2639 pos
+= 12; /* skip over conn id[4] + SALT[8] */
2640 if (packet
[pos
++] != '\0') { /* verify filler */
2642 "MySQL packet is broken.\n");
2646 /* capability flags[2] */
2647 if (!((packet
[pos
] + (packet
[pos
+ 1] << 8)) & ssl_flg
)) {
2648 BIO_printf(bio_err
, "MySQL server does not support SSL.\n");
2652 /* Sending SSL Handshake packet. */
2653 BIO_write(sbio
, ssl_req
, sizeof(ssl_req
));
2654 (void)BIO_flush(sbio
);
2657 case PROTO_POSTGRES
:
2659 static const unsigned char ssl_request
[] = {
2660 /* Length SSLRequest */
2661 0, 0, 0, 8, 4, 210, 22, 47
2665 /* Send SSLRequest packet */
2666 BIO_write(sbio
, ssl_request
, 8);
2667 (void)BIO_flush(sbio
);
2669 /* Reply will be a single S if SSL is enabled */
2670 bytes
= BIO_read(sbio
, sbuf
, BUFSIZZ
);
2671 if (bytes
!= 1 || sbuf
[0] != 'S')
2678 BIO
*fbio
= BIO_new(BIO_f_buffer());
2681 BIO_printf(bio_err
, "Unable to create BIO\n");
2684 BIO_push(fbio
, sbio
);
2685 BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2686 /* STARTTLS command requires CAPABILITIES... */
2687 BIO_printf(fbio
, "CAPABILITIES\r\n");
2688 (void)BIO_flush(fbio
);
2689 BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2690 /* no point in trying to parse the CAPABILITIES response if there is none */
2691 if (strstr(mbuf
, "101") != NULL
) {
2692 /* wait for multi-line CAPABILITIES response */
2694 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2695 if (strstr(mbuf
, "STARTTLS"))
2697 } while (mbuf_len
> 1 && mbuf
[0] != '.');
2699 (void)BIO_flush(fbio
);
2704 "Didn't find STARTTLS in server response,"
2705 " trying anyway...\n");
2706 BIO_printf(sbio
, "STARTTLS\r\n");
2707 mbuf_len
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2709 BIO_printf(bio_err
, "BIO_read failed\n");
2712 mbuf
[mbuf_len
] = '\0';
2713 if (strstr(mbuf
, "382") == NULL
) {
2714 BIO_printf(bio_err
, "STARTTLS failed: %s", mbuf
);
2722 BIO
*fbio
= BIO_new(BIO_f_buffer());
2725 BIO_printf(bio_err
, "Unable to create BIO\n");
2728 BIO_push(fbio
, sbio
);
2729 /* wait for multi-line response to end from Sieve */
2731 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2733 * According to RFC 5804 § 1.7, capability
2734 * is case-insensitive, make it uppercase
2736 if (mbuf_len
> 1 && mbuf
[0] == '"') {
2737 make_uppercase(mbuf
);
2738 if (HAS_PREFIX(mbuf
, "\"STARTTLS\""))
2741 } while (mbuf_len
> 1 && mbuf
[0] == '"');
2742 (void)BIO_flush(fbio
);
2747 "Didn't find STARTTLS in server response,"
2748 " trying anyway...\n");
2749 BIO_printf(sbio
, "STARTTLS\r\n");
2750 mbuf_len
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2752 BIO_printf(bio_err
, "BIO_read failed\n");
2755 mbuf
[mbuf_len
] = '\0';
2757 BIO_printf(bio_err
, "STARTTLS failed: %s", mbuf
);
2761 * According to RFC 5804 § 2.2, response codes are case-
2762 * insensitive, make it uppercase but preserve the response.
2764 strncpy(sbuf
, mbuf
, 2);
2765 make_uppercase(sbuf
);
2766 if (!HAS_PREFIX(sbuf
, "OK")) {
2767 BIO_printf(bio_err
, "STARTTLS not supported: %s", mbuf
);
2774 /* StartTLS Operation according to RFC 4511 */
2775 static char ldap_tls_genconf
[] = "asn1=SEQUENCE:LDAPMessage\n"
2777 "messageID=INTEGER:1\n"
2778 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2779 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2781 char *genstr
= NULL
;
2783 ASN1_TYPE
*atyp
= NULL
;
2784 BIO
*ldapbio
= BIO_new(BIO_s_mem());
2785 CONF
*cnf
= NCONF_new(NULL
);
2787 if (ldapbio
== NULL
|| cnf
== NULL
) {
2792 BIO_puts(ldapbio
, ldap_tls_genconf
);
2793 if (NCONF_load_bio(cnf
, ldapbio
, &errline
) <= 0) {
2797 BIO_printf(bio_err
, "NCONF_load_bio failed\n");
2800 BIO_printf(bio_err
, "Error on line %ld\n", errline
);
2805 genstr
= NCONF_get_string(cnf
, "default", "asn1");
2806 if (genstr
== NULL
) {
2808 BIO_printf(bio_err
, "NCONF_get_string failed\n");
2811 atyp
= ASN1_generate_nconf(genstr
, cnf
);
2814 BIO_printf(bio_err
, "ASN1_generate_nconf failed\n");
2819 /* Send SSLRequest packet */
2820 BIO_write(sbio
, atyp
->value
.sequence
->data
,
2821 atyp
->value
.sequence
->length
);
2822 (void)BIO_flush(sbio
);
2823 ASN1_TYPE_free(atyp
);
2825 mbuf_len
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2827 BIO_printf(bio_err
, "BIO_read failed\n");
2830 result
= ldap_ExtendedResponse_parse(mbuf
, mbuf_len
);
2832 BIO_printf(bio_err
, "ldap_ExtendedResponse_parse failed\n");
2834 } else if (result
> 0) {
2835 BIO_printf(bio_err
, "STARTTLS failed, LDAP Result Code: %i\n",
2844 if (early_data_file
!= NULL
2845 && ((SSL_get0_session(con
) != NULL
2846 && SSL_SESSION_get_max_early_data(SSL_get0_session(con
)) > 0)
2848 && SSL_SESSION_get_max_early_data(psksess
) > 0))) {
2849 BIO
*edfile
= BIO_new_file(early_data_file
, "r");
2850 size_t readbytes
, writtenbytes
;
2853 if (edfile
== NULL
) {
2854 BIO_printf(bio_err
, "Cannot open early data file\n");
2859 if (!BIO_read_ex(edfile
, cbuf
, BUFSIZZ
, &readbytes
))
2862 while (!SSL_write_early_data(con
, cbuf
, readbytes
, &writtenbytes
)) {
2863 switch (SSL_get_error(con
, 0)) {
2864 case SSL_ERROR_WANT_WRITE
:
2865 case SSL_ERROR_WANT_ASYNC
:
2866 case SSL_ERROR_WANT_READ
:
2867 /* Just keep trying - busy waiting */
2870 BIO_printf(bio_err
, "Error writing early data\n");
2880 user_data_init(&user_data
, con
, cbuf
, BUFSIZZ
, cmdmode
);
2885 if ((isdtls
|| isquic
)
2886 && SSL_get_event_timeout(con
, &timeout
, &is_infinite
)
2888 timeoutp
= &timeout
;
2892 if (!SSL_is_init_finished(con
) && SSL_total_renegotiations(con
) == 0
2893 && SSL_get_key_update_type(con
) == SSL_KEY_UPDATE_NONE
) {
2901 BIO_puts(bio_err
, "CONNECTION ESTABLISHED\n");
2902 print_ssl_summary(con
);
2905 print_stuff(bio_c_out
, con
, full_log
);
2909 if (starttls_proto
) {
2910 BIO_write(bio_err
, mbuf
, mbuf_len
);
2911 /* We don't need to know any more */
2913 starttls_proto
= PROTO_OFF
;
2918 BIO_printf(bio_c_out
,
2919 "drop connection and then reconnect\n");
2920 do_ssl_shutdown(con
);
2921 SSL_set_connect_state(con
);
2922 BIO_closesocket(SSL_get_fd(con
));
2930 switch (user_data_process(&user_data
, &cbuf_len
, &cbuf_off
)) {
2932 BIO_printf(bio_err
, "ERROR\n");
2934 case USER_DATA_PROCESS_SHUT
:
2938 case USER_DATA_PROCESS_RESTART
:
2941 case USER_DATA_PROCESS_NO_DATA
:
2944 case USER_DATA_PROCESS_CONTINUE
:
2950 && user_data_has_data(&user_data
));
2954 timeout
.tv_usec
= 0;
2960 ssl_pending
= read_ssl
&& SSL_has_pending(con
);
2963 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2966 * Note that select() returns when read _would not block_,
2967 * and EOF satisfies that. To avoid a CPU-hogging loop,
2968 * set the flag so we exit.
2970 if (read_tty
&& !at_eof
)
2971 openssl_fdset(fileno_stdin(), &readfds
);
2972 #if !defined(OPENSSL_SYS_VMS)
2974 openssl_fdset(fileno_stdout(), &writefds
);
2979 * Note that for QUIC we never actually check FD_ISSET() for the
2980 * underlying network fds. We just rely on select waking up when
2981 * they become readable/writeable and then SSL_handle_events() doing
2984 if ((!isquic
&& read_ssl
)
2985 || (isquic
&& SSL_net_read_desired(con
)))
2986 openssl_fdset(SSL_get_fd(con
), &readfds
);
2987 if ((!isquic
&& write_ssl
)
2988 || (isquic
&& (first_loop
|| SSL_net_write_desired(con
))))
2989 openssl_fdset(SSL_get_fd(con
), &writefds
);
2991 if (!tty_on
|| !write_tty
) {
2992 if ((!isquic
&& read_ssl
)
2993 || (isquic
&& SSL_net_read_desired(con
)))
2994 openssl_fdset(SSL_get_fd(con
), &readfds
);
2995 if ((!isquic
&& write_ssl
)
2996 || (isquic
&& (first_loop
|| SSL_net_write_desired(con
))))
2997 openssl_fdset(SSL_get_fd(con
), &writefds
);
3002 * Note: under VMS with SOCKETSHR the second parameter is
3003 * currently of type (int *) whereas under other systems it is
3004 * (void *) if you don't have a cast it will choke the compiler:
3005 * if you do have a cast then you can either go for (int *) or
3008 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
3010 * Under Windows/DOS we make the assumption that we can always
3011 * write to the tty: therefore, if we need to write to the tty we
3012 * just fall through. Otherwise we timeout the select every
3013 * second and see if there are any keypresses. Note: this is a
3014 * hack, in a proper Windows application we wouldn't do this.
3021 i
= select(width
, (void *)&readfds
, (void *)&writefds
,
3023 if (!i
&& (!has_stdin_waiting() || !read_tty
))
3026 i
= select(width
, (void *)&readfds
, (void *)&writefds
,
3030 i
= select(width
, (void *)&readfds
, (void *)&writefds
,
3034 BIO_printf(bio_err
, "bad select %d\n",
3035 get_last_socket_error());
3040 if (timeoutp
!= NULL
) {
3041 SSL_handle_events(con
);
3043 && !FD_ISSET(SSL_get_fd(con
), &readfds
)
3044 && !FD_ISSET(SSL_get_fd(con
), &writefds
))
3045 BIO_printf(bio_err
, "TIMEOUT occurred\n");
3049 && ((!isquic
&& FD_ISSET(SSL_get_fd(con
), &writefds
))
3050 || (isquic
&& (cbuf_len
> 0 || first_loop
)))) {
3051 k
= SSL_write(con
, &(cbuf
[cbuf_off
]), (unsigned int)cbuf_len
);
3052 switch (SSL_get_error(con
, k
)) {
3053 case SSL_ERROR_NONE
:
3058 /* we have done a write(con,NULL,0); */
3059 if (cbuf_len
== 0) {
3062 } else { /* if (cbuf_len > 0) */
3068 case SSL_ERROR_WANT_WRITE
:
3069 BIO_printf(bio_c_out
, "write W BLOCK\n");
3073 case SSL_ERROR_WANT_ASYNC
:
3074 BIO_printf(bio_c_out
, "write A BLOCK\n");
3075 wait_for_async(con
);
3079 case SSL_ERROR_WANT_READ
:
3080 BIO_printf(bio_c_out
, "write R BLOCK\n");
3085 case SSL_ERROR_WANT_X509_LOOKUP
:
3086 BIO_printf(bio_c_out
, "write X BLOCK\n");
3088 case SSL_ERROR_ZERO_RETURN
:
3089 if (cbuf_len
!= 0) {
3090 BIO_printf(bio_c_out
, "shutdown\n");
3099 case SSL_ERROR_SYSCALL
:
3100 if ((k
!= 0) || (cbuf_len
!= 0)) {
3101 int sockerr
= get_last_socket_error();
3103 if (!tfo
|| sockerr
!= EISCONN
) {
3104 BIO_printf(bio_err
, "write:errno=%d\n", sockerr
);
3112 case SSL_ERROR_WANT_ASYNC_JOB
:
3113 /* This shouldn't ever happen in s_client - treat as an error */
3118 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
3119 /* Assume Windows/DOS/BeOS can always write */
3120 else if (!ssl_pending
&& write_tty
)
3122 else if (!ssl_pending
&& FD_ISSET(fileno_stdout(), &writefds
))
3125 #ifdef CHARSET_EBCDIC
3126 ascii2ebcdic(&(sbuf
[sbuf_off
]), &(sbuf
[sbuf_off
]), sbuf_len
);
3128 i
= raw_write_stdout(&(sbuf
[sbuf_off
]), sbuf_len
);
3131 BIO_printf(bio_c_out
, "DONE\n");
3138 if (sbuf_len
<= 0) {
3142 } else if (ssl_pending
3143 || (!isquic
&& FD_ISSET(SSL_get_fd(con
), &readfds
))) {
3148 SSL_renegotiate(con
);
3153 k
= SSL_read(con
, sbuf
, BUFSIZZ
);
3155 switch (SSL_get_error(con
, k
)) {
3156 case SSL_ERROR_NONE
:
3165 case SSL_ERROR_WANT_ASYNC
:
3166 BIO_printf(bio_c_out
, "read A BLOCK\n");
3167 wait_for_async(con
);
3170 if ((read_tty
== 0) && (write_ssl
== 0))
3173 case SSL_ERROR_WANT_WRITE
:
3174 BIO_printf(bio_c_out
, "read W BLOCK\n");
3178 case SSL_ERROR_WANT_READ
:
3179 BIO_printf(bio_c_out
, "read R BLOCK\n");
3182 if ((read_tty
== 0) && (write_ssl
== 0))
3185 case SSL_ERROR_WANT_X509_LOOKUP
:
3186 BIO_printf(bio_c_out
, "read X BLOCK\n");
3188 case SSL_ERROR_SYSCALL
:
3189 ret
= get_last_socket_error();
3191 BIO_puts(bio_err
, "CONNECTION CLOSED BY SERVER\n");
3193 BIO_printf(bio_err
, "read:errno=%d\n", ret
);
3195 case SSL_ERROR_ZERO_RETURN
:
3196 BIO_printf(bio_c_out
, "closed\n");
3199 case SSL_ERROR_WANT_ASYNC_JOB
:
3200 /* This shouldn't ever happen in s_client. Treat as an error */
3206 /* don't wait for client input in the non-interactive mode */
3207 else if (nointeractive
) {
3212 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
3213 #if defined(OPENSSL_SYS_MSDOS)
3214 else if (has_stdin_waiting())
3216 else if (FD_ISSET(fileno_stdin(), &readfds
))
3222 i
= raw_read_stdin(cbuf
, BUFSIZZ
/ 2);
3224 /* both loops are skipped when i <= 0 */
3225 for (j
= 0; j
< i
; j
++)
3226 if (cbuf
[j
] == '\n')
3228 for (j
= i
- 1; j
>= 0; j
--) {
3229 cbuf
[j
+ lf_num
] = cbuf
[j
];
3230 if (cbuf
[j
] == '\n') {
3233 cbuf
[j
+ lf_num
] = '\r';
3236 assert(lf_num
== 0);
3238 i
= raw_read_stdin(cbuf
, BUFSIZZ
);
3239 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3244 if (!c_ign_eof
&& i
<= 0) {
3245 BIO_printf(bio_err
, "DONE\n");
3250 if (i
> 0 && !user_data_add(&user_data
, i
)) {
3261 ERR_print_errors(bio_err
); /* show any errors accumulated so far */
3263 print_stuff(bio_c_out
, con
, full_log
);
3264 do_ssl_shutdown(con
);
3267 * If we ended with an alert being sent, but still with data in the
3268 * network buffer to be read, then calling BIO_closesocket() will
3269 * result in a TCP-RST being sent. On some platforms (notably
3270 * Windows) then this will result in the peer immediately abandoning
3271 * the connection including any buffered alert data before it has
3272 * had a chance to be read. Shutting down the sending side first,
3273 * and then closing the socket sends TCP-FIN first followed by
3274 * TCP-RST. This seems to allow the peer to read the alert data.
3276 shutdown(SSL_get_fd(con
), 1); /* SHUT_WR */
3278 * We just said we have nothing else to say, but it doesn't mean that
3279 * the other side has nothing. It's even recommended to consume incoming
3280 * data. [In testing context this ensures that alerts are passed on...]
3283 timeout
.tv_usec
= 500000; /* some extreme round-trip */
3286 openssl_fdset(sock
, &readfds
);
3287 } while (select(sock
+ 1, &readfds
, NULL
, NULL
, &timeout
) > 0
3288 && BIO_read(sbio
, sbuf
, BUFSIZZ
) > 0);
3290 BIO_closesocket(SSL_get_fd(con
));
3293 ERR_print_errors(bio_err
); /* show any new or remaining errors */
3296 print_stuff(bio_c_out
, con
, 1);
3299 SSL_SESSION_free(psksess
);
3300 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3301 OPENSSL_free(next_proto
.data
);
3304 set_keylog_file(NULL
, NULL
);
3306 sk_X509_CRL_pop_free(crls
, X509_CRL_free
);
3308 OSSL_STACK_OF_X509_free(chain
);
3310 #ifndef OPENSSL_NO_SRP
3311 OPENSSL_free(srp_arg
.srppassin
);
3313 OPENSSL_free(sname_alloc
);
3314 BIO_ADDR_free(peer_addr
);
3315 OPENSSL_free(connectstr
);
3316 OPENSSL_free(bindstr
);
3317 OPENSSL_free(bindhost
);
3318 OPENSSL_free(bindport
);
3321 OPENSSL_free(thost
);
3322 OPENSSL_free(tport
);
3323 X509_VERIFY_PARAM_free(vpm
);
3324 ssl_excert_free(exc
);
3325 sk_OPENSSL_STRING_free(ssl_args
);
3326 sk_OPENSSL_STRING_free(dane_tlsa_rrset
);
3327 SSL_CONF_CTX_free(cctx
);
3328 OPENSSL_clear_free(cbuf
, BUFSIZZ
);
3329 OPENSSL_clear_free(sbuf
, BUFSIZZ
);
3330 OPENSSL_clear_free(mbuf
, BUFSIZZ
);
3331 clear_free(proxypass
);
3333 BIO_free(bio_c_out
);
3335 BIO_free(bio_c_msg
);
3340 static char *ec_curve_name(EVP_PKEY
*pkey
)
3345 if (EVP_PKEY_get_group_name(pkey
, NULL
, 0, &namelen
)) {
3346 curve
= OPENSSL_malloc(++namelen
);
3347 if (!EVP_PKEY_get_group_name(pkey
, curve
, namelen
, 0)) {
3348 OPENSSL_free(curve
);
3355 static void print_cert_key_info(BIO
*bio
, X509
*cert
)
3357 EVP_PKEY
*pkey
= X509_get0_pubkey(cert
);
3363 keyalg
= EVP_PKEY_get0_type_name(pkey
);
3365 keyalg
= OBJ_nid2ln(EVP_PKEY_get_base_id(pkey
));
3366 if (EVP_PKEY_id(pkey
) == EVP_PKEY_EC
)
3367 curve
= ec_curve_name(pkey
);
3369 BIO_printf(bio
, " a:PKEY: %s, (%s); sigalg: %s\n",
3371 OBJ_nid2ln(X509_get_signature_nid(cert
)));
3373 BIO_printf(bio
, " a:PKEY: %s, %d (bit); sigalg: %s\n",
3374 keyalg
, EVP_PKEY_get_bits(pkey
),
3375 OBJ_nid2ln(X509_get_signature_nid(cert
)));
3376 OPENSSL_free(curve
);
3379 static void print_stuff(BIO
*bio
, SSL
*s
, int full
)
3383 const SSL_CIPHER
*c
;
3384 int i
, istls13
= (SSL_version(s
) == TLS1_3_VERSION
);
3386 #ifndef OPENSSL_NO_COMP
3387 const COMP_METHOD
*comp
, *expansion
;
3389 unsigned char *exportedkeymat
;
3390 #ifndef OPENSSL_NO_CT
3391 const SSL_CTX
*ctx
= SSL_get_SSL_CTX(s
);
3395 int got_a_chain
= 0;
3397 sk
= SSL_get_peer_cert_chain(s
);
3401 BIO_printf(bio
, "---\nCertificate chain\n");
3402 for (i
= 0; i
< sk_X509_num(sk
); i
++) {
3403 X509
*chain_cert
= sk_X509_value(sk
, i
);
3405 BIO_printf(bio
, "%2d s:", i
);
3406 X509_NAME_print_ex(bio
, X509_get_subject_name(chain_cert
), 0, get_nameopt());
3407 BIO_puts(bio
, "\n");
3408 BIO_printf(bio
, " i:");
3409 X509_NAME_print_ex(bio
, X509_get_issuer_name(chain_cert
), 0, get_nameopt());
3410 BIO_puts(bio
, "\n");
3411 print_cert_key_info(bio
, chain_cert
);
3412 BIO_printf(bio
, " v:NotBefore: ");
3413 ASN1_TIME_print(bio
, X509_get0_notBefore(chain_cert
));
3414 BIO_printf(bio
, "; NotAfter: ");
3415 ASN1_TIME_print(bio
, X509_get0_notAfter(chain_cert
));
3416 BIO_puts(bio
, "\n");
3418 PEM_write_bio_X509(bio
, chain_cert
);
3422 BIO_printf(bio
, "---\n");
3423 peer
= SSL_get0_peer_certificate(s
);
3425 BIO_printf(bio
, "Server certificate\n");
3427 /* Redundant if we showed the whole chain */
3428 if (!(c_showcerts
&& got_a_chain
))
3429 PEM_write_bio_X509(bio
, peer
);
3430 dump_cert_text(bio
, peer
);
3432 BIO_printf(bio
, "no peer certificate available\n");
3435 /* Only display RPK information if configured */
3436 if (SSL_get_negotiated_client_cert_type(s
) == TLSEXT_cert_type_rpk
)
3437 BIO_printf(bio
, "Client-to-server raw public key negotiated\n");
3438 if (SSL_get_negotiated_server_cert_type(s
) == TLSEXT_cert_type_rpk
)
3439 BIO_printf(bio
, "Server-to-client raw public key negotiated\n");
3440 if (enable_server_rpk
) {
3441 EVP_PKEY
*peer_rpk
= SSL_get0_peer_rpk(s
);
3443 if (peer_rpk
!= NULL
) {
3444 BIO_printf(bio
, "Server raw public key\n");
3445 EVP_PKEY_print_public(bio
, peer_rpk
, 2, NULL
);
3447 BIO_printf(bio
, "no peer rpk available\n");
3451 print_ca_names(bio
, s
);
3453 ssl_print_sigalgs(bio
, s
);
3454 ssl_print_tmp_key(bio
, s
);
3456 #ifndef OPENSSL_NO_CT
3458 * When the SSL session is anonymous, or resumed via an abbreviated
3459 * handshake, no SCTs are provided as part of the handshake. While in
3460 * a resumed session SCTs may be present in the session's certificate,
3461 * no callbacks are invoked to revalidate these, and in any case that
3462 * set of SCTs may be incomplete. Thus it makes little sense to
3463 * attempt to display SCTs from a resumed session's certificate, and of
3464 * course none are associated with an anonymous peer.
3466 if (peer
!= NULL
&& !SSL_session_reused(s
) && SSL_ct_is_enabled(s
)) {
3467 const STACK_OF(SCT
) *scts
= SSL_get0_peer_scts(s
);
3468 int sct_count
= scts
!= NULL
? sk_SCT_num(scts
) : 0;
3470 BIO_printf(bio
, "---\nSCTs present (%i)\n", sct_count
);
3471 if (sct_count
> 0) {
3472 const CTLOG_STORE
*log_store
= SSL_CTX_get0_ctlog_store(ctx
);
3474 BIO_printf(bio
, "---\n");
3475 for (i
= 0; i
< sct_count
; ++i
) {
3476 SCT
*sct
= sk_SCT_value(scts
, i
);
3478 BIO_printf(bio
, "SCT validation status: %s\n",
3479 SCT_validation_status_string(sct
));
3480 SCT_print(sct
, bio
, 0, log_store
);
3481 if (i
< sct_count
- 1)
3482 BIO_printf(bio
, "\n---\n");
3484 BIO_printf(bio
, "\n");
3490 "---\nSSL handshake has read %ju bytes "
3491 "and written %ju bytes\n",
3492 BIO_number_read(SSL_get_rbio(s
)),
3493 BIO_number_written(SSL_get_wbio(s
)));
3495 print_verify_detail(s
, bio
);
3496 BIO_printf(bio
, (SSL_session_reused(s
) ? "---\nReused, " : "---\nNew, "));
3497 c
= SSL_get_current_cipher(s
);
3498 BIO_printf(bio
, "%s, Cipher is %s\n",
3499 SSL_CIPHER_get_version(c
), SSL_CIPHER_get_name(c
));
3500 BIO_printf(bio
, "Protocol: %s\n", SSL_get_version(s
));
3504 pktmp
= X509_get0_pubkey(peer
);
3505 BIO_printf(bio
, "Server public key is %d bit\n",
3506 EVP_PKEY_get_bits(pktmp
));
3509 ssl_print_secure_renegotiation_notes(bio
, s
);
3511 #ifndef OPENSSL_NO_COMP
3512 comp
= SSL_get_current_compression(s
);
3513 expansion
= SSL_get_current_expansion(s
);
3514 BIO_printf(bio
, "Compression: %s\n",
3515 comp
? SSL_COMP_get_name(comp
) : "NONE");
3516 BIO_printf(bio
, "Expansion: %s\n",
3517 expansion
? SSL_COMP_get_name(expansion
) : "NONE");
3519 #ifndef OPENSSL_NO_KTLS
3520 if (BIO_get_ktls_send(SSL_get_wbio(s
)))
3521 BIO_printf(bio_err
, "Using Kernel TLS for sending\n");
3522 if (BIO_get_ktls_recv(SSL_get_rbio(s
)))
3523 BIO_printf(bio_err
, "Using Kernel TLS for receiving\n");
3526 if (OSSL_TRACE_ENABLED(TLS
)) {
3527 /* Print out local port of connection: useful for debugging */
3529 union BIO_sock_info_u info
;
3531 sock
= SSL_get_fd(s
);
3532 if ((info
.addr
= BIO_ADDR_new()) != NULL
3533 && BIO_sock_info(sock
, BIO_SOCK_INFO_ADDRESS
, &info
)) {
3534 BIO_printf(bio_c_out
, "LOCAL PORT is %u\n",
3535 ntohs(BIO_ADDR_rawport(info
.addr
)));
3537 BIO_ADDR_free(info
.addr
);
3540 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3541 if (next_proto
.status
!= -1) {
3542 const unsigned char *proto
;
3543 unsigned int proto_len
;
3544 SSL_get0_next_proto_negotiated(s
, &proto
, &proto_len
);
3545 BIO_printf(bio
, "Next protocol: (%d) ", next_proto
.status
);
3546 BIO_write(bio
, proto
, proto_len
);
3547 BIO_write(bio
, "\n", 1);
3551 const unsigned char *proto
;
3552 unsigned int proto_len
;
3553 SSL_get0_alpn_selected(s
, &proto
, &proto_len
);
3554 if (proto_len
> 0) {
3555 BIO_printf(bio
, "ALPN protocol: ");
3556 BIO_write(bio
, proto
, proto_len
);
3557 BIO_write(bio
, "\n", 1);
3559 BIO_printf(bio
, "No ALPN negotiated\n");
3562 #ifndef OPENSSL_NO_SRTP
3564 SRTP_PROTECTION_PROFILE
*srtp_profile
=
3565 SSL_get_selected_srtp_profile(s
);
3568 BIO_printf(bio
, "SRTP Extension negotiated, profile=%s\n",
3569 srtp_profile
->name
);
3574 switch (SSL_get_early_data_status(s
)) {
3575 case SSL_EARLY_DATA_NOT_SENT
:
3576 BIO_printf(bio
, "Early data was not sent\n");
3579 case SSL_EARLY_DATA_REJECTED
:
3580 BIO_printf(bio
, "Early data was rejected\n");
3583 case SSL_EARLY_DATA_ACCEPTED
:
3584 BIO_printf(bio
, "Early data was accepted\n");
3590 * We also print the verify results when we dump session information,
3591 * but in TLSv1.3 we may not get that right away (or at all) depending
3592 * on when we get a NewSessionTicket. Therefore, we print it now as well.
3594 verify_result
= SSL_get_verify_result(s
);
3595 BIO_printf(bio
, "Verify return code: %ld (%s)\n", verify_result
,
3596 X509_verify_cert_error_string(verify_result
));
3598 /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3599 SSL_SESSION_print(bio
, SSL_get_session(s
));
3602 if (SSL_get_session(s
) != NULL
&& keymatexportlabel
!= NULL
) {
3603 BIO_printf(bio
, "Keying material exporter:\n");
3604 BIO_printf(bio
, " Label: '%s'\n", keymatexportlabel
);
3605 BIO_printf(bio
, " Length: %i bytes\n", keymatexportlen
);
3606 exportedkeymat
= app_malloc(keymatexportlen
, "export key");
3607 if (SSL_export_keying_material(s
, exportedkeymat
,
3610 strlen(keymatexportlabel
),
3612 BIO_printf(bio
, " Error\n");
3614 BIO_printf(bio
, " Keying material: ");
3615 for (i
= 0; i
< keymatexportlen
; i
++)
3616 BIO_printf(bio
, "%02X", exportedkeymat
[i
]);
3617 BIO_printf(bio
, "\n");
3619 OPENSSL_free(exportedkeymat
);
3621 BIO_printf(bio
, "---\n");
3622 /* flush, or debugging output gets mixed with http response */
3623 (void)BIO_flush(bio
);
3626 # ifndef OPENSSL_NO_OCSP
3627 static int ocsp_resp_cb(SSL
*s
, void *arg
)
3629 const unsigned char *p
;
3632 len
= SSL_get_tlsext_status_ocsp_resp(s
, &p
);
3633 BIO_puts(arg
, "OCSP response: ");
3635 BIO_puts(arg
, "no response sent\n");
3638 rsp
= d2i_OCSP_RESPONSE(NULL
, &p
, len
);
3640 BIO_puts(arg
, "response parse error\n");
3641 BIO_dump_indent(arg
, (char *)p
, len
, 4);
3644 BIO_puts(arg
, "\n======================================\n");
3645 OCSP_RESPONSE_print(arg
, rsp
, 0);
3646 BIO_puts(arg
, "======================================\n");
3647 OCSP_RESPONSE_free(rsp
);
3652 static int ldap_ExtendedResponse_parse(const char *buf
, long rem
)
3654 const unsigned char *cur
, *end
;
3656 int tag
, xclass
, inf
, ret
= -1;
3658 cur
= (const unsigned char *)buf
;
3664 * LDAPMessage ::= SEQUENCE {
3665 * messageID MessageID,
3666 * protocolOp CHOICE {
3668 * extendedResp ExtendedResponse,
3670 * controls [0] Controls OPTIONAL }
3672 * ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3673 * COMPONENTS OF LDAPResult,
3674 * responseName [10] LDAPOID OPTIONAL,
3675 * responseValue [11] OCTET STRING OPTIONAL }
3677 * LDAPResult ::= SEQUENCE {
3678 * resultCode ENUMERATED {
3684 * diagnosticMessage LDAPString,
3685 * referral [3] Referral OPTIONAL }
3689 inf
= ASN1_get_object(&cur
, &len
, &tag
, &xclass
, rem
);
3690 if (inf
!= V_ASN1_CONSTRUCTED
|| tag
!= V_ASN1_SEQUENCE
||
3691 (rem
= (long)(end
- cur
), len
> rem
)) {
3692 BIO_printf(bio_err
, "Unexpected LDAP response\n");
3696 rem
= len
; /* ensure that we don't overstep the SEQUENCE */
3698 /* pull MessageID */
3699 inf
= ASN1_get_object(&cur
, &len
, &tag
, &xclass
, rem
);
3700 if (inf
!= V_ASN1_UNIVERSAL
|| tag
!= V_ASN1_INTEGER
||
3701 (rem
= (long)(end
- cur
), len
> rem
)) {
3702 BIO_printf(bio_err
, "No MessageID\n");
3706 cur
+= len
; /* shall we check for MessageId match or just skip? */
3708 /* pull [APPLICATION 24] */
3709 rem
= (long)(end
- cur
);
3710 inf
= ASN1_get_object(&cur
, &len
, &tag
, &xclass
, rem
);
3711 if (inf
!= V_ASN1_CONSTRUCTED
|| xclass
!= V_ASN1_APPLICATION
||
3713 BIO_printf(bio_err
, "Not ExtendedResponse\n");
3717 /* pull resultCode */
3718 rem
= (long)(end
- cur
);
3719 inf
= ASN1_get_object(&cur
, &len
, &tag
, &xclass
, rem
);
3720 if (inf
!= V_ASN1_UNIVERSAL
|| tag
!= V_ASN1_ENUMERATED
|| len
== 0 ||
3721 (rem
= (long)(end
- cur
), len
> rem
)) {
3722 BIO_printf(bio_err
, "Not LDAPResult\n");
3726 /* len should always be one, but just in case... */
3727 for (ret
= 0, inf
= 0; inf
< len
; inf
++) {
3731 /* There is more data, but we don't care... */
3737 * Host dNS Name verifier: used for checking that the hostname is in dNS format
3738 * before setting it as SNI
3740 static int is_dNS_name(const char *host
)
3742 const size_t MAX_LABEL_LENGTH
= 63;
3745 size_t length
= strlen(host
);
3746 size_t label_length
= 0;
3747 int all_numeric
= 1;
3750 * Deviation from strict DNS name syntax, also check names with '_'
3751 * Check DNS name syntax, any '-' or '.' must be internal,
3752 * and on either side of each '.' we can't have a '-' or '.'.
3754 * If the name has just one label, we don't consider it a DNS name.
3756 for (i
= 0; i
< length
&& label_length
< MAX_LABEL_LENGTH
; ++i
) {
3759 if ((c
>= 'a' && c
<= 'z')
3760 || (c
>= 'A' && c
<= 'Z')
3767 if (c
>= '0' && c
<= '9') {
3772 /* Dot and hyphen cannot be first or last. */
3773 if (i
> 0 && i
< length
- 1) {
3779 * Next to a dot the preceding and following characters must not be
3780 * another dot or a hyphen. Otherwise, record that the name is
3781 * plausible, since it has two or more labels.
3784 && host
[i
+ 1] != '.'
3785 && host
[i
- 1] != '-'
3786 && host
[i
+ 1] != '-') {
3796 /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
3797 isdnsname
&= !all_numeric
&& !(label_length
== MAX_LABEL_LENGTH
);
3802 static void user_data_init(struct user_data_st
*user_data
, SSL
*con
, char *buf
,
3803 size_t bufmax
, int mode
)
3805 user_data
->con
= con
;
3806 user_data
->buf
= buf
;
3807 user_data
->bufmax
= bufmax
;
3808 user_data
->buflen
= 0;
3809 user_data
->bufoff
= 0;
3810 user_data
->mode
= mode
;
3811 user_data
->isfin
= 0;
3814 static int user_data_add(struct user_data_st
*user_data
, size_t i
)
3816 if (user_data
->buflen
!= 0 || i
> user_data
->bufmax
)
3819 user_data
->buflen
= i
;
3820 user_data
->bufoff
= 0;
3825 #define USER_COMMAND_HELP 0
3826 #define USER_COMMAND_QUIT 1
3827 #define USER_COMMAND_RECONNECT 2
3828 #define USER_COMMAND_RENEGOTIATE 3
3829 #define USER_COMMAND_KEY_UPDATE 4
3830 #define USER_COMMAND_FIN 5
3832 static int user_data_execute(struct user_data_st
*user_data
, int cmd
, char *arg
)
3835 case USER_COMMAND_HELP
:
3836 /* This only ever occurs in advanced mode, so just emit advanced help */
3837 BIO_printf(bio_err
, "Enter text to send to the peer followed by <enter>\n");
3838 BIO_printf(bio_err
, "To issue a command insert {cmd} or {cmd:arg} anywhere in the text\n");
3839 BIO_printf(bio_err
, "Entering {{ will send { to the peer\n");
3840 BIO_printf(bio_err
, "The following commands are available\n");
3841 BIO_printf(bio_err
, " {help}: Get this help text\n");
3842 BIO_printf(bio_err
, " {quit}: Close the connection to the peer\n");
3843 BIO_printf(bio_err
, " {reconnect}: Reconnect to the peer\n");
3844 if (SSL_is_quic(user_data
->con
)) {
3845 BIO_printf(bio_err
, " {fin}: Send FIN on the stream. No further writing is possible\n");
3846 } else if(SSL_version(user_data
->con
) == TLS1_3_VERSION
) {
3847 BIO_printf(bio_err
, " {keyup:req|noreq}: Send a Key Update message\n");
3848 BIO_printf(bio_err
, " Arguments:\n");
3849 BIO_printf(bio_err
, " req = peer update requested (default)\n");
3850 BIO_printf(bio_err
, " noreq = peer update not requested\n");
3852 BIO_printf(bio_err
, " {reneg}: Attempt to renegotiate\n");
3854 BIO_printf(bio_err
, "\n");
3855 return USER_DATA_PROCESS_NO_DATA
;
3857 case USER_COMMAND_QUIT
:
3858 BIO_printf(bio_err
, "DONE\n");
3859 return USER_DATA_PROCESS_SHUT
;
3861 case USER_COMMAND_RECONNECT
:
3862 BIO_printf(bio_err
, "RECONNECTING\n");
3863 do_ssl_shutdown(user_data
->con
);
3864 SSL_set_connect_state(user_data
->con
);
3865 BIO_closesocket(SSL_get_fd(user_data
->con
));
3866 return USER_DATA_PROCESS_RESTART
;
3868 case USER_COMMAND_RENEGOTIATE
:
3869 BIO_printf(bio_err
, "RENEGOTIATING\n");
3870 if (!SSL_renegotiate(user_data
->con
))
3872 return USER_DATA_PROCESS_CONTINUE
;
3874 case USER_COMMAND_KEY_UPDATE
: {
3877 if (OPENSSL_strcasecmp(arg
, "req") == 0)
3878 updatetype
= SSL_KEY_UPDATE_REQUESTED
;
3879 else if (OPENSSL_strcasecmp(arg
, "noreq") == 0)
3880 updatetype
= SSL_KEY_UPDATE_NOT_REQUESTED
;
3882 return USER_DATA_PROCESS_BAD_ARGUMENT
;
3883 BIO_printf(bio_err
, "KEYUPDATE\n");
3884 if (!SSL_key_update(user_data
->con
, updatetype
))
3886 return USER_DATA_PROCESS_CONTINUE
;
3889 case USER_COMMAND_FIN
:
3890 if (!SSL_stream_conclude(user_data
->con
, 0))
3892 user_data
->isfin
= 1;
3893 return USER_DATA_PROCESS_NO_DATA
;
3899 BIO_printf(bio_err
, "ERROR\n");
3900 return USER_DATA_PROCESS_SHUT
;
3903 static int user_data_process(struct user_data_st
*user_data
, size_t *len
,
3906 char *buf_start
= user_data
->buf
+ user_data
->bufoff
;
3907 size_t outlen
= user_data
->buflen
;
3909 if (user_data
->buflen
== 0) {
3912 return USER_DATA_PROCESS_NO_DATA
;
3915 if (user_data
->mode
== USER_DATA_MODE_BASIC
) {
3916 switch (buf_start
[0]) {
3918 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3919 return user_data_execute(user_data
, USER_COMMAND_QUIT
, NULL
);
3922 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3923 return user_data_execute(user_data
, USER_COMMAND_RECONNECT
, NULL
);
3926 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3927 return user_data_execute(user_data
, USER_COMMAND_RENEGOTIATE
, NULL
);
3931 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3932 return user_data_execute(user_data
, USER_COMMAND_KEY_UPDATE
,
3933 buf_start
[0] == 'K' ? "req" : "noreq");
3937 } else if (user_data
->mode
== USER_DATA_MODE_ADVANCED
) {
3938 char *cmd_start
= buf_start
;
3940 cmd_start
[outlen
] = '\0';
3942 cmd_start
= strchr(cmd_start
, '{');
3943 if (cmd_start
== buf_start
&& *(cmd_start
+ 1) == '{') {
3944 /* The "{" is escaped, so skip it */
3947 user_data
->bufoff
++;
3948 user_data
->buflen
--;
3955 if (cmd_start
== buf_start
) {
3956 /* Command detected */
3957 char *cmd_end
= strchr(cmd_start
, '}');
3959 int cmd
= -1, ret
= USER_DATA_PROCESS_NO_DATA
;
3962 if (cmd_end
== NULL
) {
3963 /* Malformed command */
3964 cmd_start
[outlen
- 1] = '\0';
3966 "ERROR PROCESSING COMMAND. REST OF LINE IGNORED: %s\n",
3968 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3969 return USER_DATA_PROCESS_NO_DATA
;
3972 arg_start
= strchr(cmd_start
, ':');
3973 if (arg_start
!= NULL
) {
3977 /* Skip over the { */
3980 * Now we have cmd_start pointing to a NUL terminated string for
3981 * the command, and arg_start either being NULL or pointing to a
3982 * NUL terminated string for the argument.
3984 if (OPENSSL_strcasecmp(cmd_start
, "help") == 0) {
3985 cmd
= USER_COMMAND_HELP
;
3986 } else if (OPENSSL_strcasecmp(cmd_start
, "quit") == 0) {
3987 cmd
= USER_COMMAND_QUIT
;
3988 } else if (OPENSSL_strcasecmp(cmd_start
, "reconnect") == 0) {
3989 cmd
= USER_COMMAND_RECONNECT
;
3990 } else if(SSL_is_quic(user_data
->con
)) {
3991 if (OPENSSL_strcasecmp(cmd_start
, "fin") == 0)
3992 cmd
= USER_COMMAND_FIN
;
3993 } if (SSL_version(user_data
->con
) == TLS1_3_VERSION
) {
3994 if (OPENSSL_strcasecmp(cmd_start
, "keyup") == 0) {
3995 cmd
= USER_COMMAND_KEY_UPDATE
;
3996 if (arg_start
== NULL
)
4000 /* (D)TLSv1.2 or below */
4001 if (OPENSSL_strcasecmp(cmd_start
, "reneg") == 0)
4002 cmd
= USER_COMMAND_RENEGOTIATE
;
4005 BIO_printf(bio_err
, "UNRECOGNISED COMMAND (IGNORED): %s\n",
4008 ret
= user_data_execute(user_data
, cmd
, arg_start
);
4009 if (ret
== USER_DATA_PROCESS_BAD_ARGUMENT
) {
4010 BIO_printf(bio_err
, "BAD ARGUMENT (COMMAND IGNORED): %s\n",
4012 ret
= USER_DATA_PROCESS_NO_DATA
;
4015 oldoff
= user_data
->bufoff
;
4016 user_data
->bufoff
= (cmd_end
- user_data
->buf
) + 1;
4017 user_data
->buflen
-= user_data
->bufoff
- oldoff
;
4018 if (user_data
->buf
+ 1 == cmd_start
4019 && user_data
->buflen
== 1
4020 && user_data
->buf
[user_data
->bufoff
] == '\n') {
4022 * This command was the only thing on the whole line. We
4023 * suppress the final `\n`
4025 user_data
->bufoff
= 0;
4026 user_data
->buflen
= 0;
4030 } else if (cmd_start
!= NULL
) {
4032 * There is a command on this line, but its not at the start. Output
4033 * the start of the line, and we'll process the command next time
4034 * we call this function
4036 outlen
= cmd_start
- buf_start
;
4040 if (user_data
->isfin
) {
4041 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
4042 return USER_DATA_PROCESS_NO_DATA
;
4045 #ifdef CHARSET_EBCDIC
4046 ebcdic2ascii(buf_start
, buf_start
, outlen
);
4049 *off
= user_data
->bufoff
;
4050 user_data
->buflen
-= outlen
;
4051 if (user_data
->buflen
== 0)
4052 user_data
->bufoff
= 0;
4054 user_data
->bufoff
+= outlen
;
4055 return USER_DATA_PROCESS_CONTINUE
;
4058 static int user_data_has_data(struct user_data_st
*user_data
)
4060 return user_data
->buflen
> 0;
4062 #endif /* OPENSSL_NO_SOCK */