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