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