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.
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
17 /* Included before async.h to avoid some warnings */
21 #include <openssl/e_os2.h>
22 #include <openssl/async.h>
23 #include <openssl/ssl.h>
24 #include <openssl/decoder.h>
26 #ifndef OPENSSL_NO_SOCK
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
34 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
36 typedef unsigned int u_int;
39 #include <openssl/bn.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>
49 # include <openssl/dh.h>
51 #include <openssl/rsa.h>
55 #include <openssl/ebcdic.h>
57 #include "internal/sockets.h"
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);
72 static const int bufsize = 16 * 1024;
73 static int accept_socket = -1;
75 #define TEST_CERT "server.pem"
76 #define TEST_CERT2 "server2.pem"
78 static int s_nbio = 0;
79 static int s_nbio_test = 0;
80 static int s_crlf = 0;
81 static int immediate_reneg = 0;
82 static SSL_CTX *ctx = NULL;
83 static SSL_CTX *ctx2 = NULL;
86 static BIO *bio_s_out = NULL;
87 static BIO *bio_s_msg = NULL;
88 static int s_debug = 0;
89 static int s_tlsextdebug = 0;
91 static int s_quiet = 0;
92 static int s_ign_eof = 0;
93 static int s_brief = 0;
95 static char *keymatexportlabel = NULL;
96 static int keymatexportlen = 20;
100 static int use_sendfile = 0;
102 static const char *session_id_prefix = NULL;
104 #ifndef OPENSSL_NO_DTLS
105 static int enable_timeouts = 0;
106 static long socket_mtu;
110 * We define this but make it always be 0 in no-dtls builds to simplify the
113 static int dtlslisten = 0;
114 static int stateless = 0;
116 static int early_data = 0;
117 static SSL_SESSION *psksess = NULL;
119 static char *psk_identity = "Client_identity";
120 char *psk_key = NULL; /* by default PSK is not used */
122 static char http_server_binmode = 0; /* for now: 0/1 = default/binary */
124 #ifndef OPENSSL_NO_PSK
125 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
127 unsigned int max_psk_len)
133 BIO_printf(bio_s_out, "psk_server_cb\n");
134 if (identity == NULL) {
135 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
139 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
140 (int)strlen(identity), identity);
142 /* here we could lookup the given identity e.g. from a database */
143 if (strcmp(identity, psk_identity) != 0) {
144 BIO_printf(bio_s_out, "PSK warning: client identity not what we expected"
145 " (got '%s' expected '%s')\n", identity, psk_identity);
148 BIO_printf(bio_s_out, "PSK client identity found\n");
151 /* convert the PSK key to binary */
152 key = OPENSSL_hexstr2buf(psk_key, &key_len);
154 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
158 if (key_len > (int)max_psk_len) {
160 "psk buffer of callback is too small (%d) for key (%ld)\n",
161 max_psk_len, key_len);
166 memcpy(psk, key, key_len);
170 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
174 BIO_printf(bio_err, "Error in PSK server callback\n");
175 (void)BIO_flush(bio_err);
176 (void)BIO_flush(bio_s_out);
181 static int psk_find_session_cb(SSL *ssl, const unsigned char *identity,
182 size_t identity_len, SSL_SESSION **sess)
184 SSL_SESSION *tmpsess = NULL;
187 const SSL_CIPHER *cipher = NULL;
189 if (strlen(psk_identity) != identity_len
190 || memcmp(psk_identity, identity, identity_len) != 0) {
195 if (psksess != NULL) {
196 SSL_SESSION_up_ref(psksess);
201 key = OPENSSL_hexstr2buf(psk_key, &key_len);
203 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
208 /* We default to SHA256 */
209 cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id);
210 if (cipher == NULL) {
211 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
216 tmpsess = SSL_SESSION_new();
218 || !SSL_SESSION_set1_master_key(tmpsess, key, key_len)
219 || !SSL_SESSION_set_cipher(tmpsess, cipher)
220 || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) {
230 #ifndef OPENSSL_NO_SRP
231 static srpsrvparm srp_callback_parm;
234 static int local_argc = 0;
235 static char **local_argv;
237 #ifdef CHARSET_EBCDIC
238 static int ebcdic_new(BIO *bi);
239 static int ebcdic_free(BIO *a);
240 static int ebcdic_read(BIO *b, char *out, int outl);
241 static int ebcdic_write(BIO *b, const char *in, int inl);
242 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
243 static int ebcdic_gets(BIO *bp, char *buf, int size);
244 static int ebcdic_puts(BIO *bp, const char *str);
246 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
247 static BIO_METHOD *methods_ebcdic = NULL;
249 /* This struct is "unwarranted chumminess with the compiler." */
255 static const BIO_METHOD *BIO_f_ebcdic_filter()
257 if (methods_ebcdic == NULL) {
258 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
259 "EBCDIC/ASCII filter");
260 if (methods_ebcdic == NULL
261 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
262 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
263 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
264 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
265 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
266 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
267 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
270 return methods_ebcdic;
273 static int ebcdic_new(BIO *bi)
275 EBCDIC_OUTBUFF *wbuf;
277 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
278 wbuf->alloced = 1024;
279 wbuf->buff[0] = '\0';
281 BIO_set_data(bi, wbuf);
286 static int ebcdic_free(BIO *a)
288 EBCDIC_OUTBUFF *wbuf;
292 wbuf = BIO_get_data(a);
294 BIO_set_data(a, NULL);
300 static int ebcdic_read(BIO *b, char *out, int outl)
303 BIO *next = BIO_next(b);
305 if (out == NULL || outl == 0)
310 ret = BIO_read(next, out, outl);
312 ascii2ebcdic(out, out, ret);
316 static int ebcdic_write(BIO *b, const char *in, int inl)
318 EBCDIC_OUTBUFF *wbuf;
319 BIO *next = BIO_next(b);
323 if ((in == NULL) || (inl <= 0))
328 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
330 if (inl > (num = wbuf->alloced)) {
331 num = num + num; /* double the size */
335 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
338 wbuf->buff[0] = '\0';
340 BIO_set_data(b, wbuf);
343 ebcdic2ascii(wbuf->buff, in, inl);
345 ret = BIO_write(next, wbuf->buff, inl);
350 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
353 BIO *next = BIO_next(b);
362 ret = BIO_ctrl(next, cmd, num, ptr);
368 static int ebcdic_gets(BIO *bp, char *buf, int size)
371 BIO *next = BIO_next(bp);
375 /* return(BIO_gets(bp->next_bio,buf,size));*/
376 for (i = 0; i < size - 1; ++i) {
377 ret = ebcdic_read(bp, &buf[i], 1);
380 else if (buf[i] == '\n') {
387 return (ret < 0 && i == 0) ? ret : i;
390 static int ebcdic_puts(BIO *bp, const char *str)
392 if (BIO_next(bp) == NULL)
394 return ebcdic_write(bp, str, strlen(str));
398 /* This is a context that we pass to callbacks */
399 typedef struct tlsextctx_st {
405 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
407 tlsextctx *p = (tlsextctx *) arg;
408 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
410 if (servername != NULL && p->biodebug != NULL) {
411 const char *cp = servername;
414 BIO_printf(p->biodebug, "Hostname in TLS extension: \"");
415 while ((uc = *cp++) != 0)
416 BIO_printf(p->biodebug,
417 (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc);
418 BIO_printf(p->biodebug, "\"\n");
421 if (p->servername == NULL)
422 return SSL_TLSEXT_ERR_NOACK;
424 if (servername != NULL) {
425 if (strcasecmp(servername, p->servername))
426 return p->extension_error;
428 BIO_printf(p->biodebug, "Switching server context.\n");
429 SSL_set_SSL_CTX(s, ctx2);
432 return SSL_TLSEXT_ERR_OK;
435 /* Structure passed to cert status callback */
436 typedef struct tlsextstatusctx_st {
438 /* File to load OCSP Response from (or NULL if no file) */
440 /* Default responder to use */
441 char *host, *path, *port;
442 char *proxy, *no_proxy;
447 static tlsextstatusctx tlscstatp = { -1 };
449 #ifndef OPENSSL_NO_OCSP
452 * Helper function to get an OCSP_RESPONSE from a responder. This is a
453 * simplified version. It examines certificates each time and makes one OCSP
454 * responder query for each request. A full version would store details such as
455 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
456 * them until they were considered "expired".
458 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
459 OCSP_RESPONSE **resp)
461 char *host = NULL, *port = NULL, *path = NULL;
462 char *proxy = NULL, *no_proxy = NULL;
464 STACK_OF(OPENSSL_STRING) *aia = NULL;
466 X509_STORE_CTX *inctx = NULL;
468 OCSP_REQUEST *req = NULL;
469 OCSP_CERTID *id = NULL;
470 STACK_OF(X509_EXTENSION) *exts;
471 int ret = SSL_TLSEXT_ERR_NOACK;
474 /* Build up OCSP query from server certificate */
475 x = SSL_get_certificate(s);
476 aia = X509_get1_ocsp(x);
478 if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl,
479 NULL, &host, &port, NULL, &path, NULL, NULL)) {
480 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
484 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
485 sk_OPENSSL_STRING_value(aia, 0));
487 if (srctx->host == NULL) {
489 "cert_status: no AIA and no default responder URL\n");
495 use_ssl = srctx->use_ssl;
497 proxy = srctx->proxy;
498 no_proxy = srctx->no_proxy;
500 inctx = X509_STORE_CTX_new();
503 if (!X509_STORE_CTX_init(inctx,
504 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
507 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
508 X509_get_issuer_name(x));
510 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
513 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
514 X509_OBJECT_free(obj);
517 req = OCSP_REQUEST_new();
520 if (!OCSP_request_add0_id(req, id))
523 /* Add any extensions to the request */
524 SSL_get_tlsext_status_exts(s, &exts);
525 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
526 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
527 if (!OCSP_REQUEST_add_ext(req, ext, -1))
530 *resp = process_responder(req, host, port, path, proxy, no_proxy,
531 use_ssl, NULL /* headers */, srctx->timeout);
533 BIO_puts(bio_err, "cert_status: error querying responder\n");
537 ret = SSL_TLSEXT_ERR_OK;
541 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
544 * If we parsed aia we need to free; otherwise they were copied and we
551 X509_email_free(aia);
553 OCSP_CERTID_free(id);
554 OCSP_REQUEST_free(req);
555 X509_STORE_CTX_free(inctx);
560 * Certificate Status callback. This is called when a client includes a
561 * certificate status request extension. The response is either obtained from a
562 * file, or from an OCSP responder.
564 static int cert_status_cb(SSL *s, void *arg)
566 tlsextstatusctx *srctx = arg;
567 OCSP_RESPONSE *resp = NULL;
568 unsigned char *rspder = NULL;
570 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
573 BIO_puts(bio_err, "cert_status: callback called\n");
575 if (srctx->respin != NULL) {
576 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
577 if (derbio == NULL) {
578 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
581 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
584 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
588 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
589 if (ret != SSL_TLSEXT_ERR_OK)
593 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
597 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
598 if (srctx->verbose) {
599 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
600 OCSP_RESPONSE_print(bio_err, resp, 2);
603 ret = SSL_TLSEXT_ERR_OK;
606 if (ret != SSL_TLSEXT_ERR_OK)
607 ERR_print_errors(bio_err);
609 OCSP_RESPONSE_free(resp);
615 #ifndef OPENSSL_NO_NEXTPROTONEG
616 /* This is the context that we pass to next_proto_cb */
617 typedef struct tlsextnextprotoctx_st {
620 } tlsextnextprotoctx;
622 static int next_proto_cb(SSL *s, const unsigned char **data,
623 unsigned int *len, void *arg)
625 tlsextnextprotoctx *next_proto = arg;
627 *data = next_proto->data;
628 *len = next_proto->len;
630 return SSL_TLSEXT_ERR_OK;
632 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
634 /* This the context that we pass to alpn_cb */
635 typedef struct tlsextalpnctx_st {
640 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
641 const unsigned char *in, unsigned int inlen, void *arg)
643 tlsextalpnctx *alpn_ctx = arg;
646 /* We can assume that |in| is syntactically valid. */
648 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
649 for (i = 0; i < inlen;) {
651 BIO_write(bio_s_out, ", ", 2);
652 BIO_write(bio_s_out, &in[i + 1], in[i]);
655 BIO_write(bio_s_out, "\n", 1);
658 if (SSL_select_next_proto
659 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
660 inlen) != OPENSSL_NPN_NEGOTIATED) {
661 return SSL_TLSEXT_ERR_ALERT_FATAL;
665 BIO_printf(bio_s_out, "ALPN protocols selected: ");
666 BIO_write(bio_s_out, *out, *outlen);
667 BIO_write(bio_s_out, "\n", 1);
670 return SSL_TLSEXT_ERR_OK;
673 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
675 /* disable resumption for sessions with forward secure ciphers */
676 return is_forward_secure;
679 typedef enum OPTION_choice {
682 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
683 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
684 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
685 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
686 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
687 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
688 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
689 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
691 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
692 OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
693 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
694 OPT_STATUS_TIMEOUT, OPT_PROXY, OPT_NO_PROXY, OPT_STATUS_URL,
695 OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
696 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
697 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
698 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK,
699 OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW,
700 OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG,
701 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
702 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
703 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS,
704 OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
705 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE,
706 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
707 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA,
708 OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG,
709 OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF,
717 const OPTIONS s_server_options[] = {
718 OPT_SECTION("General"),
719 {"help", OPT_HELP, '-', "Display this summary"},
720 {"ssl_config", OPT_SSL_CONFIG, 's',
721 "Configure SSL_CTX using the given configuration value"},
722 #ifndef OPENSSL_NO_SSL_TRACE
723 {"trace", OPT_TRACE, '-', "trace protocol messages"},
725 #ifndef OPENSSL_NO_ENGINE
726 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
729 OPT_SECTION("Network"),
730 {"port", OPT_PORT, 'p',
731 "TCP/IP port to listen on for connections (default is " PORT ")"},
732 {"accept", OPT_ACCEPT, 's',
733 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
735 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
736 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
738 {"4", OPT_4, '-', "Use IPv4 only"},
739 {"6", OPT_6, '-', "Use IPv6 only"},
741 OPT_SECTION("Identity"),
742 {"context", OPT_CONTEXT, 's', "Set session ID context"},
743 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
744 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
745 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
746 {"no-CAfile", OPT_NOCAFILE, '-',
747 "Do not load the default certificates file"},
748 {"no-CApath", OPT_NOCAPATH, '-',
749 "Do not load certificates from the default certificates directory"},
750 {"no-CAstore", OPT_NOCASTORE, '-',
751 "Do not load certificates from the default certificates store URI"},
752 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
753 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
754 {"Verify", OPT_UPPER_V_VERIFY, 'n',
755 "Turn on peer certificate verification, must have a cert"},
756 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
757 {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT},
758 {"cert2", OPT_CERT2, '<',
759 "Certificate file to use for servername; default " TEST_CERT2},
760 {"certform", OPT_CERTFORM, 'F',
761 "Server certificate file format (PEM/DER/P12); has no effect"},
762 {"cert_chain", OPT_CERT_CHAIN, '<',
763 "Server certificate chain file in PEM format"},
764 {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"},
765 {"serverinfo", OPT_SERVERINFO, 's',
766 "PEM serverinfo file for certificate"},
767 {"key", OPT_KEY, 's',
768 "Private key file to use; default is -cert file or else" TEST_CERT},
769 {"key2", OPT_KEY2, '<',
770 "-Private Key file to use for servername if not in -cert2"},
771 {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"},
772 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
773 {"dcert", OPT_DCERT, '<',
774 "Second server certificate file to use (usually for DSA)"},
775 {"dcertform", OPT_DCERTFORM, 'F',
776 "Second server certificate file format (PEM/DER/P12); has no effect"},
777 {"dcert_chain", OPT_DCERT_CHAIN, '<',
778 "second server certificate chain file in PEM format"},
779 {"dkey", OPT_DKEY, '<',
780 "Second private key file to use (usually for DSA)"},
781 {"dkeyform", OPT_DKEYFORM, 'F',
782 "Second key file format (ENGINE, other values ignored)"},
783 {"dpass", OPT_DPASS, 's',
784 "Second private key and cert file pass phrase source"},
785 {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
786 {"servername", OPT_SERVERNAME, 's',
787 "Servername for HostName TLS extension"},
788 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
789 "On servername mismatch send fatal alert (default warning alert)"},
790 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
791 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
792 {"quiet", OPT_QUIET, '-', "No server output"},
793 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
794 "Disable caching and tickets if ephemeral (EC)DH is used"},
795 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
796 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
797 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
798 "Do not treat lack of close_notify from a peer as an error"},
799 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
800 "Hex dump of all TLS extensions received"},
801 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
802 {"id_prefix", OPT_ID_PREFIX, 's',
803 "Generate SSL/TLS session IDs prefixed by arg"},
804 {"keymatexport", OPT_KEYMATEXPORT, 's',
805 "Export keying material using label"},
806 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
807 "Export len bytes of keying material; default 20"},
808 {"CRL", OPT_CRL, '<', "CRL file to use"},
809 {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"},
810 {"crl_download", OPT_CRL_DOWNLOAD, '-',
811 "Download CRLs from distribution points in certificate CDP entries"},
812 {"chainCAfile", OPT_CHAINCAFILE, '<',
813 "CA file for certificate chain (PEM format)"},
814 {"chainCApath", OPT_CHAINCAPATH, '/',
815 "use dir as certificate store path to build CA certificate chain"},
816 {"chainCAstore", OPT_CHAINCASTORE, ':',
817 "use URI as certificate store to build CA certificate chain"},
818 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
819 "CA file for certificate verification (PEM format)"},
820 {"verifyCApath", OPT_VERIFYCAPATH, '/',
821 "use dir as certificate store path to verify CA certificate"},
822 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
823 "use URI as certificate store to verify CA certificate"},
824 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
825 {"ext_cache", OPT_EXT_CACHE, '-',
826 "Disable internal cache, set up and use external cache"},
827 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
828 "Close connection on verification error"},
829 {"verify_quiet", OPT_VERIFY_QUIET, '-',
830 "No verify output except verify errors"},
831 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input EOF (default when -quiet)"},
832 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input EOF"},
834 #ifndef OPENSSL_NO_OCSP
836 {"status", OPT_STATUS, '-', "Request certificate status from server"},
837 {"status_verbose", OPT_STATUS_VERBOSE, '-',
838 "Print more output in certificate status callback"},
839 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
840 "Status request responder timeout"},
841 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
842 {"proxy", OPT_PROXY, 's',
843 "[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"},
844 {"no_proxy", OPT_NO_PROXY, 's',
845 "List of addresses of servers not to use HTTP(S) proxy for"},
847 "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
848 {"status_file", OPT_STATUS_FILE, '<',
849 "File containing DER encoded OCSP Response"},
852 OPT_SECTION("Debug"),
853 {"security_debug", OPT_SECURITY_DEBUG, '-',
854 "Print output from SSL/TLS security framework"},
855 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
856 "Print more output from SSL/TLS security framework"},
857 {"brief", OPT_BRIEF, '-',
858 "Restrict output to brief summary of connection parameters"},
859 {"rev", OPT_REV, '-',
860 "act as a simple test server which just sends back with the received text reversed"},
861 {"debug", OPT_DEBUG, '-', "Print more output"},
862 {"msg", OPT_MSG, '-', "Show protocol messages"},
863 {"msgfile", OPT_MSGFILE, '>',
864 "File to send output of -msg or -trace, instead of stdout"},
865 {"state", OPT_STATE, '-', "Print the SSL states"},
866 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
867 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
868 "Maximum number of encrypt/decrypt pipelines to be used"},
869 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
870 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
872 OPT_SECTION("Network"),
873 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
874 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
875 {"mtu", OPT_MTU, 'p', "Set link-layer MTU"},
876 {"read_buf", OPT_READ_BUF, 'p',
877 "Default read buffer size to be used for connections"},
878 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
879 "Size used to split data for encrypt pipelines"},
880 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
882 OPT_SECTION("Server identity"),
883 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
884 #ifndef OPENSSL_NO_PSK
885 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
887 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
888 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
889 #ifndef OPENSSL_NO_SRP
890 {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"},
891 {"srpuserseed", OPT_SRPUSERSEED, 's',
892 "(deprecated) A seed string for a default user salt"},
895 OPT_SECTION("Protocol and version"),
896 {"max_early_data", OPT_MAX_EARLY, 'n',
897 "The maximum number of bytes of early data as advertised in tickets"},
898 {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n',
899 "The maximum number of bytes of early data (hard limit)"},
900 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
901 {"num_tickets", OPT_S_NUM_TICKETS, 'n',
902 "The number of TLSv1.3 session tickets that a server will automatically issue" },
903 {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"},
904 {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"},
905 {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"},
906 {"no_ca_names", OPT_NOCANAMES, '-',
907 "Disable TLS Extension CA Names"},
908 {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"},
909 #ifndef OPENSSL_NO_SSL3
910 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
912 #ifndef OPENSSL_NO_TLS1
913 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
915 #ifndef OPENSSL_NO_TLS1_1
916 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
918 #ifndef OPENSSL_NO_TLS1_2
919 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
921 #ifndef OPENSSL_NO_TLS1_3
922 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
924 #ifndef OPENSSL_NO_DTLS
925 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
926 {"listen", OPT_LISTEN, '-',
927 "Listen for a DTLS ClientHello with a cookie and then connect"},
929 #ifndef OPENSSL_NO_DTLS1
930 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
932 #ifndef OPENSSL_NO_DTLS1_2
933 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
935 #ifndef OPENSSL_NO_SCTP
936 {"sctp", OPT_SCTP, '-', "Use SCTP"},
937 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
939 #ifndef OPENSSL_NO_SRTP
940 {"use_srtp", OPT_SRTP_PROFILES, 's',
941 "Offer SRTP key management with a colon-separated profile list"},
943 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
944 #ifndef OPENSSL_NO_NEXTPROTONEG
945 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
946 "Set the advertised protocols for the NPN extension (comma-separated list)"},
948 {"alpn", OPT_ALPN, 's',
949 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
950 #ifndef OPENSSL_NO_KTLS
951 {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"},
962 #define IS_PROT_FLAG(o) \
963 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
964 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
966 int s_server_main(int argc, char *argv[])
968 ENGINE *engine = NULL;
969 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
970 SSL_CONF_CTX *cctx = NULL;
971 const SSL_METHOD *meth = TLS_server_method();
972 SSL_EXCERT *exc = NULL;
973 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
974 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
975 STACK_OF(X509_CRL) *crls = NULL;
976 X509 *s_cert = NULL, *s_dcert = NULL;
977 X509_VERIFY_PARAM *vpm = NULL;
978 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
979 const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL;
980 char *dpassarg = NULL, *dpass = NULL;
981 char *passarg = NULL, *pass = NULL;
982 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
983 char *crl_file = NULL, *prog;
985 int unlink_unix_path = 0;
987 do_server_cb server_cb;
988 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
991 int nocert = 0, ret = 1;
992 int noCApath = 0, noCAfile = 0, noCAstore = 0;
993 int s_cert_format = FORMAT_UNDEF, s_key_format = FORMAT_UNDEF;
994 int s_dcert_format = FORMAT_UNDEF, s_dkey_format = FORMAT_UNDEF;
995 int rev = 0, naccept = -1, sdebug = 0;
996 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
997 int state = 0, crl_format = FORMAT_UNDEF, crl_download = 0;
999 char *port = OPENSSL_strdup(PORT);
1000 unsigned char *context = NULL;
1002 EVP_PKEY *s_key2 = NULL;
1003 X509 *s_cert2 = NULL;
1004 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
1005 const char *ssl_config = NULL;
1006 int read_buf_len = 0;
1007 #ifndef OPENSSL_NO_NEXTPROTONEG
1008 const char *next_proto_neg_in = NULL;
1009 tlsextnextprotoctx next_proto = { NULL, 0 };
1011 const char *alpn_in = NULL;
1012 tlsextalpnctx alpn_ctx = { NULL, 0 };
1013 #ifndef OPENSSL_NO_PSK
1014 /* by default do not send a PSK identity hint */
1015 char *psk_identity_hint = NULL;
1018 #ifndef OPENSSL_NO_SRP
1019 char *srpuserseed = NULL;
1020 char *srp_verifier_file = NULL;
1022 #ifndef OPENSSL_NO_SRTP
1023 char *srtp_profiles = NULL;
1025 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1026 int s_server_verify = SSL_VERIFY_NONE;
1027 int s_server_session_id_context = 1; /* anything will do */
1028 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
1029 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
1030 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
1031 #ifndef OPENSSL_NO_OCSP
1032 int s_tlsextstatus = 0;
1034 int no_resume_ephemeral = 0;
1035 unsigned int max_send_fragment = 0;
1036 unsigned int split_send_fragment = 0, max_pipelines = 0;
1037 const char *s_serverinfo_file = NULL;
1038 const char *keylog_file = NULL;
1039 int max_early_data = -1, recv_max_early_data = -1;
1040 char *psksessf = NULL;
1041 int no_ca_names = 0;
1042 #ifndef OPENSSL_NO_SCTP
1043 int sctp_label_bug = 0;
1045 int ignore_unexpected_eof = 0;
1047 /* Init of few remaining global variables */
1052 s_nbio = s_nbio_test = 0;
1062 cctx = SSL_CONF_CTX_new();
1063 vpm = X509_VERIFY_PARAM_new();
1064 if (cctx == NULL || vpm == NULL)
1066 SSL_CONF_CTX_set_flags(cctx,
1067 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1069 prog = opt_init(argc, argv, s_server_options);
1070 while ((o = opt_next()) != OPT_EOF) {
1071 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1072 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1075 if (IS_NO_PROT_FLAG(o))
1077 if (prot_opt == 1 && no_prot_opt) {
1079 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1086 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1089 opt_help(s_server_options);
1095 if (socket_family == AF_UNIX) {
1096 OPENSSL_free(host); host = NULL;
1097 OPENSSL_free(port); port = NULL;
1100 socket_family = AF_INET;
1106 if (socket_family == AF_UNIX) {
1107 OPENSSL_free(host); host = NULL;
1108 OPENSSL_free(port); port = NULL;
1111 socket_family = AF_INET6;
1114 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1120 if (socket_family == AF_UNIX) {
1121 socket_family = AF_UNSPEC;
1124 OPENSSL_free(port); port = NULL;
1125 OPENSSL_free(host); host = NULL;
1126 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1128 "%s: -port argument malformed or ambiguous\n",
1135 if (socket_family == AF_UNIX) {
1136 socket_family = AF_UNSPEC;
1139 OPENSSL_free(port); port = NULL;
1140 OPENSSL_free(host); host = NULL;
1141 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1143 "%s: -accept argument malformed or ambiguous\n",
1150 socket_family = AF_UNIX;
1151 OPENSSL_free(host); host = OPENSSL_strdup(opt_arg());
1152 OPENSSL_free(port); port = NULL;
1155 unlink_unix_path = 1;
1159 naccept = atol(opt_arg());
1162 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1163 verify_args.depth = atoi(opt_arg());
1165 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1167 case OPT_UPPER_V_VERIFY:
1169 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1170 SSL_VERIFY_CLIENT_ONCE;
1171 verify_args.depth = atoi(opt_arg());
1174 "verify depth is %d, must return a certificate\n",
1178 context = (unsigned char *)opt_arg();
1181 s_cert_file = opt_arg();
1184 if (!set_nameopt(opt_arg()))
1188 crl_file = opt_arg();
1190 case OPT_CRL_DOWNLOAD:
1193 case OPT_SERVERINFO:
1194 s_serverinfo_file = opt_arg();
1197 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format))
1201 s_key_file = opt_arg();
1204 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1208 passarg = opt_arg();
1210 case OPT_CERT_CHAIN:
1211 s_chain_file = opt_arg();
1217 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format))
1221 s_dcert_file = opt_arg();
1224 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format))
1228 dpassarg = opt_arg();
1231 s_dkey_file = opt_arg();
1233 case OPT_DCERT_CHAIN:
1234 s_dchain_file = opt_arg();
1245 case OPT_CHAINCAPATH:
1246 chCApath = opt_arg();
1248 case OPT_VERIFYCAPATH:
1249 vfyCApath = opt_arg();
1252 CAstore = opt_arg();
1257 case OPT_CHAINCASTORE:
1258 chCAstore = opt_arg();
1260 case OPT_VERIFYCASTORE:
1261 vfyCAstore = opt_arg();
1270 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1273 case OPT_S_IMMEDIATE_RENEG:
1274 immediate_reneg = 1;
1277 case OPT_S_NUM_TICKETS:
1278 case OPT_ANTI_REPLAY:
1279 case OPT_NO_ANTI_REPLAY:
1280 if (ssl_args == NULL)
1281 ssl_args = sk_OPENSSL_STRING_new_null();
1282 if (ssl_args == NULL
1283 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1284 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1285 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1290 if (!opt_verify(o, vpm))
1295 if (!args_excert(o, &exc))
1298 case OPT_VERIFY_RET_ERROR:
1299 verify_args.return_error = 1;
1301 case OPT_VERIFY_QUIET:
1302 verify_args.quiet = 1;
1304 case OPT_BUILD_CHAIN:
1313 case OPT_CHAINCAFILE:
1314 chCAfile = opt_arg();
1316 case OPT_VERIFYCAFILE:
1317 vfyCAfile = opt_arg();
1323 s_nbio = s_nbio_test = 1;
1328 case OPT_NO_IGN_EOF:
1334 case OPT_TLSEXTDEBUG:
1338 #ifndef OPENSSL_NO_OCSP
1342 case OPT_STATUS_VERBOSE:
1343 #ifndef OPENSSL_NO_OCSP
1344 s_tlsextstatus = tlscstatp.verbose = 1;
1347 case OPT_STATUS_TIMEOUT:
1348 #ifndef OPENSSL_NO_OCSP
1350 tlscstatp.timeout = atoi(opt_arg());
1354 #ifndef OPENSSL_NO_OCSP
1355 tlscstatp.proxy = opt_arg();
1359 #ifndef OPENSSL_NO_OCSP
1360 tlscstatp.no_proxy = opt_arg();
1363 case OPT_STATUS_URL:
1364 #ifndef OPENSSL_NO_OCSP
1366 if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL,
1367 &tlscstatp.host, &tlscstatp.port, NULL,
1368 &tlscstatp.path, NULL, NULL)) {
1369 BIO_printf(bio_err, "Error parsing -status_url argument\n");
1374 case OPT_STATUS_FILE:
1375 #ifndef OPENSSL_NO_OCSP
1377 tlscstatp.respin = opt_arg();
1384 bio_s_msg = BIO_new_file(opt_arg(), "w");
1387 #ifndef OPENSSL_NO_SSL_TRACE
1391 case OPT_SECURITY_DEBUG:
1394 case OPT_SECURITY_DEBUG_VERBOSE:
1407 s_quiet = s_brief = verify_args.quiet = 1;
1412 case OPT_NO_RESUME_EPHEMERAL:
1413 no_resume_ephemeral = 1;
1415 case OPT_PSK_IDENTITY:
1416 psk_identity = opt_arg();
1419 #ifndef OPENSSL_NO_PSK
1420 psk_identity_hint = opt_arg();
1424 for (p = psk_key = opt_arg(); *p; p++) {
1425 if (isxdigit(_UC(*p)))
1427 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1432 psksessf = opt_arg();
1435 #ifndef OPENSSL_NO_SRP
1436 srp_verifier_file = opt_arg();
1437 if (min_version < TLS1_VERSION)
1438 min_version = TLS1_VERSION;
1441 case OPT_SRPUSERSEED:
1442 #ifndef OPENSSL_NO_SRP
1443 srpuserseed = opt_arg();
1444 if (min_version < TLS1_VERSION)
1445 min_version = TLS1_VERSION;
1460 case OPT_SSL_CONFIG:
1461 ssl_config = opt_arg();
1464 min_version = SSL3_VERSION;
1465 max_version = SSL3_VERSION;
1468 min_version = TLS1_3_VERSION;
1469 max_version = TLS1_3_VERSION;
1472 min_version = TLS1_2_VERSION;
1473 max_version = TLS1_2_VERSION;
1476 min_version = TLS1_1_VERSION;
1477 max_version = TLS1_1_VERSION;
1480 min_version = TLS1_VERSION;
1481 max_version = TLS1_VERSION;
1484 #ifndef OPENSSL_NO_DTLS
1485 meth = DTLS_server_method();
1486 socket_type = SOCK_DGRAM;
1490 #ifndef OPENSSL_NO_DTLS
1491 meth = DTLS_server_method();
1492 min_version = DTLS1_VERSION;
1493 max_version = DTLS1_VERSION;
1494 socket_type = SOCK_DGRAM;
1498 #ifndef OPENSSL_NO_DTLS
1499 meth = DTLS_server_method();
1500 min_version = DTLS1_2_VERSION;
1501 max_version = DTLS1_2_VERSION;
1502 socket_type = SOCK_DGRAM;
1506 #ifndef OPENSSL_NO_SCTP
1507 protocol = IPPROTO_SCTP;
1510 case OPT_SCTP_LABEL_BUG:
1511 #ifndef OPENSSL_NO_SCTP
1516 #ifndef OPENSSL_NO_DTLS
1517 enable_timeouts = 1;
1521 #ifndef OPENSSL_NO_DTLS
1522 socket_mtu = atol(opt_arg());
1526 #ifndef OPENSSL_NO_DTLS
1534 session_id_prefix = opt_arg();
1537 #ifndef OPENSSL_NO_ENGINE
1538 engine = setup_engine(opt_arg(), s_debug);
1545 case OPT_PROV_CASES:
1546 if (!opt_provider(o))
1549 case OPT_SERVERNAME:
1550 tlsextcbp.servername = opt_arg();
1552 case OPT_SERVERNAME_FATAL:
1553 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1556 s_cert_file2 = opt_arg();
1559 s_key_file2 = opt_arg();
1561 case OPT_NEXTPROTONEG:
1562 # ifndef OPENSSL_NO_NEXTPROTONEG
1563 next_proto_neg_in = opt_arg();
1567 alpn_in = opt_arg();
1569 case OPT_SRTP_PROFILES:
1570 #ifndef OPENSSL_NO_SRTP
1571 srtp_profiles = opt_arg();
1574 case OPT_KEYMATEXPORT:
1575 keymatexportlabel = opt_arg();
1577 case OPT_KEYMATEXPORTLEN:
1578 keymatexportlen = atoi(opt_arg());
1583 case OPT_MAX_SEND_FRAG:
1584 max_send_fragment = atoi(opt_arg());
1586 case OPT_SPLIT_SEND_FRAG:
1587 split_send_fragment = atoi(opt_arg());
1589 case OPT_MAX_PIPELINES:
1590 max_pipelines = atoi(opt_arg());
1593 read_buf_len = atoi(opt_arg());
1595 case OPT_KEYLOG_FILE:
1596 keylog_file = opt_arg();
1599 max_early_data = atoi(opt_arg());
1600 if (max_early_data < 0) {
1601 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1605 case OPT_RECV_MAX_EARLY:
1606 recv_max_early_data = atoi(opt_arg());
1607 if (recv_max_early_data < 0) {
1608 BIO_printf(bio_err, "Invalid value for recv_max_early_data\n");
1612 case OPT_EARLY_DATA:
1614 if (max_early_data == -1)
1615 max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
1617 case OPT_HTTP_SERVER_BINMODE:
1618 http_server_binmode = 1;
1624 #ifndef OPENSSL_NO_KTLS
1628 case OPT_IGNORE_UNEXPECTED_EOF:
1629 ignore_unexpected_eof = 1;
1634 /* No extra arguments. */
1635 argc = opt_num_rest();
1639 if (!app_RAND_load())
1642 #ifndef OPENSSL_NO_NEXTPROTONEG
1643 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1644 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1648 #ifndef OPENSSL_NO_DTLS
1649 if (www && socket_type == SOCK_DGRAM) {
1650 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1654 if (dtlslisten && socket_type != SOCK_DGRAM) {
1655 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1660 if (stateless && socket_type != SOCK_STREAM) {
1661 BIO_printf(bio_err, "Can only use --stateless with TLS\n");
1666 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1668 "Can't use unix sockets and datagrams together\n");
1672 if (early_data && (www > 0 || rev)) {
1674 "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n");
1678 #ifndef OPENSSL_NO_SCTP
1679 if (protocol == IPPROTO_SCTP) {
1680 if (socket_type != SOCK_DGRAM) {
1681 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1684 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1685 socket_type = SOCK_STREAM;
1689 #ifndef OPENSSL_NO_KTLS
1690 if (use_sendfile && www <= 1) {
1691 BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n");
1696 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1697 BIO_printf(bio_err, "Error getting password\n");
1701 if (s_key_file == NULL)
1702 s_key_file = s_cert_file;
1704 if (s_key_file2 == NULL)
1705 s_key_file2 = s_cert_file2;
1707 if (!load_excert(&exc))
1711 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1712 "server certificate private key");
1716 s_cert = load_cert_pass(s_cert_file, s_cert_format, 1, pass,
1717 "server certificate");
1721 if (s_chain_file != NULL) {
1722 if (!load_certs(s_chain_file, 0, &s_chain, NULL,
1723 "server certificate chain"))
1727 if (tlsextcbp.servername != NULL) {
1728 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1729 "second server certificate private key");
1733 s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, 1, pass,
1734 "second server certificate");
1736 if (s_cert2 == NULL)
1740 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1741 if (next_proto_neg_in) {
1742 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1743 if (next_proto.data == NULL)
1747 alpn_ctx.data = NULL;
1749 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1750 if (alpn_ctx.data == NULL)
1754 if (crl_file != NULL) {
1756 crl = load_crl(crl_file, crl_format, 0, "CRL");
1759 crls = sk_X509_CRL_new_null();
1760 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1761 BIO_puts(bio_err, "Error adding CRL\n");
1762 ERR_print_errors(bio_err);
1768 if (s_dcert_file != NULL) {
1770 if (s_dkey_file == NULL)
1771 s_dkey_file = s_dcert_file;
1773 s_dkey = load_key(s_dkey_file, s_dkey_format,
1774 0, dpass, engine, "second certificate private key");
1778 s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, 1, dpass,
1779 "second server certificate");
1781 if (s_dcert == NULL) {
1782 ERR_print_errors(bio_err);
1785 if (s_dchain_file != NULL) {
1786 if (!load_certs(s_dchain_file, 0, &s_dchain, NULL,
1787 "second server certificate chain"))
1793 if (bio_s_out == NULL) {
1794 if (s_quiet && !s_debug) {
1795 bio_s_out = BIO_new(BIO_s_null());
1796 if (s_msg && bio_s_msg == NULL)
1797 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1799 if (bio_s_out == NULL)
1800 bio_s_out = dup_bio_out(FORMAT_TEXT);
1806 s_dcert_file = NULL;
1808 s_cert_file2 = NULL;
1812 ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1814 ERR_print_errors(bio_err);
1818 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1821 ssl_ctx_security_debug(ctx, sdebug);
1823 if (!config_ctx(cctx, ssl_args, ctx))
1827 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1828 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1830 ERR_print_errors(bio_err);
1834 #ifndef OPENSSL_NO_SCTP
1835 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1836 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1839 if (min_version != 0
1840 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1842 if (max_version != 0
1843 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1846 if (session_id_prefix) {
1847 if (strlen(session_id_prefix) >= 32)
1849 "warning: id_prefix is too long, only one new session will be possible\n");
1850 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1851 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1852 ERR_print_errors(bio_err);
1855 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1858 ssl_ctx_set_excert(ctx, exc);
1861 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1863 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1865 init_session_cache_ctx(ctx);
1867 SSL_CTX_sess_set_cache_size(ctx, 128);
1870 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1874 SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
1877 if (ignore_unexpected_eof)
1878 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1880 if (max_send_fragment > 0
1881 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1882 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1883 prog, max_send_fragment);
1887 if (split_send_fragment > 0
1888 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1889 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1890 prog, split_send_fragment);
1893 if (max_pipelines > 0
1894 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1895 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1896 prog, max_pipelines);
1900 if (read_buf_len > 0) {
1901 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1903 #ifndef OPENSSL_NO_SRTP
1904 if (srtp_profiles != NULL) {
1905 /* Returns 0 on success! */
1906 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1907 BIO_printf(bio_err, "Error setting SRTP profile\n");
1908 ERR_print_errors(bio_err);
1914 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1915 CAstore, noCAstore)) {
1916 ERR_print_errors(bio_err);
1919 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1920 BIO_printf(bio_err, "Error setting verify params\n");
1921 ERR_print_errors(bio_err);
1925 ssl_ctx_add_crls(ctx, crls, 0);
1927 if (!ssl_load_stores(ctx,
1928 vfyCApath, vfyCAfile, vfyCAstore,
1929 chCApath, chCAfile, chCAstore,
1930 crls, crl_download)) {
1931 BIO_printf(bio_err, "Error loading store locations\n");
1932 ERR_print_errors(bio_err);
1937 ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1939 ERR_print_errors(bio_err);
1945 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1948 ssl_ctx_security_debug(ctx2, sdebug);
1950 if (session_id_prefix) {
1951 if (strlen(session_id_prefix) >= 32)
1953 "warning: id_prefix is too long, only one new session will be possible\n");
1954 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1955 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1956 ERR_print_errors(bio_err);
1959 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1962 ssl_ctx_set_excert(ctx2, exc);
1965 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1968 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1970 init_session_cache_ctx(ctx2);
1972 SSL_CTX_sess_set_cache_size(ctx2, 128);
1975 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1977 if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath,
1978 noCApath, CAstore, noCAstore)) {
1979 ERR_print_errors(bio_err);
1982 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1983 BIO_printf(bio_err, "Error setting verify params\n");
1984 ERR_print_errors(bio_err);
1988 ssl_ctx_add_crls(ctx2, crls, 0);
1989 if (!config_ctx(cctx, ssl_args, ctx2))
1992 #ifndef OPENSSL_NO_NEXTPROTONEG
1993 if (next_proto.data)
1994 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1998 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
2001 EVP_PKEY *dhpkey = NULL;
2004 dhpkey = load_keyparams(dhfile, FORMAT_UNDEF, 0, "DH", "DH parameters");
2005 else if (s_cert_file != NULL)
2006 dhpkey = load_keyparams_suppress(s_cert_file, FORMAT_UNDEF, 0, "DH",
2007 "DH parameters", 1);
2009 if (dhpkey != NULL) {
2010 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2012 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
2014 (void)BIO_flush(bio_s_out);
2016 if (dhpkey == NULL) {
2017 SSL_CTX_set_dh_auto(ctx, 1);
2020 * We need 2 references: one for use by ctx and one for use by
2023 if (!EVP_PKEY_up_ref(dhpkey)) {
2024 EVP_PKEY_free(dhpkey);
2027 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) {
2028 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2029 ERR_print_errors(bio_err);
2030 /* Free 2 references */
2031 EVP_PKEY_free(dhpkey);
2032 EVP_PKEY_free(dhpkey);
2038 if (dhfile != NULL) {
2039 EVP_PKEY *dhpkey2 = load_keyparams_suppress(s_cert_file2,
2042 "DH parameters", 1);
2044 if (dhpkey2 != NULL) {
2045 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2046 (void)BIO_flush(bio_s_out);
2048 EVP_PKEY_free(dhpkey);
2052 if (dhpkey == NULL) {
2053 SSL_CTX_set_dh_auto(ctx2, 1);
2054 } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) {
2055 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2056 ERR_print_errors(bio_err);
2057 EVP_PKEY_free(dhpkey);
2062 EVP_PKEY_free(dhpkey);
2065 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
2068 if (s_serverinfo_file != NULL
2069 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
2070 ERR_print_errors(bio_err);
2075 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
2078 if (s_dcert != NULL) {
2079 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
2083 if (no_resume_ephemeral) {
2084 SSL_CTX_set_not_resumable_session_callback(ctx,
2085 not_resumable_sess_cb);
2088 SSL_CTX_set_not_resumable_session_callback(ctx2,
2089 not_resumable_sess_cb);
2091 #ifndef OPENSSL_NO_PSK
2092 if (psk_key != NULL) {
2094 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
2095 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
2098 if (psk_identity_hint != NULL) {
2099 if (min_version == TLS1_3_VERSION) {
2100 BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n");
2102 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
2103 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
2104 ERR_print_errors(bio_err);
2110 if (psksessf != NULL) {
2111 BIO *stmp = BIO_new_file(psksessf, "r");
2114 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
2115 ERR_print_errors(bio_err);
2118 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2120 if (psksess == NULL) {
2121 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
2122 ERR_print_errors(bio_err);
2128 if (psk_key != NULL || psksess != NULL)
2129 SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb);
2131 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
2132 if (!SSL_CTX_set_session_id_context(ctx,
2133 (void *)&s_server_session_id_context,
2134 sizeof(s_server_session_id_context))) {
2135 BIO_printf(bio_err, "error setting session id context\n");
2136 ERR_print_errors(bio_err);
2140 /* Set DTLS cookie generation and verification callbacks */
2141 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
2142 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
2144 /* Set TLS1.3 cookie generation and verification callbacks */
2145 SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback);
2146 SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback);
2149 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
2150 if (!SSL_CTX_set_session_id_context(ctx2,
2151 (void *)&s_server_session_id_context,
2152 sizeof(s_server_session_id_context))) {
2153 BIO_printf(bio_err, "error setting session id context\n");
2154 ERR_print_errors(bio_err);
2157 tlsextcbp.biodebug = bio_s_out;
2158 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
2159 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
2160 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2161 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2164 #ifndef OPENSSL_NO_SRP
2165 if (srp_verifier_file != NULL) {
2166 if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed,
2171 if (CAfile != NULL) {
2172 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2175 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2177 #ifndef OPENSSL_NO_OCSP
2178 if (s_tlsextstatus) {
2179 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2180 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2182 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2183 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2187 if (set_keylog_file(ctx, keylog_file))
2190 if (max_early_data >= 0)
2191 SSL_CTX_set_max_early_data(ctx, max_early_data);
2192 if (recv_max_early_data >= 0)
2193 SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data);
2196 server_cb = rev_body;
2198 server_cb = www_body;
2200 server_cb = sv_body;
2202 if (socket_family == AF_UNIX
2203 && unlink_unix_path)
2206 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2207 server_cb, context, naccept, bio_s_out);
2208 print_stats(bio_s_out, ctx);
2212 SSL_SESSION_free(psksess);
2213 set_keylog_file(NULL, NULL);
2215 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2217 EVP_PKEY_free(s_key);
2218 EVP_PKEY_free(s_dkey);
2219 sk_X509_pop_free(s_chain, X509_free);
2220 sk_X509_pop_free(s_dchain, X509_free);
2222 OPENSSL_free(dpass);
2225 X509_VERIFY_PARAM_free(vpm);
2227 OPENSSL_free(tlscstatp.host);
2228 OPENSSL_free(tlscstatp.port);
2229 OPENSSL_free(tlscstatp.path);
2232 EVP_PKEY_free(s_key2);
2233 #ifndef OPENSSL_NO_NEXTPROTONEG
2234 OPENSSL_free(next_proto.data);
2236 OPENSSL_free(alpn_ctx.data);
2237 ssl_excert_free(exc);
2238 sk_OPENSSL_STRING_free(ssl_args);
2239 SSL_CONF_CTX_free(cctx);
2240 release_engine(engine);
2241 BIO_free(bio_s_out);
2243 BIO_free(bio_s_msg);
2245 #ifdef CHARSET_EBCDIC
2246 BIO_meth_free(methods_ebcdic);
2251 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2253 BIO_printf(bio, "%4ld items in the session cache\n",
2254 SSL_CTX_sess_number(ssl_ctx));
2255 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2256 SSL_CTX_sess_connect(ssl_ctx));
2257 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2258 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2259 BIO_printf(bio, "%4ld client connects that finished\n",
2260 SSL_CTX_sess_connect_good(ssl_ctx));
2261 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2262 SSL_CTX_sess_accept(ssl_ctx));
2263 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2264 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2265 BIO_printf(bio, "%4ld server accepts that finished\n",
2266 SSL_CTX_sess_accept_good(ssl_ctx));
2267 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2268 BIO_printf(bio, "%4ld session cache misses\n",
2269 SSL_CTX_sess_misses(ssl_ctx));
2270 BIO_printf(bio, "%4ld session cache timeouts\n",
2271 SSL_CTX_sess_timeouts(ssl_ctx));
2272 BIO_printf(bio, "%4ld callback cache hits\n",
2273 SSL_CTX_sess_cb_hits(ssl_ctx));
2274 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2275 SSL_CTX_sess_cache_full(ssl_ctx),
2276 SSL_CTX_sess_get_cache_size(ssl_ctx));
2279 static int sv_body(int s, int stype, int prot, unsigned char *context)
2288 struct timeval timeout;
2289 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
2290 struct timeval *timeoutp;
2292 #ifndef OPENSSL_NO_DTLS
2293 # ifndef OPENSSL_NO_SCTP
2294 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2296 int isdtls = (stype == SOCK_DGRAM);
2300 buf = app_malloc(bufsize, "server buffer");
2302 if (!BIO_socket_nbio(s, 1))
2303 ERR_print_errors(bio_err);
2305 BIO_printf(bio_err, "Turned on non blocking io\n");
2314 if (s_tlsextdebug) {
2315 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2316 SSL_set_tlsext_debug_arg(con, bio_s_out);
2320 && !SSL_set_session_id_context(con, context,
2321 strlen((char *)context))) {
2322 BIO_printf(bio_err, "Error setting session id context\n");
2327 if (!SSL_clear(con)) {
2328 BIO_printf(bio_err, "Error clearing SSL connection\n");
2332 #ifndef OPENSSL_NO_DTLS
2334 # ifndef OPENSSL_NO_SCTP
2335 if (prot == IPPROTO_SCTP)
2336 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2339 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2341 if (enable_timeouts) {
2343 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2344 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2347 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2348 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2352 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2353 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2354 DTLS_get_link_min_mtu(con));
2359 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2360 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2361 BIO_printf(bio_err, "Failed to set MTU\n");
2367 /* want to do MTU discovery */
2368 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2370 # ifndef OPENSSL_NO_SCTP
2371 if (prot != IPPROTO_SCTP)
2373 /* Turn on cookie exchange. Not necessary for SCTP */
2374 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2377 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2380 BIO_printf(bio_err, "Unable to create BIO\n");
2381 ERR_print_errors(bio_err);
2388 test = BIO_new(BIO_f_nbio_test());
2389 sbio = BIO_push(test, sbio);
2392 SSL_set_bio(con, sbio, sbio);
2393 SSL_set_accept_state(con);
2394 /* SSL_set_fd(con,s); */
2397 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
2398 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2401 #ifndef OPENSSL_NO_SSL_TRACE
2403 SSL_set_msg_callback(con, SSL_trace);
2406 SSL_set_msg_callback(con, msg_cb);
2407 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2410 if (s_tlsextdebug) {
2411 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2412 SSL_set_tlsext_debug_arg(con, bio_s_out);
2416 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2419 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2421 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2422 if (edret != SSL_READ_EARLY_DATA_ERROR)
2425 switch (SSL_get_error(con, 0)) {
2426 case SSL_ERROR_WANT_WRITE:
2427 case SSL_ERROR_WANT_ASYNC:
2428 case SSL_ERROR_WANT_READ:
2429 /* Just keep trying - busy waiting */
2432 BIO_printf(bio_err, "Error reading early data\n");
2433 ERR_print_errors(bio_err);
2437 if (readbytes > 0) {
2439 BIO_printf(bio_s_out, "Early data received:\n");
2442 raw_write_stdout(buf, (unsigned int)readbytes);
2443 (void)BIO_flush(bio_s_out);
2447 if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT)
2448 BIO_printf(bio_s_out, "No early data received\n");
2450 BIO_printf(bio_s_out, "Early data was rejected\n");
2452 BIO_printf(bio_s_out, "\nEnd of early data\n");
2454 if (SSL_is_init_finished(con))
2455 print_connection_info(con);
2458 if (fileno_stdin() > s)
2459 width = fileno_stdin() + 1;
2463 int read_from_terminal;
2464 int read_from_sslcon;
2466 read_from_terminal = 0;
2467 read_from_sslcon = SSL_has_pending(con)
2468 || (async && SSL_waiting_for_async(con));
2470 if (!read_from_sslcon) {
2472 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2473 openssl_fdset(fileno_stdin(), &readfds);
2475 openssl_fdset(s, &readfds);
2477 * Note: under VMS with SOCKETSHR the second parameter is
2478 * currently of type (int *) whereas under other systems it is
2479 * (void *) if you don't have a cast it will choke the compiler:
2480 * if you do have a cast then you can either go for (int *) or
2483 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2485 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2486 * only on sockets. As a workaround we timeout the select every
2487 * second and check for any keypress. In a proper Windows
2488 * application we wouldn't do this because it is inefficient.
2491 timeout.tv_usec = 0;
2492 i = select(width, (void *)&readfds, NULL, NULL, &timeout);
2493 if (has_stdin_waiting())
2494 read_from_terminal = 1;
2495 if ((i < 0) || (!i && !read_from_terminal))
2498 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2499 timeoutp = &timeout;
2503 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2505 if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
2506 BIO_printf(bio_err, "TIMEOUT occurred\n");
2510 if (FD_ISSET(fileno_stdin(), &readfds))
2511 read_from_terminal = 1;
2513 if (FD_ISSET(s, &readfds))
2514 read_from_sslcon = 1;
2516 if (read_from_terminal) {
2520 i = raw_read_stdin(buf, bufsize / 2);
2522 /* both loops are skipped when i <= 0 */
2523 for (j = 0; j < i; j++)
2526 for (j = i - 1; j >= 0; j--) {
2527 buf[j + lf_num] = buf[j];
2528 if (buf[j] == '\n') {
2531 buf[j + lf_num] = '\r';
2534 assert(lf_num == 0);
2536 i = raw_read_stdin(buf, bufsize);
2539 if (!s_quiet && !s_brief) {
2540 if ((i <= 0) || (buf[0] == 'Q')) {
2541 BIO_printf(bio_s_out, "DONE\n");
2542 (void)BIO_flush(bio_s_out);
2544 close_accept_socket();
2548 if ((i <= 0) || (buf[0] == 'q')) {
2549 BIO_printf(bio_s_out, "DONE\n");
2550 (void)BIO_flush(bio_s_out);
2551 if (SSL_version(con) != DTLS1_VERSION)
2554 * close_accept_socket(); ret= -11;
2558 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2559 SSL_renegotiate(con);
2560 i = SSL_do_handshake(con);
2561 printf("SSL_do_handshake -> %d\n", i);
2565 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2567 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2569 SSL_renegotiate(con);
2570 i = SSL_do_handshake(con);
2571 printf("SSL_do_handshake -> %d\n", i);
2575 if ((buf[0] == 'K' || buf[0] == 'k')
2576 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2577 SSL_key_update(con, buf[0] == 'K' ?
2578 SSL_KEY_UPDATE_REQUESTED
2579 : SSL_KEY_UPDATE_NOT_REQUESTED);
2580 i = SSL_do_handshake(con);
2581 printf("SSL_do_handshake -> %d\n", i);
2585 if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2586 SSL_set_verify(con, SSL_VERIFY_PEER, NULL);
2587 i = SSL_verify_client_post_handshake(con);
2589 printf("Failed to initiate request\n");
2590 ERR_print_errors(bio_err);
2592 i = SSL_do_handshake(con);
2593 printf("SSL_do_handshake -> %d\n", i);
2598 if (buf[0] == 'P') {
2599 static const char str[] = "Lets print some clear text\n";
2600 BIO_write(SSL_get_wbio(con), str, sizeof(str) -1);
2602 if (buf[0] == 'S') {
2603 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2606 #ifdef CHARSET_EBCDIC
2607 ebcdic2ascii(buf, buf, i);
2611 /* should do a select for the write */
2614 if (++count == 100) {
2616 SSL_renegotiate(con);
2619 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2620 #ifndef OPENSSL_NO_SRP
2621 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2622 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2624 lookup_srp_user(&srp_callback_parm, bio_s_out);
2626 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2629 switch (SSL_get_error(con, k)) {
2630 case SSL_ERROR_NONE:
2632 case SSL_ERROR_WANT_ASYNC:
2633 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2634 (void)BIO_flush(bio_s_out);
2635 wait_for_async(con);
2637 case SSL_ERROR_WANT_WRITE:
2638 case SSL_ERROR_WANT_READ:
2639 case SSL_ERROR_WANT_X509_LOOKUP:
2640 BIO_printf(bio_s_out, "Write BLOCK\n");
2641 (void)BIO_flush(bio_s_out);
2643 case SSL_ERROR_WANT_ASYNC_JOB:
2645 * This shouldn't ever happen in s_server. Treat as an error
2647 case SSL_ERROR_SYSCALL:
2649 BIO_printf(bio_s_out, "ERROR\n");
2650 (void)BIO_flush(bio_s_out);
2651 ERR_print_errors(bio_err);
2655 case SSL_ERROR_ZERO_RETURN:
2656 BIO_printf(bio_s_out, "DONE\n");
2657 (void)BIO_flush(bio_s_out);
2669 if (read_from_sslcon) {
2671 * init_ssl_connection handles all async events itself so if we're
2672 * waiting for async then we shouldn't go back into
2673 * init_ssl_connection
2675 if ((!async || !SSL_waiting_for_async(con))
2676 && !SSL_is_init_finished(con)) {
2677 i = init_ssl_connection(con);
2682 } else if (i == 0) {
2688 i = SSL_read(con, (char *)buf, bufsize);
2689 #ifndef OPENSSL_NO_SRP
2690 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2691 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2693 lookup_srp_user(&srp_callback_parm, bio_s_out);
2695 i = SSL_read(con, (char *)buf, bufsize);
2698 switch (SSL_get_error(con, i)) {
2699 case SSL_ERROR_NONE:
2700 #ifdef CHARSET_EBCDIC
2701 ascii2ebcdic(buf, buf, i);
2703 raw_write_stdout(buf, (unsigned int)i);
2704 (void)BIO_flush(bio_s_out);
2705 if (SSL_has_pending(con))
2708 case SSL_ERROR_WANT_ASYNC:
2709 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2710 (void)BIO_flush(bio_s_out);
2711 wait_for_async(con);
2713 case SSL_ERROR_WANT_WRITE:
2714 case SSL_ERROR_WANT_READ:
2715 BIO_printf(bio_s_out, "Read BLOCK\n");
2716 (void)BIO_flush(bio_s_out);
2718 case SSL_ERROR_WANT_ASYNC_JOB:
2720 * This shouldn't ever happen in s_server. Treat as an error
2722 case SSL_ERROR_SYSCALL:
2724 BIO_printf(bio_s_out, "ERROR\n");
2725 (void)BIO_flush(bio_s_out);
2726 ERR_print_errors(bio_err);
2729 case SSL_ERROR_ZERO_RETURN:
2730 BIO_printf(bio_s_out, "DONE\n");
2731 (void)BIO_flush(bio_s_out);
2740 BIO_printf(bio_s_out, "shutting down SSL\n");
2741 do_ssl_shutdown(con);
2744 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2745 OPENSSL_clear_free(buf, bufsize);
2749 static void close_accept_socket(void)
2751 BIO_printf(bio_err, "shutdown accept socket\n");
2752 if (accept_socket >= 0) {
2753 BIO_closesocket(accept_socket);
2757 static int is_retryable(SSL *con, int i)
2759 int err = SSL_get_error(con, i);
2761 /* If it's not a fatal error, it must be retryable */
2762 return (err != SSL_ERROR_SSL)
2763 && (err != SSL_ERROR_SYSCALL)
2764 && (err != SSL_ERROR_ZERO_RETURN);
2767 static int init_ssl_connection(SSL *con)
2773 if (dtlslisten || stateless) {
2774 BIO_ADDR *client = NULL;
2777 if ((client = BIO_ADDR_new()) == NULL) {
2778 BIO_printf(bio_err, "ERROR - memory\n");
2781 i = DTLSv1_listen(con, client);
2783 i = SSL_stateless(con);
2790 wbio = SSL_get_wbio(con);
2792 BIO_get_fd(wbio, &fd);
2795 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2796 BIO_printf(bio_err, "ERROR - unable to connect\n");
2797 BIO_ADDR_free(client);
2801 (void)BIO_ctrl_set_connected(wbio, client);
2802 BIO_ADDR_free(client);
2807 i = SSL_accept(con);
2809 BIO_ADDR_free(client);
2813 i = SSL_accept(con);
2814 if (immediate_reneg)
2815 SSL_renegotiate(con);
2818 retry = is_retryable(con, i);
2819 #ifdef CERT_CB_TEST_RETRY
2822 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2823 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2825 "LOOKUP from certificate callback during accept\n");
2826 i = SSL_accept(con);
2828 retry = is_retryable(con, i);
2833 #ifndef OPENSSL_NO_SRP
2835 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2836 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2837 srp_callback_parm.login);
2839 lookup_srp_user(&srp_callback_parm, bio_s_out);
2841 i = SSL_accept(con);
2843 retry = is_retryable(con, i);
2846 } while (i < 0 && SSL_waiting_for_async(con));
2850 if (((dtlslisten || stateless) && i == 0)
2851 || (!dtlslisten && !stateless && retry)) {
2852 BIO_printf(bio_s_out, "DELAY\n");
2856 BIO_printf(bio_err, "ERROR\n");
2858 verify_err = SSL_get_verify_result(con);
2859 if (verify_err != X509_V_OK) {
2860 BIO_printf(bio_err, "verify error:%s\n",
2861 X509_verify_cert_error_string(verify_err));
2863 /* Always print any error messages */
2864 ERR_print_errors(bio_err);
2868 print_connection_info(con);
2872 static void print_connection_info(SSL *con)
2877 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2878 const unsigned char *next_proto_neg;
2879 unsigned next_proto_neg_len;
2881 unsigned char *exportedkeymat;
2885 print_ssl_summary(con);
2887 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2889 peer = SSL_get0_peer_certificate(con);
2891 BIO_printf(bio_s_out, "Client certificate\n");
2892 PEM_write_bio_X509(bio_s_out, peer);
2893 dump_cert_text(bio_s_out, peer);
2897 if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
2898 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2899 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2900 ssl_print_sigalgs(bio_s_out, con);
2901 #ifndef OPENSSL_NO_EC
2902 ssl_print_point_formats(bio_s_out, con);
2903 ssl_print_groups(bio_s_out, con, 0);
2905 print_ca_names(bio_s_out, con);
2906 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2908 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2909 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2910 if (next_proto_neg) {
2911 BIO_printf(bio_s_out, "NEXTPROTO is ");
2912 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2913 BIO_printf(bio_s_out, "\n");
2916 #ifndef OPENSSL_NO_SRTP
2918 SRTP_PROTECTION_PROFILE *srtp_profile
2919 = SSL_get_selected_srtp_profile(con);
2922 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2923 srtp_profile->name);
2926 if (SSL_session_reused(con))
2927 BIO_printf(bio_s_out, "Reused session-id\n");
2928 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2929 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2930 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
2931 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
2933 if (keymatexportlabel != NULL) {
2934 BIO_printf(bio_s_out, "Keying material exporter:\n");
2935 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2936 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2937 exportedkeymat = app_malloc(keymatexportlen, "export key");
2938 if (!SSL_export_keying_material(con, exportedkeymat,
2941 strlen(keymatexportlabel),
2943 BIO_printf(bio_s_out, " Error\n");
2945 BIO_printf(bio_s_out, " Keying material: ");
2946 for (i = 0; i < keymatexportlen; i++)
2947 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2948 BIO_printf(bio_s_out, "\n");
2950 OPENSSL_free(exportedkeymat);
2952 #ifndef OPENSSL_NO_KTLS
2953 if (BIO_get_ktls_send(SSL_get_wbio(con)))
2954 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
2955 if (BIO_get_ktls_recv(SSL_get_rbio(con)))
2956 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
2959 (void)BIO_flush(bio_s_out);
2962 static int www_body(int s, int stype, int prot, unsigned char *context)
2968 const SSL_CIPHER *c;
2969 BIO *io, *ssl_bio, *sbio;
2971 int total_bytes = 0;
2977 /* Set width for a select call if needed */
2980 buf = app_malloc(bufsize, "server www buffer");
2981 io = BIO_new(BIO_f_buffer());
2982 ssl_bio = BIO_new(BIO_f_ssl());
2983 if ((io == NULL) || (ssl_bio == NULL))
2987 if (!BIO_socket_nbio(s, 1))
2988 ERR_print_errors(bio_err);
2990 BIO_printf(bio_err, "Turned on non blocking io\n");
2993 /* lets make the output buffer a reasonable size */
2994 if (!BIO_set_write_buffer_size(io, bufsize))
2997 if ((con = SSL_new(ctx)) == NULL)
3000 if (s_tlsextdebug) {
3001 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3002 SSL_set_tlsext_debug_arg(con, bio_s_out);
3006 && !SSL_set_session_id_context(con, context,
3007 strlen((char *)context))) {
3012 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3016 test = BIO_new(BIO_f_nbio_test());
3017 sbio = BIO_push(test, sbio);
3019 SSL_set_bio(con, sbio, sbio);
3020 SSL_set_accept_state(con);
3022 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3023 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3024 BIO_push(io, ssl_bio);
3025 #ifdef CHARSET_EBCDIC
3026 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3030 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3031 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3034 #ifndef OPENSSL_NO_SSL_TRACE
3036 SSL_set_msg_callback(con, SSL_trace);
3039 SSL_set_msg_callback(con, msg_cb);
3040 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3044 i = BIO_gets(io, buf, bufsize - 1);
3045 if (i < 0) { /* error */
3046 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
3048 ERR_print_errors(bio_err);
3051 BIO_printf(bio_s_out, "read R BLOCK\n");
3052 #ifndef OPENSSL_NO_SRP
3053 if (BIO_should_io_special(io)
3054 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3055 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3057 lookup_srp_user(&srp_callback_parm, bio_s_out);
3065 } else if (i == 0) { /* end of input */
3070 /* else we have data */
3071 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
3072 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
3075 STACK_OF(SSL_CIPHER) *sk;
3076 static const char *space = " ";
3078 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
3079 if (strncmp("GET /renegcert", buf, 14) == 0)
3081 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
3083 i = SSL_renegotiate(con);
3084 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
3085 /* Send the HelloRequest */
3086 i = SSL_do_handshake(con);
3088 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
3089 SSL_get_error(con, i));
3090 ERR_print_errors(bio_err);
3093 /* Wait for a ClientHello to come back */
3095 openssl_fdset(s, &readfds);
3096 i = select(width, (void *)&readfds, NULL, NULL, NULL);
3097 if (i <= 0 || !FD_ISSET(s, &readfds)) {
3098 BIO_printf(bio_s_out,
3099 "Error waiting for client response\n");
3100 ERR_print_errors(bio_err);
3104 * We're not actually expecting any data here and we ignore
3105 * any that is sent. This is just to force the handshake that
3106 * we're expecting to come from the client. If they haven't
3107 * sent one there's not much we can do.
3109 BIO_gets(io, buf, bufsize - 1);
3113 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3114 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
3115 BIO_puts(io, "<pre>\n");
3116 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
3118 for (i = 0; i < local_argc; i++) {
3120 for (myp = local_argv[i]; *myp; myp++)
3123 BIO_puts(io, "<");
3126 BIO_puts(io, ">");
3129 BIO_puts(io, "&");
3132 BIO_write(io, myp, 1);
3135 BIO_write(io, " ", 1);
3140 "Secure Renegotiation IS%s supported\n",
3141 SSL_get_secure_renegotiation_support(con) ?
3145 * The following is evil and should not really be done
3147 BIO_printf(io, "Ciphers supported in s_server binary\n");
3148 sk = SSL_get_ciphers(con);
3149 j = sk_SSL_CIPHER_num(sk);
3150 for (i = 0; i < j; i++) {
3151 c = sk_SSL_CIPHER_value(sk, i);
3152 BIO_printf(io, "%-11s:%-25s ",
3153 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3154 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3158 p = SSL_get_shared_ciphers(con, buf, bufsize);
3161 "---\nCiphers common between both SSL end points:\n");
3165 BIO_write(io, space, 26 - j);
3168 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3170 BIO_write(io, p, 1);
3177 ssl_print_sigalgs(io, con);
3178 #ifndef OPENSSL_NO_EC
3179 ssl_print_groups(io, con, 0);
3181 print_ca_names(io, con);
3182 BIO_printf(io, (SSL_session_reused(con)
3183 ? "---\nReused, " : "---\nNew, "));
3184 c = SSL_get_current_cipher(con);
3185 BIO_printf(io, "%s, Cipher is %s\n",
3186 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3187 SSL_SESSION_print(io, SSL_get_session(con));
3188 BIO_printf(io, "---\n");
3189 print_stats(io, SSL_get_SSL_CTX(con));
3190 BIO_printf(io, "---\n");
3191 peer = SSL_get0_peer_certificate(con);
3193 BIO_printf(io, "Client certificate\n");
3194 X509_print(io, peer);
3195 PEM_write_bio_X509(io, peer);
3198 BIO_puts(io, "no client certificate available\n");
3200 BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
3202 } else if ((www == 2 || www == 3)
3203 && (strncmp("GET /", buf, 5) == 0)) {
3206 static const char *text =
3207 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3213 for (e = p; *e != '\0'; e++) {
3218 /* Windows drive. We treat this the same way as ".." */
3225 dot = (e[0] == '.') ? 2 : 0;
3228 dot = (e[0] == '.') ? 3 : 0;
3231 dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0;
3235 dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0;
3237 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3242 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3249 BIO_printf(io, "'%s' contains '..' or ':'\r\n", p);
3253 if (*p == '/' || *p == '\\') {
3255 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3259 /* if a directory, do the index thang */
3260 if (app_isdir(p) > 0) {
3262 BIO_printf(io, "'%s' is a directory\r\n", p);
3266 opmode = (http_server_binmode == 1) ? "rb" : "r";
3267 if ((file = BIO_new_file(p, opmode)) == NULL) {
3269 BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode);
3270 ERR_print_errors(io);
3275 BIO_printf(bio_err, "FILE:%s\n", p);
3279 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3280 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3281 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3283 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3286 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3289 #ifndef OPENSSL_NO_KTLS
3297 BIO_get_fp(file, &fp);
3299 if (fstat(fd, &st) < 0) {
3300 BIO_printf(io, "Error fstat '%s'\r\n", p);
3301 ERR_print_errors(io);
3305 filesize = st.st_size;
3306 if (((int)BIO_flush(io)) < 0)
3310 i = SSL_sendfile(con, fd, offset, filesize, 0);
3312 BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p);
3313 ERR_print_errors(io);
3320 if (filesize <= 0) {
3322 BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p);
3331 i = BIO_read(file, buf, bufsize);
3337 BIO_printf(bio_err, "%d\n", i);
3338 if (total_bytes > 3 * 1024) {
3340 BIO_printf(bio_err, "RENEGOTIATE\n");
3341 SSL_renegotiate(con);
3345 for (j = 0; j < i;) {
3349 SSL_renegotiate(con);
3351 k = BIO_write(io, &(buf[j]), i - j);
3353 if (!BIO_should_retry(io)
3354 && !SSL_waiting_for_async(con)) {
3357 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3372 i = (int)BIO_flush(io);
3374 if (!BIO_should_retry(io))
3380 /* make sure we re-use sessions */
3381 do_ssl_shutdown(con);
3389 static int rev_body(int s, int stype, int prot, unsigned char *context)
3395 BIO *io, *ssl_bio, *sbio;
3397 buf = app_malloc(bufsize, "server rev buffer");
3398 io = BIO_new(BIO_f_buffer());
3399 ssl_bio = BIO_new(BIO_f_ssl());
3400 if ((io == NULL) || (ssl_bio == NULL))
3403 /* lets make the output buffer a reasonable size */
3404 if (!BIO_set_write_buffer_size(io, bufsize))
3407 if ((con = SSL_new(ctx)) == NULL)
3410 if (s_tlsextdebug) {
3411 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3412 SSL_set_tlsext_debug_arg(con, bio_s_out);
3415 && !SSL_set_session_id_context(con, context,
3416 strlen((char *)context))) {
3418 ERR_print_errors(bio_err);
3422 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3423 SSL_set_bio(con, sbio, sbio);
3424 SSL_set_accept_state(con);
3426 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3427 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3428 BIO_push(io, ssl_bio);
3429 #ifdef CHARSET_EBCDIC
3430 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3434 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3435 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3438 #ifndef OPENSSL_NO_SSL_TRACE
3440 SSL_set_msg_callback(con, SSL_trace);
3443 SSL_set_msg_callback(con, msg_cb);
3444 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3448 i = BIO_do_handshake(io);
3451 if (!BIO_should_retry(io)) {
3452 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3453 ERR_print_errors(bio_err);
3456 #ifndef OPENSSL_NO_SRP
3457 if (BIO_should_io_special(io)
3458 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3459 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3461 lookup_srp_user(&srp_callback_parm, bio_s_out);
3467 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3468 print_ssl_summary(con);
3471 i = BIO_gets(io, buf, bufsize - 1);
3472 if (i < 0) { /* error */
3473 if (!BIO_should_retry(io)) {
3475 ERR_print_errors(bio_err);
3478 BIO_printf(bio_s_out, "read R BLOCK\n");
3479 #ifndef OPENSSL_NO_SRP
3480 if (BIO_should_io_special(io)
3481 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3482 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3484 lookup_srp_user(&srp_callback_parm, bio_s_out);
3492 } else if (i == 0) { /* end of input */
3494 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3497 char *p = buf + i - 1;
3498 while (i && (*p == '\n' || *p == '\r')) {
3502 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3504 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3507 BUF_reverse((unsigned char *)buf, NULL, i);
3509 BIO_write(io, buf, i + 1);
3514 if (!BIO_should_retry(io))
3520 /* make sure we re-use sessions */
3521 do_ssl_shutdown(con);
3530 #define MAX_SESSION_ID_ATTEMPTS 10
3531 static int generate_session_id(SSL *ssl, unsigned char *id,
3532 unsigned int *id_len)
3534 unsigned int count = 0;
3535 unsigned int session_id_prefix_len = strlen(session_id_prefix);
3538 if (RAND_bytes(id, *id_len) <= 0)
3541 * Prefix the session_id with the required prefix. NB: If our prefix
3542 * is too long, clip it - but there will be worse effects anyway, eg.
3543 * the server could only possibly create 1 session ID (ie. the
3544 * prefix!) so all future session negotiations will fail due to
3547 memcpy(id, session_id_prefix,
3548 (session_id_prefix_len < *id_len) ?
3549 session_id_prefix_len : *id_len);
3551 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3552 (++count < MAX_SESSION_ID_ATTEMPTS));
3553 if (count >= MAX_SESSION_ID_ATTEMPTS)
3559 * By default s_server uses an in-memory cache which caches SSL_SESSION
3560 * structures without any serialization. This hides some bugs which only
3561 * become apparent in deployed servers. By implementing a basic external
3562 * session cache some issues can be debugged using s_server.
3565 typedef struct simple_ssl_session_st {
3570 struct simple_ssl_session_st *next;
3571 } simple_ssl_session;
3573 static simple_ssl_session *first = NULL;
3575 static int add_session(SSL *ssl, SSL_SESSION *session)
3577 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3580 SSL_SESSION_get_id(session, &sess->idlen);
3581 sess->derlen = i2d_SSL_SESSION(session, NULL);
3582 if (sess->derlen < 0) {
3583 BIO_printf(bio_err, "Error encoding session\n");
3588 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3589 sess->der = app_malloc(sess->derlen, "get session buffer");
3591 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3592 OPENSSL_free(sess->id);
3593 OPENSSL_free(sess->der);
3599 /* Assume it still works. */
3600 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3601 BIO_printf(bio_err, "Unexpected session encoding length\n");
3602 OPENSSL_free(sess->id);
3603 OPENSSL_free(sess->der);
3610 BIO_printf(bio_err, "New session added to external cache\n");
3614 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3617 simple_ssl_session *sess;
3619 for (sess = first; sess; sess = sess->next) {
3620 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3621 const unsigned char *p = sess->der;
3622 BIO_printf(bio_err, "Lookup session: cache hit\n");
3623 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3626 BIO_printf(bio_err, "Lookup session: cache miss\n");
3630 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3632 simple_ssl_session *sess, *prev = NULL;
3633 const unsigned char *id;
3635 id = SSL_SESSION_get_id(session, &idlen);
3636 for (sess = first; sess; sess = sess->next) {
3637 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3639 prev->next = sess->next;
3642 OPENSSL_free(sess->id);
3643 OPENSSL_free(sess->der);
3651 static void init_session_cache_ctx(SSL_CTX *sctx)
3653 SSL_CTX_set_session_cache_mode(sctx,
3654 SSL_SESS_CACHE_NO_INTERNAL |
3655 SSL_SESS_CACHE_SERVER);
3656 SSL_CTX_sess_set_new_cb(sctx, add_session);
3657 SSL_CTX_sess_set_get_cb(sctx, get_session);
3658 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3661 static void free_sessions(void)
3663 simple_ssl_session *sess, *tsess;
3664 for (sess = first; sess;) {
3665 OPENSSL_free(sess->id);
3666 OPENSSL_free(sess->der);
3669 OPENSSL_free(tsess);
3674 #endif /* OPENSSL_NO_SOCK */