xref: /openssl/apps/s_client.c (revision 23b795d3)
1 /*
2  * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2005 Nokia. All rights reserved.
4  *
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
9  */
10 
11 #include "internal/e_os.h"
12 #include <ctype.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <errno.h>
17 #include <openssl/e_os2.h>
18 #include "internal/nelem.h"
19 #include "internal/sockets.h" /* for openssl_fdset() */
20 
21 #ifndef OPENSSL_NO_SOCK
22 
23 /*
24  * With IPv6, it looks like Digital has mixed up the proper order of
25  * recursive header file inclusion, resulting in the compiler complaining
26  * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
27  * needed to have fileno() declared correctly...  So let's define u_int
28  */
29 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
30 # define __U_INT
31 typedef unsigned int u_int;
32 #endif
33 
34 #include "apps.h"
35 #include "progs.h"
36 #include <openssl/x509.h>
37 #include <openssl/ssl.h>
38 #include <openssl/err.h>
39 #include <openssl/pem.h>
40 #include <openssl/rand.h>
41 #include <openssl/ocsp.h>
42 #include <openssl/bn.h>
43 #include <openssl/trace.h>
44 #include <openssl/async.h>
45 #ifndef OPENSSL_NO_CT
46 # include <openssl/ct.h>
47 #endif
48 #include "s_apps.h"
49 #include "timeouts.h"
50 #include "internal/sockets.h"
51 
52 #if defined(__has_feature)
53 # if __has_feature(memory_sanitizer)
54 #  include <sanitizer/msan_interface.h>
55 # endif
56 #endif
57 
58 #undef BUFSIZZ
59 #define BUFSIZZ 1024*16
60 #define S_CLIENT_IRC_READ_TIMEOUT 8
61 
62 #define USER_DATA_MODE_NONE     0
63 #define USER_DATA_MODE_BASIC    1
64 #define USER_DATA_MODE_ADVANCED 2
65 
66 #define USER_DATA_PROCESS_BAD_ARGUMENT 0
67 #define USER_DATA_PROCESS_SHUT         1
68 #define USER_DATA_PROCESS_RESTART      2
69 #define USER_DATA_PROCESS_NO_DATA      3
70 #define USER_DATA_PROCESS_CONTINUE     4
71 
72 struct user_data_st {
73     /* SSL connection we are processing commands for */
74     SSL *con;
75 
76     /* Buffer where we are storing data supplied by the user */
77     char *buf;
78 
79     /* Allocated size of the buffer */
80     size_t bufmax;
81 
82     /* Amount of the buffer actually used */
83     size_t buflen;
84 
85     /* Current location in the buffer where we will read from next*/
86     size_t bufoff;
87 
88     /* The mode we are using for processing commands */
89     int mode;
90 
91     /* Whether FIN has ben sent on the stream */
92     int isfin;
93 };
94 
95 static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf,
96                            size_t bufmax, int mode);
97 static int user_data_add(struct user_data_st *user_data, size_t i);
98 static int user_data_process(struct user_data_st *user_data, size_t *len,
99                              size_t *off);
100 static int user_data_has_data(struct user_data_st *user_data);
101 
102 static char *prog;
103 static int c_debug = 0;
104 static int c_showcerts = 0;
105 static char *keymatexportlabel = NULL;
106 static int keymatexportlen = 20;
107 static BIO *bio_c_out = NULL;
108 static int c_quiet = 0;
109 static char *sess_out = NULL;
110 static SSL_SESSION *psksess = NULL;
111 
112 static void print_stuff(BIO *berr, SSL *con, int full);
113 #ifndef OPENSSL_NO_OCSP
114 static int ocsp_resp_cb(SSL *s, void *arg);
115 #endif
116 static int ldap_ExtendedResponse_parse(const char *buf, long rem);
117 static int is_dNS_name(const char *host);
118 
119 static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
120 static int enable_server_rpk = 0;
121 
122 static int saved_errno;
123 
save_errno(void)124 static void save_errno(void)
125 {
126     saved_errno = errno;
127     errno = 0;
128 }
129 
restore_errno(void)130 static int restore_errno(void)
131 {
132     int ret = errno;
133     errno = saved_errno;
134     return ret;
135 }
136 
137 /* Default PSK identity and key */
138 static char *psk_identity = "Client_identity";
139 
140 #ifndef OPENSSL_NO_PSK
psk_client_cb(SSL * ssl,const char * hint,char * identity,unsigned int max_identity_len,unsigned char * psk,unsigned int max_psk_len)141 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
142                                   unsigned int max_identity_len,
143                                   unsigned char *psk,
144                                   unsigned int max_psk_len)
145 {
146     int ret;
147     long key_len;
148     unsigned char *key;
149 
150     if (c_debug)
151         BIO_printf(bio_c_out, "psk_client_cb\n");
152     if (!hint) {
153         /* no ServerKeyExchange message */
154         if (c_debug)
155             BIO_printf(bio_c_out,
156                        "NULL received PSK identity hint, continuing anyway\n");
157     } else if (c_debug) {
158         BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
159     }
160 
161     /*
162      * lookup PSK identity and PSK key based on the given identity hint here
163      */
164     ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
165     if (ret < 0 || (unsigned int)ret > max_identity_len)
166         goto out_err;
167     if (c_debug)
168         BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
169                    ret);
170 
171     /* convert the PSK key to binary */
172     key = OPENSSL_hexstr2buf(psk_key, &key_len);
173     if (key == NULL) {
174         BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
175                    psk_key);
176         return 0;
177     }
178     if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
179         BIO_printf(bio_err,
180                    "psk buffer of callback is too small (%d) for key (%ld)\n",
181                    max_psk_len, key_len);
182         OPENSSL_free(key);
183         return 0;
184     }
185 
186     memcpy(psk, key, key_len);
187     OPENSSL_free(key);
188 
189     if (c_debug)
190         BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
191 
192     return key_len;
193  out_err:
194     if (c_debug)
195         BIO_printf(bio_err, "Error in PSK client callback\n");
196     return 0;
197 }
198 #endif
199 
200 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
201 const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
202 
psk_use_session_cb(SSL * s,const EVP_MD * md,const unsigned char ** id,size_t * idlen,SSL_SESSION ** sess)203 static int psk_use_session_cb(SSL *s, const EVP_MD *md,
204                               const unsigned char **id, size_t *idlen,
205                               SSL_SESSION **sess)
206 {
207     SSL_SESSION *usesess = NULL;
208     const SSL_CIPHER *cipher = NULL;
209 
210     if (psksess != NULL) {
211         SSL_SESSION_up_ref(psksess);
212         usesess = psksess;
213     } else {
214         long key_len;
215         unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
216 
217         if (key == NULL) {
218             BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
219                        psk_key);
220             return 0;
221         }
222 
223         /* We default to SHA-256 */
224         cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
225         if (cipher == NULL) {
226             BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
227             OPENSSL_free(key);
228             return 0;
229         }
230 
231         usesess = SSL_SESSION_new();
232         if (usesess == NULL
233                 || !SSL_SESSION_set1_master_key(usesess, key, key_len)
234                 || !SSL_SESSION_set_cipher(usesess, cipher)
235                 || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
236             OPENSSL_free(key);
237             goto err;
238         }
239         OPENSSL_free(key);
240     }
241 
242     cipher = SSL_SESSION_get0_cipher(usesess);
243     if (cipher == NULL)
244         goto err;
245 
246     if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
247         /* PSK not usable, ignore it */
248         *id = NULL;
249         *idlen = 0;
250         *sess = NULL;
251         SSL_SESSION_free(usesess);
252     } else {
253         *sess = usesess;
254         *id = (unsigned char *)psk_identity;
255         *idlen = strlen(psk_identity);
256     }
257 
258     return 1;
259 
260  err:
261     SSL_SESSION_free(usesess);
262     return 0;
263 }
264 
265 /* This is a context that we pass to callbacks */
266 typedef struct tlsextctx_st {
267     BIO *biodebug;
268     int ack;
269 } tlsextctx;
270 
ssl_servername_cb(SSL * s,int * ad,void * arg)271 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
272 {
273     tlsextctx *p = (tlsextctx *) arg;
274     const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
275     if (SSL_get_servername_type(s) != -1)
276         p->ack = !SSL_session_reused(s) && hn != NULL;
277     else
278         BIO_printf(bio_err, "Can't use SSL_get_servername\n");
279 
280     return SSL_TLSEXT_ERR_OK;
281 }
282 
283 #ifndef OPENSSL_NO_NEXTPROTONEG
284 /* This the context that we pass to next_proto_cb */
285 typedef struct tlsextnextprotoctx_st {
286     unsigned char *data;
287     size_t len;
288     int status;
289 } tlsextnextprotoctx;
290 
291 static tlsextnextprotoctx next_proto;
292 
next_proto_cb(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)293 static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
294                          const unsigned char *in, unsigned int inlen,
295                          void *arg)
296 {
297     tlsextnextprotoctx *ctx = arg;
298 
299     if (!c_quiet) {
300         /* We can assume that |in| is syntactically valid. */
301         unsigned i;
302         BIO_printf(bio_c_out, "Protocols advertised by server: ");
303         for (i = 0; i < inlen;) {
304             if (i)
305                 BIO_write(bio_c_out, ", ", 2);
306             BIO_write(bio_c_out, &in[i + 1], in[i]);
307             i += in[i] + 1;
308         }
309         BIO_write(bio_c_out, "\n", 1);
310     }
311 
312     ctx->status =
313         SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
314     return SSL_TLSEXT_ERR_OK;
315 }
316 #endif                         /* ndef OPENSSL_NO_NEXTPROTONEG */
317 
serverinfo_cli_parse_cb(SSL * s,unsigned int ext_type,const unsigned char * in,size_t inlen,int * al,void * arg)318 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
319                                    const unsigned char *in, size_t inlen,
320                                    int *al, void *arg)
321 {
322     char pem_name[100];
323     unsigned char ext_buf[4 + 65536];
324 
325     /* Reconstruct the type/len fields prior to extension data */
326     inlen &= 0xffff; /* for formal memcmpy correctness */
327     ext_buf[0] = (unsigned char)(ext_type >> 8);
328     ext_buf[1] = (unsigned char)(ext_type);
329     ext_buf[2] = (unsigned char)(inlen >> 8);
330     ext_buf[3] = (unsigned char)(inlen);
331     memcpy(ext_buf + 4, in, inlen);
332 
333     BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
334                  ext_type);
335     PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
336     return 1;
337 }
338 
339 /*
340  * Hex decoder that tolerates optional whitespace.  Returns number of bytes
341  * produced, advances inptr to end of input string.
342  */
hexdecode(const char ** inptr,void * result)343 static ossl_ssize_t hexdecode(const char **inptr, void *result)
344 {
345     unsigned char **out = (unsigned char **)result;
346     const char *in = *inptr;
347     unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
348     unsigned char *cp = ret;
349     uint8_t byte;
350     int nibble = 0;
351 
352     if (ret == NULL)
353         return -1;
354 
355     for (byte = 0; *in; ++in) {
356         int x;
357 
358         if (isspace(_UC(*in)))
359             continue;
360         x = OPENSSL_hexchar2int(*in);
361         if (x < 0) {
362             OPENSSL_free(ret);
363             return 0;
364         }
365         byte |= (char)x;
366         if ((nibble ^= 1) == 0) {
367             *cp++ = byte;
368             byte = 0;
369         } else {
370             byte <<= 4;
371         }
372     }
373     if (nibble != 0) {
374         OPENSSL_free(ret);
375         return 0;
376     }
377     *inptr = in;
378 
379     return cp - (*out = ret);
380 }
381 
382 /*
383  * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
384  * inptr to next field skipping leading whitespace.
385  */
checked_uint8(const char ** inptr,void * out)386 static ossl_ssize_t checked_uint8(const char **inptr, void *out)
387 {
388     uint8_t *result = (uint8_t *)out;
389     const char *in = *inptr;
390     char *endp;
391     long v;
392     int e;
393 
394     save_errno();
395     v = strtol(in, &endp, 10);
396     e = restore_errno();
397 
398     if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
399         endp == in || !isspace(_UC(*endp)) ||
400         v != (*result = (uint8_t) v)) {
401         return -1;
402     }
403     for (in = endp; isspace(_UC(*in)); ++in)
404         continue;
405 
406     *inptr = in;
407     return 1;
408 }
409 
410 struct tlsa_field {
411     void *var;
412     const char *name;
413     ossl_ssize_t (*parser)(const char **, void *);
414 };
415 
tlsa_import_rr(SSL * con,const char * rrdata)416 static int tlsa_import_rr(SSL *con, const char *rrdata)
417 {
418     /* Not necessary to re-init these values; the "parsers" do that. */
419     static uint8_t usage;
420     static uint8_t selector;
421     static uint8_t mtype;
422     static unsigned char *data;
423     static struct tlsa_field tlsa_fields[] = {
424         { &usage, "usage", checked_uint8 },
425         { &selector, "selector", checked_uint8 },
426         { &mtype, "mtype", checked_uint8 },
427         { &data, "data", hexdecode },
428         { NULL, }
429     };
430     struct tlsa_field *f;
431     int ret;
432     const char *cp = rrdata;
433     ossl_ssize_t len = 0;
434 
435     for (f = tlsa_fields; f->var; ++f) {
436         /* Returns number of bytes produced, advances cp to next field */
437         if ((len = f->parser(&cp, f->var)) <= 0) {
438             BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
439                        prog, f->name, rrdata);
440             return 0;
441         }
442     }
443     /* The data field is last, so len is its length */
444     ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
445     OPENSSL_free(data);
446 
447     if (ret == 0) {
448         ERR_print_errors(bio_err);
449         BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
450                    prog, rrdata);
451         return 0;
452     }
453     if (ret < 0) {
454         ERR_print_errors(bio_err);
455         BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
456                    prog, rrdata);
457         return 0;
458     }
459     return ret;
460 }
461 
tlsa_import_rrset(SSL * con,STACK_OF (OPENSSL_STRING)* rrset)462 static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
463 {
464     int num = sk_OPENSSL_STRING_num(rrset);
465     int count = 0;
466     int i;
467 
468     for (i = 0; i < num; ++i) {
469         char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
470         if (tlsa_import_rr(con, rrdata) > 0)
471             ++count;
472     }
473     return count > 0;
474 }
475 
476 typedef enum OPTION_choice {
477     OPT_COMMON,
478     OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX,
479     OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT,
480     OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
481     OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
482     OPT_BRIEF, OPT_PREXIT, OPT_NO_INTERACTIVE, OPT_CRLF, OPT_QUIET, OPT_NBIO,
483     OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF,
484     OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
485     OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
486     OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
487     OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS,
488 #ifndef OPENSSL_NO_SRP
489     OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER,
490     OPT_SRP_MOREGROUPS,
491 #endif
492     OPT_SSL3, OPT_SSL_CONFIG,
493     OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
494     OPT_DTLS1_2, OPT_QUIC, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM,
495     OPT_PASS, OPT_CERT_CHAIN, OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN,
496     OPT_NEXTPROTONEG, OPT_ALPN,
497     OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
498     OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE,
499     OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
500     OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC,
501     OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST,
502     OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES,
503     OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE,
504     OPT_TFO,
505     OPT_V_ENUM,
506     OPT_X_ENUM,
507     OPT_S_ENUM, OPT_IGNORE_UNEXPECTED_EOF,
508     OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_ADV, OPT_PROXY, OPT_PROXY_USER,
509     OPT_PROXY_PASS, OPT_DANE_TLSA_DOMAIN,
510 #ifndef OPENSSL_NO_CT
511     OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
512 #endif
513     OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME,
514     OPT_ENABLE_PHA,
515     OPT_ENABLE_SERVER_RPK,
516     OPT_ENABLE_CLIENT_RPK,
517     OPT_SCTP_LABEL_BUG,
518     OPT_KTLS,
519     OPT_R_ENUM, OPT_PROV_ENUM
520 } OPTION_CHOICE;
521 
522 const OPTIONS s_client_options[] = {
523     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [host:port]\n"},
524 
525     OPT_SECTION("General"),
526     {"help", OPT_HELP, '-', "Display this summary"},
527 #ifndef OPENSSL_NO_ENGINE
528     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
529     {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
530      "Specify engine to be used for client certificate operations"},
531 #endif
532     {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified section for SSL_CTX configuration"},
533 #ifndef OPENSSL_NO_CT
534     {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
535     {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
536     {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
537 #endif
538 
539     OPT_SECTION("Network"),
540     {"host", OPT_HOST, 's', "Use -connect instead"},
541     {"port", OPT_PORT, 'p', "Use -connect instead"},
542     {"connect", OPT_CONNECT, 's',
543      "TCP/IP where to connect; default: " PORT ")"},
544     {"bind", OPT_BIND, 's', "bind local address for connection"},
545     {"proxy", OPT_PROXY, 's',
546      "Connect to via specified proxy to the real server"},
547     {"proxy_user", OPT_PROXY_USER, 's', "UserID for proxy authentication"},
548     {"proxy_pass", OPT_PROXY_PASS, 's', "Proxy authentication password source"},
549 #ifdef AF_UNIX
550     {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"},
551 #endif
552     {"4", OPT_4, '-', "Use IPv4 only"},
553 #ifdef AF_INET6
554     {"6", OPT_6, '-', "Use IPv6 only"},
555 #endif
556     {"maxfraglen", OPT_MAXFRAGLEN, 'p',
557      "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
558     {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
559     {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
560      "Size used to split data for encrypt pipelines"},
561     {"max_pipelines", OPT_MAX_PIPELINES, 'p',
562      "Maximum number of encrypt/decrypt pipelines to be used"},
563     {"read_buf", OPT_READ_BUF, 'p',
564      "Default read buffer size to be used for connections"},
565     {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
566 
567     OPT_SECTION("Identity"),
568     {"cert", OPT_CERT, '<', "Client certificate file to use"},
569     {"certform", OPT_CERTFORM, 'F',
570      "Client certificate file format (PEM/DER/P12); has no effect"},
571     {"cert_chain", OPT_CERT_CHAIN, '<',
572      "Client certificate chain file (in PEM format)"},
573     {"build_chain", OPT_BUILD_CHAIN, '-', "Build client certificate chain"},
574     {"key", OPT_KEY, 's', "Private key file to use; default: -cert file"},
575     {"keyform", OPT_KEYFORM, 'E', "Key format (ENGINE, other values ignored)"},
576     {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
577     {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
578     {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
579     {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
580     {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
581     {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
582     {"no-CAfile", OPT_NOCAFILE, '-',
583      "Do not load the default certificates file"},
584     {"no-CApath", OPT_NOCAPATH, '-',
585      "Do not load certificates from the default certificates directory"},
586     {"no-CAstore", OPT_NOCASTORE, '-',
587      "Do not load certificates from the default certificates store"},
588     {"requestCAfile", OPT_REQCAFILE, '<',
589       "PEM format file of CA names to send to the server"},
590 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
591     {"tfo", OPT_TFO, '-', "Connect using TCP Fast Open"},
592 #endif
593     {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
594     {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
595      "DANE TLSA rrdata presentation form"},
596     {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
597      "Disable name checks when matching DANE-EE(3) TLSA records"},
598     {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
599     {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
600     {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
601     {"name", OPT_PROTOHOST, 's',
602      "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
603 
604     OPT_SECTION("Session"),
605     {"reconnect", OPT_RECONNECT, '-',
606      "Drop and re-make the connection with the same Session-ID"},
607     {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
608     {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
609 
610     OPT_SECTION("Input/Output"),
611     {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
612     {"quiet", OPT_QUIET, '-', "No s_client output"},
613     {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
614     {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
615     {"starttls", OPT_STARTTLS, 's',
616      "Use the appropriate STARTTLS command before starting TLS"},
617     {"xmpphost", OPT_XMPPHOST, 's',
618      "Alias of -name option for \"-starttls xmpp[-server]\""},
619     {"brief", OPT_BRIEF, '-',
620      "Restrict output to brief summary of connection parameters"},
621     {"prexit", OPT_PREXIT, '-',
622      "Print session information when the program exits"},
623     {"no-interactive", OPT_NO_INTERACTIVE, '-',
624      "Don't run the client in the interactive mode"},
625 
626     OPT_SECTION("Debug"),
627     {"showcerts", OPT_SHOWCERTS, '-',
628      "Show all certificates sent by the server"},
629     {"debug", OPT_DEBUG, '-', "Extra output"},
630     {"msg", OPT_MSG, '-', "Show protocol messages"},
631     {"msgfile", OPT_MSGFILE, '>',
632      "File to send output of -msg or -trace, instead of stdout"},
633     {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
634     {"state", OPT_STATE, '-', "Print the ssl states"},
635     {"keymatexport", OPT_KEYMATEXPORT, 's',
636      "Export keying material using label"},
637     {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
638      "Export len bytes of keying material; default 20"},
639     {"security_debug", OPT_SECURITY_DEBUG, '-',
640      "Enable security debug messages"},
641     {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
642      "Output more security debug output"},
643 #ifndef OPENSSL_NO_SSL_TRACE
644     {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
645 #endif
646 #ifdef WATT32
647     {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
648 #endif
649     {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
650     {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
651     {"adv", OPT_ADV, '-', "Advanced command mode"},
652     {"servername", OPT_SERVERNAME, 's',
653      "Set TLS extension servername (SNI) in ClientHello (default)"},
654     {"noservername", OPT_NOSERVERNAME, '-',
655      "Do not send the server name (SNI) extension in the ClientHello"},
656     {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
657      "Hex dump of all TLS extensions received"},
658     {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
659      "Do not treat lack of close_notify from a peer as an error"},
660 #ifndef OPENSSL_NO_OCSP
661     {"status", OPT_STATUS, '-', "Request certificate status from server"},
662 #endif
663     {"serverinfo", OPT_SERVERINFO, 's',
664      "types  Send empty ClientHello extensions (comma-separated numbers)"},
665     {"alpn", OPT_ALPN, 's',
666      "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
667     {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
668     {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
669 
670     OPT_SECTION("Protocol and version"),
671 #ifndef OPENSSL_NO_SSL3
672     {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
673 #endif
674 #ifndef OPENSSL_NO_TLS1
675     {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
676 #endif
677 #ifndef OPENSSL_NO_TLS1_1
678     {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
679 #endif
680 #ifndef OPENSSL_NO_TLS1_2
681     {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
682 #endif
683 #ifndef OPENSSL_NO_TLS1_3
684     {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
685 #endif
686 #ifndef OPENSSL_NO_DTLS
687     {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
688     {"quic", OPT_QUIC, '-', "Use QUIC"},
689     {"timeout", OPT_TIMEOUT, '-',
690      "Enable send/receive timeout on DTLS connections"},
691     {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
692 #endif
693 #ifndef OPENSSL_NO_DTLS1
694     {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
695 #endif
696 #ifndef OPENSSL_NO_DTLS1_2
697     {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
698 #endif
699 #ifndef OPENSSL_NO_SCTP
700     {"sctp", OPT_SCTP, '-', "Use SCTP"},
701     {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
702 #endif
703 #ifndef OPENSSL_NO_NEXTPROTONEG
704     {"nextprotoneg", OPT_NEXTPROTONEG, 's',
705      "Enable NPN extension, considering named protocols supported (comma-separated list)"},
706 #endif
707     {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"},
708     {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"},
709     {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"},
710     {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"},
711 #ifndef OPENSSL_NO_SRTP
712     {"use_srtp", OPT_USE_SRTP, 's',
713      "Offer SRTP key management with a colon-separated profile list"},
714 #endif
715 #ifndef OPENSSL_NO_SRP
716     {"srpuser", OPT_SRPUSER, 's', "(deprecated) SRP authentication for 'user'"},
717     {"srppass", OPT_SRPPASS, 's', "(deprecated) Password for 'user'"},
718     {"srp_lateuser", OPT_SRP_LATEUSER, '-',
719      "(deprecated) SRP username into second ClientHello message"},
720     {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
721      "(deprecated) Tolerate other than the known g N values."},
722     {"srp_strength", OPT_SRP_STRENGTH, 'p',
723      "(deprecated) Minimal length in bits for N"},
724 #endif
725 #ifndef OPENSSL_NO_KTLS
726     {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"},
727 #endif
728 
729     OPT_R_OPTIONS,
730     OPT_S_OPTIONS,
731     OPT_V_OPTIONS,
732     {"CRL", OPT_CRL, '<', "CRL file to use"},
733     {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
734     {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER); default PEM"},
735     {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
736      "Close connection on verification error"},
737     {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
738     {"chainCAfile", OPT_CHAINCAFILE, '<',
739      "CA file for certificate chain (PEM format)"},
740     {"chainCApath", OPT_CHAINCAPATH, '/',
741      "Use dir as certificate store path to build CA certificate chain"},
742     {"chainCAstore", OPT_CHAINCASTORE, ':',
743      "CA store URI for certificate chain"},
744     {"verifyCAfile", OPT_VERIFYCAFILE, '<',
745      "CA file for certificate verification (PEM format)"},
746     {"verifyCApath", OPT_VERIFYCAPATH, '/',
747      "Use dir as certificate store path to verify CA certificate"},
748     {"verifyCAstore", OPT_VERIFYCASTORE, ':',
749      "CA store URI for certificate verification"},
750     OPT_X_OPTIONS,
751     OPT_PROV_OPTIONS,
752 
753     OPT_PARAMETERS(),
754     {"host:port", 0, 0, "Where to connect; same as -connect option"},
755     {NULL}
756 };
757 
758 typedef enum PROTOCOL_choice {
759     PROTO_OFF,
760     PROTO_SMTP,
761     PROTO_POP3,
762     PROTO_IMAP,
763     PROTO_FTP,
764     PROTO_TELNET,
765     PROTO_XMPP,
766     PROTO_XMPP_SERVER,
767     PROTO_IRC,
768     PROTO_MYSQL,
769     PROTO_POSTGRES,
770     PROTO_LMTP,
771     PROTO_NNTP,
772     PROTO_SIEVE,
773     PROTO_LDAP
774 } PROTOCOL_CHOICE;
775 
776 static const OPT_PAIR services[] = {
777     {"smtp", PROTO_SMTP},
778     {"pop3", PROTO_POP3},
779     {"imap", PROTO_IMAP},
780     {"ftp", PROTO_FTP},
781     {"xmpp", PROTO_XMPP},
782     {"xmpp-server", PROTO_XMPP_SERVER},
783     {"telnet", PROTO_TELNET},
784     {"irc", PROTO_IRC},
785     {"mysql", PROTO_MYSQL},
786     {"postgres", PROTO_POSTGRES},
787     {"lmtp", PROTO_LMTP},
788     {"nntp", PROTO_NNTP},
789     {"sieve", PROTO_SIEVE},
790     {"ldap", PROTO_LDAP},
791     {NULL, 0}
792 };
793 
794 #define IS_INET_FLAG(o) \
795  (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
796 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
797 
798 #define IS_PROT_FLAG(o) \
799  (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
800   || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2 \
801   || o == OPT_QUIC)
802 
803 /* Free |*dest| and optionally set it to a copy of |source|. */
freeandcopy(char ** dest,const char * source)804 static void freeandcopy(char **dest, const char *source)
805 {
806     OPENSSL_free(*dest);
807     *dest = NULL;
808     if (source != NULL)
809         *dest = OPENSSL_strdup(source);
810 }
811 
new_session_cb(SSL * s,SSL_SESSION * sess)812 static int new_session_cb(SSL *s, SSL_SESSION *sess)
813 {
814 
815     if (sess_out != NULL) {
816         BIO *stmp = BIO_new_file(sess_out, "w");
817 
818         if (stmp == NULL) {
819             BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
820         } else {
821             PEM_write_bio_SSL_SESSION(stmp, sess);
822             BIO_free(stmp);
823         }
824     }
825 
826     /*
827      * Session data gets dumped on connection for TLSv1.2 and below, and on
828      * arrival of the NewSessionTicket for TLSv1.3.
829      */
830     if (SSL_version(s) == TLS1_3_VERSION) {
831         BIO_printf(bio_c_out,
832                    "---\nPost-Handshake New Session Ticket arrived:\n");
833         SSL_SESSION_print(bio_c_out, sess);
834         BIO_printf(bio_c_out, "---\n");
835     }
836 
837     /*
838      * We always return a "fail" response so that the session gets freed again
839      * because we haven't used the reference.
840      */
841     return 0;
842 }
843 
s_client_main(int argc,char ** argv)844 int s_client_main(int argc, char **argv)
845 {
846     BIO *sbio;
847     EVP_PKEY *key = NULL;
848     SSL *con = NULL;
849     SSL_CTX *ctx = NULL;
850     STACK_OF(X509) *chain = NULL;
851     X509 *cert = NULL;
852     X509_VERIFY_PARAM *vpm = NULL;
853     SSL_EXCERT *exc = NULL;
854     SSL_CONF_CTX *cctx = NULL;
855     STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
856     char *dane_tlsa_domain = NULL;
857     STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
858     int dane_ee_no_name = 0;
859     STACK_OF(X509_CRL) *crls = NULL;
860     const SSL_METHOD *meth = TLS_client_method();
861     const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
862     char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
863     char *proxystr = NULL, *proxyuser = NULL;
864     char *proxypassarg = NULL, *proxypass = NULL;
865     char *connectstr = NULL, *bindstr = NULL;
866     char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
867     char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL, *host = NULL;
868     char *thost = NULL, *tport = NULL;
869     char *port = NULL;
870     char *bindhost = NULL, *bindport = NULL;
871     char *passarg = NULL, *pass = NULL;
872     char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
873     char *ReqCAfile = NULL;
874     char *sess_in = NULL, *crl_file = NULL, *p;
875     const char *protohost = NULL;
876     struct timeval timeout, *timeoutp;
877     fd_set readfds, writefds;
878     int noCApath = 0, noCAfile = 0, noCAstore = 0;
879     int build_chain = 0, cert_format = FORMAT_UNDEF;
880     size_t cbuf_len, cbuf_off;
881     int key_format = FORMAT_UNDEF, crlf = 0, full_log = 1, mbuf_len = 0;
882     int prexit = 0;
883     int nointeractive = 0;
884     int sdebug = 0;
885     int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
886     int ret = 1, in_init = 1, i, nbio_test = 0, sock = -1, k, width, state = 0;
887     int sbuf_len, sbuf_off, cmdmode = USER_DATA_MODE_BASIC;
888     int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
889     int starttls_proto = PROTO_OFF, crl_format = FORMAT_UNDEF, crl_download = 0;
890     int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
891     int first_loop;
892 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
893     int at_eof = 0;
894 #endif
895     int read_buf_len = 0;
896     int fallback_scsv = 0;
897     OPTION_CHOICE o;
898 #ifndef OPENSSL_NO_DTLS
899     int enable_timeouts = 0;
900     long socket_mtu = 0;
901 #endif
902 #ifndef OPENSSL_NO_ENGINE
903     ENGINE *ssl_client_engine = NULL;
904 #endif
905     ENGINE *e = NULL;
906 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
907     struct timeval tv;
908 #endif
909     const char *servername = NULL;
910     char *sname_alloc = NULL;
911     int noservername = 0;
912     const char *alpn_in = NULL;
913     tlsextctx tlsextcbp = { NULL, 0 };
914     const char *ssl_config = NULL;
915 #define MAX_SI_TYPES 100
916     unsigned short serverinfo_types[MAX_SI_TYPES];
917     int serverinfo_count = 0, start = 0, len;
918 #ifndef OPENSSL_NO_NEXTPROTONEG
919     const char *next_proto_neg_in = NULL;
920 #endif
921 #ifndef OPENSSL_NO_SRP
922     char *srppass = NULL;
923     int srp_lateuser = 0;
924     SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
925 #endif
926 #ifndef OPENSSL_NO_SRTP
927     char *srtp_profiles = NULL;
928 #endif
929 #ifndef OPENSSL_NO_CT
930     char *ctlog_file = NULL;
931     int ct_validation = 0;
932 #endif
933     int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
934     int async = 0;
935     unsigned int max_send_fragment = 0;
936     unsigned int split_send_fragment = 0, max_pipelines = 0;
937     enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
938     int count4or6 = 0;
939     uint8_t maxfraglen = 0;
940     int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
941     int c_tlsextdebug = 0;
942 #ifndef OPENSSL_NO_OCSP
943     int c_status_req = 0;
944 #endif
945     BIO *bio_c_msg = NULL;
946     const char *keylog_file = NULL, *early_data_file = NULL;
947     int isdtls = 0, isquic = 0;
948     char *psksessf = NULL;
949     int enable_pha = 0;
950     int enable_client_rpk = 0;
951 #ifndef OPENSSL_NO_SCTP
952     int sctp_label_bug = 0;
953 #endif
954     int ignore_unexpected_eof = 0;
955 #ifndef OPENSSL_NO_KTLS
956     int enable_ktls = 0;
957 #endif
958     int tfo = 0;
959     int is_infinite;
960     BIO_ADDR *peer_addr = NULL;
961     struct user_data_st user_data;
962 
963     FD_ZERO(&readfds);
964     FD_ZERO(&writefds);
965 /* Known false-positive of MemorySanitizer. */
966 #if defined(__has_feature)
967 # if __has_feature(memory_sanitizer)
968     __msan_unpoison(&readfds, sizeof(readfds));
969     __msan_unpoison(&writefds, sizeof(writefds));
970 # endif
971 #endif
972 
973     c_quiet = 0;
974     c_debug = 0;
975     c_showcerts = 0;
976     c_nbio = 0;
977     port = OPENSSL_strdup(PORT);
978     vpm = X509_VERIFY_PARAM_new();
979     cctx = SSL_CONF_CTX_new();
980 
981     if (port == NULL || vpm == NULL || cctx == NULL) {
982         BIO_printf(bio_err, "%s: out of memory\n", opt_getprog());
983         goto end;
984     }
985 
986     cbuf = app_malloc(BUFSIZZ, "cbuf");
987     sbuf = app_malloc(BUFSIZZ, "sbuf");
988     mbuf = app_malloc(BUFSIZZ, "mbuf");
989 
990     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
991 
992     prog = opt_init(argc, argv, s_client_options);
993     while ((o = opt_next()) != OPT_EOF) {
994         /* Check for intermixing flags. */
995         if (connect_type == use_unix && IS_INET_FLAG(o)) {
996             BIO_printf(bio_err,
997                        "%s: Intermixed protocol flags (unix and internet domains)\n",
998                        prog);
999             goto end;
1000         }
1001         if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
1002             BIO_printf(bio_err,
1003                        "%s: Intermixed protocol flags (internet and unix domains)\n",
1004                        prog);
1005             goto end;
1006         }
1007 
1008         if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1009             BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1010             goto end;
1011         }
1012         if (IS_NO_PROT_FLAG(o))
1013             no_prot_opt++;
1014         if (prot_opt == 1 && no_prot_opt) {
1015             BIO_printf(bio_err,
1016                        "Cannot supply both a protocol flag and '-no_<prot>'\n");
1017             goto end;
1018         }
1019 
1020         switch (o) {
1021         case OPT_EOF:
1022         case OPT_ERR:
1023  opthelp:
1024             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1025             goto end;
1026         case OPT_HELP:
1027             opt_help(s_client_options);
1028             ret = 0;
1029             goto end;
1030         case OPT_4:
1031             connect_type = use_inet;
1032             socket_family = AF_INET;
1033             count4or6++;
1034             break;
1035 #ifdef AF_INET6
1036         case OPT_6:
1037             connect_type = use_inet;
1038             socket_family = AF_INET6;
1039             count4or6++;
1040             break;
1041 #endif
1042         case OPT_HOST:
1043             connect_type = use_inet;
1044             freeandcopy(&host, opt_arg());
1045             break;
1046         case OPT_PORT:
1047             connect_type = use_inet;
1048             freeandcopy(&port, opt_arg());
1049             break;
1050         case OPT_CONNECT:
1051             connect_type = use_inet;
1052             freeandcopy(&connectstr, opt_arg());
1053             break;
1054         case OPT_BIND:
1055             freeandcopy(&bindstr, opt_arg());
1056             break;
1057         case OPT_PROXY:
1058             proxystr = opt_arg();
1059             break;
1060         case OPT_PROXY_USER:
1061             proxyuser = opt_arg();
1062             break;
1063         case OPT_PROXY_PASS:
1064             proxypassarg = opt_arg();
1065             break;
1066 #ifdef AF_UNIX
1067         case OPT_UNIX:
1068             connect_type = use_unix;
1069             socket_family = AF_UNIX;
1070             freeandcopy(&host, opt_arg());
1071             break;
1072 #endif
1073         case OPT_XMPPHOST:
1074             /* fall through, since this is an alias */
1075         case OPT_PROTOHOST:
1076             protohost = opt_arg();
1077             break;
1078         case OPT_VERIFY:
1079             verify = SSL_VERIFY_PEER;
1080             verify_args.depth = atoi(opt_arg());
1081             if (!c_quiet)
1082                 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1083             break;
1084         case OPT_CERT:
1085             cert_file = opt_arg();
1086             break;
1087         case OPT_NAMEOPT:
1088             if (!set_nameopt(opt_arg()))
1089                 goto end;
1090             break;
1091         case OPT_CRL:
1092             crl_file = opt_arg();
1093             break;
1094         case OPT_CRL_DOWNLOAD:
1095             crl_download = 1;
1096             break;
1097         case OPT_SESS_OUT:
1098             sess_out = opt_arg();
1099             break;
1100         case OPT_SESS_IN:
1101             sess_in = opt_arg();
1102             break;
1103         case OPT_CERTFORM:
1104             if (!opt_format(opt_arg(), OPT_FMT_ANY, &cert_format))
1105                 goto opthelp;
1106             break;
1107         case OPT_CRLFORM:
1108             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1109                 goto opthelp;
1110             break;
1111         case OPT_VERIFY_RET_ERROR:
1112             verify = SSL_VERIFY_PEER;
1113             verify_args.return_error = 1;
1114             break;
1115         case OPT_VERIFY_QUIET:
1116             verify_args.quiet = 1;
1117             break;
1118         case OPT_BRIEF:
1119             c_brief = verify_args.quiet = c_quiet = 1;
1120             break;
1121         case OPT_S_CASES:
1122             if (ssl_args == NULL)
1123                 ssl_args = sk_OPENSSL_STRING_new_null();
1124             if (ssl_args == NULL
1125                 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1126                 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1127                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1128                 goto end;
1129             }
1130             break;
1131         case OPT_V_CASES:
1132             if (!opt_verify(o, vpm))
1133                 goto end;
1134             vpmtouched++;
1135             break;
1136         case OPT_X_CASES:
1137             if (!args_excert(o, &exc))
1138                 goto end;
1139             break;
1140         case OPT_IGNORE_UNEXPECTED_EOF:
1141             ignore_unexpected_eof = 1;
1142             break;
1143         case OPT_PREXIT:
1144             prexit = 1;
1145             break;
1146         case OPT_NO_INTERACTIVE:
1147             nointeractive = 1;
1148             break;
1149         case OPT_CRLF:
1150             crlf = 1;
1151             break;
1152         case OPT_QUIET:
1153             c_quiet = c_ign_eof = 1;
1154             break;
1155         case OPT_NBIO:
1156             c_nbio = 1;
1157             break;
1158         case OPT_NOCMDS:
1159             cmdmode = USER_DATA_MODE_NONE;
1160             break;
1161         case OPT_ADV:
1162             cmdmode = USER_DATA_MODE_ADVANCED;
1163             break;
1164         case OPT_ENGINE:
1165             e = setup_engine(opt_arg(), 1);
1166             break;
1167         case OPT_SSL_CLIENT_ENGINE:
1168 #ifndef OPENSSL_NO_ENGINE
1169             ssl_client_engine = setup_engine(opt_arg(), 0);
1170             if (ssl_client_engine == NULL) {
1171                 BIO_printf(bio_err, "Error getting client auth engine\n");
1172                 goto opthelp;
1173             }
1174 #endif
1175             break;
1176         case OPT_R_CASES:
1177             if (!opt_rand(o))
1178                 goto end;
1179             break;
1180         case OPT_PROV_CASES:
1181             if (!opt_provider(o))
1182                 goto end;
1183             break;
1184         case OPT_IGN_EOF:
1185             c_ign_eof = 1;
1186             break;
1187         case OPT_NO_IGN_EOF:
1188             c_ign_eof = 0;
1189             break;
1190         case OPT_DEBUG:
1191             c_debug = 1;
1192             break;
1193         case OPT_TLSEXTDEBUG:
1194             c_tlsextdebug = 1;
1195             break;
1196         case OPT_STATUS:
1197 #ifndef OPENSSL_NO_OCSP
1198             c_status_req = 1;
1199 #endif
1200             break;
1201         case OPT_WDEBUG:
1202 #ifdef WATT32
1203             dbug_init();
1204 #endif
1205             break;
1206         case OPT_MSG:
1207             c_msg = 1;
1208             break;
1209         case OPT_MSGFILE:
1210             bio_c_msg = BIO_new_file(opt_arg(), "w");
1211             if (bio_c_msg == NULL) {
1212                 BIO_printf(bio_err, "Error writing file %s\n", opt_arg());
1213                 goto end;
1214             }
1215             break;
1216         case OPT_TRACE:
1217 #ifndef OPENSSL_NO_SSL_TRACE
1218             c_msg = 2;
1219 #endif
1220             break;
1221         case OPT_SECURITY_DEBUG:
1222             sdebug = 1;
1223             break;
1224         case OPT_SECURITY_DEBUG_VERBOSE:
1225             sdebug = 2;
1226             break;
1227         case OPT_SHOWCERTS:
1228             c_showcerts = 1;
1229             break;
1230         case OPT_NBIO_TEST:
1231             nbio_test = 1;
1232             break;
1233         case OPT_STATE:
1234             state = 1;
1235             break;
1236         case OPT_PSK_IDENTITY:
1237             psk_identity = opt_arg();
1238             break;
1239         case OPT_PSK:
1240             for (p = psk_key = opt_arg(); *p; p++) {
1241                 if (isxdigit(_UC(*p)))
1242                     continue;
1243                 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1244                 goto end;
1245             }
1246             break;
1247         case OPT_PSK_SESS:
1248             psksessf = opt_arg();
1249             break;
1250 #ifndef OPENSSL_NO_SRP
1251         case OPT_SRPUSER:
1252             srp_arg.srplogin = opt_arg();
1253             if (min_version < TLS1_VERSION)
1254                 min_version = TLS1_VERSION;
1255             break;
1256         case OPT_SRPPASS:
1257             srppass = opt_arg();
1258             if (min_version < TLS1_VERSION)
1259                 min_version = TLS1_VERSION;
1260             break;
1261         case OPT_SRP_STRENGTH:
1262             srp_arg.strength = atoi(opt_arg());
1263             BIO_printf(bio_err, "SRP minimal length for N is %d\n",
1264                        srp_arg.strength);
1265             if (min_version < TLS1_VERSION)
1266                 min_version = TLS1_VERSION;
1267             break;
1268         case OPT_SRP_LATEUSER:
1269             srp_lateuser = 1;
1270             if (min_version < TLS1_VERSION)
1271                 min_version = TLS1_VERSION;
1272             break;
1273         case OPT_SRP_MOREGROUPS:
1274             srp_arg.amp = 1;
1275             if (min_version < TLS1_VERSION)
1276                 min_version = TLS1_VERSION;
1277             break;
1278 #endif
1279         case OPT_SSL_CONFIG:
1280             ssl_config = opt_arg();
1281             break;
1282         case OPT_SSL3:
1283             min_version = SSL3_VERSION;
1284             max_version = SSL3_VERSION;
1285             socket_type = SOCK_STREAM;
1286 #ifndef OPENSSL_NO_DTLS
1287             isdtls = 0;
1288 #endif
1289             isquic = 0;
1290             break;
1291         case OPT_TLS1_3:
1292             min_version = TLS1_3_VERSION;
1293             max_version = TLS1_3_VERSION;
1294             socket_type = SOCK_STREAM;
1295 #ifndef OPENSSL_NO_DTLS
1296             isdtls = 0;
1297 #endif
1298             isquic = 0;
1299             break;
1300         case OPT_TLS1_2:
1301             min_version = TLS1_2_VERSION;
1302             max_version = TLS1_2_VERSION;
1303             socket_type = SOCK_STREAM;
1304 #ifndef OPENSSL_NO_DTLS
1305             isdtls = 0;
1306 #endif
1307             isquic = 0;
1308             break;
1309         case OPT_TLS1_1:
1310             min_version = TLS1_1_VERSION;
1311             max_version = TLS1_1_VERSION;
1312             socket_type = SOCK_STREAM;
1313 #ifndef OPENSSL_NO_DTLS
1314             isdtls = 0;
1315 #endif
1316             isquic = 0;
1317             break;
1318         case OPT_TLS1:
1319             min_version = TLS1_VERSION;
1320             max_version = TLS1_VERSION;
1321             socket_type = SOCK_STREAM;
1322 #ifndef OPENSSL_NO_DTLS
1323             isdtls = 0;
1324 #endif
1325             isquic = 0;
1326             break;
1327         case OPT_DTLS:
1328 #ifndef OPENSSL_NO_DTLS
1329             meth = DTLS_client_method();
1330             socket_type = SOCK_DGRAM;
1331             isdtls = 1;
1332             isquic = 0;
1333 #endif
1334             break;
1335         case OPT_DTLS1:
1336 #ifndef OPENSSL_NO_DTLS1
1337             meth = DTLS_client_method();
1338             min_version = DTLS1_VERSION;
1339             max_version = DTLS1_VERSION;
1340             socket_type = SOCK_DGRAM;
1341             isdtls = 1;
1342             isquic = 0;
1343 #endif
1344             break;
1345         case OPT_DTLS1_2:
1346 #ifndef OPENSSL_NO_DTLS1_2
1347             meth = DTLS_client_method();
1348             min_version = DTLS1_2_VERSION;
1349             max_version = DTLS1_2_VERSION;
1350             socket_type = SOCK_DGRAM;
1351             isdtls = 1;
1352             isquic = 0;
1353 #endif
1354             break;
1355         case OPT_QUIC:
1356 #ifndef OPENSSL_NO_QUIC
1357             meth = OSSL_QUIC_client_method();
1358             min_version = 0;
1359             max_version = 0;
1360             socket_type = SOCK_DGRAM;
1361 # ifndef OPENSSL_NO_DTLS
1362             isdtls = 0;
1363 # endif
1364             isquic = 1;
1365 #endif
1366             break;
1367         case OPT_SCTP:
1368 #ifndef OPENSSL_NO_SCTP
1369             protocol = IPPROTO_SCTP;
1370 #endif
1371             break;
1372         case OPT_SCTP_LABEL_BUG:
1373 #ifndef OPENSSL_NO_SCTP
1374             sctp_label_bug = 1;
1375 #endif
1376             break;
1377         case OPT_TIMEOUT:
1378 #ifndef OPENSSL_NO_DTLS
1379             enable_timeouts = 1;
1380 #endif
1381             break;
1382         case OPT_MTU:
1383 #ifndef OPENSSL_NO_DTLS
1384             socket_mtu = atol(opt_arg());
1385 #endif
1386             break;
1387         case OPT_FALLBACKSCSV:
1388             fallback_scsv = 1;
1389             break;
1390         case OPT_KEYFORM:
1391             if (!opt_format(opt_arg(), OPT_FMT_ANY, &key_format))
1392                 goto opthelp;
1393             break;
1394         case OPT_PASS:
1395             passarg = opt_arg();
1396             break;
1397         case OPT_CERT_CHAIN:
1398             chain_file = opt_arg();
1399             break;
1400         case OPT_KEY:
1401             key_file = opt_arg();
1402             break;
1403         case OPT_RECONNECT:
1404             reconnect = 5;
1405             break;
1406         case OPT_CAPATH:
1407             CApath = opt_arg();
1408             break;
1409         case OPT_NOCAPATH:
1410             noCApath = 1;
1411             break;
1412         case OPT_CHAINCAPATH:
1413             chCApath = opt_arg();
1414             break;
1415         case OPT_VERIFYCAPATH:
1416             vfyCApath = opt_arg();
1417             break;
1418         case OPT_BUILD_CHAIN:
1419             build_chain = 1;
1420             break;
1421         case OPT_REQCAFILE:
1422             ReqCAfile = opt_arg();
1423             break;
1424         case OPT_CAFILE:
1425             CAfile = opt_arg();
1426             break;
1427         case OPT_NOCAFILE:
1428             noCAfile = 1;
1429             break;
1430 #ifndef OPENSSL_NO_CT
1431         case OPT_NOCT:
1432             ct_validation = 0;
1433             break;
1434         case OPT_CT:
1435             ct_validation = 1;
1436             break;
1437         case OPT_CTLOG_FILE:
1438             ctlog_file = opt_arg();
1439             break;
1440 #endif
1441         case OPT_CHAINCAFILE:
1442             chCAfile = opt_arg();
1443             break;
1444         case OPT_VERIFYCAFILE:
1445             vfyCAfile = opt_arg();
1446             break;
1447         case OPT_CASTORE:
1448             CAstore = opt_arg();
1449             break;
1450         case OPT_NOCASTORE:
1451             noCAstore = 1;
1452             break;
1453         case OPT_CHAINCASTORE:
1454             chCAstore = opt_arg();
1455             break;
1456         case OPT_VERIFYCASTORE:
1457             vfyCAstore = opt_arg();
1458             break;
1459         case OPT_DANE_TLSA_DOMAIN:
1460             dane_tlsa_domain = opt_arg();
1461             break;
1462         case OPT_DANE_TLSA_RRDATA:
1463             if (dane_tlsa_rrset == NULL)
1464                 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1465             if (dane_tlsa_rrset == NULL ||
1466                 !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1467                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1468                 goto end;
1469             }
1470             break;
1471         case OPT_DANE_EE_NO_NAME:
1472             dane_ee_no_name = 1;
1473             break;
1474         case OPT_NEXTPROTONEG:
1475 #ifndef OPENSSL_NO_NEXTPROTONEG
1476             next_proto_neg_in = opt_arg();
1477 #endif
1478             break;
1479         case OPT_ALPN:
1480             alpn_in = opt_arg();
1481             break;
1482         case OPT_SERVERINFO:
1483             p = opt_arg();
1484             len = strlen(p);
1485             for (start = 0, i = 0; i <= len; ++i) {
1486                 if (i == len || p[i] == ',') {
1487                     serverinfo_types[serverinfo_count] = atoi(p + start);
1488                     if (++serverinfo_count == MAX_SI_TYPES)
1489                         break;
1490                     start = i + 1;
1491                 }
1492             }
1493             break;
1494         case OPT_STARTTLS:
1495             if (!opt_pair(opt_arg(), services, &starttls_proto))
1496                 goto end;
1497             break;
1498         case OPT_TFO:
1499             tfo = 1;
1500             break;
1501         case OPT_SERVERNAME:
1502             servername = opt_arg();
1503             break;
1504         case OPT_NOSERVERNAME:
1505             noservername = 1;
1506             break;
1507         case OPT_USE_SRTP:
1508 #ifndef OPENSSL_NO_SRTP
1509             srtp_profiles = opt_arg();
1510 #endif
1511             break;
1512         case OPT_KEYMATEXPORT:
1513             keymatexportlabel = opt_arg();
1514             break;
1515         case OPT_KEYMATEXPORTLEN:
1516             keymatexportlen = atoi(opt_arg());
1517             break;
1518         case OPT_ASYNC:
1519             async = 1;
1520             break;
1521         case OPT_MAXFRAGLEN:
1522             len = atoi(opt_arg());
1523             switch (len) {
1524             case 512:
1525                 maxfraglen = TLSEXT_max_fragment_length_512;
1526                 break;
1527             case 1024:
1528                 maxfraglen = TLSEXT_max_fragment_length_1024;
1529                 break;
1530             case 2048:
1531                 maxfraglen = TLSEXT_max_fragment_length_2048;
1532                 break;
1533             case 4096:
1534                 maxfraglen = TLSEXT_max_fragment_length_4096;
1535                 break;
1536             default:
1537                 BIO_printf(bio_err,
1538                            "%s: Max Fragment Len %u is out of permitted values",
1539                            prog, len);
1540                 goto opthelp;
1541             }
1542             break;
1543         case OPT_MAX_SEND_FRAG:
1544             max_send_fragment = atoi(opt_arg());
1545             break;
1546         case OPT_SPLIT_SEND_FRAG:
1547             split_send_fragment = atoi(opt_arg());
1548             break;
1549         case OPT_MAX_PIPELINES:
1550             max_pipelines = atoi(opt_arg());
1551             break;
1552         case OPT_READ_BUF:
1553             read_buf_len = atoi(opt_arg());
1554             break;
1555         case OPT_KEYLOG_FILE:
1556             keylog_file = opt_arg();
1557             break;
1558         case OPT_EARLY_DATA:
1559             early_data_file = opt_arg();
1560             break;
1561         case OPT_ENABLE_PHA:
1562             enable_pha = 1;
1563             break;
1564         case OPT_KTLS:
1565 #ifndef OPENSSL_NO_KTLS
1566             enable_ktls = 1;
1567 #endif
1568             break;
1569         case OPT_ENABLE_SERVER_RPK:
1570             enable_server_rpk = 1;
1571             break;
1572         case OPT_ENABLE_CLIENT_RPK:
1573             enable_client_rpk = 1;
1574             break;
1575         }
1576     }
1577 
1578     /* Optional argument is connect string if -connect not used. */
1579     if (opt_num_rest() == 1) {
1580         /* Don't allow -connect and a separate argument. */
1581         if (connectstr != NULL) {
1582             BIO_printf(bio_err,
1583                        "%s: cannot provide both -connect option and target parameter\n",
1584                        prog);
1585             goto opthelp;
1586         }
1587         connect_type = use_inet;
1588         freeandcopy(&connectstr, *opt_rest());
1589     } else if (!opt_check_rest_arg(NULL)) {
1590         goto opthelp;
1591     }
1592     if (!app_RAND_load())
1593         goto end;
1594 
1595     if (c_ign_eof)
1596         cmdmode = USER_DATA_MODE_NONE;
1597 
1598     if (count4or6 >= 2) {
1599         BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1600         goto opthelp;
1601     }
1602     if (noservername) {
1603         if (servername != NULL) {
1604             BIO_printf(bio_err,
1605                        "%s: Can't use -servername and -noservername together\n",
1606                        prog);
1607             goto opthelp;
1608         }
1609         if (dane_tlsa_domain != NULL) {
1610             BIO_printf(bio_err,
1611                "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1612                prog);
1613             goto opthelp;
1614         }
1615     }
1616 
1617 #ifndef OPENSSL_NO_NEXTPROTONEG
1618     if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1619         BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1620         goto opthelp;
1621     }
1622 #endif
1623 
1624     if (connectstr != NULL) {
1625         int res;
1626         char *tmp_host = host, *tmp_port = port;
1627 
1628         res = BIO_parse_hostserv(connectstr, &host, &port, BIO_PARSE_PRIO_HOST);
1629         if (tmp_host != host)
1630             OPENSSL_free(tmp_host);
1631         if (tmp_port != port)
1632             OPENSSL_free(tmp_port);
1633         if (!res) {
1634             BIO_printf(bio_err,
1635                        "%s: -connect argument or target parameter malformed or ambiguous\n",
1636                        prog);
1637             goto end;
1638         }
1639     }
1640 
1641     if (proxystr != NULL) {
1642 #ifndef OPENSSL_NO_HTTP
1643         int res;
1644         char *tmp_host = host, *tmp_port = port;
1645 
1646         if (host == NULL || port == NULL) {
1647             BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
1648             goto opthelp;
1649         }
1650 
1651         if (servername == NULL && !noservername) {
1652             servername = sname_alloc = OPENSSL_strdup(host);
1653             if (sname_alloc == NULL) {
1654                 BIO_printf(bio_err, "%s: out of memory\n", prog);
1655                 goto end;
1656             }
1657         }
1658 
1659         /* Retain the original target host:port for use in the HTTP proxy connect string */
1660         thost = OPENSSL_strdup(host);
1661         tport = OPENSSL_strdup(port);
1662         if (thost == NULL || tport == NULL) {
1663             BIO_printf(bio_err, "%s: out of memory\n", prog);
1664             goto end;
1665         }
1666 
1667         res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1668         if (tmp_host != host)
1669             OPENSSL_free(tmp_host);
1670         if (tmp_port != port)
1671             OPENSSL_free(tmp_port);
1672         if (!res) {
1673             BIO_printf(bio_err,
1674                        "%s: -proxy argument malformed or ambiguous\n", prog);
1675             goto end;
1676         }
1677 #else
1678         BIO_printf(bio_err,
1679                    "%s: -proxy not supported in no-http build\n", prog);
1680 	goto end;
1681 #endif
1682     }
1683 
1684 
1685     if (bindstr != NULL) {
1686         int res;
1687         res = BIO_parse_hostserv(bindstr, &bindhost, &bindport,
1688                                  BIO_PARSE_PRIO_HOST);
1689         if (!res) {
1690             BIO_printf(bio_err,
1691                        "%s: -bind argument parameter malformed or ambiguous\n",
1692                        prog);
1693             goto end;
1694         }
1695     }
1696 
1697 #ifdef AF_UNIX
1698     if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1699         BIO_printf(bio_err,
1700                    "Can't use unix sockets and datagrams together\n");
1701         goto end;
1702     }
1703 #endif
1704 
1705 #ifndef OPENSSL_NO_SCTP
1706     if (protocol == IPPROTO_SCTP) {
1707         if (socket_type != SOCK_DGRAM) {
1708             BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1709             goto end;
1710         }
1711         /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1712         socket_type = SOCK_STREAM;
1713     }
1714 #endif
1715 
1716 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1717     next_proto.status = -1;
1718     if (next_proto_neg_in) {
1719         next_proto.data =
1720             next_protos_parse(&next_proto.len, next_proto_neg_in);
1721         if (next_proto.data == NULL) {
1722             BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1723             goto end;
1724         }
1725     } else
1726         next_proto.data = NULL;
1727 #endif
1728 
1729     if (!app_passwd(passarg, NULL, &pass, NULL)) {
1730         BIO_printf(bio_err, "Error getting private key password\n");
1731         goto end;
1732     }
1733 
1734     if (!app_passwd(proxypassarg, NULL, &proxypass, NULL)) {
1735         BIO_printf(bio_err, "Error getting proxy password\n");
1736         goto end;
1737     }
1738 
1739     if (proxypass != NULL && proxyuser == NULL) {
1740         BIO_printf(bio_err, "Error: Must specify proxy_user with proxy_pass\n");
1741         goto end;
1742     }
1743 
1744     if (key_file == NULL)
1745         key_file = cert_file;
1746 
1747     if (key_file != NULL) {
1748         key = load_key(key_file, key_format, 0, pass, e,
1749                        "client certificate private key");
1750         if (key == NULL)
1751             goto end;
1752     }
1753 
1754     if (cert_file != NULL) {
1755         cert = load_cert_pass(cert_file, cert_format, 1, pass,
1756                               "client certificate");
1757         if (cert == NULL)
1758             goto end;
1759     }
1760 
1761     if (chain_file != NULL) {
1762         if (!load_certs(chain_file, 0, &chain, pass, "client certificate chain"))
1763             goto end;
1764     }
1765 
1766     if (crl_file != NULL) {
1767         X509_CRL *crl;
1768         crl = load_crl(crl_file, crl_format, 0, "CRL");
1769         if (crl == NULL)
1770             goto end;
1771         crls = sk_X509_CRL_new_null();
1772         if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1773             BIO_puts(bio_err, "Error adding CRL\n");
1774             ERR_print_errors(bio_err);
1775             X509_CRL_free(crl);
1776             goto end;
1777         }
1778     }
1779 
1780     if (!load_excert(&exc))
1781         goto end;
1782 
1783     if (bio_c_out == NULL) {
1784         if (c_quiet && !c_debug) {
1785             bio_c_out = BIO_new(BIO_s_null());
1786             if (c_msg && bio_c_msg == NULL) {
1787                 bio_c_msg = dup_bio_out(FORMAT_TEXT);
1788                 if (bio_c_msg == NULL) {
1789                     BIO_printf(bio_err, "Out of memory\n");
1790                     goto end;
1791                 }
1792             }
1793         } else {
1794             bio_c_out = dup_bio_out(FORMAT_TEXT);
1795         }
1796 
1797         if (bio_c_out == NULL) {
1798             BIO_printf(bio_err, "Unable to create BIO\n");
1799             goto end;
1800         }
1801     }
1802 #ifndef OPENSSL_NO_SRP
1803     if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1804         BIO_printf(bio_err, "Error getting password\n");
1805         goto end;
1806     }
1807 #endif
1808 
1809     ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1810     if (ctx == NULL) {
1811         ERR_print_errors(bio_err);
1812         goto end;
1813     }
1814 
1815     SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1816 
1817     if (sdebug)
1818         ssl_ctx_security_debug(ctx, sdebug);
1819 
1820     if (!config_ctx(cctx, ssl_args, ctx))
1821         goto end;
1822 
1823     if (ssl_config != NULL) {
1824         if (SSL_CTX_config(ctx, ssl_config) == 0) {
1825             BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1826                        ssl_config);
1827             ERR_print_errors(bio_err);
1828             goto end;
1829         }
1830     }
1831 
1832 #ifndef OPENSSL_NO_SCTP
1833     if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1834         SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1835 #endif
1836 
1837     if (min_version != 0
1838         && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1839         goto end;
1840     if (max_version != 0
1841         && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1842         goto end;
1843 
1844     if (ignore_unexpected_eof)
1845         SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1846 #ifndef OPENSSL_NO_KTLS
1847     if (enable_ktls)
1848         SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
1849 #endif
1850 
1851     if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1852         BIO_printf(bio_err, "Error setting verify params\n");
1853         ERR_print_errors(bio_err);
1854         goto end;
1855     }
1856 
1857     if (async) {
1858         SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1859     }
1860 
1861     if (max_send_fragment > 0
1862         && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1863         BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1864                    prog, max_send_fragment);
1865         goto end;
1866     }
1867 
1868     if (split_send_fragment > 0
1869         && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1870         BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1871                    prog, split_send_fragment);
1872         goto end;
1873     }
1874 
1875     if (max_pipelines > 0
1876         && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1877         BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1878                    prog, max_pipelines);
1879         goto end;
1880     }
1881 
1882     if (read_buf_len > 0) {
1883         SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1884     }
1885 
1886     if (maxfraglen > 0
1887             && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
1888         BIO_printf(bio_err,
1889                    "%s: Max Fragment Length code %u is out of permitted values"
1890                    "\n", prog, maxfraglen);
1891         goto end;
1892     }
1893 
1894     if (!ssl_load_stores(ctx,
1895                          vfyCApath, vfyCAfile, vfyCAstore,
1896                          chCApath, chCAfile, chCAstore,
1897                          crls, crl_download)) {
1898         BIO_printf(bio_err, "Error loading store locations\n");
1899         ERR_print_errors(bio_err);
1900         goto end;
1901     }
1902     if (ReqCAfile != NULL) {
1903         STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
1904 
1905         if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
1906             sk_X509_NAME_pop_free(nm, X509_NAME_free);
1907             BIO_printf(bio_err, "Error loading CA names\n");
1908             ERR_print_errors(bio_err);
1909             goto end;
1910         }
1911         SSL_CTX_set0_CA_list(ctx, nm);
1912     }
1913 #ifndef OPENSSL_NO_ENGINE
1914     if (ssl_client_engine) {
1915         if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1916             BIO_puts(bio_err, "Error setting client auth engine\n");
1917             ERR_print_errors(bio_err);
1918             release_engine(ssl_client_engine);
1919             goto end;
1920         }
1921         release_engine(ssl_client_engine);
1922     }
1923 #endif
1924 
1925 #ifndef OPENSSL_NO_PSK
1926     if (psk_key != NULL) {
1927         if (c_debug)
1928             BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1929         SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1930     }
1931 #endif
1932     if (psksessf != NULL) {
1933         BIO *stmp = BIO_new_file(psksessf, "r");
1934 
1935         if (stmp == NULL) {
1936             BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
1937             ERR_print_errors(bio_err);
1938             goto end;
1939         }
1940         psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1941         BIO_free(stmp);
1942         if (psksess == NULL) {
1943             BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
1944             ERR_print_errors(bio_err);
1945             goto end;
1946         }
1947     }
1948     if (psk_key != NULL || psksess != NULL)
1949         SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
1950 
1951 #ifndef OPENSSL_NO_SRTP
1952     if (srtp_profiles != NULL) {
1953         /* Returns 0 on success! */
1954         if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1955             BIO_printf(bio_err, "Error setting SRTP profile\n");
1956             ERR_print_errors(bio_err);
1957             goto end;
1958         }
1959     }
1960 #endif
1961 
1962     if (exc != NULL)
1963         ssl_ctx_set_excert(ctx, exc);
1964 
1965 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1966     if (next_proto.data != NULL)
1967         SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1968 #endif
1969     if (alpn_in) {
1970         size_t alpn_len;
1971         unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1972 
1973         if (alpn == NULL) {
1974             BIO_printf(bio_err, "Error parsing -alpn argument\n");
1975             goto end;
1976         }
1977         /* Returns 0 on success! */
1978         if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1979             BIO_printf(bio_err, "Error setting ALPN\n");
1980             goto end;
1981         }
1982         OPENSSL_free(alpn);
1983     }
1984 
1985     for (i = 0; i < serverinfo_count; i++) {
1986         if (!SSL_CTX_add_client_custom_ext(ctx,
1987                                            serverinfo_types[i],
1988                                            NULL, NULL, NULL,
1989                                            serverinfo_cli_parse_cb, NULL)) {
1990             BIO_printf(bio_err,
1991                        "Warning: Unable to add custom extension %u, skipping\n",
1992                        serverinfo_types[i]);
1993         }
1994     }
1995 
1996     if (state)
1997         SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1998 
1999 #ifndef OPENSSL_NO_CT
2000     /* Enable SCT processing, without early connection termination */
2001     if (ct_validation &&
2002         !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
2003         ERR_print_errors(bio_err);
2004         goto end;
2005     }
2006 
2007     if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
2008         if (ct_validation) {
2009             ERR_print_errors(bio_err);
2010             goto end;
2011         }
2012 
2013         /*
2014          * If CT validation is not enabled, the log list isn't needed so don't
2015          * show errors or abort. We try to load it regardless because then we
2016          * can show the names of the logs any SCTs came from (SCTs may be seen
2017          * even with validation disabled).
2018          */
2019         ERR_clear_error();
2020     }
2021 #endif
2022 
2023     SSL_CTX_set_verify(ctx, verify, verify_callback);
2024 
2025     if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
2026                                   CAstore, noCAstore)) {
2027         ERR_print_errors(bio_err);
2028         goto end;
2029     }
2030 
2031     ssl_ctx_add_crls(ctx, crls, crl_download);
2032 
2033     if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
2034         goto end;
2035 
2036     if (!noservername) {
2037         tlsextcbp.biodebug = bio_err;
2038         SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2039         SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2040     }
2041 #ifndef OPENSSL_NO_SRP
2042     if (srp_arg.srplogin != NULL
2043             && !set_up_srp_arg(ctx, &srp_arg, srp_lateuser, c_msg, c_debug))
2044         goto end;
2045 # endif
2046 
2047     if (dane_tlsa_domain != NULL) {
2048         if (SSL_CTX_dane_enable(ctx) <= 0) {
2049             BIO_printf(bio_err,
2050                        "%s: Error enabling DANE TLSA authentication.\n",
2051                        prog);
2052             ERR_print_errors(bio_err);
2053             goto end;
2054         }
2055     }
2056 
2057     /*
2058      * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
2059      * come at any time. Therefore, we use a callback to write out the session
2060      * when we know about it. This approach works for < TLSv1.3 as well.
2061      */
2062     SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT
2063                                         | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2064     SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
2065 
2066     if (set_keylog_file(ctx, keylog_file))
2067         goto end;
2068 
2069     con = SSL_new(ctx);
2070     if (con == NULL)
2071         goto end;
2072 
2073     if (enable_pha)
2074         SSL_set_post_handshake_auth(con, 1);
2075 
2076     if (enable_client_rpk)
2077         if (!SSL_set1_client_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
2078             BIO_printf(bio_err, "Error setting client certificate types\n");
2079             goto end;
2080         }
2081     if (enable_server_rpk) {
2082         if (!SSL_set1_server_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
2083             BIO_printf(bio_err, "Error setting server certificate types\n");
2084             goto end;
2085         }
2086     }
2087 
2088     if (sess_in != NULL) {
2089         SSL_SESSION *sess;
2090         BIO *stmp = BIO_new_file(sess_in, "r");
2091         if (stmp == NULL) {
2092             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2093             ERR_print_errors(bio_err);
2094             goto end;
2095         }
2096         sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2097         BIO_free(stmp);
2098         if (sess == NULL) {
2099             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2100             ERR_print_errors(bio_err);
2101             goto end;
2102         }
2103         if (!SSL_set_session(con, sess)) {
2104             BIO_printf(bio_err, "Can't set session\n");
2105             ERR_print_errors(bio_err);
2106             goto end;
2107         }
2108 
2109         SSL_SESSION_free(sess);
2110     }
2111 
2112     if (fallback_scsv)
2113         SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
2114 
2115     if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
2116         if (servername == NULL) {
2117             if (host == NULL || is_dNS_name(host))
2118                 servername = (host == NULL) ? "localhost" : host;
2119         }
2120         if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) {
2121             BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
2122             ERR_print_errors(bio_err);
2123             goto end;
2124         }
2125     }
2126 
2127     if (dane_tlsa_domain != NULL) {
2128         if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
2129             BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
2130                        "authentication.\n", prog);
2131             ERR_print_errors(bio_err);
2132             goto end;
2133         }
2134         if (dane_tlsa_rrset == NULL) {
2135             BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
2136                        "least one -dane_tlsa_rrdata option.\n", prog);
2137             goto end;
2138         }
2139         if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
2140             BIO_printf(bio_err, "%s: Failed to import any TLSA "
2141                        "records.\n", prog);
2142             goto end;
2143         }
2144         if (dane_ee_no_name)
2145             SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
2146     } else if (dane_tlsa_rrset != NULL) {
2147         BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
2148                    "-dane_tlsa_domain option.\n", prog);
2149         goto end;
2150     }
2151 #ifndef OPENSSL_NO_DTLS
2152     if (isdtls && tfo) {
2153         BIO_printf(bio_err, "%s: DTLS does not support the -tfo option\n", prog);
2154         goto end;
2155     }
2156 #endif
2157 #ifndef OPENSSL_NO_QUIC
2158     if (isquic && tfo) {
2159         BIO_printf(bio_err, "%s: QUIC does not support the -tfo option\n", prog);
2160         goto end;
2161     }
2162     if (isquic && alpn_in == NULL) {
2163         BIO_printf(bio_err, "%s: QUIC requires ALPN to be specified (e.g. \"h3\" for HTTP/3) via the -alpn option\n", prog);
2164         goto end;
2165     }
2166 #endif
2167 
2168     if (tfo)
2169         BIO_printf(bio_c_out, "Connecting via TFO\n");
2170  re_start:
2171     /* peer_addr might be set from previous connections */
2172     BIO_ADDR_free(peer_addr);
2173     peer_addr = NULL;
2174     if (init_client(&sock, host, port, bindhost, bindport, socket_family,
2175                     socket_type, protocol, tfo, !isquic, &peer_addr) == 0) {
2176         BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
2177         BIO_closesocket(sock);
2178         goto end;
2179     }
2180     BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock);
2181 
2182     /*
2183      * QUIC always uses a non-blocking socket - and we have to switch on
2184      * non-blocking mode at the SSL level
2185      */
2186     if (c_nbio || isquic) {
2187         if (!BIO_socket_nbio(sock, 1)) {
2188             ERR_print_errors(bio_err);
2189             goto end;
2190         }
2191         if (c_nbio) {
2192             if (isquic && !SSL_set_blocking_mode(con, 0))
2193                 goto end;
2194             BIO_printf(bio_c_out, "Turned on non blocking io\n");
2195         }
2196     }
2197 #ifndef OPENSSL_NO_DTLS
2198     if (isdtls) {
2199         union BIO_sock_info_u peer_info;
2200 
2201 #ifndef OPENSSL_NO_SCTP
2202         if (protocol == IPPROTO_SCTP)
2203             sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
2204         else
2205 #endif
2206             sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
2207 
2208         if (sbio == NULL || (peer_info.addr = BIO_ADDR_new()) == NULL) {
2209             BIO_printf(bio_err, "memory allocation failure\n");
2210             BIO_free(sbio);
2211             BIO_closesocket(sock);
2212             goto end;
2213         }
2214         if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
2215             BIO_printf(bio_err, "getsockname:errno=%d\n",
2216                        get_last_socket_error());
2217             BIO_free(sbio);
2218             BIO_ADDR_free(peer_info.addr);
2219             BIO_closesocket(sock);
2220             goto end;
2221         }
2222 
2223         (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
2224         BIO_ADDR_free(peer_info.addr);
2225         peer_info.addr = NULL;
2226 
2227         if (enable_timeouts) {
2228             timeout.tv_sec = 0;
2229             timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2230             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2231 
2232             timeout.tv_sec = 0;
2233             timeout.tv_usec = DGRAM_SND_TIMEOUT;
2234             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2235         }
2236 
2237         if (socket_mtu) {
2238             if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2239                 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2240                            DTLS_get_link_min_mtu(con));
2241                 BIO_free(sbio);
2242                 goto shut;
2243             }
2244             SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2245             if (!DTLS_set_link_mtu(con, socket_mtu)) {
2246                 BIO_printf(bio_err, "Failed to set MTU\n");
2247                 BIO_free(sbio);
2248                 goto shut;
2249             }
2250         } else {
2251             /* want to do MTU discovery */
2252             BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2253         }
2254     } else
2255 #endif /* OPENSSL_NO_DTLS */
2256 #ifndef OPENSSL_NO_QUIC
2257     if (isquic) {
2258         sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
2259         if (!SSL_set1_initial_peer_addr(con, peer_addr)) {
2260             BIO_printf(bio_err, "Failed to set the initial peer address\n");
2261             goto shut;
2262         }
2263     } else
2264 #endif
2265         sbio = BIO_new_socket(sock, BIO_NOCLOSE);
2266 
2267     if (sbio == NULL) {
2268         BIO_printf(bio_err, "Unable to create BIO\n");
2269         ERR_print_errors(bio_err);
2270         BIO_closesocket(sock);
2271         goto end;
2272     }
2273 
2274     /* Now that we're using a BIO... */
2275     if (tfo) {
2276         (void)BIO_set_conn_address(sbio, peer_addr);
2277         (void)BIO_set_tfo(sbio, 1);
2278     }
2279 
2280     if (nbio_test) {
2281         BIO *test;
2282 
2283         test = BIO_new(BIO_f_nbio_test());
2284         if (test == NULL) {
2285             BIO_printf(bio_err, "Unable to create BIO\n");
2286             BIO_free(sbio);
2287             goto shut;
2288         }
2289         sbio = BIO_push(test, sbio);
2290     }
2291 
2292     if (c_debug) {
2293         BIO_set_callback_ex(sbio, bio_dump_callback);
2294         BIO_set_callback_arg(sbio, (char *)bio_c_out);
2295     }
2296     if (c_msg) {
2297 #ifndef OPENSSL_NO_SSL_TRACE
2298         if (c_msg == 2)
2299             SSL_set_msg_callback(con, SSL_trace);
2300         else
2301 #endif
2302             SSL_set_msg_callback(con, msg_cb);
2303         SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
2304     }
2305 
2306     if (c_tlsextdebug) {
2307         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2308         SSL_set_tlsext_debug_arg(con, bio_c_out);
2309     }
2310 #ifndef OPENSSL_NO_OCSP
2311     if (c_status_req) {
2312         SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
2313         SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
2314         SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
2315     }
2316 #endif
2317 
2318     SSL_set_bio(con, sbio, sbio);
2319     SSL_set_connect_state(con);
2320 
2321     /* ok, lets connect */
2322     if (fileno_stdin() > SSL_get_fd(con))
2323         width = fileno_stdin() + 1;
2324     else
2325         width = SSL_get_fd(con) + 1;
2326 
2327     read_tty = 1;
2328     write_tty = 0;
2329     tty_on = 0;
2330     read_ssl = 1;
2331     write_ssl = 1;
2332     first_loop = 1;
2333 
2334     cbuf_len = 0;
2335     cbuf_off = 0;
2336     sbuf_len = 0;
2337     sbuf_off = 0;
2338 
2339 #ifndef OPENSSL_NO_HTTP
2340     if (proxystr != NULL) {
2341         /* Here we must use the connect string target host & port */
2342         if (!OSSL_HTTP_proxy_connect(sbio, thost, tport, proxyuser, proxypass,
2343                                      0 /* no timeout */, bio_err, prog))
2344             goto shut;
2345     }
2346 #endif
2347 
2348     switch ((PROTOCOL_CHOICE) starttls_proto) {
2349     case PROTO_OFF:
2350         break;
2351     case PROTO_LMTP:
2352     case PROTO_SMTP:
2353         {
2354             /*
2355              * This is an ugly hack that does a lot of assumptions. We do
2356              * have to handle multi-line responses which may come in a single
2357              * packet or not. We therefore have to use BIO_gets() which does
2358              * need a buffering BIO. So during the initial chitchat we do
2359              * push a buffering BIO into the chain that is removed again
2360              * later on to not disturb the rest of the s_client operation.
2361              */
2362             int foundit = 0;
2363             BIO *fbio = BIO_new(BIO_f_buffer());
2364 
2365             if (fbio == NULL) {
2366                 BIO_printf(bio_err, "Unable to create BIO\n");
2367                 goto shut;
2368             }
2369             BIO_push(fbio, sbio);
2370             /* Wait for multi-line response to end from LMTP or SMTP */
2371             do {
2372                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2373             } while (mbuf_len > 3 && mbuf[3] == '-');
2374             if (protohost == NULL)
2375                 protohost = "mail.example.com";
2376             if (starttls_proto == (int)PROTO_LMTP)
2377                 BIO_printf(fbio, "LHLO %s\r\n", protohost);
2378             else
2379                 BIO_printf(fbio, "EHLO %s\r\n", protohost);
2380             (void)BIO_flush(fbio);
2381             /*
2382              * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2383              * response.
2384              */
2385             do {
2386                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2387                 if (strstr(mbuf, "STARTTLS"))
2388                     foundit = 1;
2389             } while (mbuf_len > 3 && mbuf[3] == '-');
2390             (void)BIO_flush(fbio);
2391             BIO_pop(fbio);
2392             BIO_free(fbio);
2393             if (!foundit)
2394                 BIO_printf(bio_err,
2395                            "Didn't find STARTTLS in server response,"
2396                            " trying anyway...\n");
2397             BIO_printf(sbio, "STARTTLS\r\n");
2398             BIO_read(sbio, sbuf, BUFSIZZ);
2399         }
2400         break;
2401     case PROTO_POP3:
2402         {
2403             BIO_read(sbio, mbuf, BUFSIZZ);
2404             BIO_printf(sbio, "STLS\r\n");
2405             mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
2406             if (mbuf_len < 0) {
2407                 BIO_printf(bio_err, "BIO_read failed\n");
2408                 goto end;
2409             }
2410         }
2411         break;
2412     case PROTO_IMAP:
2413         {
2414             int foundit = 0;
2415             BIO *fbio = BIO_new(BIO_f_buffer());
2416 
2417             if (fbio == NULL) {
2418                 BIO_printf(bio_err, "Unable to create BIO\n");
2419                 goto shut;
2420             }
2421             BIO_push(fbio, sbio);
2422             BIO_gets(fbio, mbuf, BUFSIZZ);
2423             /* STARTTLS command requires CAPABILITY... */
2424             BIO_printf(fbio, ". CAPABILITY\r\n");
2425             (void)BIO_flush(fbio);
2426             /* wait for multi-line CAPABILITY response */
2427             do {
2428                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2429                 if (strstr(mbuf, "STARTTLS"))
2430                     foundit = 1;
2431             }
2432             while (mbuf_len > 3 && mbuf[0] != '.');
2433             (void)BIO_flush(fbio);
2434             BIO_pop(fbio);
2435             BIO_free(fbio);
2436             if (!foundit)
2437                 BIO_printf(bio_err,
2438                            "Didn't find STARTTLS in server response,"
2439                            " trying anyway...\n");
2440             BIO_printf(sbio, ". STARTTLS\r\n");
2441             BIO_read(sbio, sbuf, BUFSIZZ);
2442         }
2443         break;
2444     case PROTO_FTP:
2445         {
2446             BIO *fbio = BIO_new(BIO_f_buffer());
2447 
2448             if (fbio == NULL) {
2449                 BIO_printf(bio_err, "Unable to create BIO\n");
2450                 goto shut;
2451             }
2452             BIO_push(fbio, sbio);
2453             /* wait for multi-line response to end from FTP */
2454             do {
2455                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2456             }
2457             while (mbuf_len > 3 && (!isdigit((unsigned char)mbuf[0]) || !isdigit((unsigned char)mbuf[1]) || !isdigit((unsigned char)mbuf[2]) || mbuf[3] != ' '));
2458             (void)BIO_flush(fbio);
2459             BIO_pop(fbio);
2460             BIO_free(fbio);
2461             BIO_printf(sbio, "AUTH TLS\r\n");
2462             BIO_read(sbio, sbuf, BUFSIZZ);
2463         }
2464         break;
2465     case PROTO_XMPP:
2466     case PROTO_XMPP_SERVER:
2467         {
2468             int seen = 0;
2469             BIO_printf(sbio, "<stream:stream "
2470                        "xmlns:stream='http://etherx.jabber.org/streams' "
2471                        "xmlns='jabber:%s' to='%s' version='1.0'>",
2472                        starttls_proto == PROTO_XMPP ? "client" : "server",
2473                        protohost ? protohost : host);
2474             seen = BIO_read(sbio, mbuf, BUFSIZZ);
2475             if (seen < 0) {
2476                 BIO_printf(bio_err, "BIO_read failed\n");
2477                 goto end;
2478             }
2479             mbuf[seen] = '\0';
2480             while (!strstr
2481                    (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2482                    && !strstr(mbuf,
2483                               "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2484             {
2485                 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2486 
2487                 if (seen <= 0)
2488                     goto shut;
2489 
2490                 mbuf[seen] = '\0';
2491             }
2492             BIO_printf(sbio,
2493                        "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2494             seen = BIO_read(sbio, sbuf, BUFSIZZ);
2495             if (seen < 0) {
2496                 BIO_printf(bio_err, "BIO_read failed\n");
2497                 goto shut;
2498             }
2499             sbuf[seen] = '\0';
2500             if (!strstr(sbuf, "<proceed"))
2501                 goto shut;
2502             mbuf[0] = '\0';
2503         }
2504         break;
2505     case PROTO_TELNET:
2506         {
2507             static const unsigned char tls_do[] = {
2508                 /* IAC    DO   START_TLS */
2509                    255,   253, 46
2510             };
2511             static const unsigned char tls_will[] = {
2512                 /* IAC  WILL START_TLS */
2513                    255, 251, 46
2514             };
2515             static const unsigned char tls_follows[] = {
2516                 /* IAC  SB   START_TLS FOLLOWS IAC  SE */
2517                    255, 250, 46,       1,      255, 240
2518             };
2519             int bytes;
2520 
2521             /* Telnet server should demand we issue START_TLS */
2522             bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2523             if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
2524                 goto shut;
2525             /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2526             BIO_write(sbio, tls_will, 3);
2527             BIO_write(sbio, tls_follows, 6);
2528             (void)BIO_flush(sbio);
2529             /* Telnet server also sent the FOLLOWS sub-command */
2530             bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2531             if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2532                 goto shut;
2533         }
2534         break;
2535     case PROTO_IRC:
2536         {
2537             int numeric;
2538             BIO *fbio = BIO_new(BIO_f_buffer());
2539 
2540             if (fbio == NULL) {
2541                 BIO_printf(bio_err, "Unable to create BIO\n");
2542                 goto end;
2543             }
2544             BIO_push(fbio, sbio);
2545             BIO_printf(fbio, "STARTTLS\r\n");
2546             (void)BIO_flush(fbio);
2547             width = SSL_get_fd(con) + 1;
2548 
2549             do {
2550                 numeric = 0;
2551 
2552                 FD_ZERO(&readfds);
2553                 openssl_fdset(SSL_get_fd(con), &readfds);
2554                 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2555                 timeout.tv_usec = 0;
2556                 /*
2557                  * If the IRCd doesn't respond within
2558                  * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2559                  * it doesn't support STARTTLS. Many IRCds
2560                  * will not give _any_ sort of response to a
2561                  * STARTTLS command when it's not supported.
2562                  */
2563                 if (!BIO_get_buffer_num_lines(fbio)
2564                     && !BIO_pending(fbio)
2565                     && !BIO_pending(sbio)
2566                     && select(width, (void *)&readfds, NULL, NULL,
2567                               &timeout) < 1) {
2568                     BIO_printf(bio_err,
2569                                "Timeout waiting for response (%d seconds).\n",
2570                                S_CLIENT_IRC_READ_TIMEOUT);
2571                     break;
2572                 }
2573 
2574                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2575                 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2576                     break;
2577                 /* :example.net 451 STARTTLS :You have not registered */
2578                 /* :example.net 421 STARTTLS :Unknown command */
2579                 if ((numeric == 451 || numeric == 421)
2580                     && strstr(mbuf, "STARTTLS") != NULL) {
2581                     BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2582                     break;
2583                 }
2584                 if (numeric == 691) {
2585                     BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2586                     ERR_print_errors(bio_err);
2587                     break;
2588                 }
2589             } while (numeric != 670);
2590 
2591             (void)BIO_flush(fbio);
2592             BIO_pop(fbio);
2593             BIO_free(fbio);
2594             if (numeric != 670) {
2595                 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2596                 ret = 1;
2597                 goto shut;
2598             }
2599         }
2600         break;
2601     case PROTO_MYSQL:
2602         {
2603             /* SSL request packet */
2604             static const unsigned char ssl_req[] = {
2605                 /* payload_length,   sequence_id */
2606                    0x20, 0x00, 0x00, 0x01,
2607                 /* payload */
2608                 /* capability flags, CLIENT_SSL always set */
2609                    0x85, 0xae, 0x7f, 0x00,
2610                 /* max-packet size */
2611                    0x00, 0x00, 0x00, 0x01,
2612                 /* character set */
2613                    0x21,
2614                 /* string[23] reserved (all [0]) */
2615                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2616                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2617                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2618             };
2619             int bytes = 0;
2620             int ssl_flg = 0x800;
2621             int pos;
2622             const unsigned char *packet = (const unsigned char *)sbuf;
2623 
2624             /* Receiving Initial Handshake packet. */
2625             bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
2626             if (bytes < 0) {
2627                 BIO_printf(bio_err, "BIO_read failed\n");
2628                 goto shut;
2629             /* Packet length[3], Packet number[1] + minimum payload[17] */
2630             } else if (bytes < 21) {
2631                 BIO_printf(bio_err, "MySQL packet too short.\n");
2632                 goto shut;
2633             } else if (bytes != (4 + packet[0] +
2634                                  (packet[1] << 8) +
2635                                  (packet[2] << 16))) {
2636                 BIO_printf(bio_err, "MySQL packet length does not match.\n");
2637                 goto shut;
2638             /* protocol version[1] */
2639             } else if (packet[4] != 0xA) {
2640                 BIO_printf(bio_err,
2641                            "Only MySQL protocol version 10 is supported.\n");
2642                 goto shut;
2643             }
2644 
2645             pos = 5;
2646             /* server version[string+NULL] */
2647             for (;;) {
2648                 if (pos >= bytes) {
2649                     BIO_printf(bio_err, "Cannot confirm server version. ");
2650                     goto shut;
2651                 } else if (packet[pos++] == '\0') {
2652                     break;
2653                 }
2654             }
2655 
2656             /* make sure we have at least 15 bytes left in the packet */
2657             if (pos + 15 > bytes) {
2658                 BIO_printf(bio_err,
2659                            "MySQL server handshake packet is broken.\n");
2660                 goto shut;
2661             }
2662 
2663             pos += 12; /* skip over conn id[4] + SALT[8] */
2664             if (packet[pos++] != '\0') { /* verify filler */
2665                 BIO_printf(bio_err,
2666                            "MySQL packet is broken.\n");
2667                 goto shut;
2668             }
2669 
2670             /* capability flags[2] */
2671             if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
2672                 BIO_printf(bio_err, "MySQL server does not support SSL.\n");
2673                 goto shut;
2674             }
2675 
2676             /* Sending SSL Handshake packet. */
2677             BIO_write(sbio, ssl_req, sizeof(ssl_req));
2678             (void)BIO_flush(sbio);
2679         }
2680         break;
2681     case PROTO_POSTGRES:
2682         {
2683             static const unsigned char ssl_request[] = {
2684                 /* Length        SSLRequest */
2685                    0, 0, 0, 8,   4, 210, 22, 47
2686             };
2687             int bytes;
2688 
2689             /* Send SSLRequest packet */
2690             BIO_write(sbio, ssl_request, 8);
2691             (void)BIO_flush(sbio);
2692 
2693             /* Reply will be a single S if SSL is enabled */
2694             bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2695             if (bytes != 1 || sbuf[0] != 'S')
2696                 goto shut;
2697         }
2698         break;
2699     case PROTO_NNTP:
2700         {
2701             int foundit = 0;
2702             BIO *fbio = BIO_new(BIO_f_buffer());
2703 
2704             if (fbio == NULL) {
2705                 BIO_printf(bio_err, "Unable to create BIO\n");
2706                 goto end;
2707             }
2708             BIO_push(fbio, sbio);
2709             BIO_gets(fbio, mbuf, BUFSIZZ);
2710             /* STARTTLS command requires CAPABILITIES... */
2711             BIO_printf(fbio, "CAPABILITIES\r\n");
2712             (void)BIO_flush(fbio);
2713             BIO_gets(fbio, mbuf, BUFSIZZ);
2714             /* no point in trying to parse the CAPABILITIES response if there is none */
2715             if (strstr(mbuf, "101") != NULL) {
2716                 /* wait for multi-line CAPABILITIES response */
2717                 do {
2718                     mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2719                     if (strstr(mbuf, "STARTTLS"))
2720                         foundit = 1;
2721                 } while (mbuf_len > 1 && mbuf[0] != '.');
2722             }
2723             (void)BIO_flush(fbio);
2724             BIO_pop(fbio);
2725             BIO_free(fbio);
2726             if (!foundit)
2727                 BIO_printf(bio_err,
2728                            "Didn't find STARTTLS in server response,"
2729                            " trying anyway...\n");
2730             BIO_printf(sbio, "STARTTLS\r\n");
2731             mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2732             if (mbuf_len < 0) {
2733                 BIO_printf(bio_err, "BIO_read failed\n");
2734                 goto end;
2735             }
2736             mbuf[mbuf_len] = '\0';
2737             if (strstr(mbuf, "382") == NULL) {
2738                 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2739                 goto shut;
2740             }
2741         }
2742         break;
2743     case PROTO_SIEVE:
2744         {
2745             int foundit = 0;
2746             BIO *fbio = BIO_new(BIO_f_buffer());
2747 
2748             if (fbio == NULL) {
2749                 BIO_printf(bio_err, "Unable to create BIO\n");
2750                 goto end;
2751             }
2752             BIO_push(fbio, sbio);
2753             /* wait for multi-line response to end from Sieve */
2754             do {
2755                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2756                 /*
2757                  * According to RFC 5804 § 1.7, capability
2758                  * is case-insensitive, make it uppercase
2759                  */
2760                 if (mbuf_len > 1 && mbuf[0] == '"') {
2761                     make_uppercase(mbuf);
2762                     if (HAS_PREFIX(mbuf, "\"STARTTLS\""))
2763                         foundit = 1;
2764                 }
2765             } while (mbuf_len > 1 && mbuf[0] == '"');
2766             (void)BIO_flush(fbio);
2767             BIO_pop(fbio);
2768             BIO_free(fbio);
2769             if (!foundit)
2770                 BIO_printf(bio_err,
2771                            "Didn't find STARTTLS in server response,"
2772                            " trying anyway...\n");
2773             BIO_printf(sbio, "STARTTLS\r\n");
2774             mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2775             if (mbuf_len < 0) {
2776                 BIO_printf(bio_err, "BIO_read failed\n");
2777                 goto end;
2778             }
2779             mbuf[mbuf_len] = '\0';
2780             if (mbuf_len < 2) {
2781                 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2782                 goto shut;
2783             }
2784             /*
2785              * According to RFC 5804 § 2.2, response codes are case-
2786              * insensitive, make it uppercase but preserve the response.
2787              */
2788             strncpy(sbuf, mbuf, 2);
2789             make_uppercase(sbuf);
2790             if (!HAS_PREFIX(sbuf, "OK")) {
2791                 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2792                 goto shut;
2793             }
2794         }
2795         break;
2796     case PROTO_LDAP:
2797         {
2798             /* StartTLS Operation according to RFC 4511 */
2799             static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
2800                 "[LDAPMessage]\n"
2801                 "messageID=INTEGER:1\n"
2802                 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2803                 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2804             long errline = -1;
2805             char *genstr = NULL;
2806             int result = -1;
2807             ASN1_TYPE *atyp = NULL;
2808             BIO *ldapbio = BIO_new(BIO_s_mem());
2809             CONF *cnf = NCONF_new(NULL);
2810 
2811             if (ldapbio == NULL || cnf == NULL) {
2812                 BIO_free(ldapbio);
2813                 NCONF_free(cnf);
2814                 goto end;
2815             }
2816             BIO_puts(ldapbio, ldap_tls_genconf);
2817             if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
2818                 BIO_free(ldapbio);
2819                 NCONF_free(cnf);
2820                 if (errline <= 0) {
2821                     BIO_printf(bio_err, "NCONF_load_bio failed\n");
2822                     goto end;
2823                 } else {
2824                     BIO_printf(bio_err, "Error on line %ld\n", errline);
2825                     goto end;
2826                 }
2827             }
2828             BIO_free(ldapbio);
2829             genstr = NCONF_get_string(cnf, "default", "asn1");
2830             if (genstr == NULL) {
2831                 NCONF_free(cnf);
2832                 BIO_printf(bio_err, "NCONF_get_string failed\n");
2833                 goto end;
2834             }
2835             atyp = ASN1_generate_nconf(genstr, cnf);
2836             if (atyp == NULL) {
2837                 NCONF_free(cnf);
2838                 BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
2839                 goto end;
2840             }
2841             NCONF_free(cnf);
2842 
2843             /* Send SSLRequest packet */
2844             BIO_write(sbio, atyp->value.sequence->data,
2845                       atyp->value.sequence->length);
2846             (void)BIO_flush(sbio);
2847             ASN1_TYPE_free(atyp);
2848 
2849             mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2850             if (mbuf_len < 0) {
2851                 BIO_printf(bio_err, "BIO_read failed\n");
2852                 goto end;
2853             }
2854             result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
2855             if (result < 0) {
2856                 BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
2857                 goto shut;
2858             } else if (result > 0) {
2859                 BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
2860                            result);
2861                 goto shut;
2862             }
2863             mbuf_len = 0;
2864         }
2865         break;
2866     }
2867 
2868     if (early_data_file != NULL
2869             && ((SSL_get0_session(con) != NULL
2870                  && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
2871                 || (psksess != NULL
2872                     && SSL_SESSION_get_max_early_data(psksess) > 0))) {
2873         BIO *edfile = BIO_new_file(early_data_file, "r");
2874         size_t readbytes, writtenbytes;
2875         int finish = 0;
2876 
2877         if (edfile == NULL) {
2878             BIO_printf(bio_err, "Cannot open early data file\n");
2879             goto shut;
2880         }
2881 
2882         while (!finish) {
2883             if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
2884                 finish = 1;
2885 
2886             while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
2887                 switch (SSL_get_error(con, 0)) {
2888                 case SSL_ERROR_WANT_WRITE:
2889                 case SSL_ERROR_WANT_ASYNC:
2890                 case SSL_ERROR_WANT_READ:
2891                     /* Just keep trying - busy waiting */
2892                     continue;
2893                 default:
2894                     BIO_printf(bio_err, "Error writing early data\n");
2895                     BIO_free(edfile);
2896                     ERR_print_errors(bio_err);
2897                     goto shut;
2898                 }
2899             }
2900         }
2901 
2902         BIO_free(edfile);
2903     }
2904 
2905     user_data_init(&user_data, con, cbuf, BUFSIZZ, cmdmode);
2906     for (;;) {
2907         FD_ZERO(&readfds);
2908         FD_ZERO(&writefds);
2909 
2910         if ((isdtls || isquic)
2911             && SSL_get_event_timeout(con, &timeout, &is_infinite)
2912             && !is_infinite)
2913             timeoutp = &timeout;
2914         else
2915             timeoutp = NULL;
2916 
2917         if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
2918                 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
2919             in_init = 1;
2920             tty_on = 0;
2921         } else {
2922             tty_on = 1;
2923             if (in_init) {
2924                 in_init = 0;
2925                 if (c_brief) {
2926                     BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2927                     print_ssl_summary(con);
2928                 }
2929 
2930                 print_stuff(bio_c_out, con, full_log);
2931                 if (full_log > 0)
2932                     full_log--;
2933 
2934                 if (starttls_proto) {
2935                     BIO_write(bio_err, mbuf, mbuf_len);
2936                     /* We don't need to know any more */
2937                     if (!reconnect)
2938                         starttls_proto = PROTO_OFF;
2939                 }
2940 
2941                 if (reconnect) {
2942                     reconnect--;
2943                     BIO_printf(bio_c_out,
2944                                "drop connection and then reconnect\n");
2945                     do_ssl_shutdown(con);
2946                     SSL_set_connect_state(con);
2947                     BIO_closesocket(SSL_get_fd(con));
2948                     goto re_start;
2949                 }
2950             }
2951         }
2952 
2953         if (!write_ssl) {
2954             do {
2955                 switch (user_data_process(&user_data, &cbuf_len, &cbuf_off)) {
2956                 default:
2957                     BIO_printf(bio_err, "ERROR\n");
2958                     /* fall through */
2959                 case USER_DATA_PROCESS_SHUT:
2960                     ret = 0;
2961                     goto shut;
2962 
2963                 case USER_DATA_PROCESS_RESTART:
2964                     goto re_start;
2965 
2966                 case USER_DATA_PROCESS_NO_DATA:
2967                     break;
2968 
2969                 case USER_DATA_PROCESS_CONTINUE:
2970                     write_ssl = 1;
2971                     break;
2972                 }
2973             } while (!write_ssl
2974                      && cbuf_len == 0
2975                      && user_data_has_data(&user_data));
2976             if (cbuf_len > 0) {
2977                 read_tty = 0;
2978                 timeout.tv_sec = 0;
2979                 timeout.tv_usec = 0;
2980             } else {
2981                 read_tty = 1;
2982             }
2983         }
2984 
2985         ssl_pending = read_ssl && SSL_has_pending(con);
2986 
2987         if (!ssl_pending) {
2988 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2989             if (tty_on) {
2990                 /*
2991                  * Note that select() returns when read _would not block_,
2992                  * and EOF satisfies that.  To avoid a CPU-hogging loop,
2993                  * set the flag so we exit.
2994                  */
2995                 if (read_tty && !at_eof)
2996                     openssl_fdset(fileno_stdin(), &readfds);
2997 #if !defined(OPENSSL_SYS_VMS)
2998                 if (write_tty)
2999                     openssl_fdset(fileno_stdout(), &writefds);
3000 #endif
3001             }
3002 
3003             /*
3004              * Note that for QUIC we never actually check FD_ISSET() for the
3005              * underlying network fds. We just rely on select waking up when
3006              * they become readable/writeable and then SSL_handle_events() doing
3007              * the right thing.
3008              */
3009             if ((!isquic && read_ssl)
3010                     || (isquic && SSL_net_read_desired(con)))
3011                 openssl_fdset(SSL_get_fd(con), &readfds);
3012             if ((!isquic && write_ssl)
3013                     || (isquic && (first_loop || SSL_net_write_desired(con))))
3014                 openssl_fdset(SSL_get_fd(con), &writefds);
3015 #else
3016             if (!tty_on || !write_tty) {
3017                 if ((!isquic && read_ssl)
3018                         || (isquic && SSL_net_read_desired(con)))
3019                     openssl_fdset(SSL_get_fd(con), &readfds);
3020                 if ((!isquic && write_ssl)
3021                         || (isquic && (first_loop || SSL_net_write_desired(con))))
3022                     openssl_fdset(SSL_get_fd(con), &writefds);
3023             }
3024 #endif
3025 
3026             /*
3027              * Note: under VMS with SOCKETSHR the second parameter is
3028              * currently of type (int *) whereas under other systems it is
3029              * (void *) if you don't have a cast it will choke the compiler:
3030              * if you do have a cast then you can either go for (int *) or
3031              * (void *).
3032              */
3033 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
3034             /*
3035              * Under Windows/DOS we make the assumption that we can always
3036              * write to the tty: therefore, if we need to write to the tty we
3037              * just fall through. Otherwise we timeout the select every
3038              * second and see if there are any keypresses. Note: this is a
3039              * hack, in a proper Windows application we wouldn't do this.
3040              */
3041             i = 0;
3042             if (!write_tty) {
3043                 if (read_tty) {
3044                     tv.tv_sec = 1;
3045                     tv.tv_usec = 0;
3046                     i = select(width, (void *)&readfds, (void *)&writefds,
3047                                NULL, &tv);
3048                     if (!i && (!has_stdin_waiting() || !read_tty))
3049                         continue;
3050                 } else
3051                     i = select(width, (void *)&readfds, (void *)&writefds,
3052                                NULL, timeoutp);
3053             }
3054 #else
3055             i = select(width, (void *)&readfds, (void *)&writefds,
3056                        NULL, timeoutp);
3057 #endif
3058             if (i < 0) {
3059                 BIO_printf(bio_err, "bad select %d\n",
3060                            get_last_socket_error());
3061                 goto shut;
3062             }
3063         }
3064 
3065         if (timeoutp != NULL) {
3066             SSL_handle_events(con);
3067             if (isdtls
3068                     && !FD_ISSET(SSL_get_fd(con), &readfds)
3069                     && !FD_ISSET(SSL_get_fd(con), &writefds))
3070                 BIO_printf(bio_err, "TIMEOUT occurred\n");
3071         }
3072 
3073         if (!ssl_pending
3074                 && ((!isquic && FD_ISSET(SSL_get_fd(con), &writefds))
3075                     || (isquic && (cbuf_len > 0 || first_loop)))) {
3076             k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
3077             switch (SSL_get_error(con, k)) {
3078             case SSL_ERROR_NONE:
3079                 cbuf_off += k;
3080                 cbuf_len -= k;
3081                 if (k <= 0)
3082                     goto end;
3083                 /* we have done a  write(con,NULL,0); */
3084                 if (cbuf_len == 0) {
3085                     read_tty = 1;
3086                     write_ssl = 0;
3087                 } else {        /* if (cbuf_len > 0) */
3088 
3089                     read_tty = 0;
3090                     write_ssl = 1;
3091                 }
3092                 break;
3093             case SSL_ERROR_WANT_WRITE:
3094                 BIO_printf(bio_c_out, "write W BLOCK\n");
3095                 write_ssl = 1;
3096                 read_tty = 0;
3097                 break;
3098             case SSL_ERROR_WANT_ASYNC:
3099                 BIO_printf(bio_c_out, "write A BLOCK\n");
3100                 wait_for_async(con);
3101                 write_ssl = 1;
3102                 read_tty = 0;
3103                 break;
3104             case SSL_ERROR_WANT_READ:
3105                 BIO_printf(bio_c_out, "write R BLOCK\n");
3106                 write_tty = 0;
3107                 read_ssl = 1;
3108                 write_ssl = 0;
3109                 break;
3110             case SSL_ERROR_WANT_X509_LOOKUP:
3111                 BIO_printf(bio_c_out, "write X BLOCK\n");
3112                 break;
3113             case SSL_ERROR_ZERO_RETURN:
3114                 if (cbuf_len != 0) {
3115                     BIO_printf(bio_c_out, "shutdown\n");
3116                     ret = 0;
3117                     goto shut;
3118                 } else {
3119                     read_tty = 1;
3120                     write_ssl = 0;
3121                     break;
3122                 }
3123 
3124             case SSL_ERROR_SYSCALL:
3125                 if ((k != 0) || (cbuf_len != 0)) {
3126                     int sockerr = get_last_socket_error();
3127 
3128                     if (!tfo || sockerr != EISCONN) {
3129                         BIO_printf(bio_err, "write:errno=%d\n", sockerr);
3130                         goto shut;
3131                     }
3132                 } else {
3133                     read_tty = 1;
3134                     write_ssl = 0;
3135                 }
3136                 break;
3137             case SSL_ERROR_WANT_ASYNC_JOB:
3138                 /* This shouldn't ever happen in s_client - treat as an error */
3139             case SSL_ERROR_SSL:
3140                 ERR_print_errors(bio_err);
3141                 goto shut;
3142             }
3143         }
3144 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
3145         /* Assume Windows/DOS/BeOS can always write */
3146         else if (!ssl_pending && write_tty)
3147 #else
3148         else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
3149 #endif
3150         {
3151 #ifdef CHARSET_EBCDIC
3152             ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
3153 #endif
3154             i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
3155 
3156             if (i <= 0) {
3157                 BIO_printf(bio_c_out, "DONE\n");
3158                 ret = 0;
3159                 goto shut;
3160             }
3161 
3162             sbuf_len -= i;
3163             sbuf_off += i;
3164             if (sbuf_len <= 0) {
3165                 read_ssl = 1;
3166                 write_tty = 0;
3167             }
3168         } else if (ssl_pending
3169                    || (!isquic && FD_ISSET(SSL_get_fd(con), &readfds))) {
3170 #ifdef RENEG
3171             {
3172                 static int iiii;
3173                 if (++iiii == 52) {
3174                     SSL_renegotiate(con);
3175                     iiii = 0;
3176                 }
3177             }
3178 #endif
3179             k = SSL_read(con, sbuf, BUFSIZZ);
3180 
3181             switch (SSL_get_error(con, k)) {
3182             case SSL_ERROR_NONE:
3183                 if (k <= 0)
3184                     goto end;
3185                 sbuf_off = 0;
3186                 sbuf_len = k;
3187 
3188                 read_ssl = 0;
3189                 write_tty = 1;
3190                 break;
3191             case SSL_ERROR_WANT_ASYNC:
3192                 BIO_printf(bio_c_out, "read A BLOCK\n");
3193                 wait_for_async(con);
3194                 write_tty = 0;
3195                 read_ssl = 1;
3196                 if ((read_tty == 0) && (write_ssl == 0))
3197                     write_ssl = 1;
3198                 break;
3199             case SSL_ERROR_WANT_WRITE:
3200                 BIO_printf(bio_c_out, "read W BLOCK\n");
3201                 write_ssl = 1;
3202                 read_tty = 0;
3203                 break;
3204             case SSL_ERROR_WANT_READ:
3205                 BIO_printf(bio_c_out, "read R BLOCK\n");
3206                 write_tty = 0;
3207                 read_ssl = 1;
3208                 if ((read_tty == 0) && (write_ssl == 0))
3209                     write_ssl = 1;
3210                 break;
3211             case SSL_ERROR_WANT_X509_LOOKUP:
3212                 BIO_printf(bio_c_out, "read X BLOCK\n");
3213                 break;
3214             case SSL_ERROR_SYSCALL:
3215                 ret = get_last_socket_error();
3216                 if (c_brief)
3217                     BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
3218                 else
3219                     BIO_printf(bio_err, "read:errno=%d\n", ret);
3220                 goto shut;
3221             case SSL_ERROR_ZERO_RETURN:
3222                 BIO_printf(bio_c_out, "closed\n");
3223                 ret = 0;
3224                 goto shut;
3225             case SSL_ERROR_WANT_ASYNC_JOB:
3226                 /* This shouldn't ever happen in s_client. Treat as an error */
3227             case SSL_ERROR_SSL:
3228                 ERR_print_errors(bio_err);
3229                 goto shut;
3230             }
3231         }
3232 
3233         /* don't wait for client input in the non-interactive mode */
3234         else if (nointeractive) {
3235             ret = 0;
3236             goto shut;
3237         }
3238 
3239 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
3240 #if defined(OPENSSL_SYS_MSDOS)
3241         else if (has_stdin_waiting())
3242 #else
3243         else if (FD_ISSET(fileno_stdin(), &readfds))
3244 #endif
3245         {
3246             if (crlf) {
3247                 int j, lf_num;
3248 
3249                 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
3250                 lf_num = 0;
3251                 /* both loops are skipped when i <= 0 */
3252                 for (j = 0; j < i; j++)
3253                     if (cbuf[j] == '\n')
3254                         lf_num++;
3255                 for (j = i - 1; j >= 0; j--) {
3256                     cbuf[j + lf_num] = cbuf[j];
3257                     if (cbuf[j] == '\n') {
3258                         lf_num--;
3259                         i++;
3260                         cbuf[j + lf_num] = '\r';
3261                     }
3262                 }
3263                 assert(lf_num == 0);
3264             } else
3265                 i = raw_read_stdin(cbuf, BUFSIZZ);
3266 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3267             if (i == 0)
3268                 at_eof = 1;
3269 #endif
3270 
3271             if (!c_ign_eof && i <= 0) {
3272                 BIO_printf(bio_err, "DONE\n");
3273                 ret = 0;
3274                 goto shut;
3275             }
3276 
3277             if (i > 0 && !user_data_add(&user_data, i)) {
3278                 ret = 0;
3279                 goto shut;
3280             }
3281             read_tty = 0;
3282         }
3283         first_loop = 0;
3284     }
3285 
3286  shut:
3287     if (in_init)
3288         print_stuff(bio_c_out, con, full_log);
3289     do_ssl_shutdown(con);
3290 
3291     /*
3292      * If we ended with an alert being sent, but still with data in the
3293      * network buffer to be read, then calling BIO_closesocket() will
3294      * result in a TCP-RST being sent. On some platforms (notably
3295      * Windows) then this will result in the peer immediately abandoning
3296      * the connection including any buffered alert data before it has
3297      * had a chance to be read. Shutting down the sending side first,
3298      * and then closing the socket sends TCP-FIN first followed by
3299      * TCP-RST. This seems to allow the peer to read the alert data.
3300      */
3301     shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
3302     /*
3303      * We just said we have nothing else to say, but it doesn't mean that
3304      * the other side has nothing. It's even recommended to consume incoming
3305      * data. [In testing context this ensures that alerts are passed on...]
3306      */
3307     timeout.tv_sec = 0;
3308     timeout.tv_usec = 500000;  /* some extreme round-trip */
3309     do {
3310         FD_ZERO(&readfds);
3311         openssl_fdset(sock, &readfds);
3312     } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
3313              && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
3314 
3315     BIO_closesocket(SSL_get_fd(con));
3316  end:
3317     if (con != NULL) {
3318         if (prexit != 0)
3319             print_stuff(bio_c_out, con, 1);
3320         SSL_free(con);
3321     }
3322     SSL_SESSION_free(psksess);
3323 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3324     OPENSSL_free(next_proto.data);
3325 #endif
3326     SSL_CTX_free(ctx);
3327     set_keylog_file(NULL, NULL);
3328     X509_free(cert);
3329     sk_X509_CRL_pop_free(crls, X509_CRL_free);
3330     EVP_PKEY_free(key);
3331     OSSL_STACK_OF_X509_free(chain);
3332     OPENSSL_free(pass);
3333 #ifndef OPENSSL_NO_SRP
3334     OPENSSL_free(srp_arg.srppassin);
3335 #endif
3336     OPENSSL_free(sname_alloc);
3337     BIO_ADDR_free(peer_addr);
3338     OPENSSL_free(connectstr);
3339     OPENSSL_free(bindstr);
3340     OPENSSL_free(bindhost);
3341     OPENSSL_free(bindport);
3342     OPENSSL_free(host);
3343     OPENSSL_free(port);
3344     OPENSSL_free(thost);
3345     OPENSSL_free(tport);
3346     X509_VERIFY_PARAM_free(vpm);
3347     ssl_excert_free(exc);
3348     sk_OPENSSL_STRING_free(ssl_args);
3349     sk_OPENSSL_STRING_free(dane_tlsa_rrset);
3350     SSL_CONF_CTX_free(cctx);
3351     OPENSSL_clear_free(cbuf, BUFSIZZ);
3352     OPENSSL_clear_free(sbuf, BUFSIZZ);
3353     OPENSSL_clear_free(mbuf, BUFSIZZ);
3354     clear_free(proxypass);
3355     release_engine(e);
3356     BIO_free(bio_c_out);
3357     bio_c_out = NULL;
3358     BIO_free(bio_c_msg);
3359     bio_c_msg = NULL;
3360     return ret;
3361 }
3362 
print_stuff(BIO * bio,SSL * s,int full)3363 static void print_stuff(BIO *bio, SSL *s, int full)
3364 {
3365     X509 *peer = NULL;
3366     STACK_OF(X509) *sk;
3367     const SSL_CIPHER *c;
3368     EVP_PKEY *public_key;
3369     int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
3370     long verify_result;
3371 #ifndef OPENSSL_NO_COMP
3372     const COMP_METHOD *comp, *expansion;
3373 #endif
3374     unsigned char *exportedkeymat;
3375 #ifndef OPENSSL_NO_CT
3376     const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
3377 #endif
3378 
3379     if (full) {
3380         int got_a_chain = 0;
3381 
3382         sk = SSL_get_peer_cert_chain(s);
3383         if (sk != NULL) {
3384             got_a_chain = 1;
3385 
3386             BIO_printf(bio, "---\nCertificate chain\n");
3387             for (i = 0; i < sk_X509_num(sk); i++) {
3388                 BIO_printf(bio, "%2d s:", i);
3389                 X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
3390                 BIO_puts(bio, "\n");
3391                 BIO_printf(bio, "   i:");
3392                 X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
3393                 BIO_puts(bio, "\n");
3394                 public_key = X509_get_pubkey(sk_X509_value(sk, i));
3395                 if (public_key != NULL) {
3396                     BIO_printf(bio, "   a:PKEY: %s, %d (bit); sigalg: %s\n",
3397                                OBJ_nid2sn(EVP_PKEY_get_base_id(public_key)),
3398                                EVP_PKEY_get_bits(public_key),
3399                                OBJ_nid2sn(X509_get_signature_nid(sk_X509_value(sk, i))));
3400                     EVP_PKEY_free(public_key);
3401                 }
3402                 BIO_printf(bio, "   v:NotBefore: ");
3403                 ASN1_TIME_print(bio, X509_get0_notBefore(sk_X509_value(sk, i)));
3404                 BIO_printf(bio, "; NotAfter: ");
3405                 ASN1_TIME_print(bio, X509_get0_notAfter(sk_X509_value(sk, i)));
3406                 BIO_puts(bio, "\n");
3407                 if (c_showcerts)
3408                     PEM_write_bio_X509(bio, sk_X509_value(sk, i));
3409             }
3410         }
3411 
3412         BIO_printf(bio, "---\n");
3413         peer = SSL_get0_peer_certificate(s);
3414         if (peer != NULL) {
3415             BIO_printf(bio, "Server certificate\n");
3416 
3417             /* Redundant if we showed the whole chain */
3418             if (!(c_showcerts && got_a_chain))
3419                 PEM_write_bio_X509(bio, peer);
3420             dump_cert_text(bio, peer);
3421         } else {
3422             BIO_printf(bio, "no peer certificate available\n");
3423         }
3424 
3425         /* Only display RPK information if configured */
3426         if (SSL_get_negotiated_client_cert_type(s) == TLSEXT_cert_type_rpk)
3427             BIO_printf(bio, "Client-to-server raw public key negotiated\n");
3428         if (SSL_get_negotiated_server_cert_type(s) == TLSEXT_cert_type_rpk)
3429             BIO_printf(bio, "Server-to-client raw public key negotiated\n");
3430         if (enable_server_rpk) {
3431             EVP_PKEY *peer_rpk = SSL_get0_peer_rpk(s);
3432 
3433             if (peer_rpk != NULL) {
3434                 BIO_printf(bio, "Server raw public key\n");
3435                 EVP_PKEY_print_public(bio, peer_rpk, 2, NULL);
3436             } else {
3437                 BIO_printf(bio, "no peer rpk available\n");
3438             }
3439         }
3440 
3441         print_ca_names(bio, s);
3442 
3443         ssl_print_sigalgs(bio, s);
3444         ssl_print_tmp_key(bio, s);
3445 
3446 #ifndef OPENSSL_NO_CT
3447         /*
3448          * When the SSL session is anonymous, or resumed via an abbreviated
3449          * handshake, no SCTs are provided as part of the handshake.  While in
3450          * a resumed session SCTs may be present in the session's certificate,
3451          * no callbacks are invoked to revalidate these, and in any case that
3452          * set of SCTs may be incomplete.  Thus it makes little sense to
3453          * attempt to display SCTs from a resumed session's certificate, and of
3454          * course none are associated with an anonymous peer.
3455          */
3456         if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
3457             const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
3458             int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
3459 
3460             BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
3461             if (sct_count > 0) {
3462                 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
3463 
3464                 BIO_printf(bio, "---\n");
3465                 for (i = 0; i < sct_count; ++i) {
3466                     SCT *sct = sk_SCT_value(scts, i);
3467 
3468                     BIO_printf(bio, "SCT validation status: %s\n",
3469                                SCT_validation_status_string(sct));
3470                     SCT_print(sct, bio, 0, log_store);
3471                     if (i < sct_count - 1)
3472                         BIO_printf(bio, "\n---\n");
3473                 }
3474                 BIO_printf(bio, "\n");
3475             }
3476         }
3477 #endif
3478 
3479         BIO_printf(bio,
3480                    "---\nSSL handshake has read %ju bytes "
3481                    "and written %ju bytes\n",
3482                    BIO_number_read(SSL_get_rbio(s)),
3483                    BIO_number_written(SSL_get_wbio(s)));
3484     }
3485     print_verify_detail(s, bio);
3486     BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
3487     c = SSL_get_current_cipher(s);
3488     BIO_printf(bio, "%s, Cipher is %s\n",
3489                SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3490     BIO_printf(bio, "Protocol: %s\n", SSL_get_version(s));
3491     if (peer != NULL) {
3492         EVP_PKEY *pktmp;
3493 
3494         pktmp = X509_get0_pubkey(peer);
3495         BIO_printf(bio, "Server public key is %d bit\n",
3496                    EVP_PKEY_get_bits(pktmp));
3497     }
3498 
3499     ssl_print_secure_renegotiation_notes(bio, s);
3500 
3501 #ifndef OPENSSL_NO_COMP
3502     comp = SSL_get_current_compression(s);
3503     expansion = SSL_get_current_expansion(s);
3504     BIO_printf(bio, "Compression: %s\n",
3505                comp ? SSL_COMP_get_name(comp) : "NONE");
3506     BIO_printf(bio, "Expansion: %s\n",
3507                expansion ? SSL_COMP_get_name(expansion) : "NONE");
3508 #endif
3509 #ifndef OPENSSL_NO_KTLS
3510     if (BIO_get_ktls_send(SSL_get_wbio(s)))
3511         BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3512     if (BIO_get_ktls_recv(SSL_get_rbio(s)))
3513         BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3514 #endif
3515 
3516     if (OSSL_TRACE_ENABLED(TLS)) {
3517         /* Print out local port of connection: useful for debugging */
3518         int sock;
3519         union BIO_sock_info_u info;
3520 
3521         sock = SSL_get_fd(s);
3522         if ((info.addr = BIO_ADDR_new()) != NULL
3523             && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
3524             BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
3525                        ntohs(BIO_ADDR_rawport(info.addr)));
3526         }
3527         BIO_ADDR_free(info.addr);
3528     }
3529 
3530 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3531     if (next_proto.status != -1) {
3532         const unsigned char *proto;
3533         unsigned int proto_len;
3534         SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
3535         BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
3536         BIO_write(bio, proto, proto_len);
3537         BIO_write(bio, "\n", 1);
3538     }
3539 #endif
3540     {
3541         const unsigned char *proto;
3542         unsigned int proto_len;
3543         SSL_get0_alpn_selected(s, &proto, &proto_len);
3544         if (proto_len > 0) {
3545             BIO_printf(bio, "ALPN protocol: ");
3546             BIO_write(bio, proto, proto_len);
3547             BIO_write(bio, "\n", 1);
3548         } else
3549             BIO_printf(bio, "No ALPN negotiated\n");
3550     }
3551 
3552 #ifndef OPENSSL_NO_SRTP
3553     {
3554         SRTP_PROTECTION_PROFILE *srtp_profile =
3555             SSL_get_selected_srtp_profile(s);
3556 
3557         if (srtp_profile)
3558             BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
3559                        srtp_profile->name);
3560     }
3561 #endif
3562 
3563     if (istls13) {
3564         switch (SSL_get_early_data_status(s)) {
3565         case SSL_EARLY_DATA_NOT_SENT:
3566             BIO_printf(bio, "Early data was not sent\n");
3567             break;
3568 
3569         case SSL_EARLY_DATA_REJECTED:
3570             BIO_printf(bio, "Early data was rejected\n");
3571             break;
3572 
3573         case SSL_EARLY_DATA_ACCEPTED:
3574             BIO_printf(bio, "Early data was accepted\n");
3575             break;
3576 
3577         }
3578 
3579         /*
3580          * We also print the verify results when we dump session information,
3581          * but in TLSv1.3 we may not get that right away (or at all) depending
3582          * on when we get a NewSessionTicket. Therefore, we print it now as well.
3583          */
3584         verify_result = SSL_get_verify_result(s);
3585         BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
3586                    X509_verify_cert_error_string(verify_result));
3587     } else {
3588         /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3589         SSL_SESSION_print(bio, SSL_get_session(s));
3590     }
3591 
3592     if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
3593         BIO_printf(bio, "Keying material exporter:\n");
3594         BIO_printf(bio, "    Label: '%s'\n", keymatexportlabel);
3595         BIO_printf(bio, "    Length: %i bytes\n", keymatexportlen);
3596         exportedkeymat = app_malloc(keymatexportlen, "export key");
3597         if (SSL_export_keying_material(s, exportedkeymat,
3598                                         keymatexportlen,
3599                                         keymatexportlabel,
3600                                         strlen(keymatexportlabel),
3601                                         NULL, 0, 0) <= 0) {
3602             BIO_printf(bio, "    Error\n");
3603         } else {
3604             BIO_printf(bio, "    Keying material: ");
3605             for (i = 0; i < keymatexportlen; i++)
3606                 BIO_printf(bio, "%02X", exportedkeymat[i]);
3607             BIO_printf(bio, "\n");
3608         }
3609         OPENSSL_free(exportedkeymat);
3610     }
3611     BIO_printf(bio, "---\n");
3612     /* flush, or debugging output gets mixed with http response */
3613     (void)BIO_flush(bio);
3614 }
3615 
3616 # ifndef OPENSSL_NO_OCSP
ocsp_resp_cb(SSL * s,void * arg)3617 static int ocsp_resp_cb(SSL *s, void *arg)
3618 {
3619     const unsigned char *p;
3620     int len;
3621     OCSP_RESPONSE *rsp;
3622     len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3623     BIO_puts(arg, "OCSP response: ");
3624     if (p == NULL) {
3625         BIO_puts(arg, "no response sent\n");
3626         return 1;
3627     }
3628     rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3629     if (rsp == NULL) {
3630         BIO_puts(arg, "response parse error\n");
3631         BIO_dump_indent(arg, (char *)p, len, 4);
3632         return 0;
3633     }
3634     BIO_puts(arg, "\n======================================\n");
3635     OCSP_RESPONSE_print(arg, rsp, 0);
3636     BIO_puts(arg, "======================================\n");
3637     OCSP_RESPONSE_free(rsp);
3638     return 1;
3639 }
3640 # endif
3641 
ldap_ExtendedResponse_parse(const char * buf,long rem)3642 static int ldap_ExtendedResponse_parse(const char *buf, long rem)
3643 {
3644     const unsigned char *cur, *end;
3645     long len;
3646     int tag, xclass, inf, ret = -1;
3647 
3648     cur = (const unsigned char *)buf;
3649     end = cur + rem;
3650 
3651     /*
3652      * From RFC 4511:
3653      *
3654      *    LDAPMessage ::= SEQUENCE {
3655      *         messageID       MessageID,
3656      *         protocolOp      CHOICE {
3657      *              ...
3658      *              extendedResp          ExtendedResponse,
3659      *              ... },
3660      *         controls       [0] Controls OPTIONAL }
3661      *
3662      *    ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3663      *         COMPONENTS OF LDAPResult,
3664      *         responseName     [10] LDAPOID OPTIONAL,
3665      *         responseValue    [11] OCTET STRING OPTIONAL }
3666      *
3667      *    LDAPResult ::= SEQUENCE {
3668      *         resultCode         ENUMERATED {
3669      *              success                      (0),
3670      *              ...
3671      *              other                        (80),
3672      *              ...  },
3673      *         matchedDN          LDAPDN,
3674      *         diagnosticMessage  LDAPString,
3675      *         referral           [3] Referral OPTIONAL }
3676      */
3677 
3678     /* pull SEQUENCE */
3679     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3680     if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
3681         (rem = end - cur, len > rem)) {
3682         BIO_printf(bio_err, "Unexpected LDAP response\n");
3683         goto end;
3684     }
3685 
3686     rem = len;  /* ensure that we don't overstep the SEQUENCE */
3687 
3688     /* pull MessageID */
3689     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3690     if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
3691         (rem = end - cur, len > rem)) {
3692         BIO_printf(bio_err, "No MessageID\n");
3693         goto end;
3694     }
3695 
3696     cur += len; /* shall we check for MessageId match or just skip? */
3697 
3698     /* pull [APPLICATION 24] */
3699     rem = end - cur;
3700     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3701     if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
3702         tag != 24) {
3703         BIO_printf(bio_err, "Not ExtendedResponse\n");
3704         goto end;
3705     }
3706 
3707     /* pull resultCode */
3708     rem = end - cur;
3709     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3710     if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
3711         (rem = end - cur, len > rem)) {
3712         BIO_printf(bio_err, "Not LDAPResult\n");
3713         goto end;
3714     }
3715 
3716     /* len should always be one, but just in case... */
3717     for (ret = 0, inf = 0; inf < len; inf++) {
3718         ret <<= 8;
3719         ret |= cur[inf];
3720     }
3721     /* There is more data, but we don't care... */
3722  end:
3723     return ret;
3724 }
3725 
3726 /*
3727  * Host dNS Name verifier: used for checking that the hostname is in dNS format
3728  * before setting it as SNI
3729  */
is_dNS_name(const char * host)3730 static int is_dNS_name(const char *host)
3731 {
3732     const size_t MAX_LABEL_LENGTH = 63;
3733     size_t i;
3734     int isdnsname = 0;
3735     size_t length = strlen(host);
3736     size_t label_length = 0;
3737     int all_numeric = 1;
3738 
3739     /*
3740      * Deviation from strict DNS name syntax, also check names with '_'
3741      * Check DNS name syntax, any '-' or '.' must be internal,
3742      * and on either side of each '.' we can't have a '-' or '.'.
3743      *
3744      * If the name has just one label, we don't consider it a DNS name.
3745      */
3746     for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) {
3747         char c = host[i];
3748 
3749         if ((c >= 'a' && c <= 'z')
3750             || (c >= 'A' && c <= 'Z')
3751             || c == '_') {
3752             label_length += 1;
3753             all_numeric = 0;
3754             continue;
3755         }
3756 
3757         if (c >= '0' && c <= '9') {
3758             label_length += 1;
3759             continue;
3760         }
3761 
3762         /* Dot and hyphen cannot be first or last. */
3763         if (i > 0 && i < length - 1) {
3764             if (c == '-') {
3765                 label_length += 1;
3766                 continue;
3767             }
3768             /*
3769              * Next to a dot the preceding and following characters must not be
3770              * another dot or a hyphen.  Otherwise, record that the name is
3771              * plausible, since it has two or more labels.
3772              */
3773             if (c == '.'
3774                 && host[i + 1] != '.'
3775                 && host[i - 1] != '-'
3776                 && host[i + 1] != '-') {
3777                 label_length = 0;
3778                 isdnsname = 1;
3779                 continue;
3780             }
3781         }
3782         isdnsname = 0;
3783         break;
3784     }
3785 
3786     /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
3787     isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH);
3788 
3789     return isdnsname;
3790 }
3791 
user_data_init(struct user_data_st * user_data,SSL * con,char * buf,size_t bufmax,int mode)3792 static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf,
3793                            size_t bufmax, int mode)
3794 {
3795     user_data->con = con;
3796     user_data->buf = buf;
3797     user_data->bufmax = bufmax;
3798     user_data->buflen = 0;
3799     user_data->bufoff = 0;
3800     user_data->mode = mode;
3801     user_data->isfin = 0;
3802 }
3803 
user_data_add(struct user_data_st * user_data,size_t i)3804 static int user_data_add(struct user_data_st *user_data, size_t i)
3805 {
3806     if (user_data->buflen != 0 || i > user_data->bufmax)
3807         return 0;
3808 
3809     user_data->buflen = i;
3810     user_data->bufoff = 0;
3811 
3812     return 1;
3813 }
3814 
3815 #define USER_COMMAND_HELP        0
3816 #define USER_COMMAND_QUIT        1
3817 #define USER_COMMAND_RECONNECT   2
3818 #define USER_COMMAND_RENEGOTIATE 3
3819 #define USER_COMMAND_KEY_UPDATE  4
3820 #define USER_COMMAND_FIN         5
3821 
user_data_execute(struct user_data_st * user_data,int cmd,char * arg)3822 static int user_data_execute(struct user_data_st *user_data, int cmd, char *arg)
3823 {
3824     switch (cmd) {
3825     case USER_COMMAND_HELP:
3826         /* This only ever occurs in advanced mode, so just emit advanced help */
3827         BIO_printf(bio_err, "Enter text to send to the peer followed by <enter>\n");
3828         BIO_printf(bio_err, "To issue a command insert {cmd} or {cmd:arg} anywhere in the text\n");
3829         BIO_printf(bio_err, "Entering {{ will send { to the peer\n");
3830         BIO_printf(bio_err, "The following commands are available\n");
3831         BIO_printf(bio_err, "  {help}: Get this help text\n");
3832         BIO_printf(bio_err, "  {quit}: Close the connection to the peer\n");
3833         BIO_printf(bio_err, "  {reconnect}: Reconnect to the peer\n");
3834         if (SSL_is_quic(user_data->con)) {
3835             BIO_printf(bio_err, "  {fin}: Send FIN on the stream. No further writing is possible\n");
3836         } else if(SSL_version(user_data->con) == TLS1_3_VERSION) {
3837             BIO_printf(bio_err, "  {keyup:req|noreq}: Send a Key Update message\n");
3838             BIO_printf(bio_err, "                     Arguments:\n");
3839             BIO_printf(bio_err, "                     req   = peer update requested (default)\n");
3840             BIO_printf(bio_err, "                     noreq = peer update not requested\n");
3841         } else {
3842             BIO_printf(bio_err, "  {reneg}: Attempt to renegotiate\n");
3843         }
3844         BIO_printf(bio_err, "\n");
3845         return USER_DATA_PROCESS_NO_DATA;
3846 
3847     case USER_COMMAND_QUIT:
3848         BIO_printf(bio_err, "DONE\n");
3849         return USER_DATA_PROCESS_SHUT;
3850 
3851     case USER_COMMAND_RECONNECT:
3852         BIO_printf(bio_err, "RECONNECTING\n");
3853         do_ssl_shutdown(user_data->con);
3854         SSL_set_connect_state(user_data->con);
3855         BIO_closesocket(SSL_get_fd(user_data->con));
3856         return USER_DATA_PROCESS_RESTART;
3857 
3858     case USER_COMMAND_RENEGOTIATE:
3859         BIO_printf(bio_err, "RENEGOTIATING\n");
3860         if (!SSL_renegotiate(user_data->con))
3861             break;
3862         return USER_DATA_PROCESS_CONTINUE;
3863 
3864     case USER_COMMAND_KEY_UPDATE: {
3865             int updatetype;
3866 
3867             if (OPENSSL_strcasecmp(arg, "req") == 0)
3868                 updatetype = SSL_KEY_UPDATE_REQUESTED;
3869             else if (OPENSSL_strcasecmp(arg, "noreq") == 0)
3870                 updatetype = SSL_KEY_UPDATE_NOT_REQUESTED;
3871             else
3872                 return USER_DATA_PROCESS_BAD_ARGUMENT;
3873             BIO_printf(bio_err, "KEYUPDATE\n");
3874             if (!SSL_key_update(user_data->con, updatetype))
3875                 break;
3876             return USER_DATA_PROCESS_CONTINUE;
3877         }
3878 
3879     case USER_COMMAND_FIN:
3880         if (!SSL_stream_conclude(user_data->con, 0))
3881             break;
3882         user_data->isfin = 1;
3883         return USER_DATA_PROCESS_NO_DATA;
3884 
3885     default:
3886         break;
3887     }
3888 
3889     BIO_printf(bio_err, "ERROR\n");
3890     ERR_print_errors(bio_err);
3891 
3892     return USER_DATA_PROCESS_SHUT;
3893 }
3894 
user_data_process(struct user_data_st * user_data,size_t * len,size_t * off)3895 static int user_data_process(struct user_data_st *user_data, size_t *len,
3896                              size_t *off)
3897 {
3898     char *buf_start = user_data->buf + user_data->bufoff;
3899     size_t outlen = user_data->buflen;
3900 
3901     if (user_data->buflen == 0) {
3902         *len = 0;
3903         *off = 0;
3904         return USER_DATA_PROCESS_NO_DATA;
3905     }
3906 
3907     if (user_data->mode == USER_DATA_MODE_BASIC) {
3908         switch (buf_start[0]) {
3909         case 'Q':
3910             user_data->buflen = user_data->bufoff = *len = *off = 0;
3911             return user_data_execute(user_data, USER_COMMAND_QUIT, NULL);
3912 
3913         case 'C':
3914             user_data->buflen = user_data->bufoff = *len = *off = 0;
3915             return user_data_execute(user_data, USER_COMMAND_RECONNECT, NULL);
3916 
3917         case 'R':
3918             user_data->buflen = user_data->bufoff = *len = *off = 0;
3919             return user_data_execute(user_data, USER_COMMAND_RENEGOTIATE, NULL);
3920 
3921         case 'K':
3922         case 'k':
3923             user_data->buflen = user_data->bufoff = *len = *off = 0;
3924             return user_data_execute(user_data, USER_COMMAND_KEY_UPDATE,
3925                                      buf_start[0] == 'K' ? "req" : "noreq");
3926         default:
3927             break;
3928         }
3929     } else if (user_data->mode == USER_DATA_MODE_ADVANCED) {
3930         char *cmd_start = buf_start;
3931 
3932         cmd_start[outlen] = '\0';
3933         for (;;) {
3934             cmd_start = strchr(cmd_start, '{');
3935             if (cmd_start == buf_start && *(cmd_start + 1) == '{') {
3936                 /* The "{" is escaped, so skip it */
3937                 cmd_start += 2;
3938                 buf_start++;
3939                 user_data->bufoff++;
3940                 user_data->buflen--;
3941                 outlen--;
3942                 continue;
3943             }
3944             break;
3945         }
3946 
3947         if (cmd_start == buf_start) {
3948             /* Command detected */
3949             char *cmd_end = strchr(cmd_start, '}');
3950             char *arg_start;
3951             int cmd = -1, ret = USER_DATA_PROCESS_NO_DATA;
3952             size_t oldoff;
3953 
3954             if (cmd_end == NULL) {
3955                 /* Malformed command */
3956                 cmd_start[outlen - 1] = '\0';
3957                 BIO_printf(bio_err,
3958                            "ERROR PROCESSING COMMAND. REST OF LINE IGNORED: %s\n",
3959                            cmd_start);
3960                 user_data->buflen = user_data->bufoff = *len = *off = 0;
3961                 return USER_DATA_PROCESS_NO_DATA;
3962             }
3963             *cmd_end = '\0';
3964             arg_start = strchr(cmd_start, ':');
3965             if (arg_start != NULL) {
3966                 *arg_start = '\0';
3967                 arg_start++;
3968             }
3969             /* Skip over the { */
3970             cmd_start++;
3971             /*
3972              * Now we have cmd_start pointing to a NUL terminated string for
3973              * the command, and arg_start either being NULL or pointing to a
3974              * NUL terminated string for the argument.
3975              */
3976             if (OPENSSL_strcasecmp(cmd_start, "help") == 0) {
3977                 cmd = USER_COMMAND_HELP;
3978             } else if (OPENSSL_strcasecmp(cmd_start, "quit") == 0) {
3979                 cmd = USER_COMMAND_QUIT;
3980             } else if (OPENSSL_strcasecmp(cmd_start, "reconnect") == 0) {
3981                 cmd = USER_COMMAND_RECONNECT;
3982             } else if(SSL_is_quic(user_data->con)) {
3983                 if (OPENSSL_strcasecmp(cmd_start, "fin") == 0)
3984                     cmd = USER_COMMAND_FIN;
3985             } if (SSL_version(user_data->con) == TLS1_3_VERSION) {
3986                 if (OPENSSL_strcasecmp(cmd_start, "keyup") == 0) {
3987                     cmd = USER_COMMAND_KEY_UPDATE;
3988                     if (arg_start == NULL)
3989                         arg_start = "req";
3990                 }
3991             } else {
3992                 /* (D)TLSv1.2 or below */
3993                 if (OPENSSL_strcasecmp(cmd_start, "reneg") == 0)
3994                     cmd = USER_COMMAND_RENEGOTIATE;
3995             }
3996             if (cmd == -1) {
3997                 BIO_printf(bio_err, "UNRECOGNISED COMMAND (IGNORED): %s\n",
3998                            cmd_start);
3999             } else {
4000                 ret = user_data_execute(user_data, cmd, arg_start);
4001                 if (ret == USER_DATA_PROCESS_BAD_ARGUMENT) {
4002                     BIO_printf(bio_err, "BAD ARGUMENT (COMMAND IGNORED): %s\n",
4003                                arg_start);
4004                     ret = USER_DATA_PROCESS_NO_DATA;
4005                 }
4006             }
4007             oldoff = user_data->bufoff;
4008             user_data->bufoff = (cmd_end - user_data->buf) + 1;
4009             user_data->buflen -= user_data->bufoff - oldoff;
4010             if (user_data->buf + 1 == cmd_start
4011                     && user_data->buflen == 1
4012                     && user_data->buf[user_data->bufoff] == '\n') {
4013                 /*
4014                  * This command was the only thing on the whole line. We
4015                  * suppress the final `\n`
4016                  */
4017                 user_data->bufoff = 0;
4018                 user_data->buflen = 0;
4019             }
4020             *len = *off = 0;
4021             return ret;
4022         } else if (cmd_start != NULL) {
4023             /*
4024              * There is a command on this line, but its not at the start. Output
4025              * the start of the line, and we'll process the command next time
4026              * we call this function
4027              */
4028             outlen = cmd_start - buf_start;
4029         }
4030     }
4031 
4032     if (user_data->isfin) {
4033         user_data->buflen = user_data->bufoff = *len = *off = 0;
4034         return USER_DATA_PROCESS_NO_DATA;
4035     }
4036 
4037 #ifdef CHARSET_EBCDIC
4038     ebcdic2ascii(buf_start, buf_start, outlen);
4039 #endif
4040     *len = outlen;
4041     *off = user_data->bufoff;
4042     user_data->buflen -= outlen;
4043     if (user_data->buflen == 0)
4044         user_data->bufoff = 0;
4045     else
4046         user_data->bufoff += outlen;
4047     return USER_DATA_PROCESS_CONTINUE;
4048 }
4049 
user_data_has_data(struct user_data_st * user_data)4050 static int user_data_has_data(struct user_data_st *user_data)
4051 {
4052     return user_data->buflen > 0;
4053 }
4054 #endif                          /* OPENSSL_NO_SOCK */
4055