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