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