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