xref: /openbsd-src/usr.bin/openssl/s_client.c (revision d59bb9942320b767f2a19aaa7690c8c6e30b724c)
1 /* $OpenBSD: s_client.c,v 1.31 2017/01/24 09:07:40 jsing Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2005 Nokia. All rights reserved.
113  *
114  * The portions of the attached software ("Contribution") is developed by
115  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
116  * license.
117  *
118  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
119  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
120  * support (see RFC 4279) to OpenSSL.
121  *
122  * No patent licenses or other rights except those expressly stated in
123  * the OpenSSL open source license shall be deemed granted or received
124  * expressly, by implication, estoppel, or otherwise.
125  *
126  * No assurances are provided by Nokia that the Contribution does not
127  * infringe the patent or other intellectual property rights of any third
128  * party or that the license provides you with all the necessary rights
129  * to make use of the Contribution.
130  *
131  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
132  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
133  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
134  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
135  * OTHERWISE.
136  */
137 
138 #include <sys/types.h>
139 #include <sys/socket.h>
140 
141 #include <netinet/in.h>
142 
143 #include <assert.h>
144 #include <ctype.h>
145 #include <limits.h>
146 #include <netdb.h>
147 #include <stdio.h>
148 #include <stdlib.h>
149 #include <string.h>
150 #include <unistd.h>
151 #include <poll.h>
152 
153 #include "apps.h"
154 
155 #include <openssl/bn.h>
156 #include <openssl/err.h>
157 #include <openssl/ocsp.h>
158 #include <openssl/pem.h>
159 #include <openssl/ssl.h>
160 #include <openssl/x509.h>
161 
162 #include "s_apps.h"
163 #include "timeouts.h"
164 
165 /*#define SSL_HOST_NAME	"www.netscape.com" */
166 /*#define SSL_HOST_NAME	"193.118.187.102" */
167 #define SSL_HOST_NAME	"localhost"
168 
169  /*#define TEST_CERT "client.pem" *//* no default cert. */
170 
171 #define BUFSIZZ 1024*8
172 
173 static int c_nbio = 0;
174 static int c_Pause = 0;
175 static int c_debug = 0;
176 static int c_tlsextdebug = 0;
177 static int c_status_req = 0;
178 static int c_msg = 0;
179 static int c_showcerts = 0;
180 
181 static char *keymatexportlabel = NULL;
182 static int keymatexportlen = 20;
183 
184 static void sc_usage(void);
185 static void print_stuff(BIO * berr, SSL * con, int full);
186 static int ocsp_resp_cb(SSL * s, void *arg);
187 static BIO *bio_c_out = NULL;
188 static int c_quiet = 0;
189 static int c_ign_eof = 0;
190 
191 
192 static void
193 sc_usage(void)
194 {
195 	BIO_printf(bio_err, "usage: s_client args\n");
196 	BIO_printf(bio_err, "\n");
197 	BIO_printf(bio_err, " -4            - Force IPv4\n");
198 	BIO_printf(bio_err, " -6            - Force IPv6\n");
199 	BIO_printf(bio_err, " -host host     - use -connect instead\n");
200 	BIO_printf(bio_err, " -port port     - use -connect instead\n");
201 	BIO_printf(bio_err, " -connect host:port - who to connect to (default is %s:%s)\n", SSL_HOST_NAME, PORT_STR);
202 	BIO_printf(bio_err, " -proxy host:port - connect to http proxy\n");
203 
204 	BIO_printf(bio_err, " -verify arg   - turn on peer certificate verification\n");
205 	BIO_printf(bio_err, " -cert arg     - certificate file to use, PEM format assumed\n");
206 	BIO_printf(bio_err, " -certform arg - certificate format (PEM or DER) PEM default\n");
207 	BIO_printf(bio_err, " -key arg      - Private key file to use, in cert file if\n");
208 	BIO_printf(bio_err, "                 not specified but cert file is.\n");
209 	BIO_printf(bio_err, " -keyform arg  - key format (PEM or DER) PEM default\n");
210 	BIO_printf(bio_err, " -pass arg     - private key file pass phrase source\n");
211 	BIO_printf(bio_err, " -CApath arg   - PEM format directory of CA's\n");
212 	BIO_printf(bio_err, " -CAfile arg   - PEM format file of CA's\n");
213 	BIO_printf(bio_err, " -reconnect    - Drop and re-make the connection with the same Session-ID\n");
214 	BIO_printf(bio_err, " -pause        - sleep(1) after each read(2) and write(2) system call\n");
215 	BIO_printf(bio_err, " -showcerts    - show all certificates in the chain\n");
216 	BIO_printf(bio_err, " -debug        - extra output\n");
217 	BIO_printf(bio_err, " -msg          - Show protocol messages\n");
218 	BIO_printf(bio_err, " -nbio_test    - more ssl protocol testing\n");
219 	BIO_printf(bio_err, " -state        - print the 'ssl' states\n");
220 	BIO_printf(bio_err, " -nbio         - Run with non-blocking IO\n");
221 	BIO_printf(bio_err, " -crlf         - convert LF from terminal into CRLF\n");
222 	BIO_printf(bio_err, " -quiet        - no s_client output\n");
223 	BIO_printf(bio_err, " -ign_eof      - ignore input eof (default when -quiet)\n");
224 	BIO_printf(bio_err, " -no_ign_eof   - don't ignore input eof\n");
225 	BIO_printf(bio_err, " -tls1_2       - just use TLSv1.2\n");
226 	BIO_printf(bio_err, " -tls1_1       - just use TLSv1.1\n");
227 	BIO_printf(bio_err, " -tls1         - just use TLSv1\n");
228 	BIO_printf(bio_err, " -dtls1        - just use DTLSv1\n");
229 	BIO_printf(bio_err, " -mtu          - set the link layer MTU\n");
230 	BIO_printf(bio_err, " -no_tls1_2/-no_tls1_1/-no_tls1/-no_ssl3/-no_ssl2 - turn off that protocol\n");
231 	BIO_printf(bio_err, " -bugs         - Switch on all SSL implementation bug workarounds\n");
232 	BIO_printf(bio_err, " -cipher       - preferred cipher to use, use the 'openssl ciphers'\n");
233 	BIO_printf(bio_err, "                 command to see what is available\n");
234 	BIO_printf(bio_err, " -starttls prot - use the STARTTLS command before starting TLS\n");
235 	BIO_printf(bio_err, "                 for those protocols that support it, where\n");
236 	BIO_printf(bio_err, "                 'prot' defines which one to assume.  Currently,\n");
237 	BIO_printf(bio_err, "                 only \"smtp\", \"lmtp\", \"pop3\", \"imap\", \"ftp\" and \"xmpp\"\n");
238 	BIO_printf(bio_err, "                 are supported.\n");
239 	BIO_printf(bio_err, " -xmpphost host - connect to this virtual host on the xmpp server\n");
240 	BIO_printf(bio_err, " -sess_out arg - file to write SSL session to\n");
241 	BIO_printf(bio_err, " -sess_in arg  - file to read SSL session from\n");
242 	BIO_printf(bio_err, " -servername host  - Set TLS extension servername in ClientHello\n");
243 	BIO_printf(bio_err, " -tlsextdebug      - hex dump of all TLS extensions received\n");
244 	BIO_printf(bio_err, " -status           - request certificate status from server\n");
245 	BIO_printf(bio_err, " -no_ticket        - disable use of RFC4507bis session tickets\n");
246 	BIO_printf(bio_err, " -nextprotoneg arg - enable NPN extension, considering named protocols supported (comma-separated list)\n");
247 	BIO_printf(bio_err, " -alpn arg         - enable ALPN extension, considering named protocols supported (comma-separated list)\n");
248 	BIO_printf(bio_err, " -groups arg       - specify EC curve groups (colon-separated list)\n");
249 #ifndef OPENSSL_NO_SRTP
250 	BIO_printf(bio_err, " -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n");
251 #endif
252 	BIO_printf(bio_err, " -keymatexport label   - Export keying material using label\n");
253 	BIO_printf(bio_err, " -keymatexportlen len  - Export len bytes of keying material (default 20)\n");
254 }
255 
256 
257 /* This is a context that we pass to callbacks */
258 typedef struct tlsextctx_st {
259 	BIO *biodebug;
260 	int ack;
261 } tlsextctx;
262 
263 
264 static int
265 ssl_servername_cb(SSL * s, int *ad, void *arg)
266 {
267 	tlsextctx *p = (tlsextctx *) arg;
268 	const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
269 	if (SSL_get_servername_type(s) != -1)
270 		p->ack = !SSL_session_reused(s) && hn != NULL;
271 	else
272 		BIO_printf(bio_err, "Can't use SSL_get_servername\n");
273 
274 	return SSL_TLSEXT_ERR_OK;
275 }
276 
277 #ifndef OPENSSL_NO_SRTP
278 char *srtp_profiles = NULL;
279 #endif
280 
281 /* This the context that we pass to next_proto_cb */
282 typedef struct tlsextnextprotoctx_st {
283 	unsigned char *data;
284 	unsigned short len;
285 	int status;
286 } tlsextnextprotoctx;
287 
288 static tlsextnextprotoctx next_proto;
289 
290 static int
291 next_proto_cb(SSL * s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
292 {
293 	tlsextnextprotoctx *ctx = arg;
294 
295 	if (!c_quiet) {
296 		/* We can assume that |in| is syntactically valid. */
297 		unsigned i;
298 		BIO_printf(bio_c_out, "Protocols advertised by server: ");
299 		for (i = 0; i < inlen;) {
300 			if (i)
301 				BIO_write(bio_c_out, ", ", 2);
302 			BIO_write(bio_c_out, &in[i + 1], in[i]);
303 			i += in[i] + 1;
304 		}
305 		BIO_write(bio_c_out, "\n", 1);
306 	}
307 	ctx->status = SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
308 	return SSL_TLSEXT_ERR_OK;
309 }
310 
311 enum {
312 	PROTO_OFF = 0,
313 	PROTO_SMTP,
314 	PROTO_LMTP,
315 	PROTO_POP3,
316 	PROTO_IMAP,
317 	PROTO_FTP,
318 	PROTO_XMPP
319 };
320 
321 int
322 s_client_main(int argc, char **argv)
323 {
324 	unsigned int off = 0, clr = 0;
325 	SSL *con = NULL;
326 	int s, k, state = 0, af = AF_UNSPEC;
327 	char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
328 	int cbuf_len, cbuf_off;
329 	int sbuf_len, sbuf_off;
330 	char *port = PORT_STR;
331 	int full_log = 1;
332 	char *host = SSL_HOST_NAME;
333 	char *xmpphost = NULL;
334 	char *proxy = NULL, *connect = NULL;
335 	char *cert_file = NULL, *key_file = NULL;
336 	int cert_format = FORMAT_PEM, key_format = FORMAT_PEM;
337 	char *passarg = NULL, *pass = NULL;
338 	X509 *cert = NULL;
339 	EVP_PKEY *key = NULL;
340 	char *CApath = NULL, *CAfile = NULL, *cipher = NULL;
341 	int reconnect = 0, badop = 0, verify = SSL_VERIFY_NONE, bugs = 0;
342 	int crlf = 0;
343 	int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
344 	SSL_CTX *ctx = NULL;
345 	int ret = 1, in_init = 1, i, nbio_test = 0;
346 	int starttls_proto = PROTO_OFF;
347 	int prexit = 0;
348 	X509_VERIFY_PARAM *vpm = NULL;
349 	int badarg = 0;
350 	const SSL_METHOD *meth = NULL;
351 	int socket_type = SOCK_STREAM;
352 	BIO *sbio;
353 	int mbuf_len = 0;
354 	struct timeval timeout;
355 	const char *errstr = NULL;
356 	char *servername = NULL;
357 	tlsextctx tlsextcbp =
358 	{NULL, 0};
359 	const char *next_proto_neg_in = NULL;
360 	const char *alpn_in = NULL;
361 	const char *groups_in = NULL;
362 	char *sess_in = NULL;
363 	char *sess_out = NULL;
364 	struct sockaddr peer;
365 	int peerlen = sizeof(peer);
366 	int enable_timeouts = 0;
367 	long socket_mtu = 0;
368 
369 	if (single_execution) {
370 		if (pledge("stdio cpath wpath rpath inet dns tty", NULL) == -1) {
371 			perror("pledge");
372 			exit(1);
373 		}
374 	}
375 
376 	meth = SSLv23_client_method();
377 
378 	c_Pause = 0;
379 	c_quiet = 0;
380 	c_ign_eof = 0;
381 	c_debug = 0;
382 	c_msg = 0;
383 	c_showcerts = 0;
384 
385 	if (((cbuf = malloc(BUFSIZZ)) == NULL) ||
386 	    ((sbuf = malloc(BUFSIZZ)) == NULL) ||
387 	    ((mbuf = malloc(BUFSIZZ + 1)) == NULL)) {	/* NUL byte */
388 		BIO_printf(bio_err, "out of memory\n");
389 		goto end;
390 	}
391 	verify_depth = 0;
392 	c_nbio = 0;
393 
394 	argc--;
395 	argv++;
396 	while (argc >= 1) {
397 		if (strcmp(*argv, "-host") == 0) {
398 			if (--argc < 1)
399 				goto bad;
400 			host = *(++argv);
401 		} else if (strcmp(*argv, "-port") == 0) {
402 			if (--argc < 1)
403 				goto bad;
404 			port = *(++argv);
405 			if (port == NULL || *port == '\0')
406 				goto bad;
407 		} else if (strcmp(*argv, "-connect") == 0) {
408 			if (--argc < 1)
409 				goto bad;
410 			connect = *(++argv);
411 		} else if (strcmp(*argv, "-proxy") == 0) {
412 			if (--argc < 1)
413 				goto bad;
414 			proxy = *(++argv);
415 		} else if (strcmp(*argv,"-xmpphost") == 0) {
416 			if (--argc < 1)
417 				goto bad;
418 			xmpphost= *(++argv);
419 		} else if (strcmp(*argv, "-verify") == 0) {
420 			verify = SSL_VERIFY_PEER;
421 			if (--argc < 1)
422 				goto bad;
423 			verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
424 			if (errstr)
425 				goto bad;
426 			BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
427 		} else if (strcmp(*argv, "-cert") == 0) {
428 			if (--argc < 1)
429 				goto bad;
430 			cert_file = *(++argv);
431 		} else if (strcmp(*argv, "-sess_out") == 0) {
432 			if (--argc < 1)
433 				goto bad;
434 			sess_out = *(++argv);
435 		} else if (strcmp(*argv, "-sess_in") == 0) {
436 			if (--argc < 1)
437 				goto bad;
438 			sess_in = *(++argv);
439 		} else if (strcmp(*argv, "-certform") == 0) {
440 			if (--argc < 1)
441 				goto bad;
442 			cert_format = str2fmt(*(++argv));
443 		} else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) {
444 			if (badarg)
445 				goto bad;
446 			continue;
447 		} else if (strcmp(*argv, "-verify_return_error") == 0)
448 			verify_return_error = 1;
449 		else if (strcmp(*argv, "-prexit") == 0)
450 			prexit = 1;
451 		else if (strcmp(*argv, "-crlf") == 0)
452 			crlf = 1;
453 		else if (strcmp(*argv, "-quiet") == 0) {
454 			c_quiet = 1;
455 			c_ign_eof = 1;
456 		} else if (strcmp(*argv, "-ign_eof") == 0)
457 			c_ign_eof = 1;
458 		else if (strcmp(*argv, "-no_ign_eof") == 0)
459 			c_ign_eof = 0;
460 		else if (strcmp(*argv, "-pause") == 0)
461 			c_Pause = 1;
462 		else if (strcmp(*argv, "-debug") == 0)
463 			c_debug = 1;
464 		else if (strcmp(*argv, "-tlsextdebug") == 0)
465 			c_tlsextdebug = 1;
466 		else if (strcmp(*argv, "-status") == 0)
467 			c_status_req = 1;
468 		else if (strcmp(*argv, "-msg") == 0)
469 			c_msg = 1;
470 		else if (strcmp(*argv, "-showcerts") == 0)
471 			c_showcerts = 1;
472 		else if (strcmp(*argv, "-nbio_test") == 0)
473 			nbio_test = 1;
474 		else if (strcmp(*argv, "-state") == 0)
475 			state = 1;
476 		else if (strcmp(*argv, "-tls1_2") == 0)
477 			meth = TLSv1_2_client_method();
478 		else if (strcmp(*argv, "-tls1_1") == 0)
479 			meth = TLSv1_1_client_method();
480 		else if (strcmp(*argv, "-tls1") == 0)
481 			meth = TLSv1_client_method();
482 #ifndef OPENSSL_NO_DTLS1
483 		else if (strcmp(*argv, "-dtls1") == 0) {
484 			meth = DTLSv1_client_method();
485 			socket_type = SOCK_DGRAM;
486 		} else if (strcmp(*argv, "-timeout") == 0)
487 			enable_timeouts = 1;
488 		else if (strcmp(*argv, "-mtu") == 0) {
489 			if (--argc < 1)
490 				goto bad;
491 			socket_mtu = strtonum(*(++argv), 0, LONG_MAX, &errstr);
492 			if (errstr)
493 				goto bad;
494 		}
495 #endif
496 		else if (strcmp(*argv, "-bugs") == 0)
497 			bugs = 1;
498 		else if (strcmp(*argv, "-keyform") == 0) {
499 			if (--argc < 1)
500 				goto bad;
501 			key_format = str2fmt(*(++argv));
502 		} else if (strcmp(*argv, "-pass") == 0) {
503 			if (--argc < 1)
504 				goto bad;
505 			passarg = *(++argv);
506 		} else if (strcmp(*argv, "-key") == 0) {
507 			if (--argc < 1)
508 				goto bad;
509 			key_file = *(++argv);
510 		} else if (strcmp(*argv, "-reconnect") == 0) {
511 			reconnect = 5;
512 		} else if (strcmp(*argv, "-CApath") == 0) {
513 			if (--argc < 1)
514 				goto bad;
515 			CApath = *(++argv);
516 		} else if (strcmp(*argv, "-CAfile") == 0) {
517 			if (--argc < 1)
518 				goto bad;
519 			CAfile = *(++argv);
520 		} else if (strcmp(*argv, "-no_tls1_2") == 0)
521 			off |= SSL_OP_NO_TLSv1_2;
522 		else if (strcmp(*argv, "-no_tls1_1") == 0)
523 			off |= SSL_OP_NO_TLSv1_1;
524 		else if (strcmp(*argv, "-no_tls1") == 0)
525 			off |= SSL_OP_NO_TLSv1;
526 		else if (strcmp(*argv, "-no_ssl3") == 0)
527 			off |= SSL_OP_NO_SSLv3;
528 		else if (strcmp(*argv, "-no_ssl2") == 0)
529 			off |= SSL_OP_NO_SSLv2;
530 		else if (strcmp(*argv, "-no_comp") == 0) {
531 			off |= SSL_OP_NO_COMPRESSION;
532 		} else if (strcmp(*argv, "-no_ticket") == 0) {
533 			off |= SSL_OP_NO_TICKET;
534 		} else if (strcmp(*argv, "-nextprotoneg") == 0) {
535 			if (--argc < 1)
536 				goto bad;
537 			next_proto_neg_in = *(++argv);
538 		} else if (strcmp(*argv, "-alpn") == 0) {
539 			if (--argc < 1)
540 				goto bad;
541 			alpn_in = *(++argv);
542 		} else if (strcmp(*argv, "-groups") == 0) {
543 			if (--argc < 1)
544 				goto bad;
545 			groups_in = *(++argv);
546 		} else if (strcmp(*argv, "-serverpref") == 0)
547 			off |= SSL_OP_CIPHER_SERVER_PREFERENCE;
548 		else if (strcmp(*argv, "-legacy_renegotiation") == 0)
549 			; /* no-op */
550 		else if (strcmp(*argv, "-legacy_server_connect") == 0) {
551 			off |= SSL_OP_LEGACY_SERVER_CONNECT;
552 		} else if (strcmp(*argv, "-no_legacy_server_connect") == 0) {
553 			clr |= SSL_OP_LEGACY_SERVER_CONNECT;
554 		} else if (strcmp(*argv, "-cipher") == 0) {
555 			if (--argc < 1)
556 				goto bad;
557 			cipher = *(++argv);
558 		}
559 		else if (strcmp(*argv, "-nbio") == 0) {
560 			c_nbio = 1;
561 		}
562 		else if (strcmp(*argv, "-starttls") == 0) {
563 			if (--argc < 1)
564 				goto bad;
565 			++argv;
566 			if (strcmp(*argv, "smtp") == 0)
567 				starttls_proto = PROTO_SMTP;
568 			else if (strcmp(*argv, "lmtp") == 0)
569 				starttls_proto = PROTO_LMTP;
570 			else if (strcmp(*argv, "pop3") == 0)
571 				starttls_proto = PROTO_POP3;
572 			else if (strcmp(*argv, "imap") == 0)
573 				starttls_proto = PROTO_IMAP;
574 			else if (strcmp(*argv, "ftp") == 0)
575 				starttls_proto = PROTO_FTP;
576 			else if (strcmp(*argv, "xmpp") == 0)
577 				starttls_proto = PROTO_XMPP;
578 			else
579 				goto bad;
580 		}
581 		else if (strcmp(*argv, "-4") == 0) {
582 			af = AF_INET;
583 		} else if (strcmp(*argv, "-6") == 0) {
584 			af = AF_INET6;
585 		}
586 		else if (strcmp(*argv, "-servername") == 0) {
587 			if (--argc < 1)
588 				goto bad;
589 			servername = *(++argv);
590 			/* meth=TLSv1_client_method(); */
591 		}
592 #ifndef OPENSSL_NO_SRTP
593 		else if (strcmp(*argv, "-use_srtp") == 0) {
594 			if (--argc < 1)
595 				goto bad;
596 			srtp_profiles = *(++argv);
597 		}
598 #endif
599 		else if (strcmp(*argv, "-keymatexport") == 0) {
600 			if (--argc < 1)
601 				goto bad;
602 			keymatexportlabel = *(++argv);
603 		} else if (strcmp(*argv, "-keymatexportlen") == 0) {
604 			if (--argc < 1)
605 				goto bad;
606 			keymatexportlen = strtonum(*(++argv), 1, INT_MAX, &errstr);
607 			if (errstr)
608 				goto bad;
609 		} else {
610 			BIO_printf(bio_err, "unknown option %s\n", *argv);
611 			badop = 1;
612 			break;
613 		}
614 		argc--;
615 		argv++;
616 	}
617 	if (proxy != NULL) {
618 		if (!extract_host_port(proxy, &host, NULL, &port))
619 			goto bad;
620 		if (connect == NULL)
621 			connect = SSL_HOST_NAME;
622 	} else if (connect != NULL) {
623 		if (!extract_host_port(connect, &host, NULL, &port))
624 			goto bad;
625 	}
626 	if (badop) {
627 bad:
628 		if (errstr)
629 			BIO_printf(bio_err, "invalid argument %s: %s\n",
630 			    *argv, errstr);
631 		else
632 			sc_usage();
633 		goto end;
634 	}
635 
636 	next_proto.status = -1;
637 	if (next_proto_neg_in) {
638 		next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
639 		if (next_proto.data == NULL) {
640 			BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
641 			goto end;
642 		}
643 	} else
644 		next_proto.data = NULL;
645 
646 	if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
647 		BIO_printf(bio_err, "Error getting password\n");
648 		goto end;
649 	}
650 	if (key_file == NULL)
651 		key_file = cert_file;
652 
653 
654 	if (key_file) {
655 
656 		key = load_key(bio_err, key_file, key_format, 0, pass,
657 		    "client certificate private key file");
658 		if (!key) {
659 			ERR_print_errors(bio_err);
660 			goto end;
661 		}
662 	}
663 	if (cert_file) {
664 		cert = load_cert(bio_err, cert_file, cert_format,
665 		    NULL, "client certificate file");
666 
667 		if (!cert) {
668 			ERR_print_errors(bio_err);
669 			goto end;
670 		}
671 	}
672 	if (bio_c_out == NULL) {
673 		if (c_quiet && !c_debug && !c_msg) {
674 			bio_c_out = BIO_new(BIO_s_null());
675 		} else {
676 			if (bio_c_out == NULL)
677 				bio_c_out = BIO_new_fp(stdout, BIO_NOCLOSE);
678 		}
679 	}
680 
681 	ctx = SSL_CTX_new(meth);
682 	if (ctx == NULL) {
683 		ERR_print_errors(bio_err);
684 		goto end;
685 	}
686 	if (vpm)
687 		SSL_CTX_set1_param(ctx, vpm);
688 
689 #ifndef OPENSSL_NO_SRTP
690 	if (srtp_profiles != NULL)
691 		SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
692 #endif
693 	if (bugs)
694 		SSL_CTX_set_options(ctx, SSL_OP_ALL | off);
695 	else
696 		SSL_CTX_set_options(ctx, off);
697 
698 	if (clr)
699 		SSL_CTX_clear_options(ctx, clr);
700 	/*
701 	 * DTLS: partial reads end up discarding unread UDP bytes :-( Setting
702 	 * read ahead solves this problem.
703 	 */
704 	if (socket_type == SOCK_DGRAM)
705 		SSL_CTX_set_read_ahead(ctx, 1);
706 
707 	if (next_proto.data)
708 		SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
709 	if (alpn_in) {
710 		unsigned short alpn_len;
711 		unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
712 
713 		if (alpn == NULL) {
714 			BIO_printf(bio_err, "Error parsing -alpn argument\n");
715 			goto end;
716 		}
717 		SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len);
718 		free(alpn);
719 	}
720 	if (groups_in != NULL) {
721 		if (SSL_CTX_set1_groups_list(ctx, groups_in) != 1) {
722 			BIO_printf(bio_err, "Failed to set groups '%s'\n",
723 			    groups_in);
724 			goto end;
725 		}
726 	}
727 
728 	if (state)
729 		SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
730 	if (cipher != NULL)
731 		if (!SSL_CTX_set_cipher_list(ctx, cipher)) {
732 			BIO_printf(bio_err, "error setting cipher list\n");
733 			ERR_print_errors(bio_err);
734 			goto end;
735 		}
736 
737 	SSL_CTX_set_verify(ctx, verify, verify_callback);
738 	if (!set_cert_key_stuff(ctx, cert, key))
739 		goto end;
740 
741 	if ((CAfile || CApath)
742 	    && !SSL_CTX_load_verify_locations(ctx, CAfile, CApath))
743 		ERR_print_errors(bio_err);
744 
745 	if (!SSL_CTX_set_default_verify_paths(ctx))
746 		ERR_print_errors(bio_err);
747 
748 	if (servername != NULL) {
749 		tlsextcbp.biodebug = bio_err;
750 		SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
751 		SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
752 	}
753 
754 	con = SSL_new(ctx);
755 	if (sess_in) {
756 		SSL_SESSION *sess;
757 		BIO *stmp = BIO_new_file(sess_in, "r");
758 		if (!stmp) {
759 			BIO_printf(bio_err, "Can't open session file %s\n",
760 			    sess_in);
761 			ERR_print_errors(bio_err);
762 			goto end;
763 		}
764 		sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
765 		BIO_free(stmp);
766 		if (!sess) {
767 			BIO_printf(bio_err, "Can't open session file %s\n",
768 			    sess_in);
769 			ERR_print_errors(bio_err);
770 			goto end;
771 		}
772 		SSL_set_session(con, sess);
773 		SSL_SESSION_free(sess);
774 	}
775 	if (servername != NULL) {
776 		if (!SSL_set_tlsext_host_name(con, servername)) {
777 			BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
778 			ERR_print_errors(bio_err);
779 			goto end;
780 		}
781 	}
782 /*	SSL_set_cipher_list(con,"RC4-MD5"); */
783 
784 re_start:
785 
786 	if (init_client(&s, host, port, socket_type, af) == 0) {
787 		BIO_printf(bio_err, "connect:errno=%d\n", errno);
788 		goto end;
789 	}
790 	BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);
791 
792 	if (c_nbio) {
793 		if (!c_quiet)
794 			BIO_printf(bio_c_out, "turning on non blocking io\n");
795 		if (!BIO_socket_nbio(s, 1)) {
796 			ERR_print_errors(bio_err);
797 			goto end;
798 		}
799 	}
800 	if (c_Pause & 0x01)
801 		SSL_set_debug(con, 1);
802 
803 	if (SSL_version(con) == DTLS1_VERSION) {
804 
805 		sbio = BIO_new_dgram(s, BIO_NOCLOSE);
806 		if (getsockname(s, &peer, (void *) &peerlen) < 0) {
807 			BIO_printf(bio_err, "getsockname:errno=%d\n",
808 			    errno);
809 			shutdown(s, SHUT_RD);
810 			close(s);
811 			goto end;
812 		}
813 		(void) BIO_ctrl_set_connected(sbio, 1, &peer);
814 
815 		if (enable_timeouts) {
816 			timeout.tv_sec = 0;
817 			timeout.tv_usec = DGRAM_RCV_TIMEOUT;
818 			BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
819 
820 			timeout.tv_sec = 0;
821 			timeout.tv_usec = DGRAM_SND_TIMEOUT;
822 			BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
823 		}
824 		if (socket_mtu > 28) {
825 			SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
826 			SSL_set_mtu(con, socket_mtu - 28);
827 		} else
828 			/* want to do MTU discovery */
829 			BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
830 	} else
831 		sbio = BIO_new_socket(s, BIO_NOCLOSE);
832 
833 	if (nbio_test) {
834 		BIO *test;
835 
836 		test = BIO_new(BIO_f_nbio_test());
837 		sbio = BIO_push(test, sbio);
838 	}
839 	if (c_debug) {
840 		SSL_set_debug(con, 1);
841 		BIO_set_callback(sbio, bio_dump_callback);
842 		BIO_set_callback_arg(sbio, (char *) bio_c_out);
843 	}
844 	if (c_msg) {
845 		SSL_set_msg_callback(con, msg_cb);
846 		SSL_set_msg_callback_arg(con, bio_c_out);
847 	}
848 	if (c_tlsextdebug) {
849 		SSL_set_tlsext_debug_callback(con, tlsext_cb);
850 		SSL_set_tlsext_debug_arg(con, bio_c_out);
851 	}
852 	if (c_status_req) {
853 		SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
854 		SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
855 		SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
856 	}
857 
858 	SSL_set_bio(con, sbio, sbio);
859 	SSL_set_connect_state(con);
860 
861 	/* ok, lets connect */
862 	read_tty = 1;
863 	write_tty = 0;
864 	tty_on = 0;
865 	read_ssl = 1;
866 	write_ssl = 1;
867 
868 	cbuf_len = 0;
869 	cbuf_off = 0;
870 	sbuf_len = 0;
871 	sbuf_off = 0;
872 
873 	/* This is an ugly hack that does a lot of assumptions */
874 	/*
875 	 * We do have to handle multi-line responses which may come in a
876 	 * single packet or not. We therefore have to use BIO_gets() which
877 	 * does need a buffering BIO. So during the initial chitchat we do
878 	 * push a buffering BIO into the chain that is removed again later on
879 	 * to not disturb the rest of the s_client operation.
880 	 */
881 	if (starttls_proto == PROTO_SMTP || starttls_proto == PROTO_LMTP) {
882 		int foundit = 0;
883 		BIO *fbio = BIO_new(BIO_f_buffer());
884 		BIO_push(fbio, sbio);
885 		/* wait for multi-line response to end from SMTP */
886 		do {
887 			mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
888 		}
889 		while (mbuf_len > 3 && mbuf[3] == '-');
890 		/* STARTTLS command requires EHLO... */
891 		BIO_printf(fbio, "%cHLO openssl.client.net\r\n",
892 			   starttls_proto == PROTO_SMTP ? 'E' : 'L');
893 		(void) BIO_flush(fbio);
894 		/* wait for multi-line response to end EHLO SMTP response */
895 		do {
896 			mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
897 			if (strstr(mbuf, "STARTTLS"))
898 				foundit = 1;
899 		}
900 		while (mbuf_len > 3 && mbuf[3] == '-');
901 		(void) BIO_flush(fbio);
902 		BIO_pop(fbio);
903 		BIO_free(fbio);
904 		if (!foundit)
905 			BIO_printf(bio_err,
906 			    "didn't found starttls in server response,"
907 			    " try anyway...\n");
908 		BIO_printf(sbio, "STARTTLS\r\n");
909 		BIO_read(sbio, sbuf, BUFSIZZ);
910 	} else if (starttls_proto == PROTO_POP3) {
911 		mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
912 		if (mbuf_len == -1) {
913 			BIO_printf(bio_err, "BIO_read failed\n");
914 			goto end;
915 		}
916 		BIO_printf(sbio, "STLS\r\n");
917 		BIO_read(sbio, sbuf, BUFSIZZ);
918 	} else if (starttls_proto == PROTO_IMAP) {
919 		int foundit = 0;
920 		BIO *fbio = BIO_new(BIO_f_buffer());
921 		BIO_push(fbio, sbio);
922 		BIO_gets(fbio, mbuf, BUFSIZZ);
923 		/* STARTTLS command requires CAPABILITY... */
924 		BIO_printf(fbio, ". CAPABILITY\r\n");
925 		(void) BIO_flush(fbio);
926 		/* wait for multi-line CAPABILITY response */
927 		do {
928 			mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
929 			if (strstr(mbuf, "STARTTLS"))
930 				foundit = 1;
931 		}
932 		while (mbuf_len > 3 && mbuf[0] != '.');
933 		(void) BIO_flush(fbio);
934 		BIO_pop(fbio);
935 		BIO_free(fbio);
936 		if (!foundit)
937 			BIO_printf(bio_err,
938 			    "didn't found STARTTLS in server response,"
939 			    " try anyway...\n");
940 		BIO_printf(sbio, ". STARTTLS\r\n");
941 		BIO_read(sbio, sbuf, BUFSIZZ);
942 	} else if (starttls_proto == PROTO_FTP) {
943 		BIO *fbio = BIO_new(BIO_f_buffer());
944 		BIO_push(fbio, sbio);
945 		/* wait for multi-line response to end from FTP */
946 		do {
947 			mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
948 		}
949 		while (mbuf_len > 3 && mbuf[3] == '-');
950 		(void) BIO_flush(fbio);
951 		BIO_pop(fbio);
952 		BIO_free(fbio);
953 		BIO_printf(sbio, "AUTH TLS\r\n");
954 		BIO_read(sbio, sbuf, BUFSIZZ);
955 	} else if (starttls_proto == PROTO_XMPP) {
956 		int seen = 0;
957 		BIO_printf(sbio, "<stream:stream "
958 		    "xmlns:stream='http://etherx.jabber.org/streams' "
959 		    "xmlns='jabber:client' to='%s' version='1.0'>", xmpphost ? xmpphost : host);
960 		seen = BIO_read(sbio, mbuf, BUFSIZZ);
961 
962 		if (seen <= 0)
963 			goto shut;
964 
965 		mbuf[seen] = 0;
966 		while (!strstr(mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'") &&
967 		       !strstr(mbuf, "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"")) {
968 			seen = BIO_read(sbio, mbuf, BUFSIZZ);
969 
970 			if (seen <= 0)
971 				goto shut;
972 
973 			mbuf[seen] = 0;
974 		}
975 		BIO_printf(sbio, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
976 		seen = BIO_read(sbio, sbuf, BUFSIZZ);
977 		sbuf[seen] = 0;
978 		if (!strstr(sbuf, "<proceed"))
979 			goto shut;
980 		mbuf[0] = 0;
981 	} else if (proxy != NULL) {
982 		BIO_printf(sbio, "CONNECT %s HTTP/1.0\r\n\r\n", connect);
983 		mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
984 		if (mbuf_len == -1) {
985 			BIO_printf(bio_err, "BIO_read failed\n");
986 			goto end;
987 		}
988 	}
989 	for (;;) {
990 		struct pollfd pfd[3];	/* stdin, stdout, socket */
991 		int ptimeout = -1;
992 
993 		if ((SSL_version(con) == DTLS1_VERSION) &&
994 		    DTLSv1_get_timeout(con, &timeout))
995 			ptimeout = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
996 
997 		if (SSL_in_init(con) && !SSL_total_renegotiations(con)) {
998 			in_init = 1;
999 			tty_on = 0;
1000 		} else {
1001 			tty_on = 1;
1002 			if (in_init) {
1003 				in_init = 0;
1004 				if (sess_out) {
1005 					BIO *stmp = BIO_new_file(sess_out, "w");
1006 					if (stmp) {
1007 						PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con));
1008 						BIO_free(stmp);
1009 					} else
1010 						BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
1011 				}
1012 				print_stuff(bio_c_out, con, full_log);
1013 				if (full_log > 0)
1014 					full_log--;
1015 
1016 				if (starttls_proto) {
1017 					BIO_write(bio_err, mbuf, mbuf_len);
1018 					/* We don't need to know any more */
1019 					starttls_proto = PROTO_OFF;
1020 				}
1021 				if (reconnect) {
1022 					reconnect--;
1023 					BIO_printf(bio_c_out, "drop connection and then reconnect\n");
1024 					SSL_shutdown(con);
1025 					SSL_set_connect_state(con);
1026 					shutdown(SSL_get_fd(con), SHUT_RD);
1027 					close(SSL_get_fd(con));
1028 					goto re_start;
1029 				}
1030 			}
1031 		}
1032 
1033 		ssl_pending = read_ssl && SSL_pending(con);
1034 
1035 		pfd[0].fd = -1;
1036 		pfd[1].fd = -1;
1037 		if (!ssl_pending) {
1038 			if (tty_on) {
1039 				if (read_tty) {
1040 					pfd[0].fd = fileno(stdin);
1041 					pfd[0].events = POLLIN;
1042 				}
1043 				if (write_tty) {
1044 					pfd[1].fd = fileno(stdout);
1045 					pfd[1].events = POLLOUT;
1046 				}
1047 			}
1048 
1049 			pfd[2].fd = SSL_get_fd(con);
1050 			pfd[2].events = 0;
1051 			if (read_ssl)
1052 				pfd[2].events |= POLLIN;
1053 			if (write_ssl)
1054 				pfd[2].events |= POLLOUT;
1055 
1056 /*			printf("mode tty(%d %d%d) ssl(%d%d)\n",
1057 				tty_on,read_tty,write_tty,read_ssl,write_ssl);*/
1058 
1059 			i = poll(pfd, 3, ptimeout);
1060 			if (i < 0) {
1061 				BIO_printf(bio_err, "bad select %d\n",
1062 				    errno);
1063 				goto shut;
1064 				/* goto end; */
1065 			}
1066 		}
1067 		if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0) {
1068 			BIO_printf(bio_err, "TIMEOUT occured\n");
1069 		}
1070 		if (!ssl_pending && (pfd[2].revents & (POLLOUT|POLLERR|POLLNVAL))) {
1071 			if (pfd[2].revents & (POLLERR|POLLNVAL)) {
1072 				BIO_printf(bio_err, "poll error");
1073 				goto shut;
1074 			}
1075 			k = SSL_write(con, &(cbuf[cbuf_off]),
1076 			    (unsigned int) cbuf_len);
1077 			switch (SSL_get_error(con, k)) {
1078 			case SSL_ERROR_NONE:
1079 				cbuf_off += k;
1080 				cbuf_len -= k;
1081 				if (k <= 0)
1082 					goto end;
1083 				/* we have done a  write(con,NULL,0); */
1084 				if (cbuf_len <= 0) {
1085 					read_tty = 1;
1086 					write_ssl = 0;
1087 				} else {	/* if (cbuf_len > 0) */
1088 					read_tty = 0;
1089 					write_ssl = 1;
1090 				}
1091 				break;
1092 			case SSL_ERROR_WANT_WRITE:
1093 				BIO_printf(bio_c_out, "write W BLOCK\n");
1094 				write_ssl = 1;
1095 				read_tty = 0;
1096 				break;
1097 			case SSL_ERROR_WANT_READ:
1098 				BIO_printf(bio_c_out, "write R BLOCK\n");
1099 				write_tty = 0;
1100 				read_ssl = 1;
1101 				write_ssl = 0;
1102 				break;
1103 			case SSL_ERROR_WANT_X509_LOOKUP:
1104 				BIO_printf(bio_c_out, "write X BLOCK\n");
1105 				break;
1106 			case SSL_ERROR_ZERO_RETURN:
1107 				if (cbuf_len != 0) {
1108 					BIO_printf(bio_c_out, "shutdown\n");
1109 					ret = 0;
1110 					goto shut;
1111 				} else {
1112 					read_tty = 1;
1113 					write_ssl = 0;
1114 					break;
1115 				}
1116 
1117 			case SSL_ERROR_SYSCALL:
1118 				if ((k != 0) || (cbuf_len != 0)) {
1119 					BIO_printf(bio_err, "write:errno=%d\n",
1120 					    errno);
1121 					goto shut;
1122 				} else {
1123 					read_tty = 1;
1124 					write_ssl = 0;
1125 				}
1126 				break;
1127 			case SSL_ERROR_SSL:
1128 				ERR_print_errors(bio_err);
1129 				goto shut;
1130 			}
1131 		} else if (!ssl_pending &&
1132 		    (pfd[1].revents & (POLLOUT|POLLERR|POLLNVAL))) {
1133 			if (pfd[1].revents & (POLLERR|POLLNVAL)) {
1134 				BIO_printf(bio_err, "poll error");
1135 				goto shut;
1136 			}
1137 			i = write(fileno(stdout), &(sbuf[sbuf_off]), sbuf_len);
1138 
1139 			if (i <= 0) {
1140 				BIO_printf(bio_c_out, "DONE\n");
1141 				ret = 0;
1142 				goto shut;
1143 				/* goto end; */
1144 			}
1145 			sbuf_len -= i;
1146 			sbuf_off += i;
1147 			if (sbuf_len <= 0) {
1148 				read_ssl = 1;
1149 				write_tty = 0;
1150 			}
1151 		} else if (ssl_pending || (pfd[2].revents & (POLLIN|POLLHUP))) {
1152 #ifdef RENEG
1153 			{
1154 				static int iiii;
1155 				if (++iiii == 52) {
1156 					SSL_renegotiate(con);
1157 					iiii = 0;
1158 				}
1159 			}
1160 #endif
1161 			k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
1162 
1163 			switch (SSL_get_error(con, k)) {
1164 			case SSL_ERROR_NONE:
1165 				if (k <= 0)
1166 					goto end;
1167 				sbuf_off = 0;
1168 				sbuf_len = k;
1169 
1170 				read_ssl = 0;
1171 				write_tty = 1;
1172 				break;
1173 			case SSL_ERROR_WANT_WRITE:
1174 				BIO_printf(bio_c_out, "read W BLOCK\n");
1175 				write_ssl = 1;
1176 				read_tty = 0;
1177 				break;
1178 			case SSL_ERROR_WANT_READ:
1179 				BIO_printf(bio_c_out, "read R BLOCK\n");
1180 				write_tty = 0;
1181 				read_ssl = 1;
1182 				if ((read_tty == 0) && (write_ssl == 0))
1183 					write_ssl = 1;
1184 				break;
1185 			case SSL_ERROR_WANT_X509_LOOKUP:
1186 				BIO_printf(bio_c_out, "read X BLOCK\n");
1187 				break;
1188 			case SSL_ERROR_SYSCALL:
1189 				ret = errno;
1190 				BIO_printf(bio_err, "read:errno=%d\n", ret);
1191 				goto shut;
1192 			case SSL_ERROR_ZERO_RETURN:
1193 				BIO_printf(bio_c_out, "closed\n");
1194 				ret = 0;
1195 				goto shut;
1196 			case SSL_ERROR_SSL:
1197 				ERR_print_errors(bio_err);
1198 				goto shut;
1199 				/* break; */
1200 			}
1201 		} else if (pfd[0].revents) {
1202 			if (pfd[0].revents & (POLLERR|POLLNVAL)) {
1203 				BIO_printf(bio_err, "poll error");
1204 				goto shut;
1205 			}
1206 			if (crlf) {
1207 				int j, lf_num;
1208 
1209 				i = read(fileno(stdin), cbuf, BUFSIZZ / 2);
1210 				lf_num = 0;
1211 				/* both loops are skipped when i <= 0 */
1212 				for (j = 0; j < i; j++)
1213 					if (cbuf[j] == '\n')
1214 						lf_num++;
1215 				for (j = i - 1; j >= 0; j--) {
1216 					cbuf[j + lf_num] = cbuf[j];
1217 					if (cbuf[j] == '\n') {
1218 						lf_num--;
1219 						i++;
1220 						cbuf[j + lf_num] = '\r';
1221 					}
1222 				}
1223 				assert(lf_num == 0);
1224 			} else
1225 				i = read(fileno(stdin), cbuf, BUFSIZZ);
1226 
1227 			if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q'))) {
1228 				BIO_printf(bio_err, "DONE\n");
1229 				ret = 0;
1230 				goto shut;
1231 			}
1232 			if ((!c_ign_eof) && (cbuf[0] == 'R')) {
1233 				BIO_printf(bio_err, "RENEGOTIATING\n");
1234 				SSL_renegotiate(con);
1235 				cbuf_len = 0;
1236 			} else {
1237 				cbuf_len = i;
1238 				cbuf_off = 0;
1239 			}
1240 
1241 			write_ssl = 1;
1242 			read_tty = 0;
1243 		}
1244 	}
1245 
1246 	ret = 0;
1247 shut:
1248 	if (in_init)
1249 		print_stuff(bio_c_out, con, full_log);
1250 	SSL_shutdown(con);
1251 	shutdown(SSL_get_fd(con), SHUT_RD);
1252 	close(SSL_get_fd(con));
1253 end:
1254 	if (con != NULL) {
1255 		if (prexit != 0)
1256 			print_stuff(bio_c_out, con, 1);
1257 		SSL_free(con);
1258 	}
1259 	free(next_proto.data);
1260 	if (ctx != NULL)
1261 		SSL_CTX_free(ctx);
1262 	if (cert)
1263 		X509_free(cert);
1264 	if (key)
1265 		EVP_PKEY_free(key);
1266 	free(pass);
1267 	if (vpm)
1268 		X509_VERIFY_PARAM_free(vpm);
1269 	if (cbuf != NULL) {
1270 		explicit_bzero(cbuf, BUFSIZZ);
1271 		free(cbuf);
1272 	}
1273 	if (sbuf != NULL) {
1274 		explicit_bzero(sbuf, BUFSIZZ);
1275 		free(sbuf);
1276 	}
1277 	if (mbuf != NULL) {
1278 		explicit_bzero(mbuf, BUFSIZZ);
1279 		free(mbuf);
1280 	}
1281 	if (bio_c_out != NULL) {
1282 		BIO_free(bio_c_out);
1283 		bio_c_out = NULL;
1284 	}
1285 
1286 	return (ret);
1287 }
1288 
1289 
1290 static void
1291 print_stuff(BIO * bio, SSL * s, int full)
1292 {
1293 	X509 *peer = NULL;
1294 	char *p;
1295 	static const char *space = "                ";
1296 	char buf[BUFSIZ];
1297 	STACK_OF(X509) * sk;
1298 	STACK_OF(X509_NAME) * sk2;
1299 	const SSL_CIPHER *c;
1300 	X509_NAME *xn;
1301 	int j, i;
1302 	unsigned char *exportedkeymat;
1303 
1304 	if (full) {
1305 		int got_a_chain = 0;
1306 
1307 		sk = SSL_get_peer_cert_chain(s);
1308 		if (sk != NULL) {
1309 			got_a_chain = 1;	/* we don't have it for SSL2
1310 						 * (yet) */
1311 
1312 			BIO_printf(bio, "---\nCertificate chain\n");
1313 			for (i = 0; i < sk_X509_num(sk); i++) {
1314 				X509_NAME_oneline(X509_get_subject_name(
1315 					sk_X509_value(sk, i)), buf, sizeof buf);
1316 				BIO_printf(bio, "%2d s:%s\n", i, buf);
1317 				X509_NAME_oneline(X509_get_issuer_name(
1318 					sk_X509_value(sk, i)), buf, sizeof buf);
1319 				BIO_printf(bio, "   i:%s\n", buf);
1320 				if (c_showcerts)
1321 					PEM_write_bio_X509(bio, sk_X509_value(sk, i));
1322 			}
1323 		}
1324 		BIO_printf(bio, "---\n");
1325 		peer = SSL_get_peer_certificate(s);
1326 		if (peer != NULL) {
1327 			BIO_printf(bio, "Server certificate\n");
1328 			if (!(c_showcerts && got_a_chain))	/* Redundant if we
1329 								 * showed the whole
1330 								 * chain */
1331 				PEM_write_bio_X509(bio, peer);
1332 			X509_NAME_oneline(X509_get_subject_name(peer),
1333 			    buf, sizeof buf);
1334 			BIO_printf(bio, "subject=%s\n", buf);
1335 			X509_NAME_oneline(X509_get_issuer_name(peer),
1336 			    buf, sizeof buf);
1337 			BIO_printf(bio, "issuer=%s\n", buf);
1338 		} else
1339 			BIO_printf(bio, "no peer certificate available\n");
1340 
1341 		sk2 = SSL_get_client_CA_list(s);
1342 		if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0)) {
1343 			BIO_printf(bio, "---\nAcceptable client certificate CA names\n");
1344 			for (i = 0; i < sk_X509_NAME_num(sk2); i++) {
1345 				xn = sk_X509_NAME_value(sk2, i);
1346 				X509_NAME_oneline(xn, buf, sizeof(buf));
1347 				BIO_write(bio, buf, strlen(buf));
1348 				BIO_write(bio, "\n", 1);
1349 			}
1350 		} else {
1351 			BIO_printf(bio, "---\nNo client certificate CA names sent\n");
1352 		}
1353 		p = SSL_get_shared_ciphers(s, buf, sizeof buf);
1354 		if (p != NULL) {
1355 			/*
1356 			 * This works only for SSL 2.  In later protocol
1357 			 * versions, the client does not know what other
1358 			 * ciphers (in addition to the one to be used in the
1359 			 * current connection) the server supports.
1360 			 */
1361 
1362 			BIO_printf(bio, "---\nCiphers common between both SSL endpoints:\n");
1363 			j = i = 0;
1364 			while (*p) {
1365 				if (*p == ':') {
1366 					BIO_write(bio, space, 15 - j % 25);
1367 					i++;
1368 					j = 0;
1369 					BIO_write(bio, ((i % 3) ? " " : "\n"), 1);
1370 				} else {
1371 					BIO_write(bio, p, 1);
1372 					j++;
1373 				}
1374 				p++;
1375 			}
1376 			BIO_write(bio, "\n", 1);
1377 		}
1378 
1379 		ssl_print_tmp_key(bio, s);
1380 
1381 		BIO_printf(bio, "---\nSSL handshake has read %ld bytes and written %ld bytes\n",
1382 		    BIO_number_read(SSL_get_rbio(s)),
1383 		    BIO_number_written(SSL_get_wbio(s)));
1384 	}
1385 	BIO_printf(bio, (SSL_cache_hit(s) ? "---\nReused, " : "---\nNew, "));
1386 	c = SSL_get_current_cipher(s);
1387 	BIO_printf(bio, "%s, Cipher is %s\n",
1388 	    SSL_CIPHER_get_version(c),
1389 	    SSL_CIPHER_get_name(c));
1390 	if (peer != NULL) {
1391 		EVP_PKEY *pktmp;
1392 		pktmp = X509_get_pubkey(peer);
1393 		BIO_printf(bio, "Server public key is %d bit\n",
1394 		    EVP_PKEY_bits(pktmp));
1395 		EVP_PKEY_free(pktmp);
1396 	}
1397 	BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
1398 	    SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
1399 
1400 	/* Compression is not supported and will always be none. */
1401 	BIO_printf(bio, "Compression: NONE\n");
1402 	BIO_printf(bio, "Expansion: NONE\n");
1403 
1404 #ifdef SSL_DEBUG
1405 	{
1406 		/* Print out local port of connection: useful for debugging */
1407 		int sock;
1408 		struct sockaddr_in ladd;
1409 		socklen_t ladd_size = sizeof(ladd);
1410 		sock = SSL_get_fd(s);
1411 		getsockname(sock, (struct sockaddr *) & ladd, &ladd_size);
1412 		BIO_printf(bio_c_out, "LOCAL PORT is %u\n", ntohs(ladd.sin_port));
1413 	}
1414 #endif
1415 
1416 	if (next_proto.status != -1) {
1417 		const unsigned char *proto;
1418 		unsigned int proto_len;
1419 		SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
1420 		BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
1421 		BIO_write(bio, proto, proto_len);
1422 		BIO_write(bio, "\n", 1);
1423 	}
1424 	{
1425 		const unsigned char *proto;
1426 		unsigned int proto_len;
1427 		SSL_get0_alpn_selected(s, &proto, &proto_len);
1428 		if (proto_len > 0) {
1429 			BIO_printf(bio, "ALPN protocol: ");
1430 			BIO_write(bio, proto, proto_len);
1431 			BIO_write(bio, "\n", 1);
1432 		} else
1433 			BIO_printf(bio, "No ALPN negotiated\n");
1434 	}
1435 
1436 #ifndef OPENSSL_NO_SRTP
1437 	{
1438 		SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(s);
1439 
1440 		if (srtp_profile)
1441 			BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
1442 			    srtp_profile->name);
1443 	}
1444 #endif
1445 
1446 	SSL_SESSION_print(bio, SSL_get_session(s));
1447 	if (keymatexportlabel != NULL) {
1448 		BIO_printf(bio, "Keying material exporter:\n");
1449 		BIO_printf(bio, "    Label: '%s'\n", keymatexportlabel);
1450 		BIO_printf(bio, "    Length: %i bytes\n", keymatexportlen);
1451 		exportedkeymat = malloc(keymatexportlen);
1452 		if (exportedkeymat != NULL) {
1453 			if (!SSL_export_keying_material(s, exportedkeymat,
1454 				keymatexportlen,
1455 				keymatexportlabel,
1456 				strlen(keymatexportlabel),
1457 				NULL, 0, 0)) {
1458 				BIO_printf(bio, "    Error\n");
1459 			} else {
1460 				BIO_printf(bio, "    Keying material: ");
1461 				for (i = 0; i < keymatexportlen; i++)
1462 					BIO_printf(bio, "%02X",
1463 					    exportedkeymat[i]);
1464 				BIO_printf(bio, "\n");
1465 			}
1466 			free(exportedkeymat);
1467 		}
1468 	}
1469 	BIO_printf(bio, "---\n");
1470 	if (peer != NULL)
1471 		X509_free(peer);
1472 	/* flush, or debugging output gets mixed with http response */
1473 	(void) BIO_flush(bio);
1474 }
1475 
1476 
1477 static int
1478 ocsp_resp_cb(SSL * s, void *arg)
1479 {
1480 	const unsigned char *p;
1481 	int len;
1482 	OCSP_RESPONSE *rsp;
1483 	len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1484 	BIO_puts(arg, "OCSP response: ");
1485 	if (!p) {
1486 		BIO_puts(arg, "no response sent\n");
1487 		return 1;
1488 	}
1489 	rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1490 	if (!rsp) {
1491 		BIO_puts(arg, "response parse error\n");
1492 		BIO_dump_indent(arg, (char *) p, len, 4);
1493 		return 0;
1494 	}
1495 	BIO_puts(arg, "\n======================================\n");
1496 	OCSP_RESPONSE_print(arg, rsp, 0);
1497 	BIO_puts(arg, "======================================\n");
1498 	OCSP_RESPONSE_free(rsp);
1499 	return 1;
1500 }
1501 
1502