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