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