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