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