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