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