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