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