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