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