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