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