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