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