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