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