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