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