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