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