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