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