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