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