Fix typo in CONTRIBUTING.md
[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             isquic = 0;
1289             break;
1290         case OPT_TLS1_3:
1291             min_version = TLS1_3_VERSION;
1292             max_version = TLS1_3_VERSION;
1293             socket_type = SOCK_STREAM;
1294 #ifndef OPENSSL_NO_DTLS
1295             isdtls = 0;
1296 #endif
1297             isquic = 0;
1298             break;
1299         case OPT_TLS1_2:
1300             min_version = TLS1_2_VERSION;
1301             max_version = TLS1_2_VERSION;
1302             socket_type = SOCK_STREAM;
1303 #ifndef OPENSSL_NO_DTLS
1304             isdtls = 0;
1305 #endif
1306             isquic = 0;
1307             break;
1308         case OPT_TLS1_1:
1309             min_version = TLS1_1_VERSION;
1310             max_version = TLS1_1_VERSION;
1311             socket_type = SOCK_STREAM;
1312 #ifndef OPENSSL_NO_DTLS
1313             isdtls = 0;
1314 #endif
1315             isquic = 0;
1316             break;
1317         case OPT_TLS1:
1318             min_version = TLS1_VERSION;
1319             max_version = TLS1_VERSION;
1320             socket_type = SOCK_STREAM;
1321 #ifndef OPENSSL_NO_DTLS
1322             isdtls = 0;
1323 #endif
1324             isquic = 0;
1325             break;
1326         case OPT_DTLS:
1327 #ifndef OPENSSL_NO_DTLS
1328             meth = DTLS_client_method();
1329             socket_type = SOCK_DGRAM;
1330             isdtls = 1;
1331             isquic = 0;
1332 #endif
1333             break;
1334         case OPT_DTLS1:
1335 #ifndef OPENSSL_NO_DTLS1
1336             meth = DTLS_client_method();
1337             min_version = DTLS1_VERSION;
1338             max_version = DTLS1_VERSION;
1339             socket_type = SOCK_DGRAM;
1340             isdtls = 1;
1341             isquic = 0;
1342 #endif
1343             break;
1344         case OPT_DTLS1_2:
1345 #ifndef OPENSSL_NO_DTLS1_2
1346             meth = DTLS_client_method();
1347             min_version = DTLS1_2_VERSION;
1348             max_version = DTLS1_2_VERSION;
1349             socket_type = SOCK_DGRAM;
1350             isdtls = 1;
1351             isquic = 0;
1352 #endif
1353             break;
1354         case OPT_QUIC:
1355 #ifndef OPENSSL_NO_QUIC
1356             meth = OSSL_QUIC_client_method();
1357             min_version = 0;
1358             max_version = 0;
1359             socket_type = SOCK_DGRAM;
1360 # ifndef OPENSSL_NO_DTLS
1361             isdtls = 0;
1362 # endif
1363             isquic = 1;
1364 #endif
1365             break;
1366         case OPT_SCTP:
1367 #ifndef OPENSSL_NO_SCTP
1368             protocol = IPPROTO_SCTP;
1369 #endif
1370             break;
1371         case OPT_SCTP_LABEL_BUG:
1372 #ifndef OPENSSL_NO_SCTP
1373             sctp_label_bug = 1;
1374 #endif
1375             break;
1376         case OPT_TIMEOUT:
1377 #ifndef OPENSSL_NO_DTLS
1378             enable_timeouts = 1;
1379 #endif
1380             break;
1381         case OPT_MTU:
1382 #ifndef OPENSSL_NO_DTLS
1383             socket_mtu = atol(opt_arg());
1384 #endif
1385             break;
1386         case OPT_FALLBACKSCSV:
1387             fallback_scsv = 1;
1388             break;
1389         case OPT_KEYFORM:
1390             if (!opt_format(opt_arg(), OPT_FMT_ANY, &key_format))
1391                 goto opthelp;
1392             break;
1393         case OPT_PASS:
1394             passarg = opt_arg();
1395             break;
1396         case OPT_CERT_CHAIN:
1397             chain_file = opt_arg();
1398             break;
1399         case OPT_KEY:
1400             key_file = opt_arg();
1401             break;
1402         case OPT_RECONNECT:
1403             reconnect = 5;
1404             break;
1405         case OPT_CAPATH:
1406             CApath = opt_arg();
1407             break;
1408         case OPT_NOCAPATH:
1409             noCApath = 1;
1410             break;
1411         case OPT_CHAINCAPATH:
1412             chCApath = opt_arg();
1413             break;
1414         case OPT_VERIFYCAPATH:
1415             vfyCApath = opt_arg();
1416             break;
1417         case OPT_BUILD_CHAIN:
1418             build_chain = 1;
1419             break;
1420         case OPT_REQCAFILE:
1421             ReqCAfile = opt_arg();
1422             break;
1423         case OPT_CAFILE:
1424             CAfile = opt_arg();
1425             break;
1426         case OPT_NOCAFILE:
1427             noCAfile = 1;
1428             break;
1429 #ifndef OPENSSL_NO_CT
1430         case OPT_NOCT:
1431             ct_validation = 0;
1432             break;
1433         case OPT_CT:
1434             ct_validation = 1;
1435             break;
1436         case OPT_CTLOG_FILE:
1437             ctlog_file = opt_arg();
1438             break;
1439 #endif
1440         case OPT_CHAINCAFILE:
1441             chCAfile = opt_arg();
1442             break;
1443         case OPT_VERIFYCAFILE:
1444             vfyCAfile = opt_arg();
1445             break;
1446         case OPT_CASTORE:
1447             CAstore = opt_arg();
1448             break;
1449         case OPT_NOCASTORE:
1450             noCAstore = 1;
1451             break;
1452         case OPT_CHAINCASTORE:
1453             chCAstore = opt_arg();
1454             break;
1455         case OPT_VERIFYCASTORE:
1456             vfyCAstore = opt_arg();
1457             break;
1458         case OPT_DANE_TLSA_DOMAIN:
1459             dane_tlsa_domain = opt_arg();
1460             break;
1461         case OPT_DANE_TLSA_RRDATA:
1462             if (dane_tlsa_rrset == NULL)
1463                 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1464             if (dane_tlsa_rrset == NULL ||
1465                 !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1466                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1467                 goto end;
1468             }
1469             break;
1470         case OPT_DANE_EE_NO_NAME:
1471             dane_ee_no_name = 1;
1472             break;
1473         case OPT_NEXTPROTONEG:
1474 #ifndef OPENSSL_NO_NEXTPROTONEG
1475             next_proto_neg_in = opt_arg();
1476 #endif
1477             break;
1478         case OPT_ALPN:
1479             alpn_in = opt_arg();
1480             break;
1481         case OPT_SERVERINFO:
1482             p = opt_arg();
1483             len = strlen(p);
1484             for (start = 0, i = 0; i <= len; ++i) {
1485                 if (i == len || p[i] == ',') {
1486                     serverinfo_types[serverinfo_count] = atoi(p + start);
1487                     if (++serverinfo_count == MAX_SI_TYPES)
1488                         break;
1489                     start = i + 1;
1490                 }
1491             }
1492             break;
1493         case OPT_STARTTLS:
1494             if (!opt_pair(opt_arg(), services, &starttls_proto))
1495                 goto end;
1496             break;
1497         case OPT_TFO:
1498             tfo = 1;
1499             break;
1500         case OPT_SERVERNAME:
1501             servername = opt_arg();
1502             break;
1503         case OPT_NOSERVERNAME:
1504             noservername = 1;
1505             break;
1506         case OPT_USE_SRTP:
1507 #ifndef OPENSSL_NO_SRTP
1508             srtp_profiles = opt_arg();
1509 #endif
1510             break;
1511         case OPT_KEYMATEXPORT:
1512             keymatexportlabel = opt_arg();
1513             break;
1514         case OPT_KEYMATEXPORTLEN:
1515             keymatexportlen = atoi(opt_arg());
1516             break;
1517         case OPT_ASYNC:
1518             async = 1;
1519             break;
1520         case OPT_MAXFRAGLEN:
1521             len = atoi(opt_arg());
1522             switch (len) {
1523             case 512:
1524                 maxfraglen = TLSEXT_max_fragment_length_512;
1525                 break;
1526             case 1024:
1527                 maxfraglen = TLSEXT_max_fragment_length_1024;
1528                 break;
1529             case 2048:
1530                 maxfraglen = TLSEXT_max_fragment_length_2048;
1531                 break;
1532             case 4096:
1533                 maxfraglen = TLSEXT_max_fragment_length_4096;
1534                 break;
1535             default:
1536                 BIO_printf(bio_err,
1537                            "%s: Max Fragment Len %u is out of permitted values",
1538                            prog, len);
1539                 goto opthelp;
1540             }
1541             break;
1542         case OPT_MAX_SEND_FRAG:
1543             max_send_fragment = atoi(opt_arg());
1544             break;
1545         case OPT_SPLIT_SEND_FRAG:
1546             split_send_fragment = atoi(opt_arg());
1547             break;
1548         case OPT_MAX_PIPELINES:
1549             max_pipelines = atoi(opt_arg());
1550             break;
1551         case OPT_READ_BUF:
1552             read_buf_len = atoi(opt_arg());
1553             break;
1554         case OPT_KEYLOG_FILE:
1555             keylog_file = opt_arg();
1556             break;
1557         case OPT_EARLY_DATA:
1558             early_data_file = opt_arg();
1559             break;
1560         case OPT_ENABLE_PHA:
1561             enable_pha = 1;
1562             break;
1563         case OPT_KTLS:
1564 #ifndef OPENSSL_NO_KTLS
1565             enable_ktls = 1;
1566 #endif
1567             break;
1568         case OPT_ENABLE_SERVER_RPK:
1569             enable_server_rpk = 1;
1570             break;
1571         case OPT_ENABLE_CLIENT_RPK:
1572             enable_client_rpk = 1;
1573             break;
1574         }
1575     }
1576
1577     /* Optional argument is connect string if -connect not used. */
1578     if (opt_num_rest() == 1) {
1579         /* Don't allow -connect and a separate argument. */
1580         if (connectstr != NULL) {
1581             BIO_printf(bio_err,
1582                        "%s: cannot provide both -connect option and target parameter\n",
1583                        prog);
1584             goto opthelp;
1585         }
1586         connect_type = use_inet;
1587         freeandcopy(&connectstr, *opt_rest());
1588     } else if (!opt_check_rest_arg(NULL)) {
1589         goto opthelp;
1590     }
1591     if (!app_RAND_load())
1592         goto end;
1593
1594     if (c_ign_eof)
1595         cmdmode = USER_DATA_MODE_NONE;
1596
1597     if (count4or6 >= 2) {
1598         BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1599         goto opthelp;
1600     }
1601     if (noservername) {
1602         if (servername != NULL) {
1603             BIO_printf(bio_err,
1604                        "%s: Can't use -servername and -noservername together\n",
1605                        prog);
1606             goto opthelp;
1607         }
1608         if (dane_tlsa_domain != NULL) {
1609             BIO_printf(bio_err,
1610                "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1611                prog);
1612             goto opthelp;
1613         }
1614     }
1615
1616 #ifndef OPENSSL_NO_NEXTPROTONEG
1617     if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1618         BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1619         goto opthelp;
1620     }
1621 #endif
1622
1623     if (connectstr != NULL) {
1624         int res;
1625         char *tmp_host = host, *tmp_port = port;
1626
1627         res = BIO_parse_hostserv(connectstr, &host, &port, BIO_PARSE_PRIO_HOST);
1628         if (tmp_host != host)
1629             OPENSSL_free(tmp_host);
1630         if (tmp_port != port)
1631             OPENSSL_free(tmp_port);
1632         if (!res) {
1633             BIO_printf(bio_err,
1634                        "%s: -connect argument or target parameter malformed or ambiguous\n",
1635                        prog);
1636             goto end;
1637         }
1638     }
1639
1640     if (proxystr != NULL) {
1641 #ifndef OPENSSL_NO_HTTP
1642         int res;
1643         char *tmp_host = host, *tmp_port = port;
1644
1645         if (host == NULL || port == NULL) {
1646             BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
1647             goto opthelp;
1648         }
1649
1650         if (servername == NULL && !noservername) {
1651             servername = sname_alloc = OPENSSL_strdup(host);
1652             if (sname_alloc == NULL) {
1653                 BIO_printf(bio_err, "%s: out of memory\n", prog);
1654                 goto end;
1655             }
1656         }
1657
1658         /* Retain the original target host:port for use in the HTTP proxy connect string */
1659         thost = OPENSSL_strdup(host);
1660         tport = OPENSSL_strdup(port);
1661         if (thost == NULL || tport == NULL) {
1662             BIO_printf(bio_err, "%s: out of memory\n", prog);
1663             goto end;
1664         }
1665
1666         res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1667         if (tmp_host != host)
1668             OPENSSL_free(tmp_host);
1669         if (tmp_port != port)
1670             OPENSSL_free(tmp_port);
1671         if (!res) {
1672             BIO_printf(bio_err,
1673                        "%s: -proxy argument malformed or ambiguous\n", prog);
1674             goto end;
1675         }
1676 #else
1677         BIO_printf(bio_err,
1678                    "%s: -proxy not supported in no-http build\n", prog);
1679         goto end;
1680 #endif
1681     }
1682
1683
1684     if (bindstr != NULL) {
1685         int res;
1686         res = BIO_parse_hostserv(bindstr, &bindhost, &bindport,
1687                                  BIO_PARSE_PRIO_HOST);
1688         if (!res) {
1689             BIO_printf(bio_err,
1690                        "%s: -bind argument parameter malformed or ambiguous\n",
1691                        prog);
1692             goto end;
1693         }
1694     }
1695
1696 #ifdef AF_UNIX
1697     if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1698         BIO_printf(bio_err,
1699                    "Can't use unix sockets and datagrams together\n");
1700         goto end;
1701     }
1702 #endif
1703
1704 #ifndef OPENSSL_NO_SCTP
1705     if (protocol == IPPROTO_SCTP) {
1706         if (socket_type != SOCK_DGRAM) {
1707             BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1708             goto end;
1709         }
1710         /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1711         socket_type = SOCK_STREAM;
1712     }
1713 #endif
1714
1715 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1716     next_proto.status = -1;
1717     if (next_proto_neg_in) {
1718         next_proto.data =
1719             next_protos_parse(&next_proto.len, next_proto_neg_in);
1720         if (next_proto.data == NULL) {
1721             BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1722             goto end;
1723         }
1724     } else
1725         next_proto.data = NULL;
1726 #endif
1727
1728     if (!app_passwd(passarg, NULL, &pass, NULL)) {
1729         BIO_printf(bio_err, "Error getting private key password\n");
1730         goto end;
1731     }
1732
1733     if (!app_passwd(proxypassarg, NULL, &proxypass, NULL)) {
1734         BIO_printf(bio_err, "Error getting proxy password\n");
1735         goto end;
1736     }
1737
1738     if (proxypass != NULL && proxyuser == NULL) {
1739         BIO_printf(bio_err, "Error: Must specify proxy_user with proxy_pass\n");
1740         goto end;
1741     }
1742
1743     if (key_file == NULL)
1744         key_file = cert_file;
1745
1746     if (key_file != NULL) {
1747         key = load_key(key_file, key_format, 0, pass, e,
1748                        "client certificate private key");
1749         if (key == NULL)
1750             goto end;
1751     }
1752
1753     if (cert_file != NULL) {
1754         cert = load_cert_pass(cert_file, cert_format, 1, pass,
1755                               "client certificate");
1756         if (cert == NULL)
1757             goto end;
1758     }
1759
1760     if (chain_file != NULL) {
1761         if (!load_certs(chain_file, 0, &chain, pass, "client certificate chain"))
1762             goto end;
1763     }
1764
1765     if (crl_file != NULL) {
1766         X509_CRL *crl;
1767         crl = load_crl(crl_file, crl_format, 0, "CRL");
1768         if (crl == NULL)
1769             goto end;
1770         crls = sk_X509_CRL_new_null();
1771         if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1772             BIO_puts(bio_err, "Error adding CRL\n");
1773             ERR_print_errors(bio_err);
1774             X509_CRL_free(crl);
1775             goto end;
1776         }
1777     }
1778
1779     if (!load_excert(&exc))
1780         goto end;
1781
1782     if (bio_c_out == NULL) {
1783         if (c_quiet && !c_debug) {
1784             bio_c_out = BIO_new(BIO_s_null());
1785             if (c_msg && bio_c_msg == NULL) {
1786                 bio_c_msg = dup_bio_out(FORMAT_TEXT);
1787                 if (bio_c_msg == NULL) {
1788                     BIO_printf(bio_err, "Out of memory\n");
1789                     goto end;
1790                 }
1791             }
1792         } else {
1793             bio_c_out = dup_bio_out(FORMAT_TEXT);
1794         }
1795
1796         if (bio_c_out == NULL) {
1797             BIO_printf(bio_err, "Unable to create BIO\n");
1798             goto end;
1799         }
1800     }
1801 #ifndef OPENSSL_NO_SRP
1802     if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1803         BIO_printf(bio_err, "Error getting password\n");
1804         goto end;
1805     }
1806 #endif
1807
1808     ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1809     if (ctx == NULL) {
1810         ERR_print_errors(bio_err);
1811         goto end;
1812     }
1813
1814     SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1815
1816     if (sdebug)
1817         ssl_ctx_security_debug(ctx, sdebug);
1818
1819     if (!config_ctx(cctx, ssl_args, ctx))
1820         goto end;
1821
1822     if (ssl_config != NULL) {
1823         if (SSL_CTX_config(ctx, ssl_config) == 0) {
1824             BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1825                        ssl_config);
1826             ERR_print_errors(bio_err);
1827             goto end;
1828         }
1829     }
1830
1831 #ifndef OPENSSL_NO_SCTP
1832     if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1833         SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1834 #endif
1835
1836     if (min_version != 0
1837         && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1838         goto end;
1839     if (max_version != 0
1840         && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1841         goto end;
1842
1843     if (ignore_unexpected_eof)
1844         SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1845 #ifndef OPENSSL_NO_KTLS
1846     if (enable_ktls)
1847         SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
1848 #endif
1849
1850     if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1851         BIO_printf(bio_err, "Error setting verify params\n");
1852         ERR_print_errors(bio_err);
1853         goto end;
1854     }
1855
1856     if (async) {
1857         SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1858     }
1859
1860     if (max_send_fragment > 0
1861         && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1862         BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1863                    prog, max_send_fragment);
1864         goto end;
1865     }
1866
1867     if (split_send_fragment > 0
1868         && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1869         BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1870                    prog, split_send_fragment);
1871         goto end;
1872     }
1873
1874     if (max_pipelines > 0
1875         && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1876         BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1877                    prog, max_pipelines);
1878         goto end;
1879     }
1880
1881     if (read_buf_len > 0) {
1882         SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1883     }
1884
1885     if (maxfraglen > 0
1886             && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
1887         BIO_printf(bio_err,
1888                    "%s: Max Fragment Length code %u is out of permitted values"
1889                    "\n", prog, maxfraglen);
1890         goto end;
1891     }
1892
1893     if (!ssl_load_stores(ctx,
1894                          vfyCApath, vfyCAfile, vfyCAstore,
1895                          chCApath, chCAfile, chCAstore,
1896                          crls, crl_download)) {
1897         BIO_printf(bio_err, "Error loading store locations\n");
1898         ERR_print_errors(bio_err);
1899         goto end;
1900     }
1901     if (ReqCAfile != NULL) {
1902         STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
1903
1904         if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
1905             sk_X509_NAME_pop_free(nm, X509_NAME_free);
1906             BIO_printf(bio_err, "Error loading CA names\n");
1907             ERR_print_errors(bio_err);
1908             goto end;
1909         }
1910         SSL_CTX_set0_CA_list(ctx, nm);
1911     }
1912 #ifndef OPENSSL_NO_ENGINE
1913     if (ssl_client_engine) {
1914         if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1915             BIO_puts(bio_err, "Error setting client auth engine\n");
1916             ERR_print_errors(bio_err);
1917             release_engine(ssl_client_engine);
1918             goto end;
1919         }
1920         release_engine(ssl_client_engine);
1921     }
1922 #endif
1923
1924 #ifndef OPENSSL_NO_PSK
1925     if (psk_key != NULL) {
1926         if (c_debug)
1927             BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1928         SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1929     }
1930 #endif
1931     if (psksessf != NULL) {
1932         BIO *stmp = BIO_new_file(psksessf, "r");
1933
1934         if (stmp == NULL) {
1935             BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
1936             ERR_print_errors(bio_err);
1937             goto end;
1938         }
1939         psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1940         BIO_free(stmp);
1941         if (psksess == NULL) {
1942             BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
1943             ERR_print_errors(bio_err);
1944             goto end;
1945         }
1946     }
1947     if (psk_key != NULL || psksess != NULL)
1948         SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
1949
1950 #ifndef OPENSSL_NO_SRTP
1951     if (srtp_profiles != NULL) {
1952         /* Returns 0 on success! */
1953         if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1954             BIO_printf(bio_err, "Error setting SRTP profile\n");
1955             ERR_print_errors(bio_err);
1956             goto end;
1957         }
1958     }
1959 #endif
1960
1961     if (exc != NULL)
1962         ssl_ctx_set_excert(ctx, exc);
1963
1964 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1965     if (next_proto.data != NULL)
1966         SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1967 #endif
1968     if (alpn_in) {
1969         size_t alpn_len;
1970         unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1971
1972         if (alpn == NULL) {
1973             BIO_printf(bio_err, "Error parsing -alpn argument\n");
1974             goto end;
1975         }
1976         /* Returns 0 on success! */
1977         if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1978             BIO_printf(bio_err, "Error setting ALPN\n");
1979             goto end;
1980         }
1981         OPENSSL_free(alpn);
1982     }
1983
1984     for (i = 0; i < serverinfo_count; i++) {
1985         if (!SSL_CTX_add_client_custom_ext(ctx,
1986                                            serverinfo_types[i],
1987                                            NULL, NULL, NULL,
1988                                            serverinfo_cli_parse_cb, NULL)) {
1989             BIO_printf(bio_err,
1990                        "Warning: Unable to add custom extension %u, skipping\n",
1991                        serverinfo_types[i]);
1992         }
1993     }
1994
1995     if (state)
1996         SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1997
1998 #ifndef OPENSSL_NO_CT
1999     /* Enable SCT processing, without early connection termination */
2000     if (ct_validation &&
2001         !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
2002         ERR_print_errors(bio_err);
2003         goto end;
2004     }
2005
2006     if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
2007         if (ct_validation) {
2008             ERR_print_errors(bio_err);
2009             goto end;
2010         }
2011
2012         /*
2013          * If CT validation is not enabled, the log list isn't needed so don't
2014          * show errors or abort. We try to load it regardless because then we
2015          * can show the names of the logs any SCTs came from (SCTs may be seen
2016          * even with validation disabled).
2017          */
2018         ERR_clear_error();
2019     }
2020 #endif
2021
2022     SSL_CTX_set_verify(ctx, verify, verify_callback);
2023
2024     if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
2025                                   CAstore, noCAstore)) {
2026         ERR_print_errors(bio_err);
2027         goto end;
2028     }
2029
2030     ssl_ctx_add_crls(ctx, crls, crl_download);
2031
2032     if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
2033         goto end;
2034
2035     if (!noservername) {
2036         tlsextcbp.biodebug = bio_err;
2037         SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2038         SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2039     }
2040 #ifndef OPENSSL_NO_SRP
2041     if (srp_arg.srplogin != NULL
2042             && !set_up_srp_arg(ctx, &srp_arg, srp_lateuser, c_msg, c_debug))
2043         goto end;
2044 # endif
2045
2046     if (dane_tlsa_domain != NULL) {
2047         if (SSL_CTX_dane_enable(ctx) <= 0) {
2048             BIO_printf(bio_err,
2049                        "%s: Error enabling DANE TLSA authentication.\n",
2050                        prog);
2051             ERR_print_errors(bio_err);
2052             goto end;
2053         }
2054     }
2055
2056     /*
2057      * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
2058      * come at any time. Therefore, we use a callback to write out the session
2059      * when we know about it. This approach works for < TLSv1.3 as well.
2060      */
2061     SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT
2062                                         | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2063     SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
2064
2065     if (set_keylog_file(ctx, keylog_file))
2066         goto end;
2067
2068     con = SSL_new(ctx);
2069     if (con == NULL)
2070         goto end;
2071
2072     if (enable_pha)
2073         SSL_set_post_handshake_auth(con, 1);
2074
2075     if (enable_client_rpk)
2076         if (!SSL_set1_client_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
2077             BIO_printf(bio_err, "Error setting client certificate types\n");
2078             goto end;
2079         }
2080     if (enable_server_rpk) {
2081         if (!SSL_set1_server_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
2082             BIO_printf(bio_err, "Error setting server certificate types\n");
2083             goto end;
2084         }
2085     }
2086
2087     if (sess_in != NULL) {
2088         SSL_SESSION *sess;
2089         BIO *stmp = BIO_new_file(sess_in, "r");
2090         if (stmp == NULL) {
2091             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2092             ERR_print_errors(bio_err);
2093             goto end;
2094         }
2095         sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2096         BIO_free(stmp);
2097         if (sess == NULL) {
2098             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
2099             ERR_print_errors(bio_err);
2100             goto end;
2101         }
2102         if (!SSL_set_session(con, sess)) {
2103             BIO_printf(bio_err, "Can't set session\n");
2104             ERR_print_errors(bio_err);
2105             goto end;
2106         }
2107
2108         SSL_SESSION_free(sess);
2109     }
2110
2111     if (fallback_scsv)
2112         SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
2113
2114     if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
2115         if (servername == NULL) {
2116             if (host == NULL || is_dNS_name(host))
2117                 servername = (host == NULL) ? "localhost" : host;
2118         }
2119         if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) {
2120             BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
2121             ERR_print_errors(bio_err);
2122             goto end;
2123         }
2124     }
2125
2126     if (dane_tlsa_domain != NULL) {
2127         if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
2128             BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
2129                        "authentication.\n", prog);
2130             ERR_print_errors(bio_err);
2131             goto end;
2132         }
2133         if (dane_tlsa_rrset == NULL) {
2134             BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
2135                        "least one -dane_tlsa_rrdata option.\n", prog);
2136             goto end;
2137         }
2138         if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
2139             BIO_printf(bio_err, "%s: Failed to import any TLSA "
2140                        "records.\n", prog);
2141             goto end;
2142         }
2143         if (dane_ee_no_name)
2144             SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
2145     } else if (dane_tlsa_rrset != NULL) {
2146         BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
2147                    "-dane_tlsa_domain option.\n", prog);
2148         goto end;
2149     }
2150 #ifndef OPENSSL_NO_DTLS
2151     if (isdtls && tfo) {
2152         BIO_printf(bio_err, "%s: DTLS does not support the -tfo option\n", prog);
2153         goto end;
2154     }
2155 #endif
2156 #ifndef OPENSSL_NO_QUIC
2157     if (isquic && tfo) {
2158         BIO_printf(bio_err, "%s: QUIC does not support the -tfo option\n", prog);
2159         goto end;
2160     }
2161     if (isquic && alpn_in == NULL) {
2162         BIO_printf(bio_err, "%s: QUIC requires ALPN to be specified (e.g. \"h3\" for HTTP/3) via the -alpn option\n", prog);
2163         goto end;
2164     }
2165 #endif
2166
2167     if (tfo)
2168         BIO_printf(bio_c_out, "Connecting via TFO\n");
2169  re_start:
2170     if (init_client(&sock, host, port, bindhost, bindport, socket_family,
2171                     socket_type, protocol, tfo, !isquic, &peer_addr) == 0) {
2172         BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
2173         BIO_closesocket(sock);
2174         goto end;
2175     }
2176     BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock);
2177
2178     /*
2179      * QUIC always uses a non-blocking socket - and we have to switch on
2180      * non-blocking mode at the SSL level
2181      */
2182     if (c_nbio || isquic) {
2183         if (!BIO_socket_nbio(sock, 1)) {
2184             ERR_print_errors(bio_err);
2185             goto end;
2186         }
2187         if (c_nbio) {
2188             if (isquic && !SSL_set_blocking_mode(con, 0))
2189                 goto end;
2190             BIO_printf(bio_c_out, "Turned on non blocking io\n");
2191         }
2192     }
2193 #ifndef OPENSSL_NO_DTLS
2194     if (isdtls) {
2195         union BIO_sock_info_u peer_info;
2196
2197 #ifndef OPENSSL_NO_SCTP
2198         if (protocol == IPPROTO_SCTP)
2199             sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
2200         else
2201 #endif
2202             sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
2203
2204         if (sbio == NULL || (peer_info.addr = BIO_ADDR_new()) == NULL) {
2205             BIO_printf(bio_err, "memory allocation failure\n");
2206             BIO_free(sbio);
2207             BIO_closesocket(sock);
2208             goto end;
2209         }
2210         if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
2211             BIO_printf(bio_err, "getsockname:errno=%d\n",
2212                        get_last_socket_error());
2213             BIO_free(sbio);
2214             BIO_ADDR_free(peer_info.addr);
2215             BIO_closesocket(sock);
2216             goto end;
2217         }
2218
2219         (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
2220         BIO_ADDR_free(peer_info.addr);
2221         peer_info.addr = NULL;
2222
2223         if (enable_timeouts) {
2224             timeout.tv_sec = 0;
2225             timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2226             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2227
2228             timeout.tv_sec = 0;
2229             timeout.tv_usec = DGRAM_SND_TIMEOUT;
2230             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2231         }
2232
2233         if (socket_mtu) {
2234             if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2235                 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2236                            DTLS_get_link_min_mtu(con));
2237                 BIO_free(sbio);
2238                 goto shut;
2239             }
2240             SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2241             if (!DTLS_set_link_mtu(con, socket_mtu)) {
2242                 BIO_printf(bio_err, "Failed to set MTU\n");
2243                 BIO_free(sbio);
2244                 goto shut;
2245             }
2246         } else {
2247             /* want to do MTU discovery */
2248             BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2249         }
2250     } else
2251 #endif /* OPENSSL_NO_DTLS */
2252 #ifndef OPENSSL_NO_QUIC
2253     if (isquic) {
2254         sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
2255         if (!SSL_set1_initial_peer_addr(con, peer_addr)) {
2256             BIO_printf(bio_err, "Failed to set the initial peer address\n");
2257             goto shut;
2258         }
2259     } else
2260 #endif
2261         sbio = BIO_new_socket(sock, BIO_NOCLOSE);
2262
2263     if (sbio == NULL) {
2264         BIO_printf(bio_err, "Unable to create BIO\n");
2265         ERR_print_errors(bio_err);
2266         BIO_closesocket(sock);
2267         goto end;
2268     }
2269
2270     /* Now that we're using a BIO... */
2271     if (tfo) {
2272         (void)BIO_set_conn_address(sbio, peer_addr);
2273         (void)BIO_set_tfo(sbio, 1);
2274     }
2275
2276     if (nbio_test) {
2277         BIO *test;
2278
2279         test = BIO_new(BIO_f_nbio_test());
2280         if (test == NULL) {
2281             BIO_printf(bio_err, "Unable to create BIO\n");
2282             BIO_free(sbio);
2283             goto shut;
2284         }
2285         sbio = BIO_push(test, sbio);
2286     }
2287
2288     if (c_debug) {
2289         BIO_set_callback_ex(sbio, bio_dump_callback);
2290         BIO_set_callback_arg(sbio, (char *)bio_c_out);
2291     }
2292     if (c_msg) {
2293 #ifndef OPENSSL_NO_SSL_TRACE
2294         if (c_msg == 2)
2295             SSL_set_msg_callback(con, SSL_trace);
2296         else
2297 #endif
2298             SSL_set_msg_callback(con, msg_cb);
2299         SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
2300     }
2301
2302     if (c_tlsextdebug) {
2303         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2304         SSL_set_tlsext_debug_arg(con, bio_c_out);
2305     }
2306 #ifndef OPENSSL_NO_OCSP
2307     if (c_status_req) {
2308         SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
2309         SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
2310         SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
2311     }
2312 #endif
2313
2314     SSL_set_bio(con, sbio, sbio);
2315     SSL_set_connect_state(con);
2316
2317     /* ok, lets connect */
2318     if (fileno_stdin() > SSL_get_fd(con))
2319         width = fileno_stdin() + 1;
2320     else
2321         width = SSL_get_fd(con) + 1;
2322
2323     read_tty = 1;
2324     write_tty = 0;
2325     tty_on = 0;
2326     read_ssl = 1;
2327     write_ssl = 1;
2328     first_loop = 1;
2329
2330     cbuf_len = 0;
2331     cbuf_off = 0;
2332     sbuf_len = 0;
2333     sbuf_off = 0;
2334
2335 #ifndef OPENSSL_NO_HTTP
2336     if (proxystr != NULL) {
2337         /* Here we must use the connect string target host & port */
2338         if (!OSSL_HTTP_proxy_connect(sbio, thost, tport, proxyuser, proxypass,
2339                                      0 /* no timeout */, bio_err, prog))
2340             goto shut;
2341     }
2342 #endif
2343
2344     switch ((PROTOCOL_CHOICE) starttls_proto) {
2345     case PROTO_OFF:
2346         break;
2347     case PROTO_LMTP:
2348     case PROTO_SMTP:
2349         {
2350             /*
2351              * This is an ugly hack that does a lot of assumptions. We do
2352              * have to handle multi-line responses which may come in a single
2353              * packet or not. We therefore have to use BIO_gets() which does
2354              * need a buffering BIO. So during the initial chitchat we do
2355              * push a buffering BIO into the chain that is removed again
2356              * later on to not disturb the rest of the s_client operation.
2357              */
2358             int foundit = 0;
2359             BIO *fbio = BIO_new(BIO_f_buffer());
2360
2361             if (fbio == NULL) {
2362                 BIO_printf(bio_err, "Unable to create BIO\n");
2363                 goto shut;
2364             }
2365             BIO_push(fbio, sbio);
2366             /* Wait for multi-line response to end from LMTP or SMTP */
2367             do {
2368                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2369             } while (mbuf_len > 3 && mbuf[3] == '-');
2370             if (protohost == NULL)
2371                 protohost = "mail.example.com";
2372             if (starttls_proto == (int)PROTO_LMTP)
2373                 BIO_printf(fbio, "LHLO %s\r\n", protohost);
2374             else
2375                 BIO_printf(fbio, "EHLO %s\r\n", protohost);
2376             (void)BIO_flush(fbio);
2377             /*
2378              * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2379              * response.
2380              */
2381             do {
2382                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2383                 if (strstr(mbuf, "STARTTLS"))
2384                     foundit = 1;
2385             } while (mbuf_len > 3 && mbuf[3] == '-');
2386             (void)BIO_flush(fbio);
2387             BIO_pop(fbio);
2388             BIO_free(fbio);
2389             if (!foundit)
2390                 BIO_printf(bio_err,
2391                            "Didn't find STARTTLS in server response,"
2392                            " trying anyway...\n");
2393             BIO_printf(sbio, "STARTTLS\r\n");
2394             BIO_read(sbio, sbuf, BUFSIZZ);
2395         }
2396         break;
2397     case PROTO_POP3:
2398         {
2399             BIO_read(sbio, mbuf, BUFSIZZ);
2400             BIO_printf(sbio, "STLS\r\n");
2401             mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
2402             if (mbuf_len < 0) {
2403                 BIO_printf(bio_err, "BIO_read failed\n");
2404                 goto end;
2405             }
2406         }
2407         break;
2408     case PROTO_IMAP:
2409         {
2410             int foundit = 0;
2411             BIO *fbio = BIO_new(BIO_f_buffer());
2412
2413             if (fbio == NULL) {
2414                 BIO_printf(bio_err, "Unable to create BIO\n");
2415                 goto shut;
2416             }
2417             BIO_push(fbio, sbio);
2418             BIO_gets(fbio, mbuf, BUFSIZZ);
2419             /* STARTTLS command requires CAPABILITY... */
2420             BIO_printf(fbio, ". CAPABILITY\r\n");
2421             (void)BIO_flush(fbio);
2422             /* wait for multi-line CAPABILITY response */
2423             do {
2424                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2425                 if (strstr(mbuf, "STARTTLS"))
2426                     foundit = 1;
2427             }
2428             while (mbuf_len > 3 && mbuf[0] != '.');
2429             (void)BIO_flush(fbio);
2430             BIO_pop(fbio);
2431             BIO_free(fbio);
2432             if (!foundit)
2433                 BIO_printf(bio_err,
2434                            "Didn't find STARTTLS in server response,"
2435                            " trying anyway...\n");
2436             BIO_printf(sbio, ". STARTTLS\r\n");
2437             BIO_read(sbio, sbuf, BUFSIZZ);
2438         }
2439         break;
2440     case PROTO_FTP:
2441         {
2442             BIO *fbio = BIO_new(BIO_f_buffer());
2443
2444             if (fbio == NULL) {
2445                 BIO_printf(bio_err, "Unable to create BIO\n");
2446                 goto shut;
2447             }
2448             BIO_push(fbio, sbio);
2449             /* wait for multi-line response to end from FTP */
2450             do {
2451                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2452             }
2453             while (mbuf_len > 3 && (!isdigit((unsigned char)mbuf[0]) || !isdigit((unsigned char)mbuf[1]) || !isdigit((unsigned char)mbuf[2]) || mbuf[3] != ' '));
2454             (void)BIO_flush(fbio);
2455             BIO_pop(fbio);
2456             BIO_free(fbio);
2457             BIO_printf(sbio, "AUTH TLS\r\n");
2458             BIO_read(sbio, sbuf, BUFSIZZ);
2459         }
2460         break;
2461     case PROTO_XMPP:
2462     case PROTO_XMPP_SERVER:
2463         {
2464             int seen = 0;
2465             BIO_printf(sbio, "<stream:stream "
2466                        "xmlns:stream='http://etherx.jabber.org/streams' "
2467                        "xmlns='jabber:%s' to='%s' version='1.0'>",
2468                        starttls_proto == PROTO_XMPP ? "client" : "server",
2469                        protohost ? protohost : host);
2470             seen = BIO_read(sbio, mbuf, BUFSIZZ);
2471             if (seen < 0) {
2472                 BIO_printf(bio_err, "BIO_read failed\n");
2473                 goto end;
2474             }
2475             mbuf[seen] = '\0';
2476             while (!strstr
2477                    (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2478                    && !strstr(mbuf,
2479                               "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2480             {
2481                 seen = BIO_read(sbio, mbuf, BUFSIZZ);
2482
2483                 if (seen <= 0)
2484                     goto shut;
2485
2486                 mbuf[seen] = '\0';
2487             }
2488             BIO_printf(sbio,
2489                        "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2490             seen = BIO_read(sbio, sbuf, BUFSIZZ);
2491             if (seen < 0) {
2492                 BIO_printf(bio_err, "BIO_read failed\n");
2493                 goto shut;
2494             }
2495             sbuf[seen] = '\0';
2496             if (!strstr(sbuf, "<proceed"))
2497                 goto shut;
2498             mbuf[0] = '\0';
2499         }
2500         break;
2501     case PROTO_TELNET:
2502         {
2503             static const unsigned char tls_do[] = {
2504                 /* IAC    DO   START_TLS */
2505                    255,   253, 46
2506             };
2507             static const unsigned char tls_will[] = {
2508                 /* IAC  WILL START_TLS */
2509                    255, 251, 46
2510             };
2511             static const unsigned char tls_follows[] = {
2512                 /* IAC  SB   START_TLS FOLLOWS IAC  SE */
2513                    255, 250, 46,       1,      255, 240
2514             };
2515             int bytes;
2516
2517             /* Telnet server should demand we issue START_TLS */
2518             bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2519             if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
2520                 goto shut;
2521             /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2522             BIO_write(sbio, tls_will, 3);
2523             BIO_write(sbio, tls_follows, 6);
2524             (void)BIO_flush(sbio);
2525             /* Telnet server also sent the FOLLOWS sub-command */
2526             bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2527             if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2528                 goto shut;
2529         }
2530         break;
2531     case PROTO_IRC:
2532         {
2533             int numeric;
2534             BIO *fbio = BIO_new(BIO_f_buffer());
2535
2536             if (fbio == NULL) {
2537                 BIO_printf(bio_err, "Unable to create BIO\n");
2538                 goto end;
2539             }
2540             BIO_push(fbio, sbio);
2541             BIO_printf(fbio, "STARTTLS\r\n");
2542             (void)BIO_flush(fbio);
2543             width = SSL_get_fd(con) + 1;
2544
2545             do {
2546                 numeric = 0;
2547
2548                 FD_ZERO(&readfds);
2549                 openssl_fdset(SSL_get_fd(con), &readfds);
2550                 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2551                 timeout.tv_usec = 0;
2552                 /*
2553                  * If the IRCd doesn't respond within
2554                  * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2555                  * it doesn't support STARTTLS. Many IRCds
2556                  * will not give _any_ sort of response to a
2557                  * STARTTLS command when it's not supported.
2558                  */
2559                 if (!BIO_get_buffer_num_lines(fbio)
2560                     && !BIO_pending(fbio)
2561                     && !BIO_pending(sbio)
2562                     && select(width, (void *)&readfds, NULL, NULL,
2563                               &timeout) < 1) {
2564                     BIO_printf(bio_err,
2565                                "Timeout waiting for response (%d seconds).\n",
2566                                S_CLIENT_IRC_READ_TIMEOUT);
2567                     break;
2568                 }
2569
2570                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2571                 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2572                     break;
2573                 /* :example.net 451 STARTTLS :You have not registered */
2574                 /* :example.net 421 STARTTLS :Unknown command */
2575                 if ((numeric == 451 || numeric == 421)
2576                     && strstr(mbuf, "STARTTLS") != NULL) {
2577                     BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2578                     break;
2579                 }
2580                 if (numeric == 691) {
2581                     BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2582                     ERR_print_errors(bio_err);
2583                     break;
2584                 }
2585             } while (numeric != 670);
2586
2587             (void)BIO_flush(fbio);
2588             BIO_pop(fbio);
2589             BIO_free(fbio);
2590             if (numeric != 670) {
2591                 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2592                 ret = 1;
2593                 goto shut;
2594             }
2595         }
2596         break;
2597     case PROTO_MYSQL:
2598         {
2599             /* SSL request packet */
2600             static const unsigned char ssl_req[] = {
2601                 /* payload_length,   sequence_id */
2602                    0x20, 0x00, 0x00, 0x01,
2603                 /* payload */
2604                 /* capability flags, CLIENT_SSL always set */
2605                    0x85, 0xae, 0x7f, 0x00,
2606                 /* max-packet size */
2607                    0x00, 0x00, 0x00, 0x01,
2608                 /* character set */
2609                    0x21,
2610                 /* string[23] reserved (all [0]) */
2611                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2612                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2613                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2614             };
2615             int bytes = 0;
2616             int ssl_flg = 0x800;
2617             int pos;
2618             const unsigned char *packet = (const unsigned char *)sbuf;
2619
2620             /* Receiving Initial Handshake packet. */
2621             bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
2622             if (bytes < 0) {
2623                 BIO_printf(bio_err, "BIO_read failed\n");
2624                 goto shut;
2625             /* Packet length[3], Packet number[1] + minimum payload[17] */
2626             } else if (bytes < 21) {
2627                 BIO_printf(bio_err, "MySQL packet too short.\n");
2628                 goto shut;
2629             } else if (bytes != (4 + packet[0] +
2630                                  (packet[1] << 8) +
2631                                  (packet[2] << 16))) {
2632                 BIO_printf(bio_err, "MySQL packet length does not match.\n");
2633                 goto shut;
2634             /* protocol version[1] */
2635             } else if (packet[4] != 0xA) {
2636                 BIO_printf(bio_err,
2637                            "Only MySQL protocol version 10 is supported.\n");
2638                 goto shut;
2639             }
2640
2641             pos = 5;
2642             /* server version[string+NULL] */
2643             for (;;) {
2644                 if (pos >= bytes) {
2645                     BIO_printf(bio_err, "Cannot confirm server version. ");
2646                     goto shut;
2647                 } else if (packet[pos++] == '\0') {
2648                     break;
2649                 }
2650             }
2651
2652             /* make sure we have at least 15 bytes left in the packet */
2653             if (pos + 15 > bytes) {
2654                 BIO_printf(bio_err,
2655                            "MySQL server handshake packet is broken.\n");
2656                 goto shut;
2657             }
2658
2659             pos += 12; /* skip over conn id[4] + SALT[8] */
2660             if (packet[pos++] != '\0') { /* verify filler */
2661                 BIO_printf(bio_err,
2662                            "MySQL packet is broken.\n");
2663                 goto shut;
2664             }
2665
2666             /* capability flags[2] */
2667             if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
2668                 BIO_printf(bio_err, "MySQL server does not support SSL.\n");
2669                 goto shut;
2670             }
2671
2672             /* Sending SSL Handshake packet. */
2673             BIO_write(sbio, ssl_req, sizeof(ssl_req));
2674             (void)BIO_flush(sbio);
2675         }
2676         break;
2677     case PROTO_POSTGRES:
2678         {
2679             static const unsigned char ssl_request[] = {
2680                 /* Length        SSLRequest */
2681                    0, 0, 0, 8,   4, 210, 22, 47
2682             };
2683             int bytes;
2684
2685             /* Send SSLRequest packet */
2686             BIO_write(sbio, ssl_request, 8);
2687             (void)BIO_flush(sbio);
2688
2689             /* Reply will be a single S if SSL is enabled */
2690             bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2691             if (bytes != 1 || sbuf[0] != 'S')
2692                 goto shut;
2693         }
2694         break;
2695     case PROTO_NNTP:
2696         {
2697             int foundit = 0;
2698             BIO *fbio = BIO_new(BIO_f_buffer());
2699
2700             if (fbio == NULL) {
2701                 BIO_printf(bio_err, "Unable to create BIO\n");
2702                 goto end;
2703             }
2704             BIO_push(fbio, sbio);
2705             BIO_gets(fbio, mbuf, BUFSIZZ);
2706             /* STARTTLS command requires CAPABILITIES... */
2707             BIO_printf(fbio, "CAPABILITIES\r\n");
2708             (void)BIO_flush(fbio);
2709             BIO_gets(fbio, mbuf, BUFSIZZ);
2710             /* no point in trying to parse the CAPABILITIES response if there is none */
2711             if (strstr(mbuf, "101") != NULL) {
2712                 /* wait for multi-line CAPABILITIES response */
2713                 do {
2714                     mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2715                     if (strstr(mbuf, "STARTTLS"))
2716                         foundit = 1;
2717                 } while (mbuf_len > 1 && mbuf[0] != '.');
2718             }
2719             (void)BIO_flush(fbio);
2720             BIO_pop(fbio);
2721             BIO_free(fbio);
2722             if (!foundit)
2723                 BIO_printf(bio_err,
2724                            "Didn't find STARTTLS in server response,"
2725                            " trying anyway...\n");
2726             BIO_printf(sbio, "STARTTLS\r\n");
2727             mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2728             if (mbuf_len < 0) {
2729                 BIO_printf(bio_err, "BIO_read failed\n");
2730                 goto end;
2731             }
2732             mbuf[mbuf_len] = '\0';
2733             if (strstr(mbuf, "382") == NULL) {
2734                 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2735                 goto shut;
2736             }
2737         }
2738         break;
2739     case PROTO_SIEVE:
2740         {
2741             int foundit = 0;
2742             BIO *fbio = BIO_new(BIO_f_buffer());
2743
2744             if (fbio == NULL) {
2745                 BIO_printf(bio_err, "Unable to create BIO\n");
2746                 goto end;
2747             }
2748             BIO_push(fbio, sbio);
2749             /* wait for multi-line response to end from Sieve */
2750             do {
2751                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2752                 /*
2753                  * According to RFC 5804 Â§ 1.7, capability
2754                  * is case-insensitive, make it uppercase
2755                  */
2756                 if (mbuf_len > 1 && mbuf[0] == '"') {
2757                     make_uppercase(mbuf);
2758                     if (HAS_PREFIX(mbuf, "\"STARTTLS\""))
2759                         foundit = 1;
2760                 }
2761             } while (mbuf_len > 1 && mbuf[0] == '"');
2762             (void)BIO_flush(fbio);
2763             BIO_pop(fbio);
2764             BIO_free(fbio);
2765             if (!foundit)
2766                 BIO_printf(bio_err,
2767                            "Didn't find STARTTLS in server response,"
2768                            " trying anyway...\n");
2769             BIO_printf(sbio, "STARTTLS\r\n");
2770             mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2771             if (mbuf_len < 0) {
2772                 BIO_printf(bio_err, "BIO_read failed\n");
2773                 goto end;
2774             }
2775             mbuf[mbuf_len] = '\0';
2776             if (mbuf_len < 2) {
2777                 BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2778                 goto shut;
2779             }
2780             /*
2781              * According to RFC 5804 Â§ 2.2, response codes are case-
2782              * insensitive, make it uppercase but preserve the response.
2783              */
2784             strncpy(sbuf, mbuf, 2);
2785             make_uppercase(sbuf);
2786             if (!HAS_PREFIX(sbuf, "OK")) {
2787                 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2788                 goto shut;
2789             }
2790         }
2791         break;
2792     case PROTO_LDAP:
2793         {
2794             /* StartTLS Operation according to RFC 4511 */
2795             static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
2796                 "[LDAPMessage]\n"
2797                 "messageID=INTEGER:1\n"
2798                 "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2799                 "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2800             long errline = -1;
2801             char *genstr = NULL;
2802             int result = -1;
2803             ASN1_TYPE *atyp = NULL;
2804             BIO *ldapbio = BIO_new(BIO_s_mem());
2805             CONF *cnf = NCONF_new(NULL);
2806
2807             if (ldapbio == NULL || cnf == NULL) {
2808                 BIO_free(ldapbio);
2809                 NCONF_free(cnf);
2810                 goto end;
2811             }
2812             BIO_puts(ldapbio, ldap_tls_genconf);
2813             if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
2814                 BIO_free(ldapbio);
2815                 NCONF_free(cnf);
2816                 if (errline <= 0) {
2817                     BIO_printf(bio_err, "NCONF_load_bio failed\n");
2818                     goto end;
2819                 } else {
2820                     BIO_printf(bio_err, "Error on line %ld\n", errline);
2821                     goto end;
2822                 }
2823             }
2824             BIO_free(ldapbio);
2825             genstr = NCONF_get_string(cnf, "default", "asn1");
2826             if (genstr == NULL) {
2827                 NCONF_free(cnf);
2828                 BIO_printf(bio_err, "NCONF_get_string failed\n");
2829                 goto end;
2830             }
2831             atyp = ASN1_generate_nconf(genstr, cnf);
2832             if (atyp == NULL) {
2833                 NCONF_free(cnf);
2834                 BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
2835                 goto end;
2836             }
2837             NCONF_free(cnf);
2838
2839             /* Send SSLRequest packet */
2840             BIO_write(sbio, atyp->value.sequence->data,
2841                       atyp->value.sequence->length);
2842             (void)BIO_flush(sbio);
2843             ASN1_TYPE_free(atyp);
2844
2845             mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2846             if (mbuf_len < 0) {
2847                 BIO_printf(bio_err, "BIO_read failed\n");
2848                 goto end;
2849             }
2850             result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
2851             if (result < 0) {
2852                 BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
2853                 goto shut;
2854             } else if (result > 0) {
2855                 BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
2856                            result);
2857                 goto shut;
2858             }
2859             mbuf_len = 0;
2860         }
2861         break;
2862     }
2863
2864     if (early_data_file != NULL
2865             && ((SSL_get0_session(con) != NULL
2866                  && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
2867                 || (psksess != NULL
2868                     && SSL_SESSION_get_max_early_data(psksess) > 0))) {
2869         BIO *edfile = BIO_new_file(early_data_file, "r");
2870         size_t readbytes, writtenbytes;
2871         int finish = 0;
2872
2873         if (edfile == NULL) {
2874             BIO_printf(bio_err, "Cannot open early data file\n");
2875             goto shut;
2876         }
2877
2878         while (!finish) {
2879             if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
2880                 finish = 1;
2881
2882             while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
2883                 switch (SSL_get_error(con, 0)) {
2884                 case SSL_ERROR_WANT_WRITE:
2885                 case SSL_ERROR_WANT_ASYNC:
2886                 case SSL_ERROR_WANT_READ:
2887                     /* Just keep trying - busy waiting */
2888                     continue;
2889                 default:
2890                     BIO_printf(bio_err, "Error writing early data\n");
2891                     BIO_free(edfile);
2892                     ERR_print_errors(bio_err);
2893                     goto shut;
2894                 }
2895             }
2896         }
2897
2898         BIO_free(edfile);
2899     }
2900
2901     user_data_init(&user_data, con, cbuf, BUFSIZZ, cmdmode);
2902     for (;;) {
2903         FD_ZERO(&readfds);
2904         FD_ZERO(&writefds);
2905
2906         if ((isdtls || isquic)
2907             && SSL_get_event_timeout(con, &timeout, &is_infinite)
2908             && !is_infinite)
2909             timeoutp = &timeout;
2910         else
2911             timeoutp = NULL;
2912
2913         if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
2914                 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
2915             in_init = 1;
2916             tty_on = 0;
2917         } else {
2918             tty_on = 1;
2919             if (in_init) {
2920                 in_init = 0;
2921                 if (c_brief) {
2922                     BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2923                     print_ssl_summary(con);
2924                 }
2925
2926                 print_stuff(bio_c_out, con, full_log);
2927                 if (full_log > 0)
2928                     full_log--;
2929
2930                 if (starttls_proto) {
2931                     BIO_write(bio_err, mbuf, mbuf_len);
2932                     /* We don't need to know any more */
2933                     if (!reconnect)
2934                         starttls_proto = PROTO_OFF;
2935                 }
2936
2937                 if (reconnect) {
2938                     reconnect--;
2939                     BIO_printf(bio_c_out,
2940                                "drop connection and then reconnect\n");
2941                     do_ssl_shutdown(con);
2942                     SSL_set_connect_state(con);
2943                     BIO_closesocket(SSL_get_fd(con));
2944                     goto re_start;
2945                 }
2946             }
2947         }
2948
2949         if (!write_ssl) {
2950             do {
2951                 switch (user_data_process(&user_data, &cbuf_len, &cbuf_off)) {
2952                 default:
2953                     BIO_printf(bio_err, "ERROR\n");
2954                     /* fall through */
2955                 case USER_DATA_PROCESS_SHUT:
2956                     ret = 0;
2957                     goto shut;
2958
2959                 case USER_DATA_PROCESS_RESTART:
2960                     goto re_start;
2961
2962                 case USER_DATA_PROCESS_NO_DATA:
2963                     break;
2964
2965                 case USER_DATA_PROCESS_CONTINUE:
2966                     write_ssl = 1;
2967                     break;
2968                 }
2969             } while (!write_ssl
2970                      && cbuf_len == 0
2971                      && user_data_has_data(&user_data));
2972             if (cbuf_len > 0) {
2973                 read_tty = 0;
2974                 timeout.tv_sec = 0;
2975                 timeout.tv_usec = 0;
2976             } else {
2977                 read_tty = 1;
2978             }
2979         }
2980
2981         ssl_pending = read_ssl && SSL_has_pending(con);
2982
2983         if (!ssl_pending) {
2984 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2985             if (tty_on) {
2986                 /*
2987                  * Note that select() returns when read _would not block_,
2988                  * and EOF satisfies that.  To avoid a CPU-hogging loop,
2989                  * set the flag so we exit.
2990                  */
2991                 if (read_tty && !at_eof)
2992                     openssl_fdset(fileno_stdin(), &readfds);
2993 #if !defined(OPENSSL_SYS_VMS)
2994                 if (write_tty)
2995                     openssl_fdset(fileno_stdout(), &writefds);
2996 #endif
2997             }
2998
2999             /*
3000              * Note that for QUIC we never actually check FD_ISSET() for the
3001              * underlying network fds. We just rely on select waking up when
3002              * they become readable/writeable and then SSL_handle_events() doing
3003              * the right thing.
3004              */
3005             if ((!isquic && read_ssl)
3006                     || (isquic && SSL_net_read_desired(con)))
3007                 openssl_fdset(SSL_get_fd(con), &readfds);
3008             if ((!isquic && write_ssl)
3009                     || (isquic && (first_loop || SSL_net_write_desired(con))))
3010                 openssl_fdset(SSL_get_fd(con), &writefds);
3011 #else
3012             if (!tty_on || !write_tty) {
3013                 if ((!isquic && read_ssl)
3014                         || (isquic && SSL_net_read_desired(con)))
3015                     openssl_fdset(SSL_get_fd(con), &readfds);
3016                 if ((!isquic && write_ssl)
3017                         || (isquic && (first_loop || SSL_net_write_desired(con))))
3018                     openssl_fdset(SSL_get_fd(con), &writefds);
3019             }
3020 #endif
3021
3022             /*
3023              * Note: under VMS with SOCKETSHR the second parameter is
3024              * currently of type (int *) whereas under other systems it is
3025              * (void *) if you don't have a cast it will choke the compiler:
3026              * if you do have a cast then you can either go for (int *) or
3027              * (void *).
3028              */
3029 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
3030             /*
3031              * Under Windows/DOS we make the assumption that we can always
3032              * write to the tty: therefore, if we need to write to the tty we
3033              * just fall through. Otherwise we timeout the select every
3034              * second and see if there are any keypresses. Note: this is a
3035              * hack, in a proper Windows application we wouldn't do this.
3036              */
3037             i = 0;
3038             if (!write_tty) {
3039                 if (read_tty) {
3040                     tv.tv_sec = 1;
3041                     tv.tv_usec = 0;
3042                     i = select(width, (void *)&readfds, (void *)&writefds,
3043                                NULL, &tv);
3044                     if (!i && (!has_stdin_waiting() || !read_tty))
3045                         continue;
3046                 } else
3047                     i = select(width, (void *)&readfds, (void *)&writefds,
3048                                NULL, timeoutp);
3049             }
3050 #else
3051             i = select(width, (void *)&readfds, (void *)&writefds,
3052                        NULL, timeoutp);
3053 #endif
3054             if (i < 0) {
3055                 BIO_printf(bio_err, "bad select %d\n",
3056                            get_last_socket_error());
3057                 goto shut;
3058             }
3059         }
3060
3061         if (timeoutp != NULL) {
3062             SSL_handle_events(con);
3063             if (isdtls
3064                     && !FD_ISSET(SSL_get_fd(con), &readfds)
3065                     && !FD_ISSET(SSL_get_fd(con), &writefds))
3066                 BIO_printf(bio_err, "TIMEOUT occurred\n");
3067         }
3068
3069         if (!ssl_pending
3070                 && ((!isquic && FD_ISSET(SSL_get_fd(con), &writefds))
3071                     || (isquic && (cbuf_len > 0 || first_loop)))) {
3072             k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
3073             switch (SSL_get_error(con, k)) {
3074             case SSL_ERROR_NONE:
3075                 cbuf_off += k;
3076                 cbuf_len -= k;
3077                 if (k <= 0)
3078                     goto end;
3079                 /* we have done a  write(con,NULL,0); */
3080                 if (cbuf_len == 0) {
3081                     read_tty = 1;
3082                     write_ssl = 0;
3083                 } else {        /* if (cbuf_len > 0) */
3084
3085                     read_tty = 0;
3086                     write_ssl = 1;
3087                 }
3088                 break;
3089             case SSL_ERROR_WANT_WRITE:
3090                 BIO_printf(bio_c_out, "write W BLOCK\n");
3091                 write_ssl = 1;
3092                 read_tty = 0;
3093                 break;
3094             case SSL_ERROR_WANT_ASYNC:
3095                 BIO_printf(bio_c_out, "write A BLOCK\n");
3096                 wait_for_async(con);
3097                 write_ssl = 1;
3098                 read_tty = 0;
3099                 break;
3100             case SSL_ERROR_WANT_READ:
3101                 BIO_printf(bio_c_out, "write R BLOCK\n");
3102                 write_tty = 0;
3103                 read_ssl = 1;
3104                 write_ssl = 0;
3105                 break;
3106             case SSL_ERROR_WANT_X509_LOOKUP:
3107                 BIO_printf(bio_c_out, "write X BLOCK\n");
3108                 break;
3109             case SSL_ERROR_ZERO_RETURN:
3110                 if (cbuf_len != 0) {
3111                     BIO_printf(bio_c_out, "shutdown\n");
3112                     ret = 0;
3113                     goto shut;
3114                 } else {
3115                     read_tty = 1;
3116                     write_ssl = 0;
3117                     break;
3118                 }
3119
3120             case SSL_ERROR_SYSCALL:
3121                 if ((k != 0) || (cbuf_len != 0)) {
3122                     int sockerr = get_last_socket_error();
3123
3124                     if (!tfo || sockerr != EISCONN) {
3125                         BIO_printf(bio_err, "write:errno=%d\n", sockerr);
3126                         goto shut;
3127                     }
3128                 } else {
3129                     read_tty = 1;
3130                     write_ssl = 0;
3131                 }
3132                 break;
3133             case SSL_ERROR_WANT_ASYNC_JOB:
3134                 /* This shouldn't ever happen in s_client - treat as an error */
3135             case SSL_ERROR_SSL:
3136                 ERR_print_errors(bio_err);
3137                 goto shut;
3138             }
3139         }
3140 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
3141         /* Assume Windows/DOS/BeOS can always write */
3142         else if (!ssl_pending && write_tty)
3143 #else
3144         else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
3145 #endif
3146         {
3147 #ifdef CHARSET_EBCDIC
3148             ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
3149 #endif
3150             i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
3151
3152             if (i <= 0) {
3153                 BIO_printf(bio_c_out, "DONE\n");
3154                 ret = 0;
3155                 goto shut;
3156             }
3157
3158             sbuf_len -= i;
3159             sbuf_off += i;
3160             if (sbuf_len <= 0) {
3161                 read_ssl = 1;
3162                 write_tty = 0;
3163             }
3164         } else if (ssl_pending
3165                    || (!isquic && FD_ISSET(SSL_get_fd(con), &readfds))) {
3166 #ifdef RENEG
3167             {
3168                 static int iiii;
3169                 if (++iiii == 52) {
3170                     SSL_renegotiate(con);
3171                     iiii = 0;
3172                 }
3173             }
3174 #endif
3175             k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
3176
3177             switch (SSL_get_error(con, k)) {
3178             case SSL_ERROR_NONE:
3179                 if (k <= 0)
3180                     goto end;
3181                 sbuf_off = 0;
3182                 sbuf_len = k;
3183
3184                 read_ssl = 0;
3185                 write_tty = 1;
3186                 break;
3187             case SSL_ERROR_WANT_ASYNC:
3188                 BIO_printf(bio_c_out, "read A BLOCK\n");
3189                 wait_for_async(con);
3190                 write_tty = 0;
3191                 read_ssl = 1;
3192                 if ((read_tty == 0) && (write_ssl == 0))
3193                     write_ssl = 1;
3194                 break;
3195             case SSL_ERROR_WANT_WRITE:
3196                 BIO_printf(bio_c_out, "read W BLOCK\n");
3197                 write_ssl = 1;
3198                 read_tty = 0;
3199                 break;
3200             case SSL_ERROR_WANT_READ:
3201                 BIO_printf(bio_c_out, "read R BLOCK\n");
3202                 write_tty = 0;
3203                 read_ssl = 1;
3204                 if ((read_tty == 0) && (write_ssl == 0))
3205                     write_ssl = 1;
3206                 break;
3207             case SSL_ERROR_WANT_X509_LOOKUP:
3208                 BIO_printf(bio_c_out, "read X BLOCK\n");
3209                 break;
3210             case SSL_ERROR_SYSCALL:
3211                 ret = get_last_socket_error();
3212                 if (c_brief)
3213                     BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
3214                 else
3215                     BIO_printf(bio_err, "read:errno=%d\n", ret);
3216                 goto shut;
3217             case SSL_ERROR_ZERO_RETURN:
3218                 BIO_printf(bio_c_out, "closed\n");
3219                 ret = 0;
3220                 goto shut;
3221             case SSL_ERROR_WANT_ASYNC_JOB:
3222                 /* This shouldn't ever happen in s_client. Treat as an error */
3223             case SSL_ERROR_SSL:
3224                 ERR_print_errors(bio_err);
3225                 goto shut;
3226             }
3227         }
3228
3229         /* don't wait for client input in the non-interactive mode */
3230         else if (nointeractive) {
3231             ret = 0;
3232             goto shut;
3233         }
3234
3235 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
3236 #if defined(OPENSSL_SYS_MSDOS)
3237         else if (has_stdin_waiting())
3238 #else
3239         else if (FD_ISSET(fileno_stdin(), &readfds))
3240 #endif
3241         {
3242             if (crlf) {
3243                 int j, lf_num;
3244
3245                 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
3246                 lf_num = 0;
3247                 /* both loops are skipped when i <= 0 */
3248                 for (j = 0; j < i; j++)
3249                     if (cbuf[j] == '\n')
3250                         lf_num++;
3251                 for (j = i - 1; j >= 0; j--) {
3252                     cbuf[j + lf_num] = cbuf[j];
3253                     if (cbuf[j] == '\n') {
3254                         lf_num--;
3255                         i++;
3256                         cbuf[j + lf_num] = '\r';
3257                     }
3258                 }
3259                 assert(lf_num == 0);
3260             } else
3261                 i = raw_read_stdin(cbuf, BUFSIZZ);
3262 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3263             if (i == 0)
3264                 at_eof = 1;
3265 #endif
3266
3267             if (!c_ign_eof && i <= 0) {
3268                 BIO_printf(bio_err, "DONE\n");
3269                 ret = 0;
3270                 goto shut;
3271             }
3272
3273             if (i > 0 && !user_data_add(&user_data, i)) {
3274                 ret = 0;
3275                 goto shut;
3276             }
3277             read_tty = 0;
3278         }
3279         first_loop = 0;
3280     }
3281
3282  shut:
3283     if (in_init)
3284         print_stuff(bio_c_out, con, full_log);
3285     do_ssl_shutdown(con);
3286
3287     /*
3288      * If we ended with an alert being sent, but still with data in the
3289      * network buffer to be read, then calling BIO_closesocket() will
3290      * result in a TCP-RST being sent. On some platforms (notably
3291      * Windows) then this will result in the peer immediately abandoning
3292      * the connection including any buffered alert data before it has
3293      * had a chance to be read. Shutting down the sending side first,
3294      * and then closing the socket sends TCP-FIN first followed by
3295      * TCP-RST. This seems to allow the peer to read the alert data.
3296      */
3297     shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
3298     /*
3299      * We just said we have nothing else to say, but it doesn't mean that
3300      * the other side has nothing. It's even recommended to consume incoming
3301      * data. [In testing context this ensures that alerts are passed on...]
3302      */
3303     timeout.tv_sec = 0;
3304     timeout.tv_usec = 500000;  /* some extreme round-trip */
3305     do {
3306         FD_ZERO(&readfds);
3307         openssl_fdset(sock, &readfds);
3308     } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
3309              && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
3310
3311     BIO_closesocket(SSL_get_fd(con));
3312  end:
3313     if (con != NULL) {
3314         if (prexit != 0)
3315             print_stuff(bio_c_out, con, 1);
3316         SSL_free(con);
3317     }
3318     SSL_SESSION_free(psksess);
3319 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3320     OPENSSL_free(next_proto.data);
3321 #endif
3322     SSL_CTX_free(ctx);
3323     set_keylog_file(NULL, NULL);
3324     X509_free(cert);
3325     sk_X509_CRL_pop_free(crls, X509_CRL_free);
3326     EVP_PKEY_free(key);
3327     OSSL_STACK_OF_X509_free(chain);
3328     OPENSSL_free(pass);
3329 #ifndef OPENSSL_NO_SRP
3330     OPENSSL_free(srp_arg.srppassin);
3331 #endif
3332     OPENSSL_free(sname_alloc);
3333     BIO_ADDR_free(peer_addr);
3334     OPENSSL_free(connectstr);
3335     OPENSSL_free(bindstr);
3336     OPENSSL_free(bindhost);
3337     OPENSSL_free(bindport);
3338     OPENSSL_free(host);
3339     OPENSSL_free(port);
3340     OPENSSL_free(thost);
3341     OPENSSL_free(tport);
3342     X509_VERIFY_PARAM_free(vpm);
3343     ssl_excert_free(exc);
3344     sk_OPENSSL_STRING_free(ssl_args);
3345     sk_OPENSSL_STRING_free(dane_tlsa_rrset);
3346     SSL_CONF_CTX_free(cctx);
3347     OPENSSL_clear_free(cbuf, BUFSIZZ);
3348     OPENSSL_clear_free(sbuf, BUFSIZZ);
3349     OPENSSL_clear_free(mbuf, BUFSIZZ);
3350     clear_free(proxypass);
3351     release_engine(e);
3352     BIO_free(bio_c_out);
3353     bio_c_out = NULL;
3354     BIO_free(bio_c_msg);
3355     bio_c_msg = NULL;
3356     return ret;
3357 }
3358
3359 static void print_stuff(BIO *bio, SSL *s, int full)
3360 {
3361     X509 *peer = NULL;
3362     STACK_OF(X509) *sk;
3363     const SSL_CIPHER *c;
3364     EVP_PKEY *public_key;
3365     int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
3366     long verify_result;
3367 #ifndef OPENSSL_NO_COMP
3368     const COMP_METHOD *comp, *expansion;
3369 #endif
3370     unsigned char *exportedkeymat;
3371 #ifndef OPENSSL_NO_CT
3372     const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
3373 #endif
3374
3375     if (full) {
3376         int got_a_chain = 0;
3377
3378         sk = SSL_get_peer_cert_chain(s);
3379         if (sk != NULL) {
3380             got_a_chain = 1;
3381
3382             BIO_printf(bio, "---\nCertificate chain\n");
3383             for (i = 0; i < sk_X509_num(sk); i++) {
3384                 BIO_printf(bio, "%2d s:", i);
3385                 X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
3386                 BIO_puts(bio, "\n");
3387                 BIO_printf(bio, "   i:");
3388                 X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
3389                 BIO_puts(bio, "\n");
3390                 public_key = X509_get_pubkey(sk_X509_value(sk, i));
3391                 if (public_key != NULL) {
3392                     BIO_printf(bio, "   a:PKEY: %s, %d (bit); sigalg: %s\n",
3393                                OBJ_nid2sn(EVP_PKEY_get_base_id(public_key)),
3394                                EVP_PKEY_get_bits(public_key),
3395                                OBJ_nid2sn(X509_get_signature_nid(sk_X509_value(sk, i))));
3396                     EVP_PKEY_free(public_key);
3397                 }
3398                 BIO_printf(bio, "   v:NotBefore: ");
3399                 ASN1_TIME_print(bio, X509_get0_notBefore(sk_X509_value(sk, i)));
3400                 BIO_printf(bio, "; NotAfter: ");
3401                 ASN1_TIME_print(bio, X509_get0_notAfter(sk_X509_value(sk, i)));
3402                 BIO_puts(bio, "\n");
3403                 if (c_showcerts)
3404                     PEM_write_bio_X509(bio, sk_X509_value(sk, i));
3405             }
3406         }
3407
3408         BIO_printf(bio, "---\n");
3409         peer = SSL_get0_peer_certificate(s);
3410         if (peer != NULL) {
3411             BIO_printf(bio, "Server certificate\n");
3412
3413             /* Redundant if we showed the whole chain */
3414             if (!(c_showcerts && got_a_chain))
3415                 PEM_write_bio_X509(bio, peer);
3416             dump_cert_text(bio, peer);
3417         } else {
3418             BIO_printf(bio, "no peer certificate available\n");
3419         }
3420
3421         /* Only display RPK information if configured */
3422         if (SSL_get_negotiated_client_cert_type(s) == TLSEXT_cert_type_rpk)
3423             BIO_printf(bio, "Client-to-server raw public key negotiated\n");
3424         if (SSL_get_negotiated_server_cert_type(s) == TLSEXT_cert_type_rpk)
3425             BIO_printf(bio, "Server-to-client raw public key negotiated\n");
3426         if (enable_server_rpk) {
3427             EVP_PKEY *peer_rpk = SSL_get0_peer_rpk(s);
3428
3429             if (peer_rpk != NULL) {
3430                 BIO_printf(bio, "Server raw public key\n");
3431                 EVP_PKEY_print_public(bio, peer_rpk, 2, NULL);
3432             } else {
3433                 BIO_printf(bio, "no peer rpk available\n");
3434             }
3435         }
3436
3437         print_ca_names(bio, s);
3438
3439         ssl_print_sigalgs(bio, s);
3440         ssl_print_tmp_key(bio, s);
3441
3442 #ifndef OPENSSL_NO_CT
3443         /*
3444          * When the SSL session is anonymous, or resumed via an abbreviated
3445          * handshake, no SCTs are provided as part of the handshake.  While in
3446          * a resumed session SCTs may be present in the session's certificate,
3447          * no callbacks are invoked to revalidate these, and in any case that
3448          * set of SCTs may be incomplete.  Thus it makes little sense to
3449          * attempt to display SCTs from a resumed session's certificate, and of
3450          * course none are associated with an anonymous peer.
3451          */
3452         if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
3453             const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
3454             int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
3455
3456             BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
3457             if (sct_count > 0) {
3458                 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
3459
3460                 BIO_printf(bio, "---\n");
3461                 for (i = 0; i < sct_count; ++i) {
3462                     SCT *sct = sk_SCT_value(scts, i);
3463
3464                     BIO_printf(bio, "SCT validation status: %s\n",
3465                                SCT_validation_status_string(sct));
3466                     SCT_print(sct, bio, 0, log_store);
3467                     if (i < sct_count - 1)
3468                         BIO_printf(bio, "\n---\n");
3469                 }
3470                 BIO_printf(bio, "\n");
3471             }
3472         }
3473 #endif
3474
3475         BIO_printf(bio,
3476                    "---\nSSL handshake has read %ju bytes "
3477                    "and written %ju bytes\n",
3478                    BIO_number_read(SSL_get_rbio(s)),
3479                    BIO_number_written(SSL_get_wbio(s)));
3480     }
3481     print_verify_detail(s, bio);
3482     BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
3483     c = SSL_get_current_cipher(s);
3484     BIO_printf(bio, "%s, Cipher is %s\n",
3485                SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3486     if (peer != NULL) {
3487         EVP_PKEY *pktmp;
3488
3489         pktmp = X509_get0_pubkey(peer);
3490         BIO_printf(bio, "Server public key is %d bit\n",
3491                    EVP_PKEY_get_bits(pktmp));
3492     }
3493
3494     ssl_print_secure_renegotiation_notes(bio, s);
3495
3496 #ifndef OPENSSL_NO_COMP
3497     comp = SSL_get_current_compression(s);
3498     expansion = SSL_get_current_expansion(s);
3499     BIO_printf(bio, "Compression: %s\n",
3500                comp ? SSL_COMP_get_name(comp) : "NONE");
3501     BIO_printf(bio, "Expansion: %s\n",
3502                expansion ? SSL_COMP_get_name(expansion) : "NONE");
3503 #endif
3504 #ifndef OPENSSL_NO_KTLS
3505     if (BIO_get_ktls_send(SSL_get_wbio(s)))
3506         BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3507     if (BIO_get_ktls_recv(SSL_get_rbio(s)))
3508         BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3509 #endif
3510
3511     if (OSSL_TRACE_ENABLED(TLS)) {
3512         /* Print out local port of connection: useful for debugging */
3513         int sock;
3514         union BIO_sock_info_u info;
3515
3516         sock = SSL_get_fd(s);
3517         if ((info.addr = BIO_ADDR_new()) != NULL
3518             && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
3519             BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
3520                        ntohs(BIO_ADDR_rawport(info.addr)));
3521         }
3522         BIO_ADDR_free(info.addr);
3523     }
3524
3525 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3526     if (next_proto.status != -1) {
3527         const unsigned char *proto;
3528         unsigned int proto_len;
3529         SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
3530         BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
3531         BIO_write(bio, proto, proto_len);
3532         BIO_write(bio, "\n", 1);
3533     }
3534 #endif
3535     {
3536         const unsigned char *proto;
3537         unsigned int proto_len;
3538         SSL_get0_alpn_selected(s, &proto, &proto_len);
3539         if (proto_len > 0) {
3540             BIO_printf(bio, "ALPN protocol: ");
3541             BIO_write(bio, proto, proto_len);
3542             BIO_write(bio, "\n", 1);
3543         } else
3544             BIO_printf(bio, "No ALPN negotiated\n");
3545     }
3546
3547 #ifndef OPENSSL_NO_SRTP
3548     {
3549         SRTP_PROTECTION_PROFILE *srtp_profile =
3550             SSL_get_selected_srtp_profile(s);
3551
3552         if (srtp_profile)
3553             BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
3554                        srtp_profile->name);
3555     }
3556 #endif
3557
3558     if (istls13) {
3559         switch (SSL_get_early_data_status(s)) {
3560         case SSL_EARLY_DATA_NOT_SENT:
3561             BIO_printf(bio, "Early data was not sent\n");
3562             break;
3563
3564         case SSL_EARLY_DATA_REJECTED:
3565             BIO_printf(bio, "Early data was rejected\n");
3566             break;
3567
3568         case SSL_EARLY_DATA_ACCEPTED:
3569             BIO_printf(bio, "Early data was accepted\n");
3570             break;
3571
3572         }
3573
3574         /*
3575          * We also print the verify results when we dump session information,
3576          * but in TLSv1.3 we may not get that right away (or at all) depending
3577          * on when we get a NewSessionTicket. Therefore, we print it now as well.
3578          */
3579         verify_result = SSL_get_verify_result(s);
3580         BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
3581                    X509_verify_cert_error_string(verify_result));
3582     } else {
3583         /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3584         SSL_SESSION_print(bio, SSL_get_session(s));
3585     }
3586
3587     if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
3588         BIO_printf(bio, "Keying material exporter:\n");
3589         BIO_printf(bio, "    Label: '%s'\n", keymatexportlabel);
3590         BIO_printf(bio, "    Length: %i bytes\n", keymatexportlen);
3591         exportedkeymat = app_malloc(keymatexportlen, "export key");
3592         if (SSL_export_keying_material(s, exportedkeymat,
3593                                         keymatexportlen,
3594                                         keymatexportlabel,
3595                                         strlen(keymatexportlabel),
3596                                         NULL, 0, 0) <= 0) {
3597             BIO_printf(bio, "    Error\n");
3598         } else {
3599             BIO_printf(bio, "    Keying material: ");
3600             for (i = 0; i < keymatexportlen; i++)
3601                 BIO_printf(bio, "%02X", exportedkeymat[i]);
3602             BIO_printf(bio, "\n");
3603         }
3604         OPENSSL_free(exportedkeymat);
3605     }
3606     BIO_printf(bio, "---\n");
3607     /* flush, or debugging output gets mixed with http response */
3608     (void)BIO_flush(bio);
3609 }
3610
3611 # ifndef OPENSSL_NO_OCSP
3612 static int ocsp_resp_cb(SSL *s, void *arg)
3613 {
3614     const unsigned char *p;
3615     int len;
3616     OCSP_RESPONSE *rsp;
3617     len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3618     BIO_puts(arg, "OCSP response: ");
3619     if (p == NULL) {
3620         BIO_puts(arg, "no response sent\n");
3621         return 1;
3622     }
3623     rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3624     if (rsp == NULL) {
3625         BIO_puts(arg, "response parse error\n");
3626         BIO_dump_indent(arg, (char *)p, len, 4);
3627         return 0;
3628     }
3629     BIO_puts(arg, "\n======================================\n");
3630     OCSP_RESPONSE_print(arg, rsp, 0);
3631     BIO_puts(arg, "======================================\n");
3632     OCSP_RESPONSE_free(rsp);
3633     return 1;
3634 }
3635 # endif
3636
3637 static int ldap_ExtendedResponse_parse(const char *buf, long rem)
3638 {
3639     const unsigned char *cur, *end;
3640     long len;
3641     int tag, xclass, inf, ret = -1;
3642
3643     cur = (const unsigned char *)buf;
3644     end = cur + rem;
3645
3646     /*
3647      * From RFC 4511:
3648      *
3649      *    LDAPMessage ::= SEQUENCE {
3650      *         messageID       MessageID,
3651      *         protocolOp      CHOICE {
3652      *              ...
3653      *              extendedResp          ExtendedResponse,
3654      *              ... },
3655      *         controls       [0] Controls OPTIONAL }
3656      *
3657      *    ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3658      *         COMPONENTS OF LDAPResult,
3659      *         responseName     [10] LDAPOID OPTIONAL,
3660      *         responseValue    [11] OCTET STRING OPTIONAL }
3661      *
3662      *    LDAPResult ::= SEQUENCE {
3663      *         resultCode         ENUMERATED {
3664      *              success                      (0),
3665      *              ...
3666      *              other                        (80),
3667      *              ...  },
3668      *         matchedDN          LDAPDN,
3669      *         diagnosticMessage  LDAPString,
3670      *         referral           [3] Referral OPTIONAL }
3671      */
3672
3673     /* pull SEQUENCE */
3674     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3675     if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
3676         (rem = end - cur, len > rem)) {
3677         BIO_printf(bio_err, "Unexpected LDAP response\n");
3678         goto end;
3679     }
3680
3681     rem = len;  /* ensure that we don't overstep the SEQUENCE */
3682
3683     /* pull MessageID */
3684     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3685     if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
3686         (rem = end - cur, len > rem)) {
3687         BIO_printf(bio_err, "No MessageID\n");
3688         goto end;
3689     }
3690
3691     cur += len; /* shall we check for MessageId match or just skip? */
3692
3693     /* pull [APPLICATION 24] */
3694     rem = end - cur;
3695     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3696     if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
3697         tag != 24) {
3698         BIO_printf(bio_err, "Not ExtendedResponse\n");
3699         goto end;
3700     }
3701
3702     /* pull resultCode */
3703     rem = end - cur;
3704     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3705     if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
3706         (rem = end - cur, len > rem)) {
3707         BIO_printf(bio_err, "Not LDAPResult\n");
3708         goto end;
3709     }
3710
3711     /* len should always be one, but just in case... */
3712     for (ret = 0, inf = 0; inf < len; inf++) {
3713         ret <<= 8;
3714         ret |= cur[inf];
3715     }
3716     /* There is more data, but we don't care... */
3717  end:
3718     return ret;
3719 }
3720
3721 /*
3722  * Host dNS Name verifier: used for checking that the hostname is in dNS format
3723  * before setting it as SNI
3724  */
3725 static int is_dNS_name(const char *host)
3726 {
3727     const size_t MAX_LABEL_LENGTH = 63;
3728     size_t i;
3729     int isdnsname = 0;
3730     size_t length = strlen(host);
3731     size_t label_length = 0;
3732     int all_numeric = 1;
3733
3734     /*
3735      * Deviation from strict DNS name syntax, also check names with '_'
3736      * Check DNS name syntax, any '-' or '.' must be internal,
3737      * and on either side of each '.' we can't have a '-' or '.'.
3738      *
3739      * If the name has just one label, we don't consider it a DNS name.
3740      */
3741     for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) {
3742         char c = host[i];
3743
3744         if ((c >= 'a' && c <= 'z')
3745             || (c >= 'A' && c <= 'Z')
3746             || c == '_') {
3747             label_length += 1;
3748             all_numeric = 0;
3749             continue;
3750         }
3751
3752         if (c >= '0' && c <= '9') {
3753             label_length += 1;
3754             continue;
3755         }
3756
3757         /* Dot and hyphen cannot be first or last. */
3758         if (i > 0 && i < length - 1) {
3759             if (c == '-') {
3760                 label_length += 1;
3761                 continue;
3762             }
3763             /*
3764              * Next to a dot the preceding and following characters must not be
3765              * another dot or a hyphen.  Otherwise, record that the name is
3766              * plausible, since it has two or more labels.
3767              */
3768             if (c == '.'
3769                 && host[i + 1] != '.'
3770                 && host[i - 1] != '-'
3771                 && host[i + 1] != '-') {
3772                 label_length = 0;
3773                 isdnsname = 1;
3774                 continue;
3775             }
3776         }
3777         isdnsname = 0;
3778         break;
3779     }
3780
3781     /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
3782     isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH);
3783
3784     return isdnsname;
3785 }
3786
3787 static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf,
3788                            size_t bufmax, int mode)
3789 {
3790     user_data->con = con;
3791     user_data->buf = buf;
3792     user_data->bufmax = bufmax;
3793     user_data->buflen = 0;
3794     user_data->bufoff = 0;
3795     user_data->mode = mode;
3796     user_data->isfin = 0;
3797 }
3798
3799 static int user_data_add(struct user_data_st *user_data, size_t i)
3800 {
3801     if (user_data->buflen != 0 || i > user_data->bufmax)
3802         return 0;
3803
3804     user_data->buflen = i;
3805     user_data->bufoff = 0;
3806
3807     return 1;
3808 }
3809
3810 #define USER_COMMAND_HELP        0
3811 #define USER_COMMAND_QUIT        1
3812 #define USER_COMMAND_RECONNECT   2
3813 #define USER_COMMAND_RENEGOTIATE 3
3814 #define USER_COMMAND_KEY_UPDATE  4
3815 #define USER_COMMAND_FIN         5
3816
3817 static int user_data_execute(struct user_data_st *user_data, int cmd, char *arg)
3818 {
3819     switch (cmd) {
3820     case USER_COMMAND_HELP:
3821         /* This only ever occurs in advanced mode, so just emit advanced help */
3822         BIO_printf(bio_err, "Enter text to send to the peer followed by <enter>\n");
3823         BIO_printf(bio_err, "To issue a command insert {cmd} or {cmd:arg} anywhere in the text\n");
3824         BIO_printf(bio_err, "Entering {{ will send { to the peer\n");
3825         BIO_printf(bio_err, "The following commands are available\n");
3826         BIO_printf(bio_err, "  {help}: Get this help text\n");
3827         BIO_printf(bio_err, "  {quit}: Close the connection to the peer\n");
3828         BIO_printf(bio_err, "  {reconnect}: Reconnect to the peer\n");
3829         if (SSL_is_quic(user_data->con)) {
3830             BIO_printf(bio_err, "  {fin}: Send FIN on the stream. No further writing is possible\n");
3831         } else if(SSL_version(user_data->con) == TLS1_3_VERSION) {
3832             BIO_printf(bio_err, "  {keyup:req|noreq}: Send a Key Update message\n");
3833             BIO_printf(bio_err, "                     Arguments:\n");
3834             BIO_printf(bio_err, "                     req   = peer update requested (default)\n");
3835             BIO_printf(bio_err, "                     noreq = peer update not requested\n");
3836         } else {
3837             BIO_printf(bio_err, "  {reneg}: Attempt to renegotiate\n");
3838         }
3839         BIO_printf(bio_err, "\n");
3840         return USER_DATA_PROCESS_NO_DATA;
3841
3842     case USER_COMMAND_QUIT:
3843         BIO_printf(bio_err, "DONE\n");
3844         return USER_DATA_PROCESS_SHUT;
3845
3846     case USER_COMMAND_RECONNECT:
3847         BIO_printf(bio_err, "RECONNECTING\n");
3848         do_ssl_shutdown(user_data->con);
3849         SSL_set_connect_state(user_data->con);
3850         BIO_closesocket(SSL_get_fd(user_data->con));
3851         return USER_DATA_PROCESS_RESTART;
3852
3853     case USER_COMMAND_RENEGOTIATE:
3854         BIO_printf(bio_err, "RENEGOTIATING\n");
3855         if (!SSL_renegotiate(user_data->con))
3856             break;
3857         return USER_DATA_PROCESS_CONTINUE;
3858
3859     case USER_COMMAND_KEY_UPDATE: {
3860             int updatetype;
3861
3862             if (OPENSSL_strcasecmp(arg, "req") == 0)
3863                 updatetype = SSL_KEY_UPDATE_REQUESTED;
3864             else if (OPENSSL_strcasecmp(arg, "noreq") == 0)
3865                 updatetype = SSL_KEY_UPDATE_NOT_REQUESTED;
3866             else
3867                 return USER_DATA_PROCESS_BAD_ARGUMENT;
3868             BIO_printf(bio_err, "KEYUPDATE\n");
3869             if (!SSL_key_update(user_data->con, updatetype))
3870                 break;
3871             return USER_DATA_PROCESS_CONTINUE;
3872         }
3873
3874     case USER_COMMAND_FIN:
3875         if (!SSL_stream_conclude(user_data->con, 0))
3876             break;
3877         user_data->isfin = 1;
3878         return USER_DATA_PROCESS_NO_DATA;
3879
3880     default:
3881         break;
3882     }
3883
3884     BIO_printf(bio_err, "ERROR\n");
3885     ERR_print_errors(bio_err);
3886
3887     return USER_DATA_PROCESS_SHUT;
3888 }
3889
3890 static int user_data_process(struct user_data_st *user_data, size_t *len,
3891                              size_t *off)
3892 {
3893     char *buf_start = user_data->buf + user_data->bufoff;
3894     size_t outlen = user_data->buflen;
3895
3896     if (user_data->buflen == 0) {
3897         *len = 0;
3898         *off = 0;
3899         return USER_DATA_PROCESS_NO_DATA;
3900     }
3901
3902     if (user_data->mode == USER_DATA_MODE_BASIC) {
3903         switch (buf_start[0]) {
3904         case 'Q':
3905             user_data->buflen = user_data->bufoff = *len = *off = 0;
3906             return user_data_execute(user_data, USER_COMMAND_QUIT, NULL);
3907
3908         case 'C':
3909             user_data->buflen = user_data->bufoff = *len = *off = 0;
3910             return user_data_execute(user_data, USER_COMMAND_RECONNECT, NULL);
3911
3912         case 'R':
3913             user_data->buflen = user_data->bufoff = *len = *off = 0;
3914             return user_data_execute(user_data, USER_COMMAND_RENEGOTIATE, NULL);
3915
3916         case 'K':
3917         case 'k':
3918             user_data->buflen = user_data->bufoff = *len = *off = 0;
3919             return user_data_execute(user_data, USER_COMMAND_KEY_UPDATE,
3920                                      buf_start[0] == 'K' ? "req" : "noreq");
3921         default:
3922             break;
3923         }
3924     } else if (user_data->mode == USER_DATA_MODE_ADVANCED) {
3925         char *cmd_start = buf_start;
3926
3927         cmd_start[outlen] = '\0';
3928         for (;;) {
3929             cmd_start = strchr(cmd_start, '{');
3930             if (cmd_start == buf_start && *(cmd_start + 1) == '{') {
3931                 /* The "{" is escaped, so skip it */
3932                 cmd_start += 2;
3933                 buf_start++;
3934                 user_data->bufoff++;
3935                 user_data->buflen--;
3936                 outlen--;
3937                 continue;
3938             }
3939             break;
3940         }
3941
3942         if (cmd_start == buf_start) {
3943             /* Command detected */
3944             char *cmd_end = strchr(cmd_start, '}');
3945             char *arg_start;
3946             int cmd = -1, ret = USER_DATA_PROCESS_NO_DATA;
3947             size_t oldoff;
3948
3949             if (cmd_end == NULL) {
3950                 /* Malformed command */
3951                 cmd_start[outlen - 1] = '\0';
3952                 BIO_printf(bio_err,
3953                            "ERROR PROCESSING COMMAND. REST OF LINE IGNORED: %s\n",
3954                            cmd_start);
3955                 user_data->buflen = user_data->bufoff = *len = *off = 0;
3956                 return USER_DATA_PROCESS_NO_DATA;
3957             }
3958             *cmd_end = '\0';
3959             arg_start = strchr(cmd_start, ':');
3960             if (arg_start != NULL) {
3961                 *arg_start = '\0';
3962                 arg_start++;
3963             }
3964             /* Skip over the { */
3965             cmd_start++;
3966             /*
3967              * Now we have cmd_start pointing to a NUL terminated string for
3968              * the command, and arg_start either being NULL or pointing to a
3969              * NUL terminated string for the argument.
3970              */
3971             if (OPENSSL_strcasecmp(cmd_start, "help") == 0) {
3972                 cmd = USER_COMMAND_HELP;
3973             } else if (OPENSSL_strcasecmp(cmd_start, "quit") == 0) {
3974                 cmd = USER_COMMAND_QUIT;
3975             } else if (OPENSSL_strcasecmp(cmd_start, "reconnect") == 0) {
3976                 cmd = USER_COMMAND_RECONNECT;
3977             } else if(SSL_is_quic(user_data->con)) {
3978                 if (OPENSSL_strcasecmp(cmd_start, "fin") == 0)
3979                     cmd = USER_COMMAND_FIN;
3980             } if (SSL_version(user_data->con) == TLS1_3_VERSION) {
3981                 if (OPENSSL_strcasecmp(cmd_start, "keyup") == 0) {
3982                     cmd = USER_COMMAND_KEY_UPDATE;
3983                     if (arg_start == NULL)
3984                         arg_start = "req";
3985                 }
3986             } else {
3987                 /* (D)TLSv1.2 or below */
3988                 if (OPENSSL_strcasecmp(cmd_start, "reneg") == 0)
3989                     cmd = USER_COMMAND_RENEGOTIATE;
3990             }
3991             if (cmd == -1) {
3992                 BIO_printf(bio_err, "UNRECOGNISED COMMAND (IGNORED): %s\n",
3993                            cmd_start);
3994             } else {
3995                 ret = user_data_execute(user_data, cmd, arg_start);
3996                 if (ret == USER_DATA_PROCESS_BAD_ARGUMENT) {
3997                     BIO_printf(bio_err, "BAD ARGUMENT (COMMAND IGNORED): %s\n",
3998                                arg_start);
3999                     ret = USER_DATA_PROCESS_NO_DATA;
4000                 }
4001             }
4002             oldoff = user_data->bufoff;
4003             user_data->bufoff = (cmd_end - user_data->buf) + 1;
4004             user_data->buflen -= user_data->bufoff - oldoff;
4005             if (user_data->buf + 1 == cmd_start
4006                     && user_data->buflen == 1
4007                     && user_data->buf[user_data->bufoff] == '\n') {
4008                 /*
4009                  * This command was the only thing on the whole line. We
4010                  * suppress the final `\n`
4011                  */
4012                 user_data->bufoff = 0;
4013                 user_data->buflen = 0;
4014             }
4015             *len = *off = 0;
4016             return ret;
4017         } else if (cmd_start != NULL) {
4018             /*
4019              * There is a command on this line, but its not at the start. Output
4020              * the start of the line, and we'll process the command next time
4021              * we call this function
4022              */
4023             outlen = cmd_start - buf_start;
4024         }
4025     }
4026
4027     if (user_data->isfin) {
4028         user_data->buflen = user_data->bufoff = *len = *off = 0;
4029         return USER_DATA_PROCESS_NO_DATA;
4030     }
4031
4032 #ifdef CHARSET_EBCDIC
4033     ebcdic2ascii(buf_start, buf_start, outlen);
4034 #endif
4035     *len = outlen;
4036     *off = user_data->bufoff;
4037     user_data->buflen -= outlen;
4038     if (user_data->buflen == 0)
4039         user_data->bufoff = 0;
4040     else
4041         user_data->bufoff += outlen;
4042     return USER_DATA_PROCESS_CONTINUE;
4043 }
4044
4045 static int user_data_has_data(struct user_data_st *user_data)
4046 {
4047     return user_data->buflen > 0;
4048 }
4049 #endif                          /* OPENSSL_NO_SOCK */