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