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