Convert __thread to pthreads for Thread Local Storage
[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 <openssl/e_os2.h>
142
143 /*
144  * With IPv6, it looks like Digital has mixed up the proper order of
145  * recursive header file inclusion, resulting in the compiler complaining
146  * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
147  * needed to have fileno() declared correctly...  So let's define u_int
148  */
149 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
150 # define __U_INT
151 typedef unsigned int u_int;
152 #endif
153
154 #define USE_SOCKETS
155 #include "apps.h"
156 #include <openssl/x509.h>
157 #include <openssl/ssl.h>
158 #include <openssl/err.h>
159 #include <openssl/pem.h>
160 #include <openssl/rand.h>
161 #include <openssl/ocsp.h>
162 #include <openssl/bn.h>
163 #include <openssl/async.h>
164 #ifndef OPENSSL_NO_SRP
165 # include <openssl/srp.h>
166 #endif
167 #include "s_apps.h"
168 #include "timeouts.h"
169
170 #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
171 /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
172 # undef FIONBIO
173 #endif
174
175 #define SSL_HOST_NAME   "localhost"
176
177 #undef BUFSIZZ
178 #define BUFSIZZ 1024*8
179 #define S_CLIENT_IRC_READ_TIMEOUT 8
180
181 extern int verify_depth;
182 extern int verify_error;
183 extern int verify_return_error;
184 extern int verify_quiet;
185
186 static int async = 0;
187 static int c_nbio = 0;
188 static int c_tlsextdebug = 0;
189 static int c_status_req = 0;
190 static int c_Pause = 0;
191 static int c_debug = 0;
192 static int c_msg = 0;
193 static int c_showcerts = 0;
194 static char *keymatexportlabel = NULL;
195 static int keymatexportlen = 20;
196 static BIO *bio_c_out = NULL;
197 static BIO *bio_c_msg = NULL;
198 static int c_quiet = 0;
199 static int c_ign_eof = 0;
200 static int c_brief = 0;
201
202 static void print_stuff(BIO *berr, SSL *con, int full);
203 static int ocsp_resp_cb(SSL *s, void *arg);
204
205 #ifndef OPENSSL_NO_PSK
206 /* Default PSK identity and key */
207 static char *psk_identity = "Client_identity";
208 /*
209  * char *psk_key=NULL; by default PSK is not used
210  */
211
212 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
213                                   unsigned int max_identity_len,
214                                   unsigned char *psk,
215                                   unsigned int max_psk_len)
216 {
217     unsigned int psk_len = 0;
218     int ret;
219     BIGNUM *bn = NULL;
220
221     if (c_debug)
222         BIO_printf(bio_c_out, "psk_client_cb\n");
223     if (!hint) {
224         /* no ServerKeyExchange message */
225         if (c_debug)
226             BIO_printf(bio_c_out,
227                        "NULL received PSK identity hint, continuing anyway\n");
228     } else if (c_debug)
229         BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
230
231     /*
232      * lookup PSK identity and PSK key based on the given identity hint here
233      */
234     ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
235     if (ret < 0 || (unsigned int)ret > max_identity_len)
236         goto out_err;
237     if (c_debug)
238         BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
239                    ret);
240     ret = BN_hex2bn(&bn, psk_key);
241     if (!ret) {
242         BIO_printf(bio_err, "Could not convert PSK key '%s' to BIGNUM\n",
243                    psk_key);
244         BN_free(bn);
245         return 0;
246     }
247
248     if ((unsigned int)BN_num_bytes(bn) > max_psk_len) {
249         BIO_printf(bio_err,
250                    "psk buffer of callback is too small (%d) for key (%d)\n",
251                    max_psk_len, BN_num_bytes(bn));
252         BN_free(bn);
253         return 0;
254     }
255
256     psk_len = BN_bn2bin(bn, psk);
257     BN_free(bn);
258     if (psk_len == 0)
259         goto out_err;
260
261     if (c_debug)
262         BIO_printf(bio_c_out, "created PSK len=%d\n", psk_len);
263
264     return psk_len;
265  out_err:
266     if (c_debug)
267         BIO_printf(bio_err, "Error in PSK client callback\n");
268     return 0;
269 }
270 #endif
271
272 /* This is a context that we pass to callbacks */
273 typedef struct tlsextctx_st {
274     BIO *biodebug;
275     int ack;
276 } tlsextctx;
277
278 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
279 {
280     tlsextctx *p = (tlsextctx *) arg;
281     const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
282     if (SSL_get_servername_type(s) != -1)
283         p->ack = !SSL_session_reused(s) && hn != NULL;
284     else
285         BIO_printf(bio_err, "Can't use SSL_get_servername\n");
286
287     return SSL_TLSEXT_ERR_OK;
288 }
289
290 #ifndef OPENSSL_NO_SRP
291
292 /* This is a context that we pass to all callbacks */
293 typedef struct srp_arg_st {
294     char *srppassin;
295     char *srplogin;
296     int msg;                    /* copy from c_msg */
297     int debug;                  /* copy from c_debug */
298     int amp;                    /* allow more groups */
299     int strength /* minimal size for N */ ;
300 } SRP_ARG;
301
302 # define SRP_NUMBER_ITERATIONS_FOR_PRIME 64
303
304 static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g)
305 {
306     BN_CTX *bn_ctx = BN_CTX_new();
307     BIGNUM *p = BN_new();
308     BIGNUM *r = BN_new();
309     int ret =
310         g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
311         BN_is_prime_ex(N, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) &&
312         p != NULL && BN_rshift1(p, N) &&
313         /* p = (N-1)/2 */
314         BN_is_prime_ex(p, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) &&
315         r != NULL &&
316         /* verify g^((N-1)/2) == -1 (mod N) */
317         BN_mod_exp(r, g, p, N, bn_ctx) &&
318         BN_add_word(r, 1) && BN_cmp(r, N) == 0;
319
320     BN_free(r);
321     BN_free(p);
322     BN_CTX_free(bn_ctx);
323     return ret;
324 }
325
326 /*-
327  * This callback is used here for two purposes:
328  * - extended debugging
329  * - making some primality tests for unknown groups
330  * The callback is only called for a non default group.
331  *
332  * An application does not need the call back at all if
333  * only the stanard groups are used.  In real life situations,
334  * client and server already share well known groups,
335  * thus there is no need to verify them.
336  * Furthermore, in case that a server actually proposes a group that
337  * is not one of those defined in RFC 5054, it is more appropriate
338  * to add the group to a static list and then compare since
339  * primality tests are rather cpu consuming.
340  */
341
342 static int ssl_srp_verify_param_cb(SSL *s, void *arg)
343 {
344     SRP_ARG *srp_arg = (SRP_ARG *)arg;
345     BIGNUM *N = NULL, *g = NULL;
346
347     if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL))
348         return 0;
349     if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
350         BIO_printf(bio_err, "SRP parameters:\n");
351         BIO_printf(bio_err, "\tN=");
352         BN_print(bio_err, N);
353         BIO_printf(bio_err, "\n\tg=");
354         BN_print(bio_err, g);
355         BIO_printf(bio_err, "\n");
356     }
357
358     if (SRP_check_known_gN_param(g, N))
359         return 1;
360
361     if (srp_arg->amp == 1) {
362         if (srp_arg->debug)
363             BIO_printf(bio_err,
364                        "SRP param N and g are not known params, going to check deeper.\n");
365
366         /*
367          * The srp_moregroups is a real debugging feature. Implementors
368          * should rather add the value to the known ones. The minimal size
369          * has already been tested.
370          */
371         if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
372             return 1;
373     }
374     BIO_printf(bio_err, "SRP param N and g rejected.\n");
375     return 0;
376 }
377
378 # define PWD_STRLEN 1024
379
380 static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
381 {
382     SRP_ARG *srp_arg = (SRP_ARG *)arg;
383     char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer");
384     PW_CB_DATA cb_tmp;
385     int l;
386
387     cb_tmp.password = (char *)srp_arg->srppassin;
388     cb_tmp.prompt_info = "SRP user";
389     if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
390         BIO_printf(bio_err, "Can't read Password\n");
391         OPENSSL_free(pass);
392         return NULL;
393     }
394     *(pass + l) = '\0';
395
396     return pass;
397 }
398
399 #endif
400
401 static char *srtp_profiles = NULL;
402
403 #ifndef OPENSSL_NO_NEXTPROTONEG
404 /* This the context that we pass to next_proto_cb */
405 typedef struct tlsextnextprotoctx_st {
406     unsigned char *data;
407     unsigned short len;
408     int status;
409 } tlsextnextprotoctx;
410
411 static tlsextnextprotoctx next_proto;
412
413 static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
414                          const unsigned char *in, unsigned int inlen,
415                          void *arg)
416 {
417     tlsextnextprotoctx *ctx = arg;
418
419     if (!c_quiet) {
420         /* We can assume that |in| is syntactically valid. */
421         unsigned i;
422         BIO_printf(bio_c_out, "Protocols advertised by server: ");
423         for (i = 0; i < inlen;) {
424             if (i)
425                 BIO_write(bio_c_out, ", ", 2);
426             BIO_write(bio_c_out, &in[i + 1], in[i]);
427             i += in[i] + 1;
428         }
429         BIO_write(bio_c_out, "\n", 1);
430     }
431
432     ctx->status =
433         SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
434     return SSL_TLSEXT_ERR_OK;
435 }
436 #endif                         /* ndef OPENSSL_NO_NEXTPROTONEG */
437
438 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
439                                    const unsigned char *in, size_t inlen,
440                                    int *al, void *arg)
441 {
442     char pem_name[100];
443     unsigned char ext_buf[4 + 65536];
444
445     /* Reconstruct the type/len fields prior to extension data */
446     ext_buf[0] = ext_type >> 8;
447     ext_buf[1] = ext_type & 0xFF;
448     ext_buf[2] = inlen >> 8;
449     ext_buf[3] = inlen & 0xFF;
450     memcpy(ext_buf + 4, in, inlen);
451
452     BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
453                  ext_type);
454     PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
455     return 1;
456 }
457
458 typedef enum OPTION_choice {
459     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
460     OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_UNIX, OPT_XMPPHOST, OPT_VERIFY,
461     OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
462     OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
463     OPT_BRIEF, OPT_PREXIT, OPT_CRLF, OPT_QUIET, OPT_NBIO,
464     OPT_SSL_CLIENT_ENGINE, OPT_RAND, OPT_IGN_EOF, OPT_NO_IGN_EOF,
465     OPT_PAUSE, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
466     OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
467     OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
468     OPT_PSK_IDENTITY, OPT_PSK, OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH,
469     OPT_SRP_LATEUSER, OPT_SRP_MOREGROUPS, OPT_SSL3,
470     OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
471     OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS,
472     OPT_CERT_CHAIN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
473     OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE,
474     OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_NEXTPROTONEG, OPT_ALPN,
475     OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_JPAKE,
476     OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_SMTPHOST,
477     OPT_ASYNC,
478     OPT_V_ENUM,
479     OPT_X_ENUM,
480     OPT_S_ENUM,
481     OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_PROXY
482 } OPTION_CHOICE;
483
484 OPTIONS s_client_options[] = {
485     {"help", OPT_HELP, '-', "Display this summary"},
486     {"host", OPT_HOST, 's', "Use -connect instead"},
487     {"port", OPT_PORT, 'p', "Use -connect instead"},
488     {"connect", OPT_CONNECT, 's',
489      "TCP/IP where to connect (default is " SSL_HOST_NAME ":" PORT_STR ")"},
490     {"proxy", OPT_PROXY, 's',
491      "Connect to via specified proxy to the real server"},
492     {"unix", OPT_UNIX, 's', "Connect over unix domain sockets"},
493     {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
494     {"cert", OPT_CERT, '<', "Certificate file to use, PEM format assumed"},
495     {"certform", OPT_CERTFORM, 'F',
496      "Certificate format (PEM or DER) PEM default"},
497     {"key", OPT_KEY, '<', "Private key file to use, if not in -cert file"},
498     {"keyform", OPT_KEYFORM, 'F', "Key format (PEM or DER) PEM default"},
499     {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
500     {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
501     {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
502     {"no-CAfile", OPT_NOCAFILE, '-',
503      "Do not load the default certificates file"},
504     {"no-CApath", OPT_NOCAPATH, '-',
505      "Do not load certificates from the default certificates directory"},
506     {"reconnect", OPT_RECONNECT, '-',
507      "Drop and re-make the connection with the same Session-ID"},
508     {"pause", OPT_PAUSE, '-', "Sleep  after each read and write system call"},
509     {"showcerts", OPT_SHOWCERTS, '-', "Show all certificates in the chain"},
510     {"debug", OPT_DEBUG, '-', "Extra output"},
511     {"msg", OPT_MSG, '-', "Show protocol messages"},
512     {"msgfile", OPT_MSGFILE, '>'},
513     {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
514     {"state", OPT_STATE, '-', "Print the ssl states"},
515     {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
516     {"quiet", OPT_QUIET, '-', "No s_client output"},
517     {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
518     {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
519     {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
520     {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
521     {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
522     {"starttls", OPT_STARTTLS, 's',
523      "Use the appropriate STARTTLS command before starting TLS"},
524     {"xmpphost", OPT_XMPPHOST, 's',
525      "Host to use with \"-starttls xmpp[-server]\""},
526     {"rand", OPT_RAND, 's',
527      "Load the file(s) into the random number generator"},
528     {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
529     {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
530     {"use_srtp", OPT_USE_SRTP, 's',
531      "Offer SRTP key management with a colon-separated profile list"},
532     {"keymatexport", OPT_KEYMATEXPORT, 's',
533      "Export keying material using label"},
534     {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
535      "Export len bytes of keying material (default 20)"},
536     {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
537     {"name", OPT_SMTPHOST, 's', "Hostname to use for \"-starttls smtp\""},
538     {"CRL", OPT_CRL, '<'},
539     {"crl_download", OPT_CRL_DOWNLOAD, '-'},
540     {"CRLform", OPT_CRLFORM, 'F'},
541     {"verify_return_error", OPT_VERIFY_RET_ERROR, '-'},
542     {"verify_quiet", OPT_VERIFY_QUIET, '-'},
543     {"brief", OPT_BRIEF, '-'},
544     {"prexit", OPT_PREXIT, '-'},
545     {"security_debug", OPT_SECURITY_DEBUG, '-'},
546     {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-'},
547     {"cert_chain", OPT_CERT_CHAIN, '<'},
548     {"chainCApath", OPT_CHAINCAPATH, '/'},
549     {"verifyCApath", OPT_VERIFYCAPATH, '/'},
550     {"build_chain", OPT_BUILD_CHAIN, '-'},
551     {"chainCAfile", OPT_CHAINCAFILE, '<'},
552     {"verifyCAfile", OPT_VERIFYCAFILE, '<'},
553     {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
554     {"servername", OPT_SERVERNAME, 's',
555      "Set TLS extension servername in ClientHello"},
556     {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
557      "Hex dump of all TLS extensions received"},
558     {"status", OPT_STATUS, '-', "Request certificate status from server"},
559     {"serverinfo", OPT_SERVERINFO, 's',
560      "types  Send empty ClientHello extensions (comma-separated numbers)"},
561     {"alpn", OPT_ALPN, 's',
562      "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
563     {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
564     OPT_S_OPTIONS,
565     OPT_V_OPTIONS,
566     OPT_X_OPTIONS,
567 #ifndef OPENSSL_NO_SSL3
568     {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
569 #endif
570 #ifndef OPENSSL_NO_DTLS1
571     {"dtls", OPT_DTLS, '-'},
572     {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
573     {"dtls1_2", OPT_DTLS1_2, '-'},
574     {"timeout", OPT_TIMEOUT, '-'},
575     {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
576 #endif
577 #ifndef OPENSSL_NO_SSL_TRACE
578     {"trace", OPT_TRACE, '-'},
579 #endif
580 #ifdef WATT32
581     {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
582 #endif
583 #ifdef FIONBIO
584     {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
585 #endif
586 #ifndef OPENSSL_NO_PSK
587     {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
588     {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
589 # ifndef OPENSSL_NO_JPAKE
590     {"jpake", OPT_JPAKE, 's', "JPAKE secret to use"},
591 # endif
592 #endif
593 #ifndef OPENSSL_NO_SRP
594     {"srpuser", OPT_SRPUSER, 's', "SRP authentification for 'user'"},
595     {"srppass", OPT_SRPPASS, 's', "Password for 'user'"},
596     {"srp_lateuser", OPT_SRP_LATEUSER, '-',
597      "SRP username into second ClientHello message"},
598     {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
599      "Tolerate other than the known g N values."},
600     {"srp_strength", OPT_SRP_STRENGTH, 'p', "Minimal length in bits for N"},
601 #endif
602 #ifndef OPENSSL_NO_NEXTPROTONEG
603     {"nextprotoneg", OPT_NEXTPROTONEG, 's',
604      "Enable NPN extension, considering named protocols supported (comma-separated list)"},
605 #endif
606 #ifndef OPENSSL_NO_ENGINE
607     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
608     {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's'},
609 #endif
610     {NULL}
611 };
612
613 typedef enum PROTOCOL_choice {
614     PROTO_OFF,
615     PROTO_SMTP,
616     PROTO_POP3,
617     PROTO_IMAP,
618     PROTO_FTP,
619     PROTO_TELNET,
620     PROTO_XMPP,
621     PROTO_XMPP_SERVER,
622     PROTO_CONNECT,
623     PROTO_IRC
624 } PROTOCOL_CHOICE;
625
626 static OPT_PAIR services[] = {
627     {"smtp", PROTO_SMTP},
628     {"pop3", PROTO_POP3},
629     {"imap", PROTO_IMAP},
630     {"ftp", PROTO_FTP},
631     {"xmpp", PROTO_XMPP},
632     {"xmpp-server", PROTO_XMPP_SERVER},
633     {"telnet", PROTO_TELNET},
634     {"irc", PROTO_IRC},
635     {NULL}
636 };
637
638 int s_client_main(int argc, char **argv)
639 {
640     BIO *sbio;
641     EVP_PKEY *key = NULL;
642     SSL *con = NULL;
643     SSL_CTX *ctx = NULL;
644     STACK_OF(X509) *chain = NULL;
645     X509 *cert = NULL;
646     X509_VERIFY_PARAM *vpm = NULL;
647     SSL_EXCERT *exc = NULL;
648     SSL_CONF_CTX *cctx = NULL;
649     STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
650     STACK_OF(X509_CRL) *crls = NULL;
651     const SSL_METHOD *meth = TLS_client_method();
652     char *CApath = NULL, *CAfile = NULL, *cbuf = NULL, *sbuf = NULL;
653     char *mbuf = NULL, *proxystr = NULL, *connectstr = NULL;
654     char *cert_file = NULL, *key_file = NULL, *chain_file = NULL, *prog;
655     char *chCApath = NULL, *chCAfile = NULL, *host = SSL_HOST_NAME;
656     char *inrand = NULL;
657     char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
658     char *sess_in = NULL, *sess_out = NULL, *crl_file = NULL, *p;
659     char *jpake_secret = NULL, *xmpphost = NULL;
660     const char *unix_path = NULL;
661     const char *ehlo = "mail.example.com";
662     struct sockaddr peer;
663     struct timeval timeout, *timeoutp;
664     fd_set readfds, writefds;
665     int noCApath = 0, noCAfile = 0;
666     int build_chain = 0, cbuf_len, cbuf_off, cert_format = FORMAT_PEM;
667     int key_format = FORMAT_PEM, crlf = 0, full_log = 1, mbuf_len = 0;
668     int prexit = 0;
669     int enable_timeouts = 0, sdebug = 0, peerlen = sizeof peer;
670     int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
671     int ret = 1, in_init = 1, i, nbio_test = 0, s = -1, k, width, state = 0;
672     int sbuf_len, sbuf_off, socket_type = SOCK_STREAM, cmdletters = 1;
673     int starttls_proto = PROTO_OFF, crl_format = FORMAT_PEM, crl_download = 0;
674     int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
675     int fallback_scsv = 0;
676     long socket_mtu = 0, randamt = 0;
677     unsigned short port = PORT;
678     OPTION_CHOICE o;
679 #ifndef OPENSSL_NO_ENGINE
680     ENGINE *ssl_client_engine = NULL;
681 #endif
682     ENGINE *e = NULL;
683 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
684     struct timeval tv;
685 #endif
686     char *servername = NULL;
687     const char *alpn_in = NULL;
688     tlsextctx tlsextcbp = { NULL, 0 };
689 #define MAX_SI_TYPES 100
690     unsigned short serverinfo_types[MAX_SI_TYPES];
691     int serverinfo_count = 0, start = 0, len;
692 #ifndef OPENSSL_NO_NEXTPROTONEG
693     const char *next_proto_neg_in = NULL;
694 #endif
695 #ifndef OPENSSL_NO_SRP
696     char *srppass = NULL;
697     int srp_lateuser = 0;
698     SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
699 #endif
700
701     prog = opt_progname(argv[0]);
702     c_Pause = 0;
703     c_quiet = 0;
704     c_ign_eof = 0;
705     c_debug = 0;
706     c_msg = 0;
707     c_showcerts = 0;
708     c_nbio = 0;
709     verify_depth = 0;
710     verify_error = X509_V_OK;
711     vpm = X509_VERIFY_PARAM_new();
712     cbuf = app_malloc(BUFSIZZ, "cbuf");
713     sbuf = app_malloc(BUFSIZZ, "sbuf");
714     mbuf = app_malloc(BUFSIZZ, "mbuf");
715     cctx = SSL_CONF_CTX_new();
716
717     if (vpm == NULL || cctx == NULL) {
718         BIO_printf(bio_err, "%s: out of memory\n", prog);
719         goto end;
720     }
721
722     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
723
724     prog = opt_init(argc, argv, s_client_options);
725     while ((o = opt_next()) != OPT_EOF) {
726         switch (o) {
727         case OPT_EOF:
728         case OPT_ERR:
729  opthelp:
730             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
731             goto end;
732         case OPT_HELP:
733             opt_help(s_client_options);
734             ret = 0;
735             goto end;
736         case OPT_HOST:
737             host = opt_arg();
738             break;
739         case OPT_PORT:
740             port = atoi(opt_arg());
741             break;
742         case OPT_CONNECT:
743             connectstr = opt_arg();
744             break;
745         case OPT_PROXY:
746             proxystr = opt_arg();
747             starttls_proto = PROTO_CONNECT;
748             break;
749         case OPT_UNIX:
750             unix_path = opt_arg();
751             break;
752         case OPT_XMPPHOST:
753             xmpphost = opt_arg();
754             break;
755         case OPT_SMTPHOST:
756             ehlo = opt_arg();
757             break;
758         case OPT_VERIFY:
759             verify = SSL_VERIFY_PEER;
760             verify_depth = atoi(opt_arg());
761             if (!c_quiet)
762                 BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
763             break;
764         case OPT_CERT:
765             cert_file = opt_arg();
766             break;
767         case OPT_CRL:
768             crl_file = opt_arg();
769             break;
770         case OPT_CRL_DOWNLOAD:
771             crl_download = 1;
772             break;
773         case OPT_SESS_OUT:
774             sess_out = opt_arg();
775             break;
776         case OPT_SESS_IN:
777             sess_in = opt_arg();
778             break;
779         case OPT_CERTFORM:
780             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &cert_format))
781                 goto opthelp;
782             break;
783         case OPT_CRLFORM:
784             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
785                 goto opthelp;
786             break;
787         case OPT_VERIFY_RET_ERROR:
788             verify_return_error = 1;
789             break;
790         case OPT_VERIFY_QUIET:
791             verify_quiet = 1;
792             break;
793         case OPT_BRIEF:
794             c_brief = verify_quiet = c_quiet = 1;
795             break;
796         case OPT_S_CASES:
797             if (ssl_args == NULL)
798                 ssl_args = sk_OPENSSL_STRING_new_null();
799             if (ssl_args == NULL
800                 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
801                 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
802                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
803                 goto end;
804             }
805             break;
806         case OPT_V_CASES:
807             if (!opt_verify(o, vpm))
808                 goto end;
809             vpmtouched++;
810             break;
811         case OPT_X_CASES:
812             if (!args_excert(o, &exc))
813                 goto end;
814             break;
815         case OPT_PREXIT:
816             prexit = 1;
817             break;
818         case OPT_CRLF:
819             crlf = 1;
820             break;
821         case OPT_QUIET:
822             c_quiet = c_ign_eof = 1;
823             break;
824         case OPT_NBIO:
825             c_nbio = 1;
826             break;
827         case OPT_NOCMDS:
828             cmdletters = 0;
829             break;
830         case OPT_ENGINE:
831             e = setup_engine(opt_arg(), 1);
832             break;
833         case OPT_SSL_CLIENT_ENGINE:
834 #ifndef OPENSSL_NO_ENGINE
835             ssl_client_engine = ENGINE_by_id(opt_arg());
836             if (ssl_client_engine == NULL) {
837                 BIO_printf(bio_err, "Error getting client auth engine\n");
838                 goto opthelp;
839             }
840             break;
841 #endif
842             break;
843         case OPT_RAND:
844             inrand = opt_arg();
845             break;
846         case OPT_IGN_EOF:
847             c_ign_eof = 1;
848             break;
849         case OPT_NO_IGN_EOF:
850             c_ign_eof = 0;
851             break;
852         case OPT_PAUSE:
853             c_Pause = 1;
854             break;
855         case OPT_DEBUG:
856             c_debug = 1;
857             break;
858         case OPT_TLSEXTDEBUG:
859             c_tlsextdebug = 1;
860             break;
861         case OPT_STATUS:
862             c_status_req = 1;
863             break;
864         case OPT_WDEBUG:
865 #ifdef WATT32
866             dbug_init();
867 #endif
868             break;
869         case OPT_MSG:
870             c_msg = 1;
871             break;
872         case OPT_MSGFILE:
873             bio_c_msg = BIO_new_file(opt_arg(), "w");
874             break;
875         case OPT_TRACE:
876 #ifndef OPENSSL_NO_SSL_TRACE
877             c_msg = 2;
878 #endif
879             break;
880         case OPT_SECURITY_DEBUG:
881             sdebug = 1;
882             break;
883         case OPT_SECURITY_DEBUG_VERBOSE:
884             sdebug = 2;
885             break;
886         case OPT_SHOWCERTS:
887             c_showcerts = 1;
888             break;
889         case OPT_NBIO_TEST:
890             nbio_test = 1;
891             break;
892         case OPT_STATE:
893             state = 1;
894             break;
895 #ifndef OPENSSL_NO_PSK
896         case OPT_PSK_IDENTITY:
897             psk_identity = opt_arg();
898             break;
899         case OPT_PSK:
900             for (p = psk_key = opt_arg(); *p; p++) {
901                 if (isxdigit(*p))
902                     continue;
903                 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
904                 goto end;
905             }
906             break;
907 #else
908         case OPT_PSK_IDENTITY:
909         case OPT_PSK:
910             break;
911 #endif
912 #ifndef OPENSSL_NO_SRP
913         case OPT_SRPUSER:
914             srp_arg.srplogin = opt_arg();
915             meth = TLSv1_client_method();
916             break;
917         case OPT_SRPPASS:
918             srppass = opt_arg();
919             meth = TLSv1_client_method();
920             break;
921         case OPT_SRP_STRENGTH:
922             srp_arg.strength = atoi(opt_arg());
923             BIO_printf(bio_err, "SRP minimal length for N is %d\n",
924                        srp_arg.strength);
925             meth = TLSv1_client_method();
926             break;
927         case OPT_SRP_LATEUSER:
928             srp_lateuser = 1;
929             meth = TLSv1_client_method();
930             break;
931         case OPT_SRP_MOREGROUPS:
932             srp_arg.amp = 1;
933             meth = TLSv1_client_method();
934             break;
935 #else
936         case OPT_SRPUSER:
937         case OPT_SRPPASS:
938         case OPT_SRP_STRENGTH:
939         case OPT_SRP_LATEUSER:
940         case OPT_SRP_MOREGROUPS:
941             break;
942 #endif
943         case OPT_SSL3:
944 #ifndef OPENSSL_NO_SSL3
945             meth = SSLv3_client_method();
946 #endif
947             break;
948         case OPT_TLS1_2:
949             meth = TLSv1_2_client_method();
950             break;
951         case OPT_TLS1_1:
952             meth = TLSv1_1_client_method();
953             break;
954         case OPT_TLS1:
955             meth = TLSv1_client_method();
956             break;
957 #ifndef OPENSSL_NO_DTLS1
958         case OPT_DTLS:
959             meth = DTLS_client_method();
960             socket_type = SOCK_DGRAM;
961             break;
962         case OPT_DTLS1:
963             meth = DTLSv1_client_method();
964             socket_type = SOCK_DGRAM;
965             break;
966         case OPT_DTLS1_2:
967             meth = DTLSv1_2_client_method();
968             socket_type = SOCK_DGRAM;
969             break;
970         case OPT_TIMEOUT:
971             enable_timeouts = 1;
972             break;
973         case OPT_MTU:
974             socket_mtu = atol(opt_arg());
975             break;
976 #else
977         case OPT_DTLS:
978         case OPT_DTLS1:
979         case OPT_DTLS1_2:
980         case OPT_TIMEOUT:
981         case OPT_MTU:
982             break;
983 #endif
984         case OPT_FALLBACKSCSV:
985             fallback_scsv = 1;
986             break;
987         case OPT_KEYFORM:
988             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &key_format))
989                 goto opthelp;
990             break;
991         case OPT_PASS:
992             passarg = opt_arg();
993             break;
994         case OPT_CERT_CHAIN:
995             chain_file = opt_arg();
996             break;
997         case OPT_KEY:
998             key_file = opt_arg();
999             break;
1000         case OPT_RECONNECT:
1001             reconnect = 5;
1002             break;
1003         case OPT_CAPATH:
1004             CApath = opt_arg();
1005             break;
1006         case OPT_NOCAPATH:
1007             noCApath = 1;
1008             break;
1009         case OPT_CHAINCAPATH:
1010             chCApath = opt_arg();
1011             break;
1012         case OPT_VERIFYCAPATH:
1013             vfyCApath = opt_arg();
1014             break;
1015         case OPT_BUILD_CHAIN:
1016             build_chain = 1;
1017             break;
1018         case OPT_CAFILE:
1019             CAfile = opt_arg();
1020             break;
1021         case OPT_NOCAFILE:
1022             noCAfile = 1;
1023             break;
1024         case OPT_CHAINCAFILE:
1025             chCAfile = opt_arg();
1026             break;
1027         case OPT_VERIFYCAFILE:
1028             vfyCAfile = opt_arg();
1029             break;
1030         case OPT_NEXTPROTONEG:
1031             next_proto_neg_in = opt_arg();
1032             break;
1033         case OPT_ALPN:
1034             alpn_in = opt_arg();
1035             break;
1036         case OPT_SERVERINFO:
1037             p = opt_arg();
1038             len = strlen(p);
1039             for (start = 0, i = 0; i <= len; ++i) {
1040                 if (i == len || p[i] == ',') {
1041                     serverinfo_types[serverinfo_count] = atoi(p + start);
1042                     if (++serverinfo_count == MAX_SI_TYPES)
1043                         break;
1044                     start = i + 1;
1045                 }
1046             }
1047             break;
1048         case OPT_STARTTLS:
1049             if (!opt_pair(opt_arg(), services, &starttls_proto))
1050                 goto end;
1051         case OPT_SERVERNAME:
1052             servername = opt_arg();
1053             break;
1054         case OPT_JPAKE:
1055 #ifndef OPENSSL_NO_JPAKE
1056             jpake_secret = opt_arg();
1057 #endif
1058             break;
1059         case OPT_USE_SRTP:
1060             srtp_profiles = opt_arg();
1061             break;
1062         case OPT_KEYMATEXPORT:
1063             keymatexportlabel = opt_arg();
1064             break;
1065         case OPT_KEYMATEXPORTLEN:
1066             keymatexportlen = atoi(opt_arg());
1067             break;
1068         case OPT_ASYNC:
1069             async = 1;
1070             break;
1071         }
1072     }
1073     argc = opt_num_rest();
1074     argv = opt_rest();
1075
1076     if (proxystr) {
1077         if (connectstr == NULL) {
1078             BIO_printf(bio_err, "%s: -proxy requires use of -connect\n", prog);
1079             goto opthelp;
1080         }
1081         if (!extract_host_port(proxystr, &host, NULL, &port))
1082             goto end;
1083     }
1084     else if (connectstr != NULL
1085             && !extract_host_port(connectstr, &host, NULL, &port))
1086         goto end;
1087
1088     if (unix_path && (socket_type != SOCK_STREAM)) {
1089         BIO_printf(bio_err,
1090                    "Can't use unix sockets and datagrams together\n");
1091         goto end;
1092     }
1093 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1094     if (jpake_secret) {
1095         if (psk_key) {
1096             BIO_printf(bio_err, "Can't use JPAKE and PSK together\n");
1097             goto end;
1098         }
1099         psk_identity = "JPAKE";
1100     }
1101 #endif
1102
1103 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1104     next_proto.status = -1;
1105     if (next_proto_neg_in) {
1106         next_proto.data =
1107             next_protos_parse(&next_proto.len, next_proto_neg_in);
1108         if (next_proto.data == NULL) {
1109             BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1110             goto end;
1111         }
1112     } else
1113         next_proto.data = NULL;
1114 #endif
1115
1116     if (!app_passwd(passarg, NULL, &pass, NULL)) {
1117         BIO_printf(bio_err, "Error getting password\n");
1118         goto end;
1119     }
1120
1121     if (key_file == NULL)
1122         key_file = cert_file;
1123
1124     if (key_file) {
1125         key = load_key(key_file, key_format, 0, pass, e,
1126                        "client certificate private key file");
1127         if (key == NULL) {
1128             ERR_print_errors(bio_err);
1129             goto end;
1130         }
1131     }
1132
1133     if (cert_file) {
1134         cert = load_cert(cert_file, cert_format,
1135                          NULL, e, "client certificate file");
1136         if (cert == NULL) {
1137             ERR_print_errors(bio_err);
1138             goto end;
1139         }
1140     }
1141
1142     if (chain_file) {
1143         chain = load_certs(chain_file, FORMAT_PEM,
1144                            NULL, e, "client certificate chain");
1145         if (!chain)
1146             goto end;
1147     }
1148
1149     if (crl_file) {
1150         X509_CRL *crl;
1151         crl = load_crl(crl_file, crl_format);
1152         if (crl == NULL) {
1153             BIO_puts(bio_err, "Error loading CRL\n");
1154             ERR_print_errors(bio_err);
1155             goto end;
1156         }
1157         crls = sk_X509_CRL_new_null();
1158         if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1159             BIO_puts(bio_err, "Error adding CRL\n");
1160             ERR_print_errors(bio_err);
1161             X509_CRL_free(crl);
1162             goto end;
1163         }
1164     }
1165
1166     if (!load_excert(&exc))
1167         goto end;
1168
1169     if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1170         && !RAND_status()) {
1171         BIO_printf(bio_err,
1172                    "warning, not much extra random data, consider using the -rand option\n");
1173     }
1174     if (inrand != NULL) {
1175         randamt = app_RAND_load_files(inrand);
1176         BIO_printf(bio_err, "%ld semi-random bytes loaded\n", randamt);
1177     }
1178
1179     if (bio_c_out == NULL) {
1180         if (c_quiet && !c_debug) {
1181             bio_c_out = BIO_new(BIO_s_null());
1182             if (c_msg && !bio_c_msg)
1183                 bio_c_msg = dup_bio_out(FORMAT_TEXT);
1184         } else if (bio_c_out == NULL)
1185             bio_c_out = dup_bio_out(FORMAT_TEXT);
1186     }
1187 #ifndef OPENSSL_NO_SRP
1188     if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1189         BIO_printf(bio_err, "Error getting password\n");
1190         goto end;
1191     }
1192 #endif
1193
1194     ctx = SSL_CTX_new(meth);
1195     if (ctx == NULL) {
1196         ERR_print_errors(bio_err);
1197         goto end;
1198     }
1199
1200     if (sdebug)
1201         ssl_ctx_security_debug(ctx, sdebug);
1202
1203     if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1204         BIO_printf(bio_err, "Error setting verify params\n");
1205         ERR_print_errors(bio_err);
1206         goto end;
1207     }
1208
1209     if (async) {
1210         SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1211         ASYNC_init(1, 0, 0);
1212     }
1213
1214     if (!config_ctx(cctx, ssl_args, ctx, 1, jpake_secret == NULL))
1215         goto end;
1216
1217     if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1218                          crls, crl_download)) {
1219         BIO_printf(bio_err, "Error loading store locations\n");
1220         ERR_print_errors(bio_err);
1221         goto end;
1222     }
1223 #ifndef OPENSSL_NO_ENGINE
1224     if (ssl_client_engine) {
1225         if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1226             BIO_puts(bio_err, "Error setting client auth engine\n");
1227             ERR_print_errors(bio_err);
1228             ENGINE_free(ssl_client_engine);
1229             goto end;
1230         }
1231         ENGINE_free(ssl_client_engine);
1232     }
1233 #endif
1234
1235 #ifndef OPENSSL_NO_PSK
1236     if (psk_key != NULL || jpake_secret) {
1237         if (c_debug)
1238             BIO_printf(bio_c_out,
1239                        "PSK key given or JPAKE in use, setting client callback\n");
1240         SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1241     }
1242 #endif
1243 #ifndef OPENSSL_NO_SRTP
1244     if (srtp_profiles != NULL) {
1245         /* Returns 0 on success! */
1246         if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1247             BIO_printf(bio_err, "Error setting SRTP profile\n");
1248             ERR_print_errors(bio_err);
1249             goto end;
1250         }
1251     }
1252 #endif
1253
1254     if (exc)
1255         ssl_ctx_set_excert(ctx, exc);
1256
1257 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1258     if (next_proto.data)
1259         SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1260 #endif
1261     if (alpn_in) {
1262         unsigned short alpn_len;
1263         unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1264
1265         if (alpn == NULL) {
1266             BIO_printf(bio_err, "Error parsing -alpn argument\n");
1267             goto end;
1268         }
1269         /* Returns 0 on success! */
1270         if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1271            BIO_printf(bio_err, "Error setting ALPN\n");
1272             goto end;
1273         }
1274         OPENSSL_free(alpn);
1275     }
1276
1277     for (i = 0; i < serverinfo_count; i++) {
1278         if (!SSL_CTX_add_client_custom_ext(ctx,
1279                                            serverinfo_types[i],
1280                                            NULL, NULL, NULL,
1281                                            serverinfo_cli_parse_cb, NULL)) {
1282             BIO_printf(bio_err,
1283                     "Warning: Unable to add custom extension %u, skipping\n",
1284                     serverinfo_types[i]);
1285         }
1286     }
1287
1288     if (state)
1289         SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1290
1291     SSL_CTX_set_verify(ctx, verify, verify_callback);
1292
1293     if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1294         ERR_print_errors(bio_err);
1295         goto end;
1296     }
1297
1298     ssl_ctx_add_crls(ctx, crls, crl_download);
1299
1300     if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
1301         goto end;
1302
1303     if (servername != NULL) {
1304         tlsextcbp.biodebug = bio_err;
1305         SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1306         SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1307     }
1308 # ifndef OPENSSL_NO_SRP
1309     if (srp_arg.srplogin) {
1310         if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) {
1311             BIO_printf(bio_err, "Unable to set SRP username\n");
1312             goto end;
1313         }
1314         srp_arg.msg = c_msg;
1315         srp_arg.debug = c_debug;
1316         SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
1317         SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
1318         SSL_CTX_set_srp_strength(ctx, srp_arg.strength);
1319         if (c_msg || c_debug || srp_arg.amp == 0)
1320             SSL_CTX_set_srp_verify_param_callback(ctx,
1321                                                   ssl_srp_verify_param_cb);
1322     }
1323 # endif
1324
1325     con = SSL_new(ctx);
1326     if (sess_in) {
1327         SSL_SESSION *sess;
1328         BIO *stmp = BIO_new_file(sess_in, "r");
1329         if (!stmp) {
1330             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
1331             ERR_print_errors(bio_err);
1332             goto end;
1333         }
1334         sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1335         BIO_free(stmp);
1336         if (!sess) {
1337             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
1338             ERR_print_errors(bio_err);
1339             goto end;
1340         }
1341         if (!SSL_set_session(con, sess)) {
1342             BIO_printf(bio_err, "Can't set session\n");
1343             ERR_print_errors(bio_err);
1344             goto end;
1345         }
1346         SSL_SESSION_free(sess);
1347     }
1348
1349     if (fallback_scsv)
1350         SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
1351
1352     if (servername != NULL) {
1353         if (!SSL_set_tlsext_host_name(con, servername)) {
1354             BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
1355             ERR_print_errors(bio_err);
1356             goto end;
1357         }
1358     }
1359
1360  re_start:
1361 #ifdef NO_SYS_UN_H
1362     if (init_client(&s, host, port, socket_type) == 0)
1363 #else
1364     if ((!unix_path && (init_client(&s, host, port, socket_type) == 0)) ||
1365         (unix_path && (init_client_unix(&s, unix_path) == 0)))
1366 #endif
1367     {
1368         BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
1369         SHUTDOWN(s);
1370         goto end;
1371     }
1372     BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);
1373
1374 #ifdef FIONBIO
1375     if (c_nbio) {
1376         unsigned long l = 1;
1377         BIO_printf(bio_c_out, "turning on non blocking io\n");
1378         if (BIO_socket_ioctl(s, FIONBIO, &l) < 0) {
1379             ERR_print_errors(bio_err);
1380             goto end;
1381         }
1382     }
1383 #endif
1384     if (c_Pause & 0x01)
1385         SSL_set_debug(con, 1);
1386
1387     if (socket_type == SOCK_DGRAM) {
1388
1389         sbio = BIO_new_dgram(s, BIO_NOCLOSE);
1390         if (getsockname(s, &peer, (void *)&peerlen) < 0) {
1391             BIO_printf(bio_err, "getsockname:errno=%d\n",
1392                        get_last_socket_error());
1393             SHUTDOWN(s);
1394             goto end;
1395         }
1396
1397         (void)BIO_ctrl_set_connected(sbio, &peer);
1398
1399         if (enable_timeouts) {
1400             timeout.tv_sec = 0;
1401             timeout.tv_usec = DGRAM_RCV_TIMEOUT;
1402             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
1403
1404             timeout.tv_sec = 0;
1405             timeout.tv_usec = DGRAM_SND_TIMEOUT;
1406             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
1407         }
1408
1409         if (socket_mtu) {
1410             if (socket_mtu < DTLS_get_link_min_mtu(con)) {
1411                 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
1412                            DTLS_get_link_min_mtu(con));
1413                 BIO_free(sbio);
1414                 goto shut;
1415             }
1416             SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
1417             if (!DTLS_set_link_mtu(con, socket_mtu)) {
1418                 BIO_printf(bio_err, "Failed to set MTU\n");
1419                 BIO_free(sbio);
1420                 goto shut;
1421             }
1422         } else
1423             /* want to do MTU discovery */
1424             BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
1425     } else
1426         sbio = BIO_new_socket(s, BIO_NOCLOSE);
1427
1428     if (nbio_test) {
1429         BIO *test;
1430
1431         test = BIO_new(BIO_f_nbio_test());
1432         sbio = BIO_push(test, sbio);
1433     }
1434
1435     if (c_debug) {
1436         SSL_set_debug(con, 1);
1437         BIO_set_callback(sbio, bio_dump_callback);
1438         BIO_set_callback_arg(sbio, (char *)bio_c_out);
1439     }
1440     if (c_msg) {
1441 #ifndef OPENSSL_NO_SSL_TRACE
1442         if (c_msg == 2)
1443             SSL_set_msg_callback(con, SSL_trace);
1444         else
1445 #endif
1446             SSL_set_msg_callback(con, msg_cb);
1447         SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
1448     }
1449
1450     if (c_tlsextdebug) {
1451         SSL_set_tlsext_debug_callback(con, tlsext_cb);
1452         SSL_set_tlsext_debug_arg(con, bio_c_out);
1453     }
1454     if (c_status_req) {
1455         SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
1456         SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
1457         SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
1458     }
1459 #ifndef OPENSSL_NO_JPAKE
1460     if (jpake_secret)
1461         jpake_client_auth(bio_c_out, sbio, jpake_secret);
1462 #endif
1463
1464     SSL_set_bio(con, sbio, sbio);
1465     SSL_set_connect_state(con);
1466
1467     /* ok, lets connect */
1468     width = SSL_get_fd(con) + 1;
1469
1470     read_tty = 1;
1471     write_tty = 0;
1472     tty_on = 0;
1473     read_ssl = 1;
1474     write_ssl = 1;
1475
1476     cbuf_len = 0;
1477     cbuf_off = 0;
1478     sbuf_len = 0;
1479     sbuf_off = 0;
1480
1481     switch ((PROTOCOL_CHOICE) starttls_proto) {
1482     case PROTO_OFF:
1483         break;
1484     case PROTO_SMTP:
1485         {
1486             /*
1487              * This is an ugly hack that does a lot of assumptions. We do
1488              * have to handle multi-line responses which may come in a single
1489              * packet or not. We therefore have to use BIO_gets() which does
1490              * need a buffering BIO. So during the initial chitchat we do
1491              * push a buffering BIO into the chain that is removed again
1492              * later on to not disturb the rest of the s_client operation.
1493              */
1494             int foundit = 0;
1495             BIO *fbio = BIO_new(BIO_f_buffer());
1496             BIO_push(fbio, sbio);
1497             /* wait for multi-line response to end from SMTP */
1498             do {
1499                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1500             }
1501             while (mbuf_len > 3 && mbuf[3] == '-');
1502             BIO_printf(fbio, "EHLO %s\r\n", ehlo);
1503             (void)BIO_flush(fbio);
1504             /* wait for multi-line response to end EHLO SMTP response */
1505             do {
1506                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1507                 if (strstr(mbuf, "STARTTLS"))
1508                     foundit = 1;
1509             }
1510             while (mbuf_len > 3 && mbuf[3] == '-');
1511             (void)BIO_flush(fbio);
1512             BIO_pop(fbio);
1513             BIO_free(fbio);
1514             if (!foundit)
1515                 BIO_printf(bio_err,
1516                            "didn't found starttls in server response,"
1517                            " try anyway...\n");
1518             BIO_printf(sbio, "STARTTLS\r\n");
1519             BIO_read(sbio, sbuf, BUFSIZZ);
1520         }
1521         break;
1522     case PROTO_POP3:
1523         {
1524             BIO_read(sbio, mbuf, BUFSIZZ);
1525             BIO_printf(sbio, "STLS\r\n");
1526             mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
1527             if (mbuf_len < 0) {
1528                 BIO_printf(bio_err, "BIO_read failed\n");
1529                 goto end;
1530             }
1531         }
1532         break;
1533     case PROTO_IMAP:
1534         {
1535             int foundit = 0;
1536             BIO *fbio = BIO_new(BIO_f_buffer());
1537             BIO_push(fbio, sbio);
1538             BIO_gets(fbio, mbuf, BUFSIZZ);
1539             /* STARTTLS command requires CAPABILITY... */
1540             BIO_printf(fbio, ". CAPABILITY\r\n");
1541             (void)BIO_flush(fbio);
1542             /* wait for multi-line CAPABILITY response */
1543             do {
1544                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1545                 if (strstr(mbuf, "STARTTLS"))
1546                     foundit = 1;
1547             }
1548             while (mbuf_len > 3 && mbuf[0] != '.');
1549             (void)BIO_flush(fbio);
1550             BIO_pop(fbio);
1551             BIO_free(fbio);
1552             if (!foundit)
1553                 BIO_printf(bio_err,
1554                            "didn't found STARTTLS in server response,"
1555                            " try anyway...\n");
1556             BIO_printf(sbio, ". STARTTLS\r\n");
1557             BIO_read(sbio, sbuf, BUFSIZZ);
1558         }
1559         break;
1560     case PROTO_FTP:
1561         {
1562             BIO *fbio = BIO_new(BIO_f_buffer());
1563             BIO_push(fbio, sbio);
1564             /* wait for multi-line response to end from FTP */
1565             do {
1566                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1567             }
1568             while (mbuf_len > 3 && mbuf[3] == '-');
1569             (void)BIO_flush(fbio);
1570             BIO_pop(fbio);
1571             BIO_free(fbio);
1572             BIO_printf(sbio, "AUTH TLS\r\n");
1573             BIO_read(sbio, sbuf, BUFSIZZ);
1574         }
1575         break;
1576     case PROTO_XMPP:
1577     case PROTO_XMPP_SERVER:
1578         {
1579             int seen = 0;
1580             BIO_printf(sbio, "<stream:stream "
1581                        "xmlns:stream='http://etherx.jabber.org/streams' "
1582                        "xmlns='jabber:%s' to='%s' version='1.0'>",
1583                        starttls_proto == PROTO_XMPP ? "client" : "server",
1584                        xmpphost ? xmpphost : host);
1585             seen = BIO_read(sbio, mbuf, BUFSIZZ);
1586             mbuf[seen] = 0;
1587             while (!strstr
1588                    (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
1589                    && !strstr(mbuf,
1590                               "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
1591             {
1592                 seen = BIO_read(sbio, mbuf, BUFSIZZ);
1593
1594                 if (seen <= 0)
1595                     goto shut;
1596
1597                 mbuf[seen] = 0;
1598             }
1599             BIO_printf(sbio,
1600                        "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
1601             seen = BIO_read(sbio, sbuf, BUFSIZZ);
1602             sbuf[seen] = 0;
1603             if (!strstr(sbuf, "<proceed"))
1604                 goto shut;
1605             mbuf[0] = 0;
1606         }
1607         break;
1608     case PROTO_TELNET:
1609         {
1610             static const unsigned char tls_do[] = {
1611                 /* IAC    DO   START_TLS */
1612                    255,   253, 46
1613             };
1614             static const unsigned char tls_will[] = {
1615                 /* IAC  WILL START_TLS */
1616                    255, 251, 46
1617             };
1618             static const unsigned char tls_follows[] = {
1619                 /* IAC  SB   START_TLS FOLLOWS IAC  SE */
1620                    255, 250, 46,       1,      255, 240
1621             };
1622             int bytes;
1623
1624             /* Telnet server should demand we issue START_TLS */
1625             bytes = BIO_read(sbio, mbuf, BUFSIZZ);
1626             if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
1627                 goto shut;
1628             /* Agree to issue START_TLS and send the FOLLOWS sub-command */
1629             BIO_write(sbio, tls_will, 3);
1630             BIO_write(sbio, tls_follows, 6);
1631             (void)BIO_flush(sbio);
1632             /* Telnet server also sent the FOLLOWS sub-command */
1633             bytes = BIO_read(sbio, mbuf, BUFSIZZ);
1634             if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
1635                 goto shut;
1636         }
1637         break;
1638     case PROTO_CONNECT:
1639         {
1640             int foundit = 0;
1641             BIO *fbio = BIO_new(BIO_f_buffer());
1642
1643             BIO_push(fbio, sbio);
1644             BIO_printf(fbio, "CONNECT %s\r\n\r\n", connectstr);
1645             (void)BIO_flush(fbio);
1646             /* wait for multi-line response to end CONNECT response */
1647             do {
1648                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1649                 if (strstr(mbuf, "200") != NULL
1650                     && strstr(mbuf, "established") != NULL)
1651                     foundit++;
1652             } while (mbuf_len > 3 && foundit == 0);
1653             (void)BIO_flush(fbio);
1654             BIO_pop(fbio);
1655             BIO_free(fbio);
1656             if (!foundit) {
1657                 BIO_printf(bio_err, "%s: HTTP CONNECT failed\n", prog);
1658                 goto shut;
1659             }
1660         }
1661         break;
1662     case PROTO_IRC:
1663         {
1664             int numeric;
1665             BIO *fbio = BIO_new(BIO_f_buffer());
1666
1667             BIO_push(fbio, sbio);
1668             BIO_printf(fbio, "STARTTLS\r\n");
1669             (void)BIO_flush(fbio);
1670             width = SSL_get_fd(con) + 1;
1671
1672             do {
1673                 numeric = 0;
1674
1675                 FD_ZERO(&readfds);
1676                 openssl_fdset(SSL_get_fd(con), &readfds);
1677                 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
1678                 timeout.tv_usec = 0;
1679                 /*
1680                  * If the IRCd doesn't respond within
1681                  * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
1682                  * it doesn't support STARTTLS. Many IRCds
1683                  * will not give _any_ sort of response to a
1684                  * STARTTLS command when it's not supported.
1685                  */
1686                 if (!BIO_get_buffer_num_lines(fbio)
1687                     && !BIO_pending(fbio)
1688                     && !BIO_pending(sbio)
1689                     && select(width, (void *)&readfds, NULL, NULL,
1690                               &timeout) < 1) {
1691                     BIO_printf(bio_err,
1692                                "Timeout waiting for response (%d seconds).\n",
1693                                S_CLIENT_IRC_READ_TIMEOUT);
1694                     break;
1695                 }
1696
1697                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1698                 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
1699                     break;
1700                 /* :example.net 451 STARTTLS :You have not registered */
1701                 /* :example.net 421 STARTTLS :Unknown command */
1702                 if ((numeric == 451 || numeric == 421)
1703                     && strstr(mbuf, "STARTTLS") != NULL) {
1704                     BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
1705                     break;
1706                 }
1707                 if (numeric == 691) {
1708                     BIO_printf(bio_err, "STARTTLS negotiation failed: ");
1709                     ERR_print_errors(bio_err);
1710                     break;
1711                 }
1712             } while (numeric != 670);
1713
1714             (void)BIO_flush(fbio);
1715             BIO_pop(fbio);
1716             BIO_free(fbio);
1717             if (numeric != 670) {
1718                 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
1719                 ret = 1;
1720                 goto shut;
1721             }
1722         }
1723     }
1724
1725     for (;;) {
1726         FD_ZERO(&readfds);
1727         FD_ZERO(&writefds);
1728
1729         if ((SSL_version(con) == DTLS1_VERSION) &&
1730             DTLSv1_get_timeout(con, &timeout))
1731             timeoutp = &timeout;
1732         else
1733             timeoutp = NULL;
1734
1735         if (SSL_in_init(con) && !SSL_total_renegotiations(con)) {
1736             in_init = 1;
1737             tty_on = 0;
1738         } else {
1739             tty_on = 1;
1740             if (in_init) {
1741                 in_init = 0;
1742
1743                 if (servername != NULL && !SSL_session_reused(con)) {
1744                     BIO_printf(bio_c_out,
1745                                "Server did %sacknowledge servername extension.\n",
1746                                tlsextcbp.ack ? "" : "not ");
1747                 }
1748
1749                 if (sess_out) {
1750                     BIO *stmp = BIO_new_file(sess_out, "w");
1751                     if (stmp) {
1752                         PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con));
1753                         BIO_free(stmp);
1754                     } else
1755                         BIO_printf(bio_err, "Error writing session file %s\n",
1756                                    sess_out);
1757                 }
1758                 if (c_brief) {
1759                     BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
1760                     print_ssl_summary(con);
1761                 }
1762
1763                 print_stuff(bio_c_out, con, full_log);
1764                 if (full_log > 0)
1765                     full_log--;
1766
1767                 if (starttls_proto) {
1768                     BIO_write(bio_err, mbuf, mbuf_len);
1769                     /* We don't need to know any more */
1770                     if (!reconnect)
1771                         starttls_proto = PROTO_OFF;
1772                 }
1773
1774                 if (reconnect) {
1775                     reconnect--;
1776                     BIO_printf(bio_c_out,
1777                                "drop connection and then reconnect\n");
1778                     SSL_shutdown(con);
1779                     SSL_set_connect_state(con);
1780                     SHUTDOWN(SSL_get_fd(con));
1781                     goto re_start;
1782                 }
1783             }
1784         }
1785
1786         ssl_pending = read_ssl && SSL_pending(con);
1787
1788         if (!ssl_pending) {
1789 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE)
1790             if (tty_on) {
1791                 if (read_tty)
1792                     openssl_fdset(fileno(stdin), &readfds);
1793                 if (write_tty)
1794                     openssl_fdset(fileno(stdout), &writefds);
1795             }
1796             if (read_ssl)
1797                 openssl_fdset(SSL_get_fd(con), &readfds);
1798             if (write_ssl)
1799                 openssl_fdset(SSL_get_fd(con), &writefds);
1800 #else
1801             if (!tty_on || !write_tty) {
1802                 if (read_ssl)
1803                     openssl_fdset(SSL_get_fd(con), &readfds);
1804                 if (write_ssl)
1805                     openssl_fdset(SSL_get_fd(con), &writefds);
1806             }
1807 #endif
1808
1809             /*
1810              * Note: under VMS with SOCKETSHR the second parameter is
1811              * currently of type (int *) whereas under other systems it is
1812              * (void *) if you don't have a cast it will choke the compiler:
1813              * if you do have a cast then you can either go for (int *) or
1814              * (void *).
1815              */
1816 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
1817             /*
1818              * Under Windows/DOS we make the assumption that we can always
1819              * write to the tty: therefore if we need to write to the tty we
1820              * just fall through. Otherwise we timeout the select every
1821              * second and see if there are any keypresses. Note: this is a
1822              * hack, in a proper Windows application we wouldn't do this.
1823              */
1824             i = 0;
1825             if (!write_tty) {
1826                 if (read_tty) {
1827                     tv.tv_sec = 1;
1828                     tv.tv_usec = 0;
1829                     i = select(width, (void *)&readfds, (void *)&writefds,
1830                                NULL, &tv);
1831 # if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
1832                     if (!i && (!_kbhit() || !read_tty))
1833                         continue;
1834 # else
1835                     if (!i && (!((_kbhit())
1836                                  || (WAIT_OBJECT_0 ==
1837                                      WaitForSingleObject(GetStdHandle
1838                                                          (STD_INPUT_HANDLE),
1839                                                          0)))
1840                                || !read_tty))
1841                         continue;
1842 # endif
1843                 } else
1844                     i = select(width, (void *)&readfds, (void *)&writefds,
1845                                NULL, timeoutp);
1846             }
1847 #elif defined(OPENSSL_SYS_NETWARE)
1848             if (!write_tty) {
1849                 if (read_tty) {
1850                     tv.tv_sec = 1;
1851                     tv.tv_usec = 0;
1852                     i = select(width, (void *)&readfds, (void *)&writefds,
1853                                NULL, &tv);
1854                 } else
1855                     i = select(width, (void *)&readfds, (void *)&writefds,
1856                                NULL, timeoutp);
1857             }
1858 #else
1859             i = select(width, (void *)&readfds, (void *)&writefds,
1860                        NULL, timeoutp);
1861 #endif
1862             if (i < 0) {
1863                 BIO_printf(bio_err, "bad select %d\n",
1864                            get_last_socket_error());
1865                 goto shut;
1866                 /* goto end; */
1867             }
1868         }
1869
1870         if ((SSL_version(con) == DTLS1_VERSION)
1871             && DTLSv1_handle_timeout(con) > 0) {
1872             BIO_printf(bio_err, "TIMEOUT occurred\n");
1873         }
1874
1875         if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
1876             k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
1877             switch (SSL_get_error(con, k)) {
1878             case SSL_ERROR_NONE:
1879                 cbuf_off += k;
1880                 cbuf_len -= k;
1881                 if (k <= 0)
1882                     goto end;
1883                 /* we have done a  write(con,NULL,0); */
1884                 if (cbuf_len <= 0) {
1885                     read_tty = 1;
1886                     write_ssl = 0;
1887                 } else {        /* if (cbuf_len > 0) */
1888
1889                     read_tty = 0;
1890                     write_ssl = 1;
1891                 }
1892                 break;
1893             case SSL_ERROR_WANT_WRITE:
1894                 BIO_printf(bio_c_out, "write W BLOCK\n");
1895                 write_ssl = 1;
1896                 read_tty = 0;
1897                 break;
1898             case SSL_ERROR_WANT_ASYNC:
1899                 BIO_printf(bio_c_out, "write A BLOCK\n");
1900                 wait_for_async(con);
1901                 write_ssl = 1;
1902                 read_tty = 0;
1903                 break;
1904             case SSL_ERROR_WANT_READ:
1905                 BIO_printf(bio_c_out, "write R BLOCK\n");
1906                 write_tty = 0;
1907                 read_ssl = 1;
1908                 write_ssl = 0;
1909                 break;
1910             case SSL_ERROR_WANT_X509_LOOKUP:
1911                 BIO_printf(bio_c_out, "write X BLOCK\n");
1912                 break;
1913             case SSL_ERROR_ZERO_RETURN:
1914                 if (cbuf_len != 0) {
1915                     BIO_printf(bio_c_out, "shutdown\n");
1916                     ret = 0;
1917                     goto shut;
1918                 } else {
1919                     read_tty = 1;
1920                     write_ssl = 0;
1921                     break;
1922                 }
1923
1924             case SSL_ERROR_SYSCALL:
1925                 if ((k != 0) || (cbuf_len != 0)) {
1926                     BIO_printf(bio_err, "write:errno=%d\n",
1927                                get_last_socket_error());
1928                     goto shut;
1929                 } else {
1930                     read_tty = 1;
1931                     write_ssl = 0;
1932                 }
1933                 break;
1934             case SSL_ERROR_SSL:
1935                 ERR_print_errors(bio_err);
1936                 goto shut;
1937             }
1938         }
1939 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
1940         /* Assume Windows/DOS/BeOS can always write */
1941         else if (!ssl_pending && write_tty)
1942 #else
1943         else if (!ssl_pending && FD_ISSET(fileno(stdout), &writefds))
1944 #endif
1945         {
1946 #ifdef CHARSET_EBCDIC
1947             ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
1948 #endif
1949             i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
1950
1951             if (i <= 0) {
1952                 BIO_printf(bio_c_out, "DONE\n");
1953                 ret = 0;
1954                 goto shut;
1955                 /* goto end; */
1956             }
1957
1958             sbuf_len -= i;;
1959             sbuf_off += i;
1960             if (sbuf_len <= 0) {
1961                 read_ssl = 1;
1962                 write_tty = 0;
1963             }
1964         } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
1965 #ifdef RENEG
1966             {
1967                 static int iiii;
1968                 if (++iiii == 52) {
1969                     SSL_renegotiate(con);
1970                     iiii = 0;
1971                 }
1972             }
1973 #endif
1974             k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
1975
1976             switch (SSL_get_error(con, k)) {
1977             case SSL_ERROR_NONE:
1978                 if (k <= 0)
1979                     goto end;
1980                 sbuf_off = 0;
1981                 sbuf_len = k;
1982
1983                 read_ssl = 0;
1984                 write_tty = 1;
1985                 break;
1986             case SSL_ERROR_WANT_ASYNC:
1987                 BIO_printf(bio_c_out, "read A BLOCK\n");
1988                 wait_for_async(con);
1989                 write_tty = 0;
1990                 read_ssl = 1;
1991                 if ((read_tty == 0) && (write_ssl == 0))
1992                     write_ssl = 1;
1993                 break;
1994             case SSL_ERROR_WANT_WRITE:
1995                 BIO_printf(bio_c_out, "read W BLOCK\n");
1996                 write_ssl = 1;
1997                 read_tty = 0;
1998                 break;
1999             case SSL_ERROR_WANT_READ:
2000                 BIO_printf(bio_c_out, "read R BLOCK\n");
2001                 write_tty = 0;
2002                 read_ssl = 1;
2003                 if ((read_tty == 0) && (write_ssl == 0))
2004                     write_ssl = 1;
2005                 break;
2006             case SSL_ERROR_WANT_X509_LOOKUP:
2007                 BIO_printf(bio_c_out, "read X BLOCK\n");
2008                 break;
2009             case SSL_ERROR_SYSCALL:
2010                 ret = get_last_socket_error();
2011                 if (c_brief)
2012                     BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
2013                 else
2014                     BIO_printf(bio_err, "read:errno=%d\n", ret);
2015                 goto shut;
2016             case SSL_ERROR_ZERO_RETURN:
2017                 BIO_printf(bio_c_out, "closed\n");
2018                 ret = 0;
2019                 goto shut;
2020             case SSL_ERROR_SSL:
2021                 ERR_print_errors(bio_err);
2022                 goto shut;
2023                 /* break; */
2024             }
2025         }
2026 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2027 # if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
2028         else if (_kbhit())
2029 # else
2030         else if ((_kbhit())
2031                  || (WAIT_OBJECT_0 ==
2032                      WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0)))
2033 # endif
2034 #elif defined (OPENSSL_SYS_NETWARE)
2035         else if (_kbhit())
2036 #else
2037         else if (FD_ISSET(fileno(stdin), &readfds))
2038 #endif
2039         {
2040             if (crlf) {
2041                 int j, lf_num;
2042
2043                 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
2044                 lf_num = 0;
2045                 /* both loops are skipped when i <= 0 */
2046                 for (j = 0; j < i; j++)
2047                     if (cbuf[j] == '\n')
2048                         lf_num++;
2049                 for (j = i - 1; j >= 0; j--) {
2050                     cbuf[j + lf_num] = cbuf[j];
2051                     if (cbuf[j] == '\n') {
2052                         lf_num--;
2053                         i++;
2054                         cbuf[j + lf_num] = '\r';
2055                     }
2056                 }
2057                 assert(lf_num == 0);
2058             } else
2059                 i = raw_read_stdin(cbuf, BUFSIZZ);
2060
2061             if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q' && cmdletters))) {
2062                 BIO_printf(bio_err, "DONE\n");
2063                 ret = 0;
2064                 goto shut;
2065             }
2066
2067             if ((!c_ign_eof) && (cbuf[0] == 'R' && cmdletters)) {
2068                 BIO_printf(bio_err, "RENEGOTIATING\n");
2069                 SSL_renegotiate(con);
2070                 cbuf_len = 0;
2071             }
2072 #ifndef OPENSSL_NO_HEARTBEATS
2073             else if ((!c_ign_eof) && (cbuf[0] == 'B' && cmdletters)) {
2074                 BIO_printf(bio_err, "HEARTBEATING\n");
2075                 SSL_heartbeat(con);
2076                 cbuf_len = 0;
2077             }
2078 #endif
2079             else {
2080                 cbuf_len = i;
2081                 cbuf_off = 0;
2082 #ifdef CHARSET_EBCDIC
2083                 ebcdic2ascii(cbuf, cbuf, i);
2084 #endif
2085             }
2086
2087             write_ssl = 1;
2088             read_tty = 0;
2089         }
2090     }
2091
2092     ret = 0;
2093  shut:
2094     if (in_init)
2095         print_stuff(bio_c_out, con, full_log);
2096     SSL_shutdown(con);
2097     SHUTDOWN(SSL_get_fd(con));
2098  end:
2099     if (con != NULL) {
2100         if (prexit != 0)
2101             print_stuff(bio_c_out, con, 1);
2102         SSL_free(con);
2103     }
2104     if (async) {
2105         ASYNC_cleanup(1);
2106     }
2107 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2108     OPENSSL_free(next_proto.data);
2109 #endif
2110     SSL_CTX_free(ctx);
2111     X509_free(cert);
2112     sk_X509_CRL_pop_free(crls, X509_CRL_free);
2113     EVP_PKEY_free(key);
2114     sk_X509_pop_free(chain, X509_free);
2115     OPENSSL_free(pass);
2116 #ifndef OPENSSL_NO_SRP
2117     OPENSSL_free(srp_arg.srppassin);
2118 #endif
2119     X509_VERIFY_PARAM_free(vpm);
2120     ssl_excert_free(exc);
2121     sk_OPENSSL_STRING_free(ssl_args);
2122     SSL_CONF_CTX_free(cctx);
2123     OPENSSL_clear_free(cbuf, BUFSIZZ);
2124     OPENSSL_clear_free(sbuf, BUFSIZZ);
2125     OPENSSL_clear_free(mbuf, BUFSIZZ);
2126     BIO_free(bio_c_out);
2127     bio_c_out = NULL;
2128     BIO_free(bio_c_msg);
2129     bio_c_msg = NULL;
2130     return (ret);
2131 }
2132
2133 static void print_stuff(BIO *bio, SSL *s, int full)
2134 {
2135     X509 *peer = NULL;
2136     char buf[BUFSIZ];
2137     STACK_OF(X509) *sk;
2138     STACK_OF(X509_NAME) *sk2;
2139     const SSL_CIPHER *c;
2140     X509_NAME *xn;
2141     int i;
2142 #ifndef OPENSSL_NO_COMP
2143     const COMP_METHOD *comp, *expansion;
2144 #endif
2145     unsigned char *exportedkeymat;
2146
2147     if (full) {
2148         int got_a_chain = 0;
2149
2150         sk = SSL_get_peer_cert_chain(s);
2151         if (sk != NULL) {
2152             got_a_chain = 1;
2153
2154             BIO_printf(bio, "---\nCertificate chain\n");
2155             for (i = 0; i < sk_X509_num(sk); i++) {
2156                 X509_NAME_oneline(X509_get_subject_name(sk_X509_value(sk, i)),
2157                                   buf, sizeof buf);
2158                 BIO_printf(bio, "%2d s:%s\n", i, buf);
2159                 X509_NAME_oneline(X509_get_issuer_name(sk_X509_value(sk, i)),
2160                                   buf, sizeof buf);
2161                 BIO_printf(bio, "   i:%s\n", buf);
2162                 if (c_showcerts)
2163                     PEM_write_bio_X509(bio, sk_X509_value(sk, i));
2164             }
2165         }
2166
2167         BIO_printf(bio, "---\n");
2168         peer = SSL_get_peer_certificate(s);
2169         if (peer != NULL) {
2170             BIO_printf(bio, "Server certificate\n");
2171
2172             /* Redundant if we showed the whole chain */
2173             if (!(c_showcerts && got_a_chain))
2174                 PEM_write_bio_X509(bio, peer);
2175             X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
2176             BIO_printf(bio, "subject=%s\n", buf);
2177             X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
2178             BIO_printf(bio, "issuer=%s\n", buf);
2179         } else
2180             BIO_printf(bio, "no peer certificate available\n");
2181
2182         sk2 = SSL_get_client_CA_list(s);
2183         if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0)) {
2184             BIO_printf(bio, "---\nAcceptable client certificate CA names\n");
2185             for (i = 0; i < sk_X509_NAME_num(sk2); i++) {
2186                 xn = sk_X509_NAME_value(sk2, i);
2187                 X509_NAME_oneline(xn, buf, sizeof(buf));
2188                 BIO_write(bio, buf, strlen(buf));
2189                 BIO_write(bio, "\n", 1);
2190             }
2191         } else {
2192             BIO_printf(bio, "---\nNo client certificate CA names sent\n");
2193         }
2194
2195         ssl_print_sigalgs(bio, s);
2196         ssl_print_tmp_key(bio, s);
2197
2198         BIO_printf(bio,
2199                    "---\nSSL handshake has read %"PRIu64" bytes and written %"PRIu64" bytes\n",
2200                    BIO_number_read(SSL_get_rbio(s)),
2201                    BIO_number_written(SSL_get_wbio(s)));
2202     }
2203     BIO_printf(bio, (SSL_cache_hit(s) ? "---\nReused, " : "---\nNew, "));
2204     c = SSL_get_current_cipher(s);
2205     BIO_printf(bio, "%s, Cipher is %s\n",
2206                SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2207     if (peer != NULL) {
2208         EVP_PKEY *pktmp;
2209         pktmp = X509_get_pubkey(peer);
2210         BIO_printf(bio, "Server public key is %d bit\n",
2211                    EVP_PKEY_bits(pktmp));
2212         EVP_PKEY_free(pktmp);
2213     }
2214     BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
2215                SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
2216 #ifndef OPENSSL_NO_COMP
2217     comp = SSL_get_current_compression(s);
2218     expansion = SSL_get_current_expansion(s);
2219     BIO_printf(bio, "Compression: %s\n",
2220                comp ? SSL_COMP_get_name(comp) : "NONE");
2221     BIO_printf(bio, "Expansion: %s\n",
2222                expansion ? SSL_COMP_get_name(expansion) : "NONE");
2223 #endif
2224
2225 #ifdef SSL_DEBUG
2226     {
2227         /* Print out local port of connection: useful for debugging */
2228         int sock;
2229         struct sockaddr_in ladd;
2230         socklen_t ladd_size = sizeof(ladd);
2231         sock = SSL_get_fd(s);
2232         getsockname(sock, (struct sockaddr *)&ladd, &ladd_size);
2233         BIO_printf(bio_c_out, "LOCAL PORT is %u\n", ntohs(ladd.sin_port));
2234     }
2235 #endif
2236
2237 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2238     if (next_proto.status != -1) {
2239         const unsigned char *proto;
2240         unsigned int proto_len;
2241         SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
2242         BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
2243         BIO_write(bio, proto, proto_len);
2244         BIO_write(bio, "\n", 1);
2245     }
2246 #endif
2247     {
2248         const unsigned char *proto;
2249         unsigned int proto_len;
2250         SSL_get0_alpn_selected(s, &proto, &proto_len);
2251         if (proto_len > 0) {
2252             BIO_printf(bio, "ALPN protocol: ");
2253             BIO_write(bio, proto, proto_len);
2254             BIO_write(bio, "\n", 1);
2255         } else
2256             BIO_printf(bio, "No ALPN negotiated\n");
2257     }
2258
2259 #ifndef OPENSSL_NO_SRTP
2260     {
2261         SRTP_PROTECTION_PROFILE *srtp_profile =
2262             SSL_get_selected_srtp_profile(s);
2263
2264         if (srtp_profile)
2265             BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
2266                        srtp_profile->name);
2267     }
2268 #endif
2269
2270     SSL_SESSION_print(bio, SSL_get_session(s));
2271     if (keymatexportlabel != NULL) {
2272         BIO_printf(bio, "Keying material exporter:\n");
2273         BIO_printf(bio, "    Label: '%s'\n", keymatexportlabel);
2274         BIO_printf(bio, "    Length: %i bytes\n", keymatexportlen);
2275         exportedkeymat = app_malloc(keymatexportlen, "export key");
2276         if (!SSL_export_keying_material(s, exportedkeymat,
2277                                         keymatexportlen,
2278                                         keymatexportlabel,
2279                                         strlen(keymatexportlabel),
2280                                         NULL, 0, 0)) {
2281             BIO_printf(bio, "    Error\n");
2282         } else {
2283             BIO_printf(bio, "    Keying material: ");
2284             for (i = 0; i < keymatexportlen; i++)
2285                 BIO_printf(bio, "%02X", exportedkeymat[i]);
2286             BIO_printf(bio, "\n");
2287         }
2288         OPENSSL_free(exportedkeymat);
2289     }
2290     BIO_printf(bio, "---\n");
2291     X509_free(peer);
2292     /* flush, or debugging output gets mixed with http response */
2293     (void)BIO_flush(bio);
2294 }
2295
2296 static int ocsp_resp_cb(SSL *s, void *arg)
2297 {
2298     const unsigned char *p;
2299     int len;
2300     OCSP_RESPONSE *rsp;
2301     len = SSL_get_tlsext_status_ocsp_resp(s, &p);
2302     BIO_puts(arg, "OCSP response: ");
2303     if (!p) {
2304         BIO_puts(arg, "no response sent\n");
2305         return 1;
2306     }
2307     rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
2308     if (!rsp) {
2309         BIO_puts(arg, "response parse error\n");
2310         BIO_dump_indent(arg, (char *)p, len, 4);
2311         return 0;
2312     }
2313     BIO_puts(arg, "\n======================================\n");
2314     OCSP_RESPONSE_print(arg, rsp, 0);
2315     BIO_puts(arg, "======================================\n");
2316     OCSP_RESPONSE_free(rsp);
2317     return 1;
2318 }