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