1 /* $OpenBSD: s_server.c,v 1.43 2020/07/27 13:46:48 inoguchi 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 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECC cipher suite support in OpenSSL originally developed by
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116 /* ====================================================================
117  * Copyright 2005 Nokia. All rights reserved.
118  *
119  * The portions of the attached software ("Contribution") is developed by
120  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
121  * license.
122  *
123  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
124  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
125  * support (see RFC 4279) to OpenSSL.
126  *
127  * No patent licenses or other rights except those expressly stated in
128  * the OpenSSL open source license shall be deemed granted or received
129  * expressly, by implication, estoppel, or otherwise.
130  *
131  * No assurances are provided by Nokia that the Contribution does not
132  * infringe the patent or other intellectual property rights of any third
133  * party or that the license provides you with all the necessary rights
134  * to make use of the Contribution.
135  *
136  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
137  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
138  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
139  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
140  * OTHERWISE.
141  */
142 
143 /* Until the key-gen callbacks are modified to use newer prototypes, we allow
144  * deprecated functions for openssl-internal code */
145 #ifdef OPENSSL_NO_DEPRECATED
146 #undef OPENSSL_NO_DEPRECATED
147 #endif
148 
149 #include <sys/types.h>
150 #include <sys/socket.h>
151 
152 #include <assert.h>
153 #include <ctype.h>
154 #include <stdio.h>
155 #include <stdlib.h>
156 #include <limits.h>
157 #include <string.h>
158 #include <unistd.h>
159 #include <poll.h>
160 
161 #include "apps.h"
162 
163 #include <openssl/bn.h>
164 #include <openssl/err.h>
165 #include <openssl/lhash.h>
166 #include <openssl/ocsp.h>
167 #include <openssl/pem.h>
168 #include <openssl/ssl.h>
169 #include <openssl/x509.h>
170 
171 #ifndef OPENSSL_NO_DH
172 #include <openssl/dh.h>
173 #endif
174 
175 #include <openssl/rsa.h>
176 
177 #include "s_apps.h"
178 #include "timeouts.h"
179 
180 static void s_server_init(void);
181 static void sv_usage(void);
182 static void print_stats(BIO *bp, SSL_CTX *ctx);
183 static int sv_body(char *hostname, int s, unsigned char *context);
184 static void close_accept_socket(void);
185 static int init_ssl_connection(SSL *s);
186 #ifndef OPENSSL_NO_DH
187 static DH *load_dh_param(const char *dhfile);
188 #endif
189 static int www_body(char *hostname, int s, unsigned char *context);
190 static int generate_session_id(const SSL *ssl, unsigned char *id,
191     unsigned int *id_len);
192 static int ssl_servername_cb(SSL *s, int *ad, void *arg);
193 static int cert_status_cb(SSL * s, void *arg);
194 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
195     const unsigned char *in, unsigned int inlen, void *arg);
196 /* static int load_CA(SSL_CTX *ctx, char *file);*/
197 
198 #define BUFSIZZ	16*1024
199 static int bufsize = BUFSIZZ;
200 static int accept_socket = -1;
201 
202 #define TEST_CERT	"server.pem"
203 #define TEST_CERT2	"server2.pem"
204 
205 static int s_server_session_id_context = 1;	/* anything will do */
206 static SSL_CTX *ctx = NULL;
207 static SSL_CTX *ctx2 = NULL;
208 static BIO *bio_s_out = NULL;
209 
210 static int local_argc = 0;
211 static char **local_argv;
212 
213 /* This is a context that we pass to callbacks */
214 typedef struct tlsextctx_st {
215 	char *servername;
216 	BIO *biodebug;
217 	int extension_error;
218 } tlsextctx;
219 
220 /* Structure passed to cert status callback */
221 typedef struct tlsextstatusctx_st {
222 	/* Default responder to use */
223 	char *host, *path, *port;
224 	int use_ssl;
225 	int timeout;
226 	BIO *err;
227 	int verbose;
228 } tlsextstatusctx;
229 
230 /* This the context that we pass to alpn_cb */
231 typedef struct tlsextalpnctx_st {
232 	unsigned char *data;
233 	unsigned short len;
234 } tlsextalpnctx;
235 
236 static struct {
237 	char *alpn_in;
238 	char *npn_in; /* Ignored. */
239 	int bugs;
240 	char *CAfile;
241 	char *CApath;
242 #ifndef OPENSSL_NO_DTLS1
243 	int cert_chain;
244 #endif
245 	char *cert_file;
246 	char *cert_file2;
247 	int cert_format;
248 	char *cipher;
249 	unsigned char *context;
250 	int crlf;
251 	char *dcert_file;
252 	int dcert_format;
253 	int debug;
254 	char *dhfile;
255 	char *dkey_file;
256 	int dkey_format;
257 	char *dpassarg;
258 	int enable_timeouts;
259 	const char *errstr;
260 	char *groups_in;
261 	char *key_file;
262 	char *key_file2;
263 	int key_format;
264 	char *keymatexportlabel;
265 	int keymatexportlen;
266 	uint16_t max_version;
267 	uint16_t min_version;
268 	const SSL_METHOD *meth;
269 	int msg;
270 	char *named_curve;
271 	int nbio;
272 	int nbio_test;
273 	int no_cache;
274 	int nocert;
275 	int no_dhe;
276 	int no_ecdhe;
277 	int no_tmp_rsa; /* No-op. */
278 	int off;
279 	char *passarg;
280 	short port;
281 	int quiet;
282 	int server_verify;
283 	char *session_id_prefix;
284 	long socket_mtu;
285 	int socket_type;
286 #ifndef OPENSSL_NO_SRTP
287 	char *srtp_profiles;
288 #endif
289 	int state;
290 	tlsextstatusctx tlscstatp;
291 	tlsextctx tlsextcbp;
292 	int tlsextdebug;
293 	int tlsextstatus;
294 	X509_VERIFY_PARAM *vpm;
295 	int www;
296 } s_server_config;
297 
298 static int
299 s_server_opt_context(char *arg)
300 {
301 	s_server_config.context = (unsigned char *) arg;
302 	return (0);
303 }
304 
305 static int
306 s_server_opt_keymatexportlen(char *arg)
307 {
308 	s_server_config.keymatexportlen = strtonum(arg, 1, INT_MAX,
309 	    &s_server_config.errstr);
310 	if (s_server_config.errstr != NULL) {
311 		BIO_printf(bio_err, "invalid argument %s: %s\n",
312 		    arg, s_server_config.errstr);
313 		return (1);
314 	}
315 	return (0);
316 }
317 
318 #ifndef OPENSSL_NO_DTLS1
319 static int
320 s_server_opt_mtu(char *arg)
321 {
322 	s_server_config.socket_mtu = strtonum(arg, 0, LONG_MAX,
323 	    &s_server_config.errstr);
324 	if (s_server_config.errstr != NULL) {
325 		BIO_printf(bio_err, "invalid argument %s: %s\n",
326 		    arg, s_server_config.errstr);
327 		return (1);
328 	}
329 	return (0);
330 }
331 
332 static int
333 s_server_protocol_version_dtls1(void)
334 {
335 	s_server_config.meth = DTLS_server_method();
336 	s_server_config.socket_type = SOCK_DGRAM;
337 	return (0);
338 }
339 #endif
340 
341 static int
342 s_server_protocol_version_tls1(void)
343 {
344 	s_server_config.min_version = TLS1_VERSION;
345 	s_server_config.max_version = TLS1_VERSION;
346 	return (0);
347 }
348 
349 static int
350 s_server_protocol_version_tls1_1(void)
351 {
352 	s_server_config.min_version = TLS1_1_VERSION;
353 	s_server_config.max_version = TLS1_1_VERSION;
354 	return (0);
355 }
356 
357 static int
358 s_server_protocol_version_tls1_2(void)
359 {
360 	s_server_config.min_version = TLS1_2_VERSION;
361 	s_server_config.max_version = TLS1_2_VERSION;
362 	return (0);
363 }
364 
365 static int
366 s_server_protocol_version_tls1_3(void)
367 {
368 	s_server_config.min_version = TLS1_3_VERSION;
369 	s_server_config.max_version = TLS1_3_VERSION;
370 	return (0);
371 }
372 
373 static int
374 s_server_opt_nbio_test(void)
375 {
376 	s_server_config.nbio = 1;
377 	s_server_config.nbio_test = 1;
378 	return (0);
379 }
380 
381 static int
382 s_server_opt_port(char *arg)
383 {
384 	if (!extract_port(arg, &s_server_config.port))
385 		return (1);
386 	return (0);
387 }
388 
389 static int
390 s_server_opt_status_timeout(char *arg)
391 {
392 	s_server_config.tlsextstatus = 1;
393 	s_server_config.tlscstatp.timeout = strtonum(arg, 0, INT_MAX,
394 	    &s_server_config.errstr);
395 	if (s_server_config.errstr != NULL) {
396 		BIO_printf(bio_err, "invalid argument %s: %s\n",
397 		    arg, s_server_config.errstr);
398 		return (1);
399 	}
400 	return (0);
401 }
402 
403 static int
404 s_server_opt_status_url(char *arg)
405 {
406 	s_server_config.tlsextstatus = 1;
407 	if (!OCSP_parse_url(arg, &s_server_config.tlscstatp.host,
408 	    &s_server_config.tlscstatp.port, &s_server_config.tlscstatp.path,
409 	    &s_server_config.tlscstatp.use_ssl)) {
410 		BIO_printf(bio_err, "Error parsing URL\n");
411 		return (1);
412 	}
413 	return (0);
414 }
415 
416 static int
417 s_server_opt_status_verbose(void)
418 {
419 	s_server_config.tlsextstatus = 1;
420 	s_server_config.tlscstatp.verbose = 1;
421 	return (0);
422 }
423 
424 static int
425 s_server_opt_verify(char *arg)
426 {
427 	s_server_config.server_verify = SSL_VERIFY_PEER |
428 	    SSL_VERIFY_CLIENT_ONCE;
429 	verify_depth = strtonum(arg, 0, INT_MAX, &s_server_config.errstr);
430 	if (s_server_config.errstr != NULL) {
431 		BIO_printf(bio_err, "invalid argument %s: %s\n",
432 		    arg, s_server_config.errstr);
433 		return (1);
434 	}
435 	BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
436 	return (0);
437 }
438 
439 static int
440 s_server_opt_verify_fail(char *arg)
441 {
442 	s_server_config.server_verify = SSL_VERIFY_PEER |
443 	    SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
444 	verify_depth = strtonum(arg, 0, INT_MAX, &s_server_config.errstr);
445 	if (s_server_config.errstr != NULL) {
446 		BIO_printf(bio_err, "invalid argument %s: %s\n",
447 		    arg, s_server_config.errstr);
448 		return (1);
449 	}
450 	BIO_printf(bio_err, "verify depth is %d, must return a certificate\n",
451 	    verify_depth);
452 	return (0);
453 }
454 
455 static int
456 s_server_opt_verify_param(int argc, char **argv, int *argsused)
457 {
458 	char **pargs = argv;
459 	int pargc = argc;
460 	int badarg = 0;
461 
462 	if (!args_verify(&pargs, &pargc, &badarg, bio_err,
463 	    &s_server_config.vpm)) {
464 		BIO_printf(bio_err, "unknown option %s\n", *argv);
465 		return (1);
466 	}
467 	if (badarg)
468 		return (1);
469 
470 	*argsused = argc - pargc;
471 	return (0);
472 }
473 
474 static const struct option s_server_options[] = {
475 	{
476 		.name = "accept",
477 		.argname = "port",
478 		.desc = "Port to accept on (default is 4433)",
479 		.type = OPTION_ARG_FUNC,
480 		.opt.argfunc = s_server_opt_port,
481 	},
482 	{
483 		.name = "alpn",
484 		.argname = "protocols",
485 		.desc = "Set the advertised protocols for the ALPN extension"
486 			" (comma-separated list)",
487 		.type = OPTION_ARG,
488 		.opt.arg = &s_server_config.alpn_in,
489 	},
490 	{
491 		.name = "bugs",
492 		.desc = "Turn on SSL bug compatibility",
493 		.type = OPTION_FLAG,
494 		.opt.flag = &s_server_config.bugs,
495 	},
496 	{
497 		.name = "CAfile",
498 		.argname = "file",
499 		.desc = "PEM format file of CA certificates",
500 		.type = OPTION_ARG,
501 		.opt.arg = &s_server_config.CAfile,
502 	},
503 	{
504 		.name = "CApath",
505 		.argname = "directory",
506 		.desc = "PEM format directory of CA certificates",
507 		.type = OPTION_ARG,
508 		.opt.arg = &s_server_config.CApath,
509 	},
510 	{
511 		.name = "cert",
512 		.argname = "file",
513 		.desc = "Certificate file to use\n"
514 			"(default is " TEST_CERT ")",
515 		.type = OPTION_ARG,
516 		.opt.arg = &s_server_config.cert_file,
517 	},
518 	{
519 		.name = "cert2",
520 		.argname = "file",
521 		.desc = "Certificate file to use for servername\n"
522 			"(default is " TEST_CERT2 ")",
523 		.type = OPTION_ARG,
524 		.opt.arg = &s_server_config.cert_file2,
525 	},
526 	{
527 		.name = "certform",
528 		.argname = "fmt",
529 		.desc = "Certificate format (PEM or DER) PEM default",
530 		.type = OPTION_ARG_FORMAT,
531 		.opt.value = &s_server_config.cert_format,
532 	},
533 #ifndef OPENSSL_NO_DTLS1
534 	{
535 		.name = "chain",
536 		.type = OPTION_FLAG,
537 		.opt.flag = &s_server_config.cert_chain,
538 	},
539 #endif
540 	{
541 		.name = "cipher",
542 		.argname = "list",
543 		.desc = "List of ciphers to enable (see `openssl ciphers`)",
544 		.type = OPTION_ARG,
545 		.opt.arg = &s_server_config.cipher,
546 	},
547 	{
548 		.name = "context",
549 		.argname = "id",
550 		.desc = "Set session ID context",
551 		.type = OPTION_ARG_FUNC,
552 		.opt.argfunc = s_server_opt_context,
553 	},
554 	{
555 		.name = "crlf",
556 		.desc = "Convert LF from terminal into CRLF",
557 		.type = OPTION_FLAG,
558 		.opt.flag = &s_server_config.crlf,
559 	},
560 	{
561 		.name = "dcert",
562 		.argname = "file",
563 		.desc = "Second certificate file to use (usually for DSA)",
564 		.type = OPTION_ARG,
565 		.opt.arg = &s_server_config.dcert_file,
566 	},
567 	{
568 		.name = "dcertform",
569 		.argname = "fmt",
570 		.desc = "Second certificate format (PEM or DER) PEM default",
571 		.type = OPTION_ARG_FORMAT,
572 		.opt.value = &s_server_config.dcert_format,
573 	},
574 	{
575 		.name = "debug",
576 		.desc = "Print more output",
577 		.type = OPTION_FLAG,
578 		.opt.flag = &s_server_config.debug,
579 	},
580 	{
581 		.name = "dhparam",
582 		.argname = "file",
583 		.desc = "DH parameter file to use, in cert file if not specified",
584 		.type = OPTION_ARG,
585 		.opt.arg = &s_server_config.dhfile,
586 	},
587 	{
588 		.name = "dkey",
589 		.argname = "file",
590 		.desc = "Second private key file to use (usually for DSA)",
591 		.type = OPTION_ARG,
592 		.opt.arg = &s_server_config.dkey_file,
593 	},
594 	{
595 		.name = "dkeyform",
596 		.argname = "fmt",
597 		.desc = "Second key format (PEM or DER) PEM default",
598 		.type = OPTION_ARG_FORMAT,
599 		.opt.value = &s_server_config.dkey_format,
600 	},
601 	{
602 		.name = "dpass",
603 		.argname = "arg",
604 		.desc = "Second private key file pass phrase source",
605 		.type = OPTION_ARG,
606 		.opt.arg = &s_server_config.dpassarg,
607 	},
608 #ifndef OPENSSL_NO_DTLS1
609 	{
610 		.name = "dtls1",
611 		.desc = "Just talk DTLSv1",
612 		.type = OPTION_FUNC,
613 		.opt.func = s_server_protocol_version_dtls1,
614 	},
615 #endif
616 	{
617 		.name = "groups",
618 		.argname = "list",
619 		.desc = "Specify EC groups (colon-separated list)",
620 		.type = OPTION_ARG,
621 		.opt.arg = &s_server_config.groups_in,
622 	},
623 	{
624 		.name = "HTTP",
625 		.desc = "Respond to a 'GET /<path> HTTP/1.0' with file ./<path>",
626 		.type = OPTION_VALUE,
627 		.opt.value = &s_server_config.www,
628 		.value = 3,
629 	},
630 	{
631 		.name = "id_prefix",
632 		.argname = "arg",
633 		.desc = "Generate SSL/TLS session IDs prefixed by 'arg'",
634 		.type = OPTION_ARG,
635 		.opt.arg = &s_server_config.session_id_prefix,
636 	},
637 	{
638 		.name = "key",
639 		.argname = "file",
640 		.desc = "Private Key file to use, in cert file if\n"
641 			"not specified (default is " TEST_CERT ")",
642 		.type = OPTION_ARG,
643 		.opt.arg = &s_server_config.key_file,
644 	},
645 	{
646 		.name = "key2",
647 		.argname = "file",
648 		.desc = "Private Key file to use for servername, in cert file if\n"
649 			"not specified (default is " TEST_CERT2 ")",
650 		.type = OPTION_ARG,
651 		.opt.arg = &s_server_config.key_file2,
652 	},
653 	{
654 		.name = "keyform",
655 		.argname = "fmt",
656 		.desc = "Key format (PEM or DER) PEM default",
657 		.type = OPTION_ARG_FORMAT,
658 		.opt.value = &s_server_config.key_format,
659 	},
660 	{
661 		.name = "keymatexport",
662 		.argname = "label",
663 		.desc = "Export keying material using label",
664 		.type = OPTION_ARG,
665 		.opt.arg = &s_server_config.keymatexportlabel,
666 	},
667 	{
668 		.name = "keymatexportlen",
669 		.argname = "len",
670 		.desc = "Export len bytes of keying material (default 20)",
671 		.type = OPTION_ARG_FUNC,
672 		.opt.argfunc = s_server_opt_keymatexportlen,
673 	},
674 	{
675 		.name = "legacy_renegotiation",
676 		.type = OPTION_DISCARD,
677 	},
678 	{
679 		.name = "msg",
680 		.desc = "Show protocol messages",
681 		.type = OPTION_FLAG,
682 		.opt.flag = &s_server_config.msg,
683 	},
684 #ifndef OPENSSL_NO_DTLS1
685 	{
686 		.name = "mtu",
687 		.argname = "mtu",
688 		.desc = "Set link layer MTU",
689 		.type = OPTION_ARG_FUNC,
690 		.opt.argfunc = s_server_opt_mtu,
691 	},
692 #endif
693 	{
694 		.name = "named_curve",
695 		.argname = "arg",
696 		.type = OPTION_ARG,
697 		.opt.arg = &s_server_config.named_curve,
698 	},
699 	{
700 		.name = "nbio",
701 		.desc = "Run with non-blocking I/O",
702 		.type = OPTION_FLAG,
703 		.opt.flag = &s_server_config.nbio,
704 	},
705 	{
706 		.name = "nbio_test",
707 		.desc = "Test with the non-blocking test bio",
708 		.type = OPTION_FUNC,
709 		.opt.func = s_server_opt_nbio_test,
710 	},
711 	{
712 		.name = "nextprotoneg",
713 		.argname = "arg",
714 		.type = OPTION_ARG,
715 		.opt.arg = &s_server_config.npn_in, /* Ignored. */
716 	},
717 	{
718 		.name = "no_cache",
719 		.desc = "Disable session cache",
720 		.type = OPTION_FLAG,
721 		.opt.flag = &s_server_config.no_cache,
722 	},
723 	{
724 		.name = "no_comp",
725 		.desc = "Disable SSL/TLS compression",
726 		.type = OPTION_VALUE_OR,
727 		.opt.value = &s_server_config.off,
728 		.value = SSL_OP_NO_COMPRESSION,
729 	},
730 	{
731 		.name = "no_dhe",
732 		.desc = "Disable ephemeral DH",
733 		.type = OPTION_FLAG,
734 		.opt.flag = &s_server_config.no_dhe,
735 	},
736 	{
737 		.name = "no_ecdhe",
738 		.desc = "Disable ephemeral ECDH",
739 		.type = OPTION_FLAG,
740 		.opt.flag = &s_server_config.no_ecdhe,
741 	},
742 	{
743 		.name = "no_ticket",
744 		.desc = "Disable use of RFC4507bis session tickets",
745 		.type = OPTION_VALUE_OR,
746 		.opt.value = &s_server_config.off,
747 		.value = SSL_OP_NO_TICKET,
748 	},
749 	{
750 		.name = "no_ssl2",
751 		.type = OPTION_VALUE_OR,
752 		.opt.value = &s_server_config.off,
753 		.value = SSL_OP_NO_SSLv2,
754 	},
755 	{
756 		.name = "no_ssl3",
757 		.type = OPTION_VALUE_OR,
758 		.opt.value = &s_server_config.off,
759 		.value = SSL_OP_NO_SSLv3,
760 	},
761 	{
762 		.name = "no_tls1",
763 		.desc = "Just disable TLSv1",
764 		.type = OPTION_VALUE_OR,
765 		.opt.value = &s_server_config.off,
766 		.value = SSL_OP_NO_TLSv1,
767 	},
768 	{
769 		.name = "no_tls1_1",
770 		.desc = "Just disable TLSv1.1",
771 		.type = OPTION_VALUE_OR,
772 		.opt.value = &s_server_config.off,
773 		.value = SSL_OP_NO_TLSv1_1,
774 	},
775 	{
776 		.name = "no_tls1_2",
777 		.desc = "Just disable TLSv1.2",
778 		.type = OPTION_VALUE_OR,
779 		.opt.value = &s_server_config.off,
780 		.value = SSL_OP_NO_TLSv1_2,
781 	},
782 	{
783 		.name = "no_tls1_3",
784 		.desc = "Just disable TLSv1.3",
785 		.type = OPTION_VALUE_OR,
786 		.opt.value = &s_server_config.off,
787 		.value = SSL_OP_NO_TLSv1_3,
788 	},
789 	{
790 		.name = "no_tmp_rsa",
791 		.type = OPTION_DISCARD,
792 	},
793 	{
794 		.name = "nocert",
795 		.desc = "Don't use any certificates (Anon-DH)",
796 		.type = OPTION_FLAG,
797 		.opt.flag = &s_server_config.nocert,
798 	},
799 	{
800 		.name = "pass",
801 		.argname = "arg",
802 		.desc = "Private key file pass phrase source",
803 		.type = OPTION_ARG,
804 		.opt.arg = &s_server_config.passarg,
805 	},
806 	{
807 		.name = "port",
808 		.argname = "port",
809 		.type = OPTION_ARG_FUNC,
810 		.opt.argfunc = s_server_opt_port,
811 	},
812 	{
813 		.name = "quiet",
814 		.desc = "Inhibit printing of session and certificate information",
815 		.type = OPTION_FLAG,
816 		.opt.flag = &s_server_config.quiet,
817 	},
818 	{
819 		.name = "servername",
820 		.argname = "name",
821 		.desc = "Servername for HostName TLS extension",
822 		.type = OPTION_ARG,
823 		.opt.arg = &s_server_config.tlsextcbp.servername,
824 	},
825 	{
826 		.name = "servername_fatal",
827 		.desc = "On mismatch send fatal alert (default warning alert)",
828 		.type = OPTION_VALUE,
829 		.opt.value = &s_server_config.tlsextcbp.extension_error,
830 		.value = SSL_TLSEXT_ERR_ALERT_FATAL,
831 	},
832 	{
833 		.name = "serverpref",
834 		.desc = "Use server's cipher preferences",
835 		.type = OPTION_VALUE_OR,
836 		.opt.value = &s_server_config.off,
837 		.value = SSL_OP_CIPHER_SERVER_PREFERENCE,
838 	},
839 	{
840 		.name = "state",
841 		.desc = "Print the SSL states",
842 		.type = OPTION_FLAG,
843 		.opt.flag = &s_server_config.state,
844 	},
845 	{
846 		.name = "status",
847 		.desc = "Respond to certificate status requests",
848 		.type = OPTION_FLAG,
849 		.opt.flag = &s_server_config.tlsextstatus,
850 	},
851 	{
852 		.name = "status_timeout",
853 		.argname = "nsec",
854 		.desc = "Status request responder timeout",
855 		.type = OPTION_ARG_FUNC,
856 		.opt.argfunc = s_server_opt_status_timeout,
857 	},
858 	{
859 		.name = "status_url",
860 		.argname = "url",
861 		.desc = "Status request fallback URL",
862 		.type = OPTION_ARG_FUNC,
863 		.opt.argfunc = s_server_opt_status_url,
864 	},
865 	{
866 		.name = "status_verbose",
867 		.desc = "Enable status request verbose printout",
868 		.type = OPTION_FUNC,
869 		.opt.func = s_server_opt_status_verbose,
870 	},
871 #ifndef OPENSSL_NO_DTLS1
872 	{
873 		.name = "timeout",
874 		.desc = "Enable timeouts",
875 		.type = OPTION_FLAG,
876 		.opt.flag = &s_server_config.enable_timeouts,
877 	},
878 #endif
879 	{
880 		.name = "tls1",
881 		.desc = "Just talk TLSv1",
882 		.type = OPTION_FUNC,
883 		.opt.func = s_server_protocol_version_tls1,
884 	},
885 	{
886 		.name = "tls1_1",
887 		.desc = "Just talk TLSv1.1",
888 		.type = OPTION_FUNC,
889 		.opt.func = s_server_protocol_version_tls1_1,
890 	},
891 	{
892 		.name = "tls1_2",
893 		.desc = "Just talk TLSv1.2",
894 		.type = OPTION_FUNC,
895 		.opt.func = s_server_protocol_version_tls1_2,
896 	},
897 	{
898 		.name = "tls1_3",
899 		.desc = "Just talk TLSv1.3",
900 		.type = OPTION_FUNC,
901 		.opt.func = s_server_protocol_version_tls1_3,
902 	},
903 	{
904 		.name = "tlsextdebug",
905 		.desc = "Hex dump of all TLS extensions received",
906 		.type = OPTION_FLAG,
907 		.opt.flag = &s_server_config.tlsextdebug,
908 	},
909 #ifndef OPENSSL_NO_SRTP
910 	{
911 		.name = "use_srtp",
912 		.argname = "profiles",
913 		.desc = "Offer SRTP key management with a colon-separated profile list",
914 		.type = OPTION_ARG,
915 		.opt.arg = &s_server_config.srtp_profiles,
916 	},
917 #endif
918 	{
919 		.name = "Verify",
920 		.argname = "depth",
921 		.desc = "Turn on peer certificate verification, must have a cert",
922 		.type = OPTION_ARG_FUNC,
923 		.opt.argfunc = s_server_opt_verify_fail,
924 	},
925 	{
926 		.name = "verify",
927 		.argname = "depth",
928 		.desc = "Turn on peer certificate verification",
929 		.type = OPTION_ARG_FUNC,
930 		.opt.argfunc = s_server_opt_verify,
931 	},
932 	{
933 		.name = "verify_return_error",
934 		.desc = "Return verification error",
935 		.type = OPTION_FLAG,
936 		.opt.flag = &verify_return_error,
937 	},
938 	{
939 		.name = "WWW",
940 		.desc = "Respond to a 'GET /<path> HTTP/1.0' with file ./<path>",
941 		.type = OPTION_VALUE,
942 		.opt.value = &s_server_config.www,
943 		.value = 2,
944 	},
945 	{
946 		.name = "www",
947 		.desc = "Respond to a 'GET /' with a status page",
948 		.type = OPTION_VALUE,
949 		.opt.value = &s_server_config.www,
950 		.value = 1,
951 	},
952 	{
953 		.name = NULL,
954 		.desc = "",
955 		.type = OPTION_ARGV_FUNC,
956 		.opt.argvfunc = s_server_opt_verify_param,
957 	},
958 	{ NULL },
959 };
960 
961 static void
962 s_server_init(void)
963 {
964 	accept_socket = -1;
965 	s_server_config.cipher = NULL;
966 	s_server_config.server_verify = SSL_VERIFY_NONE;
967 	s_server_config.dcert_file = NULL;
968 	s_server_config.dkey_file = NULL;
969 	s_server_config.cert_file = TEST_CERT;
970 	s_server_config.key_file = NULL;
971 	s_server_config.cert_file2 = TEST_CERT2;
972 	s_server_config.key_file2 = NULL;
973 	ctx2 = NULL;
974 	s_server_config.nbio = 0;
975 	s_server_config.nbio_test = 0;
976 	ctx = NULL;
977 	s_server_config.www = 0;
978 
979 	bio_s_out = NULL;
980 	s_server_config.debug = 0;
981 	s_server_config.msg = 0;
982 	s_server_config.quiet = 0;
983 }
984 
985 static void
986 sv_usage(void)
987 {
988 	fprintf(stderr, "usage: s_server "
989 	    "[-accept port] [-alpn protocols] [-bugs] [-CAfile file]\n"
990 	    "    [-CApath directory] [-cert file] [-cert2 file]\n"
991 	    "    [-certform der | pem] [-cipher cipherlist]\n"
992 	    "    [-context id] [-crl_check] [-crl_check_all] [-crlf]\n"
993 	    "    [-dcert file] [-dcertform der | pem] [-debug]\n"
994 	    "    [-dhparam file] [-dkey file] [-dkeyform der | pem]\n"
995 	    "    [-dpass arg] [-dtls1] [-groups list] [-HTTP]\n"
996 	    "    [-id_prefix arg] [-key keyfile] [-key2 keyfile]\n"
997 	    "    [-keyform der | pem] [-keymatexport label]\n"
998 	    "    [-keymatexportlen len] [-msg] [-mtu mtu]\n"
999 	    "    [-named_curve arg] [-nbio] [-nbio_test] [-no_cache]\n"
1000 	    "    [-no_dhe] [-no_ecdhe] [-no_ticket] [-no_tls1]\n"
1001 	    "    [-no_tls1_1] [-no_tls1_2] [-no_tls1_3] [-no_tmp_rsa]\n"
1002 	    "    [-nocert] [-pass arg] [-quiet] [-servername name]\n"
1003 	    "    [-servername_fatal] [-serverpref] [-state] [-status]\n"
1004 	    "    [-status_timeout nsec] [-status_url url]\n"
1005 	    "    [-status_verbose] [-timeout] [-tls1] [-tls1_1]\n"
1006 	    "    [-tls1_2] [-tls1_3] [-tlsextdebug] [-use_srtp profiles]\n"
1007 	    "    [-Verify depth] [-verify depth] [-verify_return_error]\n"
1008 	    "    [-WWW] [-www]\n");
1009 	fprintf(stderr, "\n");
1010 	options_usage(s_server_options);
1011 	fprintf(stderr, "\n");
1012 }
1013 
1014 int
1015 s_server_main(int argc, char *argv[])
1016 {
1017 	int badop = 0;
1018 	int ret = 1;
1019 	char *pass = NULL;
1020 	char *dpass = NULL;
1021 	X509 *s_cert = NULL, *s_dcert = NULL;
1022 	EVP_PKEY *s_key = NULL, *s_dkey = NULL;
1023 	EVP_PKEY *s_key2 = NULL;
1024 	X509 *s_cert2 = NULL;
1025 	tlsextalpnctx alpn_ctx = { NULL, 0 };
1026 
1027 	if (single_execution) {
1028 		if (pledge("stdio rpath inet dns tty", NULL) == -1) {
1029 			perror("pledge");
1030 			exit(1);
1031 		}
1032 	}
1033 
1034 	memset(&s_server_config, 0, sizeof(s_server_config));
1035 	s_server_config.keymatexportlen = 20;
1036 	s_server_config.meth = TLS_server_method();
1037 	s_server_config.port = PORT;
1038 	s_server_config.cert_file = TEST_CERT;
1039 	s_server_config.cert_file2 = TEST_CERT2;
1040 	s_server_config.cert_format = FORMAT_PEM;
1041 	s_server_config.dcert_format = FORMAT_PEM;
1042 	s_server_config.dkey_format = FORMAT_PEM;
1043 	s_server_config.key_format = FORMAT_PEM;
1044 	s_server_config.server_verify = SSL_VERIFY_NONE;
1045 	s_server_config.socket_type = SOCK_STREAM;
1046 	s_server_config.tlscstatp.timeout = -1;
1047 	s_server_config.tlsextcbp.extension_error =
1048 	    SSL_TLSEXT_ERR_ALERT_WARNING;
1049 
1050 	local_argc = argc;
1051 	local_argv = argv;
1052 
1053 	s_server_init();
1054 
1055 	verify_depth = 0;
1056 
1057 	if (options_parse(argc, argv, s_server_options, NULL, NULL) != 0) {
1058 		badop = 1;
1059 		goto bad;
1060 	}
1061 	if (badop) {
1062  bad:
1063 		if (s_server_config.errstr == NULL)
1064 			sv_usage();
1065 		goto end;
1066 	}
1067 
1068 	if (!app_passwd(bio_err, s_server_config.passarg,
1069 	    s_server_config.dpassarg, &pass, &dpass)) {
1070 		BIO_printf(bio_err, "Error getting password\n");
1071 		goto end;
1072 	}
1073 	if (s_server_config.key_file == NULL)
1074 		s_server_config.key_file = s_server_config.cert_file;
1075 	if (s_server_config.key_file2 == NULL)
1076 		s_server_config.key_file2 = s_server_config.cert_file2;
1077 
1078 	if (s_server_config.nocert == 0) {
1079 		s_key = load_key(bio_err, s_server_config.key_file,
1080 		    s_server_config.key_format, 0, pass,
1081 		    "server certificate private key file");
1082 		if (!s_key) {
1083 			ERR_print_errors(bio_err);
1084 			goto end;
1085 		}
1086 		s_cert = load_cert(bio_err, s_server_config.cert_file,
1087 		    s_server_config.cert_format,
1088 		    NULL, "server certificate file");
1089 
1090 		if (!s_cert) {
1091 			ERR_print_errors(bio_err);
1092 			goto end;
1093 		}
1094 		if (s_server_config.tlsextcbp.servername) {
1095 			s_key2 = load_key(bio_err, s_server_config.key_file2,
1096 			    s_server_config.key_format, 0, pass,
1097 			    "second server certificate private key file");
1098 			if (!s_key2) {
1099 				ERR_print_errors(bio_err);
1100 				goto end;
1101 			}
1102 			s_cert2 = load_cert(bio_err, s_server_config.cert_file2,
1103 			    s_server_config.cert_format,
1104 			    NULL, "second server certificate file");
1105 
1106 			if (!s_cert2) {
1107 				ERR_print_errors(bio_err);
1108 				goto end;
1109 			}
1110 		}
1111 	}
1112 	alpn_ctx.data = NULL;
1113 	if (s_server_config.alpn_in) {
1114 		unsigned short len;
1115 		alpn_ctx.data = next_protos_parse(&len,
1116 		    s_server_config.alpn_in);
1117 		if (alpn_ctx.data == NULL)
1118 			goto end;
1119 		alpn_ctx.len = len;
1120 	}
1121 
1122 	if (s_server_config.dcert_file) {
1123 
1124 		if (s_server_config.dkey_file == NULL)
1125 			s_server_config.dkey_file = s_server_config.dcert_file;
1126 
1127 		s_dkey = load_key(bio_err, s_server_config.dkey_file,
1128 		    s_server_config.dkey_format,
1129 		    0, dpass, "second certificate private key file");
1130 		if (!s_dkey) {
1131 			ERR_print_errors(bio_err);
1132 			goto end;
1133 		}
1134 		s_dcert = load_cert(bio_err, s_server_config.dcert_file,
1135 		    s_server_config.dcert_format,
1136 		    NULL, "second server certificate file");
1137 
1138 		if (!s_dcert) {
1139 			ERR_print_errors(bio_err);
1140 			goto end;
1141 		}
1142 	}
1143 	if (bio_s_out == NULL) {
1144 		if (s_server_config.quiet && !s_server_config.debug &&
1145 		    !s_server_config.msg) {
1146 			bio_s_out = BIO_new(BIO_s_null());
1147 		} else {
1148 			if (bio_s_out == NULL)
1149 				bio_s_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1150 		}
1151 	}
1152 	if (s_server_config.nocert) {
1153 		s_server_config.cert_file = NULL;
1154 		s_server_config.key_file = NULL;
1155 		s_server_config.dcert_file = NULL;
1156 		s_server_config.dkey_file = NULL;
1157 		s_server_config.cert_file2 = NULL;
1158 		s_server_config.key_file2 = NULL;
1159 	}
1160 	ctx = SSL_CTX_new(s_server_config.meth);
1161 	if (ctx == NULL) {
1162 		ERR_print_errors(bio_err);
1163 		goto end;
1164 	}
1165 
1166 	SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1167 
1168 	if (!SSL_CTX_set_min_proto_version(ctx, s_server_config.min_version))
1169 		goto end;
1170 	if (!SSL_CTX_set_max_proto_version(ctx, s_server_config.max_version))
1171 		goto end;
1172 
1173 	if (s_server_config.session_id_prefix) {
1174 		if (strlen(s_server_config.session_id_prefix) >= 32)
1175 			BIO_printf(bio_err,
1176 			    "warning: id_prefix is too long, only one new session will be possible\n");
1177 		else if (strlen(s_server_config.session_id_prefix) >= 16)
1178 			BIO_printf(bio_err,
1179 			    "warning: id_prefix is too long if you use SSLv2\n");
1180 		if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1181 			BIO_printf(bio_err, "error setting 'id_prefix'\n");
1182 			ERR_print_errors(bio_err);
1183 			goto end;
1184 		}
1185 		BIO_printf(bio_err, "id_prefix '%s' set.\n",
1186 		    s_server_config.session_id_prefix);
1187 	}
1188 	SSL_CTX_set_quiet_shutdown(ctx, 1);
1189 	if (s_server_config.bugs)
1190 		SSL_CTX_set_options(ctx, SSL_OP_ALL);
1191 	SSL_CTX_set_options(ctx, s_server_config.off);
1192 	/*
1193 	 * DTLS: partial reads end up discarding unread UDP bytes :-( Setting
1194 	 * read ahead solves this problem.
1195 	 */
1196 	if (s_server_config.socket_type == SOCK_DGRAM)
1197 		SSL_CTX_set_read_ahead(ctx, 1);
1198 
1199 	if (s_server_config.state)
1200 		SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1201 	if (s_server_config.no_cache)
1202 		SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1203 	else
1204 		SSL_CTX_sess_set_cache_size(ctx, 128);
1205 
1206 #ifndef OPENSSL_NO_SRTP
1207 	if (s_server_config.srtp_profiles != NULL)
1208 		SSL_CTX_set_tlsext_use_srtp(ctx, s_server_config.srtp_profiles);
1209 #endif
1210 
1211 	if ((!SSL_CTX_load_verify_locations(ctx, s_server_config.CAfile,
1212 	    s_server_config.CApath)) ||
1213 	    (!SSL_CTX_set_default_verify_paths(ctx))) {
1214 		/* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
1215 		ERR_print_errors(bio_err);
1216 		/* goto end; */
1217 	}
1218 	if (s_server_config.vpm)
1219 		SSL_CTX_set1_param(ctx, s_server_config.vpm);
1220 
1221 	if (s_cert2) {
1222 		ctx2 = SSL_CTX_new(s_server_config.meth);
1223 		if (ctx2 == NULL) {
1224 			ERR_print_errors(bio_err);
1225 			goto end;
1226 		}
1227 
1228 		if (!SSL_CTX_set_min_proto_version(ctx2,
1229 		    s_server_config.min_version))
1230 			goto end;
1231 		if (!SSL_CTX_set_max_proto_version(ctx2,
1232 		    s_server_config.max_version))
1233 			goto end;
1234 		SSL_CTX_clear_mode(ctx2, SSL_MODE_AUTO_RETRY);
1235 	}
1236 	if (ctx2) {
1237 		BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1238 
1239 		if (s_server_config.session_id_prefix) {
1240 			if (strlen(s_server_config.session_id_prefix) >= 32)
1241 				BIO_printf(bio_err,
1242 				    "warning: id_prefix is too long, only one new session will be possible\n");
1243 			else if (strlen(s_server_config.session_id_prefix) >= 16)
1244 				BIO_printf(bio_err,
1245 				    "warning: id_prefix is too long if you use SSLv2\n");
1246 			if (!SSL_CTX_set_generate_session_id(ctx2,
1247 			    generate_session_id)) {
1248 				BIO_printf(bio_err,
1249 				    "error setting 'id_prefix'\n");
1250 				ERR_print_errors(bio_err);
1251 				goto end;
1252 			}
1253 			BIO_printf(bio_err, "id_prefix '%s' set.\n",
1254 			    s_server_config.session_id_prefix);
1255 		}
1256 		SSL_CTX_set_quiet_shutdown(ctx2, 1);
1257 		if (s_server_config.bugs)
1258 			SSL_CTX_set_options(ctx2, SSL_OP_ALL);
1259 		SSL_CTX_set_options(ctx2, s_server_config.off);
1260 		/*
1261 		 * DTLS: partial reads end up discarding unread UDP bytes :-(
1262 		 * Setting read ahead solves this problem.
1263 		 */
1264 		if (s_server_config.socket_type == SOCK_DGRAM)
1265 			SSL_CTX_set_read_ahead(ctx2, 1);
1266 
1267 		if (s_server_config.state)
1268 			SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1269 
1270 		if (s_server_config.no_cache)
1271 			SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1272 		else
1273 			SSL_CTX_sess_set_cache_size(ctx2, 128);
1274 
1275 		if ((!SSL_CTX_load_verify_locations(ctx2,
1276 		    s_server_config.CAfile, s_server_config.CApath)) ||
1277 		    (!SSL_CTX_set_default_verify_paths(ctx2))) {
1278 			ERR_print_errors(bio_err);
1279 		}
1280 		if (s_server_config.vpm)
1281 			SSL_CTX_set1_param(ctx2, s_server_config.vpm);
1282 	}
1283 	if (alpn_ctx.data)
1284 		SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1285 
1286 	if (s_server_config.groups_in != NULL) {
1287 		if (SSL_CTX_set1_groups_list(ctx, s_server_config.groups_in) != 1) {
1288 			BIO_printf(bio_err, "Failed to set groups '%s'\n",
1289 			    s_server_config.groups_in);
1290 			goto end;
1291 		}
1292 	}
1293 
1294 #ifndef OPENSSL_NO_DH
1295 	if (!s_server_config.no_dhe) {
1296 		DH *dh = NULL;
1297 
1298 		if (s_server_config.dhfile)
1299 			dh = load_dh_param(s_server_config.dhfile);
1300 		else if (s_server_config.cert_file)
1301 			dh = load_dh_param(s_server_config.cert_file);
1302 
1303 		if (dh != NULL)
1304 			BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1305 		else
1306 			BIO_printf(bio_s_out, "Using auto DH parameters\n");
1307 		(void) BIO_flush(bio_s_out);
1308 
1309 		if (dh == NULL)
1310 			SSL_CTX_set_dh_auto(ctx, 1);
1311 		else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1312 			BIO_printf(bio_err,
1313 			    "Error setting temp DH parameters\n");
1314 			ERR_print_errors(bio_err);
1315 			DH_free(dh);
1316 			goto end;
1317 		}
1318 
1319 		if (ctx2) {
1320 			if (!s_server_config.dhfile) {
1321 				DH *dh2 = NULL;
1322 
1323 				if (s_server_config.cert_file2 != NULL)
1324 					dh2 = load_dh_param(
1325 					    s_server_config.cert_file2);
1326 				if (dh2 != NULL) {
1327 					BIO_printf(bio_s_out,
1328 					    "Setting temp DH parameters\n");
1329 					(void) BIO_flush(bio_s_out);
1330 
1331 					DH_free(dh);
1332 					dh = dh2;
1333 				}
1334 			}
1335 			if (dh == NULL)
1336 				SSL_CTX_set_dh_auto(ctx2, 1);
1337 			else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1338 				BIO_printf(bio_err,
1339 				    "Error setting temp DH parameters\n");
1340 				ERR_print_errors(bio_err);
1341 				DH_free(dh);
1342 				goto end;
1343 			}
1344 		}
1345 		DH_free(dh);
1346 	}
1347 #endif
1348 
1349 	if (!s_server_config.no_ecdhe && s_server_config.named_curve != NULL) {
1350 		EC_KEY *ecdh = NULL;
1351 		int nid;
1352 
1353 		if ((nid = OBJ_sn2nid(s_server_config.named_curve)) == 0) {
1354 			BIO_printf(bio_err, "unknown curve name (%s)\n",
1355 			    s_server_config.named_curve);
1356 			goto end;
1357  		}
1358 		if ((ecdh = EC_KEY_new_by_curve_name(nid)) == NULL) {
1359 			BIO_printf(bio_err, "unable to create curve (%s)\n",
1360 			    s_server_config.named_curve);
1361 			goto end;
1362  		}
1363 		BIO_printf(bio_s_out, "Setting temp ECDH parameters\n");
1364 		(void) BIO_flush(bio_s_out);
1365 
1366 		SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1367 		if (ctx2)
1368 			SSL_CTX_set_tmp_ecdh(ctx2, ecdh);
1369 		EC_KEY_free(ecdh);
1370 	}
1371 
1372 	if (!set_cert_key_stuff(ctx, s_cert, s_key))
1373 		goto end;
1374 	if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2))
1375 		goto end;
1376 	if (s_dcert != NULL) {
1377 		if (!set_cert_key_stuff(ctx, s_dcert, s_dkey))
1378 			goto end;
1379 	}
1380 
1381 	if (s_server_config.cipher != NULL) {
1382 		if (!SSL_CTX_set_cipher_list(ctx, s_server_config.cipher)) {
1383 			BIO_printf(bio_err, "error setting cipher list\n");
1384 			ERR_print_errors(bio_err);
1385 			goto end;
1386 		}
1387 		if (ctx2 && !SSL_CTX_set_cipher_list(ctx2,
1388 		    s_server_config.cipher)) {
1389 			BIO_printf(bio_err, "error setting cipher list\n");
1390 			ERR_print_errors(bio_err);
1391 			goto end;
1392 		}
1393 	}
1394 	SSL_CTX_set_verify(ctx, s_server_config.server_verify, verify_callback);
1395 	SSL_CTX_set_session_id_context(ctx,
1396 	    (void *) &s_server_session_id_context,
1397 	    sizeof s_server_session_id_context);
1398 
1399 	/* Set DTLS cookie generation and verification callbacks */
1400 	SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1401 	SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1402 
1403 	if (ctx2) {
1404 		SSL_CTX_set_verify(ctx2, s_server_config.server_verify,
1405 		    verify_callback);
1406 		SSL_CTX_set_session_id_context(ctx2,
1407 		    (void *) &s_server_session_id_context,
1408 		    sizeof s_server_session_id_context);
1409 
1410 		s_server_config.tlsextcbp.biodebug = bio_s_out;
1411 		SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1412 		SSL_CTX_set_tlsext_servername_arg(ctx2,
1413 		    &s_server_config.tlsextcbp);
1414 		SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1415 		SSL_CTX_set_tlsext_servername_arg(ctx,
1416 		    &s_server_config.tlsextcbp);
1417 	}
1418 
1419 	if (s_server_config.CAfile != NULL) {
1420 		SSL_CTX_set_client_CA_list(ctx,
1421 		    SSL_load_client_CA_file(s_server_config.CAfile));
1422 		if (ctx2)
1423 			SSL_CTX_set_client_CA_list(ctx2,
1424 			    SSL_load_client_CA_file(s_server_config.CAfile));
1425 	}
1426 	BIO_printf(bio_s_out, "ACCEPT\n");
1427 	(void) BIO_flush(bio_s_out);
1428 	if (s_server_config.www)
1429 		do_server(s_server_config.port, s_server_config.socket_type,
1430 		    &accept_socket, www_body, s_server_config.context);
1431 	else
1432 		do_server(s_server_config.port, s_server_config.socket_type,
1433 		    &accept_socket, sv_body, s_server_config.context);
1434 	print_stats(bio_s_out, ctx);
1435 	ret = 0;
1436  end:
1437 	SSL_CTX_free(ctx);
1438 	X509_free(s_cert);
1439 	X509_free(s_dcert);
1440 	EVP_PKEY_free(s_key);
1441 	EVP_PKEY_free(s_dkey);
1442 	free(pass);
1443 	free(dpass);
1444 	X509_VERIFY_PARAM_free(s_server_config.vpm);
1445 	free(s_server_config.tlscstatp.host);
1446 	free(s_server_config.tlscstatp.port);
1447 	free(s_server_config.tlscstatp.path);
1448 	SSL_CTX_free(ctx2);
1449 	X509_free(s_cert2);
1450 	EVP_PKEY_free(s_key2);
1451 	free(alpn_ctx.data);
1452 	if (bio_s_out != NULL) {
1453 		BIO_free(bio_s_out);
1454 		bio_s_out = NULL;
1455 	}
1456 
1457 	return (ret);
1458 }
1459 
1460 static void
1461 print_stats(BIO *bio, SSL_CTX *ssl_ctx)
1462 {
1463 	BIO_printf(bio, "%4ld items in the session cache\n",
1464 	    SSL_CTX_sess_number(ssl_ctx));
1465 	BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
1466 	    SSL_CTX_sess_connect(ssl_ctx));
1467 	BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
1468 	    SSL_CTX_sess_connect_renegotiate(ssl_ctx));
1469 	BIO_printf(bio, "%4ld client connects that finished\n",
1470 	    SSL_CTX_sess_connect_good(ssl_ctx));
1471 	BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
1472 	    SSL_CTX_sess_accept(ssl_ctx));
1473 	BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
1474 	    SSL_CTX_sess_accept_renegotiate(ssl_ctx));
1475 	BIO_printf(bio, "%4ld server accepts that finished\n",
1476 	    SSL_CTX_sess_accept_good(ssl_ctx));
1477 	BIO_printf(bio, "%4ld session cache hits\n",
1478 	    SSL_CTX_sess_hits(ssl_ctx));
1479 	BIO_printf(bio, "%4ld session cache misses\n",
1480 	    SSL_CTX_sess_misses(ssl_ctx));
1481 	BIO_printf(bio, "%4ld session cache timeouts\n",
1482 	    SSL_CTX_sess_timeouts(ssl_ctx));
1483 	BIO_printf(bio, "%4ld callback cache hits\n",
1484 	    SSL_CTX_sess_cb_hits(ssl_ctx));
1485 	BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
1486 	    SSL_CTX_sess_cache_full(ssl_ctx),
1487 	    SSL_CTX_sess_get_cache_size(ssl_ctx));
1488 }
1489 
1490 static int
1491 sv_body(char *hostname, int s, unsigned char *context)
1492 {
1493 	char *buf = NULL;
1494 	int ret = 1;
1495 	int k, i;
1496 	unsigned long l;
1497 	SSL *con = NULL;
1498 	BIO *sbio;
1499 	struct timeval timeout;
1500 
1501 	if ((buf = malloc(bufsize)) == NULL) {
1502 		BIO_printf(bio_err, "out of memory\n");
1503 		goto err;
1504 	}
1505 	if (s_server_config.nbio) {
1506 		if (!s_server_config.quiet)
1507 			BIO_printf(bio_err, "turning on non blocking io\n");
1508 		if (!BIO_socket_nbio(s, 1))
1509 			ERR_print_errors(bio_err);
1510 	}
1511 
1512 	if (con == NULL) {
1513 		con = SSL_new(ctx);
1514 		if (s_server_config.tlsextdebug) {
1515 			SSL_set_tlsext_debug_callback(con, tlsext_cb);
1516 			SSL_set_tlsext_debug_arg(con, bio_s_out);
1517 		}
1518 		if (s_server_config.tlsextstatus) {
1519 			SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1520 			s_server_config.tlscstatp.err = bio_err;
1521 			SSL_CTX_set_tlsext_status_arg(ctx,
1522 			    &s_server_config.tlscstatp);
1523 		}
1524 		if (context)
1525 			SSL_set_session_id_context(con, context,
1526 			    strlen((char *) context));
1527 	}
1528 	SSL_clear(con);
1529 
1530 	if (SSL_version(con) == DTLS1_VERSION) {
1531 
1532 		sbio = BIO_new_dgram(s, BIO_NOCLOSE);
1533 
1534 		if (s_server_config.enable_timeouts) {
1535 			timeout.tv_sec = 0;
1536 			timeout.tv_usec = DGRAM_RCV_TIMEOUT;
1537 			BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0,
1538 			    &timeout);
1539 
1540 			timeout.tv_sec = 0;
1541 			timeout.tv_usec = DGRAM_SND_TIMEOUT;
1542 			BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0,
1543 			    &timeout);
1544 		}
1545 		if (s_server_config.socket_mtu > 28) {
1546 			SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
1547 			SSL_set_mtu(con, s_server_config.socket_mtu - 28);
1548 		} else
1549 			/* want to do MTU discovery */
1550 			BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
1551 
1552 		/* turn on cookie exchange */
1553 		SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
1554 	} else
1555 		sbio = BIO_new_socket(s, BIO_NOCLOSE);
1556 
1557 	if (s_server_config.nbio_test) {
1558 		BIO *test;
1559 
1560 		test = BIO_new(BIO_f_nbio_test());
1561 		sbio = BIO_push(test, sbio);
1562 	}
1563 
1564 	SSL_set_bio(con, sbio, sbio);
1565 	SSL_set_accept_state(con);
1566 	/* SSL_set_fd(con,s); */
1567 
1568 	if (s_server_config.debug) {
1569 		SSL_set_debug(con, 1);
1570 		BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
1571 		BIO_set_callback_arg(SSL_get_rbio(con), (char *) bio_s_out);
1572 	}
1573 	if (s_server_config.msg) {
1574 		SSL_set_msg_callback(con, msg_cb);
1575 		SSL_set_msg_callback_arg(con, bio_s_out);
1576 	}
1577 	if (s_server_config.tlsextdebug) {
1578 		SSL_set_tlsext_debug_callback(con, tlsext_cb);
1579 		SSL_set_tlsext_debug_arg(con, bio_s_out);
1580 	}
1581 
1582 	for (;;) {
1583 		int read_from_terminal;
1584 		int read_from_sslcon;
1585 		struct pollfd pfd[2];
1586 		int ptimeout;
1587 
1588 		read_from_terminal = 0;
1589 		read_from_sslcon = SSL_pending(con);
1590 
1591 		if (!read_from_sslcon) {
1592 			pfd[0].fd = fileno(stdin);
1593 			pfd[0].events = POLLIN;
1594 			pfd[1].fd = s;
1595 			pfd[1].events = POLLIN;
1596 
1597 			if ((SSL_version(con) == DTLS1_VERSION) &&
1598 			    DTLSv1_get_timeout(con, &timeout))
1599 				ptimeout = timeout.tv_sec * 1000 +
1600 				    timeout.tv_usec / 1000;
1601 			else
1602 				ptimeout = -1;
1603 
1604 			i = poll(pfd, 2, ptimeout);
1605 
1606 			if ((SSL_version(con) == DTLS1_VERSION) &&
1607 			    DTLSv1_handle_timeout(con) > 0) {
1608 				BIO_printf(bio_err, "TIMEOUT occured\n");
1609 			}
1610 			if (i <= 0)
1611 				continue;
1612 			if (pfd[0].revents) {
1613 				if ((pfd[0].revents & (POLLERR|POLLNVAL)))
1614 					continue;
1615 				read_from_terminal = 1;
1616 			}
1617 			if (pfd[1].revents) {
1618 				if ((pfd[1].revents & (POLLERR|POLLNVAL)))
1619 					continue;
1620 				read_from_sslcon = 1;
1621 			}
1622 		}
1623 		if (read_from_terminal) {
1624 			if (s_server_config.crlf) {
1625 				int j, lf_num;
1626 
1627 				i = read(fileno(stdin), buf, bufsize / 2);
1628 				lf_num = 0;
1629 				/* both loops are skipped when i <= 0 */
1630 				for (j = 0; j < i; j++)
1631 					if (buf[j] == '\n')
1632 						lf_num++;
1633 				for (j = i - 1; j >= 0; j--) {
1634 					buf[j + lf_num] = buf[j];
1635 					if (buf[j] == '\n') {
1636 						lf_num--;
1637 						i++;
1638 						buf[j + lf_num] = '\r';
1639 					}
1640 				}
1641 				assert(lf_num == 0);
1642 			} else
1643 				i = read(fileno(stdin), buf, bufsize);
1644 			if (!s_server_config.quiet) {
1645 				if ((i <= 0) || (buf[0] == 'Q')) {
1646 					BIO_printf(bio_s_out, "DONE\n");
1647 					shutdown(s, SHUT_RD);
1648 					close(s);
1649 					close_accept_socket();
1650 					ret = -11;
1651 					goto err;
1652 				}
1653 				if ((i <= 0) || (buf[0] == 'q')) {
1654 					BIO_printf(bio_s_out, "DONE\n");
1655 					if (SSL_version(con) != DTLS1_VERSION) {
1656 						shutdown(s, SHUT_RD);
1657 						close(s);
1658 					}
1659 					/*
1660 					 * close_accept_socket(); ret= -11;
1661 					 */
1662 					goto err;
1663 				}
1664 				if ((buf[0] == 'r') &&
1665 				    ((buf[1] == '\n') || (buf[1] == '\r'))) {
1666 					SSL_renegotiate(con);
1667 					i = SSL_do_handshake(con);
1668 					printf("SSL_do_handshake -> %d\n", i);
1669 					i = 0;	/* 13; */
1670 					continue;
1671 					/*
1672 					 * RE-NEGOTIATE\n");
1673 					 */
1674 				}
1675 				if ((buf[0] == 'R') &&
1676 				    ((buf[1] == '\n') || (buf[1] == '\r'))) {
1677 					SSL_set_verify(con,
1678 					    SSL_VERIFY_PEER |
1679 					    SSL_VERIFY_CLIENT_ONCE,
1680 					    NULL);
1681 					SSL_renegotiate(con);
1682 					i = SSL_do_handshake(con);
1683 					printf("SSL_do_handshake -> %d\n", i);
1684 					i = 0;	/* 13; */
1685 					continue;
1686 					/*
1687 					 * RE-NEGOTIATE asking for client
1688 					 * cert\n");
1689 					 */
1690 				}
1691 				if (buf[0] == 'P') {
1692 					static const char *str =
1693 					    "Lets print some clear text\n";
1694 					BIO_write(SSL_get_wbio(con), str,
1695 					    strlen(str));
1696 				}
1697 				if (buf[0] == 'S') {
1698 					print_stats(bio_s_out,
1699 					    SSL_get_SSL_CTX(con));
1700 				}
1701 			}
1702 			l = k = 0;
1703 			for (;;) {
1704 				/* should do a select for the write */
1705 #ifdef RENEG
1706 				{
1707 					static count = 0;
1708 					if (++count == 100) {
1709 						count = 0;
1710 						SSL_renegotiate(con);
1711 					}
1712 				}
1713 #endif
1714 				k = SSL_write(con, &(buf[l]), (unsigned int) i);
1715 				switch (SSL_get_error(con, k)) {
1716 				case SSL_ERROR_NONE:
1717 					break;
1718 				case SSL_ERROR_WANT_WRITE:
1719 				case SSL_ERROR_WANT_READ:
1720 				case SSL_ERROR_WANT_X509_LOOKUP:
1721 					BIO_printf(bio_s_out, "Write BLOCK\n");
1722 					break;
1723 				case SSL_ERROR_SYSCALL:
1724 				case SSL_ERROR_SSL:
1725 					BIO_printf(bio_s_out, "ERROR\n");
1726 					ERR_print_errors(bio_err);
1727 					ret = 1;
1728 					goto err;
1729 					/* break; */
1730 				case SSL_ERROR_ZERO_RETURN:
1731 					BIO_printf(bio_s_out, "DONE\n");
1732 					ret = 1;
1733 					goto err;
1734 				}
1735 				if (k <= 0)
1736 					continue;
1737 				l += k;
1738 				i -= k;
1739 				if (i <= 0)
1740 					break;
1741 			}
1742 		}
1743 		if (read_from_sslcon) {
1744 			if (!SSL_is_init_finished(con)) {
1745 				i = init_ssl_connection(con);
1746 
1747 				if (i < 0) {
1748 					ret = 0;
1749 					goto err;
1750 				} else if (i == 0) {
1751 					ret = 1;
1752 					goto err;
1753 				}
1754 			} else {
1755 		again:
1756 				i = SSL_read(con, (char *) buf, bufsize);
1757 				switch (SSL_get_error(con, i)) {
1758 				case SSL_ERROR_NONE: {
1759 						int len, n;
1760 						for (len = 0; len < i;) {
1761 							do {
1762 								n = write(fileno(stdout), buf + len, i - len);
1763 							} while (n == -1 && errno == EINTR);
1764 
1765 							if (n == -1) {
1766 								BIO_printf(bio_s_out, "ERROR\n");
1767 								goto err;
1768 							}
1769 							len += n;
1770 						}
1771 					}
1772 					if (SSL_pending(con))
1773 						goto again;
1774 					break;
1775 				case SSL_ERROR_WANT_WRITE:
1776 				case SSL_ERROR_WANT_READ:
1777 					BIO_printf(bio_s_out, "Read BLOCK\n");
1778 					break;
1779 				case SSL_ERROR_SYSCALL:
1780 				case SSL_ERROR_SSL:
1781 					BIO_printf(bio_s_out, "ERROR\n");
1782 					ERR_print_errors(bio_err);
1783 					ret = 1;
1784 					goto err;
1785 				case SSL_ERROR_ZERO_RETURN:
1786 					BIO_printf(bio_s_out, "DONE\n");
1787 					ret = 1;
1788 					goto err;
1789 				}
1790 			}
1791 		}
1792 	}
1793  err:
1794 	if (con != NULL) {
1795 		BIO_printf(bio_s_out, "shutting down SSL\n");
1796 		SSL_set_shutdown(con,
1797 		    SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
1798 		SSL_free(con);
1799 	}
1800 	BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
1801 	freezero(buf, bufsize);
1802 	if (ret >= 0)
1803 		BIO_printf(bio_s_out, "ACCEPT\n");
1804 	return (ret);
1805 }
1806 
1807 static void
1808 close_accept_socket(void)
1809 {
1810 	BIO_printf(bio_err, "shutdown accept socket\n");
1811 	if (accept_socket >= 0) {
1812 		shutdown(accept_socket, SHUT_RDWR);
1813 		close(accept_socket);
1814 	}
1815 }
1816 
1817 static int
1818 init_ssl_connection(SSL *con)
1819 {
1820 	int i;
1821 	const char *str;
1822 	X509 *peer;
1823 	long verify_error;
1824 	char buf[BUFSIZ];
1825 	unsigned char *exportedkeymat;
1826 
1827 	i = SSL_accept(con);
1828 	if (i <= 0) {
1829 		if (BIO_sock_should_retry(i)) {
1830 			BIO_printf(bio_s_out, "DELAY\n");
1831 			return (1);
1832 		}
1833 		BIO_printf(bio_err, "ERROR\n");
1834 		verify_error = SSL_get_verify_result(con);
1835 		if (verify_error != X509_V_OK) {
1836 			BIO_printf(bio_err, "verify error:%s\n",
1837 			    X509_verify_cert_error_string(verify_error));
1838 		} else
1839 			ERR_print_errors(bio_err);
1840 		return (0);
1841 	}
1842 	PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
1843 
1844 	peer = SSL_get_peer_certificate(con);
1845 	if (peer != NULL) {
1846 		BIO_printf(bio_s_out, "Client certificate\n");
1847 		PEM_write_bio_X509(bio_s_out, peer);
1848 		X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
1849 		BIO_printf(bio_s_out, "subject=%s\n", buf);
1850 		X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
1851 		BIO_printf(bio_s_out, "issuer=%s\n", buf);
1852 		X509_free(peer);
1853 	}
1854 	if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
1855 		BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
1856 	str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
1857 	BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
1858 
1859 #ifndef OPENSSL_NO_SRTP
1860 	{
1861 		SRTP_PROTECTION_PROFILE *srtp_profile
1862 		= SSL_get_selected_srtp_profile(con);
1863 
1864 		if (srtp_profile)
1865 			BIO_printf(bio_s_out,
1866 			    "SRTP Extension negotiated, profile=%s\n",
1867 			    srtp_profile->name);
1868 	}
1869 #endif
1870 	if (SSL_cache_hit(con))
1871 		BIO_printf(bio_s_out, "Reused session-id\n");
1872 	BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
1873 	    SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
1874 	if (s_server_config.keymatexportlabel != NULL) {
1875 		BIO_printf(bio_s_out, "Keying material exporter:\n");
1876 		BIO_printf(bio_s_out, "    Label: '%s'\n",
1877 		    s_server_config.keymatexportlabel);
1878 		BIO_printf(bio_s_out, "    Length: %i bytes\n",
1879 		    s_server_config.keymatexportlen);
1880 		exportedkeymat = malloc(s_server_config.keymatexportlen);
1881 		if (exportedkeymat != NULL) {
1882 			if (!SSL_export_keying_material(con, exportedkeymat,
1883 				s_server_config.keymatexportlen,
1884 				s_server_config.keymatexportlabel,
1885 				strlen(s_server_config.keymatexportlabel),
1886 				NULL, 0, 0)) {
1887 				BIO_printf(bio_s_out, "    Error\n");
1888 			} else {
1889 				BIO_printf(bio_s_out, "    Keying material: ");
1890 				for (i = 0; i < s_server_config.keymatexportlen; i++)
1891 					BIO_printf(bio_s_out, "%02X",
1892 					    exportedkeymat[i]);
1893 				BIO_printf(bio_s_out, "\n");
1894 			}
1895 			free(exportedkeymat);
1896 		}
1897 	}
1898 	return (1);
1899 }
1900 
1901 #ifndef OPENSSL_NO_DH
1902 static DH *
1903 load_dh_param(const char *dhfile)
1904 {
1905 	DH *ret = NULL;
1906 	BIO *bio;
1907 
1908 	if ((bio = BIO_new_file(dhfile, "r")) == NULL)
1909 		goto err;
1910 	ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1911  err:
1912 	BIO_free(bio);
1913 	return (ret);
1914 }
1915 #endif
1916 
1917 static int
1918 www_body(char *hostname, int s, unsigned char *context)
1919 {
1920 	char *buf = NULL;
1921 	int ret = 1;
1922 	int i, j, k, dot;
1923 	SSL *con;
1924 	const SSL_CIPHER *c;
1925 	BIO *io, *ssl_bio, *sbio;
1926 
1927 	buf = malloc(bufsize);
1928 	if (buf == NULL)
1929 		return (0);
1930 	io = BIO_new(BIO_f_buffer());
1931 	ssl_bio = BIO_new(BIO_f_ssl());
1932 	if ((io == NULL) || (ssl_bio == NULL))
1933 		goto err;
1934 
1935 	if (s_server_config.nbio) {
1936 		if (!s_server_config.quiet)
1937 			BIO_printf(bio_err, "turning on non blocking io\n");
1938 		if (!BIO_socket_nbio(s, 1))
1939 			ERR_print_errors(bio_err);
1940 	}
1941 
1942 	/* lets make the output buffer a reasonable size */
1943 	if (!BIO_set_write_buffer_size(io, bufsize))
1944 		goto err;
1945 
1946 	if ((con = SSL_new(ctx)) == NULL)
1947 		goto err;
1948 	if (s_server_config.tlsextdebug) {
1949 		SSL_set_tlsext_debug_callback(con, tlsext_cb);
1950 		SSL_set_tlsext_debug_arg(con, bio_s_out);
1951 	}
1952 	if (context)
1953 		SSL_set_session_id_context(con, context,
1954 		    strlen((char *) context));
1955 
1956 	sbio = BIO_new_socket(s, BIO_NOCLOSE);
1957 	if (s_server_config.nbio_test) {
1958 		BIO *test;
1959 
1960 		test = BIO_new(BIO_f_nbio_test());
1961 		sbio = BIO_push(test, sbio);
1962 	}
1963 	SSL_set_bio(con, sbio, sbio);
1964 	SSL_set_accept_state(con);
1965 
1966 	/* SSL_set_fd(con,s); */
1967 	BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
1968 	BIO_push(io, ssl_bio);
1969 
1970 	if (s_server_config.debug) {
1971 		SSL_set_debug(con, 1);
1972 		BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
1973 		BIO_set_callback_arg(SSL_get_rbio(con), (char *) bio_s_out);
1974 	}
1975 	if (s_server_config.msg) {
1976 		SSL_set_msg_callback(con, msg_cb);
1977 		SSL_set_msg_callback_arg(con, bio_s_out);
1978 	}
1979 	for (;;) {
1980 		i = BIO_gets(io, buf, bufsize - 1);
1981 		if (i < 0) {	/* error */
1982 			if (!BIO_should_retry(io)) {
1983 				if (!s_server_config.quiet)
1984 					ERR_print_errors(bio_err);
1985 				goto err;
1986 			} else {
1987 				if (s_server_config.debug)  {
1988 					BIO_printf(bio_s_out, "read R BLOCK\n");
1989 					sleep(1);
1990 				}
1991 				continue;
1992 			}
1993 		} else if (i == 0) {	/* end of input */
1994 			ret = 1;
1995 			goto end;
1996 		}
1997 		/* else we have data */
1998 		if (((s_server_config.www == 1) &&
1999 		    (strncmp("GET ", buf, 4) == 0)) ||
2000 		    ((s_server_config.www == 2) &&
2001 		    (strncmp("GET /stats ", buf, 11) == 0))) {
2002 			char *p;
2003 			X509 *peer;
2004 			STACK_OF(SSL_CIPHER) *sk;
2005 			static const char *space = "                          ";
2006 
2007 			BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2008 			BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2009 			BIO_puts(io, "<pre>\n");
2010 /*			BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
2011 			BIO_puts(io, "\n");
2012 			for (i = 0; i < local_argc; i++) {
2013 				BIO_puts(io, local_argv[i]);
2014 				BIO_write(io, " ", 1);
2015 			}
2016 			BIO_puts(io, "\n");
2017 
2018 			BIO_printf(io,
2019 			    "Secure Renegotiation IS%s supported\n",
2020 			    SSL_get_secure_renegotiation_support(con) ?
2021 			    "" : " NOT");
2022 
2023 			/*
2024 			 * The following is evil and should not really be
2025 			 * done
2026 			 */
2027 			BIO_printf(io,
2028 			    "Ciphers supported in s_server binary\n");
2029 			sk = SSL_get_ciphers(con);
2030 			j = sk_SSL_CIPHER_num(sk);
2031 			for (i = 0; i < j; i++) {
2032 				c = sk_SSL_CIPHER_value(sk, i);
2033 				BIO_printf(io, "%-11s:%-25s",
2034 				    SSL_CIPHER_get_version(c),
2035 				    SSL_CIPHER_get_name(c));
2036 				if ((((i + 1) % 2) == 0) && (i + 1 != j))
2037 					BIO_puts(io, "\n");
2038 			}
2039 			BIO_puts(io, "\n");
2040 			p = SSL_get_shared_ciphers(con, buf, bufsize);
2041 			if (p != NULL) {
2042 				BIO_printf(io,
2043 				    "---\nCiphers common between both SSL end points:\n");
2044 				j = i = 0;
2045 				while (*p) {
2046 					if (*p == ':') {
2047 						BIO_write(io, space, 26 - j);
2048 						i++;
2049 						j = 0;
2050 						BIO_write(io,
2051 						    ((i % 3) ?  " " : "\n"), 1);
2052 					} else {
2053 						BIO_write(io, p, 1);
2054 						j++;
2055 					}
2056 					p++;
2057 				}
2058 				BIO_puts(io, "\n");
2059 			}
2060 			BIO_printf(io, (SSL_cache_hit(con)
2061 				? "---\nReused, "
2062 				: "---\nNew, "));
2063 			c = SSL_get_current_cipher(con);
2064 			BIO_printf(io, "%s, Cipher is %s\n",
2065 			    SSL_CIPHER_get_version(c),
2066 			    SSL_CIPHER_get_name(c));
2067 			SSL_SESSION_print(io, SSL_get_session(con));
2068 			BIO_printf(io, "---\n");
2069 			print_stats(io, SSL_get_SSL_CTX(con));
2070 			BIO_printf(io, "---\n");
2071 			peer = SSL_get_peer_certificate(con);
2072 			if (peer != NULL) {
2073 				BIO_printf(io, "Client certificate\n");
2074 				X509_print(io, peer);
2075 				PEM_write_bio_X509(io, peer);
2076 			} else
2077 				BIO_puts(io,
2078 				    "no client certificate available\n");
2079 			BIO_puts(io, "</BODY></HTML>\r\n\r\n");
2080 			break;
2081 		} else if ((s_server_config.www == 2 ||
2082 		    s_server_config.www == 3) &&
2083 		    (strncmp("GET /", buf, 5) == 0)) {
2084 			BIO *file;
2085 			char *p, *e;
2086 			static const char *text = "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2087 
2088 			/* skip the '/' */
2089 			p = &(buf[5]);
2090 
2091 			dot = 1;
2092 			for (e = p; *e != '\0'; e++) {
2093 				if (e[0] == ' ')
2094 					break;
2095 
2096 				switch (dot) {
2097 				case 1:
2098 					dot = (e[0] == '.') ? 2 : 0;
2099 					break;
2100 				case 2:
2101 					dot = (e[0] == '.') ? 3 : 0;
2102 					break;
2103 				case 3:
2104 					dot = (e[0] == '/' || e[0] == '\\') ?
2105 					    -1 : 0;
2106 					break;
2107 				}
2108 				if (dot == 0)
2109 					dot = (e[0] == '/' || e[0] == '\\') ?
2110 					    1 : 0;
2111 			}
2112 			dot = (dot == 3) || (dot == -1);  /* filename contains
2113 							   * ".." component */
2114 
2115 			if (*e == '\0') {
2116 				BIO_puts(io, text);
2117 				BIO_printf(io,
2118 				    "'%s' is an invalid file name\r\n", p);
2119 				break;
2120 			}
2121 			*e = '\0';
2122 
2123 			if (dot) {
2124 				BIO_puts(io, text);
2125 				BIO_printf(io,
2126 				    "'%s' contains '..' reference\r\n", p);
2127 				break;
2128 			}
2129 			if (*p == '/') {
2130 				BIO_puts(io, text);
2131 				BIO_printf(io,
2132 				    "'%s' is an invalid path\r\n", p);
2133 				break;
2134 			}
2135 			/* if a directory, do the index thang */
2136 			if (app_isdir(p) > 0) {
2137 				BIO_puts(io, text);
2138 				BIO_printf(io, "'%s' is a directory\r\n", p);
2139 				break;
2140 			}
2141 			if ((file = BIO_new_file(p, "r")) == NULL) {
2142 				BIO_puts(io, text);
2143 				BIO_printf(io, "Error opening '%s'\r\n", p);
2144 				ERR_print_errors(io);
2145 				break;
2146 			}
2147 			if (!s_server_config.quiet)
2148 				BIO_printf(bio_err, "FILE:%s\n", p);
2149 
2150 			if (s_server_config.www == 2) {
2151 				i = strlen(p);
2152 				if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
2153 				    ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
2154 				    ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
2155 					BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2156 				else
2157 					BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2158 			}
2159 			/* send the file */
2160 			for (;;) {
2161 				i = BIO_read(file, buf, bufsize);
2162 				if (i <= 0)
2163 					break;
2164 
2165 #ifdef RENEG
2166 				total_bytes += i;
2167 				fprintf(stderr, "%d\n", i);
2168 				if (total_bytes > 3 * 1024) {
2169 					total_bytes = 0;
2170 					fprintf(stderr, "RENEGOTIATE\n");
2171 					SSL_renegotiate(con);
2172 				}
2173 #endif
2174 
2175 				for (j = 0; j < i;) {
2176 #ifdef RENEG
2177 					{
2178 						static count = 0;
2179 						if (++count == 13) {
2180 							SSL_renegotiate(con);
2181 						}
2182 					}
2183 #endif
2184 					k = BIO_write(io, &(buf[j]), i - j);
2185 					if (k <= 0) {
2186 						if (!BIO_should_retry(io))
2187 							goto write_error;
2188 						else {
2189 							BIO_printf(bio_s_out,
2190 							    "rwrite W BLOCK\n");
2191 						}
2192 					} else {
2193 						j += k;
2194 					}
2195 				}
2196 			}
2197 	write_error:
2198 			BIO_free(file);
2199 			break;
2200 		}
2201 	}
2202 
2203 	for (;;) {
2204 		i = (int) BIO_flush(io);
2205 		if (i <= 0) {
2206 			if (!BIO_should_retry(io))
2207 				break;
2208 		} else
2209 			break;
2210 	}
2211  end:
2212 	/* make sure we re-use sessions */
2213 	SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2214 
2215  err:
2216 
2217 	if (ret >= 0)
2218 		BIO_printf(bio_s_out, "ACCEPT\n");
2219 
2220 	free(buf);
2221 	BIO_free_all(io);
2222 /*	if (ssl_bio != NULL) BIO_free(ssl_bio);*/
2223 	return (ret);
2224 }
2225 
2226 #define MAX_SESSION_ID_ATTEMPTS 10
2227 static int
2228 generate_session_id(const SSL *ssl, unsigned char *id, unsigned int *id_len)
2229 {
2230 	unsigned int count = 0;
2231 	do {
2232 		arc4random_buf(id, *id_len);
2233 		/*
2234 		 * Prefix the session_id with the required prefix. NB: If our
2235 		 * prefix is too long, clip it - but there will be worse
2236 		 * effects anyway, eg. the server could only possibly create
2237 		 * 1 session ID (ie. the prefix!) so all future session
2238 		 * negotiations will fail due to conflicts.
2239 		 */
2240 		memcpy(id, s_server_config.session_id_prefix,
2241 		    (strlen(s_server_config.session_id_prefix) < *id_len) ?
2242 		    strlen(s_server_config.session_id_prefix) : *id_len);
2243 	}
2244 	while (SSL_has_matching_session_id(ssl, id, *id_len) &&
2245 	    (++count < MAX_SESSION_ID_ATTEMPTS));
2246 	if (count >= MAX_SESSION_ID_ATTEMPTS)
2247 		return 0;
2248 	return 1;
2249 }
2250 
2251 static int
2252 ssl_servername_cb(SSL *s, int *ad, void *arg)
2253 {
2254 	tlsextctx *p = (tlsextctx *) arg;
2255 	const char *servername = SSL_get_servername(s,
2256 	    TLSEXT_NAMETYPE_host_name);
2257 
2258 	if (servername && p->biodebug)
2259 		BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
2260 		    servername);
2261 
2262 	if (!p->servername)
2263 		return SSL_TLSEXT_ERR_NOACK;
2264 
2265 	if (servername) {
2266 		if (strcmp(servername, p->servername))
2267 			return p->extension_error;
2268 		if (ctx2) {
2269 			BIO_printf(p->biodebug, "Switching server context.\n");
2270 			SSL_set_SSL_CTX(s, ctx2);
2271 		}
2272 	}
2273 	return SSL_TLSEXT_ERR_OK;
2274 }
2275 
2276 /* Certificate Status callback. This is called when a client includes a
2277  * certificate status request extension.
2278  *
2279  * This is a simplified version. It examines certificates each time and
2280  * makes one OCSP responder query for each request.
2281  *
2282  * A full version would store details such as the OCSP certificate IDs and
2283  * minimise the number of OCSP responses by caching them until they were
2284  * considered "expired".
2285  */
2286 
2287 static int
2288 cert_status_cb(SSL *s, void *arg)
2289 {
2290 	tlsextstatusctx *srctx = arg;
2291 	BIO *err = srctx->err;
2292 	char *host = NULL, *port = NULL, *path = NULL;
2293 	int use_ssl;
2294 	unsigned char *rspder = NULL;
2295 	int rspderlen;
2296 	STACK_OF(OPENSSL_STRING) *aia = NULL;
2297 	X509 *x = NULL;
2298 	X509_STORE_CTX inctx;
2299 	X509_OBJECT obj;
2300 	OCSP_REQUEST *req = NULL;
2301 	OCSP_RESPONSE *resp = NULL;
2302 	OCSP_CERTID *id = NULL;
2303 	STACK_OF(X509_EXTENSION) *exts;
2304 	int ret = SSL_TLSEXT_ERR_NOACK;
2305 	int i;
2306 
2307 	if (srctx->verbose)
2308 		BIO_puts(err, "cert_status: callback called\n");
2309 	/* Build up OCSP query from server certificate */
2310 	x = SSL_get_certificate(s);
2311 	aia = X509_get1_ocsp(x);
2312 	if (aia) {
2313 		if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
2314 			&host, &port, &path, &use_ssl)) {
2315 			BIO_puts(err, "cert_status: can't parse AIA URL\n");
2316 			goto err;
2317 		}
2318 		if (srctx->verbose)
2319 			BIO_printf(err, "cert_status: AIA URL: %s\n",
2320 			    sk_OPENSSL_STRING_value(aia, 0));
2321 	} else {
2322 		if (!srctx->host) {
2323 			BIO_puts(srctx->err,
2324 			    "cert_status: no AIA and no default responder URL\n");
2325 			goto done;
2326 		}
2327 		host = srctx->host;
2328 		path = srctx->path;
2329 		port = srctx->port;
2330 		use_ssl = srctx->use_ssl;
2331 	}
2332 
2333 	if (!X509_STORE_CTX_init(&inctx,
2334 		SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
2335 		NULL, NULL))
2336 		goto err;
2337 	if (X509_STORE_get_by_subject(&inctx, X509_LU_X509,
2338 		X509_get_issuer_name(x), &obj) <= 0) {
2339 		BIO_puts(err,
2340 		    "cert_status: Can't retrieve issuer certificate.\n");
2341 		X509_STORE_CTX_cleanup(&inctx);
2342 		goto done;
2343 	}
2344 	req = OCSP_REQUEST_new();
2345 	if (!req)
2346 		goto err;
2347 	id = OCSP_cert_to_id(NULL, x, obj.data.x509);
2348 	X509_free(obj.data.x509);
2349 	X509_STORE_CTX_cleanup(&inctx);
2350 	if (!id)
2351 		goto err;
2352 	if (!OCSP_request_add0_id(req, id))
2353 		goto err;
2354 	id = NULL;
2355 	/* Add any extensions to the request */
2356 	SSL_get_tlsext_status_exts(s, &exts);
2357 	for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
2358 		X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
2359 		if (!OCSP_REQUEST_add_ext(req, ext, -1))
2360 			goto err;
2361 	}
2362 	resp = process_responder(err, req, host, path, port, use_ssl, NULL,
2363 	    srctx->timeout);
2364 	if (!resp) {
2365 		BIO_puts(err, "cert_status: error querying responder\n");
2366 		goto done;
2367 	}
2368 	rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
2369 	if (rspderlen <= 0)
2370 		goto err;
2371 	SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
2372 	if (srctx->verbose) {
2373 		BIO_puts(err, "cert_status: ocsp response sent:\n");
2374 		OCSP_RESPONSE_print(err, resp, 2);
2375 	}
2376 	ret = SSL_TLSEXT_ERR_OK;
2377  done:
2378 	if (ret != SSL_TLSEXT_ERR_OK)
2379 		ERR_print_errors(err);
2380 	if (aia) {
2381 		free(host);
2382 		free(path);
2383 		free(port);
2384 		X509_email_free(aia);
2385 	}
2386 	if (id)
2387 		OCSP_CERTID_free(id);
2388 	if (req)
2389 		OCSP_REQUEST_free(req);
2390 	if (resp)
2391 		OCSP_RESPONSE_free(resp);
2392 	return ret;
2393  err:
2394 	ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2395 	goto done;
2396 }
2397 
2398 static int
2399 alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
2400     const unsigned char *in, unsigned int inlen, void *arg)
2401 {
2402 	tlsextalpnctx *alpn_ctx = arg;
2403 
2404 	if (!s_server_config.quiet) {
2405 		/* We can assume that in is syntactically valid. */
2406 		unsigned i;
2407 
2408 		BIO_printf(bio_s_out,
2409 		    "ALPN protocols advertised by the client: ");
2410 		for (i = 0; i < inlen; ) {
2411 			if (i)
2412 				BIO_write(bio_s_out, ", ", 2);
2413 			BIO_write(bio_s_out, &in[i + 1], in[i]);
2414 			i += in[i] + 1;
2415 		}
2416 		BIO_write(bio_s_out, "\n", 1);
2417 	}
2418 
2419 	if (SSL_select_next_proto((unsigned char**)out, outlen, alpn_ctx->data,
2420 	    alpn_ctx->len, in, inlen) != OPENSSL_NPN_NEGOTIATED)
2421 		return (SSL_TLSEXT_ERR_NOACK);
2422 
2423 	if (!s_server_config.quiet) {
2424 		BIO_printf(bio_s_out, "ALPN protocols selected: ");
2425 		BIO_write(bio_s_out, *out, *outlen);
2426 		BIO_write(bio_s_out, "\n", 1);
2427 	}
2428 
2429 	return (SSL_TLSEXT_ERR_OK);
2430 }
2431