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