ba88bd702a817177d530d6c52e597891e998c94c
[openssl.git] / apps / s_server.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECC cipher suite support in OpenSSL originally developed by
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
114  */
115 /* ====================================================================
116  * Copyright 2005 Nokia. All rights reserved.
117  *
118  * The portions of the attached software ("Contribution") is developed by
119  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
120  * license.
121  *
122  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
123  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
124  * support (see RFC 4279) to OpenSSL.
125  *
126  * No patent licenses or other rights except those expressly stated in
127  * the OpenSSL open source license shall be deemed granted or received
128  * expressly, by implication, estoppel, or otherwise.
129  *
130  * No assurances are provided by Nokia that the Contribution does not
131  * infringe the patent or other intellectual property rights of any third
132  * party or that the license provides you with all the necessary rights
133  * to make use of the Contribution.
134  *
135  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
136  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
137  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
138  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
139  * OTHERWISE.
140  */
141
142 #include <ctype.h>
143 #include <stdio.h>
144 #include <stdlib.h>
145 #include <string.h>
146 #include <openssl/async.h>
147
148 #include <openssl/e_os2.h>
149
150 /* conflicts with winsock2 stuff on netware */
151 #if !defined(OPENSSL_SYS_NETWARE)
152 # include <sys/types.h>
153 #endif
154
155 /*
156  * With IPv6, it looks like Digital has mixed up the proper order of
157  * recursive header file inclusion, resulting in the compiler complaining
158  * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
159  * needed to have fileno() declared correctly...  So let's define u_int
160  */
161 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
162 # define __U_INT
163 typedef unsigned int u_int;
164 #endif
165
166 #include <openssl/lhash.h>
167 #include <openssl/bn.h>
168 #define USE_SOCKETS
169 #include "apps.h"
170 #include <openssl/err.h>
171 #include <openssl/pem.h>
172 #include <openssl/x509.h>
173 #include <openssl/ssl.h>
174 #include <openssl/rand.h>
175 #include <openssl/ocsp.h>
176 #ifndef OPENSSL_NO_DH
177 # include <openssl/dh.h>
178 #endif
179 #ifndef OPENSSL_NO_RSA
180 # include <openssl/rsa.h>
181 #endif
182 #ifndef OPENSSL_NO_SRP
183 # include <openssl/srp.h>
184 #endif
185 #include "s_apps.h"
186 #include "timeouts.h"
187
188 #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
189 /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
190 # undef FIONBIO
191 #endif
192
193 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
194 static int sv_body(char *hostname, int s, int stype, unsigned char *context);
195 static int www_body(char *hostname, int s, int stype, unsigned char *context);
196 static int rev_body(char *hostname, int s, int stype, unsigned char *context);
197 static void close_accept_socket(void);
198 static int init_ssl_connection(SSL *s);
199 static void print_stats(BIO *bp, SSL_CTX *ctx);
200 static int generate_session_id(const SSL *ssl, unsigned char *id,
201                                unsigned int *id_len);
202 static void init_session_cache_ctx(SSL_CTX *sctx);
203 static void free_sessions(void);
204 #ifndef OPENSSL_NO_DH
205 static DH *load_dh_param(const char *dhfile);
206 #endif
207
208 static void s_server_init(void);
209
210 /* static int load_CA(SSL_CTX *ctx, char *file);*/
211
212 #undef BUFSIZZ
213 #define BUFSIZZ 16*1024
214 static int bufsize = BUFSIZZ;
215 static int accept_socket = -1;
216
217 #define TEST_CERT       "server.pem"
218 #define TEST_CERT2      "server2.pem"
219
220 extern int verify_depth, verify_return_error, verify_quiet;
221
222 static int s_server_verify = SSL_VERIFY_NONE;
223 static int s_server_session_id_context = 1; /* anything will do */
224 static const char *s_cert_file = TEST_CERT, *s_key_file =
225     NULL, *s_chain_file = NULL;
226
227 static const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
228 static char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
229 #ifdef FIONBIO
230 static int s_nbio = 0;
231 #endif
232 static int s_nbio_test = 0;
233 static int s_crlf = 0;
234 static SSL_CTX *ctx = NULL;
235 static SSL_CTX *ctx2 = NULL;
236 static int www = 0;
237
238 static BIO *bio_s_out = NULL;
239 static BIO *bio_s_msg = NULL;
240 static int s_debug = 0;
241 static int s_tlsextdebug = 0;
242 static int s_tlsextstatus = 0;
243 static int cert_status_cb(SSL *s, void *arg);
244 static int no_resume_ephemeral = 0;
245 static int s_msg = 0;
246 static int s_quiet = 0;
247 static int s_ign_eof = 0;
248 static int s_brief = 0;
249
250 static char *keymatexportlabel = NULL;
251 static int keymatexportlen = 20;
252
253 static int async = 0;
254
255 #ifndef OPENSSL_NO_ENGINE
256 static char *engine_id = NULL;
257 #endif
258 static const char *session_id_prefix = NULL;
259
260 static int enable_timeouts = 0;
261 static long socket_mtu;
262 #ifndef OPENSSL_NO_DTLS
263 static int cert_chain = 0;
264 #endif
265 static int dtlslisten = 0;
266
267 static BIO *serverinfo_in = NULL;
268 static const char *s_serverinfo_file = NULL;
269
270 #ifndef OPENSSL_NO_PSK
271 static char *psk_identity = "Client_identity";
272 char *psk_key = NULL;           /* by default PSK is not used */
273
274 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
275                                   unsigned char *psk,
276                                   unsigned int max_psk_len)
277 {
278     unsigned int psk_len = 0;
279     int ret;
280     BIGNUM *bn = NULL;
281
282     if (s_debug)
283         BIO_printf(bio_s_out, "psk_server_cb\n");
284     if (!identity) {
285         BIO_printf(bio_err, "Error: client did not send PSK identity\n");
286         goto out_err;
287     }
288     if (s_debug)
289         BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
290                    (int)strlen(identity), identity);
291
292     /* here we could lookup the given identity e.g. from a database */
293     if (strcmp(identity, psk_identity) != 0) {
294         BIO_printf(bio_s_out, "PSK error: client identity not found"
295                    " (got '%s' expected '%s')\n", identity, psk_identity);
296         goto out_err;
297     }
298     if (s_debug)
299         BIO_printf(bio_s_out, "PSK client identity found\n");
300
301     /* convert the PSK key to binary */
302     ret = BN_hex2bn(&bn, psk_key);
303     if (!ret) {
304         BIO_printf(bio_err, "Could not convert PSK key '%s' to BIGNUM\n",
305                    psk_key);
306         BN_free(bn);
307         return 0;
308     }
309     if (BN_num_bytes(bn) > (int)max_psk_len) {
310         BIO_printf(bio_err,
311                    "psk buffer of callback is too small (%d) for key (%d)\n",
312                    max_psk_len, BN_num_bytes(bn));
313         BN_free(bn);
314         return 0;
315     }
316
317     ret = BN_bn2bin(bn, psk);
318     BN_free(bn);
319
320     if (ret < 0)
321         goto out_err;
322     psk_len = (unsigned int)ret;
323
324     if (s_debug)
325         BIO_printf(bio_s_out, "fetched PSK len=%d\n", psk_len);
326     return psk_len;
327  out_err:
328     if (s_debug)
329         BIO_printf(bio_err, "Error in PSK server callback\n");
330     (void)BIO_flush(bio_err);
331     (void)BIO_flush(bio_s_out);
332     return 0;
333 }
334 #endif
335
336 #ifndef OPENSSL_NO_SRP
337 /* This is a context that we pass to callbacks */
338 typedef struct srpsrvparm_st {
339     char *login;
340     SRP_VBASE *vb;
341     SRP_user_pwd *user;
342 } srpsrvparm;
343
344 /*
345  * This callback pretends to require some asynchronous logic in order to
346  * obtain a verifier. When the callback is called for a new connection we
347  * return with a negative value. This will provoke the accept etc to return
348  * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
349  * (which would normally occur after a worker has finished) and we set the
350  * user parameters.
351  */
352 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
353 {
354     srpsrvparm *p = (srpsrvparm *) arg;
355     if (p->login == NULL && p->user == NULL) {
356         p->login = SSL_get_srp_username(s);
357         BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
358         return (-1);
359     }
360
361     if (p->user == NULL) {
362         BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
363         return SSL3_AL_FATAL;
364     }
365     if (SSL_set_srp_server_param
366         (s, p->user->N, p->user->g, p->user->s, p->user->v,
367          p->user->info) < 0) {
368         *ad = SSL_AD_INTERNAL_ERROR;
369         return SSL3_AL_FATAL;
370     }
371     BIO_printf(bio_err,
372                "SRP parameters set: username = \"%s\" info=\"%s\" \n",
373                p->login, p->user->info);
374     /* need to check whether there are memory leaks */
375     p->user = NULL;
376     p->login = NULL;
377     return SSL_ERROR_NONE;
378 }
379
380 #endif
381
382 static void s_server_init(void)
383 {
384     accept_socket = -1;
385     verify_depth = 0;
386     s_server_verify = SSL_VERIFY_NONE;
387     s_dcert_file = NULL;
388     s_dkey_file = NULL;
389     s_dchain_file = NULL;
390     s_cert_file = TEST_CERT;
391     s_key_file = NULL;
392     s_chain_file = NULL;
393     s_cert_file2 = TEST_CERT2;
394     s_key_file2 = NULL;
395     ctx2 = NULL;
396     s_nbio = 0;
397     s_nbio_test = 0;
398     ctx = NULL;
399     www = 0;
400     bio_s_out = NULL;
401     s_debug = 0;
402     s_msg = 0;
403     s_quiet = 0;
404     s_brief = 0;
405     async = 0;
406 #ifndef OPENSSL_NO_ENGINE
407     engine_id = NULL;
408 #endif
409 }
410
411 static int local_argc = 0;
412 static char **local_argv;
413
414 #ifdef CHARSET_EBCDIC
415 static int ebcdic_new(BIO *bi);
416 static int ebcdic_free(BIO *a);
417 static int ebcdic_read(BIO *b, char *out, int outl);
418 static int ebcdic_write(BIO *b, const char *in, int inl);
419 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
420 static int ebcdic_gets(BIO *bp, char *buf, int size);
421 static int ebcdic_puts(BIO *bp, const char *str);
422
423 # define BIO_TYPE_EBCDIC_FILTER  (18|0x0200)
424 static BIO_METHOD methods_ebcdic = {
425     BIO_TYPE_EBCDIC_FILTER,
426     "EBCDIC/ASCII filter",
427     ebcdic_write,
428     ebcdic_read,
429     ebcdic_puts,
430     ebcdic_gets,
431     ebcdic_ctrl,
432     ebcdic_new,
433     ebcdic_free,
434 };
435
436 /* This struct is "unwarranted chumminess with the compiler." */
437 typedef struct {
438     size_t alloced;
439     char buff[1];
440 } EBCDIC_OUTBUFF;
441
442 BIO_METHOD *BIO_f_ebcdic_filter()
443 {
444     return (&methods_ebcdic);
445 }
446
447 static int ebcdic_new(BIO *bi)
448 {
449     EBCDIC_OUTBUFF *wbuf;
450
451     wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
452     wbuf->alloced = 1024;
453     wbuf->buff[0] = '\0';
454
455     bi->ptr = (char *)wbuf;
456     bi->init = 1;
457     bi->flags = 0;
458     return (1);
459 }
460
461 static int ebcdic_free(BIO *a)
462 {
463     if (a == NULL)
464         return (0);
465     OPENSSL_free(a->ptr);
466     a->ptr = NULL;
467     a->init = 0;
468     a->flags = 0;
469     return (1);
470 }
471
472 static int ebcdic_read(BIO *b, char *out, int outl)
473 {
474     int ret = 0;
475
476     if (out == NULL || outl == 0)
477         return (0);
478     if (b->next_bio == NULL)
479         return (0);
480
481     ret = BIO_read(b->next_bio, out, outl);
482     if (ret > 0)
483         ascii2ebcdic(out, out, ret);
484     return (ret);
485 }
486
487 static int ebcdic_write(BIO *b, const char *in, int inl)
488 {
489     EBCDIC_OUTBUFF *wbuf;
490     int ret = 0;
491     int num;
492     unsigned char n;
493
494     if ((in == NULL) || (inl <= 0))
495         return (0);
496     if (b->next_bio == NULL)
497         return (0);
498
499     wbuf = (EBCDIC_OUTBUFF *) b->ptr;
500
501     if (inl > (num = wbuf->alloced)) {
502         num = num + num;        /* double the size */
503         if (num < inl)
504             num = inl;
505         wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
506         OPENSSL_free(b->ptr);
507
508         wbuf->alloced = num;
509         wbuf->buff[0] = '\0';
510
511         b->ptr = (char *)wbuf;
512     }
513
514     ebcdic2ascii(wbuf->buff, in, inl);
515
516     ret = BIO_write(b->next_bio, wbuf->buff, inl);
517
518     return (ret);
519 }
520
521 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
522 {
523     long ret;
524
525     if (b->next_bio == NULL)
526         return (0);
527     switch (cmd) {
528     case BIO_CTRL_DUP:
529         ret = 0L;
530         break;
531     default:
532         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
533         break;
534     }
535     return (ret);
536 }
537
538 static int ebcdic_gets(BIO *bp, char *buf, int size)
539 {
540     int i, ret = 0;
541     if (bp->next_bio == NULL)
542         return (0);
543 /*      return(BIO_gets(bp->next_bio,buf,size));*/
544     for (i = 0; i < size - 1; ++i) {
545         ret = ebcdic_read(bp, &buf[i], 1);
546         if (ret <= 0)
547             break;
548         else if (buf[i] == '\n') {
549             ++i;
550             break;
551         }
552     }
553     if (i < size)
554         buf[i] = '\0';
555     return (ret < 0 && i == 0) ? ret : i;
556 }
557
558 static int ebcdic_puts(BIO *bp, const char *str)
559 {
560     if (bp->next_bio == NULL)
561         return (0);
562     return ebcdic_write(bp, str, strlen(str));
563 }
564 #endif
565
566 /* This is a context that we pass to callbacks */
567 typedef struct tlsextctx_st {
568     char *servername;
569     BIO *biodebug;
570     int extension_error;
571 } tlsextctx;
572
573 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
574 {
575     tlsextctx *p = (tlsextctx *) arg;
576     const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
577     if (servername && p->biodebug)
578         BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
579                    servername);
580
581     if (!p->servername)
582         return SSL_TLSEXT_ERR_NOACK;
583
584     if (servername) {
585         if (strcasecmp(servername, p->servername))
586             return p->extension_error;
587         if (ctx2) {
588             BIO_printf(p->biodebug, "Switching server context.\n");
589             SSL_set_SSL_CTX(s, ctx2);
590         }
591     }
592     return SSL_TLSEXT_ERR_OK;
593 }
594
595 /* Structure passed to cert status callback */
596
597 typedef struct tlsextstatusctx_st {
598     /* Default responder to use */
599     char *host, *path, *port;
600     int use_ssl;
601     int timeout;
602     int verbose;
603 } tlsextstatusctx;
604
605 static tlsextstatusctx tlscstatp = { NULL, NULL, NULL, 0, -1, 0 };
606
607 /*
608  * Certificate Status callback. This is called when a client includes a
609  * certificate status request extension. This is a simplified version. It
610  * examines certificates each time and makes one OCSP responder query for
611  * each request. A full version would store details such as the OCSP
612  * certificate IDs and minimise the number of OCSP responses by caching them
613  * until they were considered "expired".
614  */
615
616 static int cert_status_cb(SSL *s, void *arg)
617 {
618     tlsextstatusctx *srctx = arg;
619     char *host = NULL, *port = NULL, *path = NULL;
620     int use_ssl;
621     unsigned char *rspder = NULL;
622     int rspderlen;
623     STACK_OF(OPENSSL_STRING) *aia = NULL;
624     X509 *x = NULL;
625     X509_STORE_CTX inctx;
626     X509_OBJECT obj;
627     OCSP_REQUEST *req = NULL;
628     OCSP_RESPONSE *resp = NULL;
629     OCSP_CERTID *id = NULL;
630     STACK_OF(X509_EXTENSION) *exts;
631     int ret = SSL_TLSEXT_ERR_NOACK;
632     int i;
633
634     if (srctx->verbose)
635         BIO_puts(bio_err, "cert_status: callback called\n");
636     /* Build up OCSP query from server certificate */
637     x = SSL_get_certificate(s);
638     aia = X509_get1_ocsp(x);
639     if (aia) {
640         if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
641                             &host, &port, &path, &use_ssl)) {
642             BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
643             goto err;
644         }
645         if (srctx->verbose)
646             BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
647                        sk_OPENSSL_STRING_value(aia, 0));
648     } else {
649         if (!srctx->host) {
650             BIO_puts(bio_err,
651                      "cert_status: no AIA and no default responder URL\n");
652             goto done;
653         }
654         host = srctx->host;
655         path = srctx->path;
656         port = srctx->port;
657         use_ssl = srctx->use_ssl;
658     }
659
660     if (!X509_STORE_CTX_init(&inctx,
661                              SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
662                              NULL, NULL))
663         goto err;
664     if (X509_STORE_get_by_subject(&inctx, X509_LU_X509,
665                                   X509_get_issuer_name(x), &obj) <= 0) {
666         BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
667         X509_STORE_CTX_cleanup(&inctx);
668         goto done;
669     }
670     req = OCSP_REQUEST_new();
671     if (req == NULL)
672         goto err;
673     id = OCSP_cert_to_id(NULL, x, obj.data.x509);
674     X509_free(obj.data.x509);
675     X509_STORE_CTX_cleanup(&inctx);
676     if (!id)
677         goto err;
678     if (!OCSP_request_add0_id(req, id))
679         goto err;
680     id = NULL;
681     /* Add any extensions to the request */
682     SSL_get_tlsext_status_exts(s, &exts);
683     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
684         X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
685         if (!OCSP_REQUEST_add_ext(req, ext, -1))
686             goto err;
687     }
688     resp = process_responder(req, host, path, port, use_ssl, NULL,
689                              srctx->timeout);
690     if (!resp) {
691         BIO_puts(bio_err, "cert_status: error querying responder\n");
692         goto done;
693     }
694     rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
695     if (rspderlen <= 0)
696         goto err;
697     SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
698     if (srctx->verbose) {
699         BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
700         OCSP_RESPONSE_print(bio_err, resp, 2);
701     }
702     ret = SSL_TLSEXT_ERR_OK;
703  done:
704     if (ret != SSL_TLSEXT_ERR_OK)
705         ERR_print_errors(bio_err);
706     if (aia) {
707         OPENSSL_free(host);
708         OPENSSL_free(path);
709         OPENSSL_free(port);
710         X509_email_free(aia);
711     }
712     OCSP_CERTID_free(id);
713     OCSP_REQUEST_free(req);
714     OCSP_RESPONSE_free(resp);
715     return ret;
716  err:
717     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
718     goto done;
719 }
720
721 #ifndef OPENSSL_NO_NEXTPROTONEG
722 /* This is the context that we pass to next_proto_cb */
723 typedef struct tlsextnextprotoctx_st {
724     unsigned char *data;
725     unsigned int len;
726 } tlsextnextprotoctx;
727
728 static int next_proto_cb(SSL *s, const unsigned char **data,
729                          unsigned int *len, void *arg)
730 {
731     tlsextnextprotoctx *next_proto = arg;
732
733     *data = next_proto->data;
734     *len = next_proto->len;
735
736     return SSL_TLSEXT_ERR_OK;
737 }
738 #endif                         /* ndef OPENSSL_NO_NEXTPROTONEG */
739
740 /* This the context that we pass to alpn_cb */
741 typedef struct tlsextalpnctx_st {
742     unsigned char *data;
743     unsigned short len;
744 } tlsextalpnctx;
745
746 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
747                    const unsigned char *in, unsigned int inlen, void *arg)
748 {
749     tlsextalpnctx *alpn_ctx = arg;
750
751     if (!s_quiet) {
752         /* We can assume that |in| is syntactically valid. */
753         unsigned i;
754         BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
755         for (i = 0; i < inlen;) {
756             if (i)
757                 BIO_write(bio_s_out, ", ", 2);
758             BIO_write(bio_s_out, &in[i + 1], in[i]);
759             i += in[i] + 1;
760         }
761         BIO_write(bio_s_out, "\n", 1);
762     }
763
764     if (SSL_select_next_proto
765         ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
766          inlen) != OPENSSL_NPN_NEGOTIATED) {
767         return SSL_TLSEXT_ERR_NOACK;
768     }
769
770     if (!s_quiet) {
771         BIO_printf(bio_s_out, "ALPN protocols selected: ");
772         BIO_write(bio_s_out, *out, *outlen);
773         BIO_write(bio_s_out, "\n", 1);
774     }
775
776     return SSL_TLSEXT_ERR_OK;
777 }
778
779 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
780 {
781     /* disable resumption for sessions with forward secure ciphers */
782     return is_forward_secure;
783 }
784
785 static char *jpake_secret = NULL;
786 #ifndef OPENSSL_NO_SRP
787 static srpsrvparm srp_callback_parm;
788 #endif
789 #ifndef OPENSSL_NO_SRTP
790 static char *srtp_profiles = NULL;
791 #endif
792
793 typedef enum OPTION_choice {
794     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
795     OPT_ENGINE, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
796     OPT_VERIFY, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
797     OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
798     OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
799     OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
800     OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
801     OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
802     OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
803     OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
804     OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
805     OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_MSG, OPT_MSGFILE, OPT_TRACE,
806     OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF,
807     OPT_QUIET, OPT_BRIEF, OPT_NO_DHE, OPT_NO_ECDHE,
808     OPT_NO_RESUME_EPHEMERAL, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
809     OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC,
810     OPT_SSL3,
811     OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
812     OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_CHAIN, OPT_LISTEN,
813     OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
814     OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_JPAKE,
815     OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
816     OPT_S_ENUM,
817     OPT_V_ENUM,
818     OPT_X_ENUM
819 } OPTION_CHOICE;
820
821 OPTIONS s_server_options[] = {
822     {"help", OPT_HELP, '-', "Display this summary"},
823     {"port", OPT_PORT, 'p'},
824     {"accept", OPT_PORT, 'p',
825      "TCP/IP port to accept on (default is " PORT_STR ")"},
826     {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
827     {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
828     {"context", OPT_CONTEXT, 's', "Set session ID context"},
829     {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
830     {"Verify", OPT_UPPER_V_VERIFY, 'n',
831      "Turn on peer certificate verification, must have a cert"},
832     {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
833     {"naccept", OPT_NACCEPT, 'p', "Terminate after pnum connections"},
834     {"serverinfo", OPT_SERVERINFO, 's',
835      "PEM serverinfo file for certificate"},
836     {"certform", OPT_CERTFORM, 'F',
837      "Certificate format (PEM or DER) PEM default"},
838     {"key", OPT_KEY, '<',
839      "Private Key if not in -cert; default is " TEST_CERT},
840     {"keyform", OPT_KEYFORM, 'f',
841      "Key format (PEM, DER or ENGINE) PEM default"},
842     {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
843     {"dcert", OPT_DCERT, '<',
844      "Second certificate file to use (usually for DSA)"},
845     {"dcertform", OPT_DCERTFORM, 'F',
846      "Second certificate format (PEM or DER) PEM default"},
847     {"dkey", OPT_DKEY, '<',
848      "Second private key file to use (usually for DSA)"},
849     {"dkeyform", OPT_DKEYFORM, 'F',
850      "Second key format (PEM, DER or ENGINE) PEM default"},
851     {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
852     {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
853     {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
854     {"debug", OPT_DEBUG, '-', "Print more output"},
855     {"msg", OPT_MSG, '-', "Show protocol messages"},
856     {"msgfile", OPT_MSGFILE, '>'},
857     {"state", OPT_STATE, '-', "Print the SSL states"},
858     {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
859     {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
860     {"no-CAfile", OPT_NOCAFILE, '-',
861      "Do not load the default certificates file"},
862     {"no-CApath", OPT_NOCAPATH, '-',
863      "Do not load certificates from the default certificates directory"},
864     {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
865     {"quiet", OPT_QUIET, '-', "No server output"},
866     {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
867     {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
868     {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
869     {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
870      "Disable caching and tickets if ephemeral (EC)DH is used"},
871     {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
872     {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
873     {"servername", OPT_SERVERNAME, 's',
874      "Servername for HostName TLS extension"},
875     {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
876      "mismatch send fatal alert (default warning alert)"},
877     {"cert2", OPT_CERT2, '<',
878      "Certificate file to use for servername; default is" TEST_CERT2},
879     {"key2", OPT_KEY2, '<',
880      "-Private Key file to use for servername if not in -cert2"},
881     {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
882      "Hex dump of all TLS extensions received"},
883     {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path incluedes HTTP headers"},
884     {"id_prefix", OPT_ID_PREFIX, 's',
885      "Generate SSL/TLS session IDs prefixed by arg"},
886     {"rand", OPT_RAND, 's',
887      "Load the file(s) into the random number generator"},
888     {"keymatexport", OPT_KEYMATEXPORT, 's',
889      "Export keying material using label"},
890     {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
891      "Export len bytes of keying material (default 20)"},
892     {"CRL", OPT_CRL, '<'},
893     {"crl_download", OPT_CRL_DOWNLOAD, '-'},
894     {"cert_chain", OPT_CERT_CHAIN, '<'},
895     {"dcert_chain", OPT_DCERT_CHAIN, '<'},
896     {"chainCApath", OPT_CHAINCAPATH, '/'},
897     {"verifyCApath", OPT_VERIFYCAPATH, '/'},
898     {"no_cache", OPT_NO_CACHE, '-'},
899     {"ext_cache", OPT_EXT_CACHE, '-'},
900     {"CRLform", OPT_CRLFORM, 'F'},
901     {"verify_return_error", OPT_VERIFY_RET_ERROR, '-'},
902     {"verify_quiet", OPT_VERIFY_QUIET, '-'},
903     {"build_chain", OPT_BUILD_CHAIN, '-'},
904     {"chainCAfile", OPT_CHAINCAFILE, '<'},
905     {"verifyCAfile", OPT_VERIFYCAFILE, '<'},
906     {"ign_eof", OPT_IGN_EOF, '-'},
907     {"no_ign_eof", OPT_NO_IGN_EOF, '-'},
908     {"status", OPT_STATUS, '-'},
909     {"status_verbose", OPT_STATUS_VERBOSE, '-'},
910     {"status_timeout", OPT_STATUS_TIMEOUT, 'n'},
911     {"status_url", OPT_STATUS_URL, 's'},
912     {"trace", OPT_TRACE, '-'},
913     {"security_debug", OPT_SECURITY_DEBUG, '-'},
914     {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-'},
915     {"brief", OPT_BRIEF, '-'},
916     {"rev", OPT_REV, '-'},
917     {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
918     OPT_S_OPTIONS,
919     OPT_V_OPTIONS,
920     OPT_X_OPTIONS,
921 #ifdef FIONBIO
922     {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
923 #endif
924 #ifndef OPENSSL_NO_PSK
925     {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
926     {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
927 # ifndef OPENSSL_NO_JPAKE
928     {"jpake", OPT_JPAKE, 's', "JPAKE secret to use"},
929 # endif
930 #endif
931 #ifndef OPENSSL_NO_SRP
932     {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
933     {"srpuserseed", OPT_SRPUSERSEED, 's',
934      "A seed string for a default user salt"},
935 #endif
936 #ifndef OPENSSL_NO_SSL3
937     {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
938 #endif
939 #ifndef OPENSSL_NO_DTLS
940     {"dtls", OPT_DTLS, '-'},
941     {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
942     {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
943     {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
944     {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
945     {"chain", OPT_CHAIN, '-', "Read a certificate chain"},
946     {"listen", OPT_LISTEN, '-',
947      "Listen for a DTLS ClientHello with a cookie and then connect"},
948 #endif
949 #ifndef OPENSSL_NO_DH
950     {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
951 #endif
952 #ifndef OPENSSL_NO_EC
953     {"no_ecdhe", OPT_NO_ECDHE, '-', "Disable ephemeral ECDH"},
954 #endif
955 #ifndef OPENSSL_NO_NEXTPROTONEG
956     {"nextprotoneg", OPT_NEXTPROTONEG, 's',
957      "Set the advertised protocols for the NPN extension (comma-separated list)"},
958 #endif
959 #ifndef OPENSSL_NO_SRTP
960     {"use_srtp", OPT_SRTP_PROFILES, 's',
961      "Offer SRTP key management with a colon-separated profile list"},
962     {"alpn", OPT_ALPN, 's',
963      "Set the advertised protocols for the ALPN extension (comma-separated list)"},
964 #endif
965 #ifndef OPENSSL_NO_ENGINE
966     {"engine", OPT_ENGINE, 's'},
967 #endif
968     {NULL}
969 };
970
971 int s_server_main(int argc, char *argv[])
972 {
973     ENGINE *e = NULL;
974     EVP_PKEY *s_key = NULL, *s_dkey = NULL;
975     SSL_CONF_CTX *cctx = NULL;
976     const SSL_METHOD *meth = TLS_server_method();
977     SSL_EXCERT *exc = NULL;
978     STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
979     STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
980     STACK_OF(X509_CRL) *crls = NULL;
981     X509 *s_cert = NULL, *s_dcert = NULL;
982     X509_VERIFY_PARAM *vpm = NULL;
983     char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
984 #ifndef OPENSSL_NO_DH
985     char *dhfile = NULL;
986 #endif
987     char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
988     char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
989     char *crl_file = NULL, *prog;
990 #ifndef OPENSSL_NO_PSK
991     char *p;
992 #endif
993     const char *unix_path = NULL;
994 #ifndef NO_SYS_UN_H
995     int unlink_unix_path = 0;
996 #endif
997     int (*server_cb) (char *hostname, int s, int stype,
998                       unsigned char *context);
999     int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
1000 #ifndef OPENSSL_NO_DH
1001     int no_dhe = 0;
1002 #endif
1003     int no_ecdhe = 0, nocert = 0, ret = 1;
1004     int noCApath = 0, noCAfile = 0;
1005     int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
1006     int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
1007     int rev = 0, naccept = -1, sdebug = 0, socket_type = SOCK_STREAM;
1008     int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
1009     unsigned short port = PORT;
1010     unsigned char *context = NULL;
1011     OPTION_CHOICE o;
1012     EVP_PKEY *s_key2 = NULL;
1013     X509 *s_cert2 = NULL;
1014     tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
1015 #ifndef OPENSSL_NO_NEXTPROTONEG
1016     const char *next_proto_neg_in = NULL;
1017     tlsextnextprotoctx next_proto = { NULL, 0 };
1018 #endif
1019     const char *alpn_in = NULL;
1020     tlsextalpnctx alpn_ctx = { NULL, 0 };
1021 #ifndef OPENSSL_NO_PSK
1022     /* by default do not send a PSK identity hint */
1023     static char *psk_identity_hint = NULL;
1024 #endif
1025 #ifndef OPENSSL_NO_SRP
1026     char *srpuserseed = NULL;
1027     char *srp_verifier_file = NULL;
1028 #endif
1029
1030     local_argc = argc;
1031     local_argv = argv;
1032
1033     s_server_init();
1034     cctx = SSL_CONF_CTX_new();
1035     vpm = X509_VERIFY_PARAM_new();
1036     if (cctx == NULL || vpm == NULL)
1037         goto end;
1038     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1039
1040     prog = opt_init(argc, argv, s_server_options);
1041     while ((o = opt_next()) != OPT_EOF) {
1042         switch (o) {
1043 #ifdef OPENSSL_NO_PSK
1044         case OPT_PSK_HINT:
1045         case OPT_PSK:
1046 #endif
1047 #ifdef OPENSSL_NO_DTLS
1048         case OPT_DTLS:
1049         case OPT_DTLS1:
1050         case OPT_DTLS1_2:
1051         case OPT_TIMEOUT:
1052         case OPT_MTU:
1053         case OPT_CHAIN:
1054         case OPT_LISTEN:
1055 #endif
1056         case OPT_EOF:
1057         case OPT_ERR:
1058  opthelp:
1059             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1060             goto end;
1061         case OPT_HELP:
1062             opt_help(s_server_options);
1063             ret = 0;
1064             goto end;
1065
1066         case OPT_PORT:
1067             if (!extract_port(opt_arg(), &port))
1068                 goto end;
1069             break;
1070         case OPT_UNIX:
1071 #ifdef NO_SYS_UN_H
1072             BIO_printf(bio_err, "unix domain sockets unsupported\n");
1073             goto end;
1074 #else
1075             unix_path = opt_arg();
1076 #endif
1077             break;
1078         case OPT_UNLINK:
1079 #ifdef NO_SYS_UN_H
1080             BIO_printf(bio_err, "unix domain sockets unsupported\n");
1081             goto end;
1082 #else
1083             unlink_unix_path = 1;
1084 #endif
1085             break;
1086         case OPT_NACCEPT:
1087             naccept = atol(opt_arg());
1088             break;
1089         case OPT_VERIFY:
1090             s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1091             verify_depth = atoi(opt_arg());
1092             if (!s_quiet)
1093                 BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
1094             break;
1095         case OPT_UPPER_V_VERIFY:
1096             s_server_verify =
1097                 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1098                 SSL_VERIFY_CLIENT_ONCE;
1099             verify_depth = atoi(opt_arg());
1100             if (!s_quiet)
1101                 BIO_printf(bio_err,
1102                            "verify depth is %d, must return a certificate\n",
1103                            verify_depth);
1104             break;
1105         case OPT_CONTEXT:
1106             context = (unsigned char *)opt_arg();
1107             break;
1108         case OPT_CERT:
1109             s_cert_file = opt_arg();
1110             break;
1111         case OPT_CRL:
1112             crl_file = opt_arg();
1113             break;
1114         case OPT_CRL_DOWNLOAD:
1115             crl_download = 1;
1116             break;
1117         case OPT_SERVERINFO:
1118             s_serverinfo_file = opt_arg();
1119             break;
1120         case OPT_CERTFORM:
1121             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1122                 goto opthelp;
1123             break;
1124         case OPT_KEY:
1125             s_key_file = opt_arg();
1126             break;
1127         case OPT_KEYFORM:
1128             if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1129                 goto opthelp;
1130             break;
1131         case OPT_PASS:
1132             passarg = opt_arg();
1133             break;
1134         case OPT_CERT_CHAIN:
1135             s_chain_file = opt_arg();
1136             break;
1137         case OPT_DHPARAM:
1138 #ifndef OPENSSL_NO_DH
1139             dhfile = opt_arg();
1140 #endif
1141             break;
1142         case OPT_DCERTFORM:
1143             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1144                 goto opthelp;
1145             break;
1146         case OPT_DCERT:
1147             s_dcert_file = opt_arg();
1148             break;
1149         case OPT_DKEYFORM:
1150             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1151                 goto opthelp;
1152             break;
1153         case OPT_DPASS:
1154             dpassarg = opt_arg();
1155             break;
1156         case OPT_DKEY:
1157             s_dkey_file = opt_arg();
1158             break;
1159         case OPT_DCERT_CHAIN:
1160             s_dchain_file = opt_arg();
1161             break;
1162         case OPT_NOCERT:
1163             nocert = 1;
1164             break;
1165         case OPT_CAPATH:
1166             CApath = opt_arg();
1167             break;
1168         case OPT_NOCAPATH:
1169             noCApath = 1;
1170             break;
1171         case OPT_CHAINCAPATH:
1172             chCApath = opt_arg();
1173             break;
1174         case OPT_VERIFYCAPATH:
1175             vfyCApath = opt_arg();
1176             break;
1177         case OPT_NO_CACHE:
1178             no_cache = 1;
1179             break;
1180         case OPT_EXT_CACHE:
1181             ext_cache = 1;
1182             break;
1183         case OPT_CRLFORM:
1184             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1185                 goto opthelp;
1186             break;
1187         case OPT_S_CASES:
1188             if (ssl_args == NULL)
1189                 ssl_args = sk_OPENSSL_STRING_new_null();
1190             if (ssl_args == NULL
1191                 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1192                 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1193                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1194                 goto end;
1195             }
1196             break;
1197         case OPT_V_CASES:
1198             if (!opt_verify(o, vpm))
1199                 goto end;
1200             vpmtouched++;
1201             break;
1202         case OPT_X_CASES:
1203             if (!args_excert(o, &exc))
1204                 goto end;
1205             break;
1206         case OPT_VERIFY_RET_ERROR:
1207             verify_return_error = 1;
1208             break;
1209         case OPT_VERIFY_QUIET:
1210             verify_quiet = 1;
1211             break;
1212         case OPT_BUILD_CHAIN:
1213             build_chain = 1;
1214             break;
1215         case OPT_CAFILE:
1216             CAfile = opt_arg();
1217             break;
1218         case OPT_NOCAFILE:
1219             noCAfile = 1;
1220             break;
1221         case OPT_CHAINCAFILE:
1222             chCAfile = opt_arg();
1223             break;
1224         case OPT_VERIFYCAFILE:
1225             vfyCAfile = opt_arg();
1226             break;
1227         case OPT_NBIO:
1228             s_nbio = 1;
1229             break;
1230         case OPT_NBIO_TEST:
1231             s_nbio = s_nbio_test = 1;
1232             break;
1233         case OPT_IGN_EOF:
1234             s_ign_eof = 1;
1235             break;
1236         case OPT_NO_IGN_EOF:
1237             s_ign_eof = 0;
1238             break;
1239         case OPT_DEBUG:
1240             s_debug = 1;
1241             break;
1242         case OPT_TLSEXTDEBUG:
1243             s_tlsextdebug = 1;
1244             break;
1245         case OPT_STATUS:
1246             s_tlsextstatus = 1;
1247             break;
1248         case OPT_STATUS_VERBOSE:
1249             s_tlsextstatus = tlscstatp.verbose = 1;
1250             break;
1251         case OPT_STATUS_TIMEOUT:
1252             s_tlsextstatus = 1;
1253             tlscstatp.timeout = atoi(opt_arg());
1254             break;
1255         case OPT_STATUS_URL:
1256             s_tlsextstatus = 1;
1257             if (!OCSP_parse_url(opt_arg(),
1258                                 &tlscstatp.host,
1259                                 &tlscstatp.port,
1260                                 &tlscstatp.path, &tlscstatp.use_ssl)) {
1261                 BIO_printf(bio_err, "Error parsing URL\n");
1262                 goto end;
1263             }
1264             break;
1265         case OPT_MSG:
1266             s_msg = 1;
1267             break;
1268         case OPT_MSGFILE:
1269             bio_s_msg = BIO_new_file(opt_arg(), "w");
1270             break;
1271         case OPT_TRACE:
1272 #ifndef OPENSSL_NO_SSL_TRACE
1273             s_msg = 2;
1274 #else
1275             break;
1276 #endif
1277         case OPT_SECURITY_DEBUG:
1278             sdebug = 1;
1279             break;
1280         case OPT_SECURITY_DEBUG_VERBOSE:
1281             sdebug = 2;
1282             break;
1283         case OPT_STATE:
1284             state = 1;
1285             break;
1286         case OPT_CRLF:
1287             s_crlf = 1;
1288             break;
1289         case OPT_QUIET:
1290             s_quiet = 1;
1291             break;
1292         case OPT_BRIEF:
1293             s_quiet = s_brief = verify_quiet = 1;
1294             break;
1295         case OPT_NO_DHE:
1296 #ifndef OPENSSL_NO_DH
1297             no_dhe = 1;
1298 #endif
1299             break;
1300         case OPT_NO_ECDHE:
1301             no_ecdhe = 1;
1302             break;
1303         case OPT_NO_RESUME_EPHEMERAL:
1304             no_resume_ephemeral = 1;
1305             break;
1306 #ifndef OPENSSL_NO_PSK
1307         case OPT_PSK_HINT:
1308             psk_identity_hint = opt_arg();
1309             break;
1310         case OPT_PSK:
1311             for (p = psk_key = opt_arg(); *p; p++) {
1312                 if (isxdigit(*p))
1313                     continue;
1314                 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1315                 goto end;
1316             }
1317             break;
1318 #endif
1319 #ifndef OPENSSL_NO_SRP
1320         case OPT_SRPVFILE:
1321             srp_verifier_file = opt_arg();
1322             meth = TLSv1_server_method();
1323             break;
1324         case OPT_SRPUSERSEED:
1325             srpuserseed = opt_arg();
1326             meth = TLSv1_server_method();
1327             break;
1328 #else
1329         case OPT_SRPVFILE:
1330         case OPT_SRPUSERSEED:
1331             break;
1332 #endif
1333         case OPT_REV:
1334             rev = 1;
1335             break;
1336         case OPT_WWW:
1337             www = 1;
1338             break;
1339         case OPT_UPPER_WWW:
1340             www = 2;
1341             break;
1342         case OPT_HTTP:
1343             www = 3;
1344             break;
1345         case OPT_SSL3:
1346 #ifndef OPENSSL_NO_SSL3
1347             meth = SSLv3_server_method();
1348 #endif
1349             break;
1350         case OPT_TLS1_2:
1351             meth = TLSv1_2_server_method();
1352             break;
1353         case OPT_TLS1_1:
1354             meth = TLSv1_1_server_method();
1355             break;
1356         case OPT_TLS1:
1357             meth = TLSv1_server_method();
1358             break;
1359 #ifndef OPENSSL_NO_DTLS
1360         case OPT_DTLS:
1361             meth = DTLS_server_method();
1362             socket_type = SOCK_DGRAM;
1363             break;
1364         case OPT_DTLS1:
1365             meth = DTLSv1_server_method();
1366             socket_type = SOCK_DGRAM;
1367             break;
1368         case OPT_DTLS1_2:
1369             meth = DTLSv1_2_server_method();
1370             socket_type = SOCK_DGRAM;
1371             break;
1372         case OPT_TIMEOUT:
1373             enable_timeouts = 1;
1374             break;
1375         case OPT_MTU:
1376             socket_mtu = atol(opt_arg());
1377             break;
1378         case OPT_CHAIN:
1379             cert_chain = 1;
1380             break;
1381         case OPT_LISTEN:
1382             dtlslisten = 1;
1383             break;
1384 #endif
1385         case OPT_ID_PREFIX:
1386             session_id_prefix = opt_arg();
1387             break;
1388         case OPT_ENGINE:
1389             e = setup_engine(opt_arg(), 1);
1390             break;
1391         case OPT_RAND:
1392             inrand = opt_arg();
1393             break;
1394         case OPT_SERVERNAME:
1395             tlsextcbp.servername = opt_arg();
1396             break;
1397         case OPT_SERVERNAME_FATAL:
1398             tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1399             break;
1400         case OPT_CERT2:
1401             s_cert_file2 = opt_arg();
1402             break;
1403         case OPT_KEY2:
1404             s_key_file2 = opt_arg();
1405             break;
1406         case OPT_NEXTPROTONEG:
1407 # ifndef OPENSSL_NO_NEXTPROTONEG
1408             next_proto_neg_in = opt_arg();
1409 #endif
1410             break;
1411         case OPT_ALPN:
1412             alpn_in = opt_arg();
1413             break;
1414 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1415         case OPT_JPAKE:
1416             jpake_secret = opt_arg();
1417             break;
1418 #else
1419         case OPT_JPAKE:
1420             goto opthelp;
1421 #endif
1422         case OPT_SRTP_PROFILES:
1423             srtp_profiles = opt_arg();
1424             break;
1425         case OPT_KEYMATEXPORT:
1426             keymatexportlabel = opt_arg();
1427             break;
1428         case OPT_KEYMATEXPORTLEN:
1429             keymatexportlen = atoi(opt_arg());
1430             break;
1431         case OPT_ASYNC:
1432             async = 1;
1433             break;
1434         }
1435     }
1436     argc = opt_num_rest();
1437     argv = opt_rest();
1438
1439 #ifndef OPENSSL_NO_DTLS
1440     if (www && socket_type == SOCK_DGRAM) {
1441         BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1442         goto end;
1443     }
1444
1445     if (dtlslisten && socket_type != SOCK_DGRAM) {
1446         BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1447         goto end;
1448     }
1449 #endif
1450
1451     if (unix_path && (socket_type != SOCK_STREAM)) {
1452         BIO_printf(bio_err,
1453                    "Can't use unix sockets and datagrams together\n");
1454         goto end;
1455     }
1456 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1457     if (jpake_secret) {
1458         if (psk_key) {
1459             BIO_printf(bio_err, "Can't use JPAKE and PSK together\n");
1460             goto end;
1461         }
1462         psk_identity = "JPAKE";
1463     }
1464 #endif
1465
1466     if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1467         BIO_printf(bio_err, "Error getting password\n");
1468         goto end;
1469     }
1470
1471     if (s_key_file == NULL)
1472         s_key_file = s_cert_file;
1473
1474     if (s_key_file2 == NULL)
1475         s_key_file2 = s_cert_file2;
1476
1477     if (!load_excert(&exc))
1478         goto end;
1479
1480     if (nocert == 0) {
1481         s_key = load_key(s_key_file, s_key_format, 0, pass, e,
1482                          "server certificate private key file");
1483         if (!s_key) {
1484             ERR_print_errors(bio_err);
1485             goto end;
1486         }
1487
1488         s_cert = load_cert(s_cert_file, s_cert_format,
1489                            NULL, e, "server certificate file");
1490
1491         if (!s_cert) {
1492             ERR_print_errors(bio_err);
1493             goto end;
1494         }
1495         if (s_chain_file) {
1496             s_chain = load_certs(s_chain_file, FORMAT_PEM,
1497                                  NULL, e, "server certificate chain");
1498             if (!s_chain)
1499                 goto end;
1500         }
1501
1502         if (tlsextcbp.servername) {
1503             s_key2 = load_key(s_key_file2, s_key_format, 0, pass, e,
1504                               "second server certificate private key file");
1505             if (!s_key2) {
1506                 ERR_print_errors(bio_err);
1507                 goto end;
1508             }
1509
1510             s_cert2 = load_cert(s_cert_file2, s_cert_format,
1511                                 NULL, e, "second server certificate file");
1512
1513             if (!s_cert2) {
1514                 ERR_print_errors(bio_err);
1515                 goto end;
1516             }
1517         }
1518     }
1519 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1520     if (next_proto_neg_in) {
1521         unsigned short len;
1522         next_proto.data = next_protos_parse(&len, next_proto_neg_in);
1523         if (next_proto.data == NULL)
1524             goto end;
1525         next_proto.len = len;
1526     } else {
1527         next_proto.data = NULL;
1528     }
1529 #endif
1530     alpn_ctx.data = NULL;
1531     if (alpn_in) {
1532         unsigned short len;
1533         alpn_ctx.data = next_protos_parse(&len, alpn_in);
1534         if (alpn_ctx.data == NULL)
1535             goto end;
1536         alpn_ctx.len = len;
1537     }
1538
1539     if (crl_file) {
1540         X509_CRL *crl;
1541         crl = load_crl(crl_file, crl_format);
1542         if (!crl) {
1543             BIO_puts(bio_err, "Error loading CRL\n");
1544             ERR_print_errors(bio_err);
1545             goto end;
1546         }
1547         crls = sk_X509_CRL_new_null();
1548         if (!crls || !sk_X509_CRL_push(crls, crl)) {
1549             BIO_puts(bio_err, "Error adding CRL\n");
1550             ERR_print_errors(bio_err);
1551             X509_CRL_free(crl);
1552             goto end;
1553         }
1554     }
1555
1556     if (s_dcert_file) {
1557
1558         if (s_dkey_file == NULL)
1559             s_dkey_file = s_dcert_file;
1560
1561         s_dkey = load_key(s_dkey_file, s_dkey_format,
1562                           0, dpass, e, "second certificate private key file");
1563         if (!s_dkey) {
1564             ERR_print_errors(bio_err);
1565             goto end;
1566         }
1567
1568         s_dcert = load_cert(s_dcert_file, s_dcert_format,
1569                             NULL, e, "second server certificate file");
1570
1571         if (!s_dcert) {
1572             ERR_print_errors(bio_err);
1573             goto end;
1574         }
1575         if (s_dchain_file) {
1576             s_dchain = load_certs(s_dchain_file, FORMAT_PEM,
1577                                   NULL, e, "second server certificate chain");
1578             if (!s_dchain)
1579                 goto end;
1580         }
1581
1582     }
1583
1584     if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1585         && !RAND_status()) {
1586         BIO_printf(bio_err,
1587                    "warning, not much extra random data, consider using the -rand option\n");
1588     }
1589     if (inrand != NULL)
1590         BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1591                    app_RAND_load_files(inrand));
1592
1593     if (bio_s_out == NULL) {
1594         if (s_quiet && !s_debug) {
1595             bio_s_out = BIO_new(BIO_s_null());
1596             if (s_msg && !bio_s_msg)
1597                 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1598         } else {
1599             if (bio_s_out == NULL)
1600                 bio_s_out = dup_bio_out(FORMAT_TEXT);
1601         }
1602     }
1603 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1604     if (nocert)
1605 #endif
1606     {
1607         s_cert_file = NULL;
1608         s_key_file = NULL;
1609         s_dcert_file = NULL;
1610         s_dkey_file = NULL;
1611         s_cert_file2 = NULL;
1612         s_key_file2 = NULL;
1613     }
1614
1615     ctx = SSL_CTX_new(meth);
1616     if (sdebug)
1617         ssl_ctx_security_debug(ctx, sdebug);
1618     if (ctx == NULL) {
1619         ERR_print_errors(bio_err);
1620         goto end;
1621     }
1622     if (session_id_prefix) {
1623         if (strlen(session_id_prefix) >= 32)
1624             BIO_printf(bio_err,
1625                        "warning: id_prefix is too long, only one new session will be possible\n");
1626         if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1627             BIO_printf(bio_err, "error setting 'id_prefix'\n");
1628             ERR_print_errors(bio_err);
1629             goto end;
1630         }
1631         BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1632     }
1633     SSL_CTX_set_quiet_shutdown(ctx, 1);
1634     if (exc)
1635         ssl_ctx_set_excert(ctx, exc);
1636
1637     if (state)
1638         SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1639     if (no_cache)
1640         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1641     else if (ext_cache)
1642         init_session_cache_ctx(ctx);
1643     else
1644         SSL_CTX_sess_set_cache_size(ctx, 128);
1645
1646     if (async) {
1647         SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1648         ASYNC_init(1, 0, 0);
1649     }
1650
1651 #ifndef OPENSSL_NO_SRTP
1652     if (srtp_profiles != NULL) {
1653         /* Returns 0 on success! */
1654         if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1655             BIO_printf(bio_err, "Error setting SRTP profile\n");
1656             ERR_print_errors(bio_err);
1657             goto end;
1658         }
1659     }
1660 #endif
1661
1662     if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1663         ERR_print_errors(bio_err);
1664         goto end;
1665     }
1666     if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1667         BIO_printf(bio_err, "Error setting verify params\n");
1668         ERR_print_errors(bio_err);
1669         goto end;
1670     }
1671
1672     ssl_ctx_add_crls(ctx, crls, 0);
1673     if (!config_ctx(cctx, ssl_args, ctx, no_ecdhe, jpake_secret == NULL))
1674         goto end;
1675
1676     if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1677                          crls, crl_download)) {
1678         BIO_printf(bio_err, "Error loading store locations\n");
1679         ERR_print_errors(bio_err);
1680         goto end;
1681     }
1682
1683     if (s_cert2) {
1684         ctx2 = SSL_CTX_new(meth);
1685         if (ctx2 == NULL) {
1686             ERR_print_errors(bio_err);
1687             goto end;
1688         }
1689     }
1690
1691     if (ctx2) {
1692         BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1693
1694         if (sdebug)
1695             ssl_ctx_security_debug(ctx, sdebug);
1696
1697         if (session_id_prefix) {
1698             if (strlen(session_id_prefix) >= 32)
1699                 BIO_printf(bio_err,
1700                            "warning: id_prefix is too long, only one new session will be possible\n");
1701             if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1702                 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1703                 ERR_print_errors(bio_err);
1704                 goto end;
1705             }
1706             BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1707         }
1708         SSL_CTX_set_quiet_shutdown(ctx2, 1);
1709         if (exc)
1710             ssl_ctx_set_excert(ctx2, exc);
1711
1712         if (state)
1713             SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1714
1715         if (no_cache)
1716             SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1717         else if (ext_cache)
1718             init_session_cache_ctx(ctx2);
1719         else
1720             SSL_CTX_sess_set_cache_size(ctx2, 128);
1721
1722         if (async)
1723             SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1724
1725         if ((!SSL_CTX_load_verify_locations(ctx2, CAfile, CApath)) ||
1726             (!SSL_CTX_set_default_verify_paths(ctx2))) {
1727             ERR_print_errors(bio_err);
1728         }
1729         if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1730             BIO_printf(bio_err, "Error setting verify params\n");
1731             ERR_print_errors(bio_err);
1732             goto end;
1733         }
1734
1735         ssl_ctx_add_crls(ctx2, crls, 0);
1736         if (!config_ctx(cctx, ssl_args, ctx2, no_ecdhe, jpake_secret == NULL))
1737             goto end;
1738     }
1739 #ifndef OPENSSL_NO_NEXTPROTONEG
1740     if (next_proto.data)
1741         SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1742                                               &next_proto);
1743 #endif
1744     if (alpn_ctx.data)
1745         SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1746
1747 #ifndef OPENSSL_NO_DH
1748     if (!no_dhe) {
1749         DH *dh = NULL;
1750
1751         if (dhfile)
1752             dh = load_dh_param(dhfile);
1753         else if (s_cert_file)
1754             dh = load_dh_param(s_cert_file);
1755
1756         if (dh != NULL) {
1757             BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1758         } else {
1759             BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1760         }
1761         (void)BIO_flush(bio_s_out);
1762
1763         if (dh == NULL)
1764             SSL_CTX_set_dh_auto(ctx, 1);
1765         else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1766             BIO_puts(bio_err, "Error setting temp DH parameters\n");
1767             ERR_print_errors(bio_err);
1768             DH_free(dh);
1769             goto end;
1770         }
1771
1772         if (ctx2) {
1773             if (!dhfile) {
1774                 DH *dh2 = load_dh_param(s_cert_file2);
1775                 if (dh2 != NULL) {
1776                     BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1777                     (void)BIO_flush(bio_s_out);
1778
1779                     DH_free(dh);
1780                     dh = dh2;
1781                 }
1782             }
1783             if (dh == NULL)
1784                 SSL_CTX_set_dh_auto(ctx2, 1);
1785             else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1786                 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1787                 ERR_print_errors(bio_err);
1788                 DH_free(dh);
1789                 goto end;
1790             }
1791         }
1792         DH_free(dh);
1793     }
1794 #endif
1795
1796     if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1797         goto end;
1798
1799     if (s_serverinfo_file != NULL
1800         && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1801         ERR_print_errors(bio_err);
1802         goto end;
1803     }
1804
1805     if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1806         goto end;
1807
1808     if (s_dcert != NULL) {
1809         if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1810             goto end;
1811     }
1812
1813     if (no_resume_ephemeral) {
1814         SSL_CTX_set_not_resumable_session_callback(ctx,
1815                                                    not_resumable_sess_cb);
1816
1817         if (ctx2)
1818             SSL_CTX_set_not_resumable_session_callback(ctx2,
1819                                                        not_resumable_sess_cb);
1820     }
1821 #ifndef OPENSSL_NO_PSK
1822 # ifdef OPENSSL_NO_JPAKE
1823     if (psk_key != NULL)
1824 # else
1825     if (psk_key != NULL || jpake_secret)
1826 # endif
1827     {
1828         if (s_debug)
1829             BIO_printf(bio_s_out,
1830                        "PSK key given or JPAKE in use, setting server callback\n");
1831         SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1832     }
1833
1834     if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1835         BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1836         ERR_print_errors(bio_err);
1837         goto end;
1838     }
1839 #endif
1840
1841     SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1842     if (!SSL_CTX_set_session_id_context(ctx,
1843                 (void *)&s_server_session_id_context,
1844                 sizeof s_server_session_id_context)) {
1845         BIO_printf(bio_err, "error setting session id context\n");
1846         ERR_print_errors(bio_err);
1847         goto end;
1848     }
1849
1850     /* Set DTLS cookie generation and verification callbacks */
1851     SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1852     SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1853
1854     if (ctx2) {
1855         SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1856         if (!SSL_CTX_set_session_id_context(ctx2,
1857                     (void *)&s_server_session_id_context,
1858                     sizeof s_server_session_id_context)) {
1859             BIO_printf(bio_err, "error setting session id context\n");
1860             ERR_print_errors(bio_err);
1861             goto end;
1862         }
1863         tlsextcbp.biodebug = bio_s_out;
1864         SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1865         SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1866         SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1867         SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1868     }
1869
1870 #ifndef OPENSSL_NO_SRP
1871     if (srp_verifier_file != NULL) {
1872         srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1873         srp_callback_parm.user = NULL;
1874         srp_callback_parm.login = NULL;
1875         if ((ret =
1876              SRP_VBASE_init(srp_callback_parm.vb,
1877                             srp_verifier_file)) != SRP_NO_ERROR) {
1878             BIO_printf(bio_err,
1879                        "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1880                        srp_verifier_file, ret);
1881             goto end;
1882         }
1883         SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
1884         SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
1885         SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1886     } else
1887 #endif
1888     if (CAfile != NULL) {
1889         SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
1890
1891         if (ctx2)
1892             SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
1893     }
1894     if (s_tlsextstatus) {
1895         SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1896         SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1897         if (ctx2) {
1898             SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
1899             SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
1900         }
1901     }
1902
1903     BIO_printf(bio_s_out, "ACCEPT\n");
1904     (void)BIO_flush(bio_s_out);
1905     if (rev)
1906         server_cb = rev_body;
1907     else if (www)
1908         server_cb = www_body;
1909     else
1910         server_cb = sv_body;
1911 #ifndef NO_SYS_UN_H
1912     if (unix_path) {
1913         if (unlink_unix_path)
1914             unlink(unix_path);
1915         do_server_unix(unix_path, &accept_socket, server_cb, context,
1916                        naccept);
1917     } else
1918 #endif
1919         do_server(port, socket_type, &accept_socket, server_cb, context,
1920                   naccept);
1921     print_stats(bio_s_out, ctx);
1922     ret = 0;
1923  end:
1924     SSL_CTX_free(ctx);
1925     X509_free(s_cert);
1926     sk_X509_CRL_pop_free(crls, X509_CRL_free);
1927     X509_free(s_dcert);
1928     EVP_PKEY_free(s_key);
1929     EVP_PKEY_free(s_dkey);
1930     sk_X509_pop_free(s_chain, X509_free);
1931     sk_X509_pop_free(s_dchain, X509_free);
1932     OPENSSL_free(pass);
1933     OPENSSL_free(dpass);
1934     X509_VERIFY_PARAM_free(vpm);
1935     free_sessions();
1936     OPENSSL_free(tlscstatp.host);
1937     OPENSSL_free(tlscstatp.port);
1938     OPENSSL_free(tlscstatp.path);
1939     SSL_CTX_free(ctx2);
1940     X509_free(s_cert2);
1941     EVP_PKEY_free(s_key2);
1942     BIO_free(serverinfo_in);
1943 #ifndef OPENSSL_NO_NEXTPROTONEG
1944     OPENSSL_free(next_proto.data);
1945 #endif
1946     OPENSSL_free(alpn_ctx.data);
1947     ssl_excert_free(exc);
1948     sk_OPENSSL_STRING_free(ssl_args);
1949     SSL_CONF_CTX_free(cctx);
1950     BIO_free(bio_s_out);
1951     bio_s_out = NULL;
1952     BIO_free(bio_s_msg);
1953     bio_s_msg = NULL;
1954     if (async) {
1955         ASYNC_cleanup(1);
1956     }
1957     return (ret);
1958 }
1959
1960 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
1961 {
1962     BIO_printf(bio, "%4ld items in the session cache\n",
1963                SSL_CTX_sess_number(ssl_ctx));
1964     BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
1965                SSL_CTX_sess_connect(ssl_ctx));
1966     BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
1967                SSL_CTX_sess_connect_renegotiate(ssl_ctx));
1968     BIO_printf(bio, "%4ld client connects that finished\n",
1969                SSL_CTX_sess_connect_good(ssl_ctx));
1970     BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
1971                SSL_CTX_sess_accept(ssl_ctx));
1972     BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
1973                SSL_CTX_sess_accept_renegotiate(ssl_ctx));
1974     BIO_printf(bio, "%4ld server accepts that finished\n",
1975                SSL_CTX_sess_accept_good(ssl_ctx));
1976     BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
1977     BIO_printf(bio, "%4ld session cache misses\n",
1978                SSL_CTX_sess_misses(ssl_ctx));
1979     BIO_printf(bio, "%4ld session cache timeouts\n",
1980                SSL_CTX_sess_timeouts(ssl_ctx));
1981     BIO_printf(bio, "%4ld callback cache hits\n",
1982                SSL_CTX_sess_cb_hits(ssl_ctx));
1983     BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
1984                SSL_CTX_sess_cache_full(ssl_ctx),
1985                SSL_CTX_sess_get_cache_size(ssl_ctx));
1986 }
1987
1988 static int sv_body(char *hostname, int s, int stype, unsigned char *context)
1989 {
1990     char *buf = NULL;
1991     fd_set readfds;
1992     int ret = 1, width;
1993     int k, i;
1994     unsigned long l;
1995     SSL *con = NULL;
1996     BIO *sbio;
1997     struct timeval timeout;
1998 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
1999     struct timeval tv;
2000 #else
2001     struct timeval *timeoutp;
2002 #endif
2003
2004     buf = app_malloc(bufsize, "server buffer");
2005 #ifdef FIONBIO
2006     if (s_nbio) {
2007         unsigned long sl = 1;
2008
2009         if (!s_quiet)
2010             BIO_printf(bio_err, "turning on non blocking io\n");
2011         if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)
2012             ERR_print_errors(bio_err);
2013     }
2014 #endif
2015
2016     if (con == NULL) {
2017         con = SSL_new(ctx);
2018
2019         if (s_tlsextdebug) {
2020             SSL_set_tlsext_debug_callback(con, tlsext_cb);
2021             SSL_set_tlsext_debug_arg(con, bio_s_out);
2022         }
2023
2024         if (context
2025                 && !SSL_set_session_id_context(con,
2026                         context, strlen((char *)context))) {
2027             BIO_printf(bio_err, "Error setting session id context\n");
2028             ret = -1;
2029             goto err;
2030         }
2031     }
2032     if (!SSL_clear(con)) {
2033         BIO_printf(bio_err, "Error clearing SSL connection\n");
2034         ret = -1;
2035         goto err;
2036     }
2037
2038     if (stype == SOCK_DGRAM) {
2039
2040         sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2041
2042         if (enable_timeouts) {
2043             timeout.tv_sec = 0;
2044             timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2045             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2046
2047             timeout.tv_sec = 0;
2048             timeout.tv_usec = DGRAM_SND_TIMEOUT;
2049             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2050         }
2051
2052         if (socket_mtu) {
2053             if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2054                 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2055                            DTLS_get_link_min_mtu(con));
2056                 ret = -1;
2057                 BIO_free(sbio);
2058                 goto err;
2059             }
2060             SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2061             if (!DTLS_set_link_mtu(con, socket_mtu)) {
2062                 BIO_printf(bio_err, "Failed to set MTU\n");
2063                 ret = -1;
2064                 BIO_free(sbio);
2065                 goto err;
2066             }
2067         } else
2068             /* want to do MTU discovery */
2069             BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2070
2071         /* turn on cookie exchange */
2072         SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2073     } else
2074         sbio = BIO_new_socket(s, BIO_NOCLOSE);
2075
2076     if (s_nbio_test) {
2077         BIO *test;
2078
2079         test = BIO_new(BIO_f_nbio_test());
2080         sbio = BIO_push(test, sbio);
2081     }
2082 #ifndef OPENSSL_NO_JPAKE
2083     if (jpake_secret)
2084         jpake_server_auth(bio_s_out, sbio, jpake_secret);
2085 #endif
2086
2087     SSL_set_bio(con, sbio, sbio);
2088     SSL_set_accept_state(con);
2089     /* SSL_set_fd(con,s); */
2090
2091     if (s_debug) {
2092         SSL_set_debug(con, 1);
2093         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2094         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2095     }
2096     if (s_msg) {
2097 #ifndef OPENSSL_NO_SSL_TRACE
2098         if (s_msg == 2)
2099             SSL_set_msg_callback(con, SSL_trace);
2100         else
2101 #endif
2102             SSL_set_msg_callback(con, msg_cb);
2103         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2104     }
2105
2106     if (s_tlsextdebug) {
2107         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2108         SSL_set_tlsext_debug_arg(con, bio_s_out);
2109     }
2110
2111     width = s + 1;
2112     for (;;) {
2113         int read_from_terminal;
2114         int read_from_sslcon;
2115
2116         read_from_terminal = 0;
2117         read_from_sslcon = SSL_pending(con)
2118                            || (async && SSL_waiting_for_async(con));
2119
2120         if (!read_from_sslcon) {
2121             FD_ZERO(&readfds);
2122 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE)
2123             openssl_fdset(fileno(stdin), &readfds);
2124 #endif
2125             openssl_fdset(s, &readfds);
2126             /*
2127              * Note: under VMS with SOCKETSHR the second parameter is
2128              * currently of type (int *) whereas under other systems it is
2129              * (void *) if you don't have a cast it will choke the compiler:
2130              * if you do have a cast then you can either go for (int *) or
2131              * (void *).
2132              */
2133 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
2134             /*
2135              * Under DOS (non-djgpp) and Windows we can't select on stdin:
2136              * only on sockets. As a workaround we timeout the select every
2137              * second and check for any keypress. In a proper Windows
2138              * application we wouldn't do this because it is inefficient.
2139              */
2140             tv.tv_sec = 1;
2141             tv.tv_usec = 0;
2142             i = select(width, (void *)&readfds, NULL, NULL, &tv);
2143             if ((i < 0) || (!i && !_kbhit()))
2144                 continue;
2145             if (_kbhit())
2146                 read_from_terminal = 1;
2147 #else
2148             if ((SSL_version(con) == DTLS1_VERSION) &&
2149                 DTLSv1_get_timeout(con, &timeout))
2150                 timeoutp = &timeout;
2151             else
2152                 timeoutp = NULL;
2153
2154             i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2155
2156             if ((SSL_version(con) == DTLS1_VERSION)
2157                 && DTLSv1_handle_timeout(con) > 0) {
2158                 BIO_printf(bio_err, "TIMEOUT occurred\n");
2159             }
2160
2161             if (i <= 0)
2162                 continue;
2163             if (FD_ISSET(fileno(stdin), &readfds))
2164                 read_from_terminal = 1;
2165 #endif
2166             if (FD_ISSET(s, &readfds))
2167                 read_from_sslcon = 1;
2168         }
2169         if (read_from_terminal) {
2170             if (s_crlf) {
2171                 int j, lf_num;
2172
2173                 i = raw_read_stdin(buf, bufsize / 2);
2174                 lf_num = 0;
2175                 /* both loops are skipped when i <= 0 */
2176                 for (j = 0; j < i; j++)
2177                     if (buf[j] == '\n')
2178                         lf_num++;
2179                 for (j = i - 1; j >= 0; j--) {
2180                     buf[j + lf_num] = buf[j];
2181                     if (buf[j] == '\n') {
2182                         lf_num--;
2183                         i++;
2184                         buf[j + lf_num] = '\r';
2185                     }
2186                 }
2187                 assert(lf_num == 0);
2188             } else
2189                 i = raw_read_stdin(buf, bufsize);
2190             if (!s_quiet && !s_brief) {
2191                 if ((i <= 0) || (buf[0] == 'Q')) {
2192                     BIO_printf(bio_s_out, "DONE\n");
2193                     (void)BIO_flush(bio_s_out);
2194                     SHUTDOWN(s);
2195                     close_accept_socket();
2196                     ret = -11;
2197                     goto err;
2198                 }
2199                 if ((i <= 0) || (buf[0] == 'q')) {
2200                     BIO_printf(bio_s_out, "DONE\n");
2201                     (void)BIO_flush(bio_s_out);
2202                     if (SSL_version(con) != DTLS1_VERSION)
2203                         SHUTDOWN(s);
2204                     /*
2205                      * close_accept_socket(); ret= -11;
2206                      */
2207                     goto err;
2208                 }
2209 #ifndef OPENSSL_NO_HEARTBEATS
2210                 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2211                     BIO_printf(bio_err, "HEARTBEATING\n");
2212                     SSL_heartbeat(con);
2213                     i = 0;
2214                     continue;
2215                 }
2216 #endif
2217                 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2218                     SSL_renegotiate(con);
2219                     i = SSL_do_handshake(con);
2220                     printf("SSL_do_handshake -> %d\n", i);
2221                     i = 0;      /* 13; */
2222                     continue;
2223                     /*
2224                      * strcpy(buf,"server side RE-NEGOTIATE\n");
2225                      */
2226                 }
2227                 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2228                     SSL_set_verify(con,
2229                                    SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2230                                    NULL);
2231                     SSL_renegotiate(con);
2232                     i = SSL_do_handshake(con);
2233                     printf("SSL_do_handshake -> %d\n", i);
2234                     i = 0;      /* 13; */
2235                     continue;
2236                     /*
2237                      * strcpy(buf,"server side RE-NEGOTIATE asking for client
2238                      * cert\n");
2239                      */
2240                 }
2241                 if (buf[0] == 'P') {
2242                     static const char *str = "Lets print some clear text\n";
2243                     BIO_write(SSL_get_wbio(con), str, strlen(str));
2244                 }
2245                 if (buf[0] == 'S') {
2246                     print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2247                 }
2248             }
2249 #ifdef CHARSET_EBCDIC
2250             ebcdic2ascii(buf, buf, i);
2251 #endif
2252             l = k = 0;
2253             for (;;) {
2254                 /* should do a select for the write */
2255 #ifdef RENEG
2256                 {
2257                     static count = 0;
2258                     if (++count == 100) {
2259                         count = 0;
2260                         SSL_renegotiate(con);
2261                     }
2262                 }
2263 #endif
2264                 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2265 #ifndef OPENSSL_NO_SRP
2266                 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2267                     BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2268                     srp_callback_parm.user =
2269                         SRP_VBASE_get_by_user(srp_callback_parm.vb,
2270                                               srp_callback_parm.login);
2271                     if (srp_callback_parm.user)
2272                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
2273                                    srp_callback_parm.user->info);
2274                     else
2275                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
2276                     k = SSL_write(con, &(buf[l]), (unsigned int)i);
2277                 }
2278 #endif
2279                 switch (SSL_get_error(con, k)) {
2280                 case SSL_ERROR_NONE:
2281                     break;
2282                 case SSL_ERROR_WANT_ASYNC:
2283                     BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2284                     wait_for_async(con);
2285                     break;
2286                 case SSL_ERROR_WANT_WRITE:
2287                 case SSL_ERROR_WANT_READ:
2288                 case SSL_ERROR_WANT_X509_LOOKUP:
2289                     BIO_printf(bio_s_out, "Write BLOCK\n");
2290                     break;
2291                 case SSL_ERROR_SYSCALL:
2292                 case SSL_ERROR_SSL:
2293                     BIO_printf(bio_s_out, "ERROR\n");
2294                     (void)BIO_flush(bio_s_out);
2295                     ERR_print_errors(bio_err);
2296                     ret = 1;
2297                     goto err;
2298                     /* break; */
2299                 case SSL_ERROR_ZERO_RETURN:
2300                     BIO_printf(bio_s_out, "DONE\n");
2301                     (void)BIO_flush(bio_s_out);
2302                     ret = 1;
2303                     goto err;
2304                 }
2305                 if (k > 0) {
2306                     l += k;
2307                     i -= k;
2308                 }
2309                 if (i <= 0)
2310                     break;
2311             }
2312         }
2313         if (read_from_sslcon) {
2314             /*
2315              * init_ssl_connection handles all async events itself so if we're
2316              * waiting for async then we shouldn't go back into
2317              * init_ssl_connection
2318              */
2319             if ((!async || !SSL_waiting_for_async(con))
2320                     && !SSL_is_init_finished(con)) {
2321                 i = init_ssl_connection(con);
2322
2323                 if (i < 0) {
2324                     ret = 0;
2325                     goto err;
2326                 } else if (i == 0) {
2327                     ret = 1;
2328                     goto err;
2329                 }
2330             } else {
2331  again:
2332                 i = SSL_read(con, (char *)buf, bufsize);
2333 #ifndef OPENSSL_NO_SRP
2334                 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2335                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2336                     srp_callback_parm.user =
2337                         SRP_VBASE_get_by_user(srp_callback_parm.vb,
2338                                               srp_callback_parm.login);
2339                     if (srp_callback_parm.user)
2340                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
2341                                    srp_callback_parm.user->info);
2342                     else
2343                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
2344                     i = SSL_read(con, (char *)buf, bufsize);
2345                 }
2346 #endif
2347                 switch (SSL_get_error(con, i)) {
2348                 case SSL_ERROR_NONE:
2349 #ifdef CHARSET_EBCDIC
2350                     ascii2ebcdic(buf, buf, i);
2351 #endif
2352                     raw_write_stdout(buf, (unsigned int)i);
2353                     if (SSL_pending(con))
2354                         goto again;
2355                     break;
2356                 case SSL_ERROR_WANT_ASYNC:
2357                     BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2358                     wait_for_async(con);
2359                     break;
2360                 case SSL_ERROR_WANT_WRITE:
2361                 case SSL_ERROR_WANT_READ:
2362                     BIO_printf(bio_s_out, "Read BLOCK\n");
2363                     break;
2364                 case SSL_ERROR_SYSCALL:
2365                 case SSL_ERROR_SSL:
2366                     BIO_printf(bio_s_out, "ERROR\n");
2367                     (void)BIO_flush(bio_s_out);
2368                     ERR_print_errors(bio_err);
2369                     ret = 1;
2370                     goto err;
2371                 case SSL_ERROR_ZERO_RETURN:
2372                     BIO_printf(bio_s_out, "DONE\n");
2373                     (void)BIO_flush(bio_s_out);
2374                     ret = 1;
2375                     goto err;
2376                 }
2377             }
2378         }
2379     }
2380  err:
2381     if (con != NULL) {
2382         BIO_printf(bio_s_out, "shutting down SSL\n");
2383         SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2384         SSL_free(con);
2385     }
2386     BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2387     OPENSSL_clear_free(buf, bufsize);
2388     if (ret >= 0)
2389         BIO_printf(bio_s_out, "ACCEPT\n");
2390     (void)BIO_flush(bio_s_out);
2391     return (ret);
2392 }
2393
2394 static void close_accept_socket(void)
2395 {
2396     BIO_printf(bio_err, "shutdown accept socket\n");
2397     if (accept_socket >= 0) {
2398         SHUTDOWN2(accept_socket);
2399     }
2400 }
2401
2402 static int init_ssl_connection(SSL *con)
2403 {
2404     int i;
2405     const char *str;
2406     X509 *peer;
2407     long verify_err;
2408     char buf[BUFSIZ];
2409 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2410     const unsigned char *next_proto_neg;
2411     unsigned next_proto_neg_len;
2412 #endif
2413     unsigned char *exportedkeymat;
2414 #ifndef OPENSSL_NO_DTLS
2415     struct sockaddr_storage client;
2416 #endif
2417
2418 #ifndef OPENSSL_NO_DTLS
2419     if(dtlslisten) {
2420         i = DTLSv1_listen(con, &client);
2421         if (i > 0) {
2422             BIO *wbio;
2423             int fd = -1;
2424
2425             wbio = SSL_get_wbio(con);
2426             if(wbio) {
2427                 BIO_get_fd(wbio, &fd);
2428             }
2429
2430             if(!wbio || connect(fd, (struct sockaddr *)&client,
2431                                 sizeof(struct sockaddr_storage))) {
2432                 BIO_printf(bio_err, "ERROR - unable to connect\n");
2433                 return 0;
2434             }
2435             dtlslisten = 0;
2436             i = SSL_accept(con);
2437         }
2438     } else
2439 #endif
2440
2441     do {
2442         i = SSL_accept(con);
2443
2444 #ifdef CERT_CB_TEST_RETRY
2445         {
2446             while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2447                     && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2448                 BIO_printf(bio_err,
2449                        "LOOKUP from certificate callback during accept\n");
2450                 i = SSL_accept(con);
2451             }
2452         }
2453 #endif
2454
2455 #ifndef OPENSSL_NO_SRP
2456         while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2457             BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2458                        srp_callback_parm.login);
2459             srp_callback_parm.user =
2460                 SRP_VBASE_get_by_user(srp_callback_parm.vb,
2461                                       srp_callback_parm.login);
2462             if (srp_callback_parm.user)
2463                 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2464                            srp_callback_parm.user->info);
2465             else
2466                 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2467             i = SSL_accept(con);
2468         }
2469 #endif
2470     } while (i < 0 && SSL_waiting_for_async(con));
2471
2472     if (i <= 0) {
2473         if ((dtlslisten && i == 0)
2474                 || (!dtlslisten && BIO_sock_should_retry(i))) {
2475             BIO_printf(bio_s_out, "DELAY\n");
2476             return (1);
2477         }
2478
2479         BIO_printf(bio_err, "ERROR\n");
2480
2481         verify_err = SSL_get_verify_result(con);
2482         if (verify_err != X509_V_OK) {
2483             BIO_printf(bio_err, "verify error:%s\n",
2484                        X509_verify_cert_error_string(verify_err));
2485         }
2486         /* Always print any error messages */
2487         ERR_print_errors(bio_err);
2488         return (0);
2489     }
2490
2491     if (s_brief)
2492         print_ssl_summary(con);
2493
2494     PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2495
2496     peer = SSL_get_peer_certificate(con);
2497     if (peer != NULL) {
2498         BIO_printf(bio_s_out, "Client certificate\n");
2499         PEM_write_bio_X509(bio_s_out, peer);
2500         X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
2501         BIO_printf(bio_s_out, "subject=%s\n", buf);
2502         X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
2503         BIO_printf(bio_s_out, "issuer=%s\n", buf);
2504         X509_free(peer);
2505     }
2506
2507     if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2508         BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2509     str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2510     ssl_print_sigalgs(bio_s_out, con);
2511 #ifndef OPENSSL_NO_EC
2512     ssl_print_point_formats(bio_s_out, con);
2513     ssl_print_curves(bio_s_out, con, 0);
2514 #endif
2515     BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2516
2517 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2518     SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2519     if (next_proto_neg) {
2520         BIO_printf(bio_s_out, "NEXTPROTO is ");
2521         BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2522         BIO_printf(bio_s_out, "\n");
2523     }
2524 #endif
2525 #ifndef OPENSSL_NO_SRTP
2526     {
2527         SRTP_PROTECTION_PROFILE *srtp_profile
2528             = SSL_get_selected_srtp_profile(con);
2529
2530         if (srtp_profile)
2531             BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2532                        srtp_profile->name);
2533     }
2534 #endif
2535     if (SSL_cache_hit(con))
2536         BIO_printf(bio_s_out, "Reused session-id\n");
2537     BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2538                SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2539     if (keymatexportlabel != NULL) {
2540         BIO_printf(bio_s_out, "Keying material exporter:\n");
2541         BIO_printf(bio_s_out, "    Label: '%s'\n", keymatexportlabel);
2542         BIO_printf(bio_s_out, "    Length: %i bytes\n", keymatexportlen);
2543         exportedkeymat = app_malloc(keymatexportlen, "export key");
2544         if (!SSL_export_keying_material(con, exportedkeymat,
2545                                         keymatexportlen,
2546                                         keymatexportlabel,
2547                                         strlen(keymatexportlabel),
2548                                         NULL, 0, 0)) {
2549             BIO_printf(bio_s_out, "    Error\n");
2550         } else {
2551             BIO_printf(bio_s_out, "    Keying material: ");
2552             for (i = 0; i < keymatexportlen; i++)
2553                 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2554             BIO_printf(bio_s_out, "\n");
2555         }
2556         OPENSSL_free(exportedkeymat);
2557     }
2558
2559     return (1);
2560 }
2561
2562 #ifndef OPENSSL_NO_DH
2563 static DH *load_dh_param(const char *dhfile)
2564 {
2565     DH *ret = NULL;
2566     BIO *bio;
2567
2568     if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2569         goto err;
2570     ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2571  err:
2572     BIO_free(bio);
2573     return (ret);
2574 }
2575 #endif
2576
2577 static int www_body(char *hostname, int s, int stype, unsigned char *context)
2578 {
2579     char *buf = NULL;
2580     int ret = 1;
2581     int i, j, k, dot;
2582     SSL *con;
2583     const SSL_CIPHER *c;
2584     BIO *io, *ssl_bio, *sbio;
2585 #ifdef RENEG
2586     int total_bytes = 0;
2587 #endif
2588     int width;
2589     fd_set readfds;
2590
2591     /* Set width for a select call if needed */
2592     width = s + 1;
2593
2594     buf = app_malloc(bufsize, "server www buffer");
2595     io = BIO_new(BIO_f_buffer());
2596     ssl_bio = BIO_new(BIO_f_ssl());
2597     if ((io == NULL) || (ssl_bio == NULL))
2598         goto err;
2599
2600 #ifdef FIONBIO
2601     if (s_nbio) {
2602         unsigned long sl = 1;
2603
2604         if (!s_quiet)
2605             BIO_printf(bio_err, "turning on non blocking io\n");
2606         if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)
2607             ERR_print_errors(bio_err);
2608     }
2609 #endif
2610
2611     /* lets make the output buffer a reasonable size */
2612     if (!BIO_set_write_buffer_size(io, bufsize))
2613         goto err;
2614
2615     if ((con = SSL_new(ctx)) == NULL)
2616         goto err;
2617
2618     if (s_tlsextdebug) {
2619         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2620         SSL_set_tlsext_debug_arg(con, bio_s_out);
2621     }
2622
2623     if (context && !SSL_set_session_id_context(con, context,
2624                         strlen((char *)context)))
2625         goto err;
2626
2627     sbio = BIO_new_socket(s, BIO_NOCLOSE);
2628     if (s_nbio_test) {
2629         BIO *test;
2630
2631         test = BIO_new(BIO_f_nbio_test());
2632         sbio = BIO_push(test, sbio);
2633     }
2634     SSL_set_bio(con, sbio, sbio);
2635     SSL_set_accept_state(con);
2636
2637     /* SSL_set_fd(con,s); */
2638     BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2639     BIO_push(io, ssl_bio);
2640 #ifdef CHARSET_EBCDIC
2641     io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2642 #endif
2643
2644     if (s_debug) {
2645         SSL_set_debug(con, 1);
2646         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2647         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2648     }
2649     if (s_msg) {
2650 #ifndef OPENSSL_NO_SSL_TRACE
2651         if (s_msg == 2)
2652             SSL_set_msg_callback(con, SSL_trace);
2653         else
2654 #endif
2655             SSL_set_msg_callback(con, msg_cb);
2656         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2657     }
2658
2659     for (;;) {
2660         i = BIO_gets(io, buf, bufsize - 1);
2661         if (i < 0) {            /* error */
2662             if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2663                 if (!s_quiet)
2664                     ERR_print_errors(bio_err);
2665                 goto err;
2666             } else {
2667                 BIO_printf(bio_s_out, "read R BLOCK\n");
2668 #ifndef OPENSSL_NO_SRP
2669                 if (BIO_should_io_special(io)
2670                     && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2671                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2672                     srp_callback_parm.user =
2673                         SRP_VBASE_get_by_user(srp_callback_parm.vb,
2674                                               srp_callback_parm.login);
2675                     if (srp_callback_parm.user)
2676                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
2677                                    srp_callback_parm.user->info);
2678                     else
2679                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
2680                     continue;
2681                 }
2682 #endif
2683 #if defined(OPENSSL_SYS_NETWARE)
2684                 delay(1000);
2685 #elif !defined(OPENSSL_SYS_MSDOS)
2686                 sleep(1);
2687 #endif
2688                 continue;
2689             }
2690         } else if (i == 0) {    /* end of input */
2691             ret = 1;
2692             goto end;
2693         }
2694
2695         /* else we have data */
2696         if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2697             ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2698             char *p;
2699             X509 *peer;
2700             STACK_OF(SSL_CIPHER) *sk;
2701             static const char *space = "                          ";
2702
2703             if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2704                 if (strncmp("GET /renegcert", buf, 14) == 0)
2705                     SSL_set_verify(con,
2706                                    SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2707                                    NULL);
2708                 i = SSL_renegotiate(con);
2709                 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2710                 /* Send the HelloRequest */
2711                 i = SSL_do_handshake(con);
2712                 if (i <= 0) {
2713                     BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2714                                SSL_get_error(con, i));
2715                     ERR_print_errors(bio_err);
2716                     goto err;
2717                 }
2718                 /* Wait for a ClientHello to come back */
2719                 FD_ZERO(&readfds);
2720                 openssl_fdset(s, &readfds);
2721                 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2722                 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2723                     BIO_printf(bio_s_out, "Error waiting for client response\n");
2724                     ERR_print_errors(bio_err);
2725                     goto err;
2726                 }
2727                 /*
2728                  * We're not acutally expecting any data here and we ignore
2729                  * any that is sent. This is just to force the handshake that
2730                  * we're expecting to come from the client. If they haven't
2731                  * sent one there's not much we can do.
2732                  */
2733                 BIO_gets(io, buf, bufsize - 1);
2734             }
2735
2736             BIO_puts(io,
2737                      "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2738             BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2739             BIO_puts(io, "<pre>\n");
2740 /*                      BIO_puts(io,OpenSSL_version(OPENSSL_VERSION));*/
2741             BIO_puts(io, "\n");
2742             for (i = 0; i < local_argc; i++) {
2743                 const char *myp;
2744                 for (myp = local_argv[i]; *myp; myp++)
2745                     switch (*myp) {
2746                     case '<':
2747                         BIO_puts(io, "&lt;");
2748                         break;
2749                     case '>':
2750                         BIO_puts(io, "&gt;");
2751                         break;
2752                     case '&':
2753                         BIO_puts(io, "&amp;");
2754                         break;
2755                     default:
2756                         BIO_write(io, myp, 1);
2757                         break;
2758                     }
2759                 BIO_write(io, " ", 1);
2760             }
2761             BIO_puts(io, "\n");
2762
2763             BIO_printf(io,
2764                        "Secure Renegotiation IS%s supported\n",
2765                        SSL_get_secure_renegotiation_support(con) ?
2766                        "" : " NOT");
2767
2768             /*
2769              * The following is evil and should not really be done
2770              */
2771             BIO_printf(io, "Ciphers supported in s_server binary\n");
2772             sk = SSL_get_ciphers(con);
2773             j = sk_SSL_CIPHER_num(sk);
2774             for (i = 0; i < j; i++) {
2775                 c = sk_SSL_CIPHER_value(sk, i);
2776                 BIO_printf(io, "%-11s:%-25s ",
2777                            SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2778                 if ((((i + 1) % 2) == 0) && (i + 1 != j))
2779                     BIO_puts(io, "\n");
2780             }
2781             BIO_puts(io, "\n");
2782             p = SSL_get_shared_ciphers(con, buf, bufsize);
2783             if (p != NULL) {
2784                 BIO_printf(io,
2785                            "---\nCiphers common between both SSL end points:\n");
2786                 j = i = 0;
2787                 while (*p) {
2788                     if (*p == ':') {
2789                         BIO_write(io, space, 26 - j);
2790                         i++;
2791                         j = 0;
2792                         BIO_write(io, ((i % 3) ? " " : "\n"), 1);
2793                     } else {
2794                         BIO_write(io, p, 1);
2795                         j++;
2796                     }
2797                     p++;
2798                 }
2799                 BIO_puts(io, "\n");
2800             }
2801             ssl_print_sigalgs(io, con);
2802 #ifndef OPENSSL_NO_EC
2803             ssl_print_curves(io, con, 0);
2804 #endif
2805             BIO_printf(io, (SSL_cache_hit(con)
2806                             ? "---\nReused, " : "---\nNew, "));
2807             c = SSL_get_current_cipher(con);
2808             BIO_printf(io, "%s, Cipher is %s\n",
2809                        SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2810             SSL_SESSION_print(io, SSL_get_session(con));
2811             BIO_printf(io, "---\n");
2812             print_stats(io, SSL_get_SSL_CTX(con));
2813             BIO_printf(io, "---\n");
2814             peer = SSL_get_peer_certificate(con);
2815             if (peer != NULL) {
2816                 BIO_printf(io, "Client certificate\n");
2817                 X509_print(io, peer);
2818                 PEM_write_bio_X509(io, peer);
2819             } else
2820                 BIO_puts(io, "no client certificate available\n");
2821             BIO_puts(io, "</BODY></HTML>\r\n\r\n");
2822             break;
2823         } else if ((www == 2 || www == 3)
2824                    && (strncmp("GET /", buf, 5) == 0)) {
2825             BIO *file;
2826             char *p, *e;
2827             static const char *text =
2828                 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2829
2830             /* skip the '/' */
2831             p = &(buf[5]);
2832
2833             dot = 1;
2834             for (e = p; *e != '\0'; e++) {
2835                 if (e[0] == ' ')
2836                     break;
2837
2838                 switch (dot) {
2839                 case 1:
2840                     dot = (e[0] == '.') ? 2 : 0;
2841                     break;
2842                 case 2:
2843                     dot = (e[0] == '.') ? 3 : 0;
2844                     break;
2845                 case 3:
2846                     dot = (e[0] == '/') ? -1 : 0;
2847                     break;
2848                 }
2849                 if (dot == 0)
2850                     dot = (e[0] == '/') ? 1 : 0;
2851             }
2852             dot = (dot == 3) || (dot == -1); /* filename contains ".."
2853                                               * component */
2854
2855             if (*e == '\0') {
2856                 BIO_puts(io, text);
2857                 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
2858                 break;
2859             }
2860             *e = '\0';
2861
2862             if (dot) {
2863                 BIO_puts(io, text);
2864                 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
2865                 break;
2866             }
2867
2868             if (*p == '/') {
2869                 BIO_puts(io, text);
2870                 BIO_printf(io, "'%s' is an invalid path\r\n", p);
2871                 break;
2872             }
2873
2874             /* if a directory, do the index thang */
2875             if (app_isdir(p) > 0) {
2876                 BIO_puts(io, text);
2877                 BIO_printf(io, "'%s' is a directory\r\n", p);
2878                 break;
2879             }
2880
2881             if ((file = BIO_new_file(p, "r")) == NULL) {
2882                 BIO_puts(io, text);
2883                 BIO_printf(io, "Error opening '%s'\r\n", p);
2884                 ERR_print_errors(io);
2885                 break;
2886             }
2887
2888             if (!s_quiet)
2889                 BIO_printf(bio_err, "FILE:%s\n", p);
2890
2891             if (www == 2) {
2892                 i = strlen(p);
2893                 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
2894                     ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
2895                     ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
2896                     BIO_puts(io,
2897                              "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2898                 else
2899                     BIO_puts(io,
2900                              "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2901             }
2902             /* send the file */
2903             for (;;) {
2904                 i = BIO_read(file, buf, bufsize);
2905                 if (i <= 0)
2906                     break;
2907
2908 #ifdef RENEG
2909                 total_bytes += i;
2910                 BIO_printf(bio_err, "%d\n", i);
2911                 if (total_bytes > 3 * 1024) {
2912                     total_bytes = 0;
2913                     BIO_printf(bio_err, "RENEGOTIATE\n");
2914                     SSL_renegotiate(con);
2915                 }
2916 #endif
2917
2918                 for (j = 0; j < i;) {
2919 #ifdef RENEG
2920                     {
2921                         static count = 0;
2922                         if (++count == 13) {
2923                             SSL_renegotiate(con);
2924                         }
2925                     }
2926 #endif
2927                     k = BIO_write(io, &(buf[j]), i - j);
2928                     if (k <= 0) {
2929                         if (!BIO_should_retry(io)  && !SSL_waiting_for_async(con))
2930                             goto write_error;
2931                         else {
2932                             BIO_printf(bio_s_out, "rwrite W BLOCK\n");
2933                         }
2934                     } else {
2935                         j += k;
2936                     }
2937                 }
2938             }
2939  write_error:
2940             BIO_free(file);
2941             break;
2942         }
2943     }
2944
2945     for (;;) {
2946         i = (int)BIO_flush(io);
2947         if (i <= 0) {
2948             if (!BIO_should_retry(io))
2949                 break;
2950         } else
2951             break;
2952     }
2953  end:
2954     /* make sure we re-use sessions */
2955     SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2956
2957  err:
2958     if (ret >= 0)
2959         BIO_printf(bio_s_out, "ACCEPT\n");
2960     OPENSSL_free(buf);
2961     BIO_free_all(io);
2962     return (ret);
2963 }
2964
2965 static int rev_body(char *hostname, int s, int stype, unsigned char *context)
2966 {
2967     char *buf = NULL;
2968     int i;
2969     int ret = 1;
2970     SSL *con;
2971     BIO *io, *ssl_bio, *sbio;
2972
2973     buf = app_malloc(bufsize, "server rev buffer");
2974     io = BIO_new(BIO_f_buffer());
2975     ssl_bio = BIO_new(BIO_f_ssl());
2976     if ((io == NULL) || (ssl_bio == NULL))
2977         goto err;
2978
2979     /* lets make the output buffer a reasonable size */
2980     if (!BIO_set_write_buffer_size(io, bufsize))
2981         goto err;
2982
2983     if ((con = SSL_new(ctx)) == NULL)
2984         goto err;
2985
2986     if (s_tlsextdebug) {
2987         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2988         SSL_set_tlsext_debug_arg(con, bio_s_out);
2989     }
2990     if (context && !SSL_set_session_id_context(con, context,
2991                         strlen((char *)context))) {
2992         ERR_print_errors(bio_err);
2993         goto err;
2994     }
2995
2996     sbio = BIO_new_socket(s, BIO_NOCLOSE);
2997     SSL_set_bio(con, sbio, sbio);
2998     SSL_set_accept_state(con);
2999
3000     BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3001     BIO_push(io, ssl_bio);
3002 #ifdef CHARSET_EBCDIC
3003     io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3004 #endif
3005
3006     if (s_debug) {
3007         SSL_set_debug(con, 1);
3008         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3009         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3010     }
3011     if (s_msg) {
3012 #ifndef OPENSSL_NO_SSL_TRACE
3013         if (s_msg == 2)
3014             SSL_set_msg_callback(con, SSL_trace);
3015         else
3016 #endif
3017             SSL_set_msg_callback(con, msg_cb);
3018         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3019     }
3020
3021     for (;;) {
3022         i = BIO_do_handshake(io);
3023         if (i > 0)
3024             break;
3025         if (!BIO_should_retry(io)) {
3026             BIO_puts(bio_err, "CONNECTION FAILURE\n");
3027             ERR_print_errors(bio_err);
3028             goto end;
3029         }
3030 #ifndef OPENSSL_NO_SRP
3031         if (BIO_should_io_special(io)
3032             && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3033             BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3034             srp_callback_parm.user =
3035                 SRP_VBASE_get_by_user(srp_callback_parm.vb,
3036                                       srp_callback_parm.login);
3037             if (srp_callback_parm.user)
3038                 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3039                            srp_callback_parm.user->info);
3040             else
3041                 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3042             continue;
3043         }
3044 #endif
3045     }
3046     BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3047     print_ssl_summary(con);
3048
3049     for (;;) {
3050         i = BIO_gets(io, buf, bufsize - 1);
3051         if (i < 0) {            /* error */
3052             if (!BIO_should_retry(io)) {
3053                 if (!s_quiet)
3054                     ERR_print_errors(bio_err);
3055                 goto err;
3056             } else {
3057                 BIO_printf(bio_s_out, "read R BLOCK\n");
3058 #ifndef OPENSSL_NO_SRP
3059                 if (BIO_should_io_special(io)
3060                     && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3061                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3062                     srp_callback_parm.user =
3063                         SRP_VBASE_get_by_user(srp_callback_parm.vb,
3064                                               srp_callback_parm.login);
3065                     if (srp_callback_parm.user)
3066                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
3067                                    srp_callback_parm.user->info);
3068                     else
3069                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
3070                     continue;
3071                 }
3072 #endif
3073 #if defined(OPENSSL_SYS_NETWARE)
3074                 delay(1000);
3075 #elif !defined(OPENSSL_SYS_MSDOS)
3076                 sleep(1);
3077 #endif
3078                 continue;
3079             }
3080         } else if (i == 0) {    /* end of input */
3081             ret = 1;
3082             BIO_printf(bio_err, "CONNECTION CLOSED\n");
3083             goto end;
3084         } else {
3085             char *p = buf + i - 1;
3086             while (i && (*p == '\n' || *p == '\r')) {
3087                 p--;
3088                 i--;
3089             }
3090             if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3091                 ret = 1;
3092                 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3093                 goto end;
3094             }
3095             BUF_reverse((unsigned char *)buf, NULL, i);
3096             buf[i] = '\n';
3097             BIO_write(io, buf, i + 1);
3098             for (;;) {
3099                 i = BIO_flush(io);
3100                 if (i > 0)
3101                     break;
3102                 if (!BIO_should_retry(io))
3103                     goto end;
3104             }
3105         }
3106     }
3107  end:
3108     /* make sure we re-use sessions */
3109     SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3110
3111  err:
3112
3113     OPENSSL_free(buf);
3114     BIO_free_all(io);
3115     return (ret);
3116 }
3117
3118 #define MAX_SESSION_ID_ATTEMPTS 10
3119 static int generate_session_id(const SSL *ssl, unsigned char *id,
3120                                unsigned int *id_len)
3121 {
3122     unsigned int count = 0;
3123     do {
3124         if (RAND_bytes(id, *id_len) <= 0)
3125             return 0;
3126         /*
3127          * Prefix the session_id with the required prefix. NB: If our prefix
3128          * is too long, clip it - but there will be worse effects anyway, eg.
3129          * the server could only possibly create 1 session ID (ie. the
3130          * prefix!) so all future session negotiations will fail due to
3131          * conflicts.
3132          */
3133         memcpy(id, session_id_prefix,
3134                (strlen(session_id_prefix) < *id_len) ?
3135                strlen(session_id_prefix) : *id_len);
3136     }
3137     while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3138            (++count < MAX_SESSION_ID_ATTEMPTS));
3139     if (count >= MAX_SESSION_ID_ATTEMPTS)
3140         return 0;
3141     return 1;
3142 }
3143
3144 /*
3145  * By default s_server uses an in-memory cache which caches SSL_SESSION
3146  * structures without any serialisation. This hides some bugs which only
3147  * become apparent in deployed servers. By implementing a basic external
3148  * session cache some issues can be debugged using s_server.
3149  */
3150
3151 typedef struct simple_ssl_session_st {
3152     unsigned char *id;
3153     unsigned int idlen;
3154     unsigned char *der;
3155     int derlen;
3156     struct simple_ssl_session_st *next;
3157 } simple_ssl_session;
3158
3159 static simple_ssl_session *first = NULL;
3160
3161 static int add_session(SSL *ssl, SSL_SESSION *session)
3162 {
3163     simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3164     unsigned char *p;
3165
3166     SSL_SESSION_get_id(session, &sess->idlen);
3167     sess->derlen = i2d_SSL_SESSION(session, NULL);
3168     if (sess->derlen < 0) {
3169         BIO_printf(bio_err, "Error encoding session\n");
3170         OPENSSL_free(sess);
3171         return 0;
3172     }
3173
3174     sess->id = BUF_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3175     sess->der = app_malloc(sess->derlen, "get session buffer");
3176     if (!sess->id) {
3177         BIO_printf(bio_err, "Out of memory adding to external cache\n");
3178         OPENSSL_free(sess->id);
3179         OPENSSL_free(sess->der);
3180         OPENSSL_free(sess);
3181         return 0;
3182     }
3183     p = sess->der;
3184
3185     /* Assume it still works. */
3186     if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3187         BIO_printf(bio_err, "Unexpected session encoding length\n");
3188         OPENSSL_free(sess->id);
3189         OPENSSL_free(sess->der);
3190         OPENSSL_free(sess);
3191         return 0;
3192     }
3193
3194     sess->next = first;
3195     first = sess;
3196     BIO_printf(bio_err, "New session added to external cache\n");
3197     return 0;
3198 }
3199
3200 static SSL_SESSION *get_session(SSL *ssl, unsigned char *id, int idlen,
3201                                 int *do_copy)
3202 {
3203     simple_ssl_session *sess;
3204     *do_copy = 0;
3205     for (sess = first; sess; sess = sess->next) {
3206         if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3207             const unsigned char *p = sess->der;
3208             BIO_printf(bio_err, "Lookup session: cache hit\n");
3209             return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3210         }
3211     }
3212     BIO_printf(bio_err, "Lookup session: cache miss\n");
3213     return NULL;
3214 }
3215
3216 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3217 {
3218     simple_ssl_session *sess, *prev = NULL;
3219     const unsigned char *id;
3220     unsigned int idlen;
3221     id = SSL_SESSION_get_id(session, &idlen);
3222     for (sess = first; sess; sess = sess->next) {
3223         if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3224             if (prev)
3225                 prev->next = sess->next;
3226             else
3227                 first = sess->next;
3228             OPENSSL_free(sess->id);
3229             OPENSSL_free(sess->der);
3230             OPENSSL_free(sess);
3231             return;
3232         }
3233         prev = sess;
3234     }
3235 }
3236
3237 static void init_session_cache_ctx(SSL_CTX *sctx)
3238 {
3239     SSL_CTX_set_session_cache_mode(sctx,
3240                                    SSL_SESS_CACHE_NO_INTERNAL |
3241                                    SSL_SESS_CACHE_SERVER);
3242     SSL_CTX_sess_set_new_cb(sctx, add_session);
3243     SSL_CTX_sess_set_get_cb(sctx, get_session);
3244     SSL_CTX_sess_set_remove_cb(sctx, del_session);
3245 }
3246
3247 static void free_sessions(void)
3248 {
3249     simple_ssl_session *sess, *tsess;
3250     for (sess = first; sess;) {
3251         OPENSSL_free(sess->id);
3252         OPENSSL_free(sess->der);
3253         tsess = sess;
3254         sess = sess->next;
3255         OPENSSL_free(tsess);
3256     }
3257     first = NULL;
3258 }