Add DTLS-SRTP.
[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 void close_accept_socket(void );
210 static void sv_usage(void);
211 static int init_ssl_connection(SSL *s);
212 static void print_stats(BIO *bp,SSL_CTX *ctx);
213 static int generate_session_id(const SSL *ssl, unsigned char *id,
214                                 unsigned int *id_len);
215 #ifndef OPENSSL_NO_DH
216 static DH *load_dh_param(const char *dhfile);
217 static DH *get_dh512(void);
218 #endif
219
220 #ifdef MONOLITH
221 static void s_server_init(void);
222 #endif
223
224 #ifndef OPENSSL_NO_DH
225 static unsigned char dh512_p[]={
226         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
227         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
228         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
229         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
230         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
231         0x47,0x74,0xE8,0x33,
232         };
233 static unsigned char dh512_g[]={
234         0x02,
235         };
236
237 static DH *get_dh512(void)
238         {
239         DH *dh=NULL;
240
241         if ((dh=DH_new()) == NULL) return(NULL);
242         dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
243         dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
244         if ((dh->p == NULL) || (dh->g == NULL))
245                 return(NULL);
246         return(dh);
247         }
248 #endif
249
250
251 /* static int load_CA(SSL_CTX *ctx, char *file);*/
252
253 #undef BUFSIZZ
254 #define BUFSIZZ 16*1024
255 static int bufsize=BUFSIZZ;
256 static int accept_socket= -1;
257
258 #define TEST_CERT       "server.pem"
259 #ifndef OPENSSL_NO_TLSEXT
260 #define TEST_CERT2      "server2.pem"
261 #endif
262 #undef PROG
263 #define PROG            s_server_main
264
265 extern int verify_depth, verify_return_error;
266
267 static char *cipher=NULL;
268 static int s_server_verify=SSL_VERIFY_NONE;
269 static int s_server_session_id_context = 1; /* anything will do */
270 static const char *s_cert_file=TEST_CERT,*s_key_file=NULL;
271 #ifndef OPENSSL_NO_TLSEXT
272 static const char *s_cert_file2=TEST_CERT2,*s_key_file2=NULL;
273 #endif
274 static char *s_dcert_file=NULL,*s_dkey_file=NULL;
275 #ifdef FIONBIO
276 static int s_nbio=0;
277 #endif
278 static int s_nbio_test=0;
279 int s_crlf=0;
280 static SSL_CTX *ctx=NULL;
281 #ifndef OPENSSL_NO_TLSEXT
282 static SSL_CTX *ctx2=NULL;
283 #endif
284 static int www=0;
285
286 static BIO *bio_s_out=NULL;
287 static int s_debug=0;
288 #ifndef OPENSSL_NO_TLSEXT
289 static int s_tlsextdebug=0;
290 static int s_tlsextstatus=0;
291 static int cert_status_cb(SSL *s, void *arg);
292 #endif
293 static int s_msg=0;
294 static int s_quiet=0;
295
296 static int hack=0;
297 #ifndef OPENSSL_NO_ENGINE
298 static char *engine_id=NULL;
299 #endif
300 static const char *session_id_prefix=NULL;
301
302 static int enable_timeouts = 0;
303 static long socket_mtu;
304 #ifndef OPENSSL_NO_DTLS1
305 static int cert_chain = 0;
306 #endif
307
308
309 #ifndef OPENSSL_NO_PSK
310 static char *psk_identity="Client_identity";
311 char *psk_key=NULL; /* by default PSK is not used */
312
313 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
314         unsigned char *psk, unsigned int max_psk_len)
315         {
316         unsigned int psk_len = 0;
317         int ret;
318         BIGNUM *bn = NULL;
319
320         if (s_debug)
321                 BIO_printf(bio_s_out,"psk_server_cb\n");
322         if (!identity)
323                 {
324                 BIO_printf(bio_err,"Error: client did not send PSK identity\n");
325                 goto out_err;
326                 }
327         if (s_debug)
328                 BIO_printf(bio_s_out,"identity_len=%d identity=%s\n",
329                         identity ? (int)strlen(identity) : 0, identity);
330
331         /* here we could lookup the given identity e.g. from a database */
332         if (strcmp(identity, psk_identity) != 0)
333                 {
334                 BIO_printf(bio_s_out, "PSK error: client identity not found"
335                            " (got '%s' expected '%s')\n", identity,
336                            psk_identity);
337                 goto out_err;
338                 }
339         if (s_debug)
340                 BIO_printf(bio_s_out, "PSK client identity found\n");
341
342         /* convert the PSK key to binary */
343         ret = BN_hex2bn(&bn, psk_key);
344         if (!ret)
345                 {
346                 BIO_printf(bio_err,"Could not convert PSK key '%s' to BIGNUM\n", psk_key);
347                 if (bn)
348                         BN_free(bn);
349                 return 0;
350                 }
351         if (BN_num_bytes(bn) > (int)max_psk_len)
352                 {
353                 BIO_printf(bio_err,"psk buffer of callback is too small (%d) for key (%d)\n",
354                         max_psk_len, BN_num_bytes(bn));
355                 BN_free(bn);
356                 return 0;
357                 }
358
359         ret = BN_bn2bin(bn, psk);
360         BN_free(bn);
361
362         if (ret < 0)
363                 goto out_err;
364         psk_len = (unsigned int)ret;
365
366         if (s_debug)
367                 BIO_printf(bio_s_out, "fetched PSK len=%d\n", psk_len);
368         return psk_len;
369  out_err:
370         if (s_debug)
371                 BIO_printf(bio_err, "Error in PSK server callback\n");
372         return 0;
373         }
374 #endif
375
376 #ifndef OPENSSL_NO_SRP
377 /* This is a context that we pass to callbacks */
378 typedef struct srpsrvparm_st
379         {
380         int verbose;
381         char *login;
382         SRP_VBASE *vb;
383         } srpsrvparm;
384
385 static int MS_CALLBACK ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
386         {
387         srpsrvparm *p = (srpsrvparm *) arg;
388         SRP_user_pwd *user;
389
390         p->login = BUF_strdup(SSL_get_srp_username(s));
391         BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
392
393         user = SRP_VBASE_get_by_user(p->vb, p->login);
394         if (user == NULL)
395                 {
396                 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
397                 return SSL3_AL_FATAL;
398                 }
399         if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
400                                      user->info) < 0)
401                 {
402                 *ad = SSL_AD_INTERNAL_ERROR;
403                 return SSL3_AL_FATAL;
404                 }
405         return SSL_ERROR_NONE;
406         }
407
408 #endif
409
410 #ifdef MONOLITH
411 static void s_server_init(void)
412         {
413         accept_socket=-1;
414         cipher=NULL;
415         s_server_verify=SSL_VERIFY_NONE;
416         s_dcert_file=NULL;
417         s_dkey_file=NULL;
418         s_cert_file=TEST_CERT;
419         s_key_file=NULL;
420 #ifndef OPENSSL_NO_TLSEXT
421         s_cert_file2=TEST_CERT2;
422         s_key_file2=NULL;
423         ctx2=NULL;
424 #endif
425 #ifdef FIONBIO
426         s_nbio=0;
427 #endif
428         s_nbio_test=0;
429         ctx=NULL;
430         www=0;
431
432         bio_s_out=NULL;
433         s_debug=0;
434         s_msg=0;
435         s_quiet=0;
436         hack=0;
437 #ifndef OPENSSL_NO_ENGINE
438         engine_id=NULL;
439 #endif
440         }
441 #endif
442
443 static void sv_usage(void)
444         {
445         BIO_printf(bio_err,"usage: s_server [args ...]\n");
446         BIO_printf(bio_err,"\n");
447         BIO_printf(bio_err," -accept arg   - port to accept on (default is %d)\n",PORT);
448         BIO_printf(bio_err," -context arg  - set session ID context\n");
449         BIO_printf(bio_err," -verify arg   - turn on peer certificate verification\n");
450         BIO_printf(bio_err," -Verify arg   - turn on peer certificate verification, must have a cert.\n");
451         BIO_printf(bio_err," -cert arg     - certificate file to use\n");
452         BIO_printf(bio_err,"                 (default is %s)\n",TEST_CERT);
453         BIO_printf(bio_err," -crl_check    - check the peer certificate has not been revoked by its CA.\n" \
454                            "                 The CRL(s) are appended to the certificate file\n");
455         BIO_printf(bio_err," -crl_check_all - check the peer certificate has not been revoked by its CA\n" \
456                            "                 or any other CRL in the CA chain. CRL(s) are appened to the\n" \
457                            "                 the certificate file.\n");
458         BIO_printf(bio_err," -certform arg - certificate format (PEM or DER) PEM default\n");
459         BIO_printf(bio_err," -key arg      - Private Key file to use, in cert file if\n");
460         BIO_printf(bio_err,"                 not specified (default is %s)\n",TEST_CERT);
461         BIO_printf(bio_err," -keyform arg  - key format (PEM, DER or ENGINE) PEM default\n");
462         BIO_printf(bio_err," -pass arg     - private key file pass phrase source\n");
463         BIO_printf(bio_err," -dcert arg    - second certificate file to use (usually for DSA)\n");
464         BIO_printf(bio_err," -dcertform x  - second certificate format (PEM or DER) PEM default\n");
465         BIO_printf(bio_err," -dkey arg     - second private key file to use (usually for DSA)\n");
466         BIO_printf(bio_err," -dkeyform arg - second key format (PEM, DER or ENGINE) PEM default\n");
467         BIO_printf(bio_err," -dpass arg    - second private key file pass phrase source\n");
468         BIO_printf(bio_err," -dhparam arg  - DH parameter file to use, in cert file if not specified\n");
469         BIO_printf(bio_err,"                 or a default set of parameters is used\n");
470 #ifndef OPENSSL_NO_ECDH
471         BIO_printf(bio_err," -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n" \
472                            "                 Use \"openssl ecparam -list_curves\" for all names\n" \
473                            "                 (default is nistp256).\n");
474 #endif
475 #ifdef FIONBIO
476         BIO_printf(bio_err," -nbio         - Run with non-blocking IO\n");
477 #endif
478         BIO_printf(bio_err," -nbio_test    - test with the non-blocking test bio\n");
479         BIO_printf(bio_err," -crlf         - convert LF from terminal into CRLF\n");
480         BIO_printf(bio_err," -debug        - Print more output\n");
481         BIO_printf(bio_err," -msg          - Show protocol messages\n");
482         BIO_printf(bio_err," -state        - Print the SSL states\n");
483         BIO_printf(bio_err," -CApath arg   - PEM format directory of CA's\n");
484         BIO_printf(bio_err," -CAfile arg   - PEM format file of CA's\n");
485         BIO_printf(bio_err," -nocert       - Don't use any certificates (Anon-DH)\n");
486         BIO_printf(bio_err," -cipher arg   - play with 'openssl ciphers' to see what goes here\n");
487         BIO_printf(bio_err," -serverpref   - Use server's cipher preferences\n");
488         BIO_printf(bio_err," -quiet        - No server output\n");
489         BIO_printf(bio_err," -no_tmp_rsa   - Do not generate a tmp RSA key\n");
490 #ifndef OPENSSL_NO_PSK
491         BIO_printf(bio_err," -psk_hint arg - PSK identity hint to use\n");
492         BIO_printf(bio_err," -psk arg      - PSK in hex (without 0x)\n");
493 # ifndef OPENSSL_NO_JPAKE
494         BIO_printf(bio_err," -jpake arg    - JPAKE secret to use\n");
495 # endif
496 #endif
497 #ifndef OPENSSL_NO_SRP
498         BIO_printf(bio_err," -srpvfile file      - The verifier file for SRP\n");
499         BIO_printf(bio_err," -srpuserseed string - A seed string for a default user salt.\n");
500 #endif
501         BIO_printf(bio_err," -ssl2         - Just talk SSLv2\n");
502         BIO_printf(bio_err," -ssl3         - Just talk SSLv3\n");
503         BIO_printf(bio_err," -tls1_2       - Just talk TLSv1.2\n");
504         BIO_printf(bio_err," -tls1_1       - Just talk TLSv1.1\n");
505         BIO_printf(bio_err," -tls1         - Just talk TLSv1\n");
506         BIO_printf(bio_err," -dtls1        - Just talk DTLSv1\n");
507         BIO_printf(bio_err," -timeout      - Enable timeouts\n");
508         BIO_printf(bio_err," -mtu          - Set link layer MTU\n");
509         BIO_printf(bio_err," -chain        - Read a certificate chain\n");
510         BIO_printf(bio_err," -no_ssl2      - Just disable SSLv2\n");
511         BIO_printf(bio_err," -no_ssl3      - Just disable SSLv3\n");
512         BIO_printf(bio_err," -no_tls1      - Just disable TLSv1\n");
513         BIO_printf(bio_err," -no_tls1_1    - Just disable TLSv1.1\n");
514         BIO_printf(bio_err," -no_tls1_2    - Just disable TLSv1.2\n");
515 #ifndef OPENSSL_NO_DH
516         BIO_printf(bio_err," -no_dhe       - Disable ephemeral DH\n");
517 #endif
518 #ifndef OPENSSL_NO_ECDH
519         BIO_printf(bio_err," -no_ecdhe     - Disable ephemeral ECDH\n");
520 #endif
521         BIO_printf(bio_err," -bugs         - Turn on SSL bug compatibility\n");
522         BIO_printf(bio_err," -www          - Respond to a 'GET /' with a status page\n");
523         BIO_printf(bio_err," -WWW          - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
524         BIO_printf(bio_err," -HTTP         - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
525         BIO_printf(bio_err,"                 with the assumption it contains a complete HTTP response.\n");
526 #ifndef OPENSSL_NO_ENGINE
527         BIO_printf(bio_err," -engine id    - Initialise and use the specified engine\n");
528 #endif
529         BIO_printf(bio_err," -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n");
530         BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
531 #ifndef OPENSSL_NO_TLSEXT
532         BIO_printf(bio_err," -servername host - servername for HostName TLS extension\n");
533         BIO_printf(bio_err," -servername_fatal - on mismatch send fatal alert (default warning alert)\n");
534         BIO_printf(bio_err," -cert2 arg    - certificate file to use for servername\n");
535         BIO_printf(bio_err,"                 (default is %s)\n",TEST_CERT2);
536         BIO_printf(bio_err," -key2 arg     - Private Key file to use for servername, in cert file if\n");
537         BIO_printf(bio_err,"                 not specified (default is %s)\n",TEST_CERT2);
538         BIO_printf(bio_err," -tlsextdebug  - hex dump of all TLS extensions received\n");
539         BIO_printf(bio_err," -no_ticket    - disable use of RFC4507bis session tickets\n");
540         BIO_printf(bio_err," -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n");
541 # ifndef OPENSSL_NO_NEXTPROTONEG
542         BIO_printf(bio_err," -nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)\n");
543 # endif
544         BIO_printf(bio_err," -use_srtp profiles - Offer SRTP key management with a colon-separated profile list");
545 #endif
546         }
547
548 static int local_argc=0;
549 static char **local_argv;
550
551 #ifdef CHARSET_EBCDIC
552 static int ebcdic_new(BIO *bi);
553 static int ebcdic_free(BIO *a);
554 static int ebcdic_read(BIO *b, char *out, int outl);
555 static int ebcdic_write(BIO *b, const char *in, int inl);
556 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
557 static int ebcdic_gets(BIO *bp, char *buf, int size);
558 static int ebcdic_puts(BIO *bp, const char *str);
559
560 #define BIO_TYPE_EBCDIC_FILTER  (18|0x0200)
561 static BIO_METHOD methods_ebcdic=
562         {
563         BIO_TYPE_EBCDIC_FILTER,
564         "EBCDIC/ASCII filter",
565         ebcdic_write,
566         ebcdic_read,
567         ebcdic_puts,
568         ebcdic_gets,
569         ebcdic_ctrl,
570         ebcdic_new,
571         ebcdic_free,
572         };
573
574 typedef struct
575 {
576         size_t  alloced;
577         char    buff[1];
578 } EBCDIC_OUTBUFF;
579
580 BIO_METHOD *BIO_f_ebcdic_filter()
581 {
582         return(&methods_ebcdic);
583 }
584
585 static int ebcdic_new(BIO *bi)
586 {
587         EBCDIC_OUTBUFF *wbuf;
588
589         wbuf = (EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + 1024);
590         wbuf->alloced = 1024;
591         wbuf->buff[0] = '\0';
592
593         bi->ptr=(char *)wbuf;
594         bi->init=1;
595         bi->flags=0;
596         return(1);
597 }
598
599 static int ebcdic_free(BIO *a)
600 {
601         if (a == NULL) return(0);
602         if (a->ptr != NULL)
603                 OPENSSL_free(a->ptr);
604         a->ptr=NULL;
605         a->init=0;
606         a->flags=0;
607         return(1);
608 }
609         
610 static int ebcdic_read(BIO *b, char *out, int outl)
611 {
612         int ret=0;
613
614         if (out == NULL || outl == 0) return(0);
615         if (b->next_bio == NULL) return(0);
616
617         ret=BIO_read(b->next_bio,out,outl);
618         if (ret > 0)
619                 ascii2ebcdic(out,out,ret);
620         return(ret);
621 }
622
623 static int ebcdic_write(BIO *b, const char *in, int inl)
624 {
625         EBCDIC_OUTBUFF *wbuf;
626         int ret=0;
627         int num;
628         unsigned char n;
629
630         if ((in == NULL) || (inl <= 0)) return(0);
631         if (b->next_bio == NULL) return(0);
632
633         wbuf=(EBCDIC_OUTBUFF *)b->ptr;
634
635         if (inl > (num = wbuf->alloced))
636         {
637                 num = num + num;  /* double the size */
638                 if (num < inl)
639                         num = inl;
640                 OPENSSL_free(wbuf);
641                 wbuf=(EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + num);
642
643                 wbuf->alloced = num;
644                 wbuf->buff[0] = '\0';
645
646                 b->ptr=(char *)wbuf;
647         }
648
649         ebcdic2ascii(wbuf->buff, in, inl);
650
651         ret=BIO_write(b->next_bio, wbuf->buff, inl);
652
653         return(ret);
654 }
655
656 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
657 {
658         long ret;
659
660         if (b->next_bio == NULL) return(0);
661         switch (cmd)
662         {
663         case BIO_CTRL_DUP:
664                 ret=0L;
665                 break;
666         default:
667                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
668                 break;
669         }
670         return(ret);
671 }
672
673 static int ebcdic_gets(BIO *bp, char *buf, int size)
674 {
675         int i, ret=0;
676         if (bp->next_bio == NULL) return(0);
677 /*      return(BIO_gets(bp->next_bio,buf,size));*/
678         for (i=0; i<size-1; ++i)
679         {
680                 ret = ebcdic_read(bp,&buf[i],1);
681                 if (ret <= 0)
682                         break;
683                 else if (buf[i] == '\n')
684                 {
685                         ++i;
686                         break;
687                 }
688         }
689         if (i < size)
690                 buf[i] = '\0';
691         return (ret < 0 && i == 0) ? ret : i;
692 }
693
694 static int ebcdic_puts(BIO *bp, const char *str)
695 {
696         if (bp->next_bio == NULL) return(0);
697         return ebcdic_write(bp, str, strlen(str));
698 }
699 #endif
700
701 #ifndef OPENSSL_NO_TLSEXT
702
703 /* This is a context that we pass to callbacks */
704 typedef struct tlsextctx_st {
705    char * servername;
706    BIO * biodebug;
707    int extension_error;
708 } tlsextctx;
709
710
711 static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg)
712         {
713         tlsextctx * p = (tlsextctx *) arg;
714         const char * servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
715         if (servername && p->biodebug) 
716                 BIO_printf(p->biodebug,"Hostname in TLS extension: \"%s\"\n",servername);
717         
718         if (!p->servername)
719                 return SSL_TLSEXT_ERR_NOACK;
720         
721         if (servername)
722                 {
723                 if (strcmp(servername,p->servername)) 
724                         return p->extension_error;
725                 if (ctx2)
726                         {
727                         BIO_printf(p->biodebug,"Switching server context.\n");
728                         SSL_set_SSL_CTX(s,ctx2);
729                         }     
730                 }
731         return SSL_TLSEXT_ERR_OK;
732 }
733
734 /* Structure passed to cert status callback */
735
736 typedef struct tlsextstatusctx_st {
737    /* Default responder to use */
738    char *host, *path, *port;
739    int use_ssl;
740    int timeout;
741    BIO *err;
742    int verbose;
743 } tlsextstatusctx;
744
745 static tlsextstatusctx tlscstatp = {NULL, NULL, NULL, 0, -1, NULL, 0};
746
747 /* Certificate Status callback. This is called when a client includes a
748  * certificate status request extension.
749  *
750  * This is a simplified version. It examines certificates each time and
751  * makes one OCSP responder query for each request.
752  *
753  * A full version would store details such as the OCSP certificate IDs and
754  * minimise the number of OCSP responses by caching them until they were
755  * considered "expired".
756  */
757
758 static int cert_status_cb(SSL *s, void *arg)
759         {
760         tlsextstatusctx *srctx = arg;
761         BIO *err = srctx->err;
762         char *host, *port, *path;
763         int use_ssl;
764         unsigned char *rspder = NULL;
765         int rspderlen;
766         STACK_OF(OPENSSL_STRING) *aia = NULL;
767         X509 *x = NULL;
768         X509_STORE_CTX inctx;
769         X509_OBJECT obj;
770         OCSP_REQUEST *req = NULL;
771         OCSP_RESPONSE *resp = NULL;
772         OCSP_CERTID *id = NULL;
773         STACK_OF(X509_EXTENSION) *exts;
774         int ret = SSL_TLSEXT_ERR_NOACK;
775         int i;
776 #if 0
777 STACK_OF(OCSP_RESPID) *ids;
778 SSL_get_tlsext_status_ids(s, &ids);
779 BIO_printf(err, "cert_status: received %d ids\n", sk_OCSP_RESPID_num(ids));
780 #endif
781         if (srctx->verbose)
782                 BIO_puts(err, "cert_status: callback called\n");
783         /* Build up OCSP query from server certificate */
784         x = SSL_get_certificate(s);
785         aia = X509_get1_ocsp(x);
786         if (aia)
787                 {
788                 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
789                         &host, &port, &path, &use_ssl))
790                         {
791                         BIO_puts(err, "cert_status: can't parse AIA URL\n");
792                         goto err;
793                         }
794                 if (srctx->verbose)
795                         BIO_printf(err, "cert_status: AIA URL: %s\n",
796                                         sk_OPENSSL_STRING_value(aia, 0));
797                 }
798         else
799                 {
800                 if (!srctx->host)
801                         {
802                         BIO_puts(srctx->err, "cert_status: no AIA and no default responder URL\n");
803                         goto done;
804                         }
805                 host = srctx->host;
806                 path = srctx->path;
807                 port = srctx->port;
808                 use_ssl = srctx->use_ssl;
809                 }
810                 
811         if (!X509_STORE_CTX_init(&inctx,
812                                 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
813                                 NULL, NULL))
814                 goto err;
815         if (X509_STORE_get_by_subject(&inctx,X509_LU_X509,
816                                 X509_get_issuer_name(x),&obj) <= 0)
817                 {
818                 BIO_puts(err, "cert_status: Can't retrieve issuer certificate.\n");
819                 X509_STORE_CTX_cleanup(&inctx);
820                 goto done;
821                 }
822         req = OCSP_REQUEST_new();
823         if (!req)
824                 goto err;
825         id = OCSP_cert_to_id(NULL, x, obj.data.x509);
826         X509_free(obj.data.x509);
827         X509_STORE_CTX_cleanup(&inctx);
828         if (!id)
829                 goto err;
830         if (!OCSP_request_add0_id(req, id))
831                 goto err;
832         id = NULL;
833         /* Add any extensions to the request */
834         SSL_get_tlsext_status_exts(s, &exts);
835         for (i = 0; i < sk_X509_EXTENSION_num(exts); i++)
836                 {
837                 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
838                 if (!OCSP_REQUEST_add_ext(req, ext, -1))
839                         goto err;
840                 }
841         resp = process_responder(err, req, host, path, port, use_ssl, NULL,
842                                         srctx->timeout);
843         if (!resp)
844                 {
845                 BIO_puts(err, "cert_status: error querying responder\n");
846                 goto done;
847                 }
848         rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
849         if (rspderlen <= 0)
850                 goto err;
851         SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
852         if (srctx->verbose)
853                 {
854                 BIO_puts(err, "cert_status: ocsp response sent:\n");
855                 OCSP_RESPONSE_print(err, resp, 2);
856                 }
857         ret = SSL_TLSEXT_ERR_OK;
858         done:
859         if (ret != SSL_TLSEXT_ERR_OK)
860                 ERR_print_errors(err);
861         if (aia)
862                 {
863                 OPENSSL_free(host);
864                 OPENSSL_free(path);
865                 OPENSSL_free(port);
866                 X509_email_free(aia);
867                 }
868         if (id)
869                 OCSP_CERTID_free(id);
870         if (req)
871                 OCSP_REQUEST_free(req);
872         if (resp)
873                 OCSP_RESPONSE_free(resp);
874         return ret;
875         err:
876         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
877         goto done;
878         }
879
880 # ifndef OPENSSL_NO_NEXTPROTONEG
881 /* This is the context that we pass to next_proto_cb */
882 typedef struct tlsextnextprotoctx_st {
883         unsigned char *data;
884         unsigned int len;
885 } tlsextnextprotoctx;
886
887 static int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg)
888         {
889         tlsextnextprotoctx *next_proto = arg;
890
891         *data = next_proto->data;
892         *len = next_proto->len;
893
894         return SSL_TLSEXT_ERR_OK;
895         }
896 # endif  /* ndef OPENSSL_NO_NEXTPROTONEG */
897
898
899 #endif
900
901 int MAIN(int, char **);
902
903 #ifndef OPENSSL_NO_JPAKE
904 static char *jpake_secret = NULL;
905 #endif
906 static char *srtp_profiles = NULL;
907
908 int MAIN(int argc, char *argv[])
909         {
910         X509_VERIFY_PARAM *vpm = NULL;
911         int badarg = 0;
912         short port=PORT;
913         char *CApath=NULL,*CAfile=NULL;
914         unsigned char *context = NULL;
915         char *dhfile = NULL;
916 #ifndef OPENSSL_NO_ECDH
917         char *named_curve = NULL;
918 #endif
919         int badop=0,bugs=0;
920         int ret=1;
921         int off=0;
922         int no_tmp_rsa=0,no_dhe=0,no_ecdhe=0,nocert=0;
923         int state=0;
924         const SSL_METHOD *meth=NULL;
925         int socket_type=SOCK_STREAM;
926         ENGINE *e=NULL;
927         char *inrand=NULL;
928         int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
929         char *passarg = NULL, *pass = NULL;
930         char *dpassarg = NULL, *dpass = NULL;
931         int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
932         X509 *s_cert = NULL, *s_dcert = NULL;
933         EVP_PKEY *s_key = NULL, *s_dkey = NULL;
934         int no_cache = 0;
935 #ifndef OPENSSL_NO_TLSEXT
936         EVP_PKEY *s_key2 = NULL;
937         X509 *s_cert2 = NULL;
938         tlsextctx tlsextcbp = {NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING};
939 # ifndef OPENSSL_NO_NEXTPROTONEG
940         const char *next_proto_neg_in = NULL;
941         tlsextnextprotoctx next_proto;
942 # endif
943 #endif
944 #ifndef OPENSSL_NO_PSK
945         /* by default do not send a PSK identity hint */
946         static char *psk_identity_hint=NULL;
947 #endif
948 #ifndef OPENSSL_NO_SRP
949         char *srpuserseed = NULL;
950         char *srp_verifier_file = NULL;
951         srpsrvparm p;
952 #endif
953 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
954         meth=SSLv23_server_method();
955 #elif !defined(OPENSSL_NO_SSL3)
956         meth=SSLv3_server_method();
957 #elif !defined(OPENSSL_NO_SSL2)
958         meth=SSLv2_server_method();
959 #elif !defined(OPENSSL_NO_TLS1)
960         meth=TLSv1_server_method();
961 #else
962   /*  #error no SSL version enabled */
963 #endif
964
965         local_argc=argc;
966         local_argv=argv;
967
968         apps_startup();
969 #ifdef MONOLITH
970         s_server_init();
971 #endif
972
973         if (bio_err == NULL)
974                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
975
976         if (!load_config(bio_err, NULL))
977                 goto end;
978
979         verify_depth=0;
980 #ifdef FIONBIO
981         s_nbio=0;
982 #endif
983         s_nbio_test=0;
984
985         argc--;
986         argv++;
987
988         while (argc >= 1)
989                 {
990                 if      ((strcmp(*argv,"-port") == 0) ||
991                          (strcmp(*argv,"-accept") == 0))
992                         {
993                         if (--argc < 1) goto bad;
994                         if (!extract_port(*(++argv),&port))
995                                 goto bad;
996                         }
997                 else if (strcmp(*argv,"-verify") == 0)
998                         {
999                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE;
1000                         if (--argc < 1) goto bad;
1001                         verify_depth=atoi(*(++argv));
1002                         BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
1003                         }
1004                 else if (strcmp(*argv,"-Verify") == 0)
1005                         {
1006                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
1007                                 SSL_VERIFY_CLIENT_ONCE;
1008                         if (--argc < 1) goto bad;
1009                         verify_depth=atoi(*(++argv));
1010                         BIO_printf(bio_err,"verify depth is %d, must return a certificate\n",verify_depth);
1011                         }
1012                 else if (strcmp(*argv,"-context") == 0)
1013                         {
1014                         if (--argc < 1) goto bad;
1015                         context= (unsigned char *)*(++argv);
1016                         }
1017                 else if (strcmp(*argv,"-cert") == 0)
1018                         {
1019                         if (--argc < 1) goto bad;
1020                         s_cert_file= *(++argv);
1021                         }
1022                 else if (strcmp(*argv,"-certform") == 0)
1023                         {
1024                         if (--argc < 1) goto bad;
1025                         s_cert_format = str2fmt(*(++argv));
1026                         }
1027                 else if (strcmp(*argv,"-key") == 0)
1028                         {
1029                         if (--argc < 1) goto bad;
1030                         s_key_file= *(++argv);
1031                         }
1032                 else if (strcmp(*argv,"-keyform") == 0)
1033                         {
1034                         if (--argc < 1) goto bad;
1035                         s_key_format = str2fmt(*(++argv));
1036                         }
1037                 else if (strcmp(*argv,"-pass") == 0)
1038                         {
1039                         if (--argc < 1) goto bad;
1040                         passarg = *(++argv);
1041                         }
1042                 else if (strcmp(*argv,"-dhparam") == 0)
1043                         {
1044                         if (--argc < 1) goto bad;
1045                         dhfile = *(++argv);
1046                         }
1047 #ifndef OPENSSL_NO_ECDH         
1048                 else if (strcmp(*argv,"-named_curve") == 0)
1049                         {
1050                         if (--argc < 1) goto bad;
1051                         named_curve = *(++argv);
1052                         }
1053 #endif
1054                 else if (strcmp(*argv,"-dcertform") == 0)
1055                         {
1056                         if (--argc < 1) goto bad;
1057                         s_dcert_format = str2fmt(*(++argv));
1058                         }
1059                 else if (strcmp(*argv,"-dcert") == 0)
1060                         {
1061                         if (--argc < 1) goto bad;
1062                         s_dcert_file= *(++argv);
1063                         }
1064                 else if (strcmp(*argv,"-dkeyform") == 0)
1065                         {
1066                         if (--argc < 1) goto bad;
1067                         s_dkey_format = str2fmt(*(++argv));
1068                         }
1069                 else if (strcmp(*argv,"-dpass") == 0)
1070                         {
1071                         if (--argc < 1) goto bad;
1072                         dpassarg = *(++argv);
1073                         }
1074                 else if (strcmp(*argv,"-dkey") == 0)
1075                         {
1076                         if (--argc < 1) goto bad;
1077                         s_dkey_file= *(++argv);
1078                         }
1079                 else if (strcmp(*argv,"-nocert") == 0)
1080                         {
1081                         nocert=1;
1082                         }
1083                 else if (strcmp(*argv,"-CApath") == 0)
1084                         {
1085                         if (--argc < 1) goto bad;
1086                         CApath= *(++argv);
1087                         }
1088                 else if (strcmp(*argv,"-no_cache") == 0)
1089                         no_cache = 1;
1090                 else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm))
1091                         {
1092                         if (badarg)
1093                                 goto bad;
1094                         continue;
1095                         }
1096                 else if (strcmp(*argv,"-verify_return_error") == 0)
1097                         verify_return_error = 1;
1098                 else if (strcmp(*argv,"-serverpref") == 0)
1099                         { off|=SSL_OP_CIPHER_SERVER_PREFERENCE; }
1100                 else if (strcmp(*argv,"-legacy_renegotiation") == 0)
1101                         off|=SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1102                 else if (strcmp(*argv,"-cipher") == 0)
1103                         {
1104                         if (--argc < 1) goto bad;
1105                         cipher= *(++argv);
1106                         }
1107                 else if (strcmp(*argv,"-CAfile") == 0)
1108                         {
1109                         if (--argc < 1) goto bad;
1110                         CAfile= *(++argv);
1111                         }
1112 #ifdef FIONBIO  
1113                 else if (strcmp(*argv,"-nbio") == 0)
1114                         { s_nbio=1; }
1115 #endif
1116                 else if (strcmp(*argv,"-nbio_test") == 0)
1117                         {
1118 #ifdef FIONBIO  
1119                         s_nbio=1;
1120 #endif
1121                         s_nbio_test=1;
1122                         }
1123                 else if (strcmp(*argv,"-debug") == 0)
1124                         { s_debug=1; }
1125 #ifndef OPENSSL_NO_TLSEXT
1126                 else if (strcmp(*argv,"-tlsextdebug") == 0)
1127                         s_tlsextdebug=1;
1128                 else if (strcmp(*argv,"-status") == 0)
1129                         s_tlsextstatus=1;
1130                 else if (strcmp(*argv,"-status_verbose") == 0)
1131                         {
1132                         s_tlsextstatus=1;
1133                         tlscstatp.verbose = 1;
1134                         }
1135                 else if (!strcmp(*argv, "-status_timeout"))
1136                         {
1137                         s_tlsextstatus=1;
1138                         if (--argc < 1) goto bad;
1139                         tlscstatp.timeout = atoi(*(++argv));
1140                         }
1141                 else if (!strcmp(*argv, "-status_url"))
1142                         {
1143                         s_tlsextstatus=1;
1144                         if (--argc < 1) goto bad;
1145                         if (!OCSP_parse_url(*(++argv),
1146                                         &tlscstatp.host,
1147                                         &tlscstatp.port,
1148                                         &tlscstatp.path,
1149                                         &tlscstatp.use_ssl))
1150                                 {
1151                                 BIO_printf(bio_err, "Error parsing URL\n");
1152                                 goto bad;
1153                                 }
1154                         }
1155 #endif
1156                 else if (strcmp(*argv,"-msg") == 0)
1157                         { s_msg=1; }
1158                 else if (strcmp(*argv,"-hack") == 0)
1159                         { hack=1; }
1160                 else if (strcmp(*argv,"-state") == 0)
1161                         { state=1; }
1162                 else if (strcmp(*argv,"-crlf") == 0)
1163                         { s_crlf=1; }
1164                 else if (strcmp(*argv,"-quiet") == 0)
1165                         { s_quiet=1; }
1166                 else if (strcmp(*argv,"-bugs") == 0)
1167                         { bugs=1; }
1168                 else if (strcmp(*argv,"-no_tmp_rsa") == 0)
1169                         { no_tmp_rsa=1; }
1170                 else if (strcmp(*argv,"-no_dhe") == 0)
1171                         { no_dhe=1; }
1172                 else if (strcmp(*argv,"-no_ecdhe") == 0)
1173                         { no_ecdhe=1; }
1174 #ifndef OPENSSL_NO_PSK
1175                 else if (strcmp(*argv,"-psk_hint") == 0)
1176                         {
1177                         if (--argc < 1) goto bad;
1178                         psk_identity_hint= *(++argv);
1179                         }
1180                 else if (strcmp(*argv,"-psk") == 0)
1181                         {
1182                         size_t i;
1183
1184                         if (--argc < 1) goto bad;
1185                         psk_key=*(++argv);
1186                         for (i=0; i<strlen(psk_key); i++)
1187                                 {
1188                                 if (isxdigit((int)psk_key[i]))
1189                                         continue;
1190                                 BIO_printf(bio_err,"Not a hex number '%s'\n",*argv);
1191                                 goto bad;
1192                                 }
1193                         }
1194 #endif
1195 #ifndef OPENSSL_NO_SRP
1196                 else if (strcmp(*argv, "-srpvfile") == 0)
1197                         {
1198                         if (--argc < 1) goto bad;
1199                         srp_verifier_file = *(++argv);
1200                         meth=TLSv1_server_method();
1201                         }
1202                 else if (strcmp(*argv, "-srpuserseed") == 0)
1203                         {
1204                         if (--argc < 1) goto bad;
1205                         srpuserseed = *(++argv);
1206                         meth=TLSv1_server_method();
1207                         }
1208 #endif
1209                 else if (strcmp(*argv,"-www") == 0)
1210                         { www=1; }
1211                 else if (strcmp(*argv,"-WWW") == 0)
1212                         { www=2; }
1213                 else if (strcmp(*argv,"-HTTP") == 0)
1214                         { www=3; }
1215                 else if (strcmp(*argv,"-no_ssl2") == 0)
1216                         { off|=SSL_OP_NO_SSLv2; }
1217                 else if (strcmp(*argv,"-no_ssl3") == 0)
1218                         { off|=SSL_OP_NO_SSLv3; }
1219                 else if (strcmp(*argv,"-no_tls1") == 0)
1220                         { off|=SSL_OP_NO_TLSv1; }
1221                 else if (strcmp(*argv,"-no_tls1_1") == 0)
1222                         { off|=SSL_OP_NO_TLSv1_1; }
1223                 else if (strcmp(*argv,"-no_tls1_2") == 0)
1224                         { off|=SSL_OP_NO_TLSv1_2; }
1225                 else if (strcmp(*argv,"-no_comp") == 0)
1226                         { off|=SSL_OP_NO_COMPRESSION; }
1227 #ifndef OPENSSL_NO_TLSEXT
1228                 else if (strcmp(*argv,"-no_ticket") == 0)
1229                         { off|=SSL_OP_NO_TICKET; }
1230 #endif
1231 #ifndef OPENSSL_NO_SSL2
1232                 else if (strcmp(*argv,"-ssl2") == 0)
1233                         { meth=SSLv2_server_method(); }
1234 #endif
1235 #ifndef OPENSSL_NO_SSL3
1236                 else if (strcmp(*argv,"-ssl3") == 0)
1237                         { meth=SSLv3_server_method(); }
1238 #endif
1239 #ifndef OPENSSL_NO_TLS1
1240                 else if (strcmp(*argv,"-tls1") == 0)
1241                         { meth=TLSv1_server_method(); }
1242                 else if (strcmp(*argv,"-tls1_1") == 0)
1243                         { meth=TLSv1_1_server_method(); }
1244                 else if (strcmp(*argv,"-tls1_2") == 0)
1245                         { meth=TLSv1_2_server_method(); }
1246 #endif
1247 #ifndef OPENSSL_NO_DTLS1
1248                 else if (strcmp(*argv,"-dtls1") == 0)
1249                         { 
1250                         meth=DTLSv1_server_method();
1251                         socket_type = SOCK_DGRAM;
1252                         }
1253                 else if (strcmp(*argv,"-timeout") == 0)
1254                         enable_timeouts = 1;
1255                 else if (strcmp(*argv,"-mtu") == 0)
1256                         {
1257                         if (--argc < 1) goto bad;
1258                         socket_mtu = atol(*(++argv));
1259                         }
1260                 else if (strcmp(*argv, "-chain") == 0)
1261                         cert_chain = 1;
1262 #endif
1263                 else if (strcmp(*argv, "-id_prefix") == 0)
1264                         {
1265                         if (--argc < 1) goto bad;
1266                         session_id_prefix = *(++argv);
1267                         }
1268 #ifndef OPENSSL_NO_ENGINE
1269                 else if (strcmp(*argv,"-engine") == 0)
1270                         {
1271                         if (--argc < 1) goto bad;
1272                         engine_id= *(++argv);
1273                         }
1274 #endif
1275                 else if (strcmp(*argv,"-rand") == 0)
1276                         {
1277                         if (--argc < 1) goto bad;
1278                         inrand= *(++argv);
1279                         }
1280 #ifndef OPENSSL_NO_TLSEXT
1281                 else if (strcmp(*argv,"-servername") == 0)
1282                         {
1283                         if (--argc < 1) goto bad;
1284                         tlsextcbp.servername= *(++argv);
1285                         }
1286                 else if (strcmp(*argv,"-servername_fatal") == 0)
1287                         { tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL; }
1288                 else if (strcmp(*argv,"-cert2") == 0)
1289                         {
1290                         if (--argc < 1) goto bad;
1291                         s_cert_file2= *(++argv);
1292                         }
1293                 else if (strcmp(*argv,"-key2") == 0)
1294                         {
1295                         if (--argc < 1) goto bad;
1296                         s_key_file2= *(++argv);
1297                         }
1298 # ifndef OPENSSL_NO_NEXTPROTONEG
1299                 else if (strcmp(*argv,"-nextprotoneg") == 0)
1300                         {
1301                         if (--argc < 1) goto bad;
1302                         next_proto_neg_in = *(++argv);
1303                         }
1304 # endif
1305 #endif
1306 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1307                 else if (strcmp(*argv,"-jpake") == 0)
1308                         {
1309                         if (--argc < 1) goto bad;
1310                         jpake_secret = *(++argv);
1311                         }
1312 #endif
1313                 else if (strcmp(*argv,"-use_srtp") == 0)
1314                         {
1315                         if (--argc < 1) goto bad;
1316                         srtp_profiles = *(++argv);
1317                         }
1318                 else
1319                         {
1320                         BIO_printf(bio_err,"unknown option %s\n",*argv);
1321                         badop=1;
1322                         break;
1323                         }
1324                 argc--;
1325                 argv++;
1326                 }
1327         if (badop)
1328                 {
1329 bad:
1330                 sv_usage();
1331                 goto end;
1332                 }
1333
1334 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1335         if (jpake_secret)
1336                 {
1337                 if (psk_key)
1338                         {
1339                         BIO_printf(bio_err,
1340                                    "Can't use JPAKE and PSK together\n");
1341                         goto end;
1342                         }
1343                 psk_identity = "JPAKE";
1344                 if (cipher)
1345                         {
1346                         BIO_printf(bio_err, "JPAKE sets cipher to PSK\n");
1347                         goto end;
1348                         }
1349                 cipher = "PSK";
1350                 }
1351
1352 #endif
1353
1354         SSL_load_error_strings();
1355         OpenSSL_add_ssl_algorithms();
1356
1357 #ifndef OPENSSL_NO_ENGINE
1358         e = setup_engine(bio_err, engine_id, 1);
1359 #endif
1360
1361         if (!app_passwd(bio_err, passarg, dpassarg, &pass, &dpass))
1362                 {
1363                 BIO_printf(bio_err, "Error getting password\n");
1364                 goto end;
1365                 }
1366
1367
1368         if (s_key_file == NULL)
1369                 s_key_file = s_cert_file;
1370 #ifndef OPENSSL_NO_TLSEXT
1371         if (s_key_file2 == NULL)
1372                 s_key_file2 = s_cert_file2;
1373 #endif
1374
1375         if (nocert == 0)
1376                 {
1377                 s_key = load_key(bio_err, s_key_file, s_key_format, 0, pass, e,
1378                        "server certificate private key file");
1379                 if (!s_key)
1380                         {
1381                         ERR_print_errors(bio_err);
1382                         goto end;
1383                         }
1384
1385                 s_cert = load_cert(bio_err,s_cert_file,s_cert_format,
1386                         NULL, e, "server certificate file");
1387
1388                 if (!s_cert)
1389                         {
1390                         ERR_print_errors(bio_err);
1391                         goto end;
1392                         }
1393
1394 #ifndef OPENSSL_NO_TLSEXT
1395                 if (tlsextcbp.servername) 
1396                         {
1397                         s_key2 = load_key(bio_err, s_key_file2, s_key_format, 0, pass, e,
1398                                 "second server certificate private key file");
1399                         if (!s_key2)
1400                                 {
1401                                 ERR_print_errors(bio_err);
1402                                 goto end;
1403                                 }
1404                         
1405                         s_cert2 = load_cert(bio_err,s_cert_file2,s_cert_format,
1406                                 NULL, e, "second server certificate file");
1407                         
1408                         if (!s_cert2)
1409                                 {
1410                                 ERR_print_errors(bio_err);
1411                                 goto end;
1412                                 }
1413                         }
1414
1415 # ifndef OPENSSL_NO_NEXTPROTONEG
1416                 if (next_proto_neg_in)
1417                         {
1418                         unsigned short len;
1419                         next_proto.data = next_protos_parse(&len,
1420                                 next_proto_neg_in);
1421                         if (next_proto.data == NULL)
1422                                 goto end;
1423                         next_proto.len = len;
1424                         }
1425                 else
1426                         {
1427                         next_proto.data = NULL;
1428                         }
1429 # endif
1430 #endif
1431                 }
1432
1433
1434         if (s_dcert_file)
1435                 {
1436
1437                 if (s_dkey_file == NULL)
1438                         s_dkey_file = s_dcert_file;
1439
1440                 s_dkey = load_key(bio_err, s_dkey_file, s_dkey_format,
1441                                 0, dpass, e,
1442                                "second certificate private key file");
1443                 if (!s_dkey)
1444                         {
1445                         ERR_print_errors(bio_err);
1446                         goto end;
1447                         }
1448
1449                 s_dcert = load_cert(bio_err,s_dcert_file,s_dcert_format,
1450                                 NULL, e, "second server certificate file");
1451
1452                 if (!s_dcert)
1453                         {
1454                         ERR_print_errors(bio_err);
1455                         goto end;
1456                         }
1457
1458                 }
1459
1460         if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
1461                 && !RAND_status())
1462                 {
1463                 BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
1464                 }
1465         if (inrand != NULL)
1466                 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
1467                         app_RAND_load_files(inrand));
1468
1469         if (bio_s_out == NULL)
1470                 {
1471                 if (s_quiet && !s_debug && !s_msg)
1472                         {
1473                         bio_s_out=BIO_new(BIO_s_null());
1474                         }
1475                 else
1476                         {
1477                         if (bio_s_out == NULL)
1478                                 bio_s_out=BIO_new_fp(stdout,BIO_NOCLOSE);
1479                         }
1480                 }
1481
1482 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1483         if (nocert)
1484 #endif
1485                 {
1486                 s_cert_file=NULL;
1487                 s_key_file=NULL;
1488                 s_dcert_file=NULL;
1489                 s_dkey_file=NULL;
1490 #ifndef OPENSSL_NO_TLSEXT
1491                 s_cert_file2=NULL;
1492                 s_key_file2=NULL;
1493 #endif
1494                 }
1495
1496         ctx=SSL_CTX_new(meth);
1497         if (ctx == NULL)
1498                 {
1499                 ERR_print_errors(bio_err);
1500                 goto end;
1501                 }
1502         if (session_id_prefix)
1503                 {
1504                 if(strlen(session_id_prefix) >= 32)
1505                         BIO_printf(bio_err,
1506 "warning: id_prefix is too long, only one new session will be possible\n");
1507                 else if(strlen(session_id_prefix) >= 16)
1508                         BIO_printf(bio_err,
1509 "warning: id_prefix is too long if you use SSLv2\n");
1510                 if(!SSL_CTX_set_generate_session_id(ctx, generate_session_id))
1511                         {
1512                         BIO_printf(bio_err,"error setting 'id_prefix'\n");
1513                         ERR_print_errors(bio_err);
1514                         goto end;
1515                         }
1516                 BIO_printf(bio_err,"id_prefix '%s' set.\n", session_id_prefix);
1517                 }
1518         SSL_CTX_set_quiet_shutdown(ctx,1);
1519         if (bugs) SSL_CTX_set_options(ctx,SSL_OP_ALL);
1520         if (hack) SSL_CTX_set_options(ctx,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
1521         SSL_CTX_set_options(ctx,off);
1522         /* DTLS: partial reads end up discarding unread UDP bytes :-( 
1523          * Setting read ahead solves this problem.
1524          */
1525         if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1);
1526
1527         if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
1528         if (no_cache)
1529                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1530         else
1531                 SSL_CTX_sess_set_cache_size(ctx,128);
1532
1533         if (srtp_profiles != NULL)
1534                 SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
1535
1536 #if 0
1537         if (cipher == NULL) cipher=getenv("SSL_CIPHER");
1538 #endif
1539
1540 #if 0
1541         if (s_cert_file == NULL)
1542                 {
1543                 BIO_printf(bio_err,"You must specify a certificate file for the server to use\n");
1544                 goto end;
1545                 }
1546 #endif
1547
1548         if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
1549                 (!SSL_CTX_set_default_verify_paths(ctx)))
1550                 {
1551                 /* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
1552                 ERR_print_errors(bio_err);
1553                 /* goto end; */
1554                 }
1555         if (vpm)
1556                 SSL_CTX_set1_param(ctx, vpm);
1557
1558 #ifndef OPENSSL_NO_TLSEXT
1559         if (s_cert2)
1560                 {
1561                 ctx2=SSL_CTX_new(meth);
1562                 if (ctx2 == NULL)
1563                         {
1564                         ERR_print_errors(bio_err);
1565                         goto end;
1566                         }
1567                 }
1568         
1569         if (ctx2)
1570                 {
1571                 BIO_printf(bio_s_out,"Setting secondary ctx parameters\n");
1572
1573                 if (session_id_prefix)
1574                         {
1575                         if(strlen(session_id_prefix) >= 32)
1576                                 BIO_printf(bio_err,
1577                                         "warning: id_prefix is too long, only one new session will be possible\n");
1578                         else if(strlen(session_id_prefix) >= 16)
1579                                 BIO_printf(bio_err,
1580                                         "warning: id_prefix is too long if you use SSLv2\n");
1581                         if(!SSL_CTX_set_generate_session_id(ctx2, generate_session_id))
1582                                 {
1583                                 BIO_printf(bio_err,"error setting 'id_prefix'\n");
1584                                 ERR_print_errors(bio_err);
1585                                 goto end;
1586                                 }
1587                         BIO_printf(bio_err,"id_prefix '%s' set.\n", session_id_prefix);
1588                         }
1589                 SSL_CTX_set_quiet_shutdown(ctx2,1);
1590                 if (bugs) SSL_CTX_set_options(ctx2,SSL_OP_ALL);
1591                 if (hack) SSL_CTX_set_options(ctx2,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
1592                 SSL_CTX_set_options(ctx2,off);
1593                 /* DTLS: partial reads end up discarding unread UDP bytes :-( 
1594                  * Setting read ahead solves this problem.
1595                  */
1596                 if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx2, 1);
1597
1598                 if (state) SSL_CTX_set_info_callback(ctx2,apps_ssl_info_callback);
1599
1600                 if (no_cache)
1601                         SSL_CTX_set_session_cache_mode(ctx2,SSL_SESS_CACHE_OFF);
1602                 else
1603                         SSL_CTX_sess_set_cache_size(ctx2,128);
1604
1605                 if ((!SSL_CTX_load_verify_locations(ctx2,CAfile,CApath)) ||
1606                         (!SSL_CTX_set_default_verify_paths(ctx2)))
1607                         {
1608                         ERR_print_errors(bio_err);
1609                         }
1610                 if (vpm)
1611                         SSL_CTX_set1_param(ctx2, vpm);
1612                 }
1613
1614 # ifndef OPENSSL_NO_NEXTPROTONEG
1615         if (next_proto.data)
1616                 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto);
1617 # endif
1618 #endif 
1619
1620 #ifndef OPENSSL_NO_DH
1621         if (!no_dhe)
1622                 {
1623                 DH *dh=NULL;
1624
1625                 if (dhfile)
1626                         dh = load_dh_param(dhfile);
1627                 else if (s_cert_file)
1628                         dh = load_dh_param(s_cert_file);
1629
1630                 if (dh != NULL)
1631                         {
1632                         BIO_printf(bio_s_out,"Setting temp DH parameters\n");
1633                         }
1634                 else
1635                         {
1636                         BIO_printf(bio_s_out,"Using default temp DH parameters\n");
1637                         dh=get_dh512();
1638                         }
1639                 (void)BIO_flush(bio_s_out);
1640
1641                 SSL_CTX_set_tmp_dh(ctx,dh);
1642 #ifndef OPENSSL_NO_TLSEXT
1643                 if (ctx2)
1644                         {
1645                         if (!dhfile)
1646                                 { 
1647                                 DH *dh2=load_dh_param(s_cert_file2);
1648                                 if (dh2 != NULL)
1649                                         {
1650                                         BIO_printf(bio_s_out,"Setting temp DH parameters\n");
1651                                         (void)BIO_flush(bio_s_out);
1652
1653                                         DH_free(dh);
1654                                         dh = dh2;
1655                                         }
1656                                 }
1657                         SSL_CTX_set_tmp_dh(ctx2,dh);
1658                         }
1659 #endif
1660                 DH_free(dh);
1661                 }
1662 #endif
1663
1664 #ifndef OPENSSL_NO_ECDH
1665         if (!no_ecdhe)
1666                 {
1667                 EC_KEY *ecdh=NULL;
1668
1669                 if (named_curve)
1670                         {
1671                         int nid = OBJ_sn2nid(named_curve);
1672
1673                         if (nid == 0)
1674                                 {
1675                                 BIO_printf(bio_err, "unknown curve name (%s)\n", 
1676                                         named_curve);
1677                                 goto end;
1678                                 }
1679                         ecdh = EC_KEY_new_by_curve_name(nid);
1680                         if (ecdh == NULL)
1681                                 {
1682                                 BIO_printf(bio_err, "unable to create curve (%s)\n", 
1683                                         named_curve);
1684                                 goto end;
1685                                 }
1686                         }
1687
1688                 if (ecdh != NULL)
1689                         {
1690                         BIO_printf(bio_s_out,"Setting temp ECDH parameters\n");
1691                         }
1692                 else
1693                         {
1694                         BIO_printf(bio_s_out,"Using default temp ECDH parameters\n");
1695                         ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1696                         if (ecdh == NULL) 
1697                                 {
1698                                 BIO_printf(bio_err, "unable to create curve (nistp256)\n");
1699                                 goto end;
1700                                 }
1701                         }
1702                 (void)BIO_flush(bio_s_out);
1703
1704                 SSL_CTX_set_tmp_ecdh(ctx,ecdh);
1705 #ifndef OPENSSL_NO_TLSEXT
1706                 if (ctx2) 
1707                         SSL_CTX_set_tmp_ecdh(ctx2,ecdh);
1708 #endif
1709                 EC_KEY_free(ecdh);
1710                 }
1711 #endif
1712         
1713         if (!set_cert_key_stuff(ctx,s_cert,s_key))
1714                 goto end;
1715 #ifndef OPENSSL_NO_TLSEXT
1716         if (ctx2 && !set_cert_key_stuff(ctx2,s_cert2,s_key2))
1717                 goto end; 
1718 #endif
1719         if (s_dcert != NULL)
1720                 {
1721                 if (!set_cert_key_stuff(ctx,s_dcert,s_dkey))
1722                         goto end;
1723                 }
1724
1725 #ifndef OPENSSL_NO_RSA
1726 #if 1
1727         if (!no_tmp_rsa)
1728                 {
1729                 SSL_CTX_set_tmp_rsa_callback(ctx,tmp_rsa_cb);
1730 #ifndef OPENSSL_NO_TLSEXT
1731                 if (ctx2) 
1732                         SSL_CTX_set_tmp_rsa_callback(ctx2,tmp_rsa_cb);
1733 #endif          
1734                 }
1735 #else
1736         if (!no_tmp_rsa && SSL_CTX_need_tmp_RSA(ctx))
1737                 {
1738                 RSA *rsa;
1739
1740                 BIO_printf(bio_s_out,"Generating temp (512 bit) RSA key...");
1741                 BIO_flush(bio_s_out);
1742
1743                 rsa=RSA_generate_key(512,RSA_F4,NULL);
1744
1745                 if (!SSL_CTX_set_tmp_rsa(ctx,rsa))
1746                         {
1747                         ERR_print_errors(bio_err);
1748                         goto end;
1749                         }
1750 #ifndef OPENSSL_NO_TLSEXT
1751                         if (ctx2)
1752                                 {
1753                                 if (!SSL_CTX_set_tmp_rsa(ctx2,rsa))
1754                                         {
1755                                         ERR_print_errors(bio_err);
1756                                         goto end;
1757                                         }
1758                                 }
1759 #endif
1760                 RSA_free(rsa);
1761                 BIO_printf(bio_s_out,"\n");
1762                 }
1763 #endif
1764 #endif
1765
1766 #ifndef OPENSSL_NO_PSK
1767 #ifdef OPENSSL_NO_JPAKE
1768         if (psk_key != NULL)
1769 #else
1770         if (psk_key != NULL || jpake_secret)
1771 #endif
1772                 {
1773                 if (s_debug)
1774                         BIO_printf(bio_s_out, "PSK key given or JPAKE in use, setting server callback\n");
1775                 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1776                 }
1777
1778         if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint))
1779                 {
1780                 BIO_printf(bio_err,"error setting PSK identity hint to context\n");
1781                 ERR_print_errors(bio_err);
1782                 goto end;
1783                 }
1784 #endif
1785
1786         if (cipher != NULL)
1787                 {
1788                 if(!SSL_CTX_set_cipher_list(ctx,cipher))
1789                         {
1790                         BIO_printf(bio_err,"error setting cipher list\n");
1791                         ERR_print_errors(bio_err);
1792                         goto end;
1793                         }
1794 #ifndef OPENSSL_NO_TLSEXT
1795                 if (ctx2 && !SSL_CTX_set_cipher_list(ctx2,cipher))
1796                         {
1797                         BIO_printf(bio_err,"error setting cipher list\n");
1798                         ERR_print_errors(bio_err);
1799                         goto end;
1800                         }
1801 #endif
1802                 }
1803         SSL_CTX_set_verify(ctx,s_server_verify,verify_callback);
1804         SSL_CTX_set_session_id_context(ctx,(void*)&s_server_session_id_context,
1805                 sizeof s_server_session_id_context);
1806
1807         /* Set DTLS cookie generation and verification callbacks */
1808         SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1809         SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1810
1811 #ifndef OPENSSL_NO_TLSEXT
1812         if (ctx2)
1813                 {
1814                 SSL_CTX_set_verify(ctx2,s_server_verify,verify_callback);
1815                 SSL_CTX_set_session_id_context(ctx2,(void*)&s_server_session_id_context,
1816                         sizeof s_server_session_id_context);
1817
1818                 tlsextcbp.biodebug = bio_s_out;
1819                 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1820                 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1821                 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1822                 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1823                 }
1824 #endif
1825
1826 #ifndef OPENSSL_NO_SRP
1827         if (srp_verifier_file != NULL)
1828                 {
1829                 p.vb = SRP_VBASE_new(srpuserseed);
1830                 if ((ret = SRP_VBASE_init(p.vb, srp_verifier_file)) != SRP_NO_ERROR)
1831                         {
1832                         BIO_printf(bio_err,
1833                                    "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1834                                    srp_verifier_file, ret);
1835                                 goto end;
1836                         }
1837                 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE,verify_callback);
1838                 SSL_CTX_set_srp_cb_arg(ctx, &p);                        
1839                 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1840                 }
1841         else
1842 #endif
1843         if (CAfile != NULL)
1844                 {
1845                 SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file(CAfile));
1846 #ifndef OPENSSL_NO_TLSEXT
1847                 if (ctx2) 
1848                         SSL_CTX_set_client_CA_list(ctx2,SSL_load_client_CA_file(CAfile));
1849 #endif
1850                 }
1851
1852         BIO_printf(bio_s_out,"ACCEPT\n");
1853         (void)BIO_flush(bio_s_out);
1854         if (www)
1855                 do_server(port,socket_type,&accept_socket,www_body, context);
1856         else
1857                 do_server(port,socket_type,&accept_socket,sv_body, context);
1858         print_stats(bio_s_out,ctx);
1859         ret=0;
1860 end:
1861         if (ctx != NULL) SSL_CTX_free(ctx);
1862         if (s_cert)
1863                 X509_free(s_cert);
1864         if (s_dcert)
1865                 X509_free(s_dcert);
1866         if (s_key)
1867                 EVP_PKEY_free(s_key);
1868         if (s_dkey)
1869                 EVP_PKEY_free(s_dkey);
1870         if (pass)
1871                 OPENSSL_free(pass);
1872         if (dpass)
1873                 OPENSSL_free(dpass);
1874 #ifndef OPENSSL_NO_TLSEXT
1875         if (ctx2 != NULL) SSL_CTX_free(ctx2);
1876         if (s_cert2)
1877                 X509_free(s_cert2);
1878         if (s_key2)
1879                 EVP_PKEY_free(s_key2);
1880 #endif
1881         if (bio_s_out != NULL)
1882                 {
1883         BIO_free(bio_s_out);
1884                 bio_s_out=NULL;
1885                 }
1886         apps_shutdown();
1887         OPENSSL_EXIT(ret);
1888         }
1889
1890 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
1891         {
1892         BIO_printf(bio,"%4ld items in the session cache\n",
1893                 SSL_CTX_sess_number(ssl_ctx));
1894         BIO_printf(bio,"%4ld client connects (SSL_connect())\n",
1895                 SSL_CTX_sess_connect(ssl_ctx));
1896         BIO_printf(bio,"%4ld client renegotiates (SSL_connect())\n",
1897                 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
1898         BIO_printf(bio,"%4ld client connects that finished\n",
1899                 SSL_CTX_sess_connect_good(ssl_ctx));
1900         BIO_printf(bio,"%4ld server accepts (SSL_accept())\n",
1901                 SSL_CTX_sess_accept(ssl_ctx));
1902         BIO_printf(bio,"%4ld server renegotiates (SSL_accept())\n",
1903                 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
1904         BIO_printf(bio,"%4ld server accepts that finished\n",
1905                 SSL_CTX_sess_accept_good(ssl_ctx));
1906         BIO_printf(bio,"%4ld session cache hits\n",SSL_CTX_sess_hits(ssl_ctx));
1907         BIO_printf(bio,"%4ld session cache misses\n",SSL_CTX_sess_misses(ssl_ctx));
1908         BIO_printf(bio,"%4ld session cache timeouts\n",SSL_CTX_sess_timeouts(ssl_ctx));
1909         BIO_printf(bio,"%4ld callback cache hits\n",SSL_CTX_sess_cb_hits(ssl_ctx));
1910         BIO_printf(bio,"%4ld cache full overflows (%ld allowed)\n",
1911                 SSL_CTX_sess_cache_full(ssl_ctx),
1912                 SSL_CTX_sess_get_cache_size(ssl_ctx));
1913         }
1914
1915 static int sv_body(char *hostname, int s, unsigned char *context)
1916         {
1917         char *buf=NULL;
1918         fd_set readfds;
1919         int ret=1,width;
1920         int k,i;
1921         unsigned long l;
1922         SSL *con=NULL;
1923         BIO *sbio;
1924 #ifndef OPENSSL_NO_KRB5
1925         KSSL_CTX *kctx;
1926 #endif
1927         struct timeval timeout;
1928 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
1929         struct timeval tv;
1930 #else
1931         struct timeval *timeoutp;
1932 #endif
1933
1934         if ((buf=OPENSSL_malloc(bufsize)) == NULL)
1935                 {
1936                 BIO_printf(bio_err,"out of memory\n");
1937                 goto err;
1938                 }
1939 #ifdef FIONBIO  
1940         if (s_nbio)
1941                 {
1942                 unsigned long sl=1;
1943
1944                 if (!s_quiet)
1945                         BIO_printf(bio_err,"turning on non blocking io\n");
1946                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
1947                         ERR_print_errors(bio_err);
1948                 }
1949 #endif
1950
1951         if (con == NULL) {
1952                 con=SSL_new(ctx);
1953 #ifndef OPENSSL_NO_TLSEXT
1954         if (s_tlsextdebug)
1955                 {
1956                 SSL_set_tlsext_debug_callback(con, tlsext_cb);
1957                 SSL_set_tlsext_debug_arg(con, bio_s_out);
1958                 }
1959         if (s_tlsextstatus)
1960                 {
1961                 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1962                 tlscstatp.err = bio_err;
1963                 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1964                 }
1965 #endif
1966 #ifndef OPENSSL_NO_KRB5
1967                 if ((kctx = kssl_ctx_new()) != NULL)
1968                         {
1969                         SSL_set0_kssl_ctx(con, kctx);
1970                         kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
1971                         kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
1972                         }
1973 #endif  /* OPENSSL_NO_KRB5 */
1974                 if(context)
1975                       SSL_set_session_id_context(con, context,
1976                                                  strlen((char *)context));
1977         }
1978         SSL_clear(con);
1979 #if 0
1980 #ifdef TLSEXT_TYPE_opaque_prf_input
1981         SSL_set_tlsext_opaque_prf_input(con, "Test server", 11);
1982 #endif
1983 #endif
1984
1985         if (SSL_version(con) == DTLS1_VERSION)
1986                 {
1987
1988                 sbio=BIO_new_dgram(s,BIO_NOCLOSE);
1989
1990                 if (enable_timeouts)
1991                         {
1992                         timeout.tv_sec = 0;
1993                         timeout.tv_usec = DGRAM_RCV_TIMEOUT;
1994                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
1995                         
1996                         timeout.tv_sec = 0;
1997                         timeout.tv_usec = DGRAM_SND_TIMEOUT;
1998                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
1999                         }
2000
2001                 if (socket_mtu > 28)
2002                         {
2003                         SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2004                         SSL_set_mtu(con, socket_mtu - 28);
2005                         }
2006                 else
2007                         /* want to do MTU discovery */
2008                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2009
2010         /* turn on cookie exchange */
2011         SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2012                 }
2013         else
2014                 sbio=BIO_new_socket(s,BIO_NOCLOSE);
2015
2016         if (s_nbio_test)
2017                 {
2018                 BIO *test;
2019
2020                 test=BIO_new(BIO_f_nbio_test());
2021                 sbio=BIO_push(test,sbio);
2022                 }
2023 #ifndef OPENSSL_NO_JPAKE
2024         if(jpake_secret)
2025                 jpake_server_auth(bio_s_out, sbio, jpake_secret);
2026 #endif
2027
2028         SSL_set_bio(con,sbio,sbio);
2029         SSL_set_accept_state(con);
2030         /* SSL_set_fd(con,s); */
2031
2032         if (s_debug)
2033                 {
2034                 SSL_set_debug(con, 1);
2035                 BIO_set_callback(SSL_get_rbio(con),bio_dump_callback);
2036                 BIO_set_callback_arg(SSL_get_rbio(con),(char *)bio_s_out);
2037                 }
2038         if (s_msg)
2039                 {
2040                 SSL_set_msg_callback(con, msg_cb);
2041                 SSL_set_msg_callback_arg(con, bio_s_out);
2042                 }
2043 #ifndef OPENSSL_NO_TLSEXT
2044         if (s_tlsextdebug)
2045                 {
2046                 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2047                 SSL_set_tlsext_debug_arg(con, bio_s_out);
2048                 }
2049 #endif
2050
2051         width=s+1;
2052         for (;;)
2053                 {
2054                 int read_from_terminal;
2055                 int read_from_sslcon;
2056
2057                 read_from_terminal = 0;
2058                 read_from_sslcon = SSL_pending(con);
2059
2060                 if (!read_from_sslcon)
2061                         {
2062                         FD_ZERO(&readfds);
2063 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined(OPENSSL_SYS_BEOS_R5)
2064                         openssl_fdset(fileno(stdin),&readfds);
2065 #endif
2066                         openssl_fdset(s,&readfds);
2067                         /* Note: under VMS with SOCKETSHR the second parameter is
2068                          * currently of type (int *) whereas under other systems
2069                          * it is (void *) if you don't have a cast it will choke
2070                          * the compiler: if you do have a cast then you can either
2071                          * go for (int *) or (void *).
2072                          */
2073 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
2074                         /* Under DOS (non-djgpp) and Windows we can't select on stdin: only
2075                          * on sockets. As a workaround we timeout the select every
2076                          * second and check for any keypress. In a proper Windows
2077                          * application we wouldn't do this because it is inefficient.
2078                          */
2079                         tv.tv_sec = 1;
2080                         tv.tv_usec = 0;
2081                         i=select(width,(void *)&readfds,NULL,NULL,&tv);
2082                         if((i < 0) || (!i && !_kbhit() ) )continue;
2083                         if(_kbhit())
2084                                 read_from_terminal = 1;
2085 #elif defined(OPENSSL_SYS_BEOS_R5)
2086                         /* Under BeOS-R5 the situation is similar to DOS */
2087                         tv.tv_sec = 1;
2088                         tv.tv_usec = 0;
2089                         (void)fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
2090                         i=select(width,(void *)&readfds,NULL,NULL,&tv);
2091                         if ((i < 0) || (!i && read(fileno(stdin), buf, 0) < 0))
2092                                 continue;
2093                         if (read(fileno(stdin), buf, 0) >= 0)
2094                                 read_from_terminal = 1;
2095                         (void)fcntl(fileno(stdin), F_SETFL, 0);
2096 #else
2097                         if ((SSL_version(con) == DTLS1_VERSION) &&
2098                                 DTLSv1_get_timeout(con, &timeout))
2099                                 timeoutp = &timeout;
2100                         else
2101                                 timeoutp = NULL;
2102
2103                         i=select(width,(void *)&readfds,NULL,NULL,timeoutp);
2104
2105                         if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0)
2106                                 {
2107                                 BIO_printf(bio_err,"TIMEOUT occured\n");
2108                                 }
2109
2110                         if (i <= 0) continue;
2111                         if (FD_ISSET(fileno(stdin),&readfds))
2112                                 read_from_terminal = 1;
2113 #endif
2114                         if (FD_ISSET(s,&readfds))
2115                                 read_from_sslcon = 1;
2116                         }
2117                 if (read_from_terminal)
2118                         {
2119                         if (s_crlf)
2120                                 {
2121                                 int j, lf_num;
2122
2123                                 i=raw_read_stdin(buf, bufsize/2);
2124                                 lf_num = 0;
2125                                 /* both loops are skipped when i <= 0 */
2126                                 for (j = 0; j < i; j++)
2127                                         if (buf[j] == '\n')
2128                                                 lf_num++;
2129                                 for (j = i-1; j >= 0; j--)
2130                                         {
2131                                         buf[j+lf_num] = buf[j];
2132                                         if (buf[j] == '\n')
2133                                                 {
2134                                                 lf_num--;
2135                                                 i++;
2136                                                 buf[j+lf_num] = '\r';
2137                                                 }
2138                                         }
2139                                 assert(lf_num == 0);
2140                                 }
2141                         else
2142                                 i=raw_read_stdin(buf,bufsize);
2143                         if (!s_quiet)
2144                                 {
2145                                 if ((i <= 0) || (buf[0] == 'Q'))
2146                                         {
2147                                         BIO_printf(bio_s_out,"DONE\n");
2148                                         SHUTDOWN(s);
2149                                         close_accept_socket();
2150                                         ret= -11;
2151                                         goto err;
2152                                         }
2153                                 if ((i <= 0) || (buf[0] == 'q'))
2154                                         {
2155                                         BIO_printf(bio_s_out,"DONE\n");
2156                                         if (SSL_version(con) != DTLS1_VERSION)
2157                         SHUTDOWN(s);
2158         /*                              close_accept_socket();
2159                                         ret= -11;*/
2160                                         goto err;
2161                                         }
2162
2163                                 if ((buf[0] == 'r') && 
2164                                         ((buf[1] == '\n') || (buf[1] == '\r')))
2165                                         {
2166                                         SSL_renegotiate(con);
2167                                         i=SSL_do_handshake(con);
2168                                         printf("SSL_do_handshake -> %d\n",i);
2169                                         i=0; /*13; */
2170                                         continue;
2171                                         /* strcpy(buf,"server side RE-NEGOTIATE\n"); */
2172                                         }
2173                                 if ((buf[0] == 'R') &&
2174                                         ((buf[1] == '\n') || (buf[1] == '\r')))
2175                                         {
2176                                         SSL_set_verify(con,
2177                                                 SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,NULL);
2178                                         SSL_renegotiate(con);
2179                                         i=SSL_do_handshake(con);
2180                                         printf("SSL_do_handshake -> %d\n",i);
2181                                         i=0; /* 13; */
2182                                         continue;
2183                                         /* strcpy(buf,"server side RE-NEGOTIATE asking for client cert\n"); */
2184                                         }
2185                                 if (buf[0] == 'P')
2186                                         {
2187                                         static const char *str="Lets print some clear text\n";
2188                                         BIO_write(SSL_get_wbio(con),str,strlen(str));
2189                                         }
2190                                 if (buf[0] == 'S')
2191                                         {
2192                                         print_stats(bio_s_out,SSL_get_SSL_CTX(con));
2193                                         }
2194                                 }
2195 #ifdef CHARSET_EBCDIC
2196                         ebcdic2ascii(buf,buf,i);
2197 #endif
2198                         l=k=0;
2199                         for (;;)
2200                                 {
2201                                 /* should do a select for the write */
2202 #ifdef RENEG
2203 { static count=0; if (++count == 100) { count=0; SSL_renegotiate(con); } }
2204 #endif
2205                                 k=SSL_write(con,&(buf[l]),(unsigned int)i);
2206                                 switch (SSL_get_error(con,k))
2207                                         {
2208                                 case SSL_ERROR_NONE:
2209                                         break;
2210                                 case SSL_ERROR_WANT_WRITE:
2211                                 case SSL_ERROR_WANT_READ:
2212                                 case SSL_ERROR_WANT_X509_LOOKUP:
2213                                         BIO_printf(bio_s_out,"Write BLOCK\n");
2214                                         break;
2215                                 case SSL_ERROR_SYSCALL:
2216                                 case SSL_ERROR_SSL:
2217                                         BIO_printf(bio_s_out,"ERROR\n");
2218                                         ERR_print_errors(bio_err);
2219                                         ret=1;
2220                                         goto err;
2221                                         /* break; */
2222                                 case SSL_ERROR_ZERO_RETURN:
2223                                         BIO_printf(bio_s_out,"DONE\n");
2224                                         ret=1;
2225                                         goto err;
2226                                         }
2227                                 l+=k;
2228                                 i-=k;
2229                                 if (i <= 0) break;
2230                                 }
2231                         }
2232                 if (read_from_sslcon)
2233                         {
2234                         if (!SSL_is_init_finished(con))
2235                                 {
2236                                 i=init_ssl_connection(con);
2237                                 
2238                                 if (i < 0)
2239                                         {
2240                                         ret=0;
2241                                         goto err;
2242                                         }
2243                                 else if (i == 0)
2244                                         {
2245                                         ret=1;
2246                                         goto err;
2247                                         }
2248                                 }
2249                         else
2250                                 {
2251 again:  
2252                                 i=SSL_read(con,(char *)buf,bufsize);
2253                                 switch (SSL_get_error(con,i))
2254                                         {
2255                                 case SSL_ERROR_NONE:
2256 #ifdef CHARSET_EBCDIC
2257                                         ascii2ebcdic(buf,buf,i);
2258 #endif
2259                                         raw_write_stdout(buf,
2260                                                 (unsigned int)i);
2261                                         if (SSL_pending(con)) goto again;
2262                                         break;
2263                                 case SSL_ERROR_WANT_WRITE:
2264                                 case SSL_ERROR_WANT_READ:
2265                                 case SSL_ERROR_WANT_X509_LOOKUP:
2266                                         BIO_printf(bio_s_out,"Read BLOCK\n");
2267                                         break;
2268                                 case SSL_ERROR_SYSCALL:
2269                                 case SSL_ERROR_SSL:
2270                                         BIO_printf(bio_s_out,"ERROR\n");
2271                                         ERR_print_errors(bio_err);
2272                                         ret=1;
2273                                         goto err;
2274                                 case SSL_ERROR_ZERO_RETURN:
2275                                         BIO_printf(bio_s_out,"DONE\n");
2276                                         ret=1;
2277                                         goto err;
2278                                         }
2279                                 }
2280                         }
2281                 }
2282 err:
2283         if (con != NULL)
2284                 {
2285                 BIO_printf(bio_s_out,"shutting down SSL\n");
2286 #if 1
2287                 SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
2288 #else
2289                 SSL_shutdown(con);
2290 #endif
2291                 SSL_free(con);
2292                 }
2293         BIO_printf(bio_s_out,"CONNECTION CLOSED\n");
2294         if (buf != NULL)
2295                 {
2296                 OPENSSL_cleanse(buf,bufsize);
2297                 OPENSSL_free(buf);
2298                 }
2299         if (ret >= 0)
2300                 BIO_printf(bio_s_out,"ACCEPT\n");
2301         return(ret);
2302         }
2303
2304 static void close_accept_socket(void)
2305         {
2306         BIO_printf(bio_err,"shutdown accept socket\n");
2307         if (accept_socket >= 0)
2308                 {
2309                 SHUTDOWN2(accept_socket);
2310                 }
2311         }
2312
2313 static int init_ssl_connection(SSL *con)
2314         {
2315         int i;
2316         const char *str;
2317         X509 *peer;
2318         long verify_error;
2319         MS_STATIC char buf[BUFSIZ];
2320 #ifndef OPENSSL_NO_KRB5
2321         char *client_princ;
2322 #endif
2323 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
2324         const unsigned char *next_proto_neg;
2325         unsigned next_proto_neg_len;
2326 #endif
2327
2328         if ((i=SSL_accept(con)) <= 0)
2329                 {
2330                 if (BIO_sock_should_retry(i))
2331                         {
2332                         BIO_printf(bio_s_out,"DELAY\n");
2333                         return(1);
2334                         }
2335
2336                 BIO_printf(bio_err,"ERROR\n");
2337                 verify_error=SSL_get_verify_result(con);
2338                 if (verify_error != X509_V_OK)
2339                         {
2340                         BIO_printf(bio_err,"verify error:%s\n",
2341                                 X509_verify_cert_error_string(verify_error));
2342                         }
2343                 else
2344                         ERR_print_errors(bio_err);
2345                 return(0);
2346                 }
2347
2348         PEM_write_bio_SSL_SESSION(bio_s_out,SSL_get_session(con));
2349
2350         peer=SSL_get_peer_certificate(con);
2351         if (peer != NULL)
2352                 {
2353                 BIO_printf(bio_s_out,"Client certificate\n");
2354                 PEM_write_bio_X509(bio_s_out,peer);
2355                 X509_NAME_oneline(X509_get_subject_name(peer),buf,sizeof buf);
2356                 BIO_printf(bio_s_out,"subject=%s\n",buf);
2357                 X509_NAME_oneline(X509_get_issuer_name(peer),buf,sizeof buf);
2358                 BIO_printf(bio_s_out,"issuer=%s\n",buf);
2359                 X509_free(peer);
2360                 }
2361
2362         if (SSL_get_shared_ciphers(con,buf,sizeof buf) != NULL)
2363                 BIO_printf(bio_s_out,"Shared ciphers:%s\n",buf);
2364         str=SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2365         BIO_printf(bio_s_out,"CIPHER is %s\n",(str != NULL)?str:"(NONE)");
2366 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
2367         SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2368         if (next_proto_neg)
2369                 {
2370                 BIO_printf(bio_s_out,"NEXTPROTO is ");
2371                 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2372                 BIO_printf(bio_s_out, "\n");
2373                 }
2374 #endif
2375         {
2376         SRTP_PROTECTION_PROFILE *srtp_profile
2377           = SSL_get_selected_srtp_profile(con);
2378
2379         if(srtp_profile)
2380                 BIO_printf(bio_s_out,"SRTP Extension negotiated, profile=%s\n",
2381                            srtp_profile->name);
2382         }
2383         if (SSL_cache_hit(con)) BIO_printf(bio_s_out,"Reused session-id\n");
2384         if (SSL_ctrl(con,SSL_CTRL_GET_FLAGS,0,NULL) &
2385                 TLS1_FLAGS_TLS_PADDING_BUG)
2386                 BIO_printf(bio_s_out,
2387                            "Peer has incorrect TLSv1 block padding\n");
2388 #ifndef OPENSSL_NO_KRB5
2389         client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con));
2390         if (client_princ != NULL)
2391                 {
2392                 BIO_printf(bio_s_out,"Kerberos peer principal is %s\n",
2393                                                                 client_princ);
2394                 }
2395 #endif /* OPENSSL_NO_KRB5 */
2396         BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2397                       SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2398         return(1);
2399         }
2400
2401 #ifndef OPENSSL_NO_DH
2402 static DH *load_dh_param(const char *dhfile)
2403         {
2404         DH *ret=NULL;
2405         BIO *bio;
2406
2407         if ((bio=BIO_new_file(dhfile,"r")) == NULL)
2408                 goto err;
2409         ret=PEM_read_bio_DHparams(bio,NULL,NULL,NULL);
2410 err:
2411         if (bio != NULL) BIO_free(bio);
2412         return(ret);
2413         }
2414 #endif
2415 #ifndef OPENSSL_NO_KRB5
2416         char *client_princ;
2417 #endif
2418
2419 #if 0
2420 static int load_CA(SSL_CTX *ctx, char *file)
2421         {
2422         FILE *in;
2423         X509 *x=NULL;
2424
2425         if ((in=fopen(file,"r")) == NULL)
2426                 return(0);
2427
2428         for (;;)
2429                 {
2430                 if (PEM_read_X509(in,&x,NULL) == NULL)
2431                         break;
2432                 SSL_CTX_add_client_CA(ctx,x);
2433                 }
2434         if (x != NULL) X509_free(x);
2435         fclose(in);
2436         return(1);
2437         }
2438 #endif
2439
2440 static int www_body(char *hostname, int s, unsigned char *context)
2441         {
2442         char *buf=NULL;
2443         int ret=1;
2444         int i,j,k,dot;
2445         SSL *con;
2446         const SSL_CIPHER *c;
2447         BIO *io,*ssl_bio,*sbio;
2448 #ifndef OPENSSL_NO_KRB5
2449         KSSL_CTX *kctx;
2450 #endif
2451
2452         buf=OPENSSL_malloc(bufsize);
2453         if (buf == NULL) return(0);
2454         io=BIO_new(BIO_f_buffer());
2455         ssl_bio=BIO_new(BIO_f_ssl());
2456         if ((io == NULL) || (ssl_bio == NULL)) goto err;
2457
2458 #ifdef FIONBIO  
2459         if (s_nbio)
2460                 {
2461                 unsigned long sl=1;
2462
2463                 if (!s_quiet)
2464                         BIO_printf(bio_err,"turning on non blocking io\n");
2465                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
2466                         ERR_print_errors(bio_err);
2467                 }
2468 #endif
2469
2470         /* lets make the output buffer a reasonable size */
2471         if (!BIO_set_write_buffer_size(io,bufsize)) goto err;
2472
2473         if ((con=SSL_new(ctx)) == NULL) goto err;
2474 #ifndef OPENSSL_NO_TLSEXT
2475                 if (s_tlsextdebug)
2476                         {
2477                         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2478                         SSL_set_tlsext_debug_arg(con, bio_s_out);
2479                         }
2480 #endif
2481 #ifndef OPENSSL_NO_KRB5
2482         if ((kctx = kssl_ctx_new()) != NULL)
2483                 {
2484                 kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
2485                 kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
2486                 }
2487 #endif  /* OPENSSL_NO_KRB5 */
2488         if(context) SSL_set_session_id_context(con, context,
2489                                                strlen((char *)context));
2490
2491         sbio=BIO_new_socket(s,BIO_NOCLOSE);
2492         if (s_nbio_test)
2493                 {
2494                 BIO *test;
2495
2496                 test=BIO_new(BIO_f_nbio_test());
2497                 sbio=BIO_push(test,sbio);
2498                 }
2499         SSL_set_bio(con,sbio,sbio);
2500         SSL_set_accept_state(con);
2501
2502         /* SSL_set_fd(con,s); */
2503         BIO_set_ssl(ssl_bio,con,BIO_CLOSE);
2504         BIO_push(io,ssl_bio);
2505 #ifdef CHARSET_EBCDIC
2506         io = BIO_push(BIO_new(BIO_f_ebcdic_filter()),io);
2507 #endif
2508
2509         if (s_debug)
2510                 {
2511                 SSL_set_debug(con, 1);
2512                 BIO_set_callback(SSL_get_rbio(con),bio_dump_callback);
2513                 BIO_set_callback_arg(SSL_get_rbio(con),(char *)bio_s_out);
2514                 }
2515         if (s_msg)
2516                 {
2517                 SSL_set_msg_callback(con, msg_cb);
2518                 SSL_set_msg_callback_arg(con, bio_s_out);
2519                 }
2520
2521         for (;;)
2522                 {
2523                 if (hack)
2524                         {
2525                         i=SSL_accept(con);
2526
2527                         switch (SSL_get_error(con,i))
2528                                 {
2529                         case SSL_ERROR_NONE:
2530                                 break;
2531                         case SSL_ERROR_WANT_WRITE:
2532                         case SSL_ERROR_WANT_READ:
2533                         case SSL_ERROR_WANT_X509_LOOKUP:
2534                                 continue;
2535                         case SSL_ERROR_SYSCALL:
2536                         case SSL_ERROR_SSL:
2537                         case SSL_ERROR_ZERO_RETURN:
2538                                 ret=1;
2539                                 goto err;
2540                                 /* break; */
2541                                 }
2542
2543                         SSL_renegotiate(con);
2544                         SSL_write(con,NULL,0);
2545                         }
2546
2547                 i=BIO_gets(io,buf,bufsize-1);
2548                 if (i < 0) /* error */
2549                         {
2550                         if (!BIO_should_retry(io))
2551                                 {
2552                                 if (!s_quiet)
2553                                         ERR_print_errors(bio_err);
2554                                 goto err;
2555                                 }
2556                         else
2557                                 {
2558                                 BIO_printf(bio_s_out,"read R BLOCK\n");
2559 #if defined(OPENSSL_SYS_NETWARE)
2560             delay(1000);
2561 #elif !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__)
2562                                 sleep(1);
2563 #endif
2564                                 continue;
2565                                 }
2566                         }
2567                 else if (i == 0) /* end of input */
2568                         {
2569                         ret=1;
2570                         goto end;
2571                         }
2572
2573                 /* else we have data */
2574                 if (    ((www == 1) && (strncmp("GET ",buf,4) == 0)) ||
2575                         ((www == 2) && (strncmp("GET /stats ",buf,10) == 0)))
2576                         {
2577                         char *p;
2578                         X509 *peer;
2579                         STACK_OF(SSL_CIPHER) *sk;
2580                         static const char *space="                          ";
2581
2582                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2583                         BIO_puts(io,"<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2584                         BIO_puts(io,"<pre>\n");
2585 /*                      BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
2586                         BIO_puts(io,"\n");
2587                         for (i=0; i<local_argc; i++)
2588                                 {
2589                                 BIO_puts(io,local_argv[i]);
2590                                 BIO_write(io," ",1);
2591                                 }
2592                         BIO_puts(io,"\n");
2593
2594                         /* The following is evil and should not really
2595                          * be done */
2596                         BIO_printf(io,"Ciphers supported in s_server binary\n");
2597                         sk=SSL_get_ciphers(con);
2598                         j=sk_SSL_CIPHER_num(sk);
2599                         for (i=0; i<j; i++)
2600                                 {
2601                                 c=sk_SSL_CIPHER_value(sk,i);
2602                                 BIO_printf(io,"%-11s:%-25s",
2603                                         SSL_CIPHER_get_version(c),
2604                                         SSL_CIPHER_get_name(c));
2605                                 if ((((i+1)%2) == 0) && (i+1 != j))
2606                                         BIO_puts(io,"\n");
2607                                 }
2608                         BIO_puts(io,"\n");
2609                         p=SSL_get_shared_ciphers(con,buf,bufsize);
2610                         if (p != NULL)
2611                                 {
2612                                 BIO_printf(io,"---\nCiphers common between both SSL end points:\n");
2613                                 j=i=0;
2614                                 while (*p)
2615                                         {
2616                                         if (*p == ':')
2617                                                 {
2618                                                 BIO_write(io,space,26-j);
2619                                                 i++;
2620                                                 j=0;
2621                                                 BIO_write(io,((i%3)?" ":"\n"),1);
2622                                                 }
2623                                         else
2624                                                 {
2625                                                 BIO_write(io,p,1);
2626                                                 j++;
2627                                                 }
2628                                         p++;
2629                                         }
2630                                 BIO_puts(io,"\n");
2631                                 }
2632                         BIO_printf(io,(SSL_cache_hit(con)
2633                                 ?"---\nReused, "
2634                                 :"---\nNew, "));
2635                         c=SSL_get_current_cipher(con);
2636                         BIO_printf(io,"%s, Cipher is %s\n",
2637                                 SSL_CIPHER_get_version(c),
2638                                 SSL_CIPHER_get_name(c));
2639                         SSL_SESSION_print(io,SSL_get_session(con));
2640                         BIO_printf(io,"---\n");
2641                         print_stats(io,SSL_get_SSL_CTX(con));
2642                         BIO_printf(io,"---\n");
2643                         peer=SSL_get_peer_certificate(con);
2644                         if (peer != NULL)
2645                                 {
2646                                 BIO_printf(io,"Client certificate\n");
2647                                 X509_print(io,peer);
2648                                 PEM_write_bio_X509(io,peer);
2649                                 }
2650                         else
2651                                 BIO_puts(io,"no client certificate available\n");
2652                         BIO_puts(io,"</BODY></HTML>\r\n\r\n");
2653                         break;
2654                         }
2655                 else if ((www == 2 || www == 3)
2656                          && (strncmp("GET /",buf,5) == 0))
2657                         {
2658                         BIO *file;
2659                         char *p,*e;
2660                         static const char *text="HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2661
2662                         /* skip the '/' */
2663                         p= &(buf[5]);
2664
2665                         dot = 1;
2666                         for (e=p; *e != '\0'; e++)
2667                                 {
2668                                 if (e[0] == ' ')
2669                                         break;
2670
2671                                 switch (dot)
2672                                         {
2673                                 case 1:
2674                                         dot = (e[0] == '.') ? 2 : 0;
2675                                         break;
2676                                 case 2:
2677                                         dot = (e[0] == '.') ? 3 : 0;
2678                                         break;
2679                                 case 3:
2680                                         dot = (e[0] == '/') ? -1 : 0;
2681                                         break;
2682                                         }
2683                                 if (dot == 0)
2684                                         dot = (e[0] == '/') ? 1 : 0;
2685                                 }
2686                         dot = (dot == 3) || (dot == -1); /* filename contains ".." component */
2687
2688                         if (*e == '\0')
2689                                 {
2690                                 BIO_puts(io,text);
2691                                 BIO_printf(io,"'%s' is an invalid file name\r\n",p);
2692                                 break;
2693                                 }
2694                         *e='\0';
2695
2696                         if (dot)
2697                                 {
2698                                 BIO_puts(io,text);
2699                                 BIO_printf(io,"'%s' contains '..' reference\r\n",p);
2700                                 break;
2701                                 }
2702
2703                         if (*p == '/')
2704                                 {
2705                                 BIO_puts(io,text);
2706                                 BIO_printf(io,"'%s' is an invalid path\r\n",p);
2707                                 break;
2708                                 }
2709
2710 #if 0
2711                         /* append if a directory lookup */
2712                         if (e[-1] == '/')
2713                                 strcat(p,"index.html");
2714 #endif
2715
2716                         /* if a directory, do the index thang */
2717                         if (app_isdir(p)>0)
2718                                 {
2719 #if 0 /* must check buffer size */
2720                                 strcat(p,"/index.html");
2721 #else
2722                                 BIO_puts(io,text);
2723                                 BIO_printf(io,"'%s' is a directory\r\n",p);
2724                                 break;
2725 #endif
2726                                 }
2727
2728                         if ((file=BIO_new_file(p,"r")) == NULL)
2729                                 {
2730                                 BIO_puts(io,text);
2731                                 BIO_printf(io,"Error opening '%s'\r\n",p);
2732                                 ERR_print_errors(io);
2733                                 break;
2734                                 }
2735
2736                         if (!s_quiet)
2737                                 BIO_printf(bio_err,"FILE:%s\n",p);
2738
2739                         if (www == 2)
2740                                 {
2741                                 i=strlen(p);
2742                                 if (    ((i > 5) && (strcmp(&(p[i-5]),".html") == 0)) ||
2743                                         ((i > 4) && (strcmp(&(p[i-4]),".php") == 0)) ||
2744                                         ((i > 4) && (strcmp(&(p[i-4]),".htm") == 0)))
2745                                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2746                                 else
2747                                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2748                                 }
2749                         /* send the file */
2750                         for (;;)
2751                                 {
2752                                 i=BIO_read(file,buf,bufsize);
2753                                 if (i <= 0) break;
2754
2755 #ifdef RENEG
2756                                 total_bytes+=i;
2757                                 fprintf(stderr,"%d\n",i);
2758                                 if (total_bytes > 3*1024)
2759                                         {
2760                                         total_bytes=0;
2761                                         fprintf(stderr,"RENEGOTIATE\n");
2762                                         SSL_renegotiate(con);
2763                                         }
2764 #endif
2765
2766                                 for (j=0; j<i; )
2767                                         {
2768 #ifdef RENEG
2769 { static count=0; if (++count == 13) { SSL_renegotiate(con); } }
2770 #endif
2771                                         k=BIO_write(io,&(buf[j]),i-j);
2772                                         if (k <= 0)
2773                                                 {
2774                                                 if (!BIO_should_retry(io))
2775                                                         goto write_error;
2776                                                 else
2777                                                         {
2778                                                         BIO_printf(bio_s_out,"rwrite W BLOCK\n");
2779                                                         }
2780                                                 }
2781                                         else
2782                                                 {
2783                                                 j+=k;
2784                                                 }
2785                                         }
2786                                 }
2787 write_error:
2788                         BIO_free(file);
2789                         break;
2790                         }
2791                 }
2792
2793         for (;;)
2794                 {
2795                 i=(int)BIO_flush(io);
2796                 if (i <= 0)
2797                         {
2798                         if (!BIO_should_retry(io))
2799                                 break;
2800                         }
2801                 else
2802                         break;
2803                 }
2804 end:
2805 #if 1
2806         /* make sure we re-use sessions */
2807         SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
2808 #else
2809         /* This kills performance */
2810 /*      SSL_shutdown(con); A shutdown gets sent in the
2811  *      BIO_free_all(io) procession */
2812 #endif
2813
2814 err:
2815
2816         if (ret >= 0)
2817                 BIO_printf(bio_s_out,"ACCEPT\n");
2818
2819         if (buf != NULL) OPENSSL_free(buf);
2820         if (io != NULL) BIO_free_all(io);
2821 /*      if (ssl_bio != NULL) BIO_free(ssl_bio);*/
2822         return(ret);
2823         }
2824
2825 #ifndef OPENSSL_NO_RSA
2826 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
2827         {
2828         BIGNUM *bn = NULL;
2829         static RSA *rsa_tmp=NULL;
2830
2831         if (!rsa_tmp && ((bn = BN_new()) == NULL))
2832                 BIO_printf(bio_err,"Allocation error in generating RSA key\n");
2833         if (!rsa_tmp && bn)
2834                 {
2835                 if (!s_quiet)
2836                         {
2837                         BIO_printf(bio_err,"Generating temp (%d bit) RSA key...",keylength);
2838                         (void)BIO_flush(bio_err);
2839                         }
2840                 if(!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
2841                                 !RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL))
2842                         {
2843                         if(rsa_tmp) RSA_free(rsa_tmp);
2844                         rsa_tmp = NULL;
2845                         }
2846                 if (!s_quiet)
2847                         {
2848                         BIO_printf(bio_err,"\n");
2849                         (void)BIO_flush(bio_err);
2850                         }
2851                 BN_free(bn);
2852                 }
2853         return(rsa_tmp);
2854         }
2855 #endif
2856
2857 #define MAX_SESSION_ID_ATTEMPTS 10
2858 static int generate_session_id(const SSL *ssl, unsigned char *id,
2859                                 unsigned int *id_len)
2860         {
2861         unsigned int count = 0;
2862         do      {
2863                 RAND_pseudo_bytes(id, *id_len);
2864                 /* Prefix the session_id with the required prefix. NB: If our
2865                  * prefix is too long, clip it - but there will be worse effects
2866                  * anyway, eg. the server could only possibly create 1 session
2867                  * ID (ie. the prefix!) so all future session negotiations will
2868                  * fail due to conflicts. */
2869                 memcpy(id, session_id_prefix,
2870                         (strlen(session_id_prefix) < *id_len) ?
2871                         strlen(session_id_prefix) : *id_len);
2872                 }
2873         while(SSL_has_matching_session_id(ssl, id, *id_len) &&
2874                 (++count < MAX_SESSION_ID_ATTEMPTS));
2875         if(count >= MAX_SESSION_ID_ATTEMPTS)
2876                 return 0;
2877         return 1;
2878         }