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