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