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