2 * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright 2005 Nokia. All rights reserved.
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
11 #include "internal/e_os.h"
17 #include <openssl/e_os2.h>
18 #include "internal/nelem.h"
20 #ifndef OPENSSL_NO_SOCK
23 * With IPv6, it looks like Digital has mixed up the proper order of
24 * recursive header file inclusion, resulting in the compiler complaining
25 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
26 * needed to have fileno() declared correctly... So let's define u_int
28 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
30 typedef unsigned int u_int
;
35 #include <openssl/x509.h>
36 #include <openssl/ssl.h>
37 #include <openssl/err.h>
38 #include <openssl/pem.h>
39 #include <openssl/rand.h>
40 #include <openssl/ocsp.h>
41 #include <openssl/bn.h>
42 #include <openssl/trace.h>
43 #include <openssl/async.h>
45 # include <openssl/ct.h>
49 #include "internal/sockets.h"
51 #if defined(__has_feature)
52 # if __has_feature(memory_sanitizer)
53 # include <sanitizer/msan_interface.h>
58 #define BUFSIZZ 1024*8
59 #define S_CLIENT_IRC_READ_TIMEOUT 8
61 #define USER_DATA_MODE_NONE 0
62 #define USER_DATA_MODE_BASIC 1
63 #define USER_DATA_MODE_ADVANCED 2
65 #define USER_DATA_PROCESS_BAD_ARGUMENT 0
66 #define USER_DATA_PROCESS_SHUT 1
67 #define USER_DATA_PROCESS_RESTART 2
68 #define USER_DATA_PROCESS_NO_DATA 3
69 #define USER_DATA_PROCESS_CONTINUE 4
72 /* SSL connection we are processing commands for */
75 /* Buffer where we are storing data supplied by the user */
78 /* Allocated size of the buffer */
81 /* Amount of the buffer actually used */
84 /* Current location in the buffer where we will read from next*/
87 /* The mode we are using for processing commands */
90 /* Whether FIN has ben sent on the stream */
94 static void user_data_init(struct user_data_st
*user_data
, SSL
*con
, char *buf
,
95 size_t bufmax
, int mode
);
96 static int user_data_add(struct user_data_st
*user_data
, size_t i
);
97 static int user_data_process(struct user_data_st
*user_data
, size_t *len
,
99 static int user_data_has_data(struct user_data_st
*user_data
);
102 static int c_debug
= 0;
103 static int c_showcerts
= 0;
104 static char *keymatexportlabel
= NULL
;
105 static int keymatexportlen
= 20;
106 static BIO
*bio_c_out
= NULL
;
107 static int c_quiet
= 0;
108 static char *sess_out
= NULL
;
109 static SSL_SESSION
*psksess
= NULL
;
111 static void print_stuff(BIO
*berr
, SSL
*con
, int full
);
112 #ifndef OPENSSL_NO_OCSP
113 static int ocsp_resp_cb(SSL
*s
, void *arg
);
115 static int ldap_ExtendedResponse_parse(const char *buf
, long rem
);
116 static int is_dNS_name(const char *host
);
118 static const unsigned char cert_type_rpk
[] = { TLSEXT_cert_type_rpk
, TLSEXT_cert_type_x509
};
119 static int enable_server_rpk
= 0;
121 static int saved_errno
;
123 static void save_errno(void)
129 static int restore_errno(void)
136 /* Default PSK identity and key */
137 static char *psk_identity
= "Client_identity";
139 #ifndef OPENSSL_NO_PSK
140 static unsigned int psk_client_cb(SSL
*ssl
, const char *hint
, char *identity
,
141 unsigned int max_identity_len
,
143 unsigned int max_psk_len
)
150 BIO_printf(bio_c_out
, "psk_client_cb\n");
152 /* no ServerKeyExchange message */
154 BIO_printf(bio_c_out
,
155 "NULL received PSK identity hint, continuing anyway\n");
156 } else if (c_debug
) {
157 BIO_printf(bio_c_out
, "Received PSK identity hint '%s'\n", hint
);
161 * lookup PSK identity and PSK key based on the given identity hint here
163 ret
= BIO_snprintf(identity
, max_identity_len
, "%s", psk_identity
);
164 if (ret
< 0 || (unsigned int)ret
> max_identity_len
)
167 BIO_printf(bio_c_out
, "created identity '%s' len=%d\n", identity
,
170 /* convert the PSK key to binary */
171 key
= OPENSSL_hexstr2buf(psk_key
, &key_len
);
173 BIO_printf(bio_err
, "Could not convert PSK key '%s' to buffer\n",
177 if (max_psk_len
> INT_MAX
|| key_len
> (long)max_psk_len
) {
179 "psk buffer of callback is too small (%d) for key (%ld)\n",
180 max_psk_len
, key_len
);
185 memcpy(psk
, key
, key_len
);
189 BIO_printf(bio_c_out
, "created PSK len=%ld\n", key_len
);
194 BIO_printf(bio_err
, "Error in PSK client callback\n");
199 const unsigned char tls13_aes128gcmsha256_id
[] = { 0x13, 0x01 };
200 const unsigned char tls13_aes256gcmsha384_id
[] = { 0x13, 0x02 };
202 static int psk_use_session_cb(SSL
*s
, const EVP_MD
*md
,
203 const unsigned char **id
, size_t *idlen
,
206 SSL_SESSION
*usesess
= NULL
;
207 const SSL_CIPHER
*cipher
= NULL
;
209 if (psksess
!= NULL
) {
210 SSL_SESSION_up_ref(psksess
);
214 unsigned char *key
= OPENSSL_hexstr2buf(psk_key
, &key_len
);
217 BIO_printf(bio_err
, "Could not convert PSK key '%s' to buffer\n",
222 /* We default to SHA-256 */
223 cipher
= SSL_CIPHER_find(s
, tls13_aes128gcmsha256_id
);
224 if (cipher
== NULL
) {
225 BIO_printf(bio_err
, "Error finding suitable ciphersuite\n");
230 usesess
= SSL_SESSION_new();
232 || !SSL_SESSION_set1_master_key(usesess
, key
, key_len
)
233 || !SSL_SESSION_set_cipher(usesess
, cipher
)
234 || !SSL_SESSION_set_protocol_version(usesess
, TLS1_3_VERSION
)) {
241 cipher
= SSL_SESSION_get0_cipher(usesess
);
245 if (md
!= NULL
&& SSL_CIPHER_get_handshake_digest(cipher
) != md
) {
246 /* PSK not usable, ignore it */
250 SSL_SESSION_free(usesess
);
253 *id
= (unsigned char *)psk_identity
;
254 *idlen
= strlen(psk_identity
);
260 SSL_SESSION_free(usesess
);
264 /* This is a context that we pass to callbacks */
265 typedef struct tlsextctx_st
{
270 static int ssl_servername_cb(SSL
*s
, int *ad
, void *arg
)
272 tlsextctx
*p
= (tlsextctx
*) arg
;
273 const char *hn
= SSL_get_servername(s
, TLSEXT_NAMETYPE_host_name
);
274 if (SSL_get_servername_type(s
) != -1)
275 p
->ack
= !SSL_session_reused(s
) && hn
!= NULL
;
277 BIO_printf(bio_err
, "Can't use SSL_get_servername\n");
279 return SSL_TLSEXT_ERR_OK
;
282 #ifndef OPENSSL_NO_NEXTPROTONEG
283 /* This the context that we pass to next_proto_cb */
284 typedef struct tlsextnextprotoctx_st
{
288 } tlsextnextprotoctx
;
290 static tlsextnextprotoctx next_proto
;
292 static int next_proto_cb(SSL
*s
, unsigned char **out
, unsigned char *outlen
,
293 const unsigned char *in
, unsigned int inlen
,
296 tlsextnextprotoctx
*ctx
= arg
;
299 /* We can assume that |in| is syntactically valid. */
301 BIO_printf(bio_c_out
, "Protocols advertised by server: ");
302 for (i
= 0; i
< inlen
;) {
304 BIO_write(bio_c_out
, ", ", 2);
305 BIO_write(bio_c_out
, &in
[i
+ 1], in
[i
]);
308 BIO_write(bio_c_out
, "\n", 1);
312 SSL_select_next_proto(out
, outlen
, in
, inlen
, ctx
->data
, ctx
->len
);
313 return SSL_TLSEXT_ERR_OK
;
315 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
317 static int serverinfo_cli_parse_cb(SSL
*s
, unsigned int ext_type
,
318 const unsigned char *in
, size_t inlen
,
322 unsigned char ext_buf
[4 + 65536];
324 /* Reconstruct the type/len fields prior to extension data */
325 inlen
&= 0xffff; /* for formal memcmpy correctness */
326 ext_buf
[0] = (unsigned char)(ext_type
>> 8);
327 ext_buf
[1] = (unsigned char)(ext_type
);
328 ext_buf
[2] = (unsigned char)(inlen
>> 8);
329 ext_buf
[3] = (unsigned char)(inlen
);
330 memcpy(ext_buf
+ 4, in
, inlen
);
332 BIO_snprintf(pem_name
, sizeof(pem_name
), "SERVERINFO FOR EXTENSION %d",
334 PEM_write_bio(bio_c_out
, pem_name
, "", ext_buf
, 4 + inlen
);
339 * Hex decoder that tolerates optional whitespace. Returns number of bytes
340 * produced, advances inptr to end of input string.
342 static ossl_ssize_t
hexdecode(const char **inptr
, void *result
)
344 unsigned char **out
= (unsigned char **)result
;
345 const char *in
= *inptr
;
346 unsigned char *ret
= app_malloc(strlen(in
) / 2, "hexdecode");
347 unsigned char *cp
= ret
;
354 for (byte
= 0; *in
; ++in
) {
357 if (isspace(_UC(*in
)))
359 x
= OPENSSL_hexchar2int(*in
);
365 if ((nibble
^= 1) == 0) {
378 return cp
- (*out
= ret
);
382 * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
383 * inptr to next field skipping leading whitespace.
385 static ossl_ssize_t
checked_uint8(const char **inptr
, void *out
)
387 uint8_t *result
= (uint8_t *)out
;
388 const char *in
= *inptr
;
394 v
= strtol(in
, &endp
, 10);
397 if (((v
== LONG_MIN
|| v
== LONG_MAX
) && e
== ERANGE
) ||
398 endp
== in
|| !isspace(_UC(*endp
)) ||
399 v
!= (*result
= (uint8_t) v
)) {
402 for (in
= endp
; isspace(_UC(*in
)); ++in
)
412 ossl_ssize_t (*parser
)(const char **, void *);
415 static int tlsa_import_rr(SSL
*con
, const char *rrdata
)
417 /* Not necessary to re-init these values; the "parsers" do that. */
418 static uint8_t usage
;
419 static uint8_t selector
;
420 static uint8_t mtype
;
421 static unsigned char *data
;
422 static struct tlsa_field tlsa_fields
[] = {
423 { &usage
, "usage", checked_uint8
},
424 { &selector
, "selector", checked_uint8
},
425 { &mtype
, "mtype", checked_uint8
},
426 { &data
, "data", hexdecode
},
429 struct tlsa_field
*f
;
431 const char *cp
= rrdata
;
432 ossl_ssize_t len
= 0;
434 for (f
= tlsa_fields
; f
->var
; ++f
) {
435 /* Returns number of bytes produced, advances cp to next field */
436 if ((len
= f
->parser(&cp
, f
->var
)) <= 0) {
437 BIO_printf(bio_err
, "%s: warning: bad TLSA %s field in: %s\n",
438 prog
, f
->name
, rrdata
);
442 /* The data field is last, so len is its length */
443 ret
= SSL_dane_tlsa_add(con
, usage
, selector
, mtype
, data
, len
);
447 ERR_print_errors(bio_err
);
448 BIO_printf(bio_err
, "%s: warning: unusable TLSA rrdata: %s\n",
453 ERR_print_errors(bio_err
);
454 BIO_printf(bio_err
, "%s: warning: error loading TLSA rrdata: %s\n",
461 static int tlsa_import_rrset(SSL
*con
, STACK_OF(OPENSSL_STRING
) *rrset
)
463 int num
= sk_OPENSSL_STRING_num(rrset
);
467 for (i
= 0; i
< num
; ++i
) {
468 char *rrdata
= sk_OPENSSL_STRING_value(rrset
, i
);
469 if (tlsa_import_rr(con
, rrdata
) > 0)
475 typedef enum OPTION_choice
{
477 OPT_4
, OPT_6
, OPT_HOST
, OPT_PORT
, OPT_CONNECT
, OPT_BIND
, OPT_UNIX
,
478 OPT_XMPPHOST
, OPT_VERIFY
, OPT_NAMEOPT
,
479 OPT_CERT
, OPT_CRL
, OPT_CRL_DOWNLOAD
, OPT_SESS_OUT
, OPT_SESS_IN
,
480 OPT_CERTFORM
, OPT_CRLFORM
, OPT_VERIFY_RET_ERROR
, OPT_VERIFY_QUIET
,
481 OPT_BRIEF
, OPT_PREXIT
, OPT_NO_INTERACTIVE
, OPT_CRLF
, OPT_QUIET
, OPT_NBIO
,
482 OPT_SSL_CLIENT_ENGINE
, OPT_IGN_EOF
, OPT_NO_IGN_EOF
,
483 OPT_DEBUG
, OPT_TLSEXTDEBUG
, OPT_STATUS
, OPT_WDEBUG
,
484 OPT_MSG
, OPT_MSGFILE
, OPT_ENGINE
, OPT_TRACE
, OPT_SECURITY_DEBUG
,
485 OPT_SECURITY_DEBUG_VERBOSE
, OPT_SHOWCERTS
, OPT_NBIO_TEST
, OPT_STATE
,
486 OPT_PSK_IDENTITY
, OPT_PSK
, OPT_PSK_SESS
,
487 #ifndef OPENSSL_NO_SRP
488 OPT_SRPUSER
, OPT_SRPPASS
, OPT_SRP_STRENGTH
, OPT_SRP_LATEUSER
,
491 OPT_SSL3
, OPT_SSL_CONFIG
,
492 OPT_TLS1_3
, OPT_TLS1_2
, OPT_TLS1_1
, OPT_TLS1
, OPT_DTLS
, OPT_DTLS1
,
493 OPT_DTLS1_2
, OPT_QUIC
, OPT_SCTP
, OPT_TIMEOUT
, OPT_MTU
, OPT_KEYFORM
,
494 OPT_PASS
, OPT_CERT_CHAIN
, OPT_KEY
, OPT_RECONNECT
, OPT_BUILD_CHAIN
,
495 OPT_NEXTPROTONEG
, OPT_ALPN
,
496 OPT_CAPATH
, OPT_NOCAPATH
, OPT_CHAINCAPATH
, OPT_VERIFYCAPATH
,
497 OPT_CAFILE
, OPT_NOCAFILE
, OPT_CHAINCAFILE
, OPT_VERIFYCAFILE
,
498 OPT_CASTORE
, OPT_NOCASTORE
, OPT_CHAINCASTORE
, OPT_VERIFYCASTORE
,
499 OPT_SERVERINFO
, OPT_STARTTLS
, OPT_SERVERNAME
, OPT_NOSERVERNAME
, OPT_ASYNC
,
500 OPT_USE_SRTP
, OPT_KEYMATEXPORT
, OPT_KEYMATEXPORTLEN
, OPT_PROTOHOST
,
501 OPT_MAXFRAGLEN
, OPT_MAX_SEND_FRAG
, OPT_SPLIT_SEND_FRAG
, OPT_MAX_PIPELINES
,
502 OPT_READ_BUF
, OPT_KEYLOG_FILE
, OPT_EARLY_DATA
, OPT_REQCAFILE
,
506 OPT_S_ENUM
, OPT_IGNORE_UNEXPECTED_EOF
,
507 OPT_FALLBACKSCSV
, OPT_NOCMDS
, OPT_ADV
, OPT_PROXY
, OPT_PROXY_USER
,
508 OPT_PROXY_PASS
, OPT_DANE_TLSA_DOMAIN
,
509 #ifndef OPENSSL_NO_CT
510 OPT_CT
, OPT_NOCT
, OPT_CTLOG_FILE
,
512 OPT_DANE_TLSA_RRDATA
, OPT_DANE_EE_NO_NAME
,
514 OPT_ENABLE_SERVER_RPK
,
515 OPT_ENABLE_CLIENT_RPK
,
518 OPT_R_ENUM
, OPT_PROV_ENUM
521 const OPTIONS s_client_options
[] = {
522 {OPT_HELP_STR
, 1, '-', "Usage: %s [options] [host:port]\n"},
524 OPT_SECTION("General"),
525 {"help", OPT_HELP
, '-', "Display this summary"},
526 #ifndef OPENSSL_NO_ENGINE
527 {"engine", OPT_ENGINE
, 's', "Use engine, possibly a hardware device"},
528 {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE
, 's',
529 "Specify engine to be used for client certificate operations"},
531 {"ssl_config", OPT_SSL_CONFIG
, 's', "Use specified section for SSL_CTX configuration"},
532 #ifndef OPENSSL_NO_CT
533 {"ct", OPT_CT
, '-', "Request and parse SCTs (also enables OCSP stapling)"},
534 {"noct", OPT_NOCT
, '-', "Do not request or parse SCTs (default)"},
535 {"ctlogfile", OPT_CTLOG_FILE
, '<', "CT log list CONF file"},
538 OPT_SECTION("Network"),
539 {"host", OPT_HOST
, 's', "Use -connect instead"},
540 {"port", OPT_PORT
, 'p', "Use -connect instead"},
541 {"connect", OPT_CONNECT
, 's',
542 "TCP/IP where to connect; default: " PORT
")"},
543 {"bind", OPT_BIND
, 's', "bind local address for connection"},
544 {"proxy", OPT_PROXY
, 's',
545 "Connect to via specified proxy to the real server"},
546 {"proxy_user", OPT_PROXY_USER
, 's', "UserID for proxy authentication"},
547 {"proxy_pass", OPT_PROXY_PASS
, 's', "Proxy authentication password source"},
549 {"unix", OPT_UNIX
, 's', "Connect over the specified Unix-domain socket"},
551 {"4", OPT_4
, '-', "Use IPv4 only"},
553 {"6", OPT_6
, '-', "Use IPv6 only"},
555 {"maxfraglen", OPT_MAXFRAGLEN
, 'p',
556 "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
557 {"max_send_frag", OPT_MAX_SEND_FRAG
, 'p', "Maximum Size of send frames "},
558 {"split_send_frag", OPT_SPLIT_SEND_FRAG
, 'p',
559 "Size used to split data for encrypt pipelines"},
560 {"max_pipelines", OPT_MAX_PIPELINES
, 'p',
561 "Maximum number of encrypt/decrypt pipelines to be used"},
562 {"read_buf", OPT_READ_BUF
, 'p',
563 "Default read buffer size to be used for connections"},
564 {"fallback_scsv", OPT_FALLBACKSCSV
, '-', "Send the fallback SCSV"},
566 OPT_SECTION("Identity"),
567 {"cert", OPT_CERT
, '<', "Client certificate file to use"},
568 {"certform", OPT_CERTFORM
, 'F',
569 "Client certificate file format (PEM/DER/P12); has no effect"},
570 {"cert_chain", OPT_CERT_CHAIN
, '<',
571 "Client certificate chain file (in PEM format)"},
572 {"build_chain", OPT_BUILD_CHAIN
, '-', "Build client certificate chain"},
573 {"key", OPT_KEY
, 's', "Private key file to use; default: -cert file"},
574 {"keyform", OPT_KEYFORM
, 'E', "Key format (ENGINE, other values ignored)"},
575 {"pass", OPT_PASS
, 's', "Private key and cert file pass phrase source"},
576 {"verify", OPT_VERIFY
, 'p', "Turn on peer certificate verification"},
577 {"nameopt", OPT_NAMEOPT
, 's', "Certificate subject/issuer name printing options"},
578 {"CApath", OPT_CAPATH
, '/', "PEM format directory of CA's"},
579 {"CAfile", OPT_CAFILE
, '<', "PEM format file of CA's"},
580 {"CAstore", OPT_CASTORE
, ':', "URI to store of CA's"},
581 {"no-CAfile", OPT_NOCAFILE
, '-',
582 "Do not load the default certificates file"},
583 {"no-CApath", OPT_NOCAPATH
, '-',
584 "Do not load certificates from the default certificates directory"},
585 {"no-CAstore", OPT_NOCASTORE
, '-',
586 "Do not load certificates from the default certificates store"},
587 {"requestCAfile", OPT_REQCAFILE
, '<',
588 "PEM format file of CA names to send to the server"},
589 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
590 {"tfo", OPT_TFO
, '-', "Connect using TCP Fast Open"},
592 {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN
, 's', "DANE TLSA base domain"},
593 {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA
, 's',
594 "DANE TLSA rrdata presentation form"},
595 {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME
, '-',
596 "Disable name checks when matching DANE-EE(3) TLSA records"},
597 {"psk_identity", OPT_PSK_IDENTITY
, 's', "PSK identity"},
598 {"psk", OPT_PSK
, 's', "PSK in hex (without 0x)"},
599 {"psk_session", OPT_PSK_SESS
, '<', "File to read PSK SSL session from"},
600 {"name", OPT_PROTOHOST
, 's',
601 "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
603 OPT_SECTION("Session"),
604 {"reconnect", OPT_RECONNECT
, '-',
605 "Drop and re-make the connection with the same Session-ID"},
606 {"sess_out", OPT_SESS_OUT
, '>', "File to write SSL session to"},
607 {"sess_in", OPT_SESS_IN
, '<', "File to read SSL session from"},
609 OPT_SECTION("Input/Output"),
610 {"crlf", OPT_CRLF
, '-', "Convert LF from terminal into CRLF"},
611 {"quiet", OPT_QUIET
, '-', "No s_client output"},
612 {"ign_eof", OPT_IGN_EOF
, '-', "Ignore input eof (default when -quiet)"},
613 {"no_ign_eof", OPT_NO_IGN_EOF
, '-', "Don't ignore input eof"},
614 {"starttls", OPT_STARTTLS
, 's',
615 "Use the appropriate STARTTLS command before starting TLS"},
616 {"xmpphost", OPT_XMPPHOST
, 's',
617 "Alias of -name option for \"-starttls xmpp[-server]\""},
618 {"brief", OPT_BRIEF
, '-',
619 "Restrict output to brief summary of connection parameters"},
620 {"prexit", OPT_PREXIT
, '-',
621 "Print session information when the program exits"},
622 {"no-interactive", OPT_NO_INTERACTIVE
, '-',
623 "Don't run the client in the interactive mode"},
625 OPT_SECTION("Debug"),
626 {"showcerts", OPT_SHOWCERTS
, '-',
627 "Show all certificates sent by the server"},
628 {"debug", OPT_DEBUG
, '-', "Extra output"},
629 {"msg", OPT_MSG
, '-', "Show protocol messages"},
630 {"msgfile", OPT_MSGFILE
, '>',
631 "File to send output of -msg or -trace, instead of stdout"},
632 {"nbio_test", OPT_NBIO_TEST
, '-', "More ssl protocol testing"},
633 {"state", OPT_STATE
, '-', "Print the ssl states"},
634 {"keymatexport", OPT_KEYMATEXPORT
, 's',
635 "Export keying material using label"},
636 {"keymatexportlen", OPT_KEYMATEXPORTLEN
, 'p',
637 "Export len bytes of keying material; default 20"},
638 {"security_debug", OPT_SECURITY_DEBUG
, '-',
639 "Enable security debug messages"},
640 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE
, '-',
641 "Output more security debug output"},
642 #ifndef OPENSSL_NO_SSL_TRACE
643 {"trace", OPT_TRACE
, '-', "Show trace output of protocol messages"},
646 {"wdebug", OPT_WDEBUG
, '-', "WATT-32 tcp debugging"},
648 {"keylogfile", OPT_KEYLOG_FILE
, '>', "Write TLS secrets to file"},
649 {"nocommands", OPT_NOCMDS
, '-', "Do not use interactive command letters"},
650 {"adv", OPT_ADV
, '-', "Advanced command mode"},
651 {"servername", OPT_SERVERNAME
, 's',
652 "Set TLS extension servername (SNI) in ClientHello (default)"},
653 {"noservername", OPT_NOSERVERNAME
, '-',
654 "Do not send the server name (SNI) extension in the ClientHello"},
655 {"tlsextdebug", OPT_TLSEXTDEBUG
, '-',
656 "Hex dump of all TLS extensions received"},
657 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF
, '-',
658 "Do not treat lack of close_notify from a peer as an error"},
659 #ifndef OPENSSL_NO_OCSP
660 {"status", OPT_STATUS
, '-', "Request certificate status from server"},
662 {"serverinfo", OPT_SERVERINFO
, 's',
663 "types Send empty ClientHello extensions (comma-separated numbers)"},
664 {"alpn", OPT_ALPN
, 's',
665 "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
666 {"async", OPT_ASYNC
, '-', "Support asynchronous operation"},
667 {"nbio", OPT_NBIO
, '-', "Use non-blocking IO"},
669 OPT_SECTION("Protocol and version"),
670 #ifndef OPENSSL_NO_SSL3
671 {"ssl3", OPT_SSL3
, '-', "Just use SSLv3"},
673 #ifndef OPENSSL_NO_TLS1
674 {"tls1", OPT_TLS1
, '-', "Just use TLSv1"},
676 #ifndef OPENSSL_NO_TLS1_1
677 {"tls1_1", OPT_TLS1_1
, '-', "Just use TLSv1.1"},
679 #ifndef OPENSSL_NO_TLS1_2
680 {"tls1_2", OPT_TLS1_2
, '-', "Just use TLSv1.2"},
682 #ifndef OPENSSL_NO_TLS1_3
683 {"tls1_3", OPT_TLS1_3
, '-', "Just use TLSv1.3"},
685 #ifndef OPENSSL_NO_DTLS
686 {"dtls", OPT_DTLS
, '-', "Use any version of DTLS"},
687 {"quic", OPT_QUIC
, '-', "Use QUIC"},
688 {"timeout", OPT_TIMEOUT
, '-',
689 "Enable send/receive timeout on DTLS connections"},
690 {"mtu", OPT_MTU
, 'p', "Set the link layer MTU"},
692 #ifndef OPENSSL_NO_DTLS1
693 {"dtls1", OPT_DTLS1
, '-', "Just use DTLSv1"},
695 #ifndef OPENSSL_NO_DTLS1_2
696 {"dtls1_2", OPT_DTLS1_2
, '-', "Just use DTLSv1.2"},
698 #ifndef OPENSSL_NO_SCTP
699 {"sctp", OPT_SCTP
, '-', "Use SCTP"},
700 {"sctp_label_bug", OPT_SCTP_LABEL_BUG
, '-', "Enable SCTP label length bug"},
702 #ifndef OPENSSL_NO_NEXTPROTONEG
703 {"nextprotoneg", OPT_NEXTPROTONEG
, 's',
704 "Enable NPN extension, considering named protocols supported (comma-separated list)"},
706 {"early_data", OPT_EARLY_DATA
, '<', "File to send as early data"},
707 {"enable_pha", OPT_ENABLE_PHA
, '-', "Enable post-handshake-authentication"},
708 {"enable_server_rpk", OPT_ENABLE_SERVER_RPK
, '-', "Enable raw public keys (RFC7250) from the server"},
709 {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK
, '-', "Enable raw public keys (RFC7250) from the client"},
710 #ifndef OPENSSL_NO_SRTP
711 {"use_srtp", OPT_USE_SRTP
, 's',
712 "Offer SRTP key management with a colon-separated profile list"},
714 #ifndef OPENSSL_NO_SRP
715 {"srpuser", OPT_SRPUSER
, 's', "(deprecated) SRP authentication for 'user'"},
716 {"srppass", OPT_SRPPASS
, 's', "(deprecated) Password for 'user'"},
717 {"srp_lateuser", OPT_SRP_LATEUSER
, '-',
718 "(deprecated) SRP username into second ClientHello message"},
719 {"srp_moregroups", OPT_SRP_MOREGROUPS
, '-',
720 "(deprecated) Tolerate other than the known g N values."},
721 {"srp_strength", OPT_SRP_STRENGTH
, 'p',
722 "(deprecated) Minimal length in bits for N"},
724 #ifndef OPENSSL_NO_KTLS
725 {"ktls", OPT_KTLS
, '-', "Enable Kernel TLS for sending and receiving"},
731 {"CRL", OPT_CRL
, '<', "CRL file to use"},
732 {"crl_download", OPT_CRL_DOWNLOAD
, '-', "Download CRL from distribution points"},
733 {"CRLform", OPT_CRLFORM
, 'F', "CRL format (PEM or DER); default PEM"},
734 {"verify_return_error", OPT_VERIFY_RET_ERROR
, '-',
735 "Close connection on verification error"},
736 {"verify_quiet", OPT_VERIFY_QUIET
, '-', "Restrict verify output to errors"},
737 {"chainCAfile", OPT_CHAINCAFILE
, '<',
738 "CA file for certificate chain (PEM format)"},
739 {"chainCApath", OPT_CHAINCAPATH
, '/',
740 "Use dir as certificate store path to build CA certificate chain"},
741 {"chainCAstore", OPT_CHAINCASTORE
, ':',
742 "CA store URI for certificate chain"},
743 {"verifyCAfile", OPT_VERIFYCAFILE
, '<',
744 "CA file for certificate verification (PEM format)"},
745 {"verifyCApath", OPT_VERIFYCAPATH
, '/',
746 "Use dir as certificate store path to verify CA certificate"},
747 {"verifyCAstore", OPT_VERIFYCASTORE
, ':',
748 "CA store URI for certificate verification"},
753 {"host:port", 0, 0, "Where to connect; same as -connect option"},
757 typedef enum PROTOCOL_choice
{
775 static const OPT_PAIR services
[] = {
776 {"smtp", PROTO_SMTP
},
777 {"pop3", PROTO_POP3
},
778 {"imap", PROTO_IMAP
},
780 {"xmpp", PROTO_XMPP
},
781 {"xmpp-server", PROTO_XMPP_SERVER
},
782 {"telnet", PROTO_TELNET
},
784 {"mysql", PROTO_MYSQL
},
785 {"postgres", PROTO_POSTGRES
},
786 {"lmtp", PROTO_LMTP
},
787 {"nntp", PROTO_NNTP
},
788 {"sieve", PROTO_SIEVE
},
789 {"ldap", PROTO_LDAP
},
793 #define IS_INET_FLAG(o) \
794 (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
795 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
797 #define IS_PROT_FLAG(o) \
798 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
799 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2 \
802 /* Free |*dest| and optionally set it to a copy of |source|. */
803 static void freeandcopy(char **dest
, const char *source
)
808 *dest
= OPENSSL_strdup(source
);
811 static int new_session_cb(SSL
*s
, SSL_SESSION
*sess
)
814 if (sess_out
!= NULL
) {
815 BIO
*stmp
= BIO_new_file(sess_out
, "w");
818 BIO_printf(bio_err
, "Error writing session file %s\n", sess_out
);
820 PEM_write_bio_SSL_SESSION(stmp
, sess
);
826 * Session data gets dumped on connection for TLSv1.2 and below, and on
827 * arrival of the NewSessionTicket for TLSv1.3.
829 if (SSL_version(s
) == TLS1_3_VERSION
) {
830 BIO_printf(bio_c_out
,
831 "---\nPost-Handshake New Session Ticket arrived:\n");
832 SSL_SESSION_print(bio_c_out
, sess
);
833 BIO_printf(bio_c_out
, "---\n");
837 * We always return a "fail" response so that the session gets freed again
838 * because we haven't used the reference.
843 int s_client_main(int argc
, char **argv
)
846 EVP_PKEY
*key
= NULL
;
849 STACK_OF(X509
) *chain
= NULL
;
851 X509_VERIFY_PARAM
*vpm
= NULL
;
852 SSL_EXCERT
*exc
= NULL
;
853 SSL_CONF_CTX
*cctx
= NULL
;
854 STACK_OF(OPENSSL_STRING
) *ssl_args
= NULL
;
855 char *dane_tlsa_domain
= NULL
;
856 STACK_OF(OPENSSL_STRING
) *dane_tlsa_rrset
= NULL
;
857 int dane_ee_no_name
= 0;
858 STACK_OF(X509_CRL
) *crls
= NULL
;
859 const SSL_METHOD
*meth
= TLS_client_method();
860 const char *CApath
= NULL
, *CAfile
= NULL
, *CAstore
= NULL
;
861 char *cbuf
= NULL
, *sbuf
= NULL
, *mbuf
= NULL
;
862 char *proxystr
= NULL
, *proxyuser
= NULL
;
863 char *proxypassarg
= NULL
, *proxypass
= NULL
;
864 char *connectstr
= NULL
, *bindstr
= NULL
;
865 char *cert_file
= NULL
, *key_file
= NULL
, *chain_file
= NULL
;
866 char *chCApath
= NULL
, *chCAfile
= NULL
, *chCAstore
= NULL
, *host
= NULL
;
867 char *thost
= NULL
, *tport
= NULL
;
869 char *bindhost
= NULL
, *bindport
= NULL
;
870 char *passarg
= NULL
, *pass
= NULL
;
871 char *vfyCApath
= NULL
, *vfyCAfile
= NULL
, *vfyCAstore
= NULL
;
872 char *ReqCAfile
= NULL
;
873 char *sess_in
= NULL
, *crl_file
= NULL
, *p
;
874 const char *protohost
= NULL
;
875 struct timeval timeout
, *timeoutp
;
876 fd_set readfds
, writefds
;
877 int noCApath
= 0, noCAfile
= 0, noCAstore
= 0;
878 int build_chain
= 0, cert_format
= FORMAT_UNDEF
;
879 size_t cbuf_len
, cbuf_off
;
880 int key_format
= FORMAT_UNDEF
, crlf
= 0, full_log
= 1, mbuf_len
= 0;
882 int nointeractive
= 0;
884 int reconnect
= 0, verify
= SSL_VERIFY_NONE
, vpmtouched
= 0;
885 int ret
= 1, in_init
= 1, i
, nbio_test
= 0, sock
= -1, k
, width
, state
= 0;
886 int sbuf_len
, sbuf_off
, cmdmode
= USER_DATA_MODE_BASIC
;
887 int socket_family
= AF_UNSPEC
, socket_type
= SOCK_STREAM
, protocol
= 0;
888 int starttls_proto
= PROTO_OFF
, crl_format
= FORMAT_UNDEF
, crl_download
= 0;
889 int write_tty
, read_tty
, write_ssl
, read_ssl
, tty_on
, ssl_pending
;
891 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
894 int read_buf_len
= 0;
895 int fallback_scsv
= 0;
897 #ifndef OPENSSL_NO_DTLS
898 int enable_timeouts
= 0;
901 #ifndef OPENSSL_NO_ENGINE
902 ENGINE
*ssl_client_engine
= NULL
;
905 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
908 const char *servername
= NULL
;
909 char *sname_alloc
= NULL
;
910 int noservername
= 0;
911 const char *alpn_in
= NULL
;
912 tlsextctx tlsextcbp
= { NULL
, 0 };
913 const char *ssl_config
= NULL
;
914 #define MAX_SI_TYPES 100
915 unsigned short serverinfo_types
[MAX_SI_TYPES
];
916 int serverinfo_count
= 0, start
= 0, len
;
917 #ifndef OPENSSL_NO_NEXTPROTONEG
918 const char *next_proto_neg_in
= NULL
;
920 #ifndef OPENSSL_NO_SRP
921 char *srppass
= NULL
;
922 int srp_lateuser
= 0;
923 SRP_ARG srp_arg
= { NULL
, NULL
, 0, 0, 0, 1024 };
925 #ifndef OPENSSL_NO_SRTP
926 char *srtp_profiles
= NULL
;
928 #ifndef OPENSSL_NO_CT
929 char *ctlog_file
= NULL
;
930 int ct_validation
= 0;
932 int min_version
= 0, max_version
= 0, prot_opt
= 0, no_prot_opt
= 0;
934 unsigned int max_send_fragment
= 0;
935 unsigned int split_send_fragment
= 0, max_pipelines
= 0;
936 enum { use_inet
, use_unix
, use_unknown
} connect_type
= use_unknown
;
938 uint8_t maxfraglen
= 0;
939 int c_nbio
= 0, c_msg
= 0, c_ign_eof
= 0, c_brief
= 0;
940 int c_tlsextdebug
= 0;
941 #ifndef OPENSSL_NO_OCSP
942 int c_status_req
= 0;
944 BIO
*bio_c_msg
= NULL
;
945 const char *keylog_file
= NULL
, *early_data_file
= NULL
;
946 int isdtls
= 0, isquic
= 0;
947 char *psksessf
= NULL
;
949 int enable_client_rpk
= 0;
950 #ifndef OPENSSL_NO_SCTP
951 int sctp_label_bug
= 0;
953 int ignore_unexpected_eof
= 0;
954 #ifndef OPENSSL_NO_KTLS
959 BIO_ADDR
*peer_addr
= NULL
;
960 struct user_data_st user_data
;
964 /* Known false-positive of MemorySanitizer. */
965 #if defined(__has_feature)
966 # if __has_feature(memory_sanitizer)
967 __msan_unpoison(&readfds
, sizeof(readfds
));
968 __msan_unpoison(&writefds
, sizeof(writefds
));
976 port
= OPENSSL_strdup(PORT
);
977 vpm
= X509_VERIFY_PARAM_new();
978 cctx
= SSL_CONF_CTX_new();
980 if (port
== NULL
|| vpm
== NULL
|| cctx
== NULL
) {
981 BIO_printf(bio_err
, "%s: out of memory\n", opt_getprog());
985 cbuf
= app_malloc(BUFSIZZ
, "cbuf");
986 sbuf
= app_malloc(BUFSIZZ
, "sbuf");
987 mbuf
= app_malloc(BUFSIZZ
, "mbuf");
989 SSL_CONF_CTX_set_flags(cctx
, SSL_CONF_FLAG_CLIENT
| SSL_CONF_FLAG_CMDLINE
);
991 prog
= opt_init(argc
, argv
, s_client_options
);
992 while ((o
= opt_next()) != OPT_EOF
) {
993 /* Check for intermixing flags. */
994 if (connect_type
== use_unix
&& IS_INET_FLAG(o
)) {
996 "%s: Intermixed protocol flags (unix and internet domains)\n",
1000 if (connect_type
== use_inet
&& IS_UNIX_FLAG(o
)) {
1002 "%s: Intermixed protocol flags (internet and unix domains)\n",
1007 if (IS_PROT_FLAG(o
) && ++prot_opt
> 1) {
1008 BIO_printf(bio_err
, "Cannot supply multiple protocol flags\n");
1011 if (IS_NO_PROT_FLAG(o
))
1013 if (prot_opt
== 1 && no_prot_opt
) {
1015 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1023 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
1026 opt_help(s_client_options
);
1030 connect_type
= use_inet
;
1031 socket_family
= AF_INET
;
1036 connect_type
= use_inet
;
1037 socket_family
= AF_INET6
;
1042 connect_type
= use_inet
;
1043 freeandcopy(&host
, opt_arg());
1046 connect_type
= use_inet
;
1047 freeandcopy(&port
, opt_arg());
1050 connect_type
= use_inet
;
1051 freeandcopy(&connectstr
, opt_arg());
1054 freeandcopy(&bindstr
, opt_arg());
1057 proxystr
= opt_arg();
1059 case OPT_PROXY_USER
:
1060 proxyuser
= opt_arg();
1062 case OPT_PROXY_PASS
:
1063 proxypassarg
= opt_arg();
1067 connect_type
= use_unix
;
1068 socket_family
= AF_UNIX
;
1069 freeandcopy(&host
, opt_arg());
1073 /* fall through, since this is an alias */
1075 protohost
= opt_arg();
1078 verify
= SSL_VERIFY_PEER
;
1079 verify_args
.depth
= atoi(opt_arg());
1081 BIO_printf(bio_err
, "verify depth is %d\n", verify_args
.depth
);
1084 cert_file
= opt_arg();
1087 if (!set_nameopt(opt_arg()))
1091 crl_file
= opt_arg();
1093 case OPT_CRL_DOWNLOAD
:
1097 sess_out
= opt_arg();
1100 sess_in
= opt_arg();
1103 if (!opt_format(opt_arg(), OPT_FMT_ANY
, &cert_format
))
1107 if (!opt_format(opt_arg(), OPT_FMT_PEMDER
, &crl_format
))
1110 case OPT_VERIFY_RET_ERROR
:
1111 verify
= SSL_VERIFY_PEER
;
1112 verify_args
.return_error
= 1;
1114 case OPT_VERIFY_QUIET
:
1115 verify_args
.quiet
= 1;
1118 c_brief
= verify_args
.quiet
= c_quiet
= 1;
1121 if (ssl_args
== NULL
)
1122 ssl_args
= sk_OPENSSL_STRING_new_null();
1123 if (ssl_args
== NULL
1124 || !sk_OPENSSL_STRING_push(ssl_args
, opt_flag())
1125 || !sk_OPENSSL_STRING_push(ssl_args
, opt_arg())) {
1126 BIO_printf(bio_err
, "%s: Memory allocation failure\n", prog
);
1131 if (!opt_verify(o
, vpm
))
1136 if (!args_excert(o
, &exc
))
1139 case OPT_IGNORE_UNEXPECTED_EOF
:
1140 ignore_unexpected_eof
= 1;
1145 case OPT_NO_INTERACTIVE
:
1152 c_quiet
= c_ign_eof
= 1;
1158 cmdmode
= USER_DATA_MODE_NONE
;
1161 cmdmode
= USER_DATA_MODE_ADVANCED
;
1164 e
= setup_engine(opt_arg(), 1);
1166 case OPT_SSL_CLIENT_ENGINE
:
1167 #ifndef OPENSSL_NO_ENGINE
1168 ssl_client_engine
= setup_engine(opt_arg(), 0);
1169 if (ssl_client_engine
== NULL
) {
1170 BIO_printf(bio_err
, "Error getting client auth engine\n");
1179 case OPT_PROV_CASES
:
1180 if (!opt_provider(o
))
1186 case OPT_NO_IGN_EOF
:
1192 case OPT_TLSEXTDEBUG
:
1196 #ifndef OPENSSL_NO_OCSP
1209 bio_c_msg
= BIO_new_file(opt_arg(), "w");
1210 if (bio_c_msg
== NULL
) {
1211 BIO_printf(bio_err
, "Error writing file %s\n", opt_arg());
1216 #ifndef OPENSSL_NO_SSL_TRACE
1220 case OPT_SECURITY_DEBUG
:
1223 case OPT_SECURITY_DEBUG_VERBOSE
:
1235 case OPT_PSK_IDENTITY
:
1236 psk_identity
= opt_arg();
1239 for (p
= psk_key
= opt_arg(); *p
; p
++) {
1240 if (isxdigit(_UC(*p
)))
1242 BIO_printf(bio_err
, "Not a hex number '%s'\n", psk_key
);
1247 psksessf
= opt_arg();
1249 #ifndef OPENSSL_NO_SRP
1251 srp_arg
.srplogin
= opt_arg();
1252 if (min_version
< TLS1_VERSION
)
1253 min_version
= TLS1_VERSION
;
1256 srppass
= opt_arg();
1257 if (min_version
< TLS1_VERSION
)
1258 min_version
= TLS1_VERSION
;
1260 case OPT_SRP_STRENGTH
:
1261 srp_arg
.strength
= atoi(opt_arg());
1262 BIO_printf(bio_err
, "SRP minimal length for N is %d\n",
1264 if (min_version
< TLS1_VERSION
)
1265 min_version
= TLS1_VERSION
;
1267 case OPT_SRP_LATEUSER
:
1269 if (min_version
< TLS1_VERSION
)
1270 min_version
= TLS1_VERSION
;
1272 case OPT_SRP_MOREGROUPS
:
1274 if (min_version
< TLS1_VERSION
)
1275 min_version
= TLS1_VERSION
;
1278 case OPT_SSL_CONFIG
:
1279 ssl_config
= opt_arg();
1282 min_version
= SSL3_VERSION
;
1283 max_version
= SSL3_VERSION
;
1284 socket_type
= SOCK_STREAM
;
1285 #ifndef OPENSSL_NO_DTLS
1291 min_version
= TLS1_3_VERSION
;
1292 max_version
= TLS1_3_VERSION
;
1293 socket_type
= SOCK_STREAM
;
1294 #ifndef OPENSSL_NO_DTLS
1300 min_version
= TLS1_2_VERSION
;
1301 max_version
= TLS1_2_VERSION
;
1302 socket_type
= SOCK_STREAM
;
1303 #ifndef OPENSSL_NO_DTLS
1309 min_version
= TLS1_1_VERSION
;
1310 max_version
= TLS1_1_VERSION
;
1311 socket_type
= SOCK_STREAM
;
1312 #ifndef OPENSSL_NO_DTLS
1318 min_version
= TLS1_VERSION
;
1319 max_version
= TLS1_VERSION
;
1320 socket_type
= SOCK_STREAM
;
1321 #ifndef OPENSSL_NO_DTLS
1327 #ifndef OPENSSL_NO_DTLS
1328 meth
= DTLS_client_method();
1329 socket_type
= SOCK_DGRAM
;
1335 #ifndef OPENSSL_NO_DTLS1
1336 meth
= DTLS_client_method();
1337 min_version
= DTLS1_VERSION
;
1338 max_version
= DTLS1_VERSION
;
1339 socket_type
= SOCK_DGRAM
;
1345 #ifndef OPENSSL_NO_DTLS1_2
1346 meth
= DTLS_client_method();
1347 min_version
= DTLS1_2_VERSION
;
1348 max_version
= DTLS1_2_VERSION
;
1349 socket_type
= SOCK_DGRAM
;
1355 #ifndef OPENSSL_NO_QUIC
1356 meth
= OSSL_QUIC_client_method();
1359 socket_type
= SOCK_DGRAM
;
1360 # ifndef OPENSSL_NO_DTLS
1367 #ifndef OPENSSL_NO_SCTP
1368 protocol
= IPPROTO_SCTP
;
1371 case OPT_SCTP_LABEL_BUG
:
1372 #ifndef OPENSSL_NO_SCTP
1377 #ifndef OPENSSL_NO_DTLS
1378 enable_timeouts
= 1;
1382 #ifndef OPENSSL_NO_DTLS
1383 socket_mtu
= atol(opt_arg());
1386 case OPT_FALLBACKSCSV
:
1390 if (!opt_format(opt_arg(), OPT_FMT_ANY
, &key_format
))
1394 passarg
= opt_arg();
1396 case OPT_CERT_CHAIN
:
1397 chain_file
= opt_arg();
1400 key_file
= opt_arg();
1411 case OPT_CHAINCAPATH
:
1412 chCApath
= opt_arg();
1414 case OPT_VERIFYCAPATH
:
1415 vfyCApath
= opt_arg();
1417 case OPT_BUILD_CHAIN
:
1421 ReqCAfile
= opt_arg();
1429 #ifndef OPENSSL_NO_CT
1436 case OPT_CTLOG_FILE
:
1437 ctlog_file
= opt_arg();
1440 case OPT_CHAINCAFILE
:
1441 chCAfile
= opt_arg();
1443 case OPT_VERIFYCAFILE
:
1444 vfyCAfile
= opt_arg();
1447 CAstore
= opt_arg();
1452 case OPT_CHAINCASTORE
:
1453 chCAstore
= opt_arg();
1455 case OPT_VERIFYCASTORE
:
1456 vfyCAstore
= opt_arg();
1458 case OPT_DANE_TLSA_DOMAIN
:
1459 dane_tlsa_domain
= opt_arg();
1461 case OPT_DANE_TLSA_RRDATA
:
1462 if (dane_tlsa_rrset
== NULL
)
1463 dane_tlsa_rrset
= sk_OPENSSL_STRING_new_null();
1464 if (dane_tlsa_rrset
== NULL
||
1465 !sk_OPENSSL_STRING_push(dane_tlsa_rrset
, opt_arg())) {
1466 BIO_printf(bio_err
, "%s: Memory allocation failure\n", prog
);
1470 case OPT_DANE_EE_NO_NAME
:
1471 dane_ee_no_name
= 1;
1473 case OPT_NEXTPROTONEG
:
1474 #ifndef OPENSSL_NO_NEXTPROTONEG
1475 next_proto_neg_in
= opt_arg();
1479 alpn_in
= opt_arg();
1481 case OPT_SERVERINFO
:
1484 for (start
= 0, i
= 0; i
<= len
; ++i
) {
1485 if (i
== len
|| p
[i
] == ',') {
1486 serverinfo_types
[serverinfo_count
] = atoi(p
+ start
);
1487 if (++serverinfo_count
== MAX_SI_TYPES
)
1494 if (!opt_pair(opt_arg(), services
, &starttls_proto
))
1500 case OPT_SERVERNAME
:
1501 servername
= opt_arg();
1503 case OPT_NOSERVERNAME
:
1507 #ifndef OPENSSL_NO_SRTP
1508 srtp_profiles
= opt_arg();
1511 case OPT_KEYMATEXPORT
:
1512 keymatexportlabel
= opt_arg();
1514 case OPT_KEYMATEXPORTLEN
:
1515 keymatexportlen
= atoi(opt_arg());
1520 case OPT_MAXFRAGLEN
:
1521 len
= atoi(opt_arg());
1524 maxfraglen
= TLSEXT_max_fragment_length_512
;
1527 maxfraglen
= TLSEXT_max_fragment_length_1024
;
1530 maxfraglen
= TLSEXT_max_fragment_length_2048
;
1533 maxfraglen
= TLSEXT_max_fragment_length_4096
;
1537 "%s: Max Fragment Len %u is out of permitted values",
1542 case OPT_MAX_SEND_FRAG
:
1543 max_send_fragment
= atoi(opt_arg());
1545 case OPT_SPLIT_SEND_FRAG
:
1546 split_send_fragment
= atoi(opt_arg());
1548 case OPT_MAX_PIPELINES
:
1549 max_pipelines
= atoi(opt_arg());
1552 read_buf_len
= atoi(opt_arg());
1554 case OPT_KEYLOG_FILE
:
1555 keylog_file
= opt_arg();
1557 case OPT_EARLY_DATA
:
1558 early_data_file
= opt_arg();
1560 case OPT_ENABLE_PHA
:
1564 #ifndef OPENSSL_NO_KTLS
1568 case OPT_ENABLE_SERVER_RPK
:
1569 enable_server_rpk
= 1;
1571 case OPT_ENABLE_CLIENT_RPK
:
1572 enable_client_rpk
= 1;
1577 /* Optional argument is connect string if -connect not used. */
1578 if (opt_num_rest() == 1) {
1579 /* Don't allow -connect and a separate argument. */
1580 if (connectstr
!= NULL
) {
1582 "%s: cannot provide both -connect option and target parameter\n",
1586 connect_type
= use_inet
;
1587 freeandcopy(&connectstr
, *opt_rest());
1588 } else if (!opt_check_rest_arg(NULL
)) {
1591 if (!app_RAND_load())
1595 cmdmode
= USER_DATA_MODE_NONE
;
1597 if (count4or6
>= 2) {
1598 BIO_printf(bio_err
, "%s: Can't use both -4 and -6\n", prog
);
1602 if (servername
!= NULL
) {
1604 "%s: Can't use -servername and -noservername together\n",
1608 if (dane_tlsa_domain
!= NULL
) {
1610 "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1616 #ifndef OPENSSL_NO_NEXTPROTONEG
1617 if (min_version
== TLS1_3_VERSION
&& next_proto_neg_in
!= NULL
) {
1618 BIO_printf(bio_err
, "Cannot supply -nextprotoneg with TLSv1.3\n");
1623 if (connectstr
!= NULL
) {
1625 char *tmp_host
= host
, *tmp_port
= port
;
1627 res
= BIO_parse_hostserv(connectstr
, &host
, &port
, BIO_PARSE_PRIO_HOST
);
1628 if (tmp_host
!= host
)
1629 OPENSSL_free(tmp_host
);
1630 if (tmp_port
!= port
)
1631 OPENSSL_free(tmp_port
);
1634 "%s: -connect argument or target parameter malformed or ambiguous\n",
1640 if (proxystr
!= NULL
) {
1641 #ifndef OPENSSL_NO_HTTP
1643 char *tmp_host
= host
, *tmp_port
= port
;
1645 if (host
== NULL
|| port
== NULL
) {
1646 BIO_printf(bio_err
, "%s: -proxy requires use of -connect or target parameter\n", prog
);
1650 if (servername
== NULL
&& !noservername
) {
1651 servername
= sname_alloc
= OPENSSL_strdup(host
);
1652 if (sname_alloc
== NULL
) {
1653 BIO_printf(bio_err
, "%s: out of memory\n", prog
);
1658 /* Retain the original target host:port for use in the HTTP proxy connect string */
1659 thost
= OPENSSL_strdup(host
);
1660 tport
= OPENSSL_strdup(port
);
1661 if (thost
== NULL
|| tport
== NULL
) {
1662 BIO_printf(bio_err
, "%s: out of memory\n", prog
);
1666 res
= BIO_parse_hostserv(proxystr
, &host
, &port
, BIO_PARSE_PRIO_HOST
);
1667 if (tmp_host
!= host
)
1668 OPENSSL_free(tmp_host
);
1669 if (tmp_port
!= port
)
1670 OPENSSL_free(tmp_port
);
1673 "%s: -proxy argument malformed or ambiguous\n", prog
);
1678 "%s: -proxy not supported in no-http build\n", prog
);
1684 if (bindstr
!= NULL
) {
1686 res
= BIO_parse_hostserv(bindstr
, &bindhost
, &bindport
,
1687 BIO_PARSE_PRIO_HOST
);
1690 "%s: -bind argument parameter malformed or ambiguous\n",
1697 if (socket_family
== AF_UNIX
&& socket_type
!= SOCK_STREAM
) {
1699 "Can't use unix sockets and datagrams together\n");
1704 #ifndef OPENSSL_NO_SCTP
1705 if (protocol
== IPPROTO_SCTP
) {
1706 if (socket_type
!= SOCK_DGRAM
) {
1707 BIO_printf(bio_err
, "Can't use -sctp without DTLS\n");
1710 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1711 socket_type
= SOCK_STREAM
;
1715 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1716 next_proto
.status
= -1;
1717 if (next_proto_neg_in
) {
1719 next_protos_parse(&next_proto
.len
, next_proto_neg_in
);
1720 if (next_proto
.data
== NULL
) {
1721 BIO_printf(bio_err
, "Error parsing -nextprotoneg argument\n");
1725 next_proto
.data
= NULL
;
1728 if (!app_passwd(passarg
, NULL
, &pass
, NULL
)) {
1729 BIO_printf(bio_err
, "Error getting private key password\n");
1733 if (!app_passwd(proxypassarg
, NULL
, &proxypass
, NULL
)) {
1734 BIO_printf(bio_err
, "Error getting proxy password\n");
1738 if (proxypass
!= NULL
&& proxyuser
== NULL
) {
1739 BIO_printf(bio_err
, "Error: Must specify proxy_user with proxy_pass\n");
1743 if (key_file
== NULL
)
1744 key_file
= cert_file
;
1746 if (key_file
!= NULL
) {
1747 key
= load_key(key_file
, key_format
, 0, pass
, e
,
1748 "client certificate private key");
1753 if (cert_file
!= NULL
) {
1754 cert
= load_cert_pass(cert_file
, cert_format
, 1, pass
,
1755 "client certificate");
1760 if (chain_file
!= NULL
) {
1761 if (!load_certs(chain_file
, 0, &chain
, pass
, "client certificate chain"))
1765 if (crl_file
!= NULL
) {
1767 crl
= load_crl(crl_file
, crl_format
, 0, "CRL");
1770 crls
= sk_X509_CRL_new_null();
1771 if (crls
== NULL
|| !sk_X509_CRL_push(crls
, crl
)) {
1772 BIO_puts(bio_err
, "Error adding CRL\n");
1773 ERR_print_errors(bio_err
);
1779 if (!load_excert(&exc
))
1782 if (bio_c_out
== NULL
) {
1783 if (c_quiet
&& !c_debug
) {
1784 bio_c_out
= BIO_new(BIO_s_null());
1785 if (c_msg
&& bio_c_msg
== NULL
) {
1786 bio_c_msg
= dup_bio_out(FORMAT_TEXT
);
1787 if (bio_c_msg
== NULL
) {
1788 BIO_printf(bio_err
, "Out of memory\n");
1793 bio_c_out
= dup_bio_out(FORMAT_TEXT
);
1796 if (bio_c_out
== NULL
) {
1797 BIO_printf(bio_err
, "Unable to create BIO\n");
1801 #ifndef OPENSSL_NO_SRP
1802 if (!app_passwd(srppass
, NULL
, &srp_arg
.srppassin
, NULL
)) {
1803 BIO_printf(bio_err
, "Error getting password\n");
1808 ctx
= SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth
);
1810 ERR_print_errors(bio_err
);
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",
1826 ERR_print_errors(bio_err
);
1831 #ifndef OPENSSL_NO_SCTP
1832 if (protocol
== IPPROTO_SCTP
&& sctp_label_bug
== 1)
1833 SSL_CTX_set_mode(ctx
, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG
);
1836 if (min_version
!= 0
1837 && SSL_CTX_set_min_proto_version(ctx
, min_version
) == 0)
1839 if (max_version
!= 0
1840 && SSL_CTX_set_max_proto_version(ctx
, max_version
) == 0)
1843 if (ignore_unexpected_eof
)
1844 SSL_CTX_set_options(ctx
, SSL_OP_IGNORE_UNEXPECTED_EOF
);
1845 #ifndef OPENSSL_NO_KTLS
1847 SSL_CTX_set_options(ctx
, SSL_OP_ENABLE_KTLS
);
1850 if (vpmtouched
&& !SSL_CTX_set1_param(ctx
, vpm
)) {
1851 BIO_printf(bio_err
, "Error setting verify params\n");
1852 ERR_print_errors(bio_err
);
1857 SSL_CTX_set_mode(ctx
, SSL_MODE_ASYNC
);
1860 if (max_send_fragment
> 0
1861 && !SSL_CTX_set_max_send_fragment(ctx
, max_send_fragment
)) {
1862 BIO_printf(bio_err
, "%s: Max send fragment size %u is out of permitted range\n",
1863 prog
, max_send_fragment
);
1867 if (split_send_fragment
> 0
1868 && !SSL_CTX_set_split_send_fragment(ctx
, split_send_fragment
)) {
1869 BIO_printf(bio_err
, "%s: Split send fragment size %u is out of permitted range\n",
1870 prog
, split_send_fragment
);
1874 if (max_pipelines
> 0
1875 && !SSL_CTX_set_max_pipelines(ctx
, max_pipelines
)) {
1876 BIO_printf(bio_err
, "%s: Max pipelines %u is out of permitted range\n",
1877 prog
, max_pipelines
);
1881 if (read_buf_len
> 0) {
1882 SSL_CTX_set_default_read_buffer_len(ctx
, read_buf_len
);
1886 && !SSL_CTX_set_tlsext_max_fragment_length(ctx
, maxfraglen
)) {
1888 "%s: Max Fragment Length code %u is out of permitted values"
1889 "\n", prog
, maxfraglen
);
1893 if (!ssl_load_stores(ctx
,
1894 vfyCApath
, vfyCAfile
, vfyCAstore
,
1895 chCApath
, chCAfile
, chCAstore
,
1896 crls
, crl_download
)) {
1897 BIO_printf(bio_err
, "Error loading store locations\n");
1898 ERR_print_errors(bio_err
);
1901 if (ReqCAfile
!= NULL
) {
1902 STACK_OF(X509_NAME
) *nm
= sk_X509_NAME_new_null();
1904 if (nm
== NULL
|| !SSL_add_file_cert_subjects_to_stack(nm
, ReqCAfile
)) {
1905 sk_X509_NAME_pop_free(nm
, X509_NAME_free
);
1906 BIO_printf(bio_err
, "Error loading CA names\n");
1907 ERR_print_errors(bio_err
);
1910 SSL_CTX_set0_CA_list(ctx
, nm
);
1912 #ifndef OPENSSL_NO_ENGINE
1913 if (ssl_client_engine
) {
1914 if (!SSL_CTX_set_client_cert_engine(ctx
, ssl_client_engine
)) {
1915 BIO_puts(bio_err
, "Error setting client auth engine\n");
1916 ERR_print_errors(bio_err
);
1917 release_engine(ssl_client_engine
);
1920 release_engine(ssl_client_engine
);
1924 #ifndef OPENSSL_NO_PSK
1925 if (psk_key
!= NULL
) {
1927 BIO_printf(bio_c_out
, "PSK key given, setting client callback\n");
1928 SSL_CTX_set_psk_client_callback(ctx
, psk_client_cb
);
1931 if (psksessf
!= NULL
) {
1932 BIO
*stmp
= BIO_new_file(psksessf
, "r");
1935 BIO_printf(bio_err
, "Can't open PSK session file %s\n", psksessf
);
1936 ERR_print_errors(bio_err
);
1939 psksess
= PEM_read_bio_SSL_SESSION(stmp
, NULL
, 0, NULL
);
1941 if (psksess
== NULL
) {
1942 BIO_printf(bio_err
, "Can't read PSK session file %s\n", psksessf
);
1943 ERR_print_errors(bio_err
);
1947 if (psk_key
!= NULL
|| psksess
!= NULL
)
1948 SSL_CTX_set_psk_use_session_callback(ctx
, psk_use_session_cb
);
1950 #ifndef OPENSSL_NO_SRTP
1951 if (srtp_profiles
!= NULL
) {
1952 /* Returns 0 on success! */
1953 if (SSL_CTX_set_tlsext_use_srtp(ctx
, srtp_profiles
) != 0) {
1954 BIO_printf(bio_err
, "Error setting SRTP profile\n");
1955 ERR_print_errors(bio_err
);
1962 ssl_ctx_set_excert(ctx
, exc
);
1964 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1965 if (next_proto
.data
!= NULL
)
1966 SSL_CTX_set_next_proto_select_cb(ctx
, next_proto_cb
, &next_proto
);
1970 unsigned char *alpn
= next_protos_parse(&alpn_len
, alpn_in
);
1973 BIO_printf(bio_err
, "Error parsing -alpn argument\n");
1976 /* Returns 0 on success! */
1977 if (SSL_CTX_set_alpn_protos(ctx
, alpn
, alpn_len
) != 0) {
1978 BIO_printf(bio_err
, "Error setting ALPN\n");
1984 for (i
= 0; i
< serverinfo_count
; i
++) {
1985 if (!SSL_CTX_add_client_custom_ext(ctx
,
1986 serverinfo_types
[i
],
1988 serverinfo_cli_parse_cb
, NULL
)) {
1990 "Warning: Unable to add custom extension %u, skipping\n",
1991 serverinfo_types
[i
]);
1996 SSL_CTX_set_info_callback(ctx
, apps_ssl_info_callback
);
1998 #ifndef OPENSSL_NO_CT
1999 /* Enable SCT processing, without early connection termination */
2000 if (ct_validation
&&
2001 !SSL_CTX_enable_ct(ctx
, SSL_CT_VALIDATION_PERMISSIVE
)) {
2002 ERR_print_errors(bio_err
);
2006 if (!ctx_set_ctlog_list_file(ctx
, ctlog_file
)) {
2007 if (ct_validation
) {
2008 ERR_print_errors(bio_err
);
2013 * If CT validation is not enabled, the log list isn't needed so don't
2014 * show errors or abort. We try to load it regardless because then we
2015 * can show the names of the logs any SCTs came from (SCTs may be seen
2016 * even with validation disabled).
2022 SSL_CTX_set_verify(ctx
, verify
, verify_callback
);
2024 if (!ctx_set_verify_locations(ctx
, CAfile
, noCAfile
, CApath
, noCApath
,
2025 CAstore
, noCAstore
)) {
2026 ERR_print_errors(bio_err
);
2030 ssl_ctx_add_crls(ctx
, crls
, crl_download
);
2032 if (!set_cert_key_stuff(ctx
, cert
, key
, chain
, build_chain
))
2035 if (!noservername
) {
2036 tlsextcbp
.biodebug
= bio_err
;
2037 SSL_CTX_set_tlsext_servername_callback(ctx
, ssl_servername_cb
);
2038 SSL_CTX_set_tlsext_servername_arg(ctx
, &tlsextcbp
);
2040 #ifndef OPENSSL_NO_SRP
2041 if (srp_arg
.srplogin
!= NULL
2042 && !set_up_srp_arg(ctx
, &srp_arg
, srp_lateuser
, c_msg
, c_debug
))
2046 if (dane_tlsa_domain
!= NULL
) {
2047 if (SSL_CTX_dane_enable(ctx
) <= 0) {
2049 "%s: Error enabling DANE TLSA authentication.\n",
2051 ERR_print_errors(bio_err
);
2057 * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
2058 * come at any time. Therefore, we use a callback to write out the session
2059 * when we know about it. This approach works for < TLSv1.3 as well.
2061 SSL_CTX_set_session_cache_mode(ctx
, SSL_SESS_CACHE_CLIENT
2062 | SSL_SESS_CACHE_NO_INTERNAL_STORE
);
2063 SSL_CTX_sess_set_new_cb(ctx
, new_session_cb
);
2065 if (set_keylog_file(ctx
, keylog_file
))
2073 SSL_set_post_handshake_auth(con
, 1);
2075 if (enable_client_rpk
)
2076 if (!SSL_set1_client_cert_type(con
, cert_type_rpk
, sizeof(cert_type_rpk
))) {
2077 BIO_printf(bio_err
, "Error setting client certificate types\n");
2080 if (enable_server_rpk
) {
2081 if (!SSL_set1_server_cert_type(con
, cert_type_rpk
, sizeof(cert_type_rpk
))) {
2082 BIO_printf(bio_err
, "Error setting server certificate types\n");
2087 if (sess_in
!= NULL
) {
2089 BIO
*stmp
= BIO_new_file(sess_in
, "r");
2091 BIO_printf(bio_err
, "Can't open session file %s\n", sess_in
);
2092 ERR_print_errors(bio_err
);
2095 sess
= PEM_read_bio_SSL_SESSION(stmp
, NULL
, 0, NULL
);
2098 BIO_printf(bio_err
, "Can't open session file %s\n", sess_in
);
2099 ERR_print_errors(bio_err
);
2102 if (!SSL_set_session(con
, sess
)) {
2103 BIO_printf(bio_err
, "Can't set session\n");
2104 ERR_print_errors(bio_err
);
2108 SSL_SESSION_free(sess
);
2112 SSL_set_mode(con
, SSL_MODE_SEND_FALLBACK_SCSV
);
2114 if (!noservername
&& (servername
!= NULL
|| dane_tlsa_domain
== NULL
)) {
2115 if (servername
== NULL
) {
2116 if (host
== NULL
|| is_dNS_name(host
))
2117 servername
= (host
== NULL
) ? "localhost" : host
;
2119 if (servername
!= NULL
&& !SSL_set_tlsext_host_name(con
, servername
)) {
2120 BIO_printf(bio_err
, "Unable to set TLS servername extension.\n");
2121 ERR_print_errors(bio_err
);
2126 if (dane_tlsa_domain
!= NULL
) {
2127 if (SSL_dane_enable(con
, dane_tlsa_domain
) <= 0) {
2128 BIO_printf(bio_err
, "%s: Error enabling DANE TLSA "
2129 "authentication.\n", prog
);
2130 ERR_print_errors(bio_err
);
2133 if (dane_tlsa_rrset
== NULL
) {
2134 BIO_printf(bio_err
, "%s: DANE TLSA authentication requires at "
2135 "least one -dane_tlsa_rrdata option.\n", prog
);
2138 if (tlsa_import_rrset(con
, dane_tlsa_rrset
) <= 0) {
2139 BIO_printf(bio_err
, "%s: Failed to import any TLSA "
2140 "records.\n", prog
);
2143 if (dane_ee_no_name
)
2144 SSL_dane_set_flags(con
, DANE_FLAG_NO_DANE_EE_NAMECHECKS
);
2145 } else if (dane_tlsa_rrset
!= NULL
) {
2146 BIO_printf(bio_err
, "%s: DANE TLSA authentication requires the "
2147 "-dane_tlsa_domain option.\n", prog
);
2150 #ifndef OPENSSL_NO_DTLS
2151 if (isdtls
&& tfo
) {
2152 BIO_printf(bio_err
, "%s: DTLS does not support the -tfo option\n", prog
);
2156 #ifndef OPENSSL_NO_QUIC
2157 if (isquic
&& tfo
) {
2158 BIO_printf(bio_err
, "%s: QUIC does not support the -tfo option\n", prog
);
2161 if (isquic
&& alpn_in
== NULL
) {
2162 BIO_printf(bio_err
, "%s: QUIC requires ALPN to be specified (e.g. \"h3\" for HTTP/3) via the -alpn option\n", prog
);
2168 BIO_printf(bio_c_out
, "Connecting via TFO\n");
2170 if (init_client(&sock
, host
, port
, bindhost
, bindport
, socket_family
,
2171 socket_type
, protocol
, tfo
, !isquic
, &peer_addr
) == 0) {
2172 BIO_printf(bio_err
, "connect:errno=%d\n", get_last_socket_error());
2173 BIO_closesocket(sock
);
2176 BIO_printf(bio_c_out
, "CONNECTED(%08X)\n", sock
);
2179 * QUIC always uses a non-blocking socket - and we have to switch on
2180 * non-blocking mode at the SSL level
2182 if (c_nbio
|| isquic
) {
2183 if (!BIO_socket_nbio(sock
, 1)) {
2184 ERR_print_errors(bio_err
);
2188 if (isquic
&& !SSL_set_blocking_mode(con
, 0))
2190 BIO_printf(bio_c_out
, "Turned on non blocking io\n");
2193 #ifndef OPENSSL_NO_DTLS
2195 union BIO_sock_info_u peer_info
;
2197 #ifndef OPENSSL_NO_SCTP
2198 if (protocol
== IPPROTO_SCTP
)
2199 sbio
= BIO_new_dgram_sctp(sock
, BIO_NOCLOSE
);
2202 sbio
= BIO_new_dgram(sock
, BIO_NOCLOSE
);
2204 if (sbio
== NULL
|| (peer_info
.addr
= BIO_ADDR_new()) == NULL
) {
2205 BIO_printf(bio_err
, "memory allocation failure\n");
2207 BIO_closesocket(sock
);
2210 if (!BIO_sock_info(sock
, BIO_SOCK_INFO_ADDRESS
, &peer_info
)) {
2211 BIO_printf(bio_err
, "getsockname:errno=%d\n",
2212 get_last_socket_error());
2214 BIO_ADDR_free(peer_info
.addr
);
2215 BIO_closesocket(sock
);
2219 (void)BIO_ctrl_set_connected(sbio
, peer_info
.addr
);
2220 BIO_ADDR_free(peer_info
.addr
);
2221 peer_info
.addr
= NULL
;
2223 if (enable_timeouts
) {
2225 timeout
.tv_usec
= DGRAM_RCV_TIMEOUT
;
2226 BIO_ctrl(sbio
, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT
, 0, &timeout
);
2229 timeout
.tv_usec
= DGRAM_SND_TIMEOUT
;
2230 BIO_ctrl(sbio
, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT
, 0, &timeout
);
2234 if (socket_mtu
< DTLS_get_link_min_mtu(con
)) {
2235 BIO_printf(bio_err
, "MTU too small. Must be at least %ld\n",
2236 DTLS_get_link_min_mtu(con
));
2240 SSL_set_options(con
, SSL_OP_NO_QUERY_MTU
);
2241 if (!DTLS_set_link_mtu(con
, socket_mtu
)) {
2242 BIO_printf(bio_err
, "Failed to set MTU\n");
2247 /* want to do MTU discovery */
2248 BIO_ctrl(sbio
, BIO_CTRL_DGRAM_MTU_DISCOVER
, 0, NULL
);
2251 #endif /* OPENSSL_NO_DTLS */
2252 #ifndef OPENSSL_NO_QUIC
2254 sbio
= BIO_new_dgram(sock
, BIO_NOCLOSE
);
2255 if (!SSL_set1_initial_peer_addr(con
, peer_addr
)) {
2256 BIO_printf(bio_err
, "Failed to set the initial peer address\n");
2261 sbio
= BIO_new_socket(sock
, BIO_NOCLOSE
);
2264 BIO_printf(bio_err
, "Unable to create BIO\n");
2265 ERR_print_errors(bio_err
);
2266 BIO_closesocket(sock
);
2270 /* Now that we're using a BIO... */
2272 (void)BIO_set_conn_address(sbio
, peer_addr
);
2273 (void)BIO_set_tfo(sbio
, 1);
2279 test
= BIO_new(BIO_f_nbio_test());
2281 BIO_printf(bio_err
, "Unable to create BIO\n");
2285 sbio
= BIO_push(test
, sbio
);
2289 BIO_set_callback_ex(sbio
, bio_dump_callback
);
2290 BIO_set_callback_arg(sbio
, (char *)bio_c_out
);
2293 #ifndef OPENSSL_NO_SSL_TRACE
2295 SSL_set_msg_callback(con
, SSL_trace
);
2298 SSL_set_msg_callback(con
, msg_cb
);
2299 SSL_set_msg_callback_arg(con
, bio_c_msg
? bio_c_msg
: bio_c_out
);
2302 if (c_tlsextdebug
) {
2303 SSL_set_tlsext_debug_callback(con
, tlsext_cb
);
2304 SSL_set_tlsext_debug_arg(con
, bio_c_out
);
2306 #ifndef OPENSSL_NO_OCSP
2308 SSL_set_tlsext_status_type(con
, TLSEXT_STATUSTYPE_ocsp
);
2309 SSL_CTX_set_tlsext_status_cb(ctx
, ocsp_resp_cb
);
2310 SSL_CTX_set_tlsext_status_arg(ctx
, bio_c_out
);
2314 SSL_set_bio(con
, sbio
, sbio
);
2315 SSL_set_connect_state(con
);
2317 /* ok, lets connect */
2318 if (fileno_stdin() > SSL_get_fd(con
))
2319 width
= fileno_stdin() + 1;
2321 width
= SSL_get_fd(con
) + 1;
2335 #ifndef OPENSSL_NO_HTTP
2336 if (proxystr
!= NULL
) {
2337 /* Here we must use the connect string target host & port */
2338 if (!OSSL_HTTP_proxy_connect(sbio
, thost
, tport
, proxyuser
, proxypass
,
2339 0 /* no timeout */, bio_err
, prog
))
2344 switch ((PROTOCOL_CHOICE
) starttls_proto
) {
2351 * This is an ugly hack that does a lot of assumptions. We do
2352 * have to handle multi-line responses which may come in a single
2353 * packet or not. We therefore have to use BIO_gets() which does
2354 * need a buffering BIO. So during the initial chitchat we do
2355 * push a buffering BIO into the chain that is removed again
2356 * later on to not disturb the rest of the s_client operation.
2359 BIO
*fbio
= BIO_new(BIO_f_buffer());
2362 BIO_printf(bio_err
, "Unable to create BIO\n");
2365 BIO_push(fbio
, sbio
);
2366 /* Wait for multi-line response to end from LMTP or SMTP */
2368 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2369 } while (mbuf_len
> 3 && mbuf
[3] == '-');
2370 if (protohost
== NULL
)
2371 protohost
= "mail.example.com";
2372 if (starttls_proto
== (int)PROTO_LMTP
)
2373 BIO_printf(fbio
, "LHLO %s\r\n", protohost
);
2375 BIO_printf(fbio
, "EHLO %s\r\n", protohost
);
2376 (void)BIO_flush(fbio
);
2378 * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2382 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2383 if (strstr(mbuf
, "STARTTLS"))
2385 } while (mbuf_len
> 3 && mbuf
[3] == '-');
2386 (void)BIO_flush(fbio
);
2391 "Didn't find STARTTLS in server response,"
2392 " trying anyway...\n");
2393 BIO_printf(sbio
, "STARTTLS\r\n");
2394 BIO_read(sbio
, sbuf
, BUFSIZZ
);
2399 BIO_read(sbio
, mbuf
, BUFSIZZ
);
2400 BIO_printf(sbio
, "STLS\r\n");
2401 mbuf_len
= BIO_read(sbio
, sbuf
, BUFSIZZ
);
2403 BIO_printf(bio_err
, "BIO_read failed\n");
2411 BIO
*fbio
= BIO_new(BIO_f_buffer());
2414 BIO_printf(bio_err
, "Unable to create BIO\n");
2417 BIO_push(fbio
, sbio
);
2418 BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2419 /* STARTTLS command requires CAPABILITY... */
2420 BIO_printf(fbio
, ". CAPABILITY\r\n");
2421 (void)BIO_flush(fbio
);
2422 /* wait for multi-line CAPABILITY response */
2424 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2425 if (strstr(mbuf
, "STARTTLS"))
2428 while (mbuf_len
> 3 && mbuf
[0] != '.');
2429 (void)BIO_flush(fbio
);
2434 "Didn't find STARTTLS in server response,"
2435 " trying anyway...\n");
2436 BIO_printf(sbio
, ". STARTTLS\r\n");
2437 BIO_read(sbio
, sbuf
, BUFSIZZ
);
2442 BIO
*fbio
= BIO_new(BIO_f_buffer());
2445 BIO_printf(bio_err
, "Unable to create BIO\n");
2448 BIO_push(fbio
, sbio
);
2449 /* wait for multi-line response to end from FTP */
2451 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2453 while (mbuf_len
> 3 && (!isdigit((unsigned char)mbuf
[0]) || !isdigit((unsigned char)mbuf
[1]) || !isdigit((unsigned char)mbuf
[2]) || mbuf
[3] != ' '));
2454 (void)BIO_flush(fbio
);
2457 BIO_printf(sbio
, "AUTH TLS\r\n");
2458 BIO_read(sbio
, sbuf
, BUFSIZZ
);
2462 case PROTO_XMPP_SERVER
:
2465 BIO_printf(sbio
, "<stream:stream "
2466 "xmlns:stream='http://etherx.jabber.org/streams' "
2467 "xmlns='jabber:%s' to='%s' version='1.0'>",
2468 starttls_proto
== PROTO_XMPP
? "client" : "server",
2469 protohost
? protohost
: host
);
2470 seen
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2472 BIO_printf(bio_err
, "BIO_read failed\n");
2477 (mbuf
, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2479 "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2481 seen
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2489 "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2490 seen
= BIO_read(sbio
, sbuf
, BUFSIZZ
);
2492 BIO_printf(bio_err
, "BIO_read failed\n");
2496 if (!strstr(sbuf
, "<proceed"))
2503 static const unsigned char tls_do
[] = {
2504 /* IAC DO START_TLS */
2507 static const unsigned char tls_will
[] = {
2508 /* IAC WILL START_TLS */
2511 static const unsigned char tls_follows
[] = {
2512 /* IAC SB START_TLS FOLLOWS IAC SE */
2513 255, 250, 46, 1, 255, 240
2517 /* Telnet server should demand we issue START_TLS */
2518 bytes
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2519 if (bytes
!= 3 || memcmp(mbuf
, tls_do
, 3) != 0)
2521 /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2522 BIO_write(sbio
, tls_will
, 3);
2523 BIO_write(sbio
, tls_follows
, 6);
2524 (void)BIO_flush(sbio
);
2525 /* Telnet server also sent the FOLLOWS sub-command */
2526 bytes
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2527 if (bytes
!= 6 || memcmp(mbuf
, tls_follows
, 6) != 0)
2534 BIO
*fbio
= BIO_new(BIO_f_buffer());
2537 BIO_printf(bio_err
, "Unable to create BIO\n");
2540 BIO_push(fbio
, sbio
);
2541 BIO_printf(fbio
, "STARTTLS\r\n");
2542 (void)BIO_flush(fbio
);
2543 width
= SSL_get_fd(con
) + 1;
2549 openssl_fdset(SSL_get_fd(con
), &readfds
);
2550 timeout
.tv_sec
= S_CLIENT_IRC_READ_TIMEOUT
;
2551 timeout
.tv_usec
= 0;
2553 * If the IRCd doesn't respond within
2554 * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2555 * it doesn't support STARTTLS. Many IRCds
2556 * will not give _any_ sort of response to a
2557 * STARTTLS command when it's not supported.
2559 if (!BIO_get_buffer_num_lines(fbio
)
2560 && !BIO_pending(fbio
)
2561 && !BIO_pending(sbio
)
2562 && select(width
, (void *)&readfds
, NULL
, NULL
,
2565 "Timeout waiting for response (%d seconds).\n",
2566 S_CLIENT_IRC_READ_TIMEOUT
);
2570 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2571 if (mbuf_len
< 1 || sscanf(mbuf
, "%*s %d", &numeric
) != 1)
2573 /* :example.net 451 STARTTLS :You have not registered */
2574 /* :example.net 421 STARTTLS :Unknown command */
2575 if ((numeric
== 451 || numeric
== 421)
2576 && strstr(mbuf
, "STARTTLS") != NULL
) {
2577 BIO_printf(bio_err
, "STARTTLS not supported: %s", mbuf
);
2580 if (numeric
== 691) {
2581 BIO_printf(bio_err
, "STARTTLS negotiation failed: ");
2582 ERR_print_errors(bio_err
);
2585 } while (numeric
!= 670);
2587 (void)BIO_flush(fbio
);
2590 if (numeric
!= 670) {
2591 BIO_printf(bio_err
, "Server does not support STARTTLS.\n");
2599 /* SSL request packet */
2600 static const unsigned char ssl_req
[] = {
2601 /* payload_length, sequence_id */
2602 0x20, 0x00, 0x00, 0x01,
2604 /* capability flags, CLIENT_SSL always set */
2605 0x85, 0xae, 0x7f, 0x00,
2606 /* max-packet size */
2607 0x00, 0x00, 0x00, 0x01,
2610 /* string[23] reserved (all [0]) */
2611 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2612 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2613 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2616 int ssl_flg
= 0x800;
2618 const unsigned char *packet
= (const unsigned char *)sbuf
;
2620 /* Receiving Initial Handshake packet. */
2621 bytes
= BIO_read(sbio
, (void *)packet
, BUFSIZZ
);
2623 BIO_printf(bio_err
, "BIO_read failed\n");
2625 /* Packet length[3], Packet number[1] + minimum payload[17] */
2626 } else if (bytes
< 21) {
2627 BIO_printf(bio_err
, "MySQL packet too short.\n");
2629 } else if (bytes
!= (4 + packet
[0] +
2631 (packet
[2] << 16))) {
2632 BIO_printf(bio_err
, "MySQL packet length does not match.\n");
2634 /* protocol version[1] */
2635 } else if (packet
[4] != 0xA) {
2637 "Only MySQL protocol version 10 is supported.\n");
2642 /* server version[string+NULL] */
2645 BIO_printf(bio_err
, "Cannot confirm server version. ");
2647 } else if (packet
[pos
++] == '\0') {
2652 /* make sure we have at least 15 bytes left in the packet */
2653 if (pos
+ 15 > bytes
) {
2655 "MySQL server handshake packet is broken.\n");
2659 pos
+= 12; /* skip over conn id[4] + SALT[8] */
2660 if (packet
[pos
++] != '\0') { /* verify filler */
2662 "MySQL packet is broken.\n");
2666 /* capability flags[2] */
2667 if (!((packet
[pos
] + (packet
[pos
+ 1] << 8)) & ssl_flg
)) {
2668 BIO_printf(bio_err
, "MySQL server does not support SSL.\n");
2672 /* Sending SSL Handshake packet. */
2673 BIO_write(sbio
, ssl_req
, sizeof(ssl_req
));
2674 (void)BIO_flush(sbio
);
2677 case PROTO_POSTGRES
:
2679 static const unsigned char ssl_request
[] = {
2680 /* Length SSLRequest */
2681 0, 0, 0, 8, 4, 210, 22, 47
2685 /* Send SSLRequest packet */
2686 BIO_write(sbio
, ssl_request
, 8);
2687 (void)BIO_flush(sbio
);
2689 /* Reply will be a single S if SSL is enabled */
2690 bytes
= BIO_read(sbio
, sbuf
, BUFSIZZ
);
2691 if (bytes
!= 1 || sbuf
[0] != 'S')
2698 BIO
*fbio
= BIO_new(BIO_f_buffer());
2701 BIO_printf(bio_err
, "Unable to create BIO\n");
2704 BIO_push(fbio
, sbio
);
2705 BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2706 /* STARTTLS command requires CAPABILITIES... */
2707 BIO_printf(fbio
, "CAPABILITIES\r\n");
2708 (void)BIO_flush(fbio
);
2709 BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2710 /* no point in trying to parse the CAPABILITIES response if there is none */
2711 if (strstr(mbuf
, "101") != NULL
) {
2712 /* wait for multi-line CAPABILITIES response */
2714 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2715 if (strstr(mbuf
, "STARTTLS"))
2717 } while (mbuf_len
> 1 && mbuf
[0] != '.');
2719 (void)BIO_flush(fbio
);
2724 "Didn't find STARTTLS in server response,"
2725 " trying anyway...\n");
2726 BIO_printf(sbio
, "STARTTLS\r\n");
2727 mbuf_len
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2729 BIO_printf(bio_err
, "BIO_read failed\n");
2732 mbuf
[mbuf_len
] = '\0';
2733 if (strstr(mbuf
, "382") == NULL
) {
2734 BIO_printf(bio_err
, "STARTTLS failed: %s", mbuf
);
2742 BIO
*fbio
= BIO_new(BIO_f_buffer());
2745 BIO_printf(bio_err
, "Unable to create BIO\n");
2748 BIO_push(fbio
, sbio
);
2749 /* wait for multi-line response to end from Sieve */
2751 mbuf_len
= BIO_gets(fbio
, mbuf
, BUFSIZZ
);
2753 * According to RFC 5804 § 1.7, capability
2754 * is case-insensitive, make it uppercase
2756 if (mbuf_len
> 1 && mbuf
[0] == '"') {
2757 make_uppercase(mbuf
);
2758 if (HAS_PREFIX(mbuf
, "\"STARTTLS\""))
2761 } while (mbuf_len
> 1 && mbuf
[0] == '"');
2762 (void)BIO_flush(fbio
);
2767 "Didn't find STARTTLS in server response,"
2768 " trying anyway...\n");
2769 BIO_printf(sbio
, "STARTTLS\r\n");
2770 mbuf_len
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2772 BIO_printf(bio_err
, "BIO_read failed\n");
2775 mbuf
[mbuf_len
] = '\0';
2777 BIO_printf(bio_err
, "STARTTLS failed: %s", mbuf
);
2781 * According to RFC 5804 § 2.2, response codes are case-
2782 * insensitive, make it uppercase but preserve the response.
2784 strncpy(sbuf
, mbuf
, 2);
2785 make_uppercase(sbuf
);
2786 if (!HAS_PREFIX(sbuf
, "OK")) {
2787 BIO_printf(bio_err
, "STARTTLS not supported: %s", mbuf
);
2794 /* StartTLS Operation according to RFC 4511 */
2795 static char ldap_tls_genconf
[] = "asn1=SEQUENCE:LDAPMessage\n"
2797 "messageID=INTEGER:1\n"
2798 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2799 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2801 char *genstr
= NULL
;
2803 ASN1_TYPE
*atyp
= NULL
;
2804 BIO
*ldapbio
= BIO_new(BIO_s_mem());
2805 CONF
*cnf
= NCONF_new(NULL
);
2807 if (ldapbio
== NULL
|| cnf
== NULL
) {
2812 BIO_puts(ldapbio
, ldap_tls_genconf
);
2813 if (NCONF_load_bio(cnf
, ldapbio
, &errline
) <= 0) {
2817 BIO_printf(bio_err
, "NCONF_load_bio failed\n");
2820 BIO_printf(bio_err
, "Error on line %ld\n", errline
);
2825 genstr
= NCONF_get_string(cnf
, "default", "asn1");
2826 if (genstr
== NULL
) {
2828 BIO_printf(bio_err
, "NCONF_get_string failed\n");
2831 atyp
= ASN1_generate_nconf(genstr
, cnf
);
2834 BIO_printf(bio_err
, "ASN1_generate_nconf failed\n");
2839 /* Send SSLRequest packet */
2840 BIO_write(sbio
, atyp
->value
.sequence
->data
,
2841 atyp
->value
.sequence
->length
);
2842 (void)BIO_flush(sbio
);
2843 ASN1_TYPE_free(atyp
);
2845 mbuf_len
= BIO_read(sbio
, mbuf
, BUFSIZZ
);
2847 BIO_printf(bio_err
, "BIO_read failed\n");
2850 result
= ldap_ExtendedResponse_parse(mbuf
, mbuf_len
);
2852 BIO_printf(bio_err
, "ldap_ExtendedResponse_parse failed\n");
2854 } else if (result
> 0) {
2855 BIO_printf(bio_err
, "STARTTLS failed, LDAP Result Code: %i\n",
2864 if (early_data_file
!= NULL
2865 && ((SSL_get0_session(con
) != NULL
2866 && SSL_SESSION_get_max_early_data(SSL_get0_session(con
)) > 0)
2868 && SSL_SESSION_get_max_early_data(psksess
) > 0))) {
2869 BIO
*edfile
= BIO_new_file(early_data_file
, "r");
2870 size_t readbytes
, writtenbytes
;
2873 if (edfile
== NULL
) {
2874 BIO_printf(bio_err
, "Cannot open early data file\n");
2879 if (!BIO_read_ex(edfile
, cbuf
, BUFSIZZ
, &readbytes
))
2882 while (!SSL_write_early_data(con
, cbuf
, readbytes
, &writtenbytes
)) {
2883 switch (SSL_get_error(con
, 0)) {
2884 case SSL_ERROR_WANT_WRITE
:
2885 case SSL_ERROR_WANT_ASYNC
:
2886 case SSL_ERROR_WANT_READ
:
2887 /* Just keep trying - busy waiting */
2890 BIO_printf(bio_err
, "Error writing early data\n");
2892 ERR_print_errors(bio_err
);
2901 user_data_init(&user_data
, con
, cbuf
, BUFSIZZ
, cmdmode
);
2906 if ((isdtls
|| isquic
)
2907 && SSL_get_event_timeout(con
, &timeout
, &is_infinite
)
2909 timeoutp
= &timeout
;
2913 if (!SSL_is_init_finished(con
) && SSL_total_renegotiations(con
) == 0
2914 && SSL_get_key_update_type(con
) == SSL_KEY_UPDATE_NONE
) {
2922 BIO_puts(bio_err
, "CONNECTION ESTABLISHED\n");
2923 print_ssl_summary(con
);
2926 print_stuff(bio_c_out
, con
, full_log
);
2930 if (starttls_proto
) {
2931 BIO_write(bio_err
, mbuf
, mbuf_len
);
2932 /* We don't need to know any more */
2934 starttls_proto
= PROTO_OFF
;
2939 BIO_printf(bio_c_out
,
2940 "drop connection and then reconnect\n");
2941 do_ssl_shutdown(con
);
2942 SSL_set_connect_state(con
);
2943 BIO_closesocket(SSL_get_fd(con
));
2951 switch (user_data_process(&user_data
, &cbuf_len
, &cbuf_off
)) {
2953 BIO_printf(bio_err
, "ERROR\n");
2955 case USER_DATA_PROCESS_SHUT
:
2959 case USER_DATA_PROCESS_RESTART
:
2962 case USER_DATA_PROCESS_NO_DATA
:
2965 case USER_DATA_PROCESS_CONTINUE
:
2971 && user_data_has_data(&user_data
));
2975 timeout
.tv_usec
= 0;
2981 ssl_pending
= read_ssl
&& SSL_has_pending(con
);
2984 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2987 * Note that select() returns when read _would not block_,
2988 * and EOF satisfies that. To avoid a CPU-hogging loop,
2989 * set the flag so we exit.
2991 if (read_tty
&& !at_eof
)
2992 openssl_fdset(fileno_stdin(), &readfds
);
2993 #if !defined(OPENSSL_SYS_VMS)
2995 openssl_fdset(fileno_stdout(), &writefds
);
3000 * Note that for QUIC we never actually check FD_ISSET() for the
3001 * underlying network fds. We just rely on select waking up when
3002 * they become readable/writeable and then SSL_handle_events() doing
3005 if ((!isquic
&& read_ssl
)
3006 || (isquic
&& SSL_net_read_desired(con
)))
3007 openssl_fdset(SSL_get_fd(con
), &readfds
);
3008 if ((!isquic
&& write_ssl
)
3009 || (isquic
&& (first_loop
|| SSL_net_write_desired(con
))))
3010 openssl_fdset(SSL_get_fd(con
), &writefds
);
3012 if (!tty_on
|| !write_tty
) {
3013 if ((!isquic
&& read_ssl
)
3014 || (isquic
&& SSL_net_read_desired(con
)))
3015 openssl_fdset(SSL_get_fd(con
), &readfds
);
3016 if ((!isquic
&& write_ssl
)
3017 || (isquic
&& (first_loop
|| SSL_net_write_desired(con
))))
3018 openssl_fdset(SSL_get_fd(con
), &writefds
);
3023 * Note: under VMS with SOCKETSHR the second parameter is
3024 * currently of type (int *) whereas under other systems it is
3025 * (void *) if you don't have a cast it will choke the compiler:
3026 * if you do have a cast then you can either go for (int *) or
3029 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
3031 * Under Windows/DOS we make the assumption that we can always
3032 * write to the tty: therefore, if we need to write to the tty we
3033 * just fall through. Otherwise we timeout the select every
3034 * second and see if there are any keypresses. Note: this is a
3035 * hack, in a proper Windows application we wouldn't do this.
3042 i
= select(width
, (void *)&readfds
, (void *)&writefds
,
3044 if (!i
&& (!has_stdin_waiting() || !read_tty
))
3047 i
= select(width
, (void *)&readfds
, (void *)&writefds
,
3051 i
= select(width
, (void *)&readfds
, (void *)&writefds
,
3055 BIO_printf(bio_err
, "bad select %d\n",
3056 get_last_socket_error());
3061 if (timeoutp
!= NULL
) {
3062 SSL_handle_events(con
);
3064 && !FD_ISSET(SSL_get_fd(con
), &readfds
)
3065 && !FD_ISSET(SSL_get_fd(con
), &writefds
))
3066 BIO_printf(bio_err
, "TIMEOUT occurred\n");
3070 && ((!isquic
&& FD_ISSET(SSL_get_fd(con
), &writefds
))
3071 || (isquic
&& (cbuf_len
> 0 || first_loop
)))) {
3072 k
= SSL_write(con
, &(cbuf
[cbuf_off
]), (unsigned int)cbuf_len
);
3073 switch (SSL_get_error(con
, k
)) {
3074 case SSL_ERROR_NONE
:
3079 /* we have done a write(con,NULL,0); */
3080 if (cbuf_len
== 0) {
3083 } else { /* if (cbuf_len > 0) */
3089 case SSL_ERROR_WANT_WRITE
:
3090 BIO_printf(bio_c_out
, "write W BLOCK\n");
3094 case SSL_ERROR_WANT_ASYNC
:
3095 BIO_printf(bio_c_out
, "write A BLOCK\n");
3096 wait_for_async(con
);
3100 case SSL_ERROR_WANT_READ
:
3101 BIO_printf(bio_c_out
, "write R BLOCK\n");
3106 case SSL_ERROR_WANT_X509_LOOKUP
:
3107 BIO_printf(bio_c_out
, "write X BLOCK\n");
3109 case SSL_ERROR_ZERO_RETURN
:
3110 if (cbuf_len
!= 0) {
3111 BIO_printf(bio_c_out
, "shutdown\n");
3120 case SSL_ERROR_SYSCALL
:
3121 if ((k
!= 0) || (cbuf_len
!= 0)) {
3122 int sockerr
= get_last_socket_error();
3124 if (!tfo
|| sockerr
!= EISCONN
) {
3125 BIO_printf(bio_err
, "write:errno=%d\n", sockerr
);
3133 case SSL_ERROR_WANT_ASYNC_JOB
:
3134 /* This shouldn't ever happen in s_client - treat as an error */
3136 ERR_print_errors(bio_err
);
3140 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
3141 /* Assume Windows/DOS/BeOS can always write */
3142 else if (!ssl_pending
&& write_tty
)
3144 else if (!ssl_pending
&& FD_ISSET(fileno_stdout(), &writefds
))
3147 #ifdef CHARSET_EBCDIC
3148 ascii2ebcdic(&(sbuf
[sbuf_off
]), &(sbuf
[sbuf_off
]), sbuf_len
);
3150 i
= raw_write_stdout(&(sbuf
[sbuf_off
]), sbuf_len
);
3153 BIO_printf(bio_c_out
, "DONE\n");
3160 if (sbuf_len
<= 0) {
3164 } else if (ssl_pending
3165 || (!isquic
&& FD_ISSET(SSL_get_fd(con
), &readfds
))) {
3170 SSL_renegotiate(con
);
3175 k
= SSL_read(con
, sbuf
, 1024 /* BUFSIZZ */ );
3177 switch (SSL_get_error(con
, k
)) {
3178 case SSL_ERROR_NONE
:
3187 case SSL_ERROR_WANT_ASYNC
:
3188 BIO_printf(bio_c_out
, "read A BLOCK\n");
3189 wait_for_async(con
);
3192 if ((read_tty
== 0) && (write_ssl
== 0))
3195 case SSL_ERROR_WANT_WRITE
:
3196 BIO_printf(bio_c_out
, "read W BLOCK\n");
3200 case SSL_ERROR_WANT_READ
:
3201 BIO_printf(bio_c_out
, "read R BLOCK\n");
3204 if ((read_tty
== 0) && (write_ssl
== 0))
3207 case SSL_ERROR_WANT_X509_LOOKUP
:
3208 BIO_printf(bio_c_out
, "read X BLOCK\n");
3210 case SSL_ERROR_SYSCALL
:
3211 ret
= get_last_socket_error();
3213 BIO_puts(bio_err
, "CONNECTION CLOSED BY SERVER\n");
3215 BIO_printf(bio_err
, "read:errno=%d\n", ret
);
3217 case SSL_ERROR_ZERO_RETURN
:
3218 BIO_printf(bio_c_out
, "closed\n");
3221 case SSL_ERROR_WANT_ASYNC_JOB
:
3222 /* This shouldn't ever happen in s_client. Treat as an error */
3224 ERR_print_errors(bio_err
);
3229 /* don't wait for client input in the non-interactive mode */
3230 else if (nointeractive
) {
3235 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
3236 #if defined(OPENSSL_SYS_MSDOS)
3237 else if (has_stdin_waiting())
3239 else if (FD_ISSET(fileno_stdin(), &readfds
))
3245 i
= raw_read_stdin(cbuf
, BUFSIZZ
/ 2);
3247 /* both loops are skipped when i <= 0 */
3248 for (j
= 0; j
< i
; j
++)
3249 if (cbuf
[j
] == '\n')
3251 for (j
= i
- 1; j
>= 0; j
--) {
3252 cbuf
[j
+ lf_num
] = cbuf
[j
];
3253 if (cbuf
[j
] == '\n') {
3256 cbuf
[j
+ lf_num
] = '\r';
3259 assert(lf_num
== 0);
3261 i
= raw_read_stdin(cbuf
, BUFSIZZ
);
3262 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3267 if (!c_ign_eof
&& i
<= 0) {
3268 BIO_printf(bio_err
, "DONE\n");
3273 if (i
> 0 && !user_data_add(&user_data
, i
)) {
3284 print_stuff(bio_c_out
, con
, full_log
);
3285 do_ssl_shutdown(con
);
3288 * If we ended with an alert being sent, but still with data in the
3289 * network buffer to be read, then calling BIO_closesocket() will
3290 * result in a TCP-RST being sent. On some platforms (notably
3291 * Windows) then this will result in the peer immediately abandoning
3292 * the connection including any buffered alert data before it has
3293 * had a chance to be read. Shutting down the sending side first,
3294 * and then closing the socket sends TCP-FIN first followed by
3295 * TCP-RST. This seems to allow the peer to read the alert data.
3297 shutdown(SSL_get_fd(con
), 1); /* SHUT_WR */
3299 * We just said we have nothing else to say, but it doesn't mean that
3300 * the other side has nothing. It's even recommended to consume incoming
3301 * data. [In testing context this ensures that alerts are passed on...]
3304 timeout
.tv_usec
= 500000; /* some extreme round-trip */
3307 openssl_fdset(sock
, &readfds
);
3308 } while (select(sock
+ 1, &readfds
, NULL
, NULL
, &timeout
) > 0
3309 && BIO_read(sbio
, sbuf
, BUFSIZZ
) > 0);
3311 BIO_closesocket(SSL_get_fd(con
));
3315 print_stuff(bio_c_out
, con
, 1);
3318 SSL_SESSION_free(psksess
);
3319 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3320 OPENSSL_free(next_proto
.data
);
3323 set_keylog_file(NULL
, NULL
);
3325 sk_X509_CRL_pop_free(crls
, X509_CRL_free
);
3327 OSSL_STACK_OF_X509_free(chain
);
3329 #ifndef OPENSSL_NO_SRP
3330 OPENSSL_free(srp_arg
.srppassin
);
3332 OPENSSL_free(sname_alloc
);
3333 BIO_ADDR_free(peer_addr
);
3334 OPENSSL_free(connectstr
);
3335 OPENSSL_free(bindstr
);
3336 OPENSSL_free(bindhost
);
3337 OPENSSL_free(bindport
);
3340 OPENSSL_free(thost
);
3341 OPENSSL_free(tport
);
3342 X509_VERIFY_PARAM_free(vpm
);
3343 ssl_excert_free(exc
);
3344 sk_OPENSSL_STRING_free(ssl_args
);
3345 sk_OPENSSL_STRING_free(dane_tlsa_rrset
);
3346 SSL_CONF_CTX_free(cctx
);
3347 OPENSSL_clear_free(cbuf
, BUFSIZZ
);
3348 OPENSSL_clear_free(sbuf
, BUFSIZZ
);
3349 OPENSSL_clear_free(mbuf
, BUFSIZZ
);
3350 clear_free(proxypass
);
3352 BIO_free(bio_c_out
);
3354 BIO_free(bio_c_msg
);
3359 static void print_stuff(BIO
*bio
, SSL
*s
, int full
)
3363 const SSL_CIPHER
*c
;
3364 EVP_PKEY
*public_key
;
3365 int i
, istls13
= (SSL_version(s
) == TLS1_3_VERSION
);
3367 #ifndef OPENSSL_NO_COMP
3368 const COMP_METHOD
*comp
, *expansion
;
3370 unsigned char *exportedkeymat
;
3371 #ifndef OPENSSL_NO_CT
3372 const SSL_CTX
*ctx
= SSL_get_SSL_CTX(s
);
3376 int got_a_chain
= 0;
3378 sk
= SSL_get_peer_cert_chain(s
);
3382 BIO_printf(bio
, "---\nCertificate chain\n");
3383 for (i
= 0; i
< sk_X509_num(sk
); i
++) {
3384 BIO_printf(bio
, "%2d s:", i
);
3385 X509_NAME_print_ex(bio
, X509_get_subject_name(sk_X509_value(sk
, i
)), 0, get_nameopt());
3386 BIO_puts(bio
, "\n");
3387 BIO_printf(bio
, " i:");
3388 X509_NAME_print_ex(bio
, X509_get_issuer_name(sk_X509_value(sk
, i
)), 0, get_nameopt());
3389 BIO_puts(bio
, "\n");
3390 public_key
= X509_get_pubkey(sk_X509_value(sk
, i
));
3391 if (public_key
!= NULL
) {
3392 BIO_printf(bio
, " a:PKEY: %s, %d (bit); sigalg: %s\n",
3393 OBJ_nid2sn(EVP_PKEY_get_base_id(public_key
)),
3394 EVP_PKEY_get_bits(public_key
),
3395 OBJ_nid2sn(X509_get_signature_nid(sk_X509_value(sk
, i
))));
3396 EVP_PKEY_free(public_key
);
3398 BIO_printf(bio
, " v:NotBefore: ");
3399 ASN1_TIME_print(bio
, X509_get0_notBefore(sk_X509_value(sk
, i
)));
3400 BIO_printf(bio
, "; NotAfter: ");
3401 ASN1_TIME_print(bio
, X509_get0_notAfter(sk_X509_value(sk
, i
)));
3402 BIO_puts(bio
, "\n");
3404 PEM_write_bio_X509(bio
, sk_X509_value(sk
, i
));
3408 BIO_printf(bio
, "---\n");
3409 peer
= SSL_get0_peer_certificate(s
);
3411 BIO_printf(bio
, "Server certificate\n");
3413 /* Redundant if we showed the whole chain */
3414 if (!(c_showcerts
&& got_a_chain
))
3415 PEM_write_bio_X509(bio
, peer
);
3416 dump_cert_text(bio
, peer
);
3418 BIO_printf(bio
, "no peer certificate available\n");
3421 /* Only display RPK information if configured */
3422 if (SSL_get_negotiated_client_cert_type(s
) == TLSEXT_cert_type_rpk
)
3423 BIO_printf(bio
, "Client-to-server raw public key negotiated\n");
3424 if (SSL_get_negotiated_server_cert_type(s
) == TLSEXT_cert_type_rpk
)
3425 BIO_printf(bio
, "Server-to-client raw public key negotiated\n");
3426 if (enable_server_rpk
) {
3427 EVP_PKEY
*peer_rpk
= SSL_get0_peer_rpk(s
);
3429 if (peer_rpk
!= NULL
) {
3430 BIO_printf(bio
, "Server raw public key\n");
3431 EVP_PKEY_print_public(bio
, peer_rpk
, 2, NULL
);
3433 BIO_printf(bio
, "no peer rpk available\n");
3437 print_ca_names(bio
, s
);
3439 ssl_print_sigalgs(bio
, s
);
3440 ssl_print_tmp_key(bio
, s
);
3442 #ifndef OPENSSL_NO_CT
3444 * When the SSL session is anonymous, or resumed via an abbreviated
3445 * handshake, no SCTs are provided as part of the handshake. While in
3446 * a resumed session SCTs may be present in the session's certificate,
3447 * no callbacks are invoked to revalidate these, and in any case that
3448 * set of SCTs may be incomplete. Thus it makes little sense to
3449 * attempt to display SCTs from a resumed session's certificate, and of
3450 * course none are associated with an anonymous peer.
3452 if (peer
!= NULL
&& !SSL_session_reused(s
) && SSL_ct_is_enabled(s
)) {
3453 const STACK_OF(SCT
) *scts
= SSL_get0_peer_scts(s
);
3454 int sct_count
= scts
!= NULL
? sk_SCT_num(scts
) : 0;
3456 BIO_printf(bio
, "---\nSCTs present (%i)\n", sct_count
);
3457 if (sct_count
> 0) {
3458 const CTLOG_STORE
*log_store
= SSL_CTX_get0_ctlog_store(ctx
);
3460 BIO_printf(bio
, "---\n");
3461 for (i
= 0; i
< sct_count
; ++i
) {
3462 SCT
*sct
= sk_SCT_value(scts
, i
);
3464 BIO_printf(bio
, "SCT validation status: %s\n",
3465 SCT_validation_status_string(sct
));
3466 SCT_print(sct
, bio
, 0, log_store
);
3467 if (i
< sct_count
- 1)
3468 BIO_printf(bio
, "\n---\n");
3470 BIO_printf(bio
, "\n");
3476 "---\nSSL handshake has read %ju bytes "
3477 "and written %ju bytes\n",
3478 BIO_number_read(SSL_get_rbio(s
)),
3479 BIO_number_written(SSL_get_wbio(s
)));
3481 print_verify_detail(s
, bio
);
3482 BIO_printf(bio
, (SSL_session_reused(s
) ? "---\nReused, " : "---\nNew, "));
3483 c
= SSL_get_current_cipher(s
);
3484 BIO_printf(bio
, "%s, Cipher is %s\n",
3485 SSL_CIPHER_get_version(c
), SSL_CIPHER_get_name(c
));
3489 pktmp
= X509_get0_pubkey(peer
);
3490 BIO_printf(bio
, "Server public key is %d bit\n",
3491 EVP_PKEY_get_bits(pktmp
));
3494 ssl_print_secure_renegotiation_notes(bio
, s
);
3496 #ifndef OPENSSL_NO_COMP
3497 comp
= SSL_get_current_compression(s
);
3498 expansion
= SSL_get_current_expansion(s
);
3499 BIO_printf(bio
, "Compression: %s\n",
3500 comp
? SSL_COMP_get_name(comp
) : "NONE");
3501 BIO_printf(bio
, "Expansion: %s\n",
3502 expansion
? SSL_COMP_get_name(expansion
) : "NONE");
3504 #ifndef OPENSSL_NO_KTLS
3505 if (BIO_get_ktls_send(SSL_get_wbio(s
)))
3506 BIO_printf(bio_err
, "Using Kernel TLS for sending\n");
3507 if (BIO_get_ktls_recv(SSL_get_rbio(s
)))
3508 BIO_printf(bio_err
, "Using Kernel TLS for receiving\n");
3511 if (OSSL_TRACE_ENABLED(TLS
)) {
3512 /* Print out local port of connection: useful for debugging */
3514 union BIO_sock_info_u info
;
3516 sock
= SSL_get_fd(s
);
3517 if ((info
.addr
= BIO_ADDR_new()) != NULL
3518 && BIO_sock_info(sock
, BIO_SOCK_INFO_ADDRESS
, &info
)) {
3519 BIO_printf(bio_c_out
, "LOCAL PORT is %u\n",
3520 ntohs(BIO_ADDR_rawport(info
.addr
)));
3522 BIO_ADDR_free(info
.addr
);
3525 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3526 if (next_proto
.status
!= -1) {
3527 const unsigned char *proto
;
3528 unsigned int proto_len
;
3529 SSL_get0_next_proto_negotiated(s
, &proto
, &proto_len
);
3530 BIO_printf(bio
, "Next protocol: (%d) ", next_proto
.status
);
3531 BIO_write(bio
, proto
, proto_len
);
3532 BIO_write(bio
, "\n", 1);
3536 const unsigned char *proto
;
3537 unsigned int proto_len
;
3538 SSL_get0_alpn_selected(s
, &proto
, &proto_len
);
3539 if (proto_len
> 0) {
3540 BIO_printf(bio
, "ALPN protocol: ");
3541 BIO_write(bio
, proto
, proto_len
);
3542 BIO_write(bio
, "\n", 1);
3544 BIO_printf(bio
, "No ALPN negotiated\n");
3547 #ifndef OPENSSL_NO_SRTP
3549 SRTP_PROTECTION_PROFILE
*srtp_profile
=
3550 SSL_get_selected_srtp_profile(s
);
3553 BIO_printf(bio
, "SRTP Extension negotiated, profile=%s\n",
3554 srtp_profile
->name
);
3559 switch (SSL_get_early_data_status(s
)) {
3560 case SSL_EARLY_DATA_NOT_SENT
:
3561 BIO_printf(bio
, "Early data was not sent\n");
3564 case SSL_EARLY_DATA_REJECTED
:
3565 BIO_printf(bio
, "Early data was rejected\n");
3568 case SSL_EARLY_DATA_ACCEPTED
:
3569 BIO_printf(bio
, "Early data was accepted\n");
3575 * We also print the verify results when we dump session information,
3576 * but in TLSv1.3 we may not get that right away (or at all) depending
3577 * on when we get a NewSessionTicket. Therefore, we print it now as well.
3579 verify_result
= SSL_get_verify_result(s
);
3580 BIO_printf(bio
, "Verify return code: %ld (%s)\n", verify_result
,
3581 X509_verify_cert_error_string(verify_result
));
3583 /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3584 SSL_SESSION_print(bio
, SSL_get_session(s
));
3587 if (SSL_get_session(s
) != NULL
&& keymatexportlabel
!= NULL
) {
3588 BIO_printf(bio
, "Keying material exporter:\n");
3589 BIO_printf(bio
, " Label: '%s'\n", keymatexportlabel
);
3590 BIO_printf(bio
, " Length: %i bytes\n", keymatexportlen
);
3591 exportedkeymat
= app_malloc(keymatexportlen
, "export key");
3592 if (SSL_export_keying_material(s
, exportedkeymat
,
3595 strlen(keymatexportlabel
),
3597 BIO_printf(bio
, " Error\n");
3599 BIO_printf(bio
, " Keying material: ");
3600 for (i
= 0; i
< keymatexportlen
; i
++)
3601 BIO_printf(bio
, "%02X", exportedkeymat
[i
]);
3602 BIO_printf(bio
, "\n");
3604 OPENSSL_free(exportedkeymat
);
3606 BIO_printf(bio
, "---\n");
3607 /* flush, or debugging output gets mixed with http response */
3608 (void)BIO_flush(bio
);
3611 # ifndef OPENSSL_NO_OCSP
3612 static int ocsp_resp_cb(SSL
*s
, void *arg
)
3614 const unsigned char *p
;
3617 len
= SSL_get_tlsext_status_ocsp_resp(s
, &p
);
3618 BIO_puts(arg
, "OCSP response: ");
3620 BIO_puts(arg
, "no response sent\n");
3623 rsp
= d2i_OCSP_RESPONSE(NULL
, &p
, len
);
3625 BIO_puts(arg
, "response parse error\n");
3626 BIO_dump_indent(arg
, (char *)p
, len
, 4);
3629 BIO_puts(arg
, "\n======================================\n");
3630 OCSP_RESPONSE_print(arg
, rsp
, 0);
3631 BIO_puts(arg
, "======================================\n");
3632 OCSP_RESPONSE_free(rsp
);
3637 static int ldap_ExtendedResponse_parse(const char *buf
, long rem
)
3639 const unsigned char *cur
, *end
;
3641 int tag
, xclass
, inf
, ret
= -1;
3643 cur
= (const unsigned char *)buf
;
3649 * LDAPMessage ::= SEQUENCE {
3650 * messageID MessageID,
3651 * protocolOp CHOICE {
3653 * extendedResp ExtendedResponse,
3655 * controls [0] Controls OPTIONAL }
3657 * ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3658 * COMPONENTS OF LDAPResult,
3659 * responseName [10] LDAPOID OPTIONAL,
3660 * responseValue [11] OCTET STRING OPTIONAL }
3662 * LDAPResult ::= SEQUENCE {
3663 * resultCode ENUMERATED {
3669 * diagnosticMessage LDAPString,
3670 * referral [3] Referral OPTIONAL }
3674 inf
= ASN1_get_object(&cur
, &len
, &tag
, &xclass
, rem
);
3675 if (inf
!= V_ASN1_CONSTRUCTED
|| tag
!= V_ASN1_SEQUENCE
||
3676 (rem
= end
- cur
, len
> rem
)) {
3677 BIO_printf(bio_err
, "Unexpected LDAP response\n");
3681 rem
= len
; /* ensure that we don't overstep the SEQUENCE */
3683 /* pull MessageID */
3684 inf
= ASN1_get_object(&cur
, &len
, &tag
, &xclass
, rem
);
3685 if (inf
!= V_ASN1_UNIVERSAL
|| tag
!= V_ASN1_INTEGER
||
3686 (rem
= end
- cur
, len
> rem
)) {
3687 BIO_printf(bio_err
, "No MessageID\n");
3691 cur
+= len
; /* shall we check for MessageId match or just skip? */
3693 /* pull [APPLICATION 24] */
3695 inf
= ASN1_get_object(&cur
, &len
, &tag
, &xclass
, rem
);
3696 if (inf
!= V_ASN1_CONSTRUCTED
|| xclass
!= V_ASN1_APPLICATION
||
3698 BIO_printf(bio_err
, "Not ExtendedResponse\n");
3702 /* pull resultCode */
3704 inf
= ASN1_get_object(&cur
, &len
, &tag
, &xclass
, rem
);
3705 if (inf
!= V_ASN1_UNIVERSAL
|| tag
!= V_ASN1_ENUMERATED
|| len
== 0 ||
3706 (rem
= end
- cur
, len
> rem
)) {
3707 BIO_printf(bio_err
, "Not LDAPResult\n");
3711 /* len should always be one, but just in case... */
3712 for (ret
= 0, inf
= 0; inf
< len
; inf
++) {
3716 /* There is more data, but we don't care... */
3722 * Host dNS Name verifier: used for checking that the hostname is in dNS format
3723 * before setting it as SNI
3725 static int is_dNS_name(const char *host
)
3727 const size_t MAX_LABEL_LENGTH
= 63;
3730 size_t length
= strlen(host
);
3731 size_t label_length
= 0;
3732 int all_numeric
= 1;
3735 * Deviation from strict DNS name syntax, also check names with '_'
3736 * Check DNS name syntax, any '-' or '.' must be internal,
3737 * and on either side of each '.' we can't have a '-' or '.'.
3739 * If the name has just one label, we don't consider it a DNS name.
3741 for (i
= 0; i
< length
&& label_length
< MAX_LABEL_LENGTH
; ++i
) {
3744 if ((c
>= 'a' && c
<= 'z')
3745 || (c
>= 'A' && c
<= 'Z')
3752 if (c
>= '0' && c
<= '9') {
3757 /* Dot and hyphen cannot be first or last. */
3758 if (i
> 0 && i
< length
- 1) {
3764 * Next to a dot the preceding and following characters must not be
3765 * another dot or a hyphen. Otherwise, record that the name is
3766 * plausible, since it has two or more labels.
3769 && host
[i
+ 1] != '.'
3770 && host
[i
- 1] != '-'
3771 && host
[i
+ 1] != '-') {
3781 /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
3782 isdnsname
&= !all_numeric
&& !(label_length
== MAX_LABEL_LENGTH
);
3787 static void user_data_init(struct user_data_st
*user_data
, SSL
*con
, char *buf
,
3788 size_t bufmax
, int mode
)
3790 user_data
->con
= con
;
3791 user_data
->buf
= buf
;
3792 user_data
->bufmax
= bufmax
;
3793 user_data
->buflen
= 0;
3794 user_data
->bufoff
= 0;
3795 user_data
->mode
= mode
;
3796 user_data
->isfin
= 0;
3799 static int user_data_add(struct user_data_st
*user_data
, size_t i
)
3801 if (user_data
->buflen
!= 0 || i
> user_data
->bufmax
)
3804 user_data
->buflen
= i
;
3805 user_data
->bufoff
= 0;
3810 #define USER_COMMAND_HELP 0
3811 #define USER_COMMAND_QUIT 1
3812 #define USER_COMMAND_RECONNECT 2
3813 #define USER_COMMAND_RENEGOTIATE 3
3814 #define USER_COMMAND_KEY_UPDATE 4
3815 #define USER_COMMAND_FIN 5
3817 static int user_data_execute(struct user_data_st
*user_data
, int cmd
, char *arg
)
3820 case USER_COMMAND_HELP
:
3821 /* This only ever occurs in advanced mode, so just emit advanced help */
3822 BIO_printf(bio_err
, "Enter text to send to the peer followed by <enter>\n");
3823 BIO_printf(bio_err
, "To issue a command insert {cmd} or {cmd:arg} anywhere in the text\n");
3824 BIO_printf(bio_err
, "Entering {{ will send { to the peer\n");
3825 BIO_printf(bio_err
, "The following commands are available\n");
3826 BIO_printf(bio_err
, " {help}: Get this help text\n");
3827 BIO_printf(bio_err
, " {quit}: Close the connection to the peer\n");
3828 BIO_printf(bio_err
, " {reconnect}: Reconnect to the peer\n");
3829 if (SSL_is_quic(user_data
->con
)) {
3830 BIO_printf(bio_err
, " {fin}: Send FIN on the stream. No further writing is possible\n");
3831 } else if(SSL_version(user_data
->con
) == TLS1_3_VERSION
) {
3832 BIO_printf(bio_err
, " {keyup:req|noreq}: Send a Key Update message\n");
3833 BIO_printf(bio_err
, " Arguments:\n");
3834 BIO_printf(bio_err
, " req = peer update requested (default)\n");
3835 BIO_printf(bio_err
, " noreq = peer update not requested\n");
3837 BIO_printf(bio_err
, " {reneg}: Attempt to renegotiate\n");
3839 BIO_printf(bio_err
, "\n");
3840 return USER_DATA_PROCESS_NO_DATA
;
3842 case USER_COMMAND_QUIT
:
3843 BIO_printf(bio_err
, "DONE\n");
3844 return USER_DATA_PROCESS_SHUT
;
3846 case USER_COMMAND_RECONNECT
:
3847 BIO_printf(bio_err
, "RECONNECTING\n");
3848 do_ssl_shutdown(user_data
->con
);
3849 SSL_set_connect_state(user_data
->con
);
3850 BIO_closesocket(SSL_get_fd(user_data
->con
));
3851 return USER_DATA_PROCESS_RESTART
;
3853 case USER_COMMAND_RENEGOTIATE
:
3854 BIO_printf(bio_err
, "RENEGOTIATING\n");
3855 if (!SSL_renegotiate(user_data
->con
))
3857 return USER_DATA_PROCESS_CONTINUE
;
3859 case USER_COMMAND_KEY_UPDATE
: {
3862 if (OPENSSL_strcasecmp(arg
, "req") == 0)
3863 updatetype
= SSL_KEY_UPDATE_REQUESTED
;
3864 else if (OPENSSL_strcasecmp(arg
, "noreq") == 0)
3865 updatetype
= SSL_KEY_UPDATE_NOT_REQUESTED
;
3867 return USER_DATA_PROCESS_BAD_ARGUMENT
;
3868 BIO_printf(bio_err
, "KEYUPDATE\n");
3869 if (!SSL_key_update(user_data
->con
, updatetype
))
3871 return USER_DATA_PROCESS_CONTINUE
;
3874 case USER_COMMAND_FIN
:
3875 if (!SSL_stream_conclude(user_data
->con
, 0))
3877 user_data
->isfin
= 1;
3878 return USER_DATA_PROCESS_NO_DATA
;
3884 BIO_printf(bio_err
, "ERROR\n");
3885 ERR_print_errors(bio_err
);
3887 return USER_DATA_PROCESS_SHUT
;
3890 static int user_data_process(struct user_data_st
*user_data
, size_t *len
,
3893 char *buf_start
= user_data
->buf
+ user_data
->bufoff
;
3894 size_t outlen
= user_data
->buflen
;
3896 if (user_data
->buflen
== 0) {
3899 return USER_DATA_PROCESS_NO_DATA
;
3902 if (user_data
->mode
== USER_DATA_MODE_BASIC
) {
3903 switch (buf_start
[0]) {
3905 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3906 return user_data_execute(user_data
, USER_COMMAND_QUIT
, NULL
);
3909 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3910 return user_data_execute(user_data
, USER_COMMAND_RECONNECT
, NULL
);
3913 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3914 return user_data_execute(user_data
, USER_COMMAND_RENEGOTIATE
, NULL
);
3918 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3919 return user_data_execute(user_data
, USER_COMMAND_KEY_UPDATE
,
3920 buf_start
[0] == 'K' ? "req" : "noreq");
3924 } else if (user_data
->mode
== USER_DATA_MODE_ADVANCED
) {
3925 char *cmd_start
= buf_start
;
3927 cmd_start
[outlen
] = '\0';
3929 cmd_start
= strchr(cmd_start
, '{');
3930 if (cmd_start
== buf_start
&& *(cmd_start
+ 1) == '{') {
3931 /* The "{" is escaped, so skip it */
3934 user_data
->bufoff
++;
3935 user_data
->buflen
--;
3942 if (cmd_start
== buf_start
) {
3943 /* Command detected */
3944 char *cmd_end
= strchr(cmd_start
, '}');
3946 int cmd
= -1, ret
= USER_DATA_PROCESS_NO_DATA
;
3949 if (cmd_end
== NULL
) {
3950 /* Malformed command */
3951 cmd_start
[outlen
- 1] = '\0';
3953 "ERROR PROCESSING COMMAND. REST OF LINE IGNORED: %s\n",
3955 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
3956 return USER_DATA_PROCESS_NO_DATA
;
3959 arg_start
= strchr(cmd_start
, ':');
3960 if (arg_start
!= NULL
) {
3964 /* Skip over the { */
3967 * Now we have cmd_start pointing to a NUL terminated string for
3968 * the command, and arg_start either being NULL or pointing to a
3969 * NUL terminated string for the argument.
3971 if (OPENSSL_strcasecmp(cmd_start
, "help") == 0) {
3972 cmd
= USER_COMMAND_HELP
;
3973 } else if (OPENSSL_strcasecmp(cmd_start
, "quit") == 0) {
3974 cmd
= USER_COMMAND_QUIT
;
3975 } else if (OPENSSL_strcasecmp(cmd_start
, "reconnect") == 0) {
3976 cmd
= USER_COMMAND_RECONNECT
;
3977 } else if(SSL_is_quic(user_data
->con
)) {
3978 if (OPENSSL_strcasecmp(cmd_start
, "fin") == 0)
3979 cmd
= USER_COMMAND_FIN
;
3980 } if (SSL_version(user_data
->con
) == TLS1_3_VERSION
) {
3981 if (OPENSSL_strcasecmp(cmd_start
, "keyup") == 0) {
3982 cmd
= USER_COMMAND_KEY_UPDATE
;
3983 if (arg_start
== NULL
)
3987 /* (D)TLSv1.2 or below */
3988 if (OPENSSL_strcasecmp(cmd_start
, "reneg") == 0)
3989 cmd
= USER_COMMAND_RENEGOTIATE
;
3992 BIO_printf(bio_err
, "UNRECOGNISED COMMAND (IGNORED): %s\n",
3995 ret
= user_data_execute(user_data
, cmd
, arg_start
);
3996 if (ret
== USER_DATA_PROCESS_BAD_ARGUMENT
) {
3997 BIO_printf(bio_err
, "BAD ARGUMENT (COMMAND IGNORED): %s\n",
3999 ret
= USER_DATA_PROCESS_NO_DATA
;
4002 oldoff
= user_data
->bufoff
;
4003 user_data
->bufoff
= (cmd_end
- user_data
->buf
) + 1;
4004 user_data
->buflen
-= user_data
->bufoff
- oldoff
;
4005 if (user_data
->buf
+ 1 == cmd_start
4006 && user_data
->buflen
== 1
4007 && user_data
->buf
[user_data
->bufoff
] == '\n') {
4009 * This command was the only thing on the whole line. We
4010 * suppress the final `\n`
4012 user_data
->bufoff
= 0;
4013 user_data
->buflen
= 0;
4017 } else if (cmd_start
!= NULL
) {
4019 * There is a command on this line, but its not at the start. Output
4020 * the start of the line, and we'll process the command next time
4021 * we call this function
4023 outlen
= cmd_start
- buf_start
;
4027 if (user_data
->isfin
) {
4028 user_data
->buflen
= user_data
->bufoff
= *len
= *off
= 0;
4029 return USER_DATA_PROCESS_NO_DATA
;
4032 #ifdef CHARSET_EBCDIC
4033 ebcdic2ascii(buf_start
, buf_start
, outlen
);
4036 *off
= user_data
->bufoff
;
4037 user_data
->buflen
-= outlen
;
4038 if (user_data
->buflen
== 0)
4039 user_data
->bufoff
= 0;
4041 user_data
->bufoff
+= outlen
;
4042 return USER_DATA_PROCESS_CONTINUE
;
4045 static int user_data_has_data(struct user_data_st
*user_data
)
4047 return user_data
->buflen
> 0;
4049 #endif /* OPENSSL_NO_SOCK */