Test framework output improvement.
[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 const 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 error: client identity not found"
175                    " (got '%s' expected '%s')\n", identity, psk_identity);
176         goto out_err;
177     }
178     if (s_debug)
179         BIO_printf(bio_s_out, "PSK client identity found\n");
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_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_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
873     {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
874 #endif
875 #ifndef OPENSSL_NO_SRP
876     {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
877     {"srpuserseed", OPT_SRPUSERSEED, 's',
878      "A seed string for a default user salt"},
879 #endif
880 #ifndef OPENSSL_NO_SSL3
881     {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
882 #endif
883 #ifndef OPENSSL_NO_TLS1
884     {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
885 #endif
886 #ifndef OPENSSL_NO_TLS1_1
887     {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
888 #endif
889 #ifndef OPENSSL_NO_TLS1_2
890     {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
891 #endif
892 #ifndef OPENSSL_NO_TLS1_3
893     {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
894 #endif
895 #ifndef OPENSSL_NO_DTLS
896     {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
897     {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
898     {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
899     {"listen", OPT_LISTEN, '-',
900      "Listen for a DTLS ClientHello with a cookie and then connect"},
901 #endif
902 #ifndef OPENSSL_NO_DTLS1
903     {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
904 #endif
905 #ifndef OPENSSL_NO_DTLS1_2
906     {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
907 #endif
908 #ifndef OPENSSL_NO_SCTP
909     {"sctp", OPT_SCTP, '-', "Use SCTP"},
910 #endif
911 #ifndef OPENSSL_NO_DH
912     {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
913 #endif
914 #ifndef OPENSSL_NO_NEXTPROTONEG
915     {"nextprotoneg", OPT_NEXTPROTONEG, 's',
916      "Set the advertised protocols for the NPN extension (comma-separated list)"},
917 #endif
918 #ifndef OPENSSL_NO_SRTP
919     {"use_srtp", OPT_SRTP_PROFILES, 's',
920      "Offer SRTP key management with a colon-separated profile list"},
921 #endif
922     {"alpn", OPT_ALPN, 's',
923      "Set the advertised protocols for the ALPN extension (comma-separated list)"},
924 #ifndef OPENSSL_NO_ENGINE
925     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
926 #endif
927     {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
928     {"max_early_data", OPT_MAX_EARLY, 'n',
929      "The maximum number of bytes of early data"},
930     {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
931     {NULL, OPT_EOF, 0, NULL}
932 };
933
934 #define IS_PROT_FLAG(o) \
935  (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
936   || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
937
938 int s_server_main(int argc, char *argv[])
939 {
940     ENGINE *engine = NULL;
941     EVP_PKEY *s_key = NULL, *s_dkey = NULL;
942     SSL_CONF_CTX *cctx = NULL;
943     const SSL_METHOD *meth = TLS_server_method();
944     SSL_EXCERT *exc = NULL;
945     STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
946     STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
947     STACK_OF(X509_CRL) *crls = NULL;
948     X509 *s_cert = NULL, *s_dcert = NULL;
949     X509_VERIFY_PARAM *vpm = NULL;
950     const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
951     char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
952     char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
953     char *crl_file = NULL, *prog;
954 #ifdef AF_UNIX
955     int unlink_unix_path = 0;
956 #endif
957     do_server_cb server_cb;
958     int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
959 #ifndef OPENSSL_NO_DH
960     char *dhfile = NULL;
961     int no_dhe = 0;
962 #endif
963     int nocert = 0, ret = 1;
964     int noCApath = 0, noCAfile = 0;
965     int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
966     int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
967     int rev = 0, naccept = -1, sdebug = 0;
968     int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
969     int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
970     char *host = NULL;
971     char *port = BUF_strdup(PORT);
972     unsigned char *context = NULL;
973     OPTION_CHOICE o;
974     EVP_PKEY *s_key2 = NULL;
975     X509 *s_cert2 = NULL;
976     tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
977     const char *ssl_config = NULL;
978     int read_buf_len = 0;
979 #ifndef OPENSSL_NO_NEXTPROTONEG
980     const char *next_proto_neg_in = NULL;
981     tlsextnextprotoctx next_proto = { NULL, 0 };
982 #endif
983     const char *alpn_in = NULL;
984     tlsextalpnctx alpn_ctx = { NULL, 0 };
985 #ifndef OPENSSL_NO_PSK
986     /* by default do not send a PSK identity hint */
987     char *psk_identity_hint = NULL;
988     char *p;
989 #endif
990 #ifndef OPENSSL_NO_SRP
991     char *srpuserseed = NULL;
992     char *srp_verifier_file = NULL;
993 #endif
994     int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
995     int s_server_verify = SSL_VERIFY_NONE;
996     int s_server_session_id_context = 1; /* anything will do */
997     const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
998     const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
999     char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
1000 #ifndef OPENSSL_NO_OCSP
1001     int s_tlsextstatus = 0;
1002 #endif
1003     int no_resume_ephemeral = 0;
1004     unsigned int max_send_fragment = 0;
1005     unsigned int split_send_fragment = 0, max_pipelines = 0;
1006     const char *s_serverinfo_file = NULL;
1007     const char *keylog_file = NULL;
1008     int max_early_data = -1;
1009
1010     /* Init of few remaining global variables */
1011     local_argc = argc;
1012     local_argv = argv;
1013
1014     ctx = ctx2 = NULL;
1015     s_nbio = s_nbio_test = 0;
1016     www = 0;
1017     bio_s_out = NULL;
1018     s_debug = 0;
1019     s_msg = 0;
1020     s_quiet = 0;
1021     s_brief = 0;
1022     async = 0;
1023
1024     cctx = SSL_CONF_CTX_new();
1025     vpm = X509_VERIFY_PARAM_new();
1026     if (cctx == NULL || vpm == NULL)
1027         goto end;
1028     SSL_CONF_CTX_set_flags(cctx,
1029                            SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1030
1031     prog = opt_init(argc, argv, s_server_options);
1032     while ((o = opt_next()) != OPT_EOF) {
1033         if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1034             BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1035             goto end;
1036         }
1037         if (IS_NO_PROT_FLAG(o))
1038             no_prot_opt++;
1039         if (prot_opt == 1 && no_prot_opt) {
1040             BIO_printf(bio_err,
1041                        "Cannot supply both a protocol flag and '-no_<prot>'\n");
1042             goto end;
1043         }
1044         switch (o) {
1045         case OPT_EOF:
1046         case OPT_ERR:
1047  opthelp:
1048             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1049             goto end;
1050         case OPT_HELP:
1051             opt_help(s_server_options);
1052             ret = 0;
1053             goto end;
1054
1055         case OPT_4:
1056 #ifdef AF_UNIX
1057             if (socket_family == AF_UNIX) {
1058                 OPENSSL_free(host); host = NULL;
1059                 OPENSSL_free(port); port = NULL;
1060             }
1061 #endif
1062             socket_family = AF_INET;
1063             break;
1064         case OPT_6:
1065             if (1) {
1066 #ifdef AF_INET6
1067 #ifdef AF_UNIX
1068                 if (socket_family == AF_UNIX) {
1069                     OPENSSL_free(host); host = NULL;
1070                     OPENSSL_free(port); port = NULL;
1071                 }
1072 #endif
1073                 socket_family = AF_INET6;
1074             } else {
1075 #endif
1076                 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1077                 goto end;
1078             }
1079             break;
1080         case OPT_PORT:
1081 #ifdef AF_UNIX
1082             if (socket_family == AF_UNIX) {
1083                 socket_family = AF_UNSPEC;
1084             }
1085 #endif
1086             OPENSSL_free(port); port = NULL;
1087             OPENSSL_free(host); host = NULL;
1088             if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1089                 BIO_printf(bio_err,
1090                            "%s: -port argument malformed or ambiguous\n",
1091                            port);
1092                 goto end;
1093             }
1094             break;
1095         case OPT_ACCEPT:
1096 #ifdef AF_UNIX
1097             if (socket_family == AF_UNIX) {
1098                 socket_family = AF_UNSPEC;
1099             }
1100 #endif
1101             OPENSSL_free(port); port = NULL;
1102             OPENSSL_free(host); host = NULL;
1103             if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1104                 BIO_printf(bio_err,
1105                            "%s: -accept argument malformed or ambiguous\n",
1106                            port);
1107                 goto end;
1108             }
1109             break;
1110 #ifdef AF_UNIX
1111         case OPT_UNIX:
1112             socket_family = AF_UNIX;
1113             OPENSSL_free(host); host = BUF_strdup(opt_arg());
1114             OPENSSL_free(port); port = NULL;
1115             break;
1116         case OPT_UNLINK:
1117             unlink_unix_path = 1;
1118             break;
1119 #endif
1120         case OPT_NACCEPT:
1121             naccept = atol(opt_arg());
1122             break;
1123         case OPT_VERIFY:
1124             s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1125             verify_args.depth = atoi(opt_arg());
1126             if (!s_quiet)
1127                 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1128             break;
1129         case OPT_UPPER_V_VERIFY:
1130             s_server_verify =
1131                 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1132                 SSL_VERIFY_CLIENT_ONCE;
1133             verify_args.depth = atoi(opt_arg());
1134             if (!s_quiet)
1135                 BIO_printf(bio_err,
1136                            "verify depth is %d, must return a certificate\n",
1137                            verify_args.depth);
1138             break;
1139         case OPT_CONTEXT:
1140             context = (unsigned char *)opt_arg();
1141             break;
1142         case OPT_CERT:
1143             s_cert_file = opt_arg();
1144             break;
1145         case OPT_NAMEOPT:
1146             if (!set_nameopt(opt_arg()))
1147                 goto end;
1148             break;
1149         case OPT_CRL:
1150             crl_file = opt_arg();
1151             break;
1152         case OPT_CRL_DOWNLOAD:
1153             crl_download = 1;
1154             break;
1155         case OPT_SERVERINFO:
1156             s_serverinfo_file = opt_arg();
1157             break;
1158         case OPT_CERTFORM:
1159             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1160                 goto opthelp;
1161             break;
1162         case OPT_KEY:
1163             s_key_file = opt_arg();
1164             break;
1165         case OPT_KEYFORM:
1166             if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1167                 goto opthelp;
1168             break;
1169         case OPT_PASS:
1170             passarg = opt_arg();
1171             break;
1172         case OPT_CERT_CHAIN:
1173             s_chain_file = opt_arg();
1174             break;
1175         case OPT_DHPARAM:
1176 #ifndef OPENSSL_NO_DH
1177             dhfile = opt_arg();
1178 #endif
1179             break;
1180         case OPT_DCERTFORM:
1181             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1182                 goto opthelp;
1183             break;
1184         case OPT_DCERT:
1185             s_dcert_file = opt_arg();
1186             break;
1187         case OPT_DKEYFORM:
1188             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1189                 goto opthelp;
1190             break;
1191         case OPT_DPASS:
1192             dpassarg = opt_arg();
1193             break;
1194         case OPT_DKEY:
1195             s_dkey_file = opt_arg();
1196             break;
1197         case OPT_DCERT_CHAIN:
1198             s_dchain_file = opt_arg();
1199             break;
1200         case OPT_NOCERT:
1201             nocert = 1;
1202             break;
1203         case OPT_CAPATH:
1204             CApath = opt_arg();
1205             break;
1206         case OPT_NOCAPATH:
1207             noCApath = 1;
1208             break;
1209         case OPT_CHAINCAPATH:
1210             chCApath = opt_arg();
1211             break;
1212         case OPT_VERIFYCAPATH:
1213             vfyCApath = opt_arg();
1214             break;
1215         case OPT_NO_CACHE:
1216             no_cache = 1;
1217             break;
1218         case OPT_EXT_CACHE:
1219             ext_cache = 1;
1220             break;
1221         case OPT_CRLFORM:
1222             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1223                 goto opthelp;
1224             break;
1225         case OPT_S_CASES:
1226             if (ssl_args == NULL)
1227                 ssl_args = sk_OPENSSL_STRING_new_null();
1228             if (ssl_args == NULL
1229                 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1230                 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1231                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1232                 goto end;
1233             }
1234             break;
1235         case OPT_V_CASES:
1236             if (!opt_verify(o, vpm))
1237                 goto end;
1238             vpmtouched++;
1239             break;
1240         case OPT_X_CASES:
1241             if (!args_excert(o, &exc))
1242                 goto end;
1243             break;
1244         case OPT_VERIFY_RET_ERROR:
1245             verify_args.return_error = 1;
1246             break;
1247         case OPT_VERIFY_QUIET:
1248             verify_args.quiet = 1;
1249             break;
1250         case OPT_BUILD_CHAIN:
1251             build_chain = 1;
1252             break;
1253         case OPT_CAFILE:
1254             CAfile = opt_arg();
1255             break;
1256         case OPT_NOCAFILE:
1257             noCAfile = 1;
1258             break;
1259         case OPT_CHAINCAFILE:
1260             chCAfile = opt_arg();
1261             break;
1262         case OPT_VERIFYCAFILE:
1263             vfyCAfile = opt_arg();
1264             break;
1265         case OPT_NBIO:
1266             s_nbio = 1;
1267             break;
1268         case OPT_NBIO_TEST:
1269             s_nbio = s_nbio_test = 1;
1270             break;
1271         case OPT_IGN_EOF:
1272             s_ign_eof = 1;
1273             break;
1274         case OPT_NO_IGN_EOF:
1275             s_ign_eof = 0;
1276             break;
1277         case OPT_DEBUG:
1278             s_debug = 1;
1279             break;
1280         case OPT_TLSEXTDEBUG:
1281             s_tlsextdebug = 1;
1282             break;
1283         case OPT_STATUS:
1284 #ifndef OPENSSL_NO_OCSP
1285             s_tlsextstatus = 1;
1286 #endif
1287             break;
1288         case OPT_STATUS_VERBOSE:
1289 #ifndef OPENSSL_NO_OCSP
1290             s_tlsextstatus = tlscstatp.verbose = 1;
1291 #endif
1292             break;
1293         case OPT_STATUS_TIMEOUT:
1294 #ifndef OPENSSL_NO_OCSP
1295             s_tlsextstatus = 1;
1296             tlscstatp.timeout = atoi(opt_arg());
1297 #endif
1298             break;
1299         case OPT_STATUS_URL:
1300 #ifndef OPENSSL_NO_OCSP
1301             s_tlsextstatus = 1;
1302             if (!OCSP_parse_url(opt_arg(),
1303                                 &tlscstatp.host,
1304                                 &tlscstatp.port,
1305                                 &tlscstatp.path, &tlscstatp.use_ssl)) {
1306                 BIO_printf(bio_err, "Error parsing URL\n");
1307                 goto end;
1308             }
1309 #endif
1310             break;
1311         case OPT_STATUS_FILE:
1312 #ifndef OPENSSL_NO_OCSP
1313             s_tlsextstatus = 1;
1314             tlscstatp.respin = opt_arg();
1315 #endif
1316             break;
1317         case OPT_MSG:
1318             s_msg = 1;
1319             break;
1320         case OPT_MSGFILE:
1321             bio_s_msg = BIO_new_file(opt_arg(), "w");
1322             break;
1323         case OPT_TRACE:
1324 #ifndef OPENSSL_NO_SSL_TRACE
1325             s_msg = 2;
1326 #endif
1327             break;
1328         case OPT_SECURITY_DEBUG:
1329             sdebug = 1;
1330             break;
1331         case OPT_SECURITY_DEBUG_VERBOSE:
1332             sdebug = 2;
1333             break;
1334         case OPT_STATE:
1335             state = 1;
1336             break;
1337         case OPT_CRLF:
1338             s_crlf = 1;
1339             break;
1340         case OPT_QUIET:
1341             s_quiet = 1;
1342             break;
1343         case OPT_BRIEF:
1344             s_quiet = s_brief = verify_args.quiet = 1;
1345             break;
1346         case OPT_NO_DHE:
1347 #ifndef OPENSSL_NO_DH
1348             no_dhe = 1;
1349 #endif
1350             break;
1351         case OPT_NO_RESUME_EPHEMERAL:
1352             no_resume_ephemeral = 1;
1353             break;
1354         case OPT_PSK_HINT:
1355 #ifndef OPENSSL_NO_PSK
1356             psk_identity_hint = opt_arg();
1357 #endif
1358             break;
1359         case OPT_PSK:
1360 #ifndef OPENSSL_NO_PSK
1361             for (p = psk_key = opt_arg(); *p; p++) {
1362                 if (isxdigit(_UC(*p)))
1363                     continue;
1364                 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1365                 goto end;
1366             }
1367 #endif
1368             break;
1369         case OPT_SRPVFILE:
1370 #ifndef OPENSSL_NO_SRP
1371             srp_verifier_file = opt_arg();
1372             if (min_version < TLS1_VERSION)
1373                 min_version = TLS1_VERSION;
1374 #endif
1375             break;
1376         case OPT_SRPUSERSEED:
1377 #ifndef OPENSSL_NO_SRP
1378             srpuserseed = opt_arg();
1379             if (min_version < TLS1_VERSION)
1380                 min_version = TLS1_VERSION;
1381 #endif
1382             break;
1383         case OPT_REV:
1384             rev = 1;
1385             break;
1386         case OPT_WWW:
1387             www = 1;
1388             break;
1389         case OPT_UPPER_WWW:
1390             www = 2;
1391             break;
1392         case OPT_HTTP:
1393             www = 3;
1394             break;
1395         case OPT_SSL_CONFIG:
1396             ssl_config = opt_arg();
1397             break;
1398         case OPT_SSL3:
1399             min_version = SSL3_VERSION;
1400             max_version = SSL3_VERSION;
1401             break;
1402         case OPT_TLS1_3:
1403             min_version = TLS1_3_VERSION;
1404             max_version = TLS1_3_VERSION;
1405             break;
1406         case OPT_TLS1_2:
1407             min_version = TLS1_2_VERSION;
1408             max_version = TLS1_2_VERSION;
1409             break;
1410         case OPT_TLS1_1:
1411             min_version = TLS1_1_VERSION;
1412             max_version = TLS1_1_VERSION;
1413             break;
1414         case OPT_TLS1:
1415             min_version = TLS1_VERSION;
1416             max_version = TLS1_VERSION;
1417             break;
1418         case OPT_DTLS:
1419 #ifndef OPENSSL_NO_DTLS
1420             meth = DTLS_server_method();
1421             socket_type = SOCK_DGRAM;
1422 #endif
1423             break;
1424         case OPT_DTLS1:
1425 #ifndef OPENSSL_NO_DTLS
1426             meth = DTLS_server_method();
1427             min_version = DTLS1_VERSION;
1428             max_version = DTLS1_VERSION;
1429             socket_type = SOCK_DGRAM;
1430 #endif
1431             break;
1432         case OPT_DTLS1_2:
1433 #ifndef OPENSSL_NO_DTLS
1434             meth = DTLS_server_method();
1435             min_version = DTLS1_2_VERSION;
1436             max_version = DTLS1_2_VERSION;
1437             socket_type = SOCK_DGRAM;
1438 #endif
1439             break;
1440         case OPT_SCTP:
1441 #ifndef OPENSSL_NO_SCTP
1442             protocol = IPPROTO_SCTP;
1443 #endif
1444             break;
1445         case OPT_TIMEOUT:
1446 #ifndef OPENSSL_NO_DTLS
1447             enable_timeouts = 1;
1448 #endif
1449             break;
1450         case OPT_MTU:
1451 #ifndef OPENSSL_NO_DTLS
1452             socket_mtu = atol(opt_arg());
1453 #endif
1454             break;
1455         case OPT_LISTEN:
1456 #ifndef OPENSSL_NO_DTLS
1457             dtlslisten = 1;
1458 #endif
1459             break;
1460         case OPT_ID_PREFIX:
1461             session_id_prefix = opt_arg();
1462             break;
1463         case OPT_ENGINE:
1464             engine = setup_engine(opt_arg(), 1);
1465             break;
1466         case OPT_RAND:
1467             inrand = opt_arg();
1468             break;
1469         case OPT_SERVERNAME:
1470             tlsextcbp.servername = opt_arg();
1471             break;
1472         case OPT_SERVERNAME_FATAL:
1473             tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1474             break;
1475         case OPT_CERT2:
1476             s_cert_file2 = opt_arg();
1477             break;
1478         case OPT_KEY2:
1479             s_key_file2 = opt_arg();
1480             break;
1481         case OPT_NEXTPROTONEG:
1482 # ifndef OPENSSL_NO_NEXTPROTONEG
1483             next_proto_neg_in = opt_arg();
1484 #endif
1485             break;
1486         case OPT_ALPN:
1487             alpn_in = opt_arg();
1488             break;
1489         case OPT_SRTP_PROFILES:
1490 #ifndef OPENSSL_NO_SRTP
1491             srtp_profiles = opt_arg();
1492 #endif
1493             break;
1494         case OPT_KEYMATEXPORT:
1495             keymatexportlabel = opt_arg();
1496             break;
1497         case OPT_KEYMATEXPORTLEN:
1498             keymatexportlen = atoi(opt_arg());
1499             break;
1500         case OPT_ASYNC:
1501             async = 1;
1502             break;
1503         case OPT_MAX_SEND_FRAG:
1504             max_send_fragment = atoi(opt_arg());
1505             break;
1506         case OPT_SPLIT_SEND_FRAG:
1507             split_send_fragment = atoi(opt_arg());
1508             break;
1509         case OPT_MAX_PIPELINES:
1510             max_pipelines = atoi(opt_arg());
1511             break;
1512         case OPT_READ_BUF:
1513             read_buf_len = atoi(opt_arg());
1514             break;
1515         case OPT_KEYLOG_FILE:
1516             keylog_file = opt_arg();
1517             break;
1518         case OPT_MAX_EARLY:
1519             max_early_data = atoi(opt_arg());
1520             if (max_early_data < 0) {
1521                 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1522                 goto end;
1523             }
1524             break;
1525         case OPT_EARLY_DATA:
1526             early_data = 1;
1527             break;
1528         }
1529     }
1530     argc = opt_num_rest();
1531     argv = opt_rest();
1532
1533 #ifndef OPENSSL_NO_DTLS
1534     if (www && socket_type == SOCK_DGRAM) {
1535         BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1536         goto end;
1537     }
1538
1539     if (dtlslisten && socket_type != SOCK_DGRAM) {
1540         BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1541         goto end;
1542     }
1543 #endif
1544
1545 #ifdef AF_UNIX
1546     if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1547         BIO_printf(bio_err,
1548                    "Can't use unix sockets and datagrams together\n");
1549         goto end;
1550     }
1551 #endif
1552
1553 #ifndef OPENSSL_NO_SCTP
1554     if (protocol == IPPROTO_SCTP) {
1555         if (socket_type != SOCK_DGRAM) {
1556             BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1557             goto end;
1558         }
1559         /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1560         socket_type = SOCK_STREAM;
1561     }
1562 #endif
1563
1564     if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1565         BIO_printf(bio_err, "Error getting password\n");
1566         goto end;
1567     }
1568
1569     if (s_key_file == NULL)
1570         s_key_file = s_cert_file;
1571
1572     if (s_key_file2 == NULL)
1573         s_key_file2 = s_cert_file2;
1574
1575     if (!load_excert(&exc))
1576         goto end;
1577
1578     if (nocert == 0) {
1579         s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1580                          "server certificate private key file");
1581         if (!s_key) {
1582             ERR_print_errors(bio_err);
1583             goto end;
1584         }
1585
1586         s_cert = load_cert(s_cert_file, s_cert_format,
1587                            "server certificate file");
1588
1589         if (!s_cert) {
1590             ERR_print_errors(bio_err);
1591             goto end;
1592         }
1593         if (s_chain_file) {
1594             if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1595                             "server certificate chain"))
1596                 goto end;
1597         }
1598
1599         if (tlsextcbp.servername) {
1600             s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1601                               "second server certificate private key file");
1602             if (!s_key2) {
1603                 ERR_print_errors(bio_err);
1604                 goto end;
1605             }
1606
1607             s_cert2 = load_cert(s_cert_file2, s_cert_format,
1608                                 "second server certificate file");
1609
1610             if (!s_cert2) {
1611                 ERR_print_errors(bio_err);
1612                 goto end;
1613             }
1614         }
1615     }
1616 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1617     if (next_proto_neg_in) {
1618         next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1619         if (next_proto.data == NULL)
1620             goto end;
1621     }
1622 #endif
1623     alpn_ctx.data = NULL;
1624     if (alpn_in) {
1625         alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1626         if (alpn_ctx.data == NULL)
1627             goto end;
1628     }
1629
1630     if (crl_file) {
1631         X509_CRL *crl;
1632         crl = load_crl(crl_file, crl_format);
1633         if (!crl) {
1634             BIO_puts(bio_err, "Error loading CRL\n");
1635             ERR_print_errors(bio_err);
1636             goto end;
1637         }
1638         crls = sk_X509_CRL_new_null();
1639         if (!crls || !sk_X509_CRL_push(crls, crl)) {
1640             BIO_puts(bio_err, "Error adding CRL\n");
1641             ERR_print_errors(bio_err);
1642             X509_CRL_free(crl);
1643             goto end;
1644         }
1645     }
1646
1647     if (s_dcert_file) {
1648
1649         if (s_dkey_file == NULL)
1650             s_dkey_file = s_dcert_file;
1651
1652         s_dkey = load_key(s_dkey_file, s_dkey_format,
1653                           0, dpass, engine, "second certificate private key file");
1654         if (!s_dkey) {
1655             ERR_print_errors(bio_err);
1656             goto end;
1657         }
1658
1659         s_dcert = load_cert(s_dcert_file, s_dcert_format,
1660                             "second server certificate file");
1661
1662         if (!s_dcert) {
1663             ERR_print_errors(bio_err);
1664             goto end;
1665         }
1666         if (s_dchain_file) {
1667             if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1668                             "second server certificate chain"))
1669                 goto end;
1670         }
1671
1672     }
1673
1674     if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1675         && !RAND_status()) {
1676         BIO_printf(bio_err,
1677                    "warning, not much extra random data, consider using the -rand option\n");
1678     }
1679     if (inrand != NULL)
1680         BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1681                    app_RAND_load_files(inrand));
1682
1683     if (bio_s_out == NULL) {
1684         if (s_quiet && !s_debug) {
1685             bio_s_out = BIO_new(BIO_s_null());
1686             if (s_msg && !bio_s_msg)
1687                 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1688         } else {
1689             if (bio_s_out == NULL)
1690                 bio_s_out = dup_bio_out(FORMAT_TEXT);
1691         }
1692     }
1693 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1694     if (nocert)
1695 #endif
1696     {
1697         s_cert_file = NULL;
1698         s_key_file = NULL;
1699         s_dcert_file = NULL;
1700         s_dkey_file = NULL;
1701         s_cert_file2 = NULL;
1702         s_key_file2 = NULL;
1703     }
1704
1705     ctx = SSL_CTX_new(meth);
1706     if (ctx == NULL) {
1707         ERR_print_errors(bio_err);
1708         goto end;
1709     }
1710     if (sdebug)
1711         ssl_ctx_security_debug(ctx, sdebug);
1712     if (ssl_config) {
1713         if (SSL_CTX_config(ctx, ssl_config) == 0) {
1714             BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1715                        ssl_config);
1716             ERR_print_errors(bio_err);
1717             goto end;
1718         }
1719     }
1720     if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1721         goto end;
1722     if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1723         goto end;
1724
1725     if (session_id_prefix) {
1726         if (strlen(session_id_prefix) >= 32)
1727             BIO_printf(bio_err,
1728                        "warning: id_prefix is too long, only one new session will be possible\n");
1729         if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1730             BIO_printf(bio_err, "error setting 'id_prefix'\n");
1731             ERR_print_errors(bio_err);
1732             goto end;
1733         }
1734         BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1735     }
1736     SSL_CTX_set_quiet_shutdown(ctx, 1);
1737     if (exc)
1738         ssl_ctx_set_excert(ctx, exc);
1739
1740     if (state)
1741         SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1742     if (no_cache)
1743         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1744     else if (ext_cache)
1745         init_session_cache_ctx(ctx);
1746     else
1747         SSL_CTX_sess_set_cache_size(ctx, 128);
1748
1749     if (async) {
1750         SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1751     }
1752
1753     if (max_send_fragment > 0
1754         && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1755         BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1756                    prog, max_send_fragment);
1757         goto end;
1758     }
1759
1760     if (split_send_fragment > 0
1761         && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1762         BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1763                    prog, split_send_fragment);
1764         goto end;
1765     }
1766     if (max_pipelines > 0
1767         && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1768         BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1769                    prog, max_pipelines);
1770         goto end;
1771     }
1772
1773     if (read_buf_len > 0) {
1774         SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1775     }
1776 #ifndef OPENSSL_NO_SRTP
1777     if (srtp_profiles != NULL) {
1778         /* Returns 0 on success! */
1779         if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1780             BIO_printf(bio_err, "Error setting SRTP profile\n");
1781             ERR_print_errors(bio_err);
1782             goto end;
1783         }
1784     }
1785 #endif
1786
1787     if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1788         ERR_print_errors(bio_err);
1789         goto end;
1790     }
1791     if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1792         BIO_printf(bio_err, "Error setting verify params\n");
1793         ERR_print_errors(bio_err);
1794         goto end;
1795     }
1796
1797     ssl_ctx_add_crls(ctx, crls, 0);
1798     if (!config_ctx(cctx, ssl_args, ctx))
1799         goto end;
1800
1801     if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1802                          crls, crl_download)) {
1803         BIO_printf(bio_err, "Error loading store locations\n");
1804         ERR_print_errors(bio_err);
1805         goto end;
1806     }
1807
1808     if (s_cert2) {
1809         ctx2 = SSL_CTX_new(meth);
1810         if (ctx2 == NULL) {
1811             ERR_print_errors(bio_err);
1812             goto end;
1813         }
1814     }
1815
1816     if (ctx2) {
1817         BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1818
1819         if (sdebug)
1820             ssl_ctx_security_debug(ctx, sdebug);
1821
1822         if (session_id_prefix) {
1823             if (strlen(session_id_prefix) >= 32)
1824                 BIO_printf(bio_err,
1825                            "warning: id_prefix is too long, only one new session will be possible\n");
1826             if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1827                 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1828                 ERR_print_errors(bio_err);
1829                 goto end;
1830             }
1831             BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1832         }
1833         SSL_CTX_set_quiet_shutdown(ctx2, 1);
1834         if (exc)
1835             ssl_ctx_set_excert(ctx2, exc);
1836
1837         if (state)
1838             SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1839
1840         if (no_cache)
1841             SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1842         else if (ext_cache)
1843             init_session_cache_ctx(ctx2);
1844         else
1845             SSL_CTX_sess_set_cache_size(ctx2, 128);
1846
1847         if (async)
1848             SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1849
1850         if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1851                                       noCApath)) {
1852             ERR_print_errors(bio_err);
1853             goto end;
1854         }
1855         if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1856             BIO_printf(bio_err, "Error setting verify params\n");
1857             ERR_print_errors(bio_err);
1858             goto end;
1859         }
1860
1861         ssl_ctx_add_crls(ctx2, crls, 0);
1862         if (!config_ctx(cctx, ssl_args, ctx2))
1863             goto end;
1864     }
1865 #ifndef OPENSSL_NO_NEXTPROTONEG
1866     if (next_proto.data)
1867         SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1868                                               &next_proto);
1869 #endif
1870     if (alpn_ctx.data)
1871         SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1872
1873 #ifndef OPENSSL_NO_DH
1874     if (!no_dhe) {
1875         DH *dh = NULL;
1876
1877         if (dhfile)
1878             dh = load_dh_param(dhfile);
1879         else if (s_cert_file)
1880             dh = load_dh_param(s_cert_file);
1881
1882         if (dh != NULL) {
1883             BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1884         } else {
1885             BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1886         }
1887         (void)BIO_flush(bio_s_out);
1888
1889         if (dh == NULL)
1890             SSL_CTX_set_dh_auto(ctx, 1);
1891         else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1892             BIO_puts(bio_err, "Error setting temp DH parameters\n");
1893             ERR_print_errors(bio_err);
1894             DH_free(dh);
1895             goto end;
1896         }
1897
1898         if (ctx2) {
1899             if (!dhfile) {
1900                 DH *dh2 = load_dh_param(s_cert_file2);
1901                 if (dh2 != NULL) {
1902                     BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1903                     (void)BIO_flush(bio_s_out);
1904
1905                     DH_free(dh);
1906                     dh = dh2;
1907                 }
1908             }
1909             if (dh == NULL)
1910                 SSL_CTX_set_dh_auto(ctx2, 1);
1911             else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1912                 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1913                 ERR_print_errors(bio_err);
1914                 DH_free(dh);
1915                 goto end;
1916             }
1917         }
1918         DH_free(dh);
1919     }
1920 #endif
1921
1922     if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1923         goto end;
1924
1925     if (s_serverinfo_file != NULL
1926         && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1927         ERR_print_errors(bio_err);
1928         goto end;
1929     }
1930
1931     if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1932         goto end;
1933
1934     if (s_dcert != NULL) {
1935         if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1936             goto end;
1937     }
1938
1939     if (no_resume_ephemeral) {
1940         SSL_CTX_set_not_resumable_session_callback(ctx,
1941                                                    not_resumable_sess_cb);
1942
1943         if (ctx2)
1944             SSL_CTX_set_not_resumable_session_callback(ctx2,
1945                                                        not_resumable_sess_cb);
1946     }
1947 #ifndef OPENSSL_NO_PSK
1948     if (psk_key != NULL) {
1949         if (s_debug)
1950             BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
1951         SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1952     }
1953
1954     if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1955         BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1956         ERR_print_errors(bio_err);
1957         goto end;
1958     }
1959 #endif
1960
1961     SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1962     if (!SSL_CTX_set_session_id_context(ctx,
1963                                         (void *)&s_server_session_id_context,
1964                                         sizeof s_server_session_id_context)) {
1965         BIO_printf(bio_err, "error setting session id context\n");
1966         ERR_print_errors(bio_err);
1967         goto end;
1968     }
1969
1970     /* Set DTLS cookie generation and verification callbacks */
1971     SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1972     SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1973
1974     if (ctx2) {
1975         SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1976         if (!SSL_CTX_set_session_id_context(ctx2,
1977                     (void *)&s_server_session_id_context,
1978                     sizeof s_server_session_id_context)) {
1979             BIO_printf(bio_err, "error setting session id context\n");
1980             ERR_print_errors(bio_err);
1981             goto end;
1982         }
1983         tlsextcbp.biodebug = bio_s_out;
1984         SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1985         SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1986         SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1987         SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1988     }
1989
1990 #ifndef OPENSSL_NO_SRP
1991     if (srp_verifier_file != NULL) {
1992         srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1993         srp_callback_parm.user = NULL;
1994         srp_callback_parm.login = NULL;
1995         if ((ret =
1996              SRP_VBASE_init(srp_callback_parm.vb,
1997                             srp_verifier_file)) != SRP_NO_ERROR) {
1998             BIO_printf(bio_err,
1999                        "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
2000                        srp_verifier_file, ret);
2001             goto end;
2002         }
2003         SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
2004         SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
2005         SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
2006     } else
2007 #endif
2008     if (CAfile != NULL) {
2009         SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2010
2011         if (ctx2)
2012             SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2013     }
2014 #ifndef OPENSSL_NO_OCSP
2015     if (s_tlsextstatus) {
2016         SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2017         SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2018         if (ctx2) {
2019             SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2020             SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2021         }
2022     }
2023 #endif
2024     if (set_keylog_file(ctx, keylog_file))
2025         goto end;
2026
2027     if (max_early_data >= 0)
2028         SSL_CTX_set_max_early_data(ctx, max_early_data);
2029
2030     BIO_printf(bio_s_out, "ACCEPT\n");
2031     (void)BIO_flush(bio_s_out);
2032     if (rev)
2033         server_cb = rev_body;
2034     else if (www)
2035         server_cb = www_body;
2036     else
2037         server_cb = sv_body;
2038 #ifdef AF_UNIX
2039     if (socket_family == AF_UNIX
2040         && unlink_unix_path)
2041         unlink(host);
2042 #endif
2043     do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2044               server_cb, context, naccept);
2045     print_stats(bio_s_out, ctx);
2046     ret = 0;
2047  end:
2048     SSL_CTX_free(ctx);
2049     set_keylog_file(NULL, NULL);
2050     X509_free(s_cert);
2051     sk_X509_CRL_pop_free(crls, X509_CRL_free);
2052     X509_free(s_dcert);
2053     EVP_PKEY_free(s_key);
2054     EVP_PKEY_free(s_dkey);
2055     sk_X509_pop_free(s_chain, X509_free);
2056     sk_X509_pop_free(s_dchain, X509_free);
2057     OPENSSL_free(pass);
2058     OPENSSL_free(dpass);
2059     OPENSSL_free(host);
2060     OPENSSL_free(port);
2061     X509_VERIFY_PARAM_free(vpm);
2062     free_sessions();
2063     OPENSSL_free(tlscstatp.host);
2064     OPENSSL_free(tlscstatp.port);
2065     OPENSSL_free(tlscstatp.path);
2066     SSL_CTX_free(ctx2);
2067     X509_free(s_cert2);
2068     EVP_PKEY_free(s_key2);
2069 #ifndef OPENSSL_NO_NEXTPROTONEG
2070     OPENSSL_free(next_proto.data);
2071 #endif
2072     OPENSSL_free(alpn_ctx.data);
2073     ssl_excert_free(exc);
2074     sk_OPENSSL_STRING_free(ssl_args);
2075     SSL_CONF_CTX_free(cctx);
2076     release_engine(engine);
2077     BIO_free(bio_s_out);
2078     bio_s_out = NULL;
2079     BIO_free(bio_s_msg);
2080     bio_s_msg = NULL;
2081 #ifdef CHARSET_EBCDIC
2082     BIO_meth_free(methods_ebcdic);
2083 #endif
2084     return (ret);
2085 }
2086
2087 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2088 {
2089     BIO_printf(bio, "%4ld items in the session cache\n",
2090                SSL_CTX_sess_number(ssl_ctx));
2091     BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2092                SSL_CTX_sess_connect(ssl_ctx));
2093     BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2094                SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2095     BIO_printf(bio, "%4ld client connects that finished\n",
2096                SSL_CTX_sess_connect_good(ssl_ctx));
2097     BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2098                SSL_CTX_sess_accept(ssl_ctx));
2099     BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2100                SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2101     BIO_printf(bio, "%4ld server accepts that finished\n",
2102                SSL_CTX_sess_accept_good(ssl_ctx));
2103     BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2104     BIO_printf(bio, "%4ld session cache misses\n",
2105                SSL_CTX_sess_misses(ssl_ctx));
2106     BIO_printf(bio, "%4ld session cache timeouts\n",
2107                SSL_CTX_sess_timeouts(ssl_ctx));
2108     BIO_printf(bio, "%4ld callback cache hits\n",
2109                SSL_CTX_sess_cb_hits(ssl_ctx));
2110     BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2111                SSL_CTX_sess_cache_full(ssl_ctx),
2112                SSL_CTX_sess_get_cache_size(ssl_ctx));
2113 }
2114
2115 static int sv_body(int s, int stype, int prot, unsigned char *context)
2116 {
2117     char *buf = NULL;
2118     fd_set readfds;
2119     int ret = 1, width;
2120     int k, i;
2121     unsigned long l;
2122     SSL *con = NULL;
2123     BIO *sbio;
2124     struct timeval timeout;
2125 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2126     struct timeval tv;
2127 #else
2128     struct timeval *timeoutp;
2129 #endif
2130 #ifndef OPENSSL_NO_DTLS
2131 # ifndef OPENSSL_NO_SCTP
2132     int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2133 # else
2134     int isdtls = (stype == SOCK_DGRAM);
2135 # endif
2136 #endif
2137
2138     buf = app_malloc(bufsize, "server buffer");
2139     if (s_nbio) {
2140         if (!BIO_socket_nbio(s, 1))
2141             ERR_print_errors(bio_err);
2142         else if (!s_quiet)
2143             BIO_printf(bio_err, "Turned on non blocking io\n");
2144     }
2145
2146     if (con == NULL) {
2147         con = SSL_new(ctx);
2148
2149         if (s_tlsextdebug) {
2150             SSL_set_tlsext_debug_callback(con, tlsext_cb);
2151             SSL_set_tlsext_debug_arg(con, bio_s_out);
2152         }
2153
2154         if (context
2155             && !SSL_set_session_id_context(con,
2156                                            context, strlen((char *)context))) {
2157             BIO_printf(bio_err, "Error setting session id context\n");
2158             ret = -1;
2159             goto err;
2160         }
2161     }
2162     if (!SSL_clear(con)) {
2163         BIO_printf(bio_err, "Error clearing SSL connection\n");
2164         ret = -1;
2165         goto err;
2166     }
2167 #ifndef OPENSSL_NO_DTLS
2168     if (isdtls) {
2169 # ifndef OPENSSL_NO_SCTP
2170         if (prot == IPPROTO_SCTP)
2171             sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2172         else
2173 # endif
2174             sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2175
2176         if (enable_timeouts) {
2177             timeout.tv_sec = 0;
2178             timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2179             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2180
2181             timeout.tv_sec = 0;
2182             timeout.tv_usec = DGRAM_SND_TIMEOUT;
2183             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2184         }
2185
2186         if (socket_mtu) {
2187             if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2188                 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2189                            DTLS_get_link_min_mtu(con));
2190                 ret = -1;
2191                 BIO_free(sbio);
2192                 goto err;
2193             }
2194             SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2195             if (!DTLS_set_link_mtu(con, socket_mtu)) {
2196                 BIO_printf(bio_err, "Failed to set MTU\n");
2197                 ret = -1;
2198                 BIO_free(sbio);
2199                 goto err;
2200             }
2201         } else
2202             /* want to do MTU discovery */
2203             BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2204
2205 # ifndef OPENSSL_NO_SCTP
2206         if (prot != IPPROTO_SCTP) {
2207             /* Turn on cookie exchange. Not necessary for SCTP */
2208             SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2209         }
2210 # endif
2211     } else
2212 #endif
2213         sbio = BIO_new_socket(s, BIO_NOCLOSE);
2214
2215     if (sbio == NULL) {
2216         BIO_printf(bio_err, "Unable to create BIO\n");
2217         ERR_print_errors(bio_err);
2218         goto err;
2219     }
2220
2221     if (s_nbio_test) {
2222         BIO *test;
2223
2224         test = BIO_new(BIO_f_nbio_test());
2225         sbio = BIO_push(test, sbio);
2226     }
2227
2228     SSL_set_bio(con, sbio, sbio);
2229     SSL_set_accept_state(con);
2230     /* SSL_set_fd(con,s); */
2231
2232     if (s_debug) {
2233         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2234         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2235     }
2236     if (s_msg) {
2237 #ifndef OPENSSL_NO_SSL_TRACE
2238         if (s_msg == 2)
2239             SSL_set_msg_callback(con, SSL_trace);
2240         else
2241 #endif
2242             SSL_set_msg_callback(con, msg_cb);
2243         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2244     }
2245
2246     if (s_tlsextdebug) {
2247         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2248         SSL_set_tlsext_debug_arg(con, bio_s_out);
2249     }
2250
2251     if (early_data) {
2252         int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2253         size_t readbytes;
2254
2255         while (edret != SSL_READ_EARLY_DATA_FINISH) {
2256             for (;;) {
2257                 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2258                 if (edret != SSL_READ_EARLY_DATA_ERROR)
2259                     break;
2260
2261                 switch (SSL_get_error(con, 0)) {
2262                 case SSL_ERROR_WANT_WRITE:
2263                 case SSL_ERROR_WANT_ASYNC:
2264                 case SSL_ERROR_WANT_READ:
2265                     /* Just keep trying - busy waiting */
2266                     continue;
2267                 default:
2268                     BIO_printf(bio_err, "Error reading early data\n");
2269                     ERR_print_errors(bio_err);
2270                     goto err;
2271                 }
2272             }
2273             if (readbytes > 0) {
2274                 if (write_header) {
2275                     BIO_printf(bio_s_out, "Early data received:\n");
2276                     write_header = 0;
2277                 }
2278                 raw_write_stdout(buf, (unsigned int)readbytes);
2279                 (void)BIO_flush(bio_s_out);
2280             }
2281         }
2282         if (write_header)
2283             BIO_printf(bio_s_out, "No early data received\n");
2284         else
2285             BIO_printf(bio_s_out, "\nEnd of early data\n");
2286         if (SSL_is_init_finished(con))
2287             print_connection_info(con);
2288     }
2289
2290     if (fileno_stdin() > s)
2291         width = fileno_stdin() + 1;
2292     else
2293         width = s + 1;
2294     for (;;) {
2295         int read_from_terminal;
2296         int read_from_sslcon;
2297
2298         read_from_terminal = 0;
2299         read_from_sslcon = SSL_has_pending(con)
2300                            || (async && SSL_waiting_for_async(con));
2301
2302         if (!read_from_sslcon) {
2303             FD_ZERO(&readfds);
2304 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2305             openssl_fdset(fileno_stdin(), &readfds);
2306 #endif
2307             openssl_fdset(s, &readfds);
2308             /*
2309              * Note: under VMS with SOCKETSHR the second parameter is
2310              * currently of type (int *) whereas under other systems it is
2311              * (void *) if you don't have a cast it will choke the compiler:
2312              * if you do have a cast then you can either go for (int *) or
2313              * (void *).
2314              */
2315 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2316             /*
2317              * Under DOS (non-djgpp) and Windows we can't select on stdin:
2318              * only on sockets. As a workaround we timeout the select every
2319              * second and check for any keypress. In a proper Windows
2320              * application we wouldn't do this because it is inefficient.
2321              */
2322             tv.tv_sec = 1;
2323             tv.tv_usec = 0;
2324             i = select(width, (void *)&readfds, NULL, NULL, &tv);
2325             if (has_stdin_waiting())
2326                 read_from_terminal = 1;
2327             if ((i < 0) || (!i && !read_from_terminal))
2328                 continue;
2329 #else
2330             if ((SSL_version(con) == DTLS1_VERSION) &&
2331                 DTLSv1_get_timeout(con, &timeout))
2332                 timeoutp = &timeout;
2333             else
2334                 timeoutp = NULL;
2335
2336             i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2337
2338             if ((SSL_version(con) == DTLS1_VERSION)
2339                 && DTLSv1_handle_timeout(con) > 0) {
2340                 BIO_printf(bio_err, "TIMEOUT occurred\n");
2341             }
2342
2343             if (i <= 0)
2344                 continue;
2345             if (FD_ISSET(fileno_stdin(), &readfds))
2346                 read_from_terminal = 1;
2347 #endif
2348             if (FD_ISSET(s, &readfds))
2349                 read_from_sslcon = 1;
2350         }
2351         if (read_from_terminal) {
2352             if (s_crlf) {
2353                 int j, lf_num;
2354
2355                 i = raw_read_stdin(buf, bufsize / 2);
2356                 lf_num = 0;
2357                 /* both loops are skipped when i <= 0 */
2358                 for (j = 0; j < i; j++)
2359                     if (buf[j] == '\n')
2360                         lf_num++;
2361                 for (j = i - 1; j >= 0; j--) {
2362                     buf[j + lf_num] = buf[j];
2363                     if (buf[j] == '\n') {
2364                         lf_num--;
2365                         i++;
2366                         buf[j + lf_num] = '\r';
2367                     }
2368                 }
2369                 assert(lf_num == 0);
2370             } else
2371                 i = raw_read_stdin(buf, bufsize);
2372
2373             if (!s_quiet && !s_brief) {
2374                 if ((i <= 0) || (buf[0] == 'Q')) {
2375                     BIO_printf(bio_s_out, "DONE\n");
2376                     (void)BIO_flush(bio_s_out);
2377                     BIO_closesocket(s);
2378                     close_accept_socket();
2379                     ret = -11;
2380                     goto err;
2381                 }
2382                 if ((i <= 0) || (buf[0] == 'q')) {
2383                     BIO_printf(bio_s_out, "DONE\n");
2384                     (void)BIO_flush(bio_s_out);
2385                     if (SSL_version(con) != DTLS1_VERSION)
2386                         BIO_closesocket(s);
2387                     /*
2388                      * close_accept_socket(); ret= -11;
2389                      */
2390                     goto err;
2391                 }
2392 #ifndef OPENSSL_NO_HEARTBEATS
2393                 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2394                     BIO_printf(bio_err, "HEARTBEATING\n");
2395                     SSL_heartbeat(con);
2396                     i = 0;
2397                     continue;
2398                 }
2399 #endif
2400                 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2401                     SSL_renegotiate(con);
2402                     i = SSL_do_handshake(con);
2403                     printf("SSL_do_handshake -> %d\n", i);
2404                     i = 0;      /* 13; */
2405                     continue;
2406                     /*
2407                      * strcpy(buf,"server side RE-NEGOTIATE\n");
2408                      */
2409                 }
2410                 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2411                     SSL_set_verify(con,
2412                                    SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2413                                    NULL);
2414                     SSL_renegotiate(con);
2415                     i = SSL_do_handshake(con);
2416                     printf("SSL_do_handshake -> %d\n", i);
2417                     i = 0;      /* 13; */
2418                     continue;
2419                     /*
2420                      * strcpy(buf,"server side RE-NEGOTIATE asking for client
2421                      * cert\n");
2422                      */
2423                 }
2424                 if ((buf[0] == 'K' || buf[0] == 'k')
2425                         && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2426                     SSL_key_update(con, buf[0] == 'K' ?
2427                                         SSL_KEY_UPDATE_REQUESTED
2428                                         : SSL_KEY_UPDATE_NOT_REQUESTED);
2429                     i = SSL_do_handshake(con);
2430                     printf("SSL_do_handshake -> %d\n", i);
2431                     i = 0;
2432                     continue;
2433                     /*
2434                      * strcpy(buf,"server side RE-NEGOTIATE asking for client
2435                      * cert\n");
2436                      */
2437                 }
2438                 if (buf[0] == 'P') {
2439                     static const char *str = "Lets print some clear text\n";
2440                     BIO_write(SSL_get_wbio(con), str, strlen(str));
2441                 }
2442                 if (buf[0] == 'S') {
2443                     print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2444                 }
2445             }
2446 #ifdef CHARSET_EBCDIC
2447             ebcdic2ascii(buf, buf, i);
2448 #endif
2449             l = k = 0;
2450             for (;;) {
2451                 /* should do a select for the write */
2452 #ifdef RENEG
2453                 static count = 0;
2454                 if (++count == 100) {
2455                     count = 0;
2456                     SSL_renegotiate(con);
2457                 }
2458 #endif
2459                 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2460 #ifndef OPENSSL_NO_SRP
2461                 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2462                     BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2463                     SRP_user_pwd_free(srp_callback_parm.user);
2464                     srp_callback_parm.user =
2465                         SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2466                                                srp_callback_parm.login);
2467                     if (srp_callback_parm.user)
2468                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
2469                                    srp_callback_parm.user->info);
2470                     else
2471                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
2472                     k = SSL_write(con, &(buf[l]), (unsigned int)i);
2473                 }
2474 #endif
2475                 switch (SSL_get_error(con, k)) {
2476                 case SSL_ERROR_NONE:
2477                     break;
2478                 case SSL_ERROR_WANT_ASYNC:
2479                     BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2480                     (void)BIO_flush(bio_s_out);
2481                     wait_for_async(con);
2482                     break;
2483                 case SSL_ERROR_WANT_WRITE:
2484                 case SSL_ERROR_WANT_READ:
2485                 case SSL_ERROR_WANT_X509_LOOKUP:
2486                     BIO_printf(bio_s_out, "Write BLOCK\n");
2487                     (void)BIO_flush(bio_s_out);
2488                     break;
2489                 case SSL_ERROR_WANT_ASYNC_JOB:
2490                     /*
2491                      * This shouldn't ever happen in s_server. Treat as an error
2492                      */
2493                 case SSL_ERROR_SYSCALL:
2494                 case SSL_ERROR_SSL:
2495                     BIO_printf(bio_s_out, "ERROR\n");
2496                     (void)BIO_flush(bio_s_out);
2497                     ERR_print_errors(bio_err);
2498                     ret = 1;
2499                     goto err;
2500                     /* break; */
2501                 case SSL_ERROR_ZERO_RETURN:
2502                     BIO_printf(bio_s_out, "DONE\n");
2503                     (void)BIO_flush(bio_s_out);
2504                     ret = 1;
2505                     goto err;
2506                 }
2507                 if (k > 0) {
2508                     l += k;
2509                     i -= k;
2510                 }
2511                 if (i <= 0)
2512                     break;
2513             }
2514         }
2515         if (read_from_sslcon) {
2516             /*
2517              * init_ssl_connection handles all async events itself so if we're
2518              * waiting for async then we shouldn't go back into
2519              * init_ssl_connection
2520              */
2521             if ((!async || !SSL_waiting_for_async(con))
2522                     && !SSL_is_init_finished(con)) {
2523                 i = init_ssl_connection(con);
2524
2525                 if (i < 0) {
2526                     ret = 0;
2527                     goto err;
2528                 } else if (i == 0) {
2529                     ret = 1;
2530                     goto err;
2531                 }
2532             } else {
2533  again:
2534                 i = SSL_read(con, (char *)buf, bufsize);
2535 #ifndef OPENSSL_NO_SRP
2536                 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2537                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2538                     SRP_user_pwd_free(srp_callback_parm.user);
2539                     srp_callback_parm.user =
2540                         SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2541                                                srp_callback_parm.login);
2542                     if (srp_callback_parm.user)
2543                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
2544                                    srp_callback_parm.user->info);
2545                     else
2546                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
2547                     i = SSL_read(con, (char *)buf, bufsize);
2548                 }
2549 #endif
2550                 switch (SSL_get_error(con, i)) {
2551                 case SSL_ERROR_NONE:
2552 #ifdef CHARSET_EBCDIC
2553                     ascii2ebcdic(buf, buf, i);
2554 #endif
2555                     raw_write_stdout(buf, (unsigned int)i);
2556                     (void)BIO_flush(bio_s_out);
2557                     if (SSL_has_pending(con))
2558                         goto again;
2559                     break;
2560                 case SSL_ERROR_WANT_ASYNC:
2561                     BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2562                     (void)BIO_flush(bio_s_out);
2563                     wait_for_async(con);
2564                     break;
2565                 case SSL_ERROR_WANT_WRITE:
2566                 case SSL_ERROR_WANT_READ:
2567                     BIO_printf(bio_s_out, "Read BLOCK\n");
2568                     (void)BIO_flush(bio_s_out);
2569                     break;
2570                 case SSL_ERROR_WANT_ASYNC_JOB:
2571                     /*
2572                      * This shouldn't ever happen in s_server. Treat as an error
2573                      */
2574                 case SSL_ERROR_SYSCALL:
2575                 case SSL_ERROR_SSL:
2576                     BIO_printf(bio_s_out, "ERROR\n");
2577                     (void)BIO_flush(bio_s_out);
2578                     ERR_print_errors(bio_err);
2579                     ret = 1;
2580                     goto err;
2581                 case SSL_ERROR_ZERO_RETURN:
2582                     BIO_printf(bio_s_out, "DONE\n");
2583                     (void)BIO_flush(bio_s_out);
2584                     ret = 1;
2585                     goto err;
2586                 }
2587             }
2588         }
2589     }
2590  err:
2591     if (con != NULL) {
2592         BIO_printf(bio_s_out, "shutting down SSL\n");
2593         SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2594         SSL_free(con);
2595     }
2596     BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2597     OPENSSL_clear_free(buf, bufsize);
2598     if (ret >= 0)
2599         BIO_printf(bio_s_out, "ACCEPT\n");
2600     (void)BIO_flush(bio_s_out);
2601     return (ret);
2602 }
2603
2604 static void close_accept_socket(void)
2605 {
2606     BIO_printf(bio_err, "shutdown accept socket\n");
2607     if (accept_socket >= 0) {
2608         BIO_closesocket(accept_socket);
2609     }
2610 }
2611
2612 static int init_ssl_connection(SSL *con)
2613 {
2614     int i;
2615     long verify_err;
2616     int retry = 0;
2617
2618 #ifndef OPENSSL_NO_DTLS
2619     if (dtlslisten) {
2620         BIO_ADDR *client = NULL;
2621
2622         if ((client = BIO_ADDR_new()) == NULL) {
2623             BIO_printf(bio_err, "ERROR - memory\n");
2624             return 0;
2625         }
2626         i = DTLSv1_listen(con, client);
2627         if (i > 0) {
2628             BIO *wbio;
2629             int fd = -1;
2630
2631             wbio = SSL_get_wbio(con);
2632             if (wbio) {
2633                 BIO_get_fd(wbio, &fd);
2634             }
2635
2636             if (!wbio || BIO_connect(fd, client, 0) == 0) {
2637                 BIO_printf(bio_err, "ERROR - unable to connect\n");
2638                 BIO_ADDR_free(client);
2639                 return 0;
2640             }
2641             BIO_ADDR_free(client);
2642             dtlslisten = 0;
2643             i = SSL_accept(con);
2644         } else {
2645             BIO_ADDR_free(client);
2646         }
2647     } else
2648 #endif
2649
2650     do {
2651         i = SSL_accept(con);
2652
2653         if (i <= 0)
2654             retry = !SSL_want_nothing(con);
2655 #ifdef CERT_CB_TEST_RETRY
2656         {
2657             while (i <= 0
2658                     && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2659                     && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2660                 BIO_printf(bio_err,
2661                            "LOOKUP from certificate callback during accept\n");
2662                 i = SSL_accept(con);
2663                 if (i <= 0)
2664                     retry = !SSL_want_nothing(con);
2665             }
2666         }
2667 #endif
2668
2669 #ifndef OPENSSL_NO_SRP
2670         while (i <= 0
2671                && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2672             BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2673                        srp_callback_parm.login);
2674             SRP_user_pwd_free(srp_callback_parm.user);
2675             srp_callback_parm.user =
2676                 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2677                                        srp_callback_parm.login);
2678             if (srp_callback_parm.user)
2679                 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2680                            srp_callback_parm.user->info);
2681             else
2682                 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2683             i = SSL_accept(con);
2684             if (i <= 0)
2685                 retry = !SSL_want_nothing(con);
2686         }
2687 #endif
2688     } while (i < 0 && SSL_waiting_for_async(con));
2689
2690     if (i <= 0) {
2691         if ((dtlslisten && i == 0)
2692                 || (!dtlslisten && retry)) {
2693             BIO_printf(bio_s_out, "DELAY\n");
2694             return (1);
2695         }
2696
2697         BIO_printf(bio_err, "ERROR\n");
2698
2699         verify_err = SSL_get_verify_result(con);
2700         if (verify_err != X509_V_OK) {
2701             BIO_printf(bio_err, "verify error:%s\n",
2702                        X509_verify_cert_error_string(verify_err));
2703         }
2704         /* Always print any error messages */
2705         ERR_print_errors(bio_err);
2706         return (0);
2707     }
2708
2709     print_connection_info(con);
2710     return 1;
2711 }
2712
2713 static void print_connection_info(SSL *con)
2714 {
2715     const char *str;
2716     X509 *peer;
2717     char buf[BUFSIZ];
2718 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2719     const unsigned char *next_proto_neg;
2720     unsigned next_proto_neg_len;
2721 #endif
2722     unsigned char *exportedkeymat;
2723     int i;
2724
2725     if (s_brief)
2726         print_ssl_summary(con);
2727
2728     PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2729
2730     peer = SSL_get_peer_certificate(con);
2731     if (peer != NULL) {
2732         BIO_printf(bio_s_out, "Client certificate\n");
2733         PEM_write_bio_X509(bio_s_out, peer);
2734         dump_cert_text(bio_s_out, peer);
2735         X509_free(peer);
2736         peer = NULL;
2737     }
2738
2739     if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2740         BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2741     str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2742     ssl_print_sigalgs(bio_s_out, con);
2743 #ifndef OPENSSL_NO_EC
2744     ssl_print_point_formats(bio_s_out, con);
2745     ssl_print_groups(bio_s_out, con, 0);
2746 #endif
2747     print_ca_names(bio_s_out, con);
2748     BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2749
2750 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2751     SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2752     if (next_proto_neg) {
2753         BIO_printf(bio_s_out, "NEXTPROTO is ");
2754         BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2755         BIO_printf(bio_s_out, "\n");
2756     }
2757 #endif
2758 #ifndef OPENSSL_NO_SRTP
2759     {
2760         SRTP_PROTECTION_PROFILE *srtp_profile
2761             = SSL_get_selected_srtp_profile(con);
2762
2763         if (srtp_profile)
2764             BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2765                        srtp_profile->name);
2766     }
2767 #endif
2768     if (SSL_session_reused(con))
2769         BIO_printf(bio_s_out, "Reused session-id\n");
2770     BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2771                SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2772     if (keymatexportlabel != NULL) {
2773         BIO_printf(bio_s_out, "Keying material exporter:\n");
2774         BIO_printf(bio_s_out, "    Label: '%s'\n", keymatexportlabel);
2775         BIO_printf(bio_s_out, "    Length: %i bytes\n", keymatexportlen);
2776         exportedkeymat = app_malloc(keymatexportlen, "export key");
2777         if (!SSL_export_keying_material(con, exportedkeymat,
2778                                         keymatexportlen,
2779                                         keymatexportlabel,
2780                                         strlen(keymatexportlabel),
2781                                         NULL, 0, 0)) {
2782             BIO_printf(bio_s_out, "    Error\n");
2783         } else {
2784             BIO_printf(bio_s_out, "    Keying material: ");
2785             for (i = 0; i < keymatexportlen; i++)
2786                 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2787             BIO_printf(bio_s_out, "\n");
2788         }
2789         OPENSSL_free(exportedkeymat);
2790     }
2791
2792     (void)BIO_flush(bio_s_out);
2793 }
2794
2795 #ifndef OPENSSL_NO_DH
2796 static DH *load_dh_param(const char *dhfile)
2797 {
2798     DH *ret = NULL;
2799     BIO *bio;
2800
2801     if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2802         goto err;
2803     ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2804  err:
2805     BIO_free(bio);
2806     return (ret);
2807 }
2808 #endif
2809
2810 static int www_body(int s, int stype, int prot, unsigned char *context)
2811 {
2812     char *buf = NULL;
2813     int ret = 1;
2814     int i, j, k, dot;
2815     SSL *con;
2816     const SSL_CIPHER *c;
2817     BIO *io, *ssl_bio, *sbio;
2818 #ifdef RENEG
2819     int total_bytes = 0;
2820 #endif
2821     int width;
2822     fd_set readfds;
2823
2824     /* Set width for a select call if needed */
2825     width = s + 1;
2826
2827     buf = app_malloc(bufsize, "server www buffer");
2828     io = BIO_new(BIO_f_buffer());
2829     ssl_bio = BIO_new(BIO_f_ssl());
2830     if ((io == NULL) || (ssl_bio == NULL))
2831         goto err;
2832
2833     if (s_nbio) {
2834         if (!BIO_socket_nbio(s, 1))
2835             ERR_print_errors(bio_err);
2836         else if (!s_quiet)
2837             BIO_printf(bio_err, "Turned on non blocking io\n");
2838     }
2839
2840     /* lets make the output buffer a reasonable size */
2841     if (!BIO_set_write_buffer_size(io, bufsize))
2842         goto err;
2843
2844     if ((con = SSL_new(ctx)) == NULL)
2845         goto err;
2846
2847     if (s_tlsextdebug) {
2848         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2849         SSL_set_tlsext_debug_arg(con, bio_s_out);
2850     }
2851
2852     if (context
2853         && !SSL_set_session_id_context(con, context,
2854                                        strlen((char *)context)))
2855         goto err;
2856
2857     sbio = BIO_new_socket(s, BIO_NOCLOSE);
2858     if (s_nbio_test) {
2859         BIO *test;
2860
2861         test = BIO_new(BIO_f_nbio_test());
2862         sbio = BIO_push(test, sbio);
2863     }
2864     SSL_set_bio(con, sbio, sbio);
2865     SSL_set_accept_state(con);
2866
2867     /* SSL_set_fd(con,s); */
2868     BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2869     BIO_push(io, ssl_bio);
2870 #ifdef CHARSET_EBCDIC
2871     io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2872 #endif
2873
2874     if (s_debug) {
2875         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2876         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2877     }
2878     if (s_msg) {
2879 #ifndef OPENSSL_NO_SSL_TRACE
2880         if (s_msg == 2)
2881             SSL_set_msg_callback(con, SSL_trace);
2882         else
2883 #endif
2884             SSL_set_msg_callback(con, msg_cb);
2885         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2886     }
2887
2888     for (;;) {
2889         i = BIO_gets(io, buf, bufsize - 1);
2890         if (i < 0) {            /* error */
2891             if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2892                 if (!s_quiet)
2893                     ERR_print_errors(bio_err);
2894                 goto err;
2895             } else {
2896                 BIO_printf(bio_s_out, "read R BLOCK\n");
2897 #ifndef OPENSSL_NO_SRP
2898                 if (BIO_should_io_special(io)
2899                     && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2900                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2901                     SRP_user_pwd_free(srp_callback_parm.user);
2902                     srp_callback_parm.user =
2903                         SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2904                                                srp_callback_parm.login);
2905                     if (srp_callback_parm.user)
2906                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
2907                                    srp_callback_parm.user->info);
2908                     else
2909                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
2910                     continue;
2911                 }
2912 #endif
2913 #if !defined(OPENSSL_SYS_MSDOS)
2914                 sleep(1);
2915 #endif
2916                 continue;
2917             }
2918         } else if (i == 0) {    /* end of input */
2919             ret = 1;
2920             goto end;
2921         }
2922
2923         /* else we have data */
2924         if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2925             ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2926             char *p;
2927             X509 *peer = NULL;
2928             STACK_OF(SSL_CIPHER) *sk;
2929             static const char *space = "                          ";
2930
2931             if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2932                 if (strncmp("GET /renegcert", buf, 14) == 0)
2933                     SSL_set_verify(con,
2934                                    SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2935                                    NULL);
2936                 i = SSL_renegotiate(con);
2937                 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2938                 /* Send the HelloRequest */
2939                 i = SSL_do_handshake(con);
2940                 if (i <= 0) {
2941                     BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2942                                SSL_get_error(con, i));
2943                     ERR_print_errors(bio_err);
2944                     goto err;
2945                 }
2946                 /* Wait for a ClientHello to come back */
2947                 FD_ZERO(&readfds);
2948                 openssl_fdset(s, &readfds);
2949                 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2950                 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2951                     BIO_printf(bio_s_out,
2952                                "Error waiting for client response\n");
2953                     ERR_print_errors(bio_err);
2954                     goto err;
2955                 }
2956                 /*
2957                  * We're not actually expecting any data here and we ignore
2958                  * any that is sent. This is just to force the handshake that
2959                  * we're expecting to come from the client. If they haven't
2960                  * sent one there's not much we can do.
2961                  */
2962                 BIO_gets(io, buf, bufsize - 1);
2963             }
2964
2965             BIO_puts(io,
2966                      "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2967             BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2968             BIO_puts(io, "<pre>\n");
2969             /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2970             BIO_puts(io, "\n");
2971             for (i = 0; i < local_argc; i++) {
2972                 const char *myp;
2973                 for (myp = local_argv[i]; *myp; myp++)
2974                     switch (*myp) {
2975                     case '<':
2976                         BIO_puts(io, "&lt;");
2977                         break;
2978                     case '>':
2979                         BIO_puts(io, "&gt;");
2980                         break;
2981                     case '&':
2982                         BIO_puts(io, "&amp;");
2983                         break;
2984                     default:
2985                         BIO_write(io, myp, 1);
2986                         break;
2987                     }
2988                 BIO_write(io, " ", 1);
2989             }
2990             BIO_puts(io, "\n");
2991
2992             BIO_printf(io,
2993                        "Secure Renegotiation IS%s supported\n",
2994                        SSL_get_secure_renegotiation_support(con) ?
2995                        "" : " NOT");
2996
2997             /*
2998              * The following is evil and should not really be done
2999              */
3000             BIO_printf(io, "Ciphers supported in s_server binary\n");
3001             sk = SSL_get_ciphers(con);
3002             j = sk_SSL_CIPHER_num(sk);
3003             for (i = 0; i < j; i++) {
3004                 c = sk_SSL_CIPHER_value(sk, i);
3005                 BIO_printf(io, "%-11s:%-25s ",
3006                            SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3007                 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3008                     BIO_puts(io, "\n");
3009             }
3010             BIO_puts(io, "\n");
3011             p = SSL_get_shared_ciphers(con, buf, bufsize);
3012             if (p != NULL) {
3013                 BIO_printf(io,
3014                            "---\nCiphers common between both SSL end points:\n");
3015                 j = i = 0;
3016                 while (*p) {
3017                     if (*p == ':') {
3018                         BIO_write(io, space, 26 - j);
3019                         i++;
3020                         j = 0;
3021                         BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3022                     } else {
3023                         BIO_write(io, p, 1);
3024                         j++;
3025                     }
3026                     p++;
3027                 }
3028                 BIO_puts(io, "\n");
3029             }
3030             ssl_print_sigalgs(io, con);
3031 #ifndef OPENSSL_NO_EC
3032             ssl_print_groups(io, con, 0);
3033 #endif
3034             print_ca_names(io, con);
3035             BIO_printf(io, (SSL_session_reused(con)
3036                             ? "---\nReused, " : "---\nNew, "));
3037             c = SSL_get_current_cipher(con);
3038             BIO_printf(io, "%s, Cipher is %s\n",
3039                        SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3040             SSL_SESSION_print(io, SSL_get_session(con));
3041             BIO_printf(io, "---\n");
3042             print_stats(io, SSL_get_SSL_CTX(con));
3043             BIO_printf(io, "---\n");
3044             peer = SSL_get_peer_certificate(con);
3045             if (peer != NULL) {
3046                 BIO_printf(io, "Client certificate\n");
3047                 X509_print(io, peer);
3048                 PEM_write_bio_X509(io, peer);
3049                 X509_free(peer);
3050                 peer = NULL;
3051             } else
3052                 BIO_puts(io, "no client certificate available\n");
3053             BIO_puts(io, "</BODY></HTML>\r\n\r\n");
3054             break;
3055         } else if ((www == 2 || www == 3)
3056                    && (strncmp("GET /", buf, 5) == 0)) {
3057             BIO *file;
3058             char *p, *e;
3059             static const char *text =
3060                 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3061
3062             /* skip the '/' */
3063             p = &(buf[5]);
3064
3065             dot = 1;
3066             for (e = p; *e != '\0'; e++) {
3067                 if (e[0] == ' ')
3068                     break;
3069
3070                 switch (dot) {
3071                 case 1:
3072                     dot = (e[0] == '.') ? 2 : 0;
3073                     break;
3074                 case 2:
3075                     dot = (e[0] == '.') ? 3 : 0;
3076                     break;
3077                 case 3:
3078                     dot = (e[0] == '/') ? -1 : 0;
3079                     break;
3080                 }
3081                 if (dot == 0)
3082                     dot = (e[0] == '/') ? 1 : 0;
3083             }
3084             dot = (dot == 3) || (dot == -1); /* filename contains ".."
3085                                               * component */
3086
3087             if (*e == '\0') {
3088                 BIO_puts(io, text);
3089                 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3090                 break;
3091             }
3092             *e = '\0';
3093
3094             if (dot) {
3095                 BIO_puts(io, text);
3096                 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
3097                 break;
3098             }
3099
3100             if (*p == '/') {
3101                 BIO_puts(io, text);
3102                 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3103                 break;
3104             }
3105
3106             /* if a directory, do the index thang */
3107             if (app_isdir(p) > 0) {
3108                 BIO_puts(io, text);
3109                 BIO_printf(io, "'%s' is a directory\r\n", p);
3110                 break;
3111             }
3112
3113             if ((file = BIO_new_file(p, "r")) == NULL) {
3114                 BIO_puts(io, text);
3115                 BIO_printf(io, "Error opening '%s'\r\n", p);
3116                 ERR_print_errors(io);
3117                 break;
3118             }
3119
3120             if (!s_quiet)
3121                 BIO_printf(bio_err, "FILE:%s\n", p);
3122
3123             if (www == 2) {
3124                 i = strlen(p);
3125                 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3126                     ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3127                     ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3128                     BIO_puts(io,
3129                              "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3130                 else
3131                     BIO_puts(io,
3132                              "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3133             }
3134             /* send the file */
3135             for (;;) {
3136                 i = BIO_read(file, buf, bufsize);
3137                 if (i <= 0)
3138                     break;
3139
3140 #ifdef RENEG
3141                 total_bytes += i;
3142                 BIO_printf(bio_err, "%d\n", i);
3143                 if (total_bytes > 3 * 1024) {
3144                     total_bytes = 0;
3145                     BIO_printf(bio_err, "RENEGOTIATE\n");
3146                     SSL_renegotiate(con);
3147                 }
3148 #endif
3149
3150                 for (j = 0; j < i;) {
3151 #ifdef RENEG
3152                     static count = 0;
3153                     if (++count == 13) {
3154                         SSL_renegotiate(con);
3155                     }
3156 #endif
3157                     k = BIO_write(io, &(buf[j]), i - j);
3158                     if (k <= 0) {
3159                         if (!BIO_should_retry(io)
3160                             && !SSL_waiting_for_async(con))
3161                             goto write_error;
3162                         else {
3163                             BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3164                         }
3165                     } else {
3166                         j += k;
3167                     }
3168                 }
3169             }
3170  write_error:
3171             BIO_free(file);
3172             break;
3173         }
3174     }
3175
3176     for (;;) {
3177         i = (int)BIO_flush(io);
3178         if (i <= 0) {
3179             if (!BIO_should_retry(io))
3180                 break;
3181         } else
3182             break;
3183     }
3184  end:
3185     /* make sure we re-use sessions */
3186     SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3187
3188  err:
3189     if (ret >= 0)
3190         BIO_printf(bio_s_out, "ACCEPT\n");
3191     OPENSSL_free(buf);
3192     BIO_free_all(io);
3193     return (ret);
3194 }
3195
3196 static int rev_body(int s, int stype, int prot, unsigned char *context)
3197 {
3198     char *buf = NULL;
3199     int i;
3200     int ret = 1;
3201     SSL *con;
3202     BIO *io, *ssl_bio, *sbio;
3203
3204     buf = app_malloc(bufsize, "server rev buffer");
3205     io = BIO_new(BIO_f_buffer());
3206     ssl_bio = BIO_new(BIO_f_ssl());
3207     if ((io == NULL) || (ssl_bio == NULL))
3208         goto err;
3209
3210     /* lets make the output buffer a reasonable size */
3211     if (!BIO_set_write_buffer_size(io, bufsize))
3212         goto err;
3213
3214     if ((con = SSL_new(ctx)) == NULL)
3215         goto err;
3216
3217     if (s_tlsextdebug) {
3218         SSL_set_tlsext_debug_callback(con, tlsext_cb);
3219         SSL_set_tlsext_debug_arg(con, bio_s_out);
3220     }
3221     if (context
3222         && !SSL_set_session_id_context(con, context,
3223                                        strlen((char *)context))) {
3224         ERR_print_errors(bio_err);
3225         goto err;
3226     }
3227
3228     sbio = BIO_new_socket(s, BIO_NOCLOSE);
3229     SSL_set_bio(con, sbio, sbio);
3230     SSL_set_accept_state(con);
3231
3232     BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3233     BIO_push(io, ssl_bio);
3234 #ifdef CHARSET_EBCDIC
3235     io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3236 #endif
3237
3238     if (s_debug) {
3239         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3240         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3241     }
3242     if (s_msg) {
3243 #ifndef OPENSSL_NO_SSL_TRACE
3244         if (s_msg == 2)
3245             SSL_set_msg_callback(con, SSL_trace);
3246         else
3247 #endif
3248             SSL_set_msg_callback(con, msg_cb);
3249         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3250     }
3251
3252     for (;;) {
3253         i = BIO_do_handshake(io);
3254         if (i > 0)
3255             break;
3256         if (!BIO_should_retry(io)) {
3257             BIO_puts(bio_err, "CONNECTION FAILURE\n");
3258             ERR_print_errors(bio_err);
3259             goto end;
3260         }
3261 #ifndef OPENSSL_NO_SRP
3262         if (BIO_should_io_special(io)
3263             && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3264             BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3265             SRP_user_pwd_free(srp_callback_parm.user);
3266             srp_callback_parm.user =
3267                 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3268                                        srp_callback_parm.login);
3269             if (srp_callback_parm.user)
3270                 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3271                            srp_callback_parm.user->info);
3272             else
3273                 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3274             continue;
3275         }
3276 #endif
3277     }
3278     BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3279     print_ssl_summary(con);
3280
3281     for (;;) {
3282         i = BIO_gets(io, buf, bufsize - 1);
3283         if (i < 0) {            /* error */
3284             if (!BIO_should_retry(io)) {
3285                 if (!s_quiet)
3286                     ERR_print_errors(bio_err);
3287                 goto err;
3288             } else {
3289                 BIO_printf(bio_s_out, "read R BLOCK\n");
3290 #ifndef OPENSSL_NO_SRP
3291                 if (BIO_should_io_special(io)
3292                     && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3293                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3294                     SRP_user_pwd_free(srp_callback_parm.user);
3295                     srp_callback_parm.user =
3296                         SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3297                                                srp_callback_parm.login);
3298                     if (srp_callback_parm.user)
3299                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
3300                                    srp_callback_parm.user->info);
3301                     else
3302                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
3303                     continue;
3304                 }
3305 #endif
3306 #if !defined(OPENSSL_SYS_MSDOS)
3307                 sleep(1);
3308 #endif
3309                 continue;
3310             }
3311         } else if (i == 0) {    /* end of input */
3312             ret = 1;
3313             BIO_printf(bio_err, "CONNECTION CLOSED\n");
3314             goto end;
3315         } else {
3316             char *p = buf + i - 1;
3317             while (i && (*p == '\n' || *p == '\r')) {
3318                 p--;
3319                 i--;
3320             }
3321             if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3322                 ret = 1;
3323                 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3324                 goto end;
3325             }
3326             BUF_reverse((unsigned char *)buf, NULL, i);
3327             buf[i] = '\n';
3328             BIO_write(io, buf, i + 1);
3329             for (;;) {
3330                 i = BIO_flush(io);
3331                 if (i > 0)
3332                     break;
3333                 if (!BIO_should_retry(io))
3334                     goto end;
3335             }
3336         }
3337     }
3338  end:
3339     /* make sure we re-use sessions */
3340     SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3341
3342  err:
3343
3344     OPENSSL_free(buf);
3345     BIO_free_all(io);
3346     return (ret);
3347 }
3348
3349 #define MAX_SESSION_ID_ATTEMPTS 10
3350 static int generate_session_id(const SSL *ssl, unsigned char *id,
3351                                unsigned int *id_len)
3352 {
3353     unsigned int count = 0;
3354     do {
3355         if (RAND_bytes(id, *id_len) <= 0)
3356             return 0;
3357         /*
3358          * Prefix the session_id with the required prefix. NB: If our prefix
3359          * is too long, clip it - but there will be worse effects anyway, eg.
3360          * the server could only possibly create 1 session ID (ie. the
3361          * prefix!) so all future session negotiations will fail due to
3362          * conflicts.
3363          */
3364         memcpy(id, session_id_prefix,
3365                (strlen(session_id_prefix) < *id_len) ?
3366                strlen(session_id_prefix) : *id_len);
3367     }
3368     while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3369            (++count < MAX_SESSION_ID_ATTEMPTS));
3370     if (count >= MAX_SESSION_ID_ATTEMPTS)
3371         return 0;
3372     return 1;
3373 }
3374
3375 /*
3376  * By default s_server uses an in-memory cache which caches SSL_SESSION
3377  * structures without any serialisation. This hides some bugs which only
3378  * become apparent in deployed servers. By implementing a basic external
3379  * session cache some issues can be debugged using s_server.
3380  */
3381
3382 typedef struct simple_ssl_session_st {
3383     unsigned char *id;
3384     unsigned int idlen;
3385     unsigned char *der;
3386     int derlen;
3387     struct simple_ssl_session_st *next;
3388 } simple_ssl_session;
3389
3390 static simple_ssl_session *first = NULL;
3391
3392 static int add_session(SSL *ssl, SSL_SESSION *session)
3393 {
3394     simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3395     unsigned char *p;
3396
3397     SSL_SESSION_get_id(session, &sess->idlen);
3398     sess->derlen = i2d_SSL_SESSION(session, NULL);
3399     if (sess->derlen < 0) {
3400         BIO_printf(bio_err, "Error encoding session\n");
3401         OPENSSL_free(sess);
3402         return 0;
3403     }
3404
3405     sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3406     sess->der = app_malloc(sess->derlen, "get session buffer");
3407     if (!sess->id) {
3408         BIO_printf(bio_err, "Out of memory adding to external cache\n");
3409         OPENSSL_free(sess->id);
3410         OPENSSL_free(sess->der);
3411         OPENSSL_free(sess);
3412         return 0;
3413     }
3414     p = sess->der;
3415
3416     /* Assume it still works. */
3417     if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3418         BIO_printf(bio_err, "Unexpected session encoding length\n");
3419         OPENSSL_free(sess->id);
3420         OPENSSL_free(sess->der);
3421         OPENSSL_free(sess);
3422         return 0;
3423     }
3424
3425     sess->next = first;
3426     first = sess;
3427     BIO_printf(bio_err, "New session added to external cache\n");
3428     return 0;
3429 }
3430
3431 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3432                                 int *do_copy)
3433 {
3434     simple_ssl_session *sess;
3435     *do_copy = 0;
3436     for (sess = first; sess; sess = sess->next) {
3437         if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3438             const unsigned char *p = sess->der;
3439             BIO_printf(bio_err, "Lookup session: cache hit\n");
3440             return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3441         }
3442     }
3443     BIO_printf(bio_err, "Lookup session: cache miss\n");
3444     return NULL;
3445 }
3446
3447 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3448 {
3449     simple_ssl_session *sess, *prev = NULL;
3450     const unsigned char *id;
3451     unsigned int idlen;
3452     id = SSL_SESSION_get_id(session, &idlen);
3453     for (sess = first; sess; sess = sess->next) {
3454         if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3455             if (prev)
3456                 prev->next = sess->next;
3457             else
3458                 first = sess->next;
3459             OPENSSL_free(sess->id);
3460             OPENSSL_free(sess->der);
3461             OPENSSL_free(sess);
3462             return;
3463         }
3464         prev = sess;
3465     }
3466 }
3467
3468 static void init_session_cache_ctx(SSL_CTX *sctx)
3469 {
3470     SSL_CTX_set_session_cache_mode(sctx,
3471                                    SSL_SESS_CACHE_NO_INTERNAL |
3472                                    SSL_SESS_CACHE_SERVER);
3473     SSL_CTX_sess_set_new_cb(sctx, add_session);
3474     SSL_CTX_sess_set_get_cb(sctx, get_session);
3475     SSL_CTX_sess_set_remove_cb(sctx, del_session);
3476 }
3477
3478 static void free_sessions(void)
3479 {
3480     simple_ssl_session *sess, *tsess;
3481     for (sess = first; sess;) {
3482         OPENSSL_free(sess->id);
3483         OPENSSL_free(sess->der);
3484         tsess = sess;
3485         sess = sess->next;
3486         OPENSSL_free(tsess);
3487     }
3488     first = NULL;
3489 }
3490
3491 #endif                          /* OPENSSL_NO_SOCK */