]> git.ipfire.org Git - thirdparty/openssl.git/blame - apps/s_server.c
Standardize handling of #ifdef'd options.
[thirdparty/openssl.git] / apps / s_server.c
CommitLineData
58964a49 1/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
d02b48c6
RE
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
0f113f3e 7 *
d02b48c6
RE
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
0f113f3e 14 *
d02b48c6
RE
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
0f113f3e 21 *
d02b48c6
RE
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
0f113f3e 36 * 4. If you include any Windows specific code (or a derivative thereof) from
d02b48c6
RE
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
0f113f3e 39 *
d02b48c6
RE
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
0f113f3e 51 *
d02b48c6
RE
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
a661b653 57/* ====================================================================
b1277b99 58 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
a661b653
BM
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
0f113f3e 65 * notice, this list of conditions and the following disclaimer.
a661b653
BM
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
70 * distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 * acknowledgment:
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
108 *
109 */
ea262260
BM
110/* ====================================================================
111 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
0f113f3e 112 * ECC cipher suite support in OpenSSL originally developed by
ea262260
BM
113 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
114 */
ddac1974
NL
115/* ====================================================================
116 * Copyright 2005 Nokia. All rights reserved.
117 *
118 * The portions of the attached software ("Contribution") is developed by
119 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
120 * license.
121 *
122 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
123 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
124 * support (see RFC 4279) to OpenSSL.
125 *
126 * No patent licenses or other rights except those expressly stated in
127 * the OpenSSL open source license shall be deemed granted or received
128 * expressly, by implication, estoppel, or otherwise.
129 *
130 * No assurances are provided by Nokia that the Contribution does not
131 * infringe the patent or other intellectual property rights of any third
132 * party or that the license provides you with all the necessary rights
133 * to make use of the Contribution.
134 *
135 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
136 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
137 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
138 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
139 * OTHERWISE.
140 */
d02b48c6 141
1b1a6e78 142#include <assert.h>
ddac1974 143#include <ctype.h>
8c197cc5
UM
144#include <stdio.h>
145#include <stdlib.h>
146#include <string.h>
4d8743f4 147
be1bd923 148#include <openssl/e_os2.h>
8c197cc5 149
68d39f3c
MC
150/* conflicts with winsock2 stuff on netware */
151#if !defined(OPENSSL_SYS_NETWARE)
0f113f3e 152# include <sys/types.h>
4d8743f4
RL
153#endif
154
0f113f3e
MC
155/*
156 * With IPv6, it looks like Digital has mixed up the proper order of
157 * recursive header file inclusion, resulting in the compiler complaining
158 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
159 * needed to have fileno() declared correctly... So let's define u_int
160 */
bc36ee62 161#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
0f113f3e 162# define __U_INT
7d7d2cbc
UM
163typedef unsigned int u_int;
164#endif
165
ec577822
BM
166#include <openssl/lhash.h>
167#include <openssl/bn.h>
d02b48c6
RE
168#define USE_SOCKETS
169#include "apps.h"
ec577822
BM
170#include <openssl/err.h>
171#include <openssl/pem.h>
172#include <openssl/x509.h>
173#include <openssl/ssl.h>
1372965e 174#include <openssl/rand.h>
67c8e7f4 175#include <openssl/ocsp.h>
3eeaab4b 176#ifndef OPENSSL_NO_DH
0f113f3e 177# include <openssl/dh.h>
3eeaab4b
NL
178#endif
179#ifndef OPENSSL_NO_RSA
0f113f3e 180# include <openssl/rsa.h>
3eeaab4b 181#endif
edc032b5 182#ifndef OPENSSL_NO_SRP
0f113f3e 183# include <openssl/srp.h>
edc032b5 184#endif
d02b48c6 185#include "s_apps.h"
36d16f8e 186#include "timeouts.h"
d02b48c6 187
bc36ee62 188#if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
75e0770d 189/* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
0f113f3e 190# undef FIONBIO
7d7d2cbc
UM
191#endif
192
cf1b7d96 193#ifndef OPENSSL_NO_RSA
6d23cf97 194static RSA *tmp_rsa_cb(SSL *s, int is_export, int keylength);
f5d7a031 195#endif
7c2d4fee 196static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
c3b344e3
DSH
197static int sv_body(char *hostname, int s, int stype, unsigned char *context);
198static int www_body(char *hostname, int s, int stype, unsigned char *context);
199static int rev_body(char *hostname, int s, int stype, unsigned char *context);
0f113f3e 200static void close_accept_socket(void);
d02b48c6 201static int init_ssl_connection(SSL *s);
0f113f3e 202static void print_stats(BIO *bp, SSL_CTX *ctx);
1aa0d947 203static int generate_session_id(const SSL *ssl, unsigned char *id,
0f113f3e 204 unsigned int *id_len);
35b0ea4e
DSH
205static void init_session_cache_ctx(SSL_CTX *sctx);
206static void free_sessions(void);
cf1b7d96 207#ifndef OPENSSL_NO_DH
eb3eab20 208static DH *load_dh_param(const char *dhfile);
58964a49 209#endif
ea262260 210
b74ba295 211static void s_server_init(void);
d02b48c6 212
d02b48c6
RE
213/* static int load_CA(SSL_CTX *ctx, char *file);*/
214
215#undef BUFSIZZ
0f113f3e
MC
216#define BUFSIZZ 16*1024
217static int bufsize = BUFSIZZ;
218static int accept_socket = -1;
d02b48c6 219
0f113f3e 220#define TEST_CERT "server.pem"
e481f9b9 221#define TEST_CERT2 "server2.pem"
d02b48c6 222
2a7cbe77 223extern int verify_depth, verify_return_error, verify_quiet;
d02b48c6 224
0f113f3e 225static int s_server_verify = SSL_VERIFY_NONE;
b56bce4f 226static int s_server_session_id_context = 1; /* anything will do */
0f113f3e
MC
227static const char *s_cert_file = TEST_CERT, *s_key_file =
228 NULL, *s_chain_file = NULL;
5561419a 229
0f113f3e 230static const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
0f113f3e 231static char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
d02b48c6 232#ifdef FIONBIO
0f113f3e 233static int s_nbio = 0;
d02b48c6 234#endif
0f113f3e
MC
235static int s_nbio_test = 0;
236int s_crlf = 0;
237static SSL_CTX *ctx = NULL;
0f113f3e 238static SSL_CTX *ctx2 = NULL;
0f113f3e 239static int www = 0;
d02b48c6 240
0f113f3e 241static BIO *bio_s_out = NULL;
93ab9e42 242static BIO *bio_s_msg = NULL;
0f113f3e 243static int s_debug = 0;
0f113f3e
MC
244static int s_tlsextdebug = 0;
245static int s_tlsextstatus = 0;
67c8e7f4 246static int cert_status_cb(SSL *s, void *arg);
7c2d4fee 247static int no_resume_ephemeral = 0;
0f113f3e
MC
248static int s_msg = 0;
249static int s_quiet = 0;
250static int s_ign_eof = 0;
251static int s_brief = 0;
d02b48c6 252
0f113f3e
MC
253static char *keymatexportlabel = NULL;
254static int keymatexportlen = 20;
e0af0405 255
0b13e9f0 256#ifndef OPENSSL_NO_ENGINE
0f113f3e 257static char *engine_id = NULL;
0b13e9f0 258#endif
0f113f3e 259static const char *session_id_prefix = NULL;
b74ba295 260
36d16f8e 261static int enable_timeouts = 0;
b1277b99 262static long socket_mtu;
58f41a92 263#ifndef OPENSSL_NO_DTLS1
36d16f8e 264static int cert_chain = 0;
58f41a92 265#endif
36d16f8e 266
a398f821
T
267static BIO *serverinfo_in = NULL;
268static const char *s_serverinfo_file = NULL;
36086186 269
ddac1974 270#ifndef OPENSSL_NO_PSK
0f113f3e
MC
271static char *psk_identity = "Client_identity";
272char *psk_key = NULL; /* by default PSK is not used */
ddac1974
NL
273
274static unsigned int psk_server_cb(SSL *ssl, const char *identity,
0f113f3e
MC
275 unsigned char *psk,
276 unsigned int max_psk_len)
277{
278 unsigned int psk_len = 0;
279 int ret;
280 BIGNUM *bn = NULL;
281
282 if (s_debug)
283 BIO_printf(bio_s_out, "psk_server_cb\n");
284 if (!identity) {
285 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
286 goto out_err;
287 }
288 if (s_debug)
289 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
11abf922 290 (int)strlen(identity), identity);
0f113f3e
MC
291
292 /* here we could lookup the given identity e.g. from a database */
293 if (strcmp(identity, psk_identity) != 0) {
294 BIO_printf(bio_s_out, "PSK error: client identity not found"
295 " (got '%s' expected '%s')\n", identity, psk_identity);
296 goto out_err;
297 }
298 if (s_debug)
299 BIO_printf(bio_s_out, "PSK client identity found\n");
300
301 /* convert the PSK key to binary */
302 ret = BN_hex2bn(&bn, psk_key);
303 if (!ret) {
304 BIO_printf(bio_err, "Could not convert PSK key '%s' to BIGNUM\n",
305 psk_key);
23a1d5e9 306 BN_free(bn);
0f113f3e
MC
307 return 0;
308 }
309 if (BN_num_bytes(bn) > (int)max_psk_len) {
310 BIO_printf(bio_err,
311 "psk buffer of callback is too small (%d) for key (%d)\n",
312 max_psk_len, BN_num_bytes(bn));
313 BN_free(bn);
314 return 0;
315 }
316
317 ret = BN_bn2bin(bn, psk);
318 BN_free(bn);
319
320 if (ret < 0)
321 goto out_err;
322 psk_len = (unsigned int)ret;
323
324 if (s_debug)
325 BIO_printf(bio_s_out, "fetched PSK len=%d\n", psk_len);
326 return psk_len;
ddac1974 327 out_err:
0f113f3e
MC
328 if (s_debug)
329 BIO_printf(bio_err, "Error in PSK server callback\n");
c54cc2b1
RS
330 (void)BIO_flush(bio_err);
331 (void)BIO_flush(bio_s_out);
0f113f3e
MC
332 return 0;
333}
ddac1974 334#endif
36d16f8e 335
edc032b5
BL
336#ifndef OPENSSL_NO_SRP
337/* This is a context that we pass to callbacks */
0f113f3e
MC
338typedef struct srpsrvparm_st {
339 char *login;
340 SRP_VBASE *vb;
341 SRP_user_pwd *user;
342} srpsrvparm;
343
344/*
345 * This callback pretends to require some asynchronous logic in order to
346 * obtain a verifier. When the callback is called for a new connection we
347 * return with a negative value. This will provoke the accept etc to return
348 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
349 * (which would normally occur after a worker has finished) and we set the
350 * user parameters.
351 */
6d23cf97 352static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
0f113f3e
MC
353{
354 srpsrvparm *p = (srpsrvparm *) arg;
355 if (p->login == NULL && p->user == NULL) {
356 p->login = SSL_get_srp_username(s);
357 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
358 return (-1);
359 }
360
361 if (p->user == NULL) {
362 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
363 return SSL3_AL_FATAL;
364 }
365 if (SSL_set_srp_server_param
366 (s, p->user->N, p->user->g, p->user->s, p->user->v,
367 p->user->info) < 0) {
368 *ad = SSL_AD_INTERNAL_ERROR;
369 return SSL3_AL_FATAL;
370 }
371 BIO_printf(bio_err,
372 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
373 p->login, p->user->info);
374 /* need to check whether there are memory leaks */
375 p->user = NULL;
376 p->login = NULL;
377 return SSL_ERROR_NONE;
378}
edc032b5
BL
379
380#endif
381
6b691a5c 382static void s_server_init(void)
0f113f3e
MC
383{
384 accept_socket = -1;
7e1b7485 385 verify_depth = 0;
0f113f3e
MC
386 s_server_verify = SSL_VERIFY_NONE;
387 s_dcert_file = NULL;
388 s_dkey_file = NULL;
389 s_dchain_file = NULL;
390 s_cert_file = TEST_CERT;
391 s_key_file = NULL;
392 s_chain_file = NULL;
0f113f3e
MC
393 s_cert_file2 = TEST_CERT2;
394 s_key_file2 = NULL;
395 ctx2 = NULL;
0f113f3e 396 s_nbio = 0;
0f113f3e
MC
397 s_nbio_test = 0;
398 ctx = NULL;
399 www = 0;
0f113f3e
MC
400 bio_s_out = NULL;
401 s_debug = 0;
402 s_msg = 0;
403 s_quiet = 0;
404 s_brief = 0;
0b13e9f0 405#ifndef OPENSSL_NO_ENGINE
7e1b7485 406 engine_id = NULL;
0f113f3e 407#endif
0f113f3e 408}
d02b48c6 409
0f113f3e 410static int local_argc = 0;
d02b48c6 411static char **local_argv;
d02b48c6 412
a53955d8
UM
413#ifdef CHARSET_EBCDIC
414static int ebcdic_new(BIO *bi);
415static int ebcdic_free(BIO *a);
416static int ebcdic_read(BIO *b, char *out, int outl);
0fd05a2f
BM
417static int ebcdic_write(BIO *b, const char *in, int inl);
418static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
a53955d8 419static int ebcdic_gets(BIO *bp, char *buf, int size);
0fd05a2f 420static int ebcdic_puts(BIO *bp, const char *str);
a53955d8 421
0f113f3e
MC
422# define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
423static BIO_METHOD methods_ebcdic = {
424 BIO_TYPE_EBCDIC_FILTER,
425 "EBCDIC/ASCII filter",
426 ebcdic_write,
427 ebcdic_read,
428 ebcdic_puts,
429 ebcdic_gets,
430 ebcdic_ctrl,
431 ebcdic_new,
432 ebcdic_free,
433};
434
68dc6824 435/* This struct is "unwarranted chumminess with the compiler." */
0f113f3e
MC
436typedef struct {
437 size_t alloced;
438 char buff[1];
a53955d8
UM
439} EBCDIC_OUTBUFF;
440
441BIO_METHOD *BIO_f_ebcdic_filter()
442{
0f113f3e 443 return (&methods_ebcdic);
a53955d8
UM
444}
445
446static int ebcdic_new(BIO *bi)
447{
0f113f3e 448 EBCDIC_OUTBUFF *wbuf;
a53955d8 449
b4faea50 450 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
0f113f3e
MC
451 wbuf->alloced = 1024;
452 wbuf->buff[0] = '\0';
a53955d8 453
0f113f3e
MC
454 bi->ptr = (char *)wbuf;
455 bi->init = 1;
456 bi->flags = 0;
457 return (1);
a53955d8
UM
458}
459
460static int ebcdic_free(BIO *a)
461{
0f113f3e
MC
462 if (a == NULL)
463 return (0);
25aaa98a 464 OPENSSL_free(a->ptr);
0f113f3e
MC
465 a->ptr = NULL;
466 a->init = 0;
467 a->flags = 0;
468 return (1);
a53955d8 469}
0f113f3e 470
a53955d8
UM
471static int ebcdic_read(BIO *b, char *out, int outl)
472{
0f113f3e 473 int ret = 0;
a53955d8 474
0f113f3e
MC
475 if (out == NULL || outl == 0)
476 return (0);
477 if (b->next_bio == NULL)
478 return (0);
a53955d8 479
0f113f3e
MC
480 ret = BIO_read(b->next_bio, out, outl);
481 if (ret > 0)
482 ascii2ebcdic(out, out, ret);
483 return (ret);
a53955d8
UM
484}
485
0fd05a2f 486static int ebcdic_write(BIO *b, const char *in, int inl)
a53955d8 487{
0f113f3e
MC
488 EBCDIC_OUTBUFF *wbuf;
489 int ret = 0;
490 int num;
491 unsigned char n;
a53955d8 492
0f113f3e
MC
493 if ((in == NULL) || (inl <= 0))
494 return (0);
495 if (b->next_bio == NULL)
496 return (0);
a53955d8 497
0f113f3e 498 wbuf = (EBCDIC_OUTBUFF *) b->ptr;
a53955d8 499
0f113f3e
MC
500 if (inl > (num = wbuf->alloced)) {
501 num = num + num; /* double the size */
502 if (num < inl)
503 num = inl;
b4faea50 504 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
918bb865 505 OPENSSL_free(b->ptr);
a53955d8 506
0f113f3e
MC
507 wbuf->alloced = num;
508 wbuf->buff[0] = '\0';
a53955d8 509
0f113f3e
MC
510 b->ptr = (char *)wbuf;
511 }
a53955d8 512
0f113f3e 513 ebcdic2ascii(wbuf->buff, in, inl);
a53955d8 514
0f113f3e 515 ret = BIO_write(b->next_bio, wbuf->buff, inl);
a53955d8 516
0f113f3e 517 return (ret);
a53955d8
UM
518}
519
0fd05a2f 520static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
a53955d8 521{
0f113f3e
MC
522 long ret;
523
524 if (b->next_bio == NULL)
525 return (0);
526 switch (cmd) {
527 case BIO_CTRL_DUP:
528 ret = 0L;
529 break;
530 default:
531 ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
532 break;
533 }
534 return (ret);
a53955d8
UM
535}
536
537static int ebcdic_gets(BIO *bp, char *buf, int size)
538{
0f113f3e
MC
539 int i, ret = 0;
540 if (bp->next_bio == NULL)
541 return (0);
542/* return(BIO_gets(bp->next_bio,buf,size));*/
543 for (i = 0; i < size - 1; ++i) {
544 ret = ebcdic_read(bp, &buf[i], 1);
545 if (ret <= 0)
546 break;
547 else if (buf[i] == '\n') {
548 ++i;
549 break;
550 }
551 }
552 if (i < size)
553 buf[i] = '\0';
554 return (ret < 0 && i == 0) ? ret : i;
a53955d8
UM
555}
556
0fd05a2f 557static int ebcdic_puts(BIO *bp, const char *str)
a53955d8 558{
0f113f3e
MC
559 if (bp->next_bio == NULL)
560 return (0);
561 return ebcdic_write(bp, str, strlen(str));
a53955d8
UM
562}
563#endif
564
ed3883d2
BM
565/* This is a context that we pass to callbacks */
566typedef struct tlsextctx_st {
0f113f3e
MC
567 char *servername;
568 BIO *biodebug;
569 int extension_error;
ed3883d2
BM
570} tlsextctx;
571
6d23cf97 572static int ssl_servername_cb(SSL *s, int *ad, void *arg)
0f113f3e
MC
573{
574 tlsextctx *p = (tlsextctx *) arg;
575 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
576 if (servername && p->biodebug)
577 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
578 servername);
579
580 if (!p->servername)
581 return SSL_TLSEXT_ERR_NOACK;
582
583 if (servername) {
584 if (strcasecmp(servername, p->servername))
585 return p->extension_error;
586 if (ctx2) {
587 BIO_printf(p->biodebug, "Switching server context.\n");
588 SSL_set_SSL_CTX(s, ctx2);
589 }
590 }
591 return SSL_TLSEXT_ERR_OK;
ed3883d2 592}
67c8e7f4
DSH
593
594/* Structure passed to cert status callback */
595
596typedef struct tlsextstatusctx_st {
0f113f3e
MC
597 /* Default responder to use */
598 char *host, *path, *port;
599 int use_ssl;
600 int timeout;
0f113f3e 601 int verbose;
67c8e7f4
DSH
602} tlsextstatusctx;
603
7e1b7485 604static tlsextstatusctx tlscstatp = { NULL, NULL, NULL, 0, -1, 0 };
67c8e7f4 605
0f113f3e
MC
606/*
607 * Certificate Status callback. This is called when a client includes a
608 * certificate status request extension. This is a simplified version. It
609 * examines certificates each time and makes one OCSP responder query for
610 * each request. A full version would store details such as the OCSP
611 * certificate IDs and minimise the number of OCSP responses by caching them
612 * until they were considered "expired".
67c8e7f4
DSH
613 */
614
615static int cert_status_cb(SSL *s, void *arg)
0f113f3e
MC
616{
617 tlsextstatusctx *srctx = arg;
4c9b0a03 618 char *host = NULL, *port = NULL, *path = NULL;
0f113f3e
MC
619 int use_ssl;
620 unsigned char *rspder = NULL;
621 int rspderlen;
622 STACK_OF(OPENSSL_STRING) *aia = NULL;
623 X509 *x = NULL;
624 X509_STORE_CTX inctx;
625 X509_OBJECT obj;
626 OCSP_REQUEST *req = NULL;
627 OCSP_RESPONSE *resp = NULL;
628 OCSP_CERTID *id = NULL;
629 STACK_OF(X509_EXTENSION) *exts;
630 int ret = SSL_TLSEXT_ERR_NOACK;
631 int i;
7e1b7485 632
0f113f3e 633 if (srctx->verbose)
7e1b7485 634 BIO_puts(bio_err, "cert_status: callback called\n");
0f113f3e
MC
635 /* Build up OCSP query from server certificate */
636 x = SSL_get_certificate(s);
637 aia = X509_get1_ocsp(x);
638 if (aia) {
639 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
640 &host, &port, &path, &use_ssl)) {
7e1b7485 641 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
0f113f3e
MC
642 goto err;
643 }
644 if (srctx->verbose)
7e1b7485 645 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
0f113f3e
MC
646 sk_OPENSSL_STRING_value(aia, 0));
647 } else {
648 if (!srctx->host) {
7e1b7485 649 BIO_puts(bio_err,
0f113f3e
MC
650 "cert_status: no AIA and no default responder URL\n");
651 goto done;
652 }
653 host = srctx->host;
654 path = srctx->path;
655 port = srctx->port;
656 use_ssl = srctx->use_ssl;
657 }
658
659 if (!X509_STORE_CTX_init(&inctx,
660 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
661 NULL, NULL))
662 goto err;
663 if (X509_STORE_get_by_subject(&inctx, X509_LU_X509,
664 X509_get_issuer_name(x), &obj) <= 0) {
7e1b7485 665 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
0f113f3e
MC
666 X509_STORE_CTX_cleanup(&inctx);
667 goto done;
668 }
669 req = OCSP_REQUEST_new();
670 if (!req)
671 goto err;
672 id = OCSP_cert_to_id(NULL, x, obj.data.x509);
673 X509_free(obj.data.x509);
674 X509_STORE_CTX_cleanup(&inctx);
675 if (!id)
676 goto err;
677 if (!OCSP_request_add0_id(req, id))
678 goto err;
679 id = NULL;
680 /* Add any extensions to the request */
681 SSL_get_tlsext_status_exts(s, &exts);
682 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
683 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
684 if (!OCSP_REQUEST_add_ext(req, ext, -1))
685 goto err;
686 }
7e1b7485 687 resp = process_responder(req, host, path, port, use_ssl, NULL,
0f113f3e
MC
688 srctx->timeout);
689 if (!resp) {
7e1b7485 690 BIO_puts(bio_err, "cert_status: error querying responder\n");
0f113f3e
MC
691 goto done;
692 }
693 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
694 if (rspderlen <= 0)
695 goto err;
696 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
697 if (srctx->verbose) {
7e1b7485
RS
698 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
699 OCSP_RESPONSE_print(bio_err, resp, 2);
0f113f3e
MC
700 }
701 ret = SSL_TLSEXT_ERR_OK;
702 done:
703 if (ret != SSL_TLSEXT_ERR_OK)
7e1b7485 704 ERR_print_errors(bio_err);
0f113f3e
MC
705 if (aia) {
706 OPENSSL_free(host);
707 OPENSSL_free(path);
708 OPENSSL_free(port);
709 X509_email_free(aia);
710 }
25aaa98a
RS
711 OCSP_CERTID_free(id);
712 OCSP_REQUEST_free(req);
713 OCSP_RESPONSE_free(resp);
0f113f3e
MC
714 return ret;
715 err:
716 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
717 goto done;
718}
ee2ffc27 719
e481f9b9 720#ifndef OPENSSL_NO_NEXTPROTONEG
ee2ffc27
BL
721/* This is the context that we pass to next_proto_cb */
722typedef struct tlsextnextprotoctx_st {
0f113f3e
MC
723 unsigned char *data;
724 unsigned int len;
ee2ffc27
BL
725} tlsextnextprotoctx;
726
0f113f3e
MC
727static int next_proto_cb(SSL *s, const unsigned char **data,
728 unsigned int *len, void *arg)
729{
730 tlsextnextprotoctx *next_proto = arg;
ee2ffc27 731
0f113f3e
MC
732 *data = next_proto->data;
733 *len = next_proto->len;
ee2ffc27 734
0f113f3e
MC
735 return SSL_TLSEXT_ERR_OK;
736}
e481f9b9 737#endif /* ndef OPENSSL_NO_NEXTPROTONEG */
6f017a8f
AL
738
739/* This the context that we pass to alpn_cb */
740typedef struct tlsextalpnctx_st {
0f113f3e
MC
741 unsigned char *data;
742 unsigned short len;
6f017a8f
AL
743} tlsextalpnctx;
744
0f113f3e
MC
745static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
746 const unsigned char *in, unsigned int inlen, void *arg)
747{
748 tlsextalpnctx *alpn_ctx = arg;
749
750 if (!s_quiet) {
751 /* We can assume that |in| is syntactically valid. */
752 unsigned i;
753 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
754 for (i = 0; i < inlen;) {
755 if (i)
756 BIO_write(bio_s_out, ", ", 2);
757 BIO_write(bio_s_out, &in[i + 1], in[i]);
758 i += in[i] + 1;
759 }
760 BIO_write(bio_s_out, "\n", 1);
761 }
762
763 if (SSL_select_next_proto
764 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
765 inlen) != OPENSSL_NPN_NEGOTIATED) {
766 return SSL_TLSEXT_ERR_NOACK;
767 }
768
769 if (!s_quiet) {
770 BIO_printf(bio_s_out, "ALPN protocols selected: ");
771 BIO_write(bio_s_out, *out, *outlen);
772 BIO_write(bio_s_out, "\n", 1);
773 }
774
775 return SSL_TLSEXT_ERR_OK;
776}
ed3883d2 777
7c2d4fee 778static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
0f113f3e
MC
779{
780 /* disable resumption for sessions with forward secure ciphers */
781 return is_forward_secure;
782}
7c2d4fee 783
6caa4edd 784static char *jpake_secret = NULL;
c79f22c6 785#ifndef OPENSSL_NO_SRP
0f113f3e 786static srpsrvparm srp_callback_parm;
c79f22c6 787#endif
e783bae2 788#ifndef OPENSSL_NO_SRTP
333f926d 789static char *srtp_profiles = NULL;
e783bae2 790#endif
6caa4edd 791
7e1b7485
RS
792typedef enum OPTION_choice {
793 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
794 OPT_ENGINE, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
795 OPT_VERIFY, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
796 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
797 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
798 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
799 OPT_CAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
800 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
801 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE,
802 OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG,
803 OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE, OPT_STATUS_TIMEOUT,
804 OPT_STATUS_URL, OPT_MSG, OPT_MSGFILE, OPT_TRACE, OPT_SECURITY_DEBUG,
805 OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF, OPT_QUIET,
806 OPT_BRIEF, OPT_NO_TMP_RSA, OPT_NO_DHE, OPT_NO_ECDHE,
807 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
808 OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP,
7e1b7485 809 OPT_SSL3,
7e1b7485
RS
810 OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
811 OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_CHAIN,
812 OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
813 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_JPAKE,
814 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
815 OPT_S_ENUM,
816 OPT_V_ENUM,
5561419a 817 OPT_X_ENUM
7e1b7485
RS
818} OPTION_CHOICE;
819
820OPTIONS s_server_options[] = {
821 {"help", OPT_HELP, '-', "Display this summary"},
7e1b7485
RS
822 {"port", OPT_PORT, 'p'},
823 {"accept", OPT_PORT, 'p',
824 "TCP/IP port to accept on (default is " PORT_STR ")"},
825 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
826 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
827 {"context", OPT_CONTEXT, 's', "Set session ID context"},
828 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
829 {"Verify", OPT_UPPER_V_VERIFY, 'n',
830 "Turn on peer certificate verification, must have a cert"},
831 {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
832 {"naccept", OPT_NACCEPT, 'p', "Terminate after pnum connections"},
7e1b7485
RS
833 {"serverinfo", OPT_SERVERINFO, 's',
834 "PEM serverinfo file for certificate"},
7e1b7485
RS
835 {"certform", OPT_CERTFORM, 'F',
836 "Certificate format (PEM or DER) PEM default"},
837 {"key", OPT_KEY, '<',
838 "Private Key if not in -cert; default is " TEST_CERT},
839 {"keyform", OPT_KEYFORM, 'f',
840 "Key format (PEM, DER or ENGINE) PEM default"},
841 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
842 {"dcert", OPT_DCERT, '<',
843 "Second certificate file to use (usually for DSA)"},
844 {"dcertform", OPT_DCERTFORM, 'F',
845 "Second certificate format (PEM or DER) PEM default"},
846 {"dkey", OPT_DKEY, '<',
847 "Second private key file to use (usually for DSA)"},
848 {"dkeyform", OPT_DKEYFORM, 'F',
849 "Second key format (PEM, DER or ENGINE) PEM default"},
850 {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
7e1b7485
RS
851 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
852 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
853 {"debug", OPT_DEBUG, '-', "Print more output"},
854 {"msg", OPT_MSG, '-', "Show protocol messages"},
855 {"msgfile", OPT_MSGFILE, '>'},
856 {"state", OPT_STATE, '-', "Print the SSL states"},
857 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
858 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
859 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
860 {"quiet", OPT_QUIET, '-', "No server output"},
861 {"no_tmp_rsa", OPT_NO_TMP_RSA, '-', "Do not generate a tmp RSA key"},
7e1b7485
RS
862 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
863 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
864 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
7e1b7485
RS
865 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
866 "Disable caching and tickets if ephemeral (EC)DH is used"},
867 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
868 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
7e1b7485
RS
869 {"servername", OPT_SERVERNAME, 's',
870 "Servername for HostName TLS extension"},
871 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
872 "mismatch send fatal alert (default warning alert)"},
873 {"cert2", OPT_CERT2, '<',
874 "Certificate file to use for servername; default is" TEST_CERT2},
875 {"key2", OPT_KEY2, '<',
876 "-Private Key file to use for servername if not in -cert2"},
877 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
878 "Hex dump of all TLS extensions received"},
9c3bcfa0
RS
879 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path incluedes HTTP headers"},
880 {"id_prefix", OPT_ID_PREFIX, 's',
881 "Generate SSL/TLS session IDs prefixed by arg"},
882 {"rand", OPT_RAND, 's',
883 "Load the file(s) into the random number generator"},
7e1b7485
RS
884 {"keymatexport", OPT_KEYMATEXPORT, 's',
885 "Export keying material using label"},
886 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
887 "Export len bytes of keying material (default 20)"},
888 {"CRL", OPT_CRL, '<'},
889 {"crl_download", OPT_CRL_DOWNLOAD, '-'},
890 {"cert_chain", OPT_CERT_CHAIN, '<'},
891 {"dcert_chain", OPT_DCERT_CHAIN, '<'},
892 {"chainCApath", OPT_CHAINCAPATH, '/'},
893 {"verifyCApath", OPT_VERIFYCAPATH, '/'},
894 {"no_cache", OPT_NO_CACHE, '-'},
895 {"ext_cache", OPT_EXT_CACHE, '-'},
896 {"CRLform", OPT_CRLFORM, 'F'},
897 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-'},
898 {"verify_quiet", OPT_VERIFY_QUIET, '-'},
899 {"build_chain", OPT_BUILD_CHAIN, '-'},
900 {"chainCAfile", OPT_CHAINCAFILE, '<'},
901 {"verifyCAfile", OPT_VERIFYCAFILE, '<'},
902 {"ign_eof", OPT_IGN_EOF, '-'},
903 {"no_ign_eof", OPT_NO_IGN_EOF, '-'},
904 {"status", OPT_STATUS, '-'},
905 {"status_verbose", OPT_STATUS_VERBOSE, '-'},
906 {"status_timeout", OPT_STATUS_TIMEOUT, 'n'},
907 {"status_url", OPT_STATUS_URL, 's'},
908 {"trace", OPT_TRACE, '-'},
909 {"security_debug", OPT_SECURITY_DEBUG, '-'},
910 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-'},
911 {"brief", OPT_BRIEF, '-'},
912 {"rev", OPT_REV, '-'},
7e1b7485
RS
913 OPT_S_OPTIONS,
914 OPT_V_OPTIONS,
915 OPT_X_OPTIONS,
9c3bcfa0
RS
916#ifdef FIONBIO
917 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
918#endif
919#ifndef OPENSSL_NO_PSK
920 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
921 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
922# ifndef OPENSSL_NO_JPAKE
923 {"jpake", OPT_JPAKE, 's', "JPAKE secret to use"},
924# endif
925#endif
926#ifndef OPENSSL_NO_SRP
927 {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
928 {"srpuserseed", OPT_SRPUSERSEED, 's',
929 "A seed string for a default user salt"},
930#endif
931#ifndef OPENSSL_NO_SSL3
932 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
933#endif
934#ifndef OPENSSL_NO_DTLS1
935 {"dtls", OPT_DTLS, '-'},
936 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
937 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
938 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
939 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
940 {"chain", OPT_CHAIN, '-', "Read a certificate chain"},
941#endif
942#ifndef OPENSSL_NO_DH
943 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
944#endif
945#ifndef OPENSSL_NO_EC
946 {"no_ecdhe", OPT_NO_ECDHE, '-', "Disable ephemeral ECDH"},
947#endif
948#ifndef OPENSSL_NO_NEXTPROTONEG
949 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
950 "Set the advertised protocols for the NPN extension (comma-separated list)"},
951#endif
952#ifndef OPENSSL_NO_SRTP
953 {"use_srtp", OPT_SRTP_PROFILES, '<',
954 "Offer SRTP key management with a colon-separated profile list"},
955 {"alpn", OPT_ALPN, 's',
956 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
957#endif
958#ifndef OPENSSL_NO_ENGINE
959 {"engine", OPT_ENGINE, 's'},
960#endif
7e1b7485
RS
961 {NULL}
962};
963
964int s_server_main(int argc, char *argv[])
0f113f3e 965{
7e1b7485
RS
966 ENGINE *e = NULL;
967 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
968 SSL_CONF_CTX *cctx = NULL;
32ec4153 969 const SSL_METHOD *meth = TLS_server_method();
7e1b7485
RS
970 SSL_EXCERT *exc = NULL;
971 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
972 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
973 STACK_OF(X509_CRL) *crls = NULL;
974 X509 *s_cert = NULL, *s_dcert = NULL;
0f113f3e 975 X509_VERIFY_PARAM *vpm = NULL;
7e1b7485
RS
976 char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
977 char *dhfile = NULL, *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
978 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
a7f82a1a
MC
979 char *crl_file = NULL, *prog;
980#ifndef OPENSSL_NO_PSK
981 char *p;
982#endif
0f113f3e 983 const char *unix_path = NULL;
9cd86abb 984#ifndef NO_SYS_UN_H
0f113f3e
MC
985 int unlink_unix_path = 0;
986#endif
987 int (*server_cb) (char *hostname, int s, int stype,
988 unsigned char *context);
7e1b7485
RS
989 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
990 int no_tmp_rsa = 0, no_dhe = 0, no_ecdhe = 0, nocert = 0, ret = 1;
0f113f3e 991 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
0f113f3e 992 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
7e1b7485
RS
993 int rev = 0, naccept = -1, sdebug = 0, socket_type = SOCK_STREAM;
994 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
995 unsigned short port = PORT;
996 unsigned char *context = NULL;
997 OPTION_CHOICE o;
0f113f3e
MC
998 EVP_PKEY *s_key2 = NULL;
999 X509 *s_cert2 = NULL;
1000 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
e481f9b9 1001#ifndef OPENSSL_NO_NEXTPROTONEG
0f113f3e
MC
1002 const char *next_proto_neg_in = NULL;
1003 tlsextnextprotoctx next_proto = { NULL, 0 };
e481f9b9 1004#endif
0f113f3e
MC
1005 const char *alpn_in = NULL;
1006 tlsextalpnctx alpn_ctx = { NULL, 0 };
ddac1974 1007#ifndef OPENSSL_NO_PSK
0f113f3e
MC
1008 /* by default do not send a PSK identity hint */
1009 static char *psk_identity_hint = NULL;
ddac1974 1010#endif
edc032b5 1011#ifndef OPENSSL_NO_SRP
0f113f3e
MC
1012 char *srpuserseed = NULL;
1013 char *srp_verifier_file = NULL;
edc032b5 1014#endif
d02b48c6 1015
0f113f3e
MC
1016 local_argc = argc;
1017 local_argv = argv;
d02b48c6 1018
0f113f3e 1019 s_server_init();
0f113f3e 1020 cctx = SSL_CONF_CTX_new();
7e1b7485
RS
1021 vpm = X509_VERIFY_PARAM_new();
1022 if (cctx == NULL || vpm == NULL)
0f113f3e 1023 goto end;
7e1b7485
RS
1024 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1025
1026 prog = opt_init(argc, argv, s_server_options);
1027 while ((o = opt_next()) != OPT_EOF) {
1028 switch (o) {
a7f82a1a
MC
1029#ifdef OPENSSL_NO_PSK
1030 case OPT_PSK_HINT:
1031 case OPT_PSK:
1032#endif
1033#ifdef OPENSSL_NO_DTLS1
1034 case OPT_DTLS:
1035 case OPT_DTLS1:
1036 case OPT_DTLS1_2:
1037 case OPT_TIMEOUT:
1038 case OPT_MTU:
1039 case OPT_CHAIN:
1040#endif
7e1b7485
RS
1041 case OPT_EOF:
1042 case OPT_ERR:
1043 opthelp:
1044 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1045 goto end;
1046 case OPT_HELP:
1047 opt_help(s_server_options);
1048 ret = 0;
1049 goto end;
0f113f3e 1050
7e1b7485
RS
1051 case OPT_PORT:
1052 if (!extract_port(opt_arg(), &port))
1053 goto end;
1054 break;
1055 case OPT_UNIX:
a9351320 1056#ifdef NO_SYS_UN_H
0f113f3e 1057 BIO_printf(bio_err, "unix domain sockets unsupported\n");
7e1b7485 1058 goto end;
a9351320 1059#else
7e1b7485 1060 unix_path = opt_arg();
a9351320 1061#endif
7e1b7485
RS
1062 break;
1063 case OPT_UNLINK:
a9351320 1064#ifdef NO_SYS_UN_H
0f113f3e 1065 BIO_printf(bio_err, "unix domain sockets unsupported\n");
7e1b7485 1066 goto end;
a9351320 1067#else
0f113f3e
MC
1068 unlink_unix_path = 1;
1069#endif
7e1b7485
RS
1070 break;
1071 case OPT_NACCEPT:
1072 naccept = atol(opt_arg());
1073 break;
1074 case OPT_VERIFY:
0f113f3e 1075 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
7e1b7485 1076 verify_depth = atoi(opt_arg());
0f113f3e
MC
1077 if (!s_quiet)
1078 BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
7e1b7485
RS
1079 break;
1080 case OPT_UPPER_V_VERIFY:
0f113f3e
MC
1081 s_server_verify =
1082 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1083 SSL_VERIFY_CLIENT_ONCE;
7e1b7485 1084 verify_depth = atoi(opt_arg());
0f113f3e
MC
1085 if (!s_quiet)
1086 BIO_printf(bio_err,
1087 "verify depth is %d, must return a certificate\n",
1088 verify_depth);
7e1b7485
RS
1089 break;
1090 case OPT_CONTEXT:
1091 context = (unsigned char *)opt_arg();
1092 break;
1093 case OPT_CERT:
1094 s_cert_file = opt_arg();
1095 break;
1096 case OPT_CRL:
1097 crl_file = opt_arg();
1098 break;
1099 case OPT_CRL_DOWNLOAD:
0f113f3e 1100 crl_download = 1;
7e1b7485 1101 break;
7e1b7485
RS
1102 case OPT_SERVERINFO:
1103 s_serverinfo_file = opt_arg();
1104 break;
7e1b7485
RS
1105 case OPT_CERTFORM:
1106 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1107 goto opthelp;
1108 break;
1109 case OPT_KEY:
1110 s_key_file = opt_arg();
1111 break;
1112 case OPT_KEYFORM:
1113 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1114 goto opthelp;
1115 break;
1116 case OPT_PASS:
1117 passarg = opt_arg();
1118 break;
1119 case OPT_CERT_CHAIN:
1120 s_chain_file = opt_arg();
1121 break;
1122 case OPT_DHPARAM:
1123 dhfile = opt_arg();
1124 break;
1125 case OPT_DCERTFORM:
1126 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1127 goto opthelp;
1128 break;
1129 case OPT_DCERT:
1130 s_dcert_file = opt_arg();
1131 break;
1132 case OPT_DKEYFORM:
1133 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1134 goto opthelp;
1135 break;
1136 case OPT_DPASS:
1137 dpassarg = opt_arg();
1138 break;
1139 case OPT_DKEY:
1140 s_dkey_file = opt_arg();
1141 break;
1142 case OPT_DCERT_CHAIN:
1143 s_dchain_file = opt_arg();
1144 break;
1145 case OPT_NOCERT:
0f113f3e 1146 nocert = 1;
7e1b7485
RS
1147 break;
1148 case OPT_CAPATH:
1149 CApath = opt_arg();
1150 break;
1151 case OPT_CHAINCAPATH:
1152 chCApath = opt_arg();
1153 break;
1154 case OPT_VERIFYCAPATH:
1155 vfyCApath = opt_arg();
1156 break;
1157 case OPT_NO_CACHE:
0f113f3e 1158 no_cache = 1;
7e1b7485
RS
1159 break;
1160 case OPT_EXT_CACHE:
0f113f3e 1161 ext_cache = 1;
7e1b7485
RS
1162 break;
1163 case OPT_CRLFORM:
1164 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1165 goto opthelp;
1166 break;
1167 case OPT_S_CASES:
1168 if (ssl_args == NULL)
1169 ssl_args = sk_OPENSSL_STRING_new_null();
1170 if (ssl_args == NULL
1171 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1172 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1173 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1174 goto end;
1175 }
1176 break;
1177 case OPT_V_CASES:
1178 if (!opt_verify(o, vpm))
1179 goto end;
1180 vpmtouched++;
1181 break;
1182 case OPT_X_CASES:
1183 if (!args_excert(o, &exc))
1184 goto end;
1185 break;
1186 case OPT_VERIFY_RET_ERROR:
0f113f3e 1187 verify_return_error = 1;
7e1b7485
RS
1188 break;
1189 case OPT_VERIFY_QUIET:
0f113f3e 1190 verify_quiet = 1;
7e1b7485
RS
1191 break;
1192 case OPT_BUILD_CHAIN:
0f113f3e 1193 build_chain = 1;
7e1b7485
RS
1194 break;
1195 case OPT_CAFILE:
1196 CAfile = opt_arg();
1197 break;
1198 case OPT_CHAINCAFILE:
1199 chCAfile = opt_arg();
1200 break;
1201 case OPT_VERIFYCAFILE:
1202 vfyCAfile = opt_arg();
1203 break;
1204 case OPT_NBIO:
0f113f3e 1205 s_nbio = 1;
7e1b7485
RS
1206 break;
1207 case OPT_NBIO_TEST:
1208 s_nbio = s_nbio_test = 1;
1209 break;
1210 case OPT_IGN_EOF:
0f113f3e 1211 s_ign_eof = 1;
7e1b7485
RS
1212 break;
1213 case OPT_NO_IGN_EOF:
0f113f3e 1214 s_ign_eof = 0;
7e1b7485
RS
1215 break;
1216 case OPT_DEBUG:
0f113f3e 1217 s_debug = 1;
7e1b7485 1218 break;
7e1b7485 1219 case OPT_TLSEXTDEBUG:
0f113f3e 1220 s_tlsextdebug = 1;
7e1b7485
RS
1221 break;
1222 case OPT_STATUS:
0f113f3e 1223 s_tlsextstatus = 1;
7e1b7485
RS
1224 break;
1225 case OPT_STATUS_VERBOSE:
1226 s_tlsextstatus = tlscstatp.verbose = 1;
1227 break;
1228 case OPT_STATUS_TIMEOUT:
0f113f3e 1229 s_tlsextstatus = 1;
7e1b7485
RS
1230 tlscstatp.timeout = atoi(opt_arg());
1231 break;
1232 case OPT_STATUS_URL:
0f113f3e 1233 s_tlsextstatus = 1;
7e1b7485 1234 if (!OCSP_parse_url(opt_arg(),
0f113f3e
MC
1235 &tlscstatp.host,
1236 &tlscstatp.port,
1237 &tlscstatp.path, &tlscstatp.use_ssl)) {
1238 BIO_printf(bio_err, "Error parsing URL\n");
7e1b7485 1239 goto end;
0f113f3e 1240 }
7e1b7485 1241 break;
7e1b7485 1242 case OPT_MSG:
0f113f3e 1243 s_msg = 1;
7e1b7485
RS
1244 break;
1245 case OPT_MSGFILE:
1246 bio_s_msg = BIO_new_file(opt_arg(), "w");
1247 break;
7e1b7485 1248 case OPT_TRACE:
9c3bcfa0 1249#ifndef OPENSSL_NO_SSL_TRACE
0f113f3e 1250 s_msg = 2;
7e1b7485 1251#else
9c3bcfa0 1252 break;
0f113f3e 1253#endif
7e1b7485 1254 case OPT_SECURITY_DEBUG:
0f113f3e 1255 sdebug = 1;
7e1b7485
RS
1256 break;
1257 case OPT_SECURITY_DEBUG_VERBOSE:
0f113f3e 1258 sdebug = 2;
7e1b7485
RS
1259 break;
1260 case OPT_STATE:
0f113f3e 1261 state = 1;
7e1b7485
RS
1262 break;
1263 case OPT_CRLF:
0f113f3e 1264 s_crlf = 1;
7e1b7485
RS
1265 break;
1266 case OPT_QUIET:
0f113f3e 1267 s_quiet = 1;
7e1b7485
RS
1268 break;
1269 case OPT_BRIEF:
1270 s_quiet = s_brief = verify_quiet = 1;
1271 break;
1272 case OPT_NO_TMP_RSA:
0f113f3e 1273 no_tmp_rsa = 1;
7e1b7485
RS
1274 break;
1275 case OPT_NO_DHE:
0f113f3e 1276 no_dhe = 1;
7e1b7485
RS
1277 break;
1278 case OPT_NO_ECDHE:
0f113f3e 1279 no_ecdhe = 1;
7e1b7485
RS
1280 break;
1281 case OPT_NO_RESUME_EPHEMERAL:
0f113f3e 1282 no_resume_ephemeral = 1;
7e1b7485 1283 break;
ddac1974 1284#ifndef OPENSSL_NO_PSK
7e1b7485
RS
1285 case OPT_PSK_HINT:
1286 psk_identity_hint = opt_arg();
1287 break;
1288 case OPT_PSK:
1289 for (p = psk_key = opt_arg(); *p; p++) {
1290 if (isxdigit(*p))
0f113f3e
MC
1291 continue;
1292 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
7e1b7485 1293 goto end;
0f113f3e 1294 }
7e1b7485 1295 break;
9c3bcfa0
RS
1296#else
1297 case OPT_PSK_HINT:
1298 case OPT_PSK:
1299 break;
edc032b5
BL
1300#endif
1301#ifndef OPENSSL_NO_SRP
7e1b7485
RS
1302 case OPT_SRPVFILE:
1303 srp_verifier_file = opt_arg();
0f113f3e 1304 meth = TLSv1_server_method();
7e1b7485
RS
1305 break;
1306 case OPT_SRPUSERSEED:
1307 srpuserseed = opt_arg();
0f113f3e 1308 meth = TLSv1_server_method();
7e1b7485 1309 break;
857048a7
RS
1310#else
1311 case OPT_SRPVFILE:
1312 case OPT_SRPUSERSEED:
1313 break;
0f113f3e 1314#endif
7e1b7485 1315 case OPT_REV:
0f113f3e 1316 rev = 1;
7e1b7485
RS
1317 break;
1318 case OPT_WWW:
0f113f3e 1319 www = 1;
7e1b7485
RS
1320 break;
1321 case OPT_UPPER_WWW:
0f113f3e 1322 www = 2;
7e1b7485
RS
1323 break;
1324 case OPT_HTTP:
0f113f3e 1325 www = 3;
7e1b7485 1326 break;
7e1b7485 1327 case OPT_SSL3:
9c3bcfa0 1328#ifndef OPENSSL_NO_SSL3
4407d070 1329 meth = SSLv3_server_method();
58964a49 1330#endif
9c3bcfa0 1331 break;
7e1b7485 1332 case OPT_TLS1_2:
4407d070 1333 meth = TLSv1_2_server_method();
7e1b7485
RS
1334 break;
1335 case OPT_TLS1_1:
4407d070 1336 meth = TLSv1_1_server_method();
7e1b7485
RS
1337 break;
1338 case OPT_TLS1:
4407d070 1339 meth = TLSv1_server_method();
7e1b7485 1340 break;
36d16f8e 1341#ifndef OPENSSL_NO_DTLS1
7e1b7485 1342 case OPT_DTLS:
4407d070 1343 meth = DTLS_server_method();
0f113f3e 1344 socket_type = SOCK_DGRAM;
7e1b7485
RS
1345 break;
1346 case OPT_DTLS1:
4407d070 1347 meth = DTLSv1_server_method();
0f113f3e 1348 socket_type = SOCK_DGRAM;
7e1b7485
RS
1349 break;
1350 case OPT_DTLS1_2:
4407d070 1351 meth = DTLSv1_2_server_method();
0f113f3e 1352 socket_type = SOCK_DGRAM;
7e1b7485
RS
1353 break;
1354 case OPT_TIMEOUT:
0f113f3e 1355 enable_timeouts = 1;
7e1b7485
RS
1356 break;
1357 case OPT_MTU:
1358 socket_mtu = atol(opt_arg());
1359 break;
1360 case OPT_CHAIN:
0f113f3e 1361 cert_chain = 1;
7e1b7485 1362 break;
9c3bcfa0
RS
1363#else
1364 case OPT_DTLS:
1365 case OPT_DTLS1:
1366 case OPT_DTLS1_2:
1367 case OPT_TIMEOUT:
1368 case OPT_MTU:
1369 case OPT_CHAIN:
1370 break;
0f113f3e 1371#endif
7e1b7485
RS
1372 case OPT_ID_PREFIX:
1373 session_id_prefix = opt_arg();
1374 break;
1375 case OPT_ENGINE:
333b070e 1376 e = setup_engine(opt_arg(), 1);
7e1b7485
RS
1377 break;
1378 case OPT_RAND:
1379 inrand = opt_arg();
1380 break;
7e1b7485
RS
1381 case OPT_SERVERNAME:
1382 tlsextcbp.servername = opt_arg();
1383 break;
1384 case OPT_SERVERNAME_FATAL:
0f113f3e 1385 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
7e1b7485
RS
1386 break;
1387 case OPT_CERT2:
1388 s_cert_file2 = opt_arg();
1389 break;
1390 case OPT_KEY2:
1391 s_key_file2 = opt_arg();
1392 break;
7e1b7485 1393 case OPT_NEXTPROTONEG:
9c3bcfa0 1394# ifndef OPENSSL_NO_NEXTPROTONEG
7e1b7485 1395 next_proto_neg_in = opt_arg();
e481f9b9 1396#endif
9c3bcfa0 1397 break;
7e1b7485
RS
1398 case OPT_ALPN:
1399 alpn_in = opt_arg();
1400 break;
79bd20fd 1401#if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
7e1b7485
RS
1402 case OPT_JPAKE:
1403 jpake_secret = opt_arg();
1404 break;
1405#else
1406 case OPT_JPAKE:
1407 goto opthelp;
0f113f3e 1408#endif
7e1b7485
RS
1409 case OPT_SRTP_PROFILES:
1410 srtp_profiles = opt_arg();
1411 break;
1412 case OPT_KEYMATEXPORT:
1413 keymatexportlabel = opt_arg();
1414 break;
1415 case OPT_KEYMATEXPORTLEN:
1416 keymatexportlen = atoi(opt_arg());
0f113f3e
MC
1417 break;
1418 }
0f113f3e 1419 }
7e1b7485
RS
1420 argc = opt_num_rest();
1421 argv = opt_rest();
1422
199772e5 1423#ifndef OPENSSL_NO_DTLS1
0f113f3e
MC
1424 if (www && socket_type == SOCK_DGRAM) {
1425 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1426 goto end;
1427 }
1428#endif
1429
1430 if (unix_path && (socket_type != SOCK_STREAM)) {
1431 BIO_printf(bio_err,
1432 "Can't use unix sockets and datagrams together\n");
1433 goto end;
1434 }
79bd20fd 1435#if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
0f113f3e
MC
1436 if (jpake_secret) {
1437 if (psk_key) {
1438 BIO_printf(bio_err, "Can't use JPAKE and PSK together\n");
1439 goto end;
1440 }
1441 psk_identity = "JPAKE";
1442 }
f3b7bdad 1443#endif
2900fc8a 1444
7e1b7485 1445 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
0f113f3e
MC
1446 BIO_printf(bio_err, "Error getting password\n");
1447 goto end;
1448 }
826a42a0 1449
296f54ee
RL
1450 if (!app_load_modules(NULL))
1451 goto end;
1452
0f113f3e
MC
1453 if (s_key_file == NULL)
1454 s_key_file = s_cert_file;
e481f9b9 1455
0f113f3e
MC
1456 if (s_key_file2 == NULL)
1457 s_key_file2 = s_cert_file2;
ed3883d2 1458
7e1b7485 1459 if (!load_excert(&exc))
0f113f3e
MC
1460 goto end;
1461
1462 if (nocert == 0) {
7e1b7485 1463 s_key = load_key(s_key_file, s_key_format, 0, pass, e,
0f113f3e
MC
1464 "server certificate private key file");
1465 if (!s_key) {
1466 ERR_print_errors(bio_err);
1467 goto end;
1468 }
826a42a0 1469
7e1b7485 1470 s_cert = load_cert(s_cert_file, s_cert_format,
0f113f3e
MC
1471 NULL, e, "server certificate file");
1472
1473 if (!s_cert) {
1474 ERR_print_errors(bio_err);
1475 goto end;
1476 }
1477 if (s_chain_file) {
7e1b7485 1478 s_chain = load_certs(s_chain_file, FORMAT_PEM,
0f113f3e
MC
1479 NULL, e, "server certificate chain");
1480 if (!s_chain)
1481 goto end;
1482 }
e481f9b9 1483
0f113f3e 1484 if (tlsextcbp.servername) {
7e1b7485 1485 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, e,
0f113f3e
MC
1486 "second server certificate private key file");
1487 if (!s_key2) {
1488 ERR_print_errors(bio_err);
1489 goto end;
1490 }
1491
7e1b7485 1492 s_cert2 = load_cert(s_cert_file2, s_cert_format,
0f113f3e
MC
1493 NULL, e, "second server certificate file");
1494
1495 if (!s_cert2) {
1496 ERR_print_errors(bio_err);
1497 goto end;
1498 }
1499 }
0f113f3e 1500 }
e481f9b9 1501#if !defined(OPENSSL_NO_NEXTPROTONEG)
0f113f3e
MC
1502 if (next_proto_neg_in) {
1503 unsigned short len;
1504 next_proto.data = next_protos_parse(&len, next_proto_neg_in);
1505 if (next_proto.data == NULL)
1506 goto end;
1507 next_proto.len = len;
1508 } else {
1509 next_proto.data = NULL;
1510 }
e481f9b9 1511#endif
0f113f3e
MC
1512 alpn_ctx.data = NULL;
1513 if (alpn_in) {
1514 unsigned short len;
1515 alpn_ctx.data = next_protos_parse(&len, alpn_in);
1516 if (alpn_ctx.data == NULL)
1517 goto end;
1518 alpn_ctx.len = len;
1519 }
0f113f3e
MC
1520
1521 if (crl_file) {
1522 X509_CRL *crl;
1523 crl = load_crl(crl_file, crl_format);
1524 if (!crl) {
1525 BIO_puts(bio_err, "Error loading CRL\n");
1526 ERR_print_errors(bio_err);
1527 goto end;
1528 }
1529 crls = sk_X509_CRL_new_null();
1530 if (!crls || !sk_X509_CRL_push(crls, crl)) {
1531 BIO_puts(bio_err, "Error adding CRL\n");
1532 ERR_print_errors(bio_err);
1533 X509_CRL_free(crl);
1534 goto end;
1535 }
1536 }
1537
1538 if (s_dcert_file) {
d02b48c6 1539
0f113f3e
MC
1540 if (s_dkey_file == NULL)
1541 s_dkey_file = s_dcert_file;
1542
7e1b7485 1543 s_dkey = load_key(s_dkey_file, s_dkey_format,
0f113f3e
MC
1544 0, dpass, e, "second certificate private key file");
1545 if (!s_dkey) {
1546 ERR_print_errors(bio_err);
1547 goto end;
1548 }
1549
7e1b7485 1550 s_dcert = load_cert(s_dcert_file, s_dcert_format,
0f113f3e
MC
1551 NULL, e, "second server certificate file");
1552
1553 if (!s_dcert) {
1554 ERR_print_errors(bio_err);
1555 goto end;
1556 }
1557 if (s_dchain_file) {
7e1b7485 1558 s_dchain = load_certs(s_dchain_file, FORMAT_PEM,
0f113f3e
MC
1559 NULL, e, "second server certificate chain");
1560 if (!s_dchain)
1561 goto end;
1562 }
1563
1564 }
1565
7e1b7485 1566 if (!app_RAND_load_file(NULL, 1) && inrand == NULL
0f113f3e
MC
1567 && !RAND_status()) {
1568 BIO_printf(bio_err,
1569 "warning, not much extra random data, consider using the -rand option\n");
1570 }
1571 if (inrand != NULL)
1572 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1573 app_RAND_load_files(inrand));
1574
1575 if (bio_s_out == NULL) {
1576 if (s_quiet && !s_debug) {
1577 bio_s_out = BIO_new(BIO_s_null());
1578 if (s_msg && !bio_s_msg)
7e1b7485 1579 bio_s_msg = dup_bio_out();
0f113f3e
MC
1580 } else {
1581 if (bio_s_out == NULL)
7e1b7485 1582 bio_s_out = dup_bio_out();
0f113f3e
MC
1583 }
1584 }
10bf4fc2 1585#if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
0f113f3e 1586 if (nocert)
d02b48c6 1587#endif
0f113f3e
MC
1588 {
1589 s_cert_file = NULL;
1590 s_key_file = NULL;
1591 s_dcert_file = NULL;
1592 s_dkey_file = NULL;
0f113f3e
MC
1593 s_cert_file2 = NULL;
1594 s_key_file2 = NULL;
0f113f3e
MC
1595 }
1596
1597 ctx = SSL_CTX_new(meth);
1598 if (sdebug)
ecf3a1fb 1599 ssl_ctx_security_debug(ctx, sdebug);
0f113f3e
MC
1600 if (ctx == NULL) {
1601 ERR_print_errors(bio_err);
1602 goto end;
1603 }
1604 if (session_id_prefix) {
1605 if (strlen(session_id_prefix) >= 32)
1606 BIO_printf(bio_err,
1607 "warning: id_prefix is too long, only one new session will be possible\n");
1608 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1609 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1610 ERR_print_errors(bio_err);
1611 goto end;
1612 }
1613 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1614 }
1615 SSL_CTX_set_quiet_shutdown(ctx, 1);
0f113f3e
MC
1616 if (exc)
1617 ssl_ctx_set_excert(ctx, exc);
0f113f3e
MC
1618
1619 if (state)
1620 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1621 if (no_cache)
1622 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1623 else if (ext_cache)
1624 init_session_cache_ctx(ctx);
1625 else
1626 SSL_CTX_sess_set_cache_size(ctx, 128);
58964a49 1627
e783bae2 1628#ifndef OPENSSL_NO_SRTP
ac59d705 1629 if (srtp_profiles != NULL) {
7e1b7485
RS
1630 /* Returns 0 on success! */
1631 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
ac59d705
MC
1632 BIO_printf(bio_err, "Error setting SRTP profile\n");
1633 ERR_print_errors(bio_err);
1634 goto end;
1635 }
1636 }
e783bae2 1637#endif
333f926d 1638
7e1b7485 1639 if (!ctx_set_verify_locations(ctx, CAfile, CApath)) {
0f113f3e 1640 ERR_print_errors(bio_err);
7e1b7485 1641 goto end;
0f113f3e 1642 }
7e1b7485
RS
1643 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1644 BIO_printf(bio_err, "Error setting verify params\n");
ac59d705
MC
1645 ERR_print_errors(bio_err);
1646 goto end;
1647 }
0f113f3e
MC
1648
1649 ssl_ctx_add_crls(ctx, crls, 0);
7e1b7485 1650 if (!config_ctx(cctx, ssl_args, ctx, no_ecdhe, jpake_secret == NULL))
0f113f3e
MC
1651 goto end;
1652
1653 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1654 crls, crl_download)) {
1655 BIO_printf(bio_err, "Error loading store locations\n");
1656 ERR_print_errors(bio_err);
1657 goto end;
1658 }
e481f9b9 1659
0f113f3e
MC
1660 if (s_cert2) {
1661 ctx2 = SSL_CTX_new(meth);
1662 if (ctx2 == NULL) {
1663 ERR_print_errors(bio_err);
1664 goto end;
1665 }
1666 }
1667
1668 if (ctx2) {
1669 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1670
1671 if (sdebug)
ecf3a1fb 1672 ssl_ctx_security_debug(ctx, sdebug);
0f113f3e
MC
1673
1674 if (session_id_prefix) {
1675 if (strlen(session_id_prefix) >= 32)
1676 BIO_printf(bio_err,
1677 "warning: id_prefix is too long, only one new session will be possible\n");
1678 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1679 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1680 ERR_print_errors(bio_err);
1681 goto end;
1682 }
1683 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1684 }
1685 SSL_CTX_set_quiet_shutdown(ctx2, 1);
0f113f3e
MC
1686 if (exc)
1687 ssl_ctx_set_excert(ctx2, exc);
0f113f3e
MC
1688
1689 if (state)
1690 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1691
1692 if (no_cache)
1693 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1694 else if (ext_cache)
1695 init_session_cache_ctx(ctx2);
1696 else
1697 SSL_CTX_sess_set_cache_size(ctx2, 128);
1698
1699 if ((!SSL_CTX_load_verify_locations(ctx2, CAfile, CApath)) ||
1700 (!SSL_CTX_set_default_verify_paths(ctx2))) {
1701 ERR_print_errors(bio_err);
1702 }
7e1b7485
RS
1703 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1704 BIO_printf(bio_err, "Error setting verify params\n");
ac59d705
MC
1705 ERR_print_errors(bio_err);
1706 goto end;
1707 }
ee2ffc27 1708
0f113f3e 1709 ssl_ctx_add_crls(ctx2, crls, 0);
7e1b7485 1710 if (!config_ctx(cctx, ssl_args, ctx2, no_ecdhe, jpake_secret == NULL))
0f113f3e
MC
1711 goto end;
1712 }
e481f9b9 1713#ifndef OPENSSL_NO_NEXTPROTONEG
0f113f3e
MC
1714 if (next_proto.data)
1715 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1716 &next_proto);
e481f9b9 1717#endif
0f113f3e
MC
1718 if (alpn_ctx.data)
1719 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
b1277b99 1720
cf1b7d96 1721#ifndef OPENSSL_NO_DH
0f113f3e
MC
1722 if (!no_dhe) {
1723 DH *dh = NULL;
1724
1725 if (dhfile)
1726 dh = load_dh_param(dhfile);
1727 else if (s_cert_file)
1728 dh = load_dh_param(s_cert_file);
1729
1730 if (dh != NULL) {
1731 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1732 } else {
1733 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1734 }
1735 (void)BIO_flush(bio_s_out);
1736
1737 if (dh == NULL)
1738 SSL_CTX_set_dh_auto(ctx, 1);
1739 else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1740 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1741 ERR_print_errors(bio_err);
1742 DH_free(dh);
1743 goto end;
1744 }
e481f9b9 1745
0f113f3e
MC
1746 if (ctx2) {
1747 if (!dhfile) {
1748 DH *dh2 = load_dh_param(s_cert_file2);
1749 if (dh2 != NULL) {
1750 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1751 (void)BIO_flush(bio_s_out);
1752
1753 DH_free(dh);
1754 dh = dh2;
1755 }
1756 }
1757 if (dh == NULL)
1758 SSL_CTX_set_dh_auto(ctx2, 1);
1759 else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1760 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1761 ERR_print_errors(bio_err);
1762 DH_free(dh);
1763 goto end;
1764 }
1765 }
0f113f3e
MC
1766 DH_free(dh);
1767 }
ed3883d2 1768#endif
d02b48c6 1769
0f113f3e
MC
1770 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1771 goto end;
e481f9b9 1772
0f113f3e
MC
1773 if (s_serverinfo_file != NULL
1774 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1775 ERR_print_errors(bio_err);
1776 goto end;
1777 }
e481f9b9 1778
0f113f3e
MC
1779 if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1780 goto end;
e481f9b9 1781
0f113f3e
MC
1782 if (s_dcert != NULL) {
1783 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1784 goto end;
1785 }
1786#ifndef OPENSSL_NO_RSA
0f113f3e
MC
1787 if (!no_tmp_rsa) {
1788 SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb);
0f113f3e
MC
1789 if (ctx2)
1790 SSL_CTX_set_tmp_rsa_callback(ctx2, tmp_rsa_cb);
0f113f3e 1791 }
d02b48c6
RE
1792#endif
1793
0f113f3e
MC
1794 if (no_resume_ephemeral) {
1795 SSL_CTX_set_not_resumable_session_callback(ctx,
1796 not_resumable_sess_cb);
e481f9b9 1797
0f113f3e
MC
1798 if (ctx2)
1799 SSL_CTX_set_not_resumable_session_callback(ctx2,
1800 not_resumable_sess_cb);
0f113f3e 1801 }
ddac1974 1802#ifndef OPENSSL_NO_PSK
0f113f3e
MC
1803# ifdef OPENSSL_NO_JPAKE
1804 if (psk_key != NULL)
1805# else
1806 if (psk_key != NULL || jpake_secret)
1807# endif
1808 {
1809 if (s_debug)
1810 BIO_printf(bio_s_out,
1811 "PSK key given or JPAKE in use, setting server callback\n");
1812 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1813 }
ddac1974 1814
0f113f3e
MC
1815 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1816 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1817 ERR_print_errors(bio_err);
1818 goto end;
1819 }
ddac1974
NL
1820#endif
1821
0f113f3e 1822 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
61986d32 1823 if (!SSL_CTX_set_session_id_context(ctx,
7e1b7485
RS
1824 (void *)&s_server_session_id_context,
1825 sizeof s_server_session_id_context)) {
ac59d705
MC
1826 BIO_printf(bio_err, "error setting session id context\n");
1827 ERR_print_errors(bio_err);
1828 goto end;
1829 }
d02b48c6 1830
0f113f3e
MC
1831 /* Set DTLS cookie generation and verification callbacks */
1832 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1833 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
07a9d1a2 1834
0f113f3e
MC
1835 if (ctx2) {
1836 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
61986d32 1837 if (!SSL_CTX_set_session_id_context(ctx2,
7e1b7485
RS
1838 (void *)&s_server_session_id_context,
1839 sizeof s_server_session_id_context)) {
ac59d705
MC
1840 BIO_printf(bio_err, "error setting session id context\n");
1841 ERR_print_errors(bio_err);
1842 goto end;
1843 }
0f113f3e
MC
1844 tlsextcbp.biodebug = bio_s_out;
1845 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1846 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1847 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1848 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1849 }
f1fd4544 1850
edc032b5 1851#ifndef OPENSSL_NO_SRP
0f113f3e
MC
1852 if (srp_verifier_file != NULL) {
1853 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1854 srp_callback_parm.user = NULL;
1855 srp_callback_parm.login = NULL;
1856 if ((ret =
1857 SRP_VBASE_init(srp_callback_parm.vb,
1858 srp_verifier_file)) != SRP_NO_ERROR) {
1859 BIO_printf(bio_err,
1860 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1861 srp_verifier_file, ret);
1862 goto end;
1863 }
1864 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
1865 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
1866 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1867 } else
1868#endif
1869 if (CAfile != NULL) {
1870 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
e481f9b9 1871
0f113f3e
MC
1872 if (ctx2)
1873 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
0f113f3e
MC
1874 }
1875
1876 BIO_printf(bio_s_out, "ACCEPT\n");
1877 (void)BIO_flush(bio_s_out);
1878 if (rev)
1879 server_cb = rev_body;
1880 else if (www)
1881 server_cb = www_body;
1882 else
1883 server_cb = sv_body;
9cd86abb 1884#ifndef NO_SYS_UN_H
0f113f3e
MC
1885 if (unix_path) {
1886 if (unlink_unix_path)
1887 unlink(unix_path);
1888 do_server_unix(unix_path, &accept_socket, server_cb, context,
1889 naccept);
1890 } else
1891#endif
1892 do_server(port, socket_type, &accept_socket, server_cb, context,
1893 naccept);
1894 print_stats(bio_s_out, ctx);
1895 ret = 0;
1896 end:
62adbcee 1897 SSL_CTX_free(ctx);
222561fe
RS
1898 X509_free(s_cert);
1899 sk_X509_CRL_pop_free(crls, X509_CRL_free);
1900 X509_free(s_dcert);
c5ba2d99
RS
1901 EVP_PKEY_free(s_key);
1902 EVP_PKEY_free(s_dkey);
222561fe
RS
1903 sk_X509_pop_free(s_chain, X509_free);
1904 sk_X509_pop_free(s_dchain, X509_free);
25aaa98a
RS
1905 OPENSSL_free(pass);
1906 OPENSSL_free(dpass);
222561fe 1907 X509_VERIFY_PARAM_free(vpm);
0f113f3e 1908 free_sessions();
25aaa98a
RS
1909 OPENSSL_free(tlscstatp.host);
1910 OPENSSL_free(tlscstatp.port);
1911 OPENSSL_free(tlscstatp.path);
62adbcee 1912 SSL_CTX_free(ctx2);
222561fe 1913 X509_free(s_cert2);
c5ba2d99 1914 EVP_PKEY_free(s_key2);
ca3a82c3 1915 BIO_free(serverinfo_in);
e481f9b9 1916#ifndef OPENSSL_NO_NEXTPROTONEG
25aaa98a 1917 OPENSSL_free(next_proto.data);
0f113f3e 1918#endif
e481f9b9 1919 OPENSSL_free(alpn_ctx.data);
0f113f3e 1920 ssl_excert_free(exc);
7e1b7485 1921 sk_OPENSSL_STRING_free(ssl_args);
62adbcee 1922 SSL_CONF_CTX_free(cctx);
ca3a82c3
RS
1923 BIO_free(bio_s_out);
1924 bio_s_out = NULL;
1925 BIO_free(bio_s_msg);
1926 bio_s_msg = NULL;
7e1b7485 1927 return (ret);
0f113f3e 1928}
d02b48c6 1929
6b691a5c 1930static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
0f113f3e
MC
1931{
1932 BIO_printf(bio, "%4ld items in the session cache\n",
1933 SSL_CTX_sess_number(ssl_ctx));
1934 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
1935 SSL_CTX_sess_connect(ssl_ctx));
1936 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
1937 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
1938 BIO_printf(bio, "%4ld client connects that finished\n",
1939 SSL_CTX_sess_connect_good(ssl_ctx));
1940 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
1941 SSL_CTX_sess_accept(ssl_ctx));
1942 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
1943 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
1944 BIO_printf(bio, "%4ld server accepts that finished\n",
1945 SSL_CTX_sess_accept_good(ssl_ctx));
1946 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
1947 BIO_printf(bio, "%4ld session cache misses\n",
1948 SSL_CTX_sess_misses(ssl_ctx));
1949 BIO_printf(bio, "%4ld session cache timeouts\n",
1950 SSL_CTX_sess_timeouts(ssl_ctx));
1951 BIO_printf(bio, "%4ld callback cache hits\n",
1952 SSL_CTX_sess_cb_hits(ssl_ctx));
1953 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
1954 SSL_CTX_sess_cache_full(ssl_ctx),
1955 SSL_CTX_sess_get_cache_size(ssl_ctx));
1956}
d02b48c6 1957
c3b344e3 1958static int sv_body(char *hostname, int s, int stype, unsigned char *context)
0f113f3e
MC
1959{
1960 char *buf = NULL;
1961 fd_set readfds;
1962 int ret = 1, width;
1963 int k, i;
1964 unsigned long l;
1965 SSL *con = NULL;
1966 BIO *sbio;
0f113f3e 1967 struct timeval timeout;
b317819b 1968#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
0f113f3e 1969 struct timeval tv;
ba4526e0 1970#else
0f113f3e 1971 struct timeval *timeoutp;
06f4536a 1972#endif
d02b48c6 1973
68dc6824 1974 buf = app_malloc(bufsize, "server buffer");
0f113f3e
MC
1975#ifdef FIONBIO
1976 if (s_nbio) {
1977 unsigned long sl = 1;
d02b48c6 1978
0f113f3e
MC
1979 if (!s_quiet)
1980 BIO_printf(bio_err, "turning on non blocking io\n");
1981 if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)
1982 ERR_print_errors(bio_err);
1983 }
d02b48c6
RE
1984#endif
1985
0f113f3e
MC
1986 if (con == NULL) {
1987 con = SSL_new(ctx);
e481f9b9 1988
0f113f3e
MC
1989 if (s_tlsextdebug) {
1990 SSL_set_tlsext_debug_callback(con, tlsext_cb);
1991 SSL_set_tlsext_debug_arg(con, bio_s_out);
1992 }
1993 if (s_tlsextstatus) {
1994 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
0f113f3e
MC
1995 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1996 }
e481f9b9 1997
7e1b7485
RS
1998 if (context
1999 && !SSL_set_session_id_context(con,
2000 context, strlen((char *)context))) {
ac59d705
MC
2001 BIO_printf(bio_err, "Error setting session id context\n");
2002 ret = -1;
2003 goto err;
2004 }
2005 }
61986d32 2006 if (!SSL_clear(con)) {
ac59d705
MC
2007 BIO_printf(bio_err, "Error clearing SSL connection\n");
2008 ret = -1;
2009 goto err;
0f113f3e 2010 }
0f113f3e
MC
2011
2012 if (stype == SOCK_DGRAM) {
2013
2014 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2015
2016 if (enable_timeouts) {
2017 timeout.tv_sec = 0;
2018 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2019 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2020
2021 timeout.tv_sec = 0;
2022 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2023 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2024 }
2025
2026 if (socket_mtu) {
2027 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2028 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2029 DTLS_get_link_min_mtu(con));
2030 ret = -1;
2031 BIO_free(sbio);
2032 goto err;
2033 }
2034 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2035 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2036 BIO_printf(bio_err, "Failed to set MTU\n");
2037 ret = -1;
2038 BIO_free(sbio);
2039 goto err;
2040 }
2041 } else
2042 /* want to do MTU discovery */
2043 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
36d16f8e
BL
2044
2045 /* turn on cookie exchange */
2046 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
0f113f3e
MC
2047 } else
2048 sbio = BIO_new_socket(s, BIO_NOCLOSE);
36d16f8e 2049
0f113f3e
MC
2050 if (s_nbio_test) {
2051 BIO *test;
d02b48c6 2052
0f113f3e
MC
2053 test = BIO_new(BIO_f_nbio_test());
2054 sbio = BIO_push(test, sbio);
2055 }
79bd20fd 2056#ifndef OPENSSL_NO_JPAKE
0f113f3e
MC
2057 if (jpake_secret)
2058 jpake_server_auth(bio_s_out, sbio, jpake_secret);
2059#endif
2060
2061 SSL_set_bio(con, sbio, sbio);
2062 SSL_set_accept_state(con);
2063 /* SSL_set_fd(con,s); */
2064
2065 if (s_debug) {
2066 SSL_set_debug(con, 1);
2067 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2068 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2069 }
2070 if (s_msg) {
93ab9e42 2071#ifndef OPENSSL_NO_SSL_TRACE
0f113f3e
MC
2072 if (s_msg == 2)
2073 SSL_set_msg_callback(con, SSL_trace);
2074 else
93ab9e42 2075#endif
0f113f3e
MC
2076 SSL_set_msg_callback(con, msg_cb);
2077 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2078 }
e481f9b9 2079
0f113f3e
MC
2080 if (s_tlsextdebug) {
2081 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2082 SSL_set_tlsext_debug_arg(con, bio_s_out);
2083 }
d02b48c6 2084
0f113f3e
MC
2085 width = s + 1;
2086 for (;;) {
2087 int read_from_terminal;
2088 int read_from_sslcon;
a2a01589 2089
0f113f3e
MC
2090 read_from_terminal = 0;
2091 read_from_sslcon = SSL_pending(con);
a2a01589 2092
0f113f3e
MC
2093 if (!read_from_sslcon) {
2094 FD_ZERO(&readfds);
b317819b 2095#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE)
0f113f3e
MC
2096 openssl_fdset(fileno(stdin), &readfds);
2097#endif
2098 openssl_fdset(s, &readfds);
2099 /*
2100 * Note: under VMS with SOCKETSHR the second parameter is
2101 * currently of type (int *) whereas under other systems it is
2102 * (void *) if you don't have a cast it will choke the compiler:
2103 * if you do have a cast then you can either go for (int *) or
2104 * (void *).
2105 */
4d8743f4 2106#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
0f113f3e
MC
2107 /*
2108 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2109 * only on sockets. As a workaround we timeout the select every
2110 * second and check for any keypress. In a proper Windows
2111 * application we wouldn't do this because it is inefficient.
2112 */
2113 tv.tv_sec = 1;
2114 tv.tv_usec = 0;
2115 i = select(width, (void *)&readfds, NULL, NULL, &tv);
2116 if ((i < 0) || (!i && !_kbhit()))
2117 continue;
2118 if (_kbhit())
2119 read_from_terminal = 1;
06f4536a 2120#else
0f113f3e
MC
2121 if ((SSL_version(con) == DTLS1_VERSION) &&
2122 DTLSv1_get_timeout(con, &timeout))
2123 timeoutp = &timeout;
2124 else
2125 timeoutp = NULL;
2126
2127 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2128
2129 if ((SSL_version(con) == DTLS1_VERSION)
2130 && DTLSv1_handle_timeout(con) > 0) {
2131 BIO_printf(bio_err, "TIMEOUT occurred\n");
2132 }
2133
2134 if (i <= 0)
2135 continue;
2136 if (FD_ISSET(fileno(stdin), &readfds))
2137 read_from_terminal = 1;
2138#endif
2139 if (FD_ISSET(s, &readfds))
2140 read_from_sslcon = 1;
2141 }
2142 if (read_from_terminal) {
2143 if (s_crlf) {
2144 int j, lf_num;
2145
2146 i = raw_read_stdin(buf, bufsize / 2);
2147 lf_num = 0;
2148 /* both loops are skipped when i <= 0 */
2149 for (j = 0; j < i; j++)
2150 if (buf[j] == '\n')
2151 lf_num++;
2152 for (j = i - 1; j >= 0; j--) {
2153 buf[j + lf_num] = buf[j];
2154 if (buf[j] == '\n') {
2155 lf_num--;
2156 i++;
2157 buf[j + lf_num] = '\r';
2158 }
2159 }
2160 assert(lf_num == 0);
2161 } else
2162 i = raw_read_stdin(buf, bufsize);
2163 if (!s_quiet && !s_brief) {
2164 if ((i <= 0) || (buf[0] == 'Q')) {
2165 BIO_printf(bio_s_out, "DONE\n");
7e1b7485 2166 (void)BIO_flush(bio_s_out);
0f113f3e
MC
2167 SHUTDOWN(s);
2168 close_accept_socket();
2169 ret = -11;
2170 goto err;
2171 }
2172 if ((i <= 0) || (buf[0] == 'q')) {
2173 BIO_printf(bio_s_out, "DONE\n");
7e1b7485 2174 (void)BIO_flush(bio_s_out);
0f113f3e 2175 if (SSL_version(con) != DTLS1_VERSION)
36d16f8e 2176 SHUTDOWN(s);
0f113f3e
MC
2177 /*
2178 * close_accept_socket(); ret= -11;
2179 */
2180 goto err;
2181 }
4817504d 2182#ifndef OPENSSL_NO_HEARTBEATS
0f113f3e
MC
2183 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2184 BIO_printf(bio_err, "HEARTBEATING\n");
2185 SSL_heartbeat(con);
2186 i = 0;
2187 continue;
2188 }
2189#endif
2190 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2191 SSL_renegotiate(con);
2192 i = SSL_do_handshake(con);
2193 printf("SSL_do_handshake -> %d\n", i);
2194 i = 0; /* 13; */
2195 continue;
2196 /*
2197 * strcpy(buf,"server side RE-NEGOTIATE\n");
2198 */
2199 }
2200 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2201 SSL_set_verify(con,
2202 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2203 NULL);
2204 SSL_renegotiate(con);
2205 i = SSL_do_handshake(con);
2206 printf("SSL_do_handshake -> %d\n", i);
2207 i = 0; /* 13; */
2208 continue;
2209 /*
2210 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2211 * cert\n");
2212 */
2213 }
2214 if (buf[0] == 'P') {
2215 static const char *str = "Lets print some clear text\n";
2216 BIO_write(SSL_get_wbio(con), str, strlen(str));
2217 }
2218 if (buf[0] == 'S') {
2219 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2220 }
2221 }
a53955d8 2222#ifdef CHARSET_EBCDIC
0f113f3e 2223 ebcdic2ascii(buf, buf, i);
a53955d8 2224#endif
0f113f3e
MC
2225 l = k = 0;
2226 for (;;) {
2227 /* should do a select for the write */
58964a49 2228#ifdef RENEG
0f113f3e
MC
2229 {
2230 static count = 0;
2231 if (++count == 100) {
2232 count = 0;
2233 SSL_renegotiate(con);
2234 }
2235 }
d02b48c6 2236#endif
0f113f3e 2237 k = SSL_write(con, &(buf[l]), (unsigned int)i);
9641be2a 2238#ifndef OPENSSL_NO_SRP
0f113f3e
MC
2239 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2240 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2241 srp_callback_parm.user =
2242 SRP_VBASE_get_by_user(srp_callback_parm.vb,
2243 srp_callback_parm.login);
2244 if (srp_callback_parm.user)
2245 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2246 srp_callback_parm.user->info);
2247 else
2248 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2249 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2250 }
2251#endif
2252 switch (SSL_get_error(con, k)) {
2253 case SSL_ERROR_NONE:
2254 break;
2255 case SSL_ERROR_WANT_WRITE:
2256 case SSL_ERROR_WANT_READ:
2257 case SSL_ERROR_WANT_X509_LOOKUP:
2258 BIO_printf(bio_s_out, "Write BLOCK\n");
2259 break;
2260 case SSL_ERROR_SYSCALL:
2261 case SSL_ERROR_SSL:
2262 BIO_printf(bio_s_out, "ERROR\n");
7e1b7485 2263 (void)BIO_flush(bio_s_out);
0f113f3e
MC
2264 ERR_print_errors(bio_err);
2265 ret = 1;
2266 goto err;
2267 /* break; */
2268 case SSL_ERROR_ZERO_RETURN:
2269 BIO_printf(bio_s_out, "DONE\n");
7e1b7485 2270 (void)BIO_flush(bio_s_out);
0f113f3e
MC
2271 ret = 1;
2272 goto err;
2273 }
00d565cf
RS
2274 if (k > 0) {
2275 l += k;
2276 i -= k;
2277 }
0f113f3e
MC
2278 if (i <= 0)
2279 break;
2280 }
2281 }
2282 if (read_from_sslcon) {
2283 if (!SSL_is_init_finished(con)) {
2284 i = init_ssl_connection(con);
2285
2286 if (i < 0) {
2287 ret = 0;
2288 goto err;
2289 } else if (i == 0) {
2290 ret = 1;
2291 goto err;
2292 }
2293 } else {
2294 again:
2295 i = SSL_read(con, (char *)buf, bufsize);
9641be2a 2296#ifndef OPENSSL_NO_SRP
0f113f3e
MC
2297 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2298 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2299 srp_callback_parm.user =
2300 SRP_VBASE_get_by_user(srp_callback_parm.vb,
2301 srp_callback_parm.login);
2302 if (srp_callback_parm.user)
2303 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2304 srp_callback_parm.user->info);
2305 else
2306 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2307 i = SSL_read(con, (char *)buf, bufsize);
2308 }
2309#endif
2310 switch (SSL_get_error(con, i)) {
2311 case SSL_ERROR_NONE:
a53955d8 2312#ifdef CHARSET_EBCDIC
0f113f3e
MC
2313 ascii2ebcdic(buf, buf, i);
2314#endif
2315 raw_write_stdout(buf, (unsigned int)i);
2316 if (SSL_pending(con))
2317 goto again;
2318 break;
2319 case SSL_ERROR_WANT_WRITE:
2320 case SSL_ERROR_WANT_READ:
2321 BIO_printf(bio_s_out, "Read BLOCK\n");
2322 break;
2323 case SSL_ERROR_SYSCALL:
2324 case SSL_ERROR_SSL:
2325 BIO_printf(bio_s_out, "ERROR\n");
7e1b7485 2326 (void)BIO_flush(bio_s_out);
0f113f3e
MC
2327 ERR_print_errors(bio_err);
2328 ret = 1;
2329 goto err;
2330 case SSL_ERROR_ZERO_RETURN:
2331 BIO_printf(bio_s_out, "DONE\n");
7e1b7485 2332 (void)BIO_flush(bio_s_out);
0f113f3e
MC
2333 ret = 1;
2334 goto err;
2335 }
2336 }
2337 }
2338 }
2339 err:
2340 if (con != NULL) {
2341 BIO_printf(bio_s_out, "shutting down SSL\n");
0f113f3e 2342 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
0f113f3e
MC
2343 SSL_free(con);
2344 }
2345 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
4b45c6e5 2346 OPENSSL_clear_free(buf, bufsize);
0f113f3e
MC
2347 if (ret >= 0)
2348 BIO_printf(bio_s_out, "ACCEPT\n");
c54cc2b1 2349 (void)BIO_flush(bio_s_out);
0f113f3e
MC
2350 return (ret);
2351}
d02b48c6 2352
6b691a5c 2353static void close_accept_socket(void)
0f113f3e
MC
2354{
2355 BIO_printf(bio_err, "shutdown accept socket\n");
2356 if (accept_socket >= 0) {
2357 SHUTDOWN2(accept_socket);
2358 }
2359}
d02b48c6 2360
6b691a5c 2361static int init_ssl_connection(SSL *con)
0f113f3e
MC
2362{
2363 int i;
2364 const char *str;
2365 X509 *peer;
2366 long verify_error;
68b00c23 2367 char buf[BUFSIZ];
e481f9b9 2368#if !defined(OPENSSL_NO_NEXTPROTONEG)
0f113f3e
MC
2369 const unsigned char *next_proto_neg;
2370 unsigned next_proto_neg_len;
4f7a2ab8 2371#endif
0f113f3e 2372 unsigned char *exportedkeymat;
d02b48c6 2373
0f113f3e 2374 i = SSL_accept(con);
3323314f 2375#ifdef CERT_CB_TEST_RETRY
0f113f3e
MC
2376 {
2377 while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2378 && SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) {
2379 fprintf(stderr,
2380 "LOOKUP from certificate callback during accept\n");
2381 i = SSL_accept(con);
2382 }
2383 }
3323314f 2384#endif
9641be2a 2385#ifndef OPENSSL_NO_SRP
0f113f3e
MC
2386 while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2387 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2388 srp_callback_parm.login);
2389 srp_callback_parm.user =
2390 SRP_VBASE_get_by_user(srp_callback_parm.vb,
2391 srp_callback_parm.login);
2392 if (srp_callback_parm.user)
2393 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2394 srp_callback_parm.user->info);
2395 else
2396 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2397 i = SSL_accept(con);
2398 }
2399#endif
2400
2401 if (i <= 0) {
2402 if (BIO_sock_should_retry(i)) {
2403 BIO_printf(bio_s_out, "DELAY\n");
2404 return (1);
2405 }
2406
2407 BIO_printf(bio_err, "ERROR\n");
7e1b7485 2408
0f113f3e
MC
2409 verify_error = SSL_get_verify_result(con);
2410 if (verify_error != X509_V_OK) {
2411 BIO_printf(bio_err, "verify error:%s\n",
2412 X509_verify_cert_error_string(verify_error));
2413 }
2414 /* Always print any error messages */
2415 ERR_print_errors(bio_err);
2416 return (0);
2417 }
2418
2419 if (s_brief)
ecf3a1fb 2420 print_ssl_summary(con);
0f113f3e
MC
2421
2422 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2423
2424 peer = SSL_get_peer_certificate(con);
2425 if (peer != NULL) {
2426 BIO_printf(bio_s_out, "Client certificate\n");
2427 PEM_write_bio_X509(bio_s_out, peer);
2428 X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
2429 BIO_printf(bio_s_out, "subject=%s\n", buf);
2430 X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
2431 BIO_printf(bio_s_out, "issuer=%s\n", buf);
2432 X509_free(peer);
2433 }
2434
2435 if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2436 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2437 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2438 ssl_print_sigalgs(bio_s_out, con);
14536c8c 2439#ifndef OPENSSL_NO_EC
0f113f3e
MC
2440 ssl_print_point_formats(bio_s_out, con);
2441 ssl_print_curves(bio_s_out, con, 0);
14536c8c 2442#endif
0f113f3e 2443 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
e7f8ff43 2444
e481f9b9 2445#if !defined(OPENSSL_NO_NEXTPROTONEG)
0f113f3e
MC
2446 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2447 if (next_proto_neg) {
2448 BIO_printf(bio_s_out, "NEXTPROTO is ");
2449 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2450 BIO_printf(bio_s_out, "\n");
2451 }
ee2ffc27 2452#endif
e783bae2 2453#ifndef OPENSSL_NO_SRTP
0f113f3e
MC
2454 {
2455 SRTP_PROTECTION_PROFILE *srtp_profile
2456 = SSL_get_selected_srtp_profile(con);
2457
2458 if (srtp_profile)
2459 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2460 srtp_profile->name);
2461 }
2462#endif
2463 if (SSL_cache_hit(con))
2464 BIO_printf(bio_s_out, "Reused session-id\n");
2465 if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) &
2466 TLS1_FLAGS_TLS_PADDING_BUG)
2467 BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n");
0f113f3e
MC
2468 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2469 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2470 if (keymatexportlabel != NULL) {
2471 BIO_printf(bio_s_out, "Keying material exporter:\n");
2472 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2473 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
68dc6824
RS
2474 exportedkeymat = app_malloc(keymatexportlen, "export key");
2475 if (!SSL_export_keying_material(con, exportedkeymat,
2476 keymatexportlen,
2477 keymatexportlabel,
2478 strlen(keymatexportlabel),
2479 NULL, 0, 0)) {
2480 BIO_printf(bio_s_out, " Error\n");
2481 } else {
2482 BIO_printf(bio_s_out, " Keying material: ");
2483 for (i = 0; i < keymatexportlen; i++)
2484 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2485 BIO_printf(bio_s_out, "\n");
0f113f3e 2486 }
68dc6824 2487 OPENSSL_free(exportedkeymat);
0f113f3e
MC
2488 }
2489
2490 return (1);
2491}
d02b48c6 2492
cf1b7d96 2493#ifndef OPENSSL_NO_DH
eb3eab20 2494static DH *load_dh_param(const char *dhfile)
0f113f3e
MC
2495{
2496 DH *ret = NULL;
2497 BIO *bio;
2498
2499 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2500 goto err;
2501 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2502 err:
ca3a82c3 2503 BIO_free(bio);
0f113f3e
MC
2504 return (ret);
2505}
58964a49 2506#endif
d02b48c6 2507
c3b344e3 2508static int www_body(char *hostname, int s, int stype, unsigned char *context)
0f113f3e
MC
2509{
2510 char *buf = NULL;
2511 int ret = 1;
2512 int i, j, k, dot;
2513 SSL *con;
2514 const SSL_CIPHER *c;
2515 BIO *io, *ssl_bio, *sbio;
7e1b7485
RS
2516#ifdef RENEG
2517 int total_bytes = 0;
2518#endif
d02b48c6 2519
68dc6824 2520 buf = app_malloc(bufsize, "server www buffer");
0f113f3e
MC
2521 io = BIO_new(BIO_f_buffer());
2522 ssl_bio = BIO_new(BIO_f_ssl());
2523 if ((io == NULL) || (ssl_bio == NULL))
2524 goto err;
d02b48c6 2525
0f113f3e
MC
2526#ifdef FIONBIO
2527 if (s_nbio) {
2528 unsigned long sl = 1;
d02b48c6 2529
0f113f3e
MC
2530 if (!s_quiet)
2531 BIO_printf(bio_err, "turning on non blocking io\n");
2532 if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)
2533 ERR_print_errors(bio_err);
2534 }
d02b48c6
RE
2535#endif
2536
0f113f3e
MC
2537 /* lets make the output buffer a reasonable size */
2538 if (!BIO_set_write_buffer_size(io, bufsize))
2539 goto err;
d02b48c6 2540
0f113f3e
MC
2541 if ((con = SSL_new(ctx)) == NULL)
2542 goto err;
e481f9b9 2543
0f113f3e
MC
2544 if (s_tlsextdebug) {
2545 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2546 SSL_set_tlsext_debug_arg(con, bio_s_out);
2547 }
e481f9b9 2548
ac59d705 2549 if (context && !SSL_set_session_id_context(con, context,
7e1b7485 2550 strlen((char *)context)))
ac59d705 2551 goto err;
0f113f3e
MC
2552
2553 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2554 if (s_nbio_test) {
2555 BIO *test;
2556
2557 test = BIO_new(BIO_f_nbio_test());
2558 sbio = BIO_push(test, sbio);
2559 }
2560 SSL_set_bio(con, sbio, sbio);
2561 SSL_set_accept_state(con);
2562
2563 /* SSL_set_fd(con,s); */
2564 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2565 BIO_push(io, ssl_bio);
a53955d8 2566#ifdef CHARSET_EBCDIC
0f113f3e 2567 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
a53955d8 2568#endif
d02b48c6 2569
0f113f3e
MC
2570 if (s_debug) {
2571 SSL_set_debug(con, 1);
2572 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2573 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2574 }
2575 if (s_msg) {
93ab9e42 2576#ifndef OPENSSL_NO_SSL_TRACE
0f113f3e
MC
2577 if (s_msg == 2)
2578 SSL_set_msg_callback(con, SSL_trace);
2579 else
2580#endif
2581 SSL_set_msg_callback(con, msg_cb);
2582 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2583 }
2584
2585 for (;;) {
0f113f3e
MC
2586 i = BIO_gets(io, buf, bufsize - 1);
2587 if (i < 0) { /* error */
2588 if (!BIO_should_retry(io)) {
2589 if (!s_quiet)
2590 ERR_print_errors(bio_err);
2591 goto err;
2592 } else {
2593 BIO_printf(bio_s_out, "read R BLOCK\n");
4d8743f4 2594#if defined(OPENSSL_SYS_NETWARE)
0f113f3e 2595 delay(1000);
f642ebc1 2596#elif !defined(OPENSSL_SYS_MSDOS)
0f113f3e
MC
2597 sleep(1);
2598#endif
2599 continue;
2600 }
2601 } else if (i == 0) { /* end of input */
2602 ret = 1;
2603 goto end;
2604 }
d02b48c6 2605
0f113f3e
MC
2606 /* else we have data */
2607 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
0b142f02 2608 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
0f113f3e
MC
2609 char *p;
2610 X509 *peer;
2611 STACK_OF(SSL_CIPHER) *sk;
2612 static const char *space = " ";
2613
2614 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2615 if (strncmp("GET /renegcert", buf, 14) == 0)
2616 SSL_set_verify(con,
2617 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2618 NULL);
2619 i = SSL_renegotiate(con);
2620 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2621 i = SSL_do_handshake(con);
2622 if (i <= 0) {
2623 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2624 SSL_get_error(con, i));
2625 ERR_print_errors(bio_err);
2626 goto err;
2627 }
2628 /* EVIL HACK! */
2629 SSL_set_state(con, SSL_ST_ACCEPT);
2630 i = SSL_do_handshake(con);
2631 BIO_printf(bio_s_out, "SSL_do_handshake -> %d\n", i);
2632 if (i <= 0) {
2633 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2634 SSL_get_error(con, i));
2635 ERR_print_errors(bio_err);
2636 goto err;
2637 }
2638 }
2639
2640 BIO_puts(io,
2641 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2642 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2643 BIO_puts(io, "<pre>\n");
2644/* BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
2645 BIO_puts(io, "\n");
2646 for (i = 0; i < local_argc; i++) {
f92beb98
RS
2647 const char *myp;
2648 for (myp = local_argv[i]; *myp; myp++)
2649 switch (*myp) {
2650 case '<':
2651 BIO_puts(io, "&lt;");
2652 break;
2653 case '>':
2654 BIO_puts(io, "&gt;");
2655 break;
2656 case '&':
2657 BIO_puts(io, "&amp;");
2658 break;
2659 default:
2660 BIO_write(io, myp, 1);
2661 break;
2662 }
0f113f3e
MC
2663 BIO_write(io, " ", 1);
2664 }
2665 BIO_puts(io, "\n");
2666
2667 BIO_printf(io,
2668 "Secure Renegotiation IS%s supported\n",
2669 SSL_get_secure_renegotiation_support(con) ?
2670 "" : " NOT");
2671
2672 /*
2673 * The following is evil and should not really be done
2674 */
2675 BIO_printf(io, "Ciphers supported in s_server binary\n");
2676 sk = SSL_get_ciphers(con);
2677 j = sk_SSL_CIPHER_num(sk);
2678 for (i = 0; i < j; i++) {
2679 c = sk_SSL_CIPHER_value(sk, i);
7e1b7485 2680 BIO_printf(io, "%-11s:%-25s ",
0f113f3e
MC
2681 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2682 if ((((i + 1) % 2) == 0) && (i + 1 != j))
2683 BIO_puts(io, "\n");
2684 }
2685 BIO_puts(io, "\n");
2686 p = SSL_get_shared_ciphers(con, buf, bufsize);
2687 if (p != NULL) {
2688 BIO_printf(io,
2689 "---\nCiphers common between both SSL end points:\n");
2690 j = i = 0;
2691 while (*p) {
2692 if (*p == ':') {
2693 BIO_write(io, space, 26 - j);
2694 i++;
2695 j = 0;
2696 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
2697 } else {
2698 BIO_write(io, p, 1);
2699 j++;
2700 }
2701 p++;
2702 }
2703 BIO_puts(io, "\n");
2704 }
2705 ssl_print_sigalgs(io, con);
2706#ifndef OPENSSL_NO_EC
2707 ssl_print_curves(io, con, 0);
2708#endif
2709 BIO_printf(io, (SSL_cache_hit(con)
2710 ? "---\nReused, " : "---\nNew, "));
2711 c = SSL_get_current_cipher(con);
2712 BIO_printf(io, "%s, Cipher is %s\n",
2713 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2714 SSL_SESSION_print(io, SSL_get_session(con));
2715 BIO_printf(io, "---\n");
2716 print_stats(io, SSL_get_SSL_CTX(con));
2717 BIO_printf(io, "---\n");
2718 peer = SSL_get_peer_certificate(con);
2719 if (peer != NULL) {
2720 BIO_printf(io, "Client certificate\n");
2721 X509_print(io, peer);
2722 PEM_write_bio_X509(io, peer);
2723 } else
2724 BIO_puts(io, "no client certificate available\n");
2725 BIO_puts(io, "</BODY></HTML>\r\n\r\n");
2726 break;
2727 } else if ((www == 2 || www == 3)
2728 && (strncmp("GET /", buf, 5) == 0)) {
2729 BIO *file;
2730 char *p, *e;
2731 static const char *text =
2732 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2733
2734 /* skip the '/' */
2735 p = &(buf[5]);
2736
2737 dot = 1;
2738 for (e = p; *e != '\0'; e++) {
2739 if (e[0] == ' ')
2740 break;
2741
2742 switch (dot) {
2743 case 1:
2744 dot = (e[0] == '.') ? 2 : 0;
2745 break;
2746 case 2:
2747 dot = (e[0] == '.') ? 3 : 0;
2748 break;
2749 case 3:
2750 dot = (e[0] == '/') ? -1 : 0;
2751 break;
2752 }
2753 if (dot == 0)
2754 dot = (e[0] == '/') ? 1 : 0;
2755 }
2756 dot = (dot == 3) || (dot == -1); /* filename contains ".."
2757 * component */
2758
2759 if (*e == '\0') {
2760 BIO_puts(io, text);
2761 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
2762 break;
2763 }
2764 *e = '\0';
2765
2766 if (dot) {
2767 BIO_puts(io, text);
2768 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
2769 break;
2770 }
2771
2772 if (*p == '/') {
2773 BIO_puts(io, text);
2774 BIO_printf(io, "'%s' is an invalid path\r\n", p);
2775 break;
2776 }
d02b48c6 2777
0f113f3e
MC
2778 /* if a directory, do the index thang */
2779 if (app_isdir(p) > 0) {
0f113f3e
MC
2780 BIO_puts(io, text);
2781 BIO_printf(io, "'%s' is a directory\r\n", p);
2782 break;
0f113f3e
MC
2783 }
2784
2785 if ((file = BIO_new_file(p, "r")) == NULL) {
2786 BIO_puts(io, text);
2787 BIO_printf(io, "Error opening '%s'\r\n", p);
2788 ERR_print_errors(io);
2789 break;
2790 }
2791
2792 if (!s_quiet)
2793 BIO_printf(bio_err, "FILE:%s\n", p);
2794
2795 if (www == 2) {
2796 i = strlen(p);
2797 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
2798 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
2799 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
2800 BIO_puts(io,
2801 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2802 else
2803 BIO_puts(io,
2804 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2805 }
2806 /* send the file */
2807 for (;;) {
2808 i = BIO_read(file, buf, bufsize);
2809 if (i <= 0)
2810 break;
d02b48c6 2811
dfeab068 2812#ifdef RENEG
0f113f3e
MC
2813 total_bytes += i;
2814 fprintf(stderr, "%d\n", i);
2815 if (total_bytes > 3 * 1024) {
2816 total_bytes = 0;
2817 fprintf(stderr, "RENEGOTIATE\n");
2818 SSL_renegotiate(con);
2819 }
2820#endif
2821
2822 for (j = 0; j < i;) {
58964a49 2823#ifdef RENEG
0f113f3e
MC
2824 {
2825 static count = 0;
2826 if (++count == 13) {
2827 SSL_renegotiate(con);
2828 }
2829 }
2830#endif
2831 k = BIO_write(io, &(buf[j]), i - j);
2832 if (k <= 0) {
2833 if (!BIO_should_retry(io))
2834 goto write_error;
2835 else {
2836 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
2837 }
2838 } else {
2839 j += k;
2840 }
2841 }
2842 }
2843 write_error:
2844 BIO_free(file);
2845 break;
2846 }
2847 }
2848
2849 for (;;) {
2850 i = (int)BIO_flush(io);
2851 if (i <= 0) {
2852 if (!BIO_should_retry(io))
2853 break;
2854 } else
2855 break;
2856 }
2857 end:
0f113f3e
MC
2858 /* make sure we re-use sessions */
2859 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
d02b48c6 2860
0f113f3e 2861 err:
0f113f3e
MC
2862 if (ret >= 0)
2863 BIO_printf(bio_s_out, "ACCEPT\n");
b548a1f1 2864 OPENSSL_free(buf);
ca3a82c3 2865 BIO_free_all(io);
0f113f3e
MC
2866 return (ret);
2867}
d02b48c6 2868
c3b344e3 2869static int rev_body(char *hostname, int s, int stype, unsigned char *context)
0f113f3e
MC
2870{
2871 char *buf = NULL;
2872 int i;
2873 int ret = 1;
2874 SSL *con;
2875 BIO *io, *ssl_bio, *sbio;
4f3df8be 2876
68dc6824 2877 buf = app_malloc(bufsize, "server rev buffer");
0f113f3e
MC
2878 io = BIO_new(BIO_f_buffer());
2879 ssl_bio = BIO_new(BIO_f_ssl());
2880 if ((io == NULL) || (ssl_bio == NULL))
2881 goto err;
4f3df8be 2882
0f113f3e
MC
2883 /* lets make the output buffer a reasonable size */
2884 if (!BIO_set_write_buffer_size(io, bufsize))
2885 goto err;
4f3df8be 2886
0f113f3e
MC
2887 if ((con = SSL_new(ctx)) == NULL)
2888 goto err;
e481f9b9 2889
0f113f3e
MC
2890 if (s_tlsextdebug) {
2891 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2892 SSL_set_tlsext_debug_arg(con, bio_s_out);
2893 }
ac59d705 2894 if (context && !SSL_set_session_id_context(con, context,
7e1b7485 2895 strlen((char *)context))) {
ac59d705
MC
2896 ERR_print_errors(bio_err);
2897 goto err;
2898 }
0f113f3e
MC
2899
2900 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2901 SSL_set_bio(con, sbio, sbio);
2902 SSL_set_accept_state(con);
2903
2904 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2905 BIO_push(io, ssl_bio);
4f3df8be 2906#ifdef CHARSET_EBCDIC
0f113f3e 2907 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
4f3df8be
DSH
2908#endif
2909
0f113f3e
MC
2910 if (s_debug) {
2911 SSL_set_debug(con, 1);
2912 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2913 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2914 }
2915 if (s_msg) {
4f3df8be 2916#ifndef OPENSSL_NO_SSL_TRACE
0f113f3e
MC
2917 if (s_msg == 2)
2918 SSL_set_msg_callback(con, SSL_trace);
2919 else
2920#endif
2921 SSL_set_msg_callback(con, msg_cb);
2922 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2923 }
2924
2925 for (;;) {
2926 i = BIO_do_handshake(io);
2927 if (i > 0)
2928 break;
2929 if (!BIO_should_retry(io)) {
2930 BIO_puts(bio_err, "CONNECTION FAILURE\n");
2931 ERR_print_errors(bio_err);
2932 goto end;
2933 }
2934 }
2935 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
ecf3a1fb 2936 print_ssl_summary(con);
0f113f3e
MC
2937
2938 for (;;) {
2939 i = BIO_gets(io, buf, bufsize - 1);
2940 if (i < 0) { /* error */
2941 if (!BIO_should_retry(io)) {
2942 if (!s_quiet)
2943 ERR_print_errors(bio_err);
2944 goto err;
2945 } else {
2946 BIO_printf(bio_s_out, "read R BLOCK\n");
4f3df8be 2947#if defined(OPENSSL_SYS_NETWARE)
0f113f3e 2948 delay(1000);
a9008157 2949#elif !defined(OPENSSL_SYS_MSDOS)
0f113f3e
MC
2950 sleep(1);
2951#endif
2952 continue;
2953 }
2954 } else if (i == 0) { /* end of input */
2955 ret = 1;
2956 BIO_printf(bio_err, "CONNECTION CLOSED\n");
2957 goto end;
2958 } else {
2959 char *p = buf + i - 1;
2960 while (i && (*p == '\n' || *p == '\r')) {
2961 p--;
2962 i--;
2963 }
86885c28 2964 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
0f113f3e
MC
2965 ret = 1;
2966 BIO_printf(bio_err, "CONNECTION CLOSED\n");
2967 goto end;
2968 }
2969 BUF_reverse((unsigned char *)buf, NULL, i);
2970 buf[i] = '\n';
2971 BIO_write(io, buf, i + 1);
2972 for (;;) {
2973 i = BIO_flush(io);
2974 if (i > 0)
2975 break;
2976 if (!BIO_should_retry(io))
2977 goto end;
2978 }
2979 }
2980 }
2981 end:
2982 /* make sure we re-use sessions */
2983 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2984
2985 err:
2986
b548a1f1 2987 OPENSSL_free(buf);
ca3a82c3 2988 BIO_free_all(io);
0f113f3e
MC
2989 return (ret);
2990}
4f3df8be 2991
cf1b7d96 2992#ifndef OPENSSL_NO_RSA
6d23cf97 2993static RSA *tmp_rsa_cb(SSL *s, int is_export, int keylength)
0f113f3e
MC
2994{
2995 BIGNUM *bn = NULL;
2996 static RSA *rsa_tmp = NULL;
2997
2998 if (!rsa_tmp && ((bn = BN_new()) == NULL))
2999 BIO_printf(bio_err, "Allocation error in generating RSA key\n");
3000 if (!rsa_tmp && bn) {
3001 if (!s_quiet) {
3002 BIO_printf(bio_err, "Generating temp (%d bit) RSA key...",
3003 keylength);
3004 (void)BIO_flush(bio_err);
3005 }
3006 if (!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
3007 !RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
d6407083 3008 RSA_free(rsa_tmp);
0f113f3e
MC
3009 rsa_tmp = NULL;
3010 }
3011 if (!s_quiet) {
3012 BIO_printf(bio_err, "\n");
3013 (void)BIO_flush(bio_err);
3014 }
3015 BN_free(bn);
3016 }
3017 return (rsa_tmp);
3018}
f5d7a031 3019#endif
1aa0d947
GT
3020
3021#define MAX_SESSION_ID_ATTEMPTS 10
3022static int generate_session_id(const SSL *ssl, unsigned char *id,
0f113f3e
MC
3023 unsigned int *id_len)
3024{
3025 unsigned int count = 0;
3026 do {
266483d2
MC
3027 if (RAND_bytes(id, *id_len) <= 0)
3028 return 0;
0f113f3e
MC
3029 /*
3030 * Prefix the session_id with the required prefix. NB: If our prefix
3031 * is too long, clip it - but there will be worse effects anyway, eg.
3032 * the server could only possibly create 1 session ID (ie. the
3033 * prefix!) so all future session negotiations will fail due to
3034 * conflicts.
3035 */
3036 memcpy(id, session_id_prefix,
3037 (strlen(session_id_prefix) < *id_len) ?
3038 strlen(session_id_prefix) : *id_len);
3039 }
3040 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3041 (++count < MAX_SESSION_ID_ATTEMPTS));
3042 if (count >= MAX_SESSION_ID_ATTEMPTS)
3043 return 0;
3044 return 1;
3045}
3046
3047/*
3048 * By default s_server uses an in-memory cache which caches SSL_SESSION
35b0ea4e
DSH
3049 * structures without any serialisation. This hides some bugs which only
3050 * become apparent in deployed servers. By implementing a basic external
3051 * session cache some issues can be debugged using s_server.
3052 */
3053
0f113f3e
MC
3054typedef struct simple_ssl_session_st {
3055 unsigned char *id;
3056 unsigned int idlen;
3057 unsigned char *der;
3058 int derlen;
3059 struct simple_ssl_session_st *next;
3060} simple_ssl_session;
35b0ea4e
DSH
3061
3062static simple_ssl_session *first = NULL;
3063
3064static int add_session(SSL *ssl, SSL_SESSION *session)
0f113f3e 3065{
b4faea50 3066 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
0f113f3e 3067 unsigned char *p;
35b0ea4e 3068
0f113f3e
MC
3069 SSL_SESSION_get_id(session, &sess->idlen);
3070 sess->derlen = i2d_SSL_SESSION(session, NULL);
7e1b7485
RS
3071 if (sess->derlen < 0) {
3072 BIO_printf(bio_err, "Error encoding session\n");
a194ee7b 3073 OPENSSL_free(sess);
7e1b7485
RS
3074 return 0;
3075 }
35b0ea4e 3076
0f113f3e 3077 sess->id = BUF_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
68dc6824
RS
3078 sess->der = app_malloc(sess->derlen, "get session buffer");
3079 if (!sess->id) {
7e1b7485 3080 BIO_printf(bio_err, "Out of memory adding to external cache\n");
a194ee7b
RS
3081 OPENSSL_free(sess->id);
3082 OPENSSL_free(sess->der);
918bb865
MC
3083 OPENSSL_free(sess);
3084 return 0;
3085 }
0f113f3e 3086 p = sess->der;
7e1b7485
RS
3087
3088 /* Assume it still works. */
3089 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
ce6766de 3090 BIO_printf(bio_err, "Unexpected session encoding length\n");
a194ee7b
RS
3091 OPENSSL_free(sess->id);
3092 OPENSSL_free(sess->der);
3093 OPENSSL_free(sess);
ac59d705
MC
3094 return 0;
3095 }
35b0ea4e 3096
0f113f3e
MC
3097 sess->next = first;
3098 first = sess;
3099 BIO_printf(bio_err, "New session added to external cache\n");
3100 return 0;
3101}
35b0ea4e
DSH
3102
3103static SSL_SESSION *get_session(SSL *ssl, unsigned char *id, int idlen,
0f113f3e
MC
3104 int *do_copy)
3105{
3106 simple_ssl_session *sess;
3107 *do_copy = 0;
3108 for (sess = first; sess; sess = sess->next) {
3109 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3110 const unsigned char *p = sess->der;
3111 BIO_printf(bio_err, "Lookup session: cache hit\n");
3112 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3113 }
3114 }
3115 BIO_printf(bio_err, "Lookup session: cache miss\n");
3116 return NULL;
3117}
35b0ea4e
DSH
3118
3119static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
0f113f3e
MC
3120{
3121 simple_ssl_session *sess, *prev = NULL;
3122 const unsigned char *id;
3123 unsigned int idlen;
3124 id = SSL_SESSION_get_id(session, &idlen);
3125 for (sess = first; sess; sess = sess->next) {
3126 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3127 if (prev)
3128 prev->next = sess->next;
3129 else
3130 first = sess->next;
3131 OPENSSL_free(sess->id);
3132 OPENSSL_free(sess->der);
3133 OPENSSL_free(sess);
3134 return;
3135 }
3136 prev = sess;
3137 }
3138}
35b0ea4e
DSH
3139
3140static void init_session_cache_ctx(SSL_CTX *sctx)
0f113f3e
MC
3141{
3142 SSL_CTX_set_session_cache_mode(sctx,
3143 SSL_SESS_CACHE_NO_INTERNAL |
3144 SSL_SESS_CACHE_SERVER);
3145 SSL_CTX_sess_set_new_cb(sctx, add_session);
3146 SSL_CTX_sess_set_get_cb(sctx, get_session);
3147 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3148}
35b0ea4e
DSH
3149
3150static void free_sessions(void)
0f113f3e
MC
3151{
3152 simple_ssl_session *sess, *tsess;
3153 for (sess = first; sess;) {
3154 OPENSSL_free(sess->id);
3155 OPENSSL_free(sess->der);
3156 tsess = sess;
3157 sess = sess->next;
3158 OPENSSL_free(tsess);
3159 }
3160 first = NULL;
3161}