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