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