New option to 'x509' -next_serial. This outputs the certificate
[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-2001 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 /* Until the key-gen callbacks are modified to use newer prototypes, we allow
118  * deprecated functions for openssl-internal code */
119 #ifdef OPENSSL_NO_DEPRECATED
120 #undef OPENSSL_NO_DEPRECATED
121 #endif
122
123 #include <assert.h>
124 #include <stdio.h>
125 #include <stdlib.h>
126 #include <string.h>
127
128 #include <sys/stat.h>
129 #include <openssl/e_os2.h>
130 #ifdef OPENSSL_NO_STDIO
131 #define APPS_WIN16
132 #endif
133
134 #if !defined(OPENSSL_SYS_NETWARE)  /* conflicts with winsock2 stuff on netware */
135 #include <sys/types.h>
136 #endif
137
138 /* With IPv6, it looks like Digital has mixed up the proper order of
139    recursive header file inclusion, resulting in the compiler complaining
140    that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
141    is needed to have fileno() declared correctly...  So let's define u_int */
142 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
143 #define __U_INT
144 typedef unsigned int u_int;
145 #endif
146
147 #include <openssl/lhash.h>
148 #include <openssl/bn.h>
149 #define USE_SOCKETS
150 #include "apps.h"
151 #include <openssl/err.h>
152 #include <openssl/pem.h>
153 #include <openssl/x509.h>
154 #include <openssl/ssl.h>
155 #include <openssl/rand.h>
156 #include "s_apps.h"
157
158 #ifdef OPENSSL_SYS_WINCE
159 /* Windows CE incorrectly defines fileno as returning void*, so to avoid problems below... */
160 #ifdef fileno
161 #undef fileno
162 #endif
163 #define fileno(a) (int)_fileno(a)
164 #endif
165
166 #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
167 /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
168 #undef FIONBIO
169 #endif
170
171 #ifndef OPENSSL_NO_RSA
172 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength);
173 #endif
174 static int sv_body(char *hostname, int s, unsigned char *context);
175 static int www_body(char *hostname, int s, unsigned char *context);
176 static void close_accept_socket(void );
177 static void sv_usage(void);
178 static int init_ssl_connection(SSL *s);
179 static void print_stats(BIO *bp,SSL_CTX *ctx);
180 static int generate_session_id(const SSL *ssl, unsigned char *id,
181                                 unsigned int *id_len);
182 #ifndef OPENSSL_NO_DH
183 static DH *load_dh_param(char *dhfile);
184 static DH *get_dh512(void);
185 #endif
186
187 #ifdef MONOLITH
188 static void s_server_init(void);
189 #endif
190
191 #ifndef S_ISDIR
192 # if defined(_S_IFMT) && defined(_S_IFDIR)
193 #  define S_ISDIR(a)    (((a) & _S_IFMT) == _S_IFDIR)
194 # else
195 #  define S_ISDIR(a)    (((a) & S_IFMT) == S_IFDIR)
196 # endif
197 #endif
198
199 #ifndef OPENSSL_NO_DH
200 static unsigned char dh512_p[]={
201         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
202         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
203         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
204         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
205         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
206         0x47,0x74,0xE8,0x33,
207         };
208 static unsigned char dh512_g[]={
209         0x02,
210         };
211
212 static DH *get_dh512(void)
213         {
214         DH *dh=NULL;
215
216         if ((dh=DH_new()) == NULL) return(NULL);
217         dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
218         dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
219         if ((dh->p == NULL) || (dh->g == NULL))
220                 return(NULL);
221         return(dh);
222         }
223 #endif
224
225
226 /* static int load_CA(SSL_CTX *ctx, char *file);*/
227
228 #undef BUFSIZZ
229 #define BUFSIZZ 16*1024
230 static int bufsize=BUFSIZZ;
231 static int accept_socket= -1;
232
233 #define TEST_CERT       "server.pem"
234 #undef PROG
235 #define PROG            s_server_main
236
237 extern int verify_depth;
238
239 static char *cipher=NULL;
240 static int s_server_verify=SSL_VERIFY_NONE;
241 static int s_server_session_id_context = 1; /* anything will do */
242 static char *s_cert_file=TEST_CERT,*s_key_file=NULL;
243 static char *s_dcert_file=NULL,*s_dkey_file=NULL;
244 #ifdef FIONBIO
245 static int s_nbio=0;
246 #endif
247 static int s_nbio_test=0;
248 int s_crlf=0;
249 static SSL_CTX *ctx=NULL;
250 static int www=0;
251
252 static BIO *bio_s_out=NULL;
253 static int s_debug=0;
254 static int s_msg=0;
255 static int s_quiet=0;
256
257 static int hack=0;
258 #ifndef OPENSSL_NO_ENGINE
259 static char *engine_id=NULL;
260 #endif
261 static const char *session_id_prefix=NULL;
262
263 #ifdef MONOLITH
264 static void s_server_init(void)
265         {
266         accept_socket=-1;
267         cipher=NULL;
268         s_server_verify=SSL_VERIFY_NONE;
269         s_dcert_file=NULL;
270         s_dkey_file=NULL;
271         s_cert_file=TEST_CERT;
272         s_key_file=NULL;
273 #ifdef FIONBIO
274         s_nbio=0;
275 #endif
276         s_nbio_test=0;
277         ctx=NULL;
278         www=0;
279
280         bio_s_out=NULL;
281         s_debug=0;
282         s_msg=0;
283         s_quiet=0;
284         hack=0;
285 #ifndef OPENSSL_NO_ENGINE
286         engine_id=NULL;
287 #endif
288         }
289 #endif
290
291 static void sv_usage(void)
292         {
293         BIO_printf(bio_err,"usage: s_server [args ...]\n");
294         BIO_printf(bio_err,"\n");
295         BIO_printf(bio_err," -accept arg   - port to accept on (default is %d)\n",PORT);
296         BIO_printf(bio_err," -context arg  - set session ID context\n");
297         BIO_printf(bio_err," -verify arg   - turn on peer certificate verification\n");
298         BIO_printf(bio_err," -Verify arg   - turn on peer certificate verification, must have a cert.\n");
299         BIO_printf(bio_err," -cert arg     - certificate file to use, PEM format assumed\n");
300         BIO_printf(bio_err,"                 (default is %s)\n",TEST_CERT);
301         BIO_printf(bio_err," -key arg      - Private Key file to use, PEM format assumed, in cert file if\n");
302         BIO_printf(bio_err,"                 not specified (default is %s)\n",TEST_CERT);
303         BIO_printf(bio_err," -dcert arg    - second certificate file to use (usually for DSA)\n");
304         BIO_printf(bio_err," -dkey arg     - second private key file to use (usually for DSA)\n");
305         BIO_printf(bio_err," -dhparam arg  - DH parameter file to use, in cert file if not specified\n");
306         BIO_printf(bio_err,"                 or a default set of parameters is used\n");
307 #ifndef OPENSSL_NO_ECDH
308         BIO_printf(bio_err," -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n" \
309                            "                 Use \"openssl ecparam -list_curves\" for all names\n" \
310                            "                 (default is sect163r2).\n");
311 #endif
312 #ifdef FIONBIO
313         BIO_printf(bio_err," -nbio         - Run with non-blocking IO\n");
314 #endif
315         BIO_printf(bio_err," -nbio_test    - test with the non-blocking test bio\n");
316         BIO_printf(bio_err," -crlf         - convert LF from terminal into CRLF\n");
317         BIO_printf(bio_err," -debug        - Print more output\n");
318         BIO_printf(bio_err," -msg          - Show protocol messages\n");
319         BIO_printf(bio_err," -state        - Print the SSL states\n");
320         BIO_printf(bio_err," -CApath arg   - PEM format directory of CA's\n");
321         BIO_printf(bio_err," -CAfile arg   - PEM format file of CA's\n");
322         BIO_printf(bio_err," -nocert       - Don't use any certificates (Anon-DH)\n");
323         BIO_printf(bio_err," -cipher arg   - play with 'openssl ciphers' to see what goes here\n");
324         BIO_printf(bio_err," -serverpref   - Use server's cipher preferences\n");
325         BIO_printf(bio_err," -quiet        - No server output\n");
326         BIO_printf(bio_err," -no_tmp_rsa   - Do not generate a tmp RSA key\n");
327         BIO_printf(bio_err," -ssl2         - Just talk SSLv2\n");
328         BIO_printf(bio_err," -ssl3         - Just talk SSLv3\n");
329         BIO_printf(bio_err," -tls1         - Just talk TLSv1\n");
330         BIO_printf(bio_err," -no_ssl2      - Just disable SSLv2\n");
331         BIO_printf(bio_err," -no_ssl3      - Just disable SSLv3\n");
332         BIO_printf(bio_err," -no_tls1      - Just disable TLSv1\n");
333 #ifndef OPENSSL_NO_DH
334         BIO_printf(bio_err," -no_dhe       - Disable ephemeral DH\n");
335 #endif
336 #ifndef OPENSSL_NO_ECDH
337         BIO_printf(bio_err," -no_ecdhe     - Disable ephemeral ECDH\n");
338 #endif
339         BIO_printf(bio_err," -bugs         - Turn on SSL bug compatibility\n");
340         BIO_printf(bio_err," -www          - Respond to a 'GET /' with a status page\n");
341         BIO_printf(bio_err," -WWW          - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
342         BIO_printf(bio_err," -HTTP         - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
343         BIO_printf(bio_err,"                 with the assumption it contains a complete HTTP response.\n");
344 #ifndef OPENSSL_NO_ENGINE
345         BIO_printf(bio_err," -engine id    - Initialise and use the specified engine\n");
346 #endif
347         BIO_printf(bio_err," -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n");
348         BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
349         }
350
351 static int local_argc=0;
352 static char **local_argv;
353
354 #ifdef CHARSET_EBCDIC
355 static int ebcdic_new(BIO *bi);
356 static int ebcdic_free(BIO *a);
357 static int ebcdic_read(BIO *b, char *out, int outl);
358 static int ebcdic_write(BIO *b, const char *in, int inl);
359 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
360 static int ebcdic_gets(BIO *bp, char *buf, int size);
361 static int ebcdic_puts(BIO *bp, const char *str);
362
363 #define BIO_TYPE_EBCDIC_FILTER  (18|0x0200)
364 static BIO_METHOD methods_ebcdic=
365         {
366         BIO_TYPE_EBCDIC_FILTER,
367         "EBCDIC/ASCII filter",
368         ebcdic_write,
369         ebcdic_read,
370         ebcdic_puts,
371         ebcdic_gets,
372         ebcdic_ctrl,
373         ebcdic_new,
374         ebcdic_free,
375         };
376
377 typedef struct
378 {
379         size_t  alloced;
380         char    buff[1];
381 } EBCDIC_OUTBUFF;
382
383 BIO_METHOD *BIO_f_ebcdic_filter()
384 {
385         return(&methods_ebcdic);
386 }
387
388 static int ebcdic_new(BIO *bi)
389 {
390         EBCDIC_OUTBUFF *wbuf;
391
392         wbuf = (EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + 1024);
393         wbuf->alloced = 1024;
394         wbuf->buff[0] = '\0';
395
396         bi->ptr=(char *)wbuf;
397         bi->init=1;
398         bi->flags=0;
399         return(1);
400 }
401
402 static int ebcdic_free(BIO *a)
403 {
404         if (a == NULL) return(0);
405         if (a->ptr != NULL)
406                 OPENSSL_free(a->ptr);
407         a->ptr=NULL;
408         a->init=0;
409         a->flags=0;
410         return(1);
411 }
412         
413 static int ebcdic_read(BIO *b, char *out, int outl)
414 {
415         int ret=0;
416
417         if (out == NULL || outl == 0) return(0);
418         if (b->next_bio == NULL) return(0);
419
420         ret=BIO_read(b->next_bio,out,outl);
421         if (ret > 0)
422                 ascii2ebcdic(out,out,ret);
423         return(ret);
424 }
425
426 static int ebcdic_write(BIO *b, const char *in, int inl)
427 {
428         EBCDIC_OUTBUFF *wbuf;
429         int ret=0;
430         int num;
431         unsigned char n;
432
433         if ((in == NULL) || (inl <= 0)) return(0);
434         if (b->next_bio == NULL) return(0);
435
436         wbuf=(EBCDIC_OUTBUFF *)b->ptr;
437
438         if (inl > (num = wbuf->alloced))
439         {
440                 num = num + num;  /* double the size */
441                 if (num < inl)
442                         num = inl;
443                 OPENSSL_free(wbuf);
444                 wbuf=(EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + num);
445
446                 wbuf->alloced = num;
447                 wbuf->buff[0] = '\0';
448
449                 b->ptr=(char *)wbuf;
450         }
451
452         ebcdic2ascii(wbuf->buff, in, inl);
453
454         ret=BIO_write(b->next_bio, wbuf->buff, inl);
455
456         return(ret);
457 }
458
459 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
460 {
461         long ret;
462
463         if (b->next_bio == NULL) return(0);
464         switch (cmd)
465         {
466         case BIO_CTRL_DUP:
467                 ret=0L;
468                 break;
469         default:
470                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
471                 break;
472         }
473         return(ret);
474 }
475
476 static int ebcdic_gets(BIO *bp, char *buf, int size)
477 {
478         int i, ret=0;
479         if (bp->next_bio == NULL) return(0);
480 /*      return(BIO_gets(bp->next_bio,buf,size));*/
481         for (i=0; i<size-1; ++i)
482         {
483                 ret = ebcdic_read(bp,&buf[i],1);
484                 if (ret <= 0)
485                         break;
486                 else if (buf[i] == '\n')
487                 {
488                         ++i;
489                         break;
490                 }
491         }
492         if (i < size)
493                 buf[i] = '\0';
494         return (ret < 0 && i == 0) ? ret : i;
495 }
496
497 static int ebcdic_puts(BIO *bp, const char *str)
498 {
499         if (bp->next_bio == NULL) return(0);
500         return ebcdic_write(bp, str, strlen(str));
501 }
502 #endif
503
504 int MAIN(int, char **);
505
506 int MAIN(int argc, char *argv[])
507         {
508         X509_STORE *store = NULL;
509         int vflags = 0;
510         short port=PORT;
511         char *CApath=NULL,*CAfile=NULL;
512         char *context = NULL;
513         char *dhfile = NULL;
514         char *named_curve = NULL;
515         int badop=0,bugs=0;
516         int ret=1;
517         int off=0;
518         int no_tmp_rsa=0,no_dhe=0,no_ecdhe=0,nocert=0;
519         int state=0;
520         SSL_METHOD *meth=NULL;
521 #ifndef OPENSSL_NO_ENGINE
522         ENGINE *e=NULL;
523 #endif
524         char *inrand=NULL;
525
526 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
527         meth=SSLv23_server_method();
528 #elif !defined(OPENSSL_NO_SSL3)
529         meth=SSLv3_server_method();
530 #elif !defined(OPENSSL_NO_SSL2)
531         meth=SSLv2_server_method();
532 #endif
533
534         local_argc=argc;
535         local_argv=argv;
536
537         apps_startup();
538 #ifdef MONOLITH
539         s_server_init();
540 #endif
541
542         if (bio_err == NULL)
543                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
544
545         if (!load_config(bio_err, NULL))
546                 goto end;
547
548         verify_depth=0;
549 #ifdef FIONBIO
550         s_nbio=0;
551 #endif
552         s_nbio_test=0;
553
554         argc--;
555         argv++;
556
557         while (argc >= 1)
558                 {
559                 if      ((strcmp(*argv,"-port") == 0) ||
560                          (strcmp(*argv,"-accept") == 0))
561                         {
562                         if (--argc < 1) goto bad;
563                         if (!extract_port(*(++argv),&port))
564                                 goto bad;
565                         }
566                 else if (strcmp(*argv,"-verify") == 0)
567                         {
568                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE;
569                         if (--argc < 1) goto bad;
570                         verify_depth=atoi(*(++argv));
571                         BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
572                         }
573                 else if (strcmp(*argv,"-Verify") == 0)
574                         {
575                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
576                                 SSL_VERIFY_CLIENT_ONCE;
577                         if (--argc < 1) goto bad;
578                         verify_depth=atoi(*(++argv));
579                         BIO_printf(bio_err,"verify depth is %d, must return a certificate\n",verify_depth);
580                         }
581                 else if (strcmp(*argv,"-context") == 0)
582                         {
583                         if (--argc < 1) goto bad;
584                         context= *(++argv);
585                         }
586                 else if (strcmp(*argv,"-cert") == 0)
587                         {
588                         if (--argc < 1) goto bad;
589                         s_cert_file= *(++argv);
590                         }
591                 else if (strcmp(*argv,"-key") == 0)
592                         {
593                         if (--argc < 1) goto bad;
594                         s_key_file= *(++argv);
595                         }
596                 else if (strcmp(*argv,"-dhparam") == 0)
597                         {
598                         if (--argc < 1) goto bad;
599                         dhfile = *(++argv);
600                         }
601 #ifndef OPENSSL_NO_ECDH         
602                 else if (strcmp(*argv,"-named_curve") == 0)
603                         {
604                         if (--argc < 1) goto bad;
605                         named_curve = *(++argv);
606                         }
607 #endif
608                 else if (strcmp(*argv,"-dcert") == 0)
609                         {
610                         if (--argc < 1) goto bad;
611                         s_dcert_file= *(++argv);
612                         }
613                 else if (strcmp(*argv,"-dkey") == 0)
614                         {
615                         if (--argc < 1) goto bad;
616                         s_dkey_file= *(++argv);
617                         }
618                 else if (strcmp(*argv,"-nocert") == 0)
619                         {
620                         nocert=1;
621                         }
622                 else if (strcmp(*argv,"-CApath") == 0)
623                         {
624                         if (--argc < 1) goto bad;
625                         CApath= *(++argv);
626                         }
627                 else if (strcmp(*argv,"-crl_check") == 0)
628                         {
629                         vflags |= X509_V_FLAG_CRL_CHECK;
630                         }
631                 else if (strcmp(*argv,"-crl_check") == 0)
632                         {
633                         vflags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
634                         }
635                 else if (strcmp(*argv,"-serverpref") == 0)
636                         { off|=SSL_OP_CIPHER_SERVER_PREFERENCE; }
637                 else if (strcmp(*argv,"-cipher") == 0)
638                         {
639                         if (--argc < 1) goto bad;
640                         cipher= *(++argv);
641                         }
642                 else if (strcmp(*argv,"-CAfile") == 0)
643                         {
644                         if (--argc < 1) goto bad;
645                         CAfile= *(++argv);
646                         }
647 #ifdef FIONBIO  
648                 else if (strcmp(*argv,"-nbio") == 0)
649                         { s_nbio=1; }
650 #endif
651                 else if (strcmp(*argv,"-nbio_test") == 0)
652                         {
653 #ifdef FIONBIO  
654                         s_nbio=1;
655 #endif
656                         s_nbio_test=1;
657                         }
658                 else if (strcmp(*argv,"-debug") == 0)
659                         { s_debug=1; }
660                 else if (strcmp(*argv,"-msg") == 0)
661                         { s_msg=1; }
662                 else if (strcmp(*argv,"-hack") == 0)
663                         { hack=1; }
664                 else if (strcmp(*argv,"-state") == 0)
665                         { state=1; }
666                 else if (strcmp(*argv,"-crlf") == 0)
667                         { s_crlf=1; }
668                 else if (strcmp(*argv,"-quiet") == 0)
669                         { s_quiet=1; }
670                 else if (strcmp(*argv,"-bugs") == 0)
671                         { bugs=1; }
672                 else if (strcmp(*argv,"-no_tmp_rsa") == 0)
673                         { no_tmp_rsa=1; }
674                 else if (strcmp(*argv,"-no_dhe") == 0)
675                         { no_dhe=1; }
676                 else if (strcmp(*argv,"-no_ecdhe") == 0)
677                         { no_ecdhe=1; }
678                 else if (strcmp(*argv,"-www") == 0)
679                         { www=1; }
680                 else if (strcmp(*argv,"-WWW") == 0)
681                         { www=2; }
682                 else if (strcmp(*argv,"-HTTP") == 0)
683                         { www=3; }
684                 else if (strcmp(*argv,"-no_ssl2") == 0)
685                         { off|=SSL_OP_NO_SSLv2; }
686                 else if (strcmp(*argv,"-no_ssl3") == 0)
687                         { off|=SSL_OP_NO_SSLv3; }
688                 else if (strcmp(*argv,"-no_tls1") == 0)
689                         { off|=SSL_OP_NO_TLSv1; }
690 #ifndef OPENSSL_NO_SSL2
691                 else if (strcmp(*argv,"-ssl2") == 0)
692                         { meth=SSLv2_server_method(); }
693 #endif
694 #ifndef OPENSSL_NO_SSL3
695                 else if (strcmp(*argv,"-ssl3") == 0)
696                         { meth=SSLv3_server_method(); }
697 #endif
698 #ifndef OPENSSL_NO_TLS1
699                 else if (strcmp(*argv,"-tls1") == 0)
700                         { meth=TLSv1_server_method(); }
701 #endif
702                 else if (strcmp(*argv, "-id_prefix") == 0)
703                         {
704                         if (--argc < 1) goto bad;
705                         session_id_prefix = *(++argv);
706                         }
707 #ifndef OPENSSL_NO_ENGINE
708                 else if (strcmp(*argv,"-engine") == 0)
709                         {
710                         if (--argc < 1) goto bad;
711                         engine_id= *(++argv);
712                         }
713 #endif
714                 else if (strcmp(*argv,"-rand") == 0)
715                         {
716                         if (--argc < 1) goto bad;
717                         inrand= *(++argv);
718                         }
719                 else
720                         {
721                         BIO_printf(bio_err,"unknown option %s\n",*argv);
722                         badop=1;
723                         break;
724                         }
725                 argc--;
726                 argv++;
727                 }
728         if (badop)
729                 {
730 bad:
731                 sv_usage();
732                 goto end;
733                 }
734
735         SSL_load_error_strings();
736         OpenSSL_add_ssl_algorithms();
737
738 #ifndef OPENSSL_NO_ENGINE
739         e = setup_engine(bio_err, engine_id, 1);
740 #endif
741
742         if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
743                 && !RAND_status())
744                 {
745                 BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
746                 }
747         if (inrand != NULL)
748                 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
749                         app_RAND_load_files(inrand));
750
751         if (bio_s_out == NULL)
752                 {
753                 if (s_quiet && !s_debug && !s_msg)
754                         {
755                         bio_s_out=BIO_new(BIO_s_null());
756                         }
757                 else
758                         {
759                         if (bio_s_out == NULL)
760                                 bio_s_out=BIO_new_fp(stdout,BIO_NOCLOSE);
761                         }
762                 }
763
764 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
765         if (nocert)
766 #endif
767                 {
768                 s_cert_file=NULL;
769                 s_key_file=NULL;
770                 s_dcert_file=NULL;
771                 s_dkey_file=NULL;
772                 }
773
774         ctx=SSL_CTX_new(meth);
775         if (ctx == NULL)
776                 {
777                 ERR_print_errors(bio_err);
778                 goto end;
779                 }
780         if (session_id_prefix)
781                 {
782                 if(strlen(session_id_prefix) >= 32)
783                         BIO_printf(bio_err,
784 "warning: id_prefix is too long, only one new session will be possible\n");
785                 else if(strlen(session_id_prefix) >= 16)
786                         BIO_printf(bio_err,
787 "warning: id_prefix is too long if you use SSLv2\n");
788                 if(!SSL_CTX_set_generate_session_id(ctx, generate_session_id))
789                         {
790                         BIO_printf(bio_err,"error setting 'id_prefix'\n");
791                         ERR_print_errors(bio_err);
792                         goto end;
793                         }
794                 BIO_printf(bio_err,"id_prefix '%s' set.\n", session_id_prefix);
795                 }
796         SSL_CTX_set_quiet_shutdown(ctx,1);
797         if (bugs) SSL_CTX_set_options(ctx,SSL_OP_ALL);
798         if (hack) SSL_CTX_set_options(ctx,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
799         SSL_CTX_set_options(ctx,off);
800
801         if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
802
803         SSL_CTX_sess_set_cache_size(ctx,128);
804
805 #if 0
806         if (cipher == NULL) cipher=getenv("SSL_CIPHER");
807 #endif
808
809 #if 0
810         if (s_cert_file == NULL)
811                 {
812                 BIO_printf(bio_err,"You must specify a certificate file for the server to use\n");
813                 goto end;
814                 }
815 #endif
816
817         if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
818                 (!SSL_CTX_set_default_verify_paths(ctx)))
819                 {
820                 /* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
821                 ERR_print_errors(bio_err);
822                 /* goto end; */
823                 }
824         store = SSL_CTX_get_cert_store(ctx);
825         X509_STORE_set_flags(store, vflags);
826
827 #ifndef OPENSSL_NO_DH
828         if (!no_dhe)
829                 {
830                 DH *dh=NULL;
831
832                 if (dhfile)
833                         dh = load_dh_param(dhfile);
834                 else if (s_cert_file)
835                         dh = load_dh_param(s_cert_file);
836
837                 if (dh != NULL)
838                         {
839                         BIO_printf(bio_s_out,"Setting temp DH parameters\n");
840                         }
841                 else
842                         {
843                         BIO_printf(bio_s_out,"Using default temp DH parameters\n");
844                         dh=get_dh512();
845                         }
846                 (void)BIO_flush(bio_s_out);
847
848                 SSL_CTX_set_tmp_dh(ctx,dh);
849                 DH_free(dh);
850                 }
851 #endif
852
853 #ifndef OPENSSL_NO_ECDH
854         if (!no_ecdhe)
855                 {
856                 EC_KEY *ecdh=NULL;
857
858                 ecdh = EC_KEY_new();
859                 if (ecdh == NULL)
860                         {
861                         BIO_printf(bio_err,"Could not create ECDH struct.\n");
862                         goto end;
863                         }
864
865                 if (named_curve)
866                         {
867                         int nid = OBJ_sn2nid(named_curve);
868
869                         if (nid == 0)
870                                 {
871                                 BIO_printf(bio_err, "unknown curve name (%s)\n", 
872                                         named_curve);
873                                 goto end;
874                                 }
875
876                         ecdh->group = EC_GROUP_new_by_nid(nid);
877                         if (ecdh->group == NULL)
878                                 {
879                                 BIO_printf(bio_err, "unable to create curve (%s)\n", 
880                                         named_curve);
881                                 goto end;
882                                 }
883                         }
884
885                 if (ecdh->group != NULL)
886                         {
887                         BIO_printf(bio_s_out,"Setting temp ECDH parameters\n");
888                         }
889                 else
890                         {
891                         BIO_printf(bio_s_out,"Using default temp ECDH parameters\n");
892                         ecdh->group=EC_GROUP_new_by_nid(NID_sect163r2);
893                         if (ecdh->group == NULL) 
894                                 {
895                                 BIO_printf(bio_err, "unable to create curve (sect163r2)\n");
896                                 goto end;
897                                 }
898                         }
899                 (void)BIO_flush(bio_s_out);
900
901                 SSL_CTX_set_tmp_ecdh(ctx,ecdh);
902                 EC_KEY_free(ecdh);
903                 }
904 #endif
905         
906         if (!set_cert_stuff(ctx,s_cert_file,s_key_file))
907                 goto end;
908         if (s_dcert_file != NULL)
909                 {
910                 if (!set_cert_stuff(ctx,s_dcert_file,s_dkey_file))
911                         goto end;
912                 }
913
914 #ifndef OPENSSL_NO_RSA
915 #if 1
916         if (!no_tmp_rsa)
917                 SSL_CTX_set_tmp_rsa_callback(ctx,tmp_rsa_cb);
918 #else
919         if (!no_tmp_rsa && SSL_CTX_need_tmp_RSA(ctx))
920                 {
921                 RSA *rsa;
922
923                 BIO_printf(bio_s_out,"Generating temp (512 bit) RSA key...");
924                 BIO_flush(bio_s_out);
925
926                 rsa=RSA_generate_key(512,RSA_F4,NULL);
927
928                 if (!SSL_CTX_set_tmp_rsa(ctx,rsa))
929                         {
930                         ERR_print_errors(bio_err);
931                         goto end;
932                         }
933                 RSA_free(rsa);
934                 BIO_printf(bio_s_out,"\n");
935                 }
936 #endif
937 #endif
938
939         if (cipher != NULL)
940                 if(!SSL_CTX_set_cipher_list(ctx,cipher)) {
941                 BIO_printf(bio_err,"error setting cipher list\n");
942                 ERR_print_errors(bio_err);
943                 goto end;
944         }
945         SSL_CTX_set_verify(ctx,s_server_verify,verify_callback);
946         SSL_CTX_set_session_id_context(ctx,(void*)&s_server_session_id_context,
947                 sizeof s_server_session_id_context);
948
949         if (CAfile != NULL)
950             SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file(CAfile));
951
952         BIO_printf(bio_s_out,"ACCEPT\n");
953         if (www)
954                 do_server(port,&accept_socket,www_body, context);
955         else
956                 do_server(port,&accept_socket,sv_body, context);
957         print_stats(bio_s_out,ctx);
958         ret=0;
959 end:
960         if (ctx != NULL) SSL_CTX_free(ctx);
961         if (bio_s_out != NULL)
962                 {
963                 BIO_free(bio_s_out);
964                 bio_s_out=NULL;
965                 }
966         apps_shutdown();
967         OPENSSL_EXIT(ret);
968         }
969
970 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
971         {
972         BIO_printf(bio,"%4ld items in the session cache\n",
973                 SSL_CTX_sess_number(ssl_ctx));
974         BIO_printf(bio,"%4ld client connects (SSL_connect())\n",
975                 SSL_CTX_sess_connect(ssl_ctx));
976         BIO_printf(bio,"%4ld client renegotiates (SSL_connect())\n",
977                 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
978         BIO_printf(bio,"%4ld client connects that finished\n",
979                 SSL_CTX_sess_connect_good(ssl_ctx));
980         BIO_printf(bio,"%4ld server accepts (SSL_accept())\n",
981                 SSL_CTX_sess_accept(ssl_ctx));
982         BIO_printf(bio,"%4ld server renegotiates (SSL_accept())\n",
983                 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
984         BIO_printf(bio,"%4ld server accepts that finished\n",
985                 SSL_CTX_sess_accept_good(ssl_ctx));
986         BIO_printf(bio,"%4ld session cache hits\n",SSL_CTX_sess_hits(ssl_ctx));
987         BIO_printf(bio,"%4ld session cache misses\n",SSL_CTX_sess_misses(ssl_ctx));
988         BIO_printf(bio,"%4ld session cache timeouts\n",SSL_CTX_sess_timeouts(ssl_ctx));
989         BIO_printf(bio,"%4ld callback cache hits\n",SSL_CTX_sess_cb_hits(ssl_ctx));
990         BIO_printf(bio,"%4ld cache full overflows (%ld allowed)\n",
991                 SSL_CTX_sess_cache_full(ssl_ctx),
992                 SSL_CTX_sess_get_cache_size(ssl_ctx));
993         }
994
995 static int sv_body(char *hostname, int s, unsigned char *context)
996         {
997         char *buf=NULL;
998         fd_set readfds;
999         int ret=1,width;
1000         int k,i;
1001         unsigned long l;
1002         SSL *con=NULL;
1003         BIO *sbio;
1004 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
1005         struct timeval tv;
1006 #endif
1007
1008         if ((buf=OPENSSL_malloc(bufsize)) == NULL)
1009                 {
1010                 BIO_printf(bio_err,"out of memory\n");
1011                 goto err;
1012                 }
1013 #ifdef FIONBIO  
1014         if (s_nbio)
1015                 {
1016                 unsigned long sl=1;
1017
1018                 if (!s_quiet)
1019                         BIO_printf(bio_err,"turning on non blocking io\n");
1020                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
1021                         ERR_print_errors(bio_err);
1022                 }
1023 #endif
1024
1025         if (con == NULL) {
1026                 con=SSL_new(ctx);
1027 #ifndef OPENSSL_NO_KRB5
1028                 if ((con->kssl_ctx = kssl_ctx_new()) != NULL)
1029                         {
1030                         kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVICE,
1031                                                                 KRB5SVC);
1032                         kssl_ctx_setstring(con->kssl_ctx, KSSL_KEYTAB,
1033                                                                 KRB5KEYTAB);
1034                         }
1035 #endif  /* OPENSSL_NO_KRB5 */
1036                 if(context)
1037                       SSL_set_session_id_context(con, context,
1038                                                  strlen((char *)context));
1039         }
1040         SSL_clear(con);
1041
1042         sbio=BIO_new_socket(s,BIO_NOCLOSE);
1043         if (s_nbio_test)
1044                 {
1045                 BIO *test;
1046
1047                 test=BIO_new(BIO_f_nbio_test());
1048                 sbio=BIO_push(test,sbio);
1049                 }
1050         SSL_set_bio(con,sbio,sbio);
1051         SSL_set_accept_state(con);
1052         /* SSL_set_fd(con,s); */
1053
1054         if (s_debug)
1055                 {
1056                 con->debug=1;
1057                 BIO_set_callback(SSL_get_rbio(con),bio_dump_cb);
1058                 BIO_set_callback_arg(SSL_get_rbio(con),bio_s_out);
1059                 }
1060         if (s_msg)
1061                 {
1062                 SSL_set_msg_callback(con, msg_cb);
1063                 SSL_set_msg_callback_arg(con, bio_s_out);
1064                 }
1065
1066         width=s+1;
1067         for (;;)
1068                 {
1069                 int read_from_terminal;
1070                 int read_from_sslcon;
1071
1072                 read_from_terminal = 0;
1073                 read_from_sslcon = SSL_pending(con);
1074
1075                 if (!read_from_sslcon)
1076                         {
1077                         FD_ZERO(&readfds);
1078 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE)
1079                         FD_SET(fileno(stdin),&readfds);
1080 #endif
1081                         FD_SET(s,&readfds);
1082                         /* Note: under VMS with SOCKETSHR the second parameter is
1083                          * currently of type (int *) whereas under other systems
1084                          * it is (void *) if you don't have a cast it will choke
1085                          * the compiler: if you do have a cast then you can either
1086                          * go for (int *) or (void *).
1087                          */
1088 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
1089                         /* Under DOS (non-djgpp) and Windows we can't select on stdin: only
1090                          * on sockets. As a workaround we timeout the select every
1091                          * second and check for any keypress. In a proper Windows
1092                          * application we wouldn't do this because it is inefficient.
1093                          */
1094                         tv.tv_sec = 1;
1095                         tv.tv_usec = 0;
1096                         i=select(width,(void *)&readfds,NULL,NULL,&tv);
1097                         if((i < 0) || (!i && !_kbhit() ) )continue;
1098                         if(_kbhit())
1099                                 read_from_terminal = 1;
1100 #else
1101                         i=select(width,(void *)&readfds,NULL,NULL,NULL);
1102                         if (i <= 0) continue;
1103                         if (FD_ISSET(fileno(stdin),&readfds))
1104                                 read_from_terminal = 1;
1105 #endif
1106                         if (FD_ISSET(s,&readfds))
1107                                 read_from_sslcon = 1;
1108                         }
1109                 if (read_from_terminal)
1110                         {
1111                         if (s_crlf)
1112                                 {
1113                                 int j, lf_num;
1114
1115                                 i=read(fileno(stdin), buf, bufsize/2);
1116                                 lf_num = 0;
1117                                 /* both loops are skipped when i <= 0 */
1118                                 for (j = 0; j < i; j++)
1119                                         if (buf[j] == '\n')
1120                                                 lf_num++;
1121                                 for (j = i-1; j >= 0; j--)
1122                                         {
1123                                         buf[j+lf_num] = buf[j];
1124                                         if (buf[j] == '\n')
1125                                                 {
1126                                                 lf_num--;
1127                                                 i++;
1128                                                 buf[j+lf_num] = '\r';
1129                                                 }
1130                                         }
1131                                 assert(lf_num == 0);
1132                                 }
1133                         else
1134                                 i=read(fileno(stdin),buf,bufsize);
1135                         if (!s_quiet)
1136                                 {
1137                                 if ((i <= 0) || (buf[0] == 'Q'))
1138                                         {
1139                                         BIO_printf(bio_s_out,"DONE\n");
1140                                         SHUTDOWN(s);
1141                                         close_accept_socket();
1142                                         ret= -11;
1143                                         goto err;
1144                                         }
1145                                 if ((i <= 0) || (buf[0] == 'q'))
1146                                         {
1147                                         BIO_printf(bio_s_out,"DONE\n");
1148                                         SHUTDOWN(s);
1149         /*                              close_accept_socket();
1150                                         ret= -11;*/
1151                                         goto err;
1152                                         }
1153                                 if ((buf[0] == 'r') && 
1154                                         ((buf[1] == '\n') || (buf[1] == '\r')))
1155                                         {
1156                                         SSL_renegotiate(con);
1157                                         i=SSL_do_handshake(con);
1158                                         printf("SSL_do_handshake -> %d\n",i);
1159                                         i=0; /*13; */
1160                                         continue;
1161                                         /* strcpy(buf,"server side RE-NEGOTIATE\n"); */
1162                                         }
1163                                 if ((buf[0] == 'R') &&
1164                                         ((buf[1] == '\n') || (buf[1] == '\r')))
1165                                         {
1166                                         SSL_set_verify(con,
1167                                                 SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,NULL);
1168                                         SSL_renegotiate(con);
1169                                         i=SSL_do_handshake(con);
1170                                         printf("SSL_do_handshake -> %d\n",i);
1171                                         i=0; /* 13; */
1172                                         continue;
1173                                         /* strcpy(buf,"server side RE-NEGOTIATE asking for client cert\n"); */
1174                                         }
1175                                 if (buf[0] == 'P')
1176                                         {
1177                                         static char *str="Lets print some clear text\n";
1178                                         BIO_write(SSL_get_wbio(con),str,strlen(str));
1179                                         }
1180                                 if (buf[0] == 'S')
1181                                         {
1182                                         print_stats(bio_s_out,SSL_get_SSL_CTX(con));
1183                                         }
1184                                 }
1185 #ifdef CHARSET_EBCDIC
1186                         ebcdic2ascii(buf,buf,i);
1187 #endif
1188                         l=k=0;
1189                         for (;;)
1190                                 {
1191                                 /* should do a select for the write */
1192 #ifdef RENEG
1193 { static count=0; if (++count == 100) { count=0; SSL_renegotiate(con); } }
1194 #endif
1195                                 k=SSL_write(con,&(buf[l]),(unsigned int)i);
1196                                 switch (SSL_get_error(con,k))
1197                                         {
1198                                 case SSL_ERROR_NONE:
1199                                         break;
1200                                 case SSL_ERROR_WANT_WRITE:
1201                                 case SSL_ERROR_WANT_READ:
1202                                 case SSL_ERROR_WANT_X509_LOOKUP:
1203                                         BIO_printf(bio_s_out,"Write BLOCK\n");
1204                                         break;
1205                                 case SSL_ERROR_SYSCALL:
1206                                 case SSL_ERROR_SSL:
1207                                         BIO_printf(bio_s_out,"ERROR\n");
1208                                         ERR_print_errors(bio_err);
1209                                         ret=1;
1210                                         goto err;
1211                                         /* break; */
1212                                 case SSL_ERROR_ZERO_RETURN:
1213                                         BIO_printf(bio_s_out,"DONE\n");
1214                                         ret=1;
1215                                         goto err;
1216                                         }
1217                                 l+=k;
1218                                 i-=k;
1219                                 if (i <= 0) break;
1220                                 }
1221                         }
1222                 if (read_from_sslcon)
1223                         {
1224                         if (!SSL_is_init_finished(con))
1225                                 {
1226                                 i=init_ssl_connection(con);
1227                                 
1228                                 if (i < 0)
1229                                         {
1230                                         ret=0;
1231                                         goto err;
1232                                         }
1233                                 else if (i == 0)
1234                                         {
1235                                         ret=1;
1236                                         goto err;
1237                                         }
1238                                 }
1239                         else
1240                                 {
1241 again:  
1242                                 i=SSL_read(con,(char *)buf,bufsize);
1243                                 switch (SSL_get_error(con,i))
1244                                         {
1245                                 case SSL_ERROR_NONE:
1246 #ifdef CHARSET_EBCDIC
1247                                         ascii2ebcdic(buf,buf,i);
1248 #endif
1249                                         write(fileno(stdout),buf,
1250                                                 (unsigned int)i);
1251                                         if (SSL_pending(con)) goto again;
1252                                         break;
1253                                 case SSL_ERROR_WANT_WRITE:
1254                                 case SSL_ERROR_WANT_READ:
1255                                 case SSL_ERROR_WANT_X509_LOOKUP:
1256                                         BIO_printf(bio_s_out,"Read BLOCK\n");
1257                                         break;
1258                                 case SSL_ERROR_SYSCALL:
1259                                 case SSL_ERROR_SSL:
1260                                         BIO_printf(bio_s_out,"ERROR\n");
1261                                         ERR_print_errors(bio_err);
1262                                         ret=1;
1263                                         goto err;
1264                                 case SSL_ERROR_ZERO_RETURN:
1265                                         BIO_printf(bio_s_out,"DONE\n");
1266                                         ret=1;
1267                                         goto err;
1268                                         }
1269                                 }
1270                         }
1271                 }
1272 err:
1273         BIO_printf(bio_s_out,"shutting down SSL\n");
1274 #if 1
1275         SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1276 #else
1277         SSL_shutdown(con);
1278 #endif
1279         if (con != NULL) SSL_free(con);
1280         BIO_printf(bio_s_out,"CONNECTION CLOSED\n");
1281         if (buf != NULL)
1282                 {
1283                 OPENSSL_cleanse(buf,bufsize);
1284                 OPENSSL_free(buf);
1285                 }
1286         if (ret >= 0)
1287                 BIO_printf(bio_s_out,"ACCEPT\n");
1288         return(ret);
1289         }
1290
1291 static void close_accept_socket(void)
1292         {
1293         BIO_printf(bio_err,"shutdown accept socket\n");
1294         if (accept_socket >= 0)
1295                 {
1296                 SHUTDOWN2(accept_socket);
1297                 }
1298         }
1299
1300 static int init_ssl_connection(SSL *con)
1301         {
1302         int i;
1303         const char *str;
1304         X509 *peer;
1305         long verify_error;
1306         MS_STATIC char buf[BUFSIZ];
1307
1308         if ((i=SSL_accept(con)) <= 0)
1309                 {
1310                 if (BIO_sock_should_retry(i))
1311                         {
1312                         BIO_printf(bio_s_out,"DELAY\n");
1313                         return(1);
1314                         }
1315
1316                 BIO_printf(bio_err,"ERROR\n");
1317                 verify_error=SSL_get_verify_result(con);
1318                 if (verify_error != X509_V_OK)
1319                         {
1320                         BIO_printf(bio_err,"verify error:%s\n",
1321                                 X509_verify_cert_error_string(verify_error));
1322                         }
1323                 else
1324                         ERR_print_errors(bio_err);
1325                 return(0);
1326                 }
1327
1328         PEM_write_bio_SSL_SESSION(bio_s_out,SSL_get_session(con));
1329
1330         peer=SSL_get_peer_certificate(con);
1331         if (peer != NULL)
1332                 {
1333                 BIO_printf(bio_s_out,"Client certificate\n");
1334                 PEM_write_bio_X509(bio_s_out,peer);
1335                 X509_NAME_oneline(X509_get_subject_name(peer),buf,sizeof buf);
1336                 BIO_printf(bio_s_out,"subject=%s\n",buf);
1337                 X509_NAME_oneline(X509_get_issuer_name(peer),buf,sizeof buf);
1338                 BIO_printf(bio_s_out,"issuer=%s\n",buf);
1339                 X509_free(peer);
1340                 }
1341
1342         if (SSL_get_shared_ciphers(con,buf,sizeof buf) != NULL)
1343                 BIO_printf(bio_s_out,"Shared ciphers:%s\n",buf);
1344         str=SSL_CIPHER_get_name(SSL_get_current_cipher(con));
1345         BIO_printf(bio_s_out,"CIPHER is %s\n",(str != NULL)?str:"(NONE)");
1346         if (con->hit) BIO_printf(bio_s_out,"Reused session-id\n");
1347         if (SSL_ctrl(con,SSL_CTRL_GET_FLAGS,0,NULL) &
1348                 TLS1_FLAGS_TLS_PADDING_BUG)
1349                 BIO_printf(bio_s_out,"Peer has incorrect TLSv1 block padding\n");
1350 #ifndef OPENSSL_NO_KRB5
1351         if (con->kssl_ctx->client_princ != NULL)
1352                 {
1353                 BIO_printf(bio_s_out,"Kerberos peer principal is %s\n",
1354                         con->kssl_ctx->client_princ);
1355                 }
1356 #endif /* OPENSSL_NO_KRB5 */
1357         return(1);
1358         }
1359
1360 #ifndef OPENSSL_NO_DH
1361 static DH *load_dh_param(char *dhfile)
1362         {
1363         DH *ret=NULL;
1364         BIO *bio;
1365
1366         if ((bio=BIO_new_file(dhfile,"r")) == NULL)
1367                 goto err;
1368         ret=PEM_read_bio_DHparams(bio,NULL,NULL,NULL);
1369 err:
1370         if (bio != NULL) BIO_free(bio);
1371         return(ret);
1372         }
1373 #endif
1374
1375 #if 0
1376 static int load_CA(SSL_CTX *ctx, char *file)
1377         {
1378         FILE *in;
1379         X509 *x=NULL;
1380
1381         if ((in=fopen(file,"r")) == NULL)
1382                 return(0);
1383
1384         for (;;)
1385                 {
1386                 if (PEM_read_X509(in,&x,NULL) == NULL)
1387                         break;
1388                 SSL_CTX_add_client_CA(ctx,x);
1389                 }
1390         if (x != NULL) X509_free(x);
1391         fclose(in);
1392         return(1);
1393         }
1394 #endif
1395
1396 static int www_body(char *hostname, int s, unsigned char *context)
1397         {
1398         char *buf=NULL;
1399         int ret=1;
1400         int i,j,k,blank,dot;
1401         struct stat st_buf;
1402         SSL *con;
1403         SSL_CIPHER *c;
1404         BIO *io,*ssl_bio,*sbio;
1405         long total_bytes;
1406
1407         buf=OPENSSL_malloc(bufsize);
1408         if (buf == NULL) return(0);
1409         io=BIO_new(BIO_f_buffer());
1410         ssl_bio=BIO_new(BIO_f_ssl());
1411         if ((io == NULL) || (ssl_bio == NULL)) goto err;
1412
1413 #ifdef FIONBIO  
1414         if (s_nbio)
1415                 {
1416                 unsigned long sl=1;
1417
1418                 if (!s_quiet)
1419                         BIO_printf(bio_err,"turning on non blocking io\n");
1420                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
1421                         ERR_print_errors(bio_err);
1422                 }
1423 #endif
1424
1425         /* lets make the output buffer a reasonable size */
1426         if (!BIO_set_write_buffer_size(io,bufsize)) goto err;
1427
1428         if ((con=SSL_new(ctx)) == NULL) goto err;
1429 #ifndef OPENSSL_NO_KRB5
1430         if ((con->kssl_ctx = kssl_ctx_new()) != NULL)
1431                 {
1432                 kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVICE, KRB5SVC);
1433                 kssl_ctx_setstring(con->kssl_ctx, KSSL_KEYTAB, KRB5KEYTAB);
1434                 }
1435 #endif  /* OPENSSL_NO_KRB5 */
1436         if(context) SSL_set_session_id_context(con, context,
1437                                                strlen((char *)context));
1438
1439         sbio=BIO_new_socket(s,BIO_NOCLOSE);
1440         if (s_nbio_test)
1441                 {
1442                 BIO *test;
1443
1444                 test=BIO_new(BIO_f_nbio_test());
1445                 sbio=BIO_push(test,sbio);
1446                 }
1447         SSL_set_bio(con,sbio,sbio);
1448         SSL_set_accept_state(con);
1449
1450         /* SSL_set_fd(con,s); */
1451         BIO_set_ssl(ssl_bio,con,BIO_CLOSE);
1452         BIO_push(io,ssl_bio);
1453 #ifdef CHARSET_EBCDIC
1454         io = BIO_push(BIO_new(BIO_f_ebcdic_filter()),io);
1455 #endif
1456
1457         if (s_debug)
1458                 {
1459                 con->debug=1;
1460                 BIO_set_callback(SSL_get_rbio(con),bio_dump_cb);
1461                 BIO_set_callback_arg(SSL_get_rbio(con),bio_s_out);
1462                 }
1463         if (s_msg)
1464                 {
1465                 SSL_set_msg_callback(con, msg_cb);
1466                 SSL_set_msg_callback_arg(con, bio_s_out);
1467                 }
1468
1469         blank=0;
1470         for (;;)
1471                 {
1472                 if (hack)
1473                         {
1474                         i=SSL_accept(con);
1475
1476                         switch (SSL_get_error(con,i))
1477                                 {
1478                         case SSL_ERROR_NONE:
1479                                 break;
1480                         case SSL_ERROR_WANT_WRITE:
1481                         case SSL_ERROR_WANT_READ:
1482                         case SSL_ERROR_WANT_X509_LOOKUP:
1483                                 continue;
1484                         case SSL_ERROR_SYSCALL:
1485                         case SSL_ERROR_SSL:
1486                         case SSL_ERROR_ZERO_RETURN:
1487                                 ret=1;
1488                                 goto err;
1489                                 /* break; */
1490                                 }
1491
1492                         SSL_renegotiate(con);
1493                         SSL_write(con,NULL,0);
1494                         }
1495
1496                 i=BIO_gets(io,buf,bufsize-1);
1497                 if (i < 0) /* error */
1498                         {
1499                         if (!BIO_should_retry(io))
1500                                 {
1501                                 if (!s_quiet)
1502                                         ERR_print_errors(bio_err);
1503                                 goto err;
1504                                 }
1505                         else
1506                                 {
1507                                 BIO_printf(bio_s_out,"read R BLOCK\n");
1508 #if defined(OPENSSL_SYS_NETWARE)
1509             delay(1000);
1510 #elif !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__)
1511                                 sleep(1);
1512 #endif
1513                                 continue;
1514                                 }
1515                         }
1516                 else if (i == 0) /* end of input */
1517                         {
1518                         ret=1;
1519                         goto end;
1520                         }
1521
1522                 /* else we have data */
1523                 if (    ((www == 1) && (strncmp("GET ",buf,4) == 0)) ||
1524                         ((www == 2) && (strncmp("GET /stats ",buf,10) == 0)))
1525                         {
1526                         char *p;
1527                         X509 *peer;
1528                         STACK_OF(SSL_CIPHER) *sk;
1529                         static char *space="                          ";
1530
1531                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
1532                         BIO_puts(io,"<HTML><BODY BGCOLOR=\"#ffffff\">\n");
1533                         BIO_puts(io,"<pre>\n");
1534 /*                      BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
1535                         BIO_puts(io,"\n");
1536                         for (i=0; i<local_argc; i++)
1537                                 {
1538                                 BIO_puts(io,local_argv[i]);
1539                                 BIO_write(io," ",1);
1540                                 }
1541                         BIO_puts(io,"\n");
1542
1543                         /* The following is evil and should not really
1544                          * be done */
1545                         BIO_printf(io,"Ciphers supported in s_server binary\n");
1546                         sk=SSL_get_ciphers(con);
1547                         j=sk_SSL_CIPHER_num(sk);
1548                         for (i=0; i<j; i++)
1549                                 {
1550                                 c=sk_SSL_CIPHER_value(sk,i);
1551                                 BIO_printf(io,"%-11s:%-25s",
1552                                         SSL_CIPHER_get_version(c),
1553                                         SSL_CIPHER_get_name(c));
1554                                 if ((((i+1)%2) == 0) && (i+1 != j))
1555                                         BIO_puts(io,"\n");
1556                                 }
1557                         BIO_puts(io,"\n");
1558                         p=SSL_get_shared_ciphers(con,buf,bufsize);
1559                         if (p != NULL)
1560                                 {
1561                                 BIO_printf(io,"---\nCiphers common between both SSL end points:\n");
1562                                 j=i=0;
1563                                 while (*p)
1564                                         {
1565                                         if (*p == ':')
1566                                                 {
1567                                                 BIO_write(io,space,26-j);
1568                                                 i++;
1569                                                 j=0;
1570                                                 BIO_write(io,((i%3)?" ":"\n"),1);
1571                                                 }
1572                                         else
1573                                                 {
1574                                                 BIO_write(io,p,1);
1575                                                 j++;
1576                                                 }
1577                                         p++;
1578                                         }
1579                                 BIO_puts(io,"\n");
1580                                 }
1581                         BIO_printf(io,((con->hit)
1582                                 ?"---\nReused, "
1583                                 :"---\nNew, "));
1584                         c=SSL_get_current_cipher(con);
1585                         BIO_printf(io,"%s, Cipher is %s\n",
1586                                 SSL_CIPHER_get_version(c),
1587                                 SSL_CIPHER_get_name(c));
1588                         SSL_SESSION_print(io,SSL_get_session(con));
1589                         BIO_printf(io,"---\n");
1590                         print_stats(io,SSL_get_SSL_CTX(con));
1591                         BIO_printf(io,"---\n");
1592                         peer=SSL_get_peer_certificate(con);
1593                         if (peer != NULL)
1594                                 {
1595                                 BIO_printf(io,"Client certificate\n");
1596                                 X509_print(io,peer);
1597                                 PEM_write_bio_X509(io,peer);
1598                                 }
1599                         else
1600                                 BIO_puts(io,"no client certificate available\n");
1601                         BIO_puts(io,"</BODY></HTML>\r\n\r\n");
1602                         break;
1603                         }
1604                 else if ((www == 2 || www == 3)
1605                          && (strncmp("GET /",buf,5) == 0))
1606                         {
1607                         BIO *file;
1608                         char *p,*e;
1609                         static char *text="HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
1610
1611                         /* skip the '/' */
1612                         p= &(buf[5]);
1613
1614                         dot = 1;
1615                         for (e=p; *e != '\0'; e++)
1616                                 {
1617                                 if (e[0] == ' ')
1618                                         break;
1619
1620                                 switch (dot)
1621                                         {
1622                                 case 1:
1623                                         dot = (e[0] == '.') ? 2 : 0;
1624                                         break;
1625                                 case 2:
1626                                         dot = (e[0] == '.') ? 3 : 0;
1627                                         break;
1628                                 case 3:
1629                                         dot = (e[0] == '/') ? -1 : 0;
1630                                         break;
1631                                         }
1632                                 if (dot == 0)
1633                                         dot = (e[0] == '/') ? 1 : 0;
1634                                 }
1635                         dot = (dot == 3) || (dot == -1); /* filename contains ".." component */
1636
1637                         if (*e == '\0')
1638                                 {
1639                                 BIO_puts(io,text);
1640                                 BIO_printf(io,"'%s' is an invalid file name\r\n",p);
1641                                 break;
1642                                 }
1643                         *e='\0';
1644
1645                         if (dot)
1646                                 {
1647                                 BIO_puts(io,text);
1648                                 BIO_printf(io,"'%s' contains '..' reference\r\n",p);
1649                                 break;
1650                                 }
1651
1652                         if (*p == '/')
1653                                 {
1654                                 BIO_puts(io,text);
1655                                 BIO_printf(io,"'%s' is an invalid path\r\n",p);
1656                                 break;
1657                                 }
1658
1659 #if 0
1660                         /* append if a directory lookup */
1661                         if (e[-1] == '/')
1662                                 strcat(p,"index.html");
1663 #endif
1664
1665                         /* if a directory, do the index thang */
1666                         if (stat(p,&st_buf) < 0)
1667                                 {
1668                                 BIO_puts(io,text);
1669                                 BIO_printf(io,"Error accessing '%s'\r\n",p);
1670                                 ERR_print_errors(io);
1671                                 break;
1672                                 }
1673                         if (S_ISDIR(st_buf.st_mode))
1674                                 {
1675 #if 0 /* must check buffer size */
1676                                 strcat(p,"/index.html");
1677 #else
1678                                 BIO_puts(io,text);
1679                                 BIO_printf(io,"'%s' is a directory\r\n",p);
1680                                 break;
1681 #endif
1682                                 }
1683
1684                         if ((file=BIO_new_file(p,"r")) == NULL)
1685                                 {
1686                                 BIO_puts(io,text);
1687                                 BIO_printf(io,"Error opening '%s'\r\n",p);
1688                                 ERR_print_errors(io);
1689                                 break;
1690                                 }
1691
1692                         if (!s_quiet)
1693                                 BIO_printf(bio_err,"FILE:%s\n",p);
1694
1695                         if (www == 2)
1696                                 {
1697                                 i=strlen(p);
1698                                 if (    ((i > 5) && (strcmp(&(p[i-5]),".html") == 0)) ||
1699                                         ((i > 4) && (strcmp(&(p[i-4]),".php") == 0)) ||
1700                                         ((i > 4) && (strcmp(&(p[i-4]),".htm") == 0)))
1701                                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
1702                                 else
1703                                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
1704                                 }
1705                         /* send the file */
1706                         total_bytes=0;
1707                         for (;;)
1708                                 {
1709                                 i=BIO_read(file,buf,bufsize);
1710                                 if (i <= 0) break;
1711
1712 #ifdef RENEG
1713                                 total_bytes+=i;
1714                                 fprintf(stderr,"%d\n",i);
1715                                 if (total_bytes > 3*1024)
1716                                         {
1717                                         total_bytes=0;
1718                                         fprintf(stderr,"RENEGOTIATE\n");
1719                                         SSL_renegotiate(con);
1720                                         }
1721 #endif
1722
1723                                 for (j=0; j<i; )
1724                                         {
1725 #ifdef RENEG
1726 { static count=0; if (++count == 13) { SSL_renegotiate(con); } }
1727 #endif
1728                                         k=BIO_write(io,&(buf[j]),i-j);
1729                                         if (k <= 0)
1730                                                 {
1731                                                 if (!BIO_should_retry(io))
1732                                                         goto write_error;
1733                                                 else
1734                                                         {
1735                                                         BIO_printf(bio_s_out,"rwrite W BLOCK\n");
1736                                                         }
1737                                                 }
1738                                         else
1739                                                 {
1740                                                 j+=k;
1741                                                 }
1742                                         }
1743                                 }
1744 write_error:
1745                         BIO_free(file);
1746                         break;
1747                         }
1748                 }
1749
1750         for (;;)
1751                 {
1752                 i=(int)BIO_flush(io);
1753                 if (i <= 0)
1754                         {
1755                         if (!BIO_should_retry(io))
1756                                 break;
1757                         }
1758                 else
1759                         break;
1760                 }
1761 end:
1762 #if 1
1763         /* make sure we re-use sessions */
1764         SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1765 #else
1766         /* This kills performance */
1767 /*      SSL_shutdown(con); A shutdown gets sent in the
1768  *      BIO_free_all(io) procession */
1769 #endif
1770
1771 err:
1772
1773         if (ret >= 0)
1774                 BIO_printf(bio_s_out,"ACCEPT\n");
1775
1776         if (buf != NULL) OPENSSL_free(buf);
1777         if (io != NULL) BIO_free_all(io);
1778 /*      if (ssl_bio != NULL) BIO_free(ssl_bio);*/
1779         return(ret);
1780         }
1781
1782 #ifndef OPENSSL_NO_RSA
1783 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
1784         {
1785         static RSA *rsa_tmp=NULL;
1786
1787         if (rsa_tmp == NULL)
1788                 {
1789                 if (!s_quiet)
1790                         {
1791                         BIO_printf(bio_err,"Generating temp (%d bit) RSA key...",keylength);
1792                         (void)BIO_flush(bio_err);
1793                         }
1794                 if(((rsa_tmp = RSA_new()) == NULL) || !RSA_generate_key_ex(
1795                                         rsa_tmp, keylength,RSA_F4,NULL))
1796                         {
1797                         if(rsa_tmp) RSA_free(rsa_tmp);
1798                         rsa_tmp = NULL;
1799                         }
1800                 if (!s_quiet)
1801                         {
1802                         BIO_printf(bio_err,"\n");
1803                         (void)BIO_flush(bio_err);
1804                         }
1805                 }
1806         return(rsa_tmp);
1807         }
1808 #endif
1809
1810 #define MAX_SESSION_ID_ATTEMPTS 10
1811 static int generate_session_id(const SSL *ssl, unsigned char *id,
1812                                 unsigned int *id_len)
1813         {
1814         unsigned int count = 0;
1815         do      {
1816                 RAND_pseudo_bytes(id, *id_len);
1817                 /* Prefix the session_id with the required prefix. NB: If our
1818                  * prefix is too long, clip it - but there will be worse effects
1819                  * anyway, eg. the server could only possibly create 1 session
1820                  * ID (ie. the prefix!) so all future session negotiations will
1821                  * fail due to conflicts. */
1822                 memcpy(id, session_id_prefix,
1823                         (strlen(session_id_prefix) < *id_len) ?
1824                         strlen(session_id_prefix) : *id_len);
1825                 }
1826         while(SSL_has_matching_session_id(ssl, id, *id_len) &&
1827                 (++count < MAX_SESSION_ID_ATTEMPTS));
1828         if(count >= MAX_SESSION_ID_ATTEMPTS)
1829                 return 0;
1830         return 1;
1831         }