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