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