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