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