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