[test] ECC: make sure negative tests pass for the right reasons
[openssl.git] / apps / s_server.c
1 /*
2  * Copyright 1995-2018 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, 's',
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     {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
715     {"dcertform", OPT_DCERTFORM, 'F',
716      "Second certificate format (PEM or DER) PEM default"},
717     {"dkey", OPT_DKEY, '<',
718      "Second private key file to use (usually for DSA)"},
719     {"dkeyform", OPT_DKEYFORM, 'F',
720      "Second key format (PEM, DER or ENGINE) PEM default"},
721     {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
722     {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
723     {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
724     {"debug", OPT_DEBUG, '-', "Print more output"},
725     {"msg", OPT_MSG, '-', "Show protocol messages"},
726     {"msgfile", OPT_MSGFILE, '>',
727      "File to send output of -msg or -trace, instead of stdout"},
728     {"state", OPT_STATE, '-', "Print the SSL states"},
729     {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
730     {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
731     {"no-CAfile", OPT_NOCAFILE, '-',
732      "Do not load the default certificates file"},
733     {"no-CApath", OPT_NOCAPATH, '-',
734      "Do not load certificates from the default certificates directory"},
735     {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
736     {"quiet", OPT_QUIET, '-', "No server output"},
737     {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
738      "Disable caching and tickets if ephemeral (EC)DH is used"},
739     {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
740     {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
741     {"servername", OPT_SERVERNAME, 's',
742      "Servername for HostName TLS extension"},
743     {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
744      "mismatch send fatal alert (default warning alert)"},
745     {"cert2", OPT_CERT2, '<',
746      "Certificate file to use for servername; default is" TEST_CERT2},
747     {"key2", OPT_KEY2, '<',
748      "-Private Key file to use for servername if not in -cert2"},
749     {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
750      "Hex dump of all TLS extensions received"},
751     {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
752     {"id_prefix", OPT_ID_PREFIX, 's',
753      "Generate SSL/TLS session IDs prefixed by arg"},
754     {"rand", OPT_RAND, 's',
755      "Load the file(s) into the random number generator"},
756     {"keymatexport", OPT_KEYMATEXPORT, 's',
757      "Export keying material using label"},
758     {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
759      "Export len bytes of keying material (default 20)"},
760     {"CRL", OPT_CRL, '<', "CRL file to use"},
761     {"crl_download", OPT_CRL_DOWNLOAD, '-',
762      "Download CRL from distribution points"},
763     {"cert_chain", OPT_CERT_CHAIN, '<',
764      "certificate chain file in PEM format"},
765     {"dcert_chain", OPT_DCERT_CHAIN, '<',
766      "second certificate chain file in PEM format"},
767     {"chainCApath", OPT_CHAINCAPATH, '/',
768      "use dir as certificate store path to build CA certificate chain"},
769     {"verifyCApath", OPT_VERIFYCAPATH, '/',
770      "use dir as certificate store path to verify CA certificate"},
771     {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
772     {"ext_cache", OPT_EXT_CACHE, '-',
773      "Disable internal cache, setup and use external cache"},
774     {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
775     {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
776      "Close connection on verification error"},
777     {"verify_quiet", OPT_VERIFY_QUIET, '-',
778      "No verify output except verify errors"},
779     {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
780     {"chainCAfile", OPT_CHAINCAFILE, '<',
781      "CA file for certificate chain (PEM format)"},
782     {"verifyCAfile", OPT_VERIFYCAFILE, '<',
783      "CA file for certificate verification (PEM format)"},
784     {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
785     {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
786 #ifndef OPENSSL_NO_OCSP
787     {"status", OPT_STATUS, '-', "Request certificate status from server"},
788     {"status_verbose", OPT_STATUS_VERBOSE, '-',
789      "Print more output in certificate status callback"},
790     {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
791      "Status request responder timeout"},
792     {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
793 #endif
794 #ifndef OPENSSL_NO_SSL_TRACE
795     {"trace", OPT_TRACE, '-', "trace protocol messages"},
796 #endif
797     {"security_debug", OPT_SECURITY_DEBUG, '-',
798      "Print output from SSL/TLS security framework"},
799     {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
800      "Print more output from SSL/TLS security framework"},
801     {"brief", OPT_BRIEF, '-',
802      "Restrict output to brief summary of connection parameters"},
803     {"rev", OPT_REV, '-',
804      "act as a simple test server which just sends back with the received text reversed"},
805     {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
806     {"ssl_config", OPT_SSL_CONFIG, 's',
807      "Configure SSL_CTX using the configuration 'val'"},
808     {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'n',
809      "Size used to split data for encrypt pipelines"},
810     {"max_pipelines", OPT_MAX_PIPELINES, 'n',
811      "Maximum number of encrypt/decrypt pipelines to be used"},
812     {"read_buf", OPT_READ_BUF, 'n',
813      "Default read buffer size to be used for connections"},
814     OPT_S_OPTIONS,
815     OPT_V_OPTIONS,
816     OPT_X_OPTIONS,
817     {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
818 #ifndef OPENSSL_NO_PSK
819     {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
820     {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
821 #endif
822 #ifndef OPENSSL_NO_SRP
823     {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
824     {"srpuserseed", OPT_SRPUSERSEED, 's',
825      "A seed string for a default user salt"},
826 #endif
827 #ifndef OPENSSL_NO_SSL3
828     {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
829 #endif
830 #ifndef OPENSSL_NO_TLS1
831     {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
832 #endif
833 #ifndef OPENSSL_NO_TLS1_1
834     {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
835 #endif
836 #ifndef OPENSSL_NO_TLS1_2
837     {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
838 #endif
839 #ifndef OPENSSL_NO_DTLS
840     {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
841     {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
842     {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
843     {"listen", OPT_LISTEN, '-',
844      "Listen for a DTLS ClientHello with a cookie and then connect"},
845 #endif
846 #ifndef OPENSSL_NO_DTLS1
847     {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
848 #endif
849 #ifndef OPENSSL_NO_DTLS1_2
850     {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
851 #endif
852 #ifndef OPENSSL_NO_DH
853     {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
854 #endif
855 #ifndef OPENSSL_NO_NEXTPROTONEG
856     {"nextprotoneg", OPT_NEXTPROTONEG, 's',
857      "Set the advertised protocols for the NPN extension (comma-separated list)"},
858 #endif
859 #ifndef OPENSSL_NO_SRTP
860     {"use_srtp", OPT_SRTP_PROFILES, 's',
861      "Offer SRTP key management with a colon-separated profile list"},
862 #endif
863     {"alpn", OPT_ALPN, 's',
864      "Set the advertised protocols for the ALPN extension (comma-separated list)"},
865 #ifndef OPENSSL_NO_ENGINE
866     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
867 #endif
868     {NULL, OPT_EOF, 0, NULL}
869 };
870
871 #define IS_PROT_FLAG(o) \
872  (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
873   || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
874
875 int s_server_main(int argc, char *argv[])
876 {
877     ENGINE *engine = NULL;
878     EVP_PKEY *s_key = NULL, *s_dkey = NULL;
879     SSL_CONF_CTX *cctx = NULL;
880     const SSL_METHOD *meth = TLS_server_method();
881     SSL_EXCERT *exc = NULL;
882     STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
883     STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
884     STACK_OF(X509_CRL) *crls = NULL;
885     X509 *s_cert = NULL, *s_dcert = NULL;
886     X509_VERIFY_PARAM *vpm = NULL;
887     const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
888     char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
889     char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
890     char *crl_file = NULL, *prog;
891 #ifdef AF_UNIX
892     int unlink_unix_path = 0;
893 #endif
894     do_server_cb server_cb;
895     int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
896 #ifndef OPENSSL_NO_DH
897     char *dhfile = NULL;
898     int no_dhe = 0;
899 #endif
900     int nocert = 0, ret = 1;
901     int noCApath = 0, noCAfile = 0;
902     int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
903     int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
904     int rev = 0, naccept = -1, sdebug = 0;
905     int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM;
906     int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
907     char *host = NULL;
908     char *port = BUF_strdup(PORT);
909     unsigned char *context = NULL;
910     OPTION_CHOICE o;
911     EVP_PKEY *s_key2 = NULL;
912     X509 *s_cert2 = NULL;
913     tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
914     const char *ssl_config = NULL;
915     int read_buf_len = 0;
916 #ifndef OPENSSL_NO_NEXTPROTONEG
917     const char *next_proto_neg_in = NULL;
918     tlsextnextprotoctx next_proto = { NULL, 0 };
919 #endif
920     const char *alpn_in = NULL;
921     tlsextalpnctx alpn_ctx = { NULL, 0 };
922 #ifndef OPENSSL_NO_PSK
923     /* by default do not send a PSK identity hint */
924     char *psk_identity_hint = NULL;
925     char *p;
926 #endif
927 #ifndef OPENSSL_NO_SRP
928     char *srpuserseed = NULL;
929     char *srp_verifier_file = NULL;
930 #endif
931     int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
932     int s_server_verify = SSL_VERIFY_NONE;
933     int s_server_session_id_context = 1; /* anything will do */
934     const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
935     const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
936     char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
937 #ifndef OPENSSL_NO_OCSP
938     int s_tlsextstatus = 0;
939 #endif
940     int no_resume_ephemeral = 0;
941     unsigned int split_send_fragment = 0, max_pipelines = 0;
942     const char *s_serverinfo_file = NULL;
943
944     /* Init of few remaining global variables */
945     local_argc = argc;
946     local_argv = argv;
947
948     ctx = ctx2 = NULL;
949     s_nbio = s_nbio_test = 0;
950     www = 0;
951     bio_s_out = NULL;
952     s_debug = 0;
953     s_msg = 0;
954     s_quiet = 0;
955     s_brief = 0;
956     async = 0;
957
958     cctx = SSL_CONF_CTX_new();
959     vpm = X509_VERIFY_PARAM_new();
960     if (cctx == NULL || vpm == NULL)
961         goto end;
962     SSL_CONF_CTX_set_flags(cctx,
963                            SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
964
965     prog = opt_init(argc, argv, s_server_options);
966     while ((o = opt_next()) != OPT_EOF) {
967         if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
968             BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
969             goto end;
970         }
971         if (IS_NO_PROT_FLAG(o))
972             no_prot_opt++;
973         if (prot_opt == 1 && no_prot_opt) {
974             BIO_printf(bio_err,
975                        "Cannot supply both a protocol flag and '-no_<prot>'\n");
976             goto end;
977         }
978         switch (o) {
979         case OPT_EOF:
980         case OPT_ERR:
981  opthelp:
982             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
983             goto end;
984         case OPT_HELP:
985             opt_help(s_server_options);
986             ret = 0;
987             goto end;
988
989         case OPT_4:
990 #ifdef AF_UNIX
991             if (socket_family == AF_UNIX) {
992                 OPENSSL_free(host); host = NULL;
993                 OPENSSL_free(port); port = NULL;
994             }
995 #endif
996             socket_family = AF_INET;
997             break;
998         case OPT_6:
999             if (1) {
1000 #ifdef AF_INET6
1001 #ifdef AF_UNIX
1002                 if (socket_family == AF_UNIX) {
1003                     OPENSSL_free(host); host = NULL;
1004                     OPENSSL_free(port); port = NULL;
1005                 }
1006 #endif
1007                 socket_family = AF_INET6;
1008             } else {
1009 #endif
1010                 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1011                 goto end;
1012             }
1013             break;
1014         case OPT_PORT:
1015 #ifdef AF_UNIX
1016             if (socket_family == AF_UNIX) {
1017                 socket_family = AF_UNSPEC;
1018             }
1019 #endif
1020             OPENSSL_free(port); port = NULL;
1021             OPENSSL_free(host); host = NULL;
1022             if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1023                 BIO_printf(bio_err,
1024                            "%s: -port argument malformed or ambiguous\n",
1025                            port);
1026                 goto end;
1027             }
1028             break;
1029         case OPT_ACCEPT:
1030 #ifdef AF_UNIX
1031             if (socket_family == AF_UNIX) {
1032                 socket_family = AF_UNSPEC;
1033             }
1034 #endif
1035             OPENSSL_free(port); port = NULL;
1036             OPENSSL_free(host); host = NULL;
1037             if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1038                 BIO_printf(bio_err,
1039                            "%s: -accept argument malformed or ambiguous\n",
1040                            port);
1041                 goto end;
1042             }
1043             break;
1044 #ifdef AF_UNIX
1045         case OPT_UNIX:
1046             socket_family = AF_UNIX;
1047             OPENSSL_free(host); host = BUF_strdup(opt_arg());
1048             OPENSSL_free(port); port = NULL;
1049             break;
1050         case OPT_UNLINK:
1051             unlink_unix_path = 1;
1052             break;
1053 #endif
1054         case OPT_NACCEPT:
1055             naccept = atol(opt_arg());
1056             break;
1057         case OPT_VERIFY:
1058             s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1059             verify_args.depth = atoi(opt_arg());
1060             if (!s_quiet)
1061                 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1062             break;
1063         case OPT_UPPER_V_VERIFY:
1064             s_server_verify =
1065                 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1066                 SSL_VERIFY_CLIENT_ONCE;
1067             verify_args.depth = atoi(opt_arg());
1068             if (!s_quiet)
1069                 BIO_printf(bio_err,
1070                            "verify depth is %d, must return a certificate\n",
1071                            verify_args.depth);
1072             break;
1073         case OPT_CONTEXT:
1074             context = (unsigned char *)opt_arg();
1075             break;
1076         case OPT_CERT:
1077             s_cert_file = opt_arg();
1078             break;
1079         case OPT_CRL:
1080             crl_file = opt_arg();
1081             break;
1082         case OPT_CRL_DOWNLOAD:
1083             crl_download = 1;
1084             break;
1085         case OPT_SERVERINFO:
1086             s_serverinfo_file = opt_arg();
1087             break;
1088         case OPT_CERTFORM:
1089             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1090                 goto opthelp;
1091             break;
1092         case OPT_KEY:
1093             s_key_file = opt_arg();
1094             break;
1095         case OPT_KEYFORM:
1096             if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1097                 goto opthelp;
1098             break;
1099         case OPT_PASS:
1100             passarg = opt_arg();
1101             break;
1102         case OPT_CERT_CHAIN:
1103             s_chain_file = opt_arg();
1104             break;
1105         case OPT_DHPARAM:
1106 #ifndef OPENSSL_NO_DH
1107             dhfile = opt_arg();
1108 #endif
1109             break;
1110         case OPT_DCERTFORM:
1111             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1112                 goto opthelp;
1113             break;
1114         case OPT_DCERT:
1115             s_dcert_file = opt_arg();
1116             break;
1117         case OPT_DKEYFORM:
1118             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1119                 goto opthelp;
1120             break;
1121         case OPT_DPASS:
1122             dpassarg = opt_arg();
1123             break;
1124         case OPT_DKEY:
1125             s_dkey_file = opt_arg();
1126             break;
1127         case OPT_DCERT_CHAIN:
1128             s_dchain_file = opt_arg();
1129             break;
1130         case OPT_NOCERT:
1131             nocert = 1;
1132             break;
1133         case OPT_CAPATH:
1134             CApath = opt_arg();
1135             break;
1136         case OPT_NOCAPATH:
1137             noCApath = 1;
1138             break;
1139         case OPT_CHAINCAPATH:
1140             chCApath = opt_arg();
1141             break;
1142         case OPT_VERIFYCAPATH:
1143             vfyCApath = opt_arg();
1144             break;
1145         case OPT_NO_CACHE:
1146             no_cache = 1;
1147             break;
1148         case OPT_EXT_CACHE:
1149             ext_cache = 1;
1150             break;
1151         case OPT_CRLFORM:
1152             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1153                 goto opthelp;
1154             break;
1155         case OPT_S_CASES:
1156             if (ssl_args == NULL)
1157                 ssl_args = sk_OPENSSL_STRING_new_null();
1158             if (ssl_args == NULL
1159                 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1160                 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1161                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1162                 goto end;
1163             }
1164             break;
1165         case OPT_V_CASES:
1166             if (!opt_verify(o, vpm))
1167                 goto end;
1168             vpmtouched++;
1169             break;
1170         case OPT_X_CASES:
1171             if (!args_excert(o, &exc))
1172                 goto end;
1173             break;
1174         case OPT_VERIFY_RET_ERROR:
1175             verify_args.return_error = 1;
1176             break;
1177         case OPT_VERIFY_QUIET:
1178             verify_args.quiet = 1;
1179             break;
1180         case OPT_BUILD_CHAIN:
1181             build_chain = 1;
1182             break;
1183         case OPT_CAFILE:
1184             CAfile = opt_arg();
1185             break;
1186         case OPT_NOCAFILE:
1187             noCAfile = 1;
1188             break;
1189         case OPT_CHAINCAFILE:
1190             chCAfile = opt_arg();
1191             break;
1192         case OPT_VERIFYCAFILE:
1193             vfyCAfile = opt_arg();
1194             break;
1195         case OPT_NBIO:
1196             s_nbio = 1;
1197             break;
1198         case OPT_NBIO_TEST:
1199             s_nbio = s_nbio_test = 1;
1200             break;
1201         case OPT_IGN_EOF:
1202             s_ign_eof = 1;
1203             break;
1204         case OPT_NO_IGN_EOF:
1205             s_ign_eof = 0;
1206             break;
1207         case OPT_DEBUG:
1208             s_debug = 1;
1209             break;
1210         case OPT_TLSEXTDEBUG:
1211             s_tlsextdebug = 1;
1212             break;
1213         case OPT_STATUS:
1214 #ifndef OPENSSL_NO_OCSP
1215             s_tlsextstatus = 1;
1216 #endif
1217             break;
1218         case OPT_STATUS_VERBOSE:
1219 #ifndef OPENSSL_NO_OCSP
1220             s_tlsextstatus = tlscstatp.verbose = 1;
1221 #endif
1222             break;
1223         case OPT_STATUS_TIMEOUT:
1224 #ifndef OPENSSL_NO_OCSP
1225             s_tlsextstatus = 1;
1226             tlscstatp.timeout = atoi(opt_arg());
1227 #endif
1228             break;
1229         case OPT_STATUS_URL:
1230 #ifndef OPENSSL_NO_OCSP
1231             s_tlsextstatus = 1;
1232             if (!OCSP_parse_url(opt_arg(),
1233                                 &tlscstatp.host,
1234                                 &tlscstatp.port,
1235                                 &tlscstatp.path, &tlscstatp.use_ssl)) {
1236                 BIO_printf(bio_err, "Error parsing URL\n");
1237                 goto end;
1238             }
1239 #endif
1240             break;
1241         case OPT_MSG:
1242             s_msg = 1;
1243             break;
1244         case OPT_MSGFILE:
1245             bio_s_msg = BIO_new_file(opt_arg(), "w");
1246             break;
1247         case OPT_TRACE:
1248 #ifndef OPENSSL_NO_SSL_TRACE
1249             s_msg = 2;
1250 #endif
1251             break;
1252         case OPT_SECURITY_DEBUG:
1253             sdebug = 1;
1254             break;
1255         case OPT_SECURITY_DEBUG_VERBOSE:
1256             sdebug = 2;
1257             break;
1258         case OPT_STATE:
1259             state = 1;
1260             break;
1261         case OPT_CRLF:
1262             s_crlf = 1;
1263             break;
1264         case OPT_QUIET:
1265             s_quiet = 1;
1266             break;
1267         case OPT_BRIEF:
1268             s_quiet = s_brief = verify_args.quiet = 1;
1269             break;
1270         case OPT_NO_DHE:
1271 #ifndef OPENSSL_NO_DH
1272             no_dhe = 1;
1273 #endif
1274             break;
1275         case OPT_NO_RESUME_EPHEMERAL:
1276             no_resume_ephemeral = 1;
1277             break;
1278         case OPT_PSK_HINT:
1279 #ifndef OPENSSL_NO_PSK
1280             psk_identity_hint = opt_arg();
1281 #endif
1282             break;
1283         case OPT_PSK:
1284 #ifndef OPENSSL_NO_PSK
1285             for (p = psk_key = opt_arg(); *p; p++) {
1286                 if (isxdigit(_UC(*p)))
1287                     continue;
1288                 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1289                 goto end;
1290             }
1291 #endif
1292             break;
1293         case OPT_SRPVFILE:
1294 #ifndef OPENSSL_NO_SRP
1295             srp_verifier_file = opt_arg();
1296             if (min_version < TLS1_VERSION)
1297                 min_version = TLS1_VERSION;
1298 #endif
1299             break;
1300         case OPT_SRPUSERSEED:
1301 #ifndef OPENSSL_NO_SRP
1302             srpuserseed = opt_arg();
1303             if (min_version < TLS1_VERSION)
1304                 min_version = TLS1_VERSION;
1305 #endif
1306             break;
1307         case OPT_REV:
1308             rev = 1;
1309             break;
1310         case OPT_WWW:
1311             www = 1;
1312             break;
1313         case OPT_UPPER_WWW:
1314             www = 2;
1315             break;
1316         case OPT_HTTP:
1317             www = 3;
1318             break;
1319         case OPT_SSL_CONFIG:
1320             ssl_config = opt_arg();
1321             break;
1322         case OPT_SSL3:
1323             min_version = SSL3_VERSION;
1324             max_version = SSL3_VERSION;
1325             break;
1326         case OPT_TLS1_2:
1327             min_version = TLS1_2_VERSION;
1328             max_version = TLS1_2_VERSION;
1329             break;
1330         case OPT_TLS1_1:
1331             min_version = TLS1_1_VERSION;
1332             max_version = TLS1_1_VERSION;
1333             break;
1334         case OPT_TLS1:
1335             min_version = TLS1_VERSION;
1336             max_version = TLS1_VERSION;
1337             break;
1338         case OPT_DTLS:
1339 #ifndef OPENSSL_NO_DTLS
1340             meth = DTLS_server_method();
1341             socket_type = SOCK_DGRAM;
1342 #endif
1343             break;
1344         case OPT_DTLS1:
1345 #ifndef OPENSSL_NO_DTLS
1346             meth = DTLS_server_method();
1347             min_version = DTLS1_VERSION;
1348             max_version = DTLS1_VERSION;
1349             socket_type = SOCK_DGRAM;
1350 #endif
1351             break;
1352         case OPT_DTLS1_2:
1353 #ifndef OPENSSL_NO_DTLS
1354             meth = DTLS_server_method();
1355             min_version = DTLS1_2_VERSION;
1356             max_version = DTLS1_2_VERSION;
1357             socket_type = SOCK_DGRAM;
1358 #endif
1359             break;
1360         case OPT_TIMEOUT:
1361 #ifndef OPENSSL_NO_DTLS
1362             enable_timeouts = 1;
1363 #endif
1364             break;
1365         case OPT_MTU:
1366 #ifndef OPENSSL_NO_DTLS
1367             socket_mtu = atol(opt_arg());
1368 #endif
1369             break;
1370         case OPT_LISTEN:
1371 #ifndef OPENSSL_NO_DTLS
1372             dtlslisten = 1;
1373 #endif
1374             break;
1375         case OPT_ID_PREFIX:
1376             session_id_prefix = opt_arg();
1377             break;
1378         case OPT_ENGINE:
1379             engine = setup_engine(opt_arg(), 1);
1380             break;
1381         case OPT_RAND:
1382             inrand = opt_arg();
1383             break;
1384         case OPT_SERVERNAME:
1385             tlsextcbp.servername = opt_arg();
1386             break;
1387         case OPT_SERVERNAME_FATAL:
1388             tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1389             break;
1390         case OPT_CERT2:
1391             s_cert_file2 = opt_arg();
1392             break;
1393         case OPT_KEY2:
1394             s_key_file2 = opt_arg();
1395             break;
1396         case OPT_NEXTPROTONEG:
1397 # ifndef OPENSSL_NO_NEXTPROTONEG
1398             next_proto_neg_in = opt_arg();
1399 #endif
1400             break;
1401         case OPT_ALPN:
1402             alpn_in = opt_arg();
1403             break;
1404         case OPT_SRTP_PROFILES:
1405 #ifndef OPENSSL_NO_SRTP
1406             srtp_profiles = opt_arg();
1407 #endif
1408             break;
1409         case OPT_KEYMATEXPORT:
1410             keymatexportlabel = opt_arg();
1411             break;
1412         case OPT_KEYMATEXPORTLEN:
1413             keymatexportlen = atoi(opt_arg());
1414             break;
1415         case OPT_ASYNC:
1416             async = 1;
1417             break;
1418         case OPT_SPLIT_SEND_FRAG:
1419             split_send_fragment = atoi(opt_arg());
1420             if (split_send_fragment == 0) {
1421                 /*
1422                  * Not allowed - set to a deliberately bad value so we get an
1423                  * error message below
1424                  */
1425                 split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1;
1426             }
1427             break;
1428         case OPT_MAX_PIPELINES:
1429             max_pipelines = atoi(opt_arg());
1430             break;
1431         case OPT_READ_BUF:
1432             read_buf_len = atoi(opt_arg());
1433             break;
1434
1435         }
1436     }
1437     argc = opt_num_rest();
1438     argv = opt_rest();
1439
1440 #ifndef OPENSSL_NO_DTLS
1441     if (www && socket_type == SOCK_DGRAM) {
1442         BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1443         goto end;
1444     }
1445
1446     if (dtlslisten && socket_type != SOCK_DGRAM) {
1447         BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1448         goto end;
1449     }
1450 #endif
1451
1452 #ifdef AF_UNIX
1453     if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1454         BIO_printf(bio_err,
1455                    "Can't use unix sockets and datagrams together\n");
1456         goto end;
1457     }
1458 #endif
1459
1460     if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1461         BIO_printf(bio_err, "Bad split send fragment size\n");
1462         goto end;
1463     }
1464
1465     if (max_pipelines > SSL_MAX_PIPELINES) {
1466         BIO_printf(bio_err, "Bad max pipelines value\n");
1467         goto end;
1468     }
1469
1470     if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1471         BIO_printf(bio_err, "Error getting password\n");
1472         goto end;
1473     }
1474
1475     if (s_key_file == NULL)
1476         s_key_file = s_cert_file;
1477
1478     if (s_key_file2 == NULL)
1479         s_key_file2 = s_cert_file2;
1480
1481     if (!load_excert(&exc))
1482         goto end;
1483
1484     if (nocert == 0) {
1485         s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1486                          "server certificate private key file");
1487         if (!s_key) {
1488             ERR_print_errors(bio_err);
1489             goto end;
1490         }
1491
1492         s_cert = load_cert(s_cert_file, s_cert_format,
1493                            "server certificate file");
1494
1495         if (!s_cert) {
1496             ERR_print_errors(bio_err);
1497             goto end;
1498         }
1499         if (s_chain_file) {
1500             if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1501                             "server certificate chain"))
1502                 goto end;
1503         }
1504
1505         if (tlsextcbp.servername) {
1506             s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1507                               "second server certificate private key file");
1508             if (!s_key2) {
1509                 ERR_print_errors(bio_err);
1510                 goto end;
1511             }
1512
1513             s_cert2 = load_cert(s_cert_file2, s_cert_format,
1514                                 "second server certificate file");
1515
1516             if (!s_cert2) {
1517                 ERR_print_errors(bio_err);
1518                 goto end;
1519             }
1520         }
1521     }
1522 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1523     if (next_proto_neg_in) {
1524         next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1525         if (next_proto.data == NULL)
1526             goto end;
1527     }
1528 #endif
1529     alpn_ctx.data = NULL;
1530     if (alpn_in) {
1531         alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1532         if (alpn_ctx.data == NULL)
1533             goto end;
1534     }
1535
1536     if (crl_file) {
1537         X509_CRL *crl;
1538         crl = load_crl(crl_file, crl_format);
1539         if (!crl) {
1540             BIO_puts(bio_err, "Error loading CRL\n");
1541             ERR_print_errors(bio_err);
1542             goto end;
1543         }
1544         crls = sk_X509_CRL_new_null();
1545         if (!crls || !sk_X509_CRL_push(crls, crl)) {
1546             BIO_puts(bio_err, "Error adding CRL\n");
1547             ERR_print_errors(bio_err);
1548             X509_CRL_free(crl);
1549             goto end;
1550         }
1551     }
1552
1553     if (s_dcert_file) {
1554
1555         if (s_dkey_file == NULL)
1556             s_dkey_file = s_dcert_file;
1557
1558         s_dkey = load_key(s_dkey_file, s_dkey_format,
1559                           0, dpass, engine, "second certificate private key file");
1560         if (!s_dkey) {
1561             ERR_print_errors(bio_err);
1562             goto end;
1563         }
1564
1565         s_dcert = load_cert(s_dcert_file, s_dcert_format,
1566                             "second server certificate file");
1567
1568         if (!s_dcert) {
1569             ERR_print_errors(bio_err);
1570             goto end;
1571         }
1572         if (s_dchain_file) {
1573             if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1574                             "second server certificate chain"))
1575                 goto end;
1576         }
1577
1578     }
1579
1580     if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1581         && !RAND_status()) {
1582         BIO_printf(bio_err,
1583                    "warning, not much extra random data, consider using the -rand option\n");
1584     }
1585     if (inrand != NULL)
1586         BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1587                    app_RAND_load_files(inrand));
1588
1589     if (bio_s_out == NULL) {
1590         if (s_quiet && !s_debug) {
1591             bio_s_out = BIO_new(BIO_s_null());
1592             if (s_msg && !bio_s_msg)
1593                 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1594         } else {
1595             if (bio_s_out == NULL)
1596                 bio_s_out = dup_bio_out(FORMAT_TEXT);
1597         }
1598     }
1599 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1600     if (nocert)
1601 #endif
1602     {
1603         s_cert_file = NULL;
1604         s_key_file = NULL;
1605         s_dcert_file = NULL;
1606         s_dkey_file = NULL;
1607         s_cert_file2 = NULL;
1608         s_key_file2 = NULL;
1609     }
1610
1611     ctx = SSL_CTX_new(meth);
1612     if (ctx == NULL) {
1613         ERR_print_errors(bio_err);
1614         goto end;
1615     }
1616     if (sdebug)
1617         ssl_ctx_security_debug(ctx, sdebug);
1618
1619     if (!config_ctx(cctx, ssl_args, ctx))
1620         goto end;
1621
1622     if (ssl_config) {
1623         if (SSL_CTX_config(ctx, ssl_config) == 0) {
1624             BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1625                        ssl_config);
1626             ERR_print_errors(bio_err);
1627             goto end;
1628         }
1629     }
1630     if (min_version != 0
1631         && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1632         goto end;
1633     if (max_version != 0
1634         && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1635         goto end;
1636
1637     if (session_id_prefix) {
1638         if (strlen(session_id_prefix) >= 32)
1639             BIO_printf(bio_err,
1640                        "warning: id_prefix is too long, only one new session will be possible\n");
1641         if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1642             BIO_printf(bio_err, "error setting 'id_prefix'\n");
1643             ERR_print_errors(bio_err);
1644             goto end;
1645         }
1646         BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1647     }
1648     SSL_CTX_set_quiet_shutdown(ctx, 1);
1649     if (exc)
1650         ssl_ctx_set_excert(ctx, exc);
1651
1652     if (state)
1653         SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1654     if (no_cache)
1655         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1656     else if (ext_cache)
1657         init_session_cache_ctx(ctx);
1658     else
1659         SSL_CTX_sess_set_cache_size(ctx, 128);
1660
1661     if (async) {
1662         SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1663     }
1664     if (split_send_fragment > 0) {
1665         SSL_CTX_set_split_send_fragment(ctx, split_send_fragment);
1666     }
1667     if (max_pipelines > 0) {
1668         SSL_CTX_set_max_pipelines(ctx, max_pipelines);
1669     }
1670
1671     if (read_buf_len > 0) {
1672         SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1673     }
1674 #ifndef OPENSSL_NO_SRTP
1675     if (srtp_profiles != NULL) {
1676         /* Returns 0 on success! */
1677         if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1678             BIO_printf(bio_err, "Error setting SRTP profile\n");
1679             ERR_print_errors(bio_err);
1680             goto end;
1681         }
1682     }
1683 #endif
1684
1685     if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1686         ERR_print_errors(bio_err);
1687         goto end;
1688     }
1689     if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1690         BIO_printf(bio_err, "Error setting verify params\n");
1691         ERR_print_errors(bio_err);
1692         goto end;
1693     }
1694
1695     ssl_ctx_add_crls(ctx, crls, 0);
1696
1697     if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1698                          crls, crl_download)) {
1699         BIO_printf(bio_err, "Error loading store locations\n");
1700         ERR_print_errors(bio_err);
1701         goto end;
1702     }
1703
1704     if (s_cert2) {
1705         ctx2 = SSL_CTX_new(meth);
1706         if (ctx2 == NULL) {
1707             ERR_print_errors(bio_err);
1708             goto end;
1709         }
1710     }
1711
1712     if (ctx2) {
1713         BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1714
1715         if (sdebug)
1716             ssl_ctx_security_debug(ctx, sdebug);
1717
1718         if (session_id_prefix) {
1719             if (strlen(session_id_prefix) >= 32)
1720                 BIO_printf(bio_err,
1721                            "warning: id_prefix is too long, only one new session will be possible\n");
1722             if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1723                 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1724                 ERR_print_errors(bio_err);
1725                 goto end;
1726             }
1727             BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1728         }
1729         SSL_CTX_set_quiet_shutdown(ctx2, 1);
1730         if (exc)
1731             ssl_ctx_set_excert(ctx2, exc);
1732
1733         if (state)
1734             SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1735
1736         if (no_cache)
1737             SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1738         else if (ext_cache)
1739             init_session_cache_ctx(ctx2);
1740         else
1741             SSL_CTX_sess_set_cache_size(ctx2, 128);
1742
1743         if (async)
1744             SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1745
1746         if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1747                                       noCApath)) {
1748             ERR_print_errors(bio_err);
1749             goto end;
1750         }
1751         if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1752             BIO_printf(bio_err, "Error setting verify params\n");
1753             ERR_print_errors(bio_err);
1754             goto end;
1755         }
1756
1757         ssl_ctx_add_crls(ctx2, crls, 0);
1758         if (!config_ctx(cctx, ssl_args, ctx2))
1759             goto end;
1760     }
1761 #ifndef OPENSSL_NO_NEXTPROTONEG
1762     if (next_proto.data)
1763         SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1764                                               &next_proto);
1765 #endif
1766     if (alpn_ctx.data)
1767         SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1768
1769 #ifndef OPENSSL_NO_DH
1770     if (!no_dhe) {
1771         DH *dh = NULL;
1772
1773         if (dhfile)
1774             dh = load_dh_param(dhfile);
1775         else if (s_cert_file)
1776             dh = load_dh_param(s_cert_file);
1777
1778         if (dh != NULL) {
1779             BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1780         } else {
1781             BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1782         }
1783         (void)BIO_flush(bio_s_out);
1784
1785         if (dh == NULL)
1786             SSL_CTX_set_dh_auto(ctx, 1);
1787         else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1788             BIO_puts(bio_err, "Error setting temp DH parameters\n");
1789             ERR_print_errors(bio_err);
1790             DH_free(dh);
1791             goto end;
1792         }
1793
1794         if (ctx2) {
1795             if (!dhfile) {
1796                 DH *dh2 = load_dh_param(s_cert_file2);
1797                 if (dh2 != NULL) {
1798                     BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1799                     (void)BIO_flush(bio_s_out);
1800
1801                     DH_free(dh);
1802                     dh = dh2;
1803                 }
1804             }
1805             if (dh == NULL)
1806                 SSL_CTX_set_dh_auto(ctx2, 1);
1807             else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1808                 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1809                 ERR_print_errors(bio_err);
1810                 DH_free(dh);
1811                 goto end;
1812             }
1813         }
1814         DH_free(dh);
1815     }
1816 #endif
1817
1818     if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1819         goto end;
1820
1821     if (s_serverinfo_file != NULL
1822         && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1823         ERR_print_errors(bio_err);
1824         goto end;
1825     }
1826
1827     if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1828         goto end;
1829
1830     if (s_dcert != NULL) {
1831         if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1832             goto end;
1833     }
1834
1835     if (no_resume_ephemeral) {
1836         SSL_CTX_set_not_resumable_session_callback(ctx,
1837                                                    not_resumable_sess_cb);
1838
1839         if (ctx2)
1840             SSL_CTX_set_not_resumable_session_callback(ctx2,
1841                                                        not_resumable_sess_cb);
1842     }
1843 #ifndef OPENSSL_NO_PSK
1844     if (psk_key != NULL) {
1845         if (s_debug)
1846             BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
1847         SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1848     }
1849
1850     if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1851         BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1852         ERR_print_errors(bio_err);
1853         goto end;
1854     }
1855 #endif
1856
1857     SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1858     if (!SSL_CTX_set_session_id_context(ctx,
1859                                         (void *)&s_server_session_id_context,
1860                                         sizeof(s_server_session_id_context))) {
1861         BIO_printf(bio_err, "error setting session id context\n");
1862         ERR_print_errors(bio_err);
1863         goto end;
1864     }
1865
1866     /* Set DTLS cookie generation and verification callbacks */
1867     SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1868     SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1869
1870     if (ctx2) {
1871         SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1872         if (!SSL_CTX_set_session_id_context(ctx2,
1873                     (void *)&s_server_session_id_context,
1874                     sizeof(s_server_session_id_context))) {
1875             BIO_printf(bio_err, "error setting session id context\n");
1876             ERR_print_errors(bio_err);
1877             goto end;
1878         }
1879         tlsextcbp.biodebug = bio_s_out;
1880         SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1881         SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1882         SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1883         SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1884     }
1885
1886 #ifndef OPENSSL_NO_SRP
1887     if (srp_verifier_file != NULL) {
1888         srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1889         srp_callback_parm.user = NULL;
1890         srp_callback_parm.login = NULL;
1891         if ((ret =
1892              SRP_VBASE_init(srp_callback_parm.vb,
1893                             srp_verifier_file)) != SRP_NO_ERROR) {
1894             BIO_printf(bio_err,
1895                        "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1896                        srp_verifier_file, ret);
1897             goto end;
1898         }
1899         SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
1900         SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
1901         SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1902     } else
1903 #endif
1904     if (CAfile != NULL) {
1905         SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
1906
1907         if (ctx2)
1908             SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
1909     }
1910 #ifndef OPENSSL_NO_OCSP
1911     if (s_tlsextstatus) {
1912         SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1913         SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1914         if (ctx2) {
1915             SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
1916             SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
1917         }
1918     }
1919 #endif
1920
1921     BIO_printf(bio_s_out, "ACCEPT\n");
1922     (void)BIO_flush(bio_s_out);
1923     if (rev)
1924         server_cb = rev_body;
1925     else if (www)
1926         server_cb = www_body;
1927     else
1928         server_cb = sv_body;
1929 #ifdef AF_UNIX
1930     if (socket_family == AF_UNIX
1931         && unlink_unix_path)
1932         unlink(host);
1933 #endif
1934     do_server(&accept_socket, host, port, socket_family, socket_type,
1935               server_cb, context, naccept);
1936     print_stats(bio_s_out, ctx);
1937     ret = 0;
1938  end:
1939     SSL_CTX_free(ctx);
1940     X509_free(s_cert);
1941     sk_X509_CRL_pop_free(crls, X509_CRL_free);
1942     X509_free(s_dcert);
1943     EVP_PKEY_free(s_key);
1944     EVP_PKEY_free(s_dkey);
1945     sk_X509_pop_free(s_chain, X509_free);
1946     sk_X509_pop_free(s_dchain, X509_free);
1947     OPENSSL_free(pass);
1948     OPENSSL_free(dpass);
1949     OPENSSL_free(host);
1950     OPENSSL_free(port);
1951     X509_VERIFY_PARAM_free(vpm);
1952     free_sessions();
1953     OPENSSL_free(tlscstatp.host);
1954     OPENSSL_free(tlscstatp.port);
1955     OPENSSL_free(tlscstatp.path);
1956     SSL_CTX_free(ctx2);
1957     X509_free(s_cert2);
1958     EVP_PKEY_free(s_key2);
1959 #ifndef OPENSSL_NO_NEXTPROTONEG
1960     OPENSSL_free(next_proto.data);
1961 #endif
1962     OPENSSL_free(alpn_ctx.data);
1963     ssl_excert_free(exc);
1964     sk_OPENSSL_STRING_free(ssl_args);
1965     SSL_CONF_CTX_free(cctx);
1966     release_engine(engine);
1967     BIO_free(bio_s_out);
1968     bio_s_out = NULL;
1969     BIO_free(bio_s_msg);
1970     bio_s_msg = NULL;
1971 #ifdef CHARSET_EBCDIC
1972     BIO_meth_free(methods_ebcdic);
1973 #endif
1974     return (ret);
1975 }
1976
1977 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
1978 {
1979     BIO_printf(bio, "%4ld items in the session cache\n",
1980                SSL_CTX_sess_number(ssl_ctx));
1981     BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
1982                SSL_CTX_sess_connect(ssl_ctx));
1983     BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
1984                SSL_CTX_sess_connect_renegotiate(ssl_ctx));
1985     BIO_printf(bio, "%4ld client connects that finished\n",
1986                SSL_CTX_sess_connect_good(ssl_ctx));
1987     BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
1988                SSL_CTX_sess_accept(ssl_ctx));
1989     BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
1990                SSL_CTX_sess_accept_renegotiate(ssl_ctx));
1991     BIO_printf(bio, "%4ld server accepts that finished\n",
1992                SSL_CTX_sess_accept_good(ssl_ctx));
1993     BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
1994     BIO_printf(bio, "%4ld session cache misses\n",
1995                SSL_CTX_sess_misses(ssl_ctx));
1996     BIO_printf(bio, "%4ld session cache timeouts\n",
1997                SSL_CTX_sess_timeouts(ssl_ctx));
1998     BIO_printf(bio, "%4ld callback cache hits\n",
1999                SSL_CTX_sess_cb_hits(ssl_ctx));
2000     BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2001                SSL_CTX_sess_cache_full(ssl_ctx),
2002                SSL_CTX_sess_get_cache_size(ssl_ctx));
2003 }
2004
2005 static int sv_body(int s, int stype, unsigned char *context)
2006 {
2007     char *buf = NULL;
2008     fd_set readfds;
2009     int ret = 1, width;
2010     int k, i;
2011     unsigned long l;
2012     SSL *con = NULL;
2013     BIO *sbio;
2014     struct timeval timeout;
2015 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
2016     struct timeval *timeoutp;
2017 #endif
2018
2019     buf = app_malloc(bufsize, "server buffer");
2020     if (s_nbio) {
2021         if (!BIO_socket_nbio(s, 1))
2022             ERR_print_errors(bio_err);
2023         else if (!s_quiet)
2024             BIO_printf(bio_err, "Turned on non blocking io\n");
2025     }
2026
2027     if (con == NULL) {
2028         con = SSL_new(ctx);
2029
2030         if (s_tlsextdebug) {
2031             SSL_set_tlsext_debug_callback(con, tlsext_cb);
2032             SSL_set_tlsext_debug_arg(con, bio_s_out);
2033         }
2034
2035         if (context
2036             && !SSL_set_session_id_context(con,
2037                                            context, strlen((char *)context))) {
2038             BIO_printf(bio_err, "Error setting session id context\n");
2039             ret = -1;
2040             goto err;
2041         }
2042     }
2043     if (!SSL_clear(con)) {
2044         BIO_printf(bio_err, "Error clearing SSL connection\n");
2045         ret = -1;
2046         goto err;
2047     }
2048 #ifndef OPENSSL_NO_DTLS
2049     if (stype == SOCK_DGRAM) {
2050
2051         sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2052
2053         if (enable_timeouts) {
2054             timeout.tv_sec = 0;
2055             timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2056             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2057
2058             timeout.tv_sec = 0;
2059             timeout.tv_usec = DGRAM_SND_TIMEOUT;
2060             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2061         }
2062
2063         if (socket_mtu) {
2064             if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2065                 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2066                            DTLS_get_link_min_mtu(con));
2067                 ret = -1;
2068                 BIO_free(sbio);
2069                 goto err;
2070             }
2071             SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2072             if (!DTLS_set_link_mtu(con, socket_mtu)) {
2073                 BIO_printf(bio_err, "Failed to set MTU\n");
2074                 ret = -1;
2075                 BIO_free(sbio);
2076                 goto err;
2077             }
2078         } else
2079             /* want to do MTU discovery */
2080             BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2081
2082         /* turn on cookie exchange */
2083         SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2084     } else
2085 #endif
2086         sbio = BIO_new_socket(s, BIO_NOCLOSE);
2087
2088     if (s_nbio_test) {
2089         BIO *test;
2090
2091         test = BIO_new(BIO_f_nbio_test());
2092         sbio = BIO_push(test, sbio);
2093     }
2094
2095     SSL_set_bio(con, sbio, sbio);
2096     SSL_set_accept_state(con);
2097     /* SSL_set_fd(con,s); */
2098
2099     if (s_debug) {
2100         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2101         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2102     }
2103     if (s_msg) {
2104 #ifndef OPENSSL_NO_SSL_TRACE
2105         if (s_msg == 2)
2106             SSL_set_msg_callback(con, SSL_trace);
2107         else
2108 #endif
2109             SSL_set_msg_callback(con, msg_cb);
2110         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2111     }
2112
2113     if (s_tlsextdebug) {
2114         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2115         SSL_set_tlsext_debug_arg(con, bio_s_out);
2116     }
2117
2118     if (fileno_stdin() > s)
2119         width = fileno_stdin() + 1;
2120     else
2121         width = s + 1;
2122     for (;;) {
2123         int read_from_terminal;
2124         int read_from_sslcon;
2125
2126         read_from_terminal = 0;
2127         read_from_sslcon = SSL_has_pending(con)
2128                            || (async && SSL_waiting_for_async(con));
2129
2130         if (!read_from_sslcon) {
2131             FD_ZERO(&readfds);
2132 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2133             openssl_fdset(fileno_stdin(), &readfds);
2134 #endif
2135             openssl_fdset(s, &readfds);
2136             /*
2137              * Note: under VMS with SOCKETSHR the second parameter is
2138              * currently of type (int *) whereas under other systems it is
2139              * (void *) if you don't have a cast it will choke the compiler:
2140              * if you do have a cast then you can either go for (int *) or
2141              * (void *).
2142              */
2143 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2144             /*
2145              * Under DOS (non-djgpp) and Windows we can't select on stdin:
2146              * only on sockets. As a workaround we timeout the select every
2147              * second and check for any keypress. In a proper Windows
2148              * application we wouldn't do this because it is inefficient.
2149              */
2150             timeout.tv_sec = 1;
2151             timeout.tv_usec = 0;
2152             i = select(width, (void *)&readfds, NULL, NULL, &timeout);
2153             if (has_stdin_waiting())
2154                 read_from_terminal = 1;
2155             if ((i < 0) || (!i && !read_from_terminal))
2156                 continue;
2157 #else
2158             if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2159                 timeoutp = &timeout;
2160             else
2161                 timeoutp = NULL;
2162
2163             i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2164
2165             if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
2166                 BIO_printf(bio_err, "TIMEOUT occurred\n");
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 ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
2578         BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
2579
2580     if (keymatexportlabel != NULL) {
2581         BIO_printf(bio_s_out, "Keying material exporter:\n");
2582         BIO_printf(bio_s_out, "    Label: '%s'\n", keymatexportlabel);
2583         BIO_printf(bio_s_out, "    Length: %i bytes\n", keymatexportlen);
2584         exportedkeymat = app_malloc(keymatexportlen, "export key");
2585         if (!SSL_export_keying_material(con, exportedkeymat,
2586                                         keymatexportlen,
2587                                         keymatexportlabel,
2588                                         strlen(keymatexportlabel),
2589                                         NULL, 0, 0)) {
2590             BIO_printf(bio_s_out, "    Error\n");
2591         } else {
2592             BIO_printf(bio_s_out, "    Keying material: ");
2593             for (i = 0; i < keymatexportlen; i++)
2594                 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2595             BIO_printf(bio_s_out, "\n");
2596         }
2597         OPENSSL_free(exportedkeymat);
2598     }
2599
2600     (void)BIO_flush(bio_s_out);
2601     return (1);
2602 }
2603
2604 #ifndef OPENSSL_NO_DH
2605 static DH *load_dh_param(const char *dhfile)
2606 {
2607     DH *ret = NULL;
2608     BIO *bio;
2609
2610     if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2611         goto err;
2612     ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2613  err:
2614     BIO_free(bio);
2615     return (ret);
2616 }
2617 #endif
2618
2619 static int www_body(int s, int stype, unsigned char *context)
2620 {
2621     char *buf = NULL;
2622     int ret = 1;
2623     int i, j, k, dot;
2624     SSL *con;
2625     const SSL_CIPHER *c;
2626     BIO *io, *ssl_bio, *sbio;
2627 #ifdef RENEG
2628     int total_bytes = 0;
2629 #endif
2630     int width;
2631     fd_set readfds;
2632
2633     /* Set width for a select call if needed */
2634     width = s + 1;
2635
2636     buf = app_malloc(bufsize, "server www buffer");
2637     io = BIO_new(BIO_f_buffer());
2638     ssl_bio = BIO_new(BIO_f_ssl());
2639     if ((io == NULL) || (ssl_bio == NULL))
2640         goto err;
2641
2642     if (s_nbio) {
2643         if (!BIO_socket_nbio(s, 1))
2644             ERR_print_errors(bio_err);
2645         else if (!s_quiet)
2646             BIO_printf(bio_err, "Turned on non blocking io\n");
2647     }
2648
2649     /* lets make the output buffer a reasonable size */
2650     if (!BIO_set_write_buffer_size(io, bufsize))
2651         goto err;
2652
2653     if ((con = SSL_new(ctx)) == NULL)
2654         goto err;
2655
2656     if (s_tlsextdebug) {
2657         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2658         SSL_set_tlsext_debug_arg(con, bio_s_out);
2659     }
2660
2661     if (context
2662         && !SSL_set_session_id_context(con, context,
2663                                        strlen((char *)context))) {
2664         SSL_free(con);
2665         goto err;
2666     }
2667
2668     sbio = BIO_new_socket(s, BIO_NOCLOSE);
2669     if (s_nbio_test) {
2670         BIO *test;
2671
2672         test = BIO_new(BIO_f_nbio_test());
2673         sbio = BIO_push(test, sbio);
2674     }
2675     SSL_set_bio(con, sbio, sbio);
2676     SSL_set_accept_state(con);
2677
2678     /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
2679     BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2680     BIO_push(io, ssl_bio);
2681 #ifdef CHARSET_EBCDIC
2682     io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2683 #endif
2684
2685     if (s_debug) {
2686         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2687         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2688     }
2689     if (s_msg) {
2690 #ifndef OPENSSL_NO_SSL_TRACE
2691         if (s_msg == 2)
2692             SSL_set_msg_callback(con, SSL_trace);
2693         else
2694 #endif
2695             SSL_set_msg_callback(con, msg_cb);
2696         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2697     }
2698
2699     for (;;) {
2700         i = BIO_gets(io, buf, bufsize - 1);
2701         if (i < 0) {            /* error */
2702             if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2703                 if (!s_quiet)
2704                     ERR_print_errors(bio_err);
2705                 goto err;
2706             } else {
2707                 BIO_printf(bio_s_out, "read R BLOCK\n");
2708 #ifndef OPENSSL_NO_SRP
2709                 if (BIO_should_io_special(io)
2710                     && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2711                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2712                     SRP_user_pwd_free(srp_callback_parm.user);
2713                     srp_callback_parm.user =
2714                         SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2715                                                srp_callback_parm.login);
2716                     if (srp_callback_parm.user)
2717                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
2718                                    srp_callback_parm.user->info);
2719                     else
2720                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
2721                     continue;
2722                 }
2723 #endif
2724 #if !defined(OPENSSL_SYS_MSDOS)
2725                 sleep(1);
2726 #endif
2727                 continue;
2728             }
2729         } else if (i == 0) {    /* end of input */
2730             ret = 1;
2731             goto end;
2732         }
2733
2734         /* else we have data */
2735         if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2736             ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2737             char *p;
2738             X509 *peer = NULL;
2739             STACK_OF(SSL_CIPHER) *sk;
2740             static const char *space = "                          ";
2741
2742             if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2743                 if (strncmp("GET /renegcert", buf, 14) == 0)
2744                     SSL_set_verify(con,
2745                                    SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2746                                    NULL);
2747                 i = SSL_renegotiate(con);
2748                 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2749                 /* Send the HelloRequest */
2750                 i = SSL_do_handshake(con);
2751                 if (i <= 0) {
2752                     BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2753                                SSL_get_error(con, i));
2754                     ERR_print_errors(bio_err);
2755                     goto err;
2756                 }
2757                 /* Wait for a ClientHello to come back */
2758                 FD_ZERO(&readfds);
2759                 openssl_fdset(s, &readfds);
2760                 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2761                 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2762                     BIO_printf(bio_s_out,
2763                                "Error waiting for client response\n");
2764                     ERR_print_errors(bio_err);
2765                     goto err;
2766                 }
2767                 /*
2768                  * We're not actually expecting any data here and we ignore
2769                  * any that is sent. This is just to force the handshake that
2770                  * we're expecting to come from the client. If they haven't
2771                  * sent one there's not much we can do.
2772                  */
2773                 BIO_gets(io, buf, bufsize - 1);
2774             }
2775
2776             BIO_puts(io,
2777                      "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2778             BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2779             BIO_puts(io, "<pre>\n");
2780             /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2781             BIO_puts(io, "\n");
2782             for (i = 0; i < local_argc; i++) {
2783                 const char *myp;
2784                 for (myp = local_argv[i]; *myp; myp++)
2785                     switch (*myp) {
2786                     case '<':
2787                         BIO_puts(io, "&lt;");
2788                         break;
2789                     case '>':
2790                         BIO_puts(io, "&gt;");
2791                         break;
2792                     case '&':
2793                         BIO_puts(io, "&amp;");
2794                         break;
2795                     default:
2796                         BIO_write(io, myp, 1);
2797                         break;
2798                     }
2799                 BIO_write(io, " ", 1);
2800             }
2801             BIO_puts(io, "\n");
2802
2803             BIO_printf(io,
2804                        "Secure Renegotiation IS%s supported\n",
2805                        SSL_get_secure_renegotiation_support(con) ?
2806                        "" : " NOT");
2807
2808             /*
2809              * The following is evil and should not really be done
2810              */
2811             BIO_printf(io, "Ciphers supported in s_server binary\n");
2812             sk = SSL_get_ciphers(con);
2813             j = sk_SSL_CIPHER_num(sk);
2814             for (i = 0; i < j; i++) {
2815                 c = sk_SSL_CIPHER_value(sk, i);
2816                 BIO_printf(io, "%-11s:%-25s ",
2817                            SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2818                 if ((((i + 1) % 2) == 0) && (i + 1 != j))
2819                     BIO_puts(io, "\n");
2820             }
2821             BIO_puts(io, "\n");
2822             p = SSL_get_shared_ciphers(con, buf, bufsize);
2823             if (p != NULL) {
2824                 BIO_printf(io,
2825                            "---\nCiphers common between both SSL end points:\n");
2826                 j = i = 0;
2827                 while (*p) {
2828                     if (*p == ':') {
2829                         BIO_write(io, space, 26 - j);
2830                         i++;
2831                         j = 0;
2832                         BIO_write(io, ((i % 3) ? " " : "\n"), 1);
2833                     } else {
2834                         BIO_write(io, p, 1);
2835                         j++;
2836                     }
2837                     p++;
2838                 }
2839                 BIO_puts(io, "\n");
2840             }
2841             ssl_print_sigalgs(io, con);
2842 #ifndef OPENSSL_NO_EC
2843             ssl_print_curves(io, con, 0);
2844 #endif
2845             BIO_printf(io, (SSL_session_reused(con)
2846                             ? "---\nReused, " : "---\nNew, "));
2847             c = SSL_get_current_cipher(con);
2848             BIO_printf(io, "%s, Cipher is %s\n",
2849                        SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2850             SSL_SESSION_print(io, SSL_get_session(con));
2851             BIO_printf(io, "---\n");
2852             print_stats(io, SSL_get_SSL_CTX(con));
2853             BIO_printf(io, "---\n");
2854             peer = SSL_get_peer_certificate(con);
2855             if (peer != NULL) {
2856                 BIO_printf(io, "Client certificate\n");
2857                 X509_print(io, peer);
2858                 PEM_write_bio_X509(io, peer);
2859                 X509_free(peer);
2860                 peer = NULL;
2861             } else {
2862                 BIO_puts(io, "no client certificate available\n");
2863             }
2864             BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
2865             break;
2866         } else if ((www == 2 || www == 3)
2867                    && (strncmp("GET /", buf, 5) == 0)) {
2868             BIO *file;
2869             char *p, *e;
2870             static const char *text =
2871                 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2872
2873             /* skip the '/' */
2874             p = &(buf[5]);
2875
2876             dot = 1;
2877             for (e = p; *e != '\0'; e++) {
2878                 if (e[0] == ' ')
2879                     break;
2880
2881                 switch (dot) {
2882                 case 1:
2883                     dot = (e[0] == '.') ? 2 : 0;
2884                     break;
2885                 case 2:
2886                     dot = (e[0] == '.') ? 3 : 0;
2887                     break;
2888                 case 3:
2889                     dot = (e[0] == '/') ? -1 : 0;
2890                     break;
2891                 }
2892                 if (dot == 0)
2893                     dot = (e[0] == '/') ? 1 : 0;
2894             }
2895             dot = (dot == 3) || (dot == -1); /* filename contains ".."
2896                                               * component */
2897
2898             if (*e == '\0') {
2899                 BIO_puts(io, text);
2900                 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
2901                 break;
2902             }
2903             *e = '\0';
2904
2905             if (dot) {
2906                 BIO_puts(io, text);
2907                 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
2908                 break;
2909             }
2910
2911             if (*p == '/') {
2912                 BIO_puts(io, text);
2913                 BIO_printf(io, "'%s' is an invalid path\r\n", p);
2914                 break;
2915             }
2916
2917             /* if a directory, do the index thang */
2918             if (app_isdir(p) > 0) {
2919                 BIO_puts(io, text);
2920                 BIO_printf(io, "'%s' is a directory\r\n", p);
2921                 break;
2922             }
2923
2924             if ((file = BIO_new_file(p, "r")) == NULL) {
2925                 BIO_puts(io, text);
2926                 BIO_printf(io, "Error opening '%s'\r\n", p);
2927                 ERR_print_errors(io);
2928                 break;
2929             }
2930
2931             if (!s_quiet)
2932                 BIO_printf(bio_err, "FILE:%s\n", p);
2933
2934             if (www == 2) {
2935                 i = strlen(p);
2936                 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
2937                     ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
2938                     ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
2939                     BIO_puts(io,
2940                              "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2941                 else
2942                     BIO_puts(io,
2943                              "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2944             }
2945             /* send the file */
2946             for (;;) {
2947                 i = BIO_read(file, buf, bufsize);
2948                 if (i <= 0)
2949                     break;
2950
2951 #ifdef RENEG
2952                 total_bytes += i;
2953                 BIO_printf(bio_err, "%d\n", i);
2954                 if (total_bytes > 3 * 1024) {
2955                     total_bytes = 0;
2956                     BIO_printf(bio_err, "RENEGOTIATE\n");
2957                     SSL_renegotiate(con);
2958                 }
2959 #endif
2960
2961                 for (j = 0; j < i;) {
2962 #ifdef RENEG
2963                     static count = 0;
2964                     if (++count == 13) {
2965                         SSL_renegotiate(con);
2966                     }
2967 #endif
2968                     k = BIO_write(io, &(buf[j]), i - j);
2969                     if (k <= 0) {
2970                         if (!BIO_should_retry(io)
2971                             && !SSL_waiting_for_async(con))
2972                             goto write_error;
2973                         else {
2974                             BIO_printf(bio_s_out, "rwrite W BLOCK\n");
2975                         }
2976                     } else {
2977                         j += k;
2978                     }
2979                 }
2980             }
2981  write_error:
2982             BIO_free(file);
2983             break;
2984         }
2985     }
2986
2987     for (;;) {
2988         i = (int)BIO_flush(io);
2989         if (i <= 0) {
2990             if (!BIO_should_retry(io))
2991                 break;
2992         } else
2993             break;
2994     }
2995  end:
2996     /* make sure we re-use sessions */
2997     SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2998
2999  err:
3000     if (ret >= 0)
3001         BIO_printf(bio_s_out, "ACCEPT\n");
3002     OPENSSL_free(buf);
3003     BIO_free_all(io);
3004     return (ret);
3005 }
3006
3007 static int rev_body(int s, int stype, unsigned char *context)
3008 {
3009     char *buf = NULL;
3010     int i;
3011     int ret = 1;
3012     SSL *con;
3013     BIO *io, *ssl_bio, *sbio;
3014
3015     buf = app_malloc(bufsize, "server rev buffer");
3016     io = BIO_new(BIO_f_buffer());
3017     ssl_bio = BIO_new(BIO_f_ssl());
3018     if ((io == NULL) || (ssl_bio == NULL))
3019         goto err;
3020
3021     /* lets make the output buffer a reasonable size */
3022     if (!BIO_set_write_buffer_size(io, bufsize))
3023         goto err;
3024
3025     if ((con = SSL_new(ctx)) == NULL)
3026         goto err;
3027
3028     if (s_tlsextdebug) {
3029         SSL_set_tlsext_debug_callback(con, tlsext_cb);
3030         SSL_set_tlsext_debug_arg(con, bio_s_out);
3031     }
3032     if (context
3033         && !SSL_set_session_id_context(con, context,
3034                                        strlen((char *)context))) {
3035         SSL_free(con);
3036         ERR_print_errors(bio_err);
3037         goto err;
3038     }
3039
3040     sbio = BIO_new_socket(s, BIO_NOCLOSE);
3041     SSL_set_bio(con, sbio, sbio);
3042     SSL_set_accept_state(con);
3043
3044     /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3045     BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3046     BIO_push(io, ssl_bio);
3047 #ifdef CHARSET_EBCDIC
3048     io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3049 #endif
3050
3051     if (s_debug) {
3052         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3053         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3054     }
3055     if (s_msg) {
3056 #ifndef OPENSSL_NO_SSL_TRACE
3057         if (s_msg == 2)
3058             SSL_set_msg_callback(con, SSL_trace);
3059         else
3060 #endif
3061             SSL_set_msg_callback(con, msg_cb);
3062         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3063     }
3064
3065     for (;;) {
3066         i = BIO_do_handshake(io);
3067         if (i > 0)
3068             break;
3069         if (!BIO_should_retry(io)) {
3070             BIO_puts(bio_err, "CONNECTION FAILURE\n");
3071             ERR_print_errors(bio_err);
3072             goto end;
3073         }
3074 #ifndef OPENSSL_NO_SRP
3075         if (BIO_should_io_special(io)
3076             && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3077             BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3078             SRP_user_pwd_free(srp_callback_parm.user);
3079             srp_callback_parm.user =
3080                 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3081                                        srp_callback_parm.login);
3082             if (srp_callback_parm.user)
3083                 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3084                            srp_callback_parm.user->info);
3085             else
3086                 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3087             continue;
3088         }
3089 #endif
3090     }
3091     BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3092     print_ssl_summary(con);
3093
3094     for (;;) {
3095         i = BIO_gets(io, buf, bufsize - 1);
3096         if (i < 0) {            /* error */
3097             if (!BIO_should_retry(io)) {
3098                 if (!s_quiet)
3099                     ERR_print_errors(bio_err);
3100                 goto err;
3101             } else {
3102                 BIO_printf(bio_s_out, "read R BLOCK\n");
3103 #ifndef OPENSSL_NO_SRP
3104                 if (BIO_should_io_special(io)
3105                     && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3106                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3107                     SRP_user_pwd_free(srp_callback_parm.user);
3108                     srp_callback_parm.user =
3109                         SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3110                                                srp_callback_parm.login);
3111                     if (srp_callback_parm.user)
3112                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
3113                                    srp_callback_parm.user->info);
3114                     else
3115                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
3116                     continue;
3117                 }
3118 #endif
3119 #if !defined(OPENSSL_SYS_MSDOS)
3120                 sleep(1);
3121 #endif
3122                 continue;
3123             }
3124         } else if (i == 0) {    /* end of input */
3125             ret = 1;
3126             BIO_printf(bio_err, "CONNECTION CLOSED\n");
3127             goto end;
3128         } else {
3129             char *p = buf + i - 1;
3130             while (i && (*p == '\n' || *p == '\r')) {
3131                 p--;
3132                 i--;
3133             }
3134             if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3135                 ret = 1;
3136                 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3137                 goto end;
3138             }
3139             BUF_reverse((unsigned char *)buf, NULL, i);
3140             buf[i] = '\n';
3141             BIO_write(io, buf, i + 1);
3142             for (;;) {
3143                 i = BIO_flush(io);
3144                 if (i > 0)
3145                     break;
3146                 if (!BIO_should_retry(io))
3147                     goto end;
3148             }
3149         }
3150     }
3151  end:
3152     /* make sure we re-use sessions */
3153     SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3154
3155  err:
3156
3157     OPENSSL_free(buf);
3158     BIO_free_all(io);
3159     return (ret);
3160 }
3161
3162 #define MAX_SESSION_ID_ATTEMPTS 10
3163 static int generate_session_id(const SSL *ssl, unsigned char *id,
3164                                unsigned int *id_len)
3165 {
3166     unsigned int count = 0;
3167     do {
3168         if (RAND_bytes(id, *id_len) <= 0)
3169             return 0;
3170         /*
3171          * Prefix the session_id with the required prefix. NB: If our prefix
3172          * is too long, clip it - but there will be worse effects anyway, eg.
3173          * the server could only possibly create 1 session ID (ie. the
3174          * prefix!) so all future session negotiations will fail due to
3175          * conflicts.
3176          */
3177         memcpy(id, session_id_prefix,
3178                (strlen(session_id_prefix) < *id_len) ?
3179                strlen(session_id_prefix) : *id_len);
3180     }
3181     while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3182            (++count < MAX_SESSION_ID_ATTEMPTS));
3183     if (count >= MAX_SESSION_ID_ATTEMPTS)
3184         return 0;
3185     return 1;
3186 }
3187
3188 /*
3189  * By default s_server uses an in-memory cache which caches SSL_SESSION
3190  * structures without any serialisation. This hides some bugs which only
3191  * become apparent in deployed servers. By implementing a basic external
3192  * session cache some issues can be debugged using s_server.
3193  */
3194
3195 typedef struct simple_ssl_session_st {
3196     unsigned char *id;
3197     unsigned int idlen;
3198     unsigned char *der;
3199     int derlen;
3200     struct simple_ssl_session_st *next;
3201 } simple_ssl_session;
3202
3203 static simple_ssl_session *first = NULL;
3204
3205 static int add_session(SSL *ssl, SSL_SESSION *session)
3206 {
3207     simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3208     unsigned char *p;
3209
3210     SSL_SESSION_get_id(session, &sess->idlen);
3211     sess->derlen = i2d_SSL_SESSION(session, NULL);
3212     if (sess->derlen < 0) {
3213         BIO_printf(bio_err, "Error encoding session\n");
3214         OPENSSL_free(sess);
3215         return 0;
3216     }
3217
3218     sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3219     sess->der = app_malloc(sess->derlen, "get session buffer");
3220     if (!sess->id) {
3221         BIO_printf(bio_err, "Out of memory adding to external cache\n");
3222         OPENSSL_free(sess->id);
3223         OPENSSL_free(sess->der);
3224         OPENSSL_free(sess);
3225         return 0;
3226     }
3227     p = sess->der;
3228
3229     /* Assume it still works. */
3230     if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3231         BIO_printf(bio_err, "Unexpected session encoding length\n");
3232         OPENSSL_free(sess->id);
3233         OPENSSL_free(sess->der);
3234         OPENSSL_free(sess);
3235         return 0;
3236     }
3237
3238     sess->next = first;
3239     first = sess;
3240     BIO_printf(bio_err, "New session added to external cache\n");
3241     return 0;
3242 }
3243
3244 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3245                                 int *do_copy)
3246 {
3247     simple_ssl_session *sess;
3248     *do_copy = 0;
3249     for (sess = first; sess; sess = sess->next) {
3250         if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3251             const unsigned char *p = sess->der;
3252             BIO_printf(bio_err, "Lookup session: cache hit\n");
3253             return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3254         }
3255     }
3256     BIO_printf(bio_err, "Lookup session: cache miss\n");
3257     return NULL;
3258 }
3259
3260 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3261 {
3262     simple_ssl_session *sess, *prev = NULL;
3263     const unsigned char *id;
3264     unsigned int idlen;
3265     id = SSL_SESSION_get_id(session, &idlen);
3266     for (sess = first; sess; sess = sess->next) {
3267         if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3268             if (prev)
3269                 prev->next = sess->next;
3270             else
3271                 first = sess->next;
3272             OPENSSL_free(sess->id);
3273             OPENSSL_free(sess->der);
3274             OPENSSL_free(sess);
3275             return;
3276         }
3277         prev = sess;
3278     }
3279 }
3280
3281 static void init_session_cache_ctx(SSL_CTX *sctx)
3282 {
3283     SSL_CTX_set_session_cache_mode(sctx,
3284                                    SSL_SESS_CACHE_NO_INTERNAL |
3285                                    SSL_SESS_CACHE_SERVER);
3286     SSL_CTX_sess_set_new_cb(sctx, add_session);
3287     SSL_CTX_sess_set_get_cb(sctx, get_session);
3288     SSL_CTX_sess_set_remove_cb(sctx, del_session);
3289 }
3290
3291 static void free_sessions(void)
3292 {
3293     simple_ssl_session *sess, *tsess;
3294     for (sess = first; sess;) {
3295         OPENSSL_free(sess->id);
3296         OPENSSL_free(sess->der);
3297         tsess = sess;
3298         sess = sess->next;
3299         OPENSSL_free(tsess);
3300     }
3301     first = NULL;
3302 }
3303
3304 #endif                          /* OPENSSL_NO_SOCK */