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 SSL_CTX *ctx = NULL;
82 static SSL_CTX *ctx2 = NULL;
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;
90 static int s_quiet = 0;
91 static int s_ign_eof = 0;
92 static int s_brief = 0;
94 static char *keymatexportlabel = NULL;
95 static int keymatexportlen = 20;
99 static int use_sendfile = 0;
101 static const char *session_id_prefix = NULL;
103 #ifndef OPENSSL_NO_DTLS
104 static int enable_timeouts = 0;
105 static long socket_mtu;
109 * We define this but make it always be 0 in no-dtls builds to simplify the
112 static int dtlslisten = 0;
113 static int stateless = 0;
115 static int early_data = 0;
116 static SSL_SESSION *psksess = NULL;
118 static char *psk_identity = "Client_identity";
119 char *psk_key = NULL; /* by default PSK is not used */
121 static char http_server_binmode = 0; /* for now: 0/1 = default/binary */
123 #ifndef OPENSSL_NO_PSK
124 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
126 unsigned int max_psk_len)
132 BIO_printf(bio_s_out, "psk_server_cb\n");
134 if (!SSL_is_dtls(ssl) && SSL_version(ssl) >= TLS1_3_VERSION) {
136 * This callback is designed for use in (D)TLSv1.2 (or below). It is
137 * possible to use a single callback for all protocol versions - but it
138 * is preferred to use a dedicated callback for TLSv1.3. For TLSv1.3 we
139 * have psk_find_session_cb.
144 if (identity == NULL) {
145 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
149 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
150 (int)strlen(identity), identity);
152 /* here we could lookup the given identity e.g. from a database */
153 if (strcmp(identity, psk_identity) != 0) {
154 BIO_printf(bio_s_out, "PSK warning: client identity not what we expected"
155 " (got '%s' expected '%s')\n", identity, psk_identity);
158 BIO_printf(bio_s_out, "PSK client identity found\n");
161 /* convert the PSK key to binary */
162 key = OPENSSL_hexstr2buf(psk_key, &key_len);
164 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
168 if (key_len > (int)max_psk_len) {
170 "psk buffer of callback is too small (%d) for key (%ld)\n",
171 max_psk_len, key_len);
176 memcpy(psk, key, key_len);
180 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
184 BIO_printf(bio_err, "Error in PSK server callback\n");
185 (void)BIO_flush(bio_err);
186 (void)BIO_flush(bio_s_out);
191 static int psk_find_session_cb(SSL *ssl, const unsigned char *identity,
192 size_t identity_len, SSL_SESSION **sess)
194 SSL_SESSION *tmpsess = NULL;
197 const SSL_CIPHER *cipher = NULL;
199 if (strlen(psk_identity) != identity_len
200 || memcmp(psk_identity, identity, identity_len) != 0) {
205 if (psksess != NULL) {
206 SSL_SESSION_up_ref(psksess);
211 key = OPENSSL_hexstr2buf(psk_key, &key_len);
213 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
218 /* We default to SHA256 */
219 cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id);
220 if (cipher == NULL) {
221 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
226 tmpsess = SSL_SESSION_new();
228 || !SSL_SESSION_set1_master_key(tmpsess, key, key_len)
229 || !SSL_SESSION_set_cipher(tmpsess, cipher)
230 || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) {
240 #ifndef OPENSSL_NO_SRP
241 static srpsrvparm srp_callback_parm;
244 static int local_argc = 0;
245 static char **local_argv;
247 #ifdef CHARSET_EBCDIC
248 static int ebcdic_new(BIO *bi);
249 static int ebcdic_free(BIO *a);
250 static int ebcdic_read(BIO *b, char *out, int outl);
251 static int ebcdic_write(BIO *b, const char *in, int inl);
252 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
253 static int ebcdic_gets(BIO *bp, char *buf, int size);
254 static int ebcdic_puts(BIO *bp, const char *str);
256 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
257 static BIO_METHOD *methods_ebcdic = NULL;
259 /* This struct is "unwarranted chumminess with the compiler." */
265 static const BIO_METHOD *BIO_f_ebcdic_filter()
267 if (methods_ebcdic == NULL) {
268 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
269 "EBCDIC/ASCII filter");
270 if (methods_ebcdic == NULL
271 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
272 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
273 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
274 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
275 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
276 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
277 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
280 return methods_ebcdic;
283 static int ebcdic_new(BIO *bi)
285 EBCDIC_OUTBUFF *wbuf;
287 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
288 wbuf->alloced = 1024;
289 wbuf->buff[0] = '\0';
291 BIO_set_data(bi, wbuf);
296 static int ebcdic_free(BIO *a)
298 EBCDIC_OUTBUFF *wbuf;
302 wbuf = BIO_get_data(a);
304 BIO_set_data(a, NULL);
310 static int ebcdic_read(BIO *b, char *out, int outl)
313 BIO *next = BIO_next(b);
315 if (out == NULL || outl == 0)
320 ret = BIO_read(next, out, outl);
322 ascii2ebcdic(out, out, ret);
326 static int ebcdic_write(BIO *b, const char *in, int inl)
328 EBCDIC_OUTBUFF *wbuf;
329 BIO *next = BIO_next(b);
333 if ((in == NULL) || (inl <= 0))
338 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
340 if (inl > (num = wbuf->alloced)) {
341 num = num + num; /* double the size */
345 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
348 wbuf->buff[0] = '\0';
350 BIO_set_data(b, wbuf);
353 ebcdic2ascii(wbuf->buff, in, inl);
355 ret = BIO_write(next, wbuf->buff, inl);
360 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
363 BIO *next = BIO_next(b);
372 ret = BIO_ctrl(next, cmd, num, ptr);
378 static int ebcdic_gets(BIO *bp, char *buf, int size)
381 BIO *next = BIO_next(bp);
385 /* return(BIO_gets(bp->next_bio,buf,size));*/
386 for (i = 0; i < size - 1; ++i) {
387 ret = ebcdic_read(bp, &buf[i], 1);
390 else if (buf[i] == '\n') {
397 return (ret < 0 && i == 0) ? ret : i;
400 static int ebcdic_puts(BIO *bp, const char *str)
402 if (BIO_next(bp) == NULL)
404 return ebcdic_write(bp, str, strlen(str));
408 /* This is a context that we pass to callbacks */
409 typedef struct tlsextctx_st {
415 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
417 tlsextctx *p = (tlsextctx *) arg;
418 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
420 if (servername != NULL && p->biodebug != NULL) {
421 const char *cp = servername;
424 BIO_printf(p->biodebug, "Hostname in TLS extension: \"");
425 while ((uc = *cp++) != 0)
426 BIO_printf(p->biodebug,
427 (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc);
428 BIO_printf(p->biodebug, "\"\n");
431 if (p->servername == NULL)
432 return SSL_TLSEXT_ERR_NOACK;
434 if (servername != NULL) {
435 if (strcasecmp(servername, p->servername))
436 return p->extension_error;
438 BIO_printf(p->biodebug, "Switching server context.\n");
439 SSL_set_SSL_CTX(s, ctx2);
442 return SSL_TLSEXT_ERR_OK;
445 /* Structure passed to cert status callback */
446 typedef struct tlsextstatusctx_st {
448 /* File to load OCSP Response from (or NULL if no file) */
450 /* Default responder to use */
451 char *host, *path, *port;
452 char *proxy, *no_proxy;
457 static tlsextstatusctx tlscstatp = { -1 };
459 #ifndef OPENSSL_NO_OCSP
462 * Helper function to get an OCSP_RESPONSE from a responder. This is a
463 * simplified version. It examines certificates each time and makes one OCSP
464 * responder query for each request. A full version would store details such as
465 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
466 * them until they were considered "expired".
468 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
469 OCSP_RESPONSE **resp)
471 char *host = NULL, *port = NULL, *path = NULL;
472 char *proxy = NULL, *no_proxy = NULL;
474 STACK_OF(OPENSSL_STRING) *aia = NULL;
476 X509_STORE_CTX *inctx = NULL;
478 OCSP_REQUEST *req = NULL;
479 OCSP_CERTID *id = NULL;
480 STACK_OF(X509_EXTENSION) *exts;
481 int ret = SSL_TLSEXT_ERR_NOACK;
484 /* Build up OCSP query from server certificate */
485 x = SSL_get_certificate(s);
486 aia = X509_get1_ocsp(x);
488 if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl,
489 NULL, &host, &port, NULL, &path, NULL, NULL)) {
490 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
494 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
495 sk_OPENSSL_STRING_value(aia, 0));
497 if (srctx->host == NULL) {
499 "cert_status: no AIA and no default responder URL\n");
505 use_ssl = srctx->use_ssl;
507 proxy = srctx->proxy;
508 no_proxy = srctx->no_proxy;
510 inctx = X509_STORE_CTX_new();
513 if (!X509_STORE_CTX_init(inctx,
514 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
517 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
518 X509_get_issuer_name(x));
520 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
523 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
524 X509_OBJECT_free(obj);
527 req = OCSP_REQUEST_new();
530 if (!OCSP_request_add0_id(req, id))
533 /* Add any extensions to the request */
534 SSL_get_tlsext_status_exts(s, &exts);
535 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
536 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
537 if (!OCSP_REQUEST_add_ext(req, ext, -1))
540 *resp = process_responder(req, host, port, path, proxy, no_proxy,
541 use_ssl, NULL /* headers */, srctx->timeout);
543 BIO_puts(bio_err, "cert_status: error querying responder\n");
547 ret = SSL_TLSEXT_ERR_OK;
551 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
554 * If we parsed aia we need to free; otherwise they were copied and we
561 X509_email_free(aia);
563 OCSP_CERTID_free(id);
564 OCSP_REQUEST_free(req);
565 X509_STORE_CTX_free(inctx);
570 * Certificate Status callback. This is called when a client includes a
571 * certificate status request extension. The response is either obtained from a
572 * file, or from an OCSP responder.
574 static int cert_status_cb(SSL *s, void *arg)
576 tlsextstatusctx *srctx = arg;
577 OCSP_RESPONSE *resp = NULL;
578 unsigned char *rspder = NULL;
580 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
583 BIO_puts(bio_err, "cert_status: callback called\n");
585 if (srctx->respin != NULL) {
586 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
587 if (derbio == NULL) {
588 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
591 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
594 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
598 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
599 if (ret != SSL_TLSEXT_ERR_OK)
603 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
607 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
608 if (srctx->verbose) {
609 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
610 OCSP_RESPONSE_print(bio_err, resp, 2);
613 ret = SSL_TLSEXT_ERR_OK;
616 if (ret != SSL_TLSEXT_ERR_OK)
617 ERR_print_errors(bio_err);
619 OCSP_RESPONSE_free(resp);
625 #ifndef OPENSSL_NO_NEXTPROTONEG
626 /* This is the context that we pass to next_proto_cb */
627 typedef struct tlsextnextprotoctx_st {
630 } tlsextnextprotoctx;
632 static int next_proto_cb(SSL *s, const unsigned char **data,
633 unsigned int *len, void *arg)
635 tlsextnextprotoctx *next_proto = arg;
637 *data = next_proto->data;
638 *len = next_proto->len;
640 return SSL_TLSEXT_ERR_OK;
642 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
644 /* This the context that we pass to alpn_cb */
645 typedef struct tlsextalpnctx_st {
650 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
651 const unsigned char *in, unsigned int inlen, void *arg)
653 tlsextalpnctx *alpn_ctx = arg;
656 /* We can assume that |in| is syntactically valid. */
658 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
659 for (i = 0; i < inlen;) {
661 BIO_write(bio_s_out, ", ", 2);
662 BIO_write(bio_s_out, &in[i + 1], in[i]);
665 BIO_write(bio_s_out, "\n", 1);
668 if (SSL_select_next_proto
669 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
670 inlen) != OPENSSL_NPN_NEGOTIATED) {
671 return SSL_TLSEXT_ERR_ALERT_FATAL;
675 BIO_printf(bio_s_out, "ALPN protocols selected: ");
676 BIO_write(bio_s_out, *out, *outlen);
677 BIO_write(bio_s_out, "\n", 1);
680 return SSL_TLSEXT_ERR_OK;
683 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
685 /* disable resumption for sessions with forward secure ciphers */
686 return is_forward_secure;
689 typedef enum OPTION_choice {
692 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
693 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
694 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
695 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
696 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
697 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
698 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
699 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
701 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
702 OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
703 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
704 OPT_STATUS_TIMEOUT, OPT_PROXY, OPT_NO_PROXY, OPT_STATUS_URL,
705 OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
706 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
707 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
708 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK,
709 OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW,
710 OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG,
711 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
712 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
713 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS,
714 OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
715 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE,
716 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
717 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA,
718 OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG,
719 OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF, OPT_KTLS,
727 const OPTIONS s_server_options[] = {
728 OPT_SECTION("General"),
729 {"help", OPT_HELP, '-', "Display this summary"},
730 {"ssl_config", OPT_SSL_CONFIG, 's',
731 "Configure SSL_CTX using the given configuration value"},
732 #ifndef OPENSSL_NO_SSL_TRACE
733 {"trace", OPT_TRACE, '-', "trace protocol messages"},
735 #ifndef OPENSSL_NO_ENGINE
736 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
739 OPT_SECTION("Network"),
740 {"port", OPT_PORT, 'p',
741 "TCP/IP port to listen on for connections (default is " PORT ")"},
742 {"accept", OPT_ACCEPT, 's',
743 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
745 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
746 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
748 {"4", OPT_4, '-', "Use IPv4 only"},
749 {"6", OPT_6, '-', "Use IPv6 only"},
751 OPT_SECTION("Identity"),
752 {"context", OPT_CONTEXT, 's', "Set session ID context"},
753 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
754 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
755 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
756 {"no-CAfile", OPT_NOCAFILE, '-',
757 "Do not load the default certificates file"},
758 {"no-CApath", OPT_NOCAPATH, '-',
759 "Do not load certificates from the default certificates directory"},
760 {"no-CAstore", OPT_NOCASTORE, '-',
761 "Do not load certificates from the default certificates store URI"},
762 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
763 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
764 {"Verify", OPT_UPPER_V_VERIFY, 'n',
765 "Turn on peer certificate verification, must have a cert"},
766 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
767 {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT},
768 {"cert2", OPT_CERT2, '<',
769 "Certificate file to use for servername; default " TEST_CERT2},
770 {"certform", OPT_CERTFORM, 'F',
771 "Server certificate file format (PEM/DER/P12); has no effect"},
772 {"cert_chain", OPT_CERT_CHAIN, '<',
773 "Server certificate chain file in PEM format"},
774 {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"},
775 {"serverinfo", OPT_SERVERINFO, 's',
776 "PEM serverinfo file for certificate"},
777 {"key", OPT_KEY, 's',
778 "Private key file to use; default is -cert file or else" TEST_CERT},
779 {"key2", OPT_KEY2, '<',
780 "-Private Key file to use for servername if not in -cert2"},
781 {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"},
782 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
783 {"dcert", OPT_DCERT, '<',
784 "Second server certificate file to use (usually for DSA)"},
785 {"dcertform", OPT_DCERTFORM, 'F',
786 "Second server certificate file format (PEM/DER/P12); has no effect"},
787 {"dcert_chain", OPT_DCERT_CHAIN, '<',
788 "second server certificate chain file in PEM format"},
789 {"dkey", OPT_DKEY, '<',
790 "Second private key file to use (usually for DSA)"},
791 {"dkeyform", OPT_DKEYFORM, 'F',
792 "Second key file format (ENGINE, other values ignored)"},
793 {"dpass", OPT_DPASS, 's',
794 "Second private key and cert file pass phrase source"},
795 {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
796 {"servername", OPT_SERVERNAME, 's',
797 "Servername for HostName TLS extension"},
798 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
799 "On servername mismatch send fatal alert (default warning alert)"},
800 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
801 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
802 {"quiet", OPT_QUIET, '-', "No server output"},
803 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
804 "Disable caching and tickets if ephemeral (EC)DH is used"},
805 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
806 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
807 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
808 "Do not treat lack of close_notify from a peer as an error"},
809 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
810 "Hex dump of all TLS extensions received"},
811 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
812 {"id_prefix", OPT_ID_PREFIX, 's',
813 "Generate SSL/TLS session IDs prefixed by arg"},
814 {"keymatexport", OPT_KEYMATEXPORT, 's',
815 "Export keying material using label"},
816 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
817 "Export len bytes of keying material; default 20"},
818 {"CRL", OPT_CRL, '<', "CRL file to use"},
819 {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"},
820 {"crl_download", OPT_CRL_DOWNLOAD, '-',
821 "Download CRLs from distribution points in certificate CDP entries"},
822 {"chainCAfile", OPT_CHAINCAFILE, '<',
823 "CA file for certificate chain (PEM format)"},
824 {"chainCApath", OPT_CHAINCAPATH, '/',
825 "use dir as certificate store path to build CA certificate chain"},
826 {"chainCAstore", OPT_CHAINCASTORE, ':',
827 "use URI as certificate store to build CA certificate chain"},
828 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
829 "CA file for certificate verification (PEM format)"},
830 {"verifyCApath", OPT_VERIFYCAPATH, '/',
831 "use dir as certificate store path to verify CA certificate"},
832 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
833 "use URI as certificate store to verify CA certificate"},
834 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
835 {"ext_cache", OPT_EXT_CACHE, '-',
836 "Disable internal cache, set up and use external cache"},
837 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
838 "Close connection on verification error"},
839 {"verify_quiet", OPT_VERIFY_QUIET, '-',
840 "No verify output except verify errors"},
841 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input EOF (default when -quiet)"},
842 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input EOF"},
844 #ifndef OPENSSL_NO_OCSP
846 {"status", OPT_STATUS, '-', "Request certificate status from server"},
847 {"status_verbose", OPT_STATUS_VERBOSE, '-',
848 "Print more output in certificate status callback"},
849 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
850 "Status request responder timeout"},
851 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
852 {"proxy", OPT_PROXY, 's',
853 "[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"},
854 {"no_proxy", OPT_NO_PROXY, 's',
855 "List of addresses of servers not to use HTTP(S) proxy for"},
857 "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
858 {"status_file", OPT_STATUS_FILE, '<',
859 "File containing DER encoded OCSP Response"},
862 OPT_SECTION("Debug"),
863 {"security_debug", OPT_SECURITY_DEBUG, '-',
864 "Print output from SSL/TLS security framework"},
865 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
866 "Print more output from SSL/TLS security framework"},
867 {"brief", OPT_BRIEF, '-',
868 "Restrict output to brief summary of connection parameters"},
869 {"rev", OPT_REV, '-',
870 "act as an echo server that sends back received text reversed"},
871 {"debug", OPT_DEBUG, '-', "Print more output"},
872 {"msg", OPT_MSG, '-', "Show protocol messages"},
873 {"msgfile", OPT_MSGFILE, '>',
874 "File to send output of -msg or -trace, instead of stdout"},
875 {"state", OPT_STATE, '-', "Print the SSL states"},
876 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
877 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
878 "Maximum number of encrypt/decrypt pipelines to be used"},
879 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
880 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
882 OPT_SECTION("Network"),
883 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
884 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
885 {"mtu", OPT_MTU, 'p', "Set link-layer MTU"},
886 {"read_buf", OPT_READ_BUF, 'p',
887 "Default read buffer size to be used for connections"},
888 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
889 "Size used to split data for encrypt pipelines"},
890 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
892 OPT_SECTION("Server identity"),
893 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
894 #ifndef OPENSSL_NO_PSK
895 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
897 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
898 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
899 #ifndef OPENSSL_NO_SRP
900 {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"},
901 {"srpuserseed", OPT_SRPUSERSEED, 's',
902 "(deprecated) A seed string for a default user salt"},
905 OPT_SECTION("Protocol and version"),
906 {"max_early_data", OPT_MAX_EARLY, 'n',
907 "The maximum number of bytes of early data as advertised in tickets"},
908 {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n',
909 "The maximum number of bytes of early data (hard limit)"},
910 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
911 {"num_tickets", OPT_S_NUM_TICKETS, 'n',
912 "The number of TLSv1.3 session tickets that a server will automatically issue" },
913 {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"},
914 {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"},
915 {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"},
916 {"no_ca_names", OPT_NOCANAMES, '-',
917 "Disable TLS Extension CA Names"},
918 {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"},
919 #ifndef OPENSSL_NO_SSL3
920 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
922 #ifndef OPENSSL_NO_TLS1
923 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
925 #ifndef OPENSSL_NO_TLS1_1
926 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
928 #ifndef OPENSSL_NO_TLS1_2
929 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
931 #ifndef OPENSSL_NO_TLS1_3
932 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
934 #ifndef OPENSSL_NO_DTLS
935 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
936 {"listen", OPT_LISTEN, '-',
937 "Listen for a DTLS ClientHello with a cookie and then connect"},
939 #ifndef OPENSSL_NO_DTLS1
940 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
942 #ifndef OPENSSL_NO_DTLS1_2
943 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
945 #ifndef OPENSSL_NO_SCTP
946 {"sctp", OPT_SCTP, '-', "Use SCTP"},
947 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
949 #ifndef OPENSSL_NO_SRTP
950 {"use_srtp", OPT_SRTP_PROFILES, 's',
951 "Offer SRTP key management with a colon-separated profile list"},
953 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
954 #ifndef OPENSSL_NO_NEXTPROTONEG
955 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
956 "Set the advertised protocols for the NPN extension (comma-separated list)"},
958 {"alpn", OPT_ALPN, 's',
959 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
960 #ifndef OPENSSL_NO_KTLS
961 {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"},
962 {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"},
973 #define IS_PROT_FLAG(o) \
974 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
975 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
977 int s_server_main(int argc, char *argv[])
979 ENGINE *engine = NULL;
980 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
981 SSL_CONF_CTX *cctx = NULL;
982 const SSL_METHOD *meth = TLS_server_method();
983 SSL_EXCERT *exc = NULL;
984 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
985 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
986 STACK_OF(X509_CRL) *crls = NULL;
987 X509 *s_cert = NULL, *s_dcert = NULL;
988 X509_VERIFY_PARAM *vpm = NULL;
989 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
990 const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL;
991 char *dpassarg = NULL, *dpass = NULL;
992 char *passarg = NULL, *pass = NULL;
993 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
994 char *crl_file = NULL, *prog;
996 int unlink_unix_path = 0;
998 do_server_cb server_cb;
999 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
1000 char *dhfile = NULL;
1002 int nocert = 0, ret = 1;
1003 int noCApath = 0, noCAfile = 0, noCAstore = 0;
1004 int s_cert_format = FORMAT_UNDEF, s_key_format = FORMAT_UNDEF;
1005 int s_dcert_format = FORMAT_UNDEF, s_dkey_format = FORMAT_UNDEF;
1006 int rev = 0, naccept = -1, sdebug = 0;
1007 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
1008 int state = 0, crl_format = FORMAT_UNDEF, crl_download = 0;
1010 char *port = OPENSSL_strdup(PORT);
1011 unsigned char *context = NULL;
1013 EVP_PKEY *s_key2 = NULL;
1014 X509 *s_cert2 = NULL;
1015 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
1016 const char *ssl_config = NULL;
1017 int read_buf_len = 0;
1018 #ifndef OPENSSL_NO_NEXTPROTONEG
1019 const char *next_proto_neg_in = NULL;
1020 tlsextnextprotoctx next_proto = { NULL, 0 };
1022 const char *alpn_in = NULL;
1023 tlsextalpnctx alpn_ctx = { NULL, 0 };
1024 #ifndef OPENSSL_NO_PSK
1025 /* by default do not send a PSK identity hint */
1026 char *psk_identity_hint = NULL;
1029 #ifndef OPENSSL_NO_SRP
1030 char *srpuserseed = NULL;
1031 char *srp_verifier_file = NULL;
1033 #ifndef OPENSSL_NO_SRTP
1034 char *srtp_profiles = NULL;
1036 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1037 int s_server_verify = SSL_VERIFY_NONE;
1038 int s_server_session_id_context = 1; /* anything will do */
1039 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
1040 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
1041 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
1042 #ifndef OPENSSL_NO_OCSP
1043 int s_tlsextstatus = 0;
1045 int no_resume_ephemeral = 0;
1046 unsigned int max_send_fragment = 0;
1047 unsigned int split_send_fragment = 0, max_pipelines = 0;
1048 const char *s_serverinfo_file = NULL;
1049 const char *keylog_file = NULL;
1050 int max_early_data = -1, recv_max_early_data = -1;
1051 char *psksessf = NULL;
1052 int no_ca_names = 0;
1053 #ifndef OPENSSL_NO_SCTP
1054 int sctp_label_bug = 0;
1056 int ignore_unexpected_eof = 0;
1057 #ifndef OPENSSL_NO_KTLS
1058 int enable_ktls = 0;
1061 /* Init of few remaining global variables */
1066 s_nbio = s_nbio_test = 0;
1076 cctx = SSL_CONF_CTX_new();
1077 vpm = X509_VERIFY_PARAM_new();
1078 if (cctx == NULL || vpm == NULL)
1080 SSL_CONF_CTX_set_flags(cctx,
1081 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1083 prog = opt_init(argc, argv, s_server_options);
1084 while ((o = opt_next()) != OPT_EOF) {
1085 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1086 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1089 if (IS_NO_PROT_FLAG(o))
1091 if (prot_opt == 1 && no_prot_opt) {
1093 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1100 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1103 opt_help(s_server_options);
1109 if (socket_family == AF_UNIX) {
1110 OPENSSL_free(host); host = NULL;
1111 OPENSSL_free(port); port = NULL;
1114 socket_family = AF_INET;
1120 if (socket_family == AF_UNIX) {
1121 OPENSSL_free(host); host = NULL;
1122 OPENSSL_free(port); port = NULL;
1125 socket_family = AF_INET6;
1128 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1134 if (socket_family == AF_UNIX) {
1135 socket_family = AF_UNSPEC;
1138 OPENSSL_free(port); port = NULL;
1139 OPENSSL_free(host); host = NULL;
1140 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1142 "%s: -port argument malformed or ambiguous\n",
1149 if (socket_family == AF_UNIX) {
1150 socket_family = AF_UNSPEC;
1153 OPENSSL_free(port); port = NULL;
1154 OPENSSL_free(host); host = NULL;
1155 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1157 "%s: -accept argument malformed or ambiguous\n",
1164 socket_family = AF_UNIX;
1165 OPENSSL_free(host); host = OPENSSL_strdup(opt_arg());
1166 OPENSSL_free(port); port = NULL;
1169 unlink_unix_path = 1;
1173 naccept = atol(opt_arg());
1176 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1177 verify_args.depth = atoi(opt_arg());
1179 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1181 case OPT_UPPER_V_VERIFY:
1183 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1184 SSL_VERIFY_CLIENT_ONCE;
1185 verify_args.depth = atoi(opt_arg());
1188 "verify depth is %d, must return a certificate\n",
1192 context = (unsigned char *)opt_arg();
1195 s_cert_file = opt_arg();
1198 if (!set_nameopt(opt_arg()))
1202 crl_file = opt_arg();
1204 case OPT_CRL_DOWNLOAD:
1207 case OPT_SERVERINFO:
1208 s_serverinfo_file = opt_arg();
1211 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format))
1215 s_key_file = opt_arg();
1218 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1222 passarg = opt_arg();
1224 case OPT_CERT_CHAIN:
1225 s_chain_file = opt_arg();
1231 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format))
1235 s_dcert_file = opt_arg();
1238 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format))
1242 dpassarg = opt_arg();
1245 s_dkey_file = opt_arg();
1247 case OPT_DCERT_CHAIN:
1248 s_dchain_file = opt_arg();
1259 case OPT_CHAINCAPATH:
1260 chCApath = opt_arg();
1262 case OPT_VERIFYCAPATH:
1263 vfyCApath = opt_arg();
1266 CAstore = opt_arg();
1271 case OPT_CHAINCASTORE:
1272 chCAstore = opt_arg();
1274 case OPT_VERIFYCASTORE:
1275 vfyCAstore = opt_arg();
1284 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1288 case OPT_S_NUM_TICKETS:
1289 case OPT_ANTI_REPLAY:
1290 case OPT_NO_ANTI_REPLAY:
1291 if (ssl_args == NULL)
1292 ssl_args = sk_OPENSSL_STRING_new_null();
1293 if (ssl_args == NULL
1294 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1295 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1296 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1301 if (!opt_verify(o, vpm))
1306 if (!args_excert(o, &exc))
1309 case OPT_VERIFY_RET_ERROR:
1310 verify_args.return_error = 1;
1312 case OPT_VERIFY_QUIET:
1313 verify_args.quiet = 1;
1315 case OPT_BUILD_CHAIN:
1324 case OPT_CHAINCAFILE:
1325 chCAfile = opt_arg();
1327 case OPT_VERIFYCAFILE:
1328 vfyCAfile = opt_arg();
1334 s_nbio = s_nbio_test = 1;
1339 case OPT_NO_IGN_EOF:
1345 case OPT_TLSEXTDEBUG:
1349 #ifndef OPENSSL_NO_OCSP
1353 case OPT_STATUS_VERBOSE:
1354 #ifndef OPENSSL_NO_OCSP
1355 s_tlsextstatus = tlscstatp.verbose = 1;
1358 case OPT_STATUS_TIMEOUT:
1359 #ifndef OPENSSL_NO_OCSP
1361 tlscstatp.timeout = atoi(opt_arg());
1365 #ifndef OPENSSL_NO_OCSP
1366 tlscstatp.proxy = opt_arg();
1370 #ifndef OPENSSL_NO_OCSP
1371 tlscstatp.no_proxy = opt_arg();
1374 case OPT_STATUS_URL:
1375 #ifndef OPENSSL_NO_OCSP
1377 if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL,
1378 &tlscstatp.host, &tlscstatp.port, NULL,
1379 &tlscstatp.path, NULL, NULL)) {
1380 BIO_printf(bio_err, "Error parsing -status_url argument\n");
1385 case OPT_STATUS_FILE:
1386 #ifndef OPENSSL_NO_OCSP
1388 tlscstatp.respin = opt_arg();
1395 bio_s_msg = BIO_new_file(opt_arg(), "w");
1398 #ifndef OPENSSL_NO_SSL_TRACE
1402 case OPT_SECURITY_DEBUG:
1405 case OPT_SECURITY_DEBUG_VERBOSE:
1418 s_quiet = s_brief = verify_args.quiet = 1;
1423 case OPT_NO_RESUME_EPHEMERAL:
1424 no_resume_ephemeral = 1;
1426 case OPT_PSK_IDENTITY:
1427 psk_identity = opt_arg();
1430 #ifndef OPENSSL_NO_PSK
1431 psk_identity_hint = opt_arg();
1435 for (p = psk_key = opt_arg(); *p; p++) {
1436 if (isxdigit(_UC(*p)))
1438 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1443 psksessf = opt_arg();
1446 #ifndef OPENSSL_NO_SRP
1447 srp_verifier_file = opt_arg();
1448 if (min_version < TLS1_VERSION)
1449 min_version = TLS1_VERSION;
1452 case OPT_SRPUSERSEED:
1453 #ifndef OPENSSL_NO_SRP
1454 srpuserseed = opt_arg();
1455 if (min_version < TLS1_VERSION)
1456 min_version = TLS1_VERSION;
1471 case OPT_SSL_CONFIG:
1472 ssl_config = opt_arg();
1475 min_version = SSL3_VERSION;
1476 max_version = SSL3_VERSION;
1479 min_version = TLS1_3_VERSION;
1480 max_version = TLS1_3_VERSION;
1483 min_version = TLS1_2_VERSION;
1484 max_version = TLS1_2_VERSION;
1487 min_version = TLS1_1_VERSION;
1488 max_version = TLS1_1_VERSION;
1491 min_version = TLS1_VERSION;
1492 max_version = TLS1_VERSION;
1495 #ifndef OPENSSL_NO_DTLS
1496 meth = DTLS_server_method();
1497 socket_type = SOCK_DGRAM;
1501 #ifndef OPENSSL_NO_DTLS
1502 meth = DTLS_server_method();
1503 min_version = DTLS1_VERSION;
1504 max_version = DTLS1_VERSION;
1505 socket_type = SOCK_DGRAM;
1509 #ifndef OPENSSL_NO_DTLS
1510 meth = DTLS_server_method();
1511 min_version = DTLS1_2_VERSION;
1512 max_version = DTLS1_2_VERSION;
1513 socket_type = SOCK_DGRAM;
1517 #ifndef OPENSSL_NO_SCTP
1518 protocol = IPPROTO_SCTP;
1521 case OPT_SCTP_LABEL_BUG:
1522 #ifndef OPENSSL_NO_SCTP
1527 #ifndef OPENSSL_NO_DTLS
1528 enable_timeouts = 1;
1532 #ifndef OPENSSL_NO_DTLS
1533 socket_mtu = atol(opt_arg());
1537 #ifndef OPENSSL_NO_DTLS
1545 session_id_prefix = opt_arg();
1548 #ifndef OPENSSL_NO_ENGINE
1549 engine = setup_engine(opt_arg(), s_debug);
1556 case OPT_PROV_CASES:
1557 if (!opt_provider(o))
1560 case OPT_SERVERNAME:
1561 tlsextcbp.servername = opt_arg();
1563 case OPT_SERVERNAME_FATAL:
1564 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1567 s_cert_file2 = opt_arg();
1570 s_key_file2 = opt_arg();
1572 case OPT_NEXTPROTONEG:
1573 # ifndef OPENSSL_NO_NEXTPROTONEG
1574 next_proto_neg_in = opt_arg();
1578 alpn_in = opt_arg();
1580 case OPT_SRTP_PROFILES:
1581 #ifndef OPENSSL_NO_SRTP
1582 srtp_profiles = opt_arg();
1585 case OPT_KEYMATEXPORT:
1586 keymatexportlabel = opt_arg();
1588 case OPT_KEYMATEXPORTLEN:
1589 keymatexportlen = atoi(opt_arg());
1594 case OPT_MAX_SEND_FRAG:
1595 max_send_fragment = atoi(opt_arg());
1597 case OPT_SPLIT_SEND_FRAG:
1598 split_send_fragment = atoi(opt_arg());
1600 case OPT_MAX_PIPELINES:
1601 max_pipelines = atoi(opt_arg());
1604 read_buf_len = atoi(opt_arg());
1606 case OPT_KEYLOG_FILE:
1607 keylog_file = opt_arg();
1610 max_early_data = atoi(opt_arg());
1611 if (max_early_data < 0) {
1612 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1616 case OPT_RECV_MAX_EARLY:
1617 recv_max_early_data = atoi(opt_arg());
1618 if (recv_max_early_data < 0) {
1619 BIO_printf(bio_err, "Invalid value for recv_max_early_data\n");
1623 case OPT_EARLY_DATA:
1625 if (max_early_data == -1)
1626 max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
1628 case OPT_HTTP_SERVER_BINMODE:
1629 http_server_binmode = 1;
1635 #ifndef OPENSSL_NO_KTLS
1640 #ifndef OPENSSL_NO_KTLS
1644 case OPT_IGNORE_UNEXPECTED_EOF:
1645 ignore_unexpected_eof = 1;
1650 /* No extra arguments. */
1651 argc = opt_num_rest();
1655 if (!app_RAND_load())
1658 #ifndef OPENSSL_NO_NEXTPROTONEG
1659 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1660 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1664 #ifndef OPENSSL_NO_DTLS
1665 if (www && socket_type == SOCK_DGRAM) {
1666 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1670 if (dtlslisten && socket_type != SOCK_DGRAM) {
1671 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1676 if (stateless && socket_type != SOCK_STREAM) {
1677 BIO_printf(bio_err, "Can only use --stateless with TLS\n");
1682 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1684 "Can't use unix sockets and datagrams together\n");
1688 if (early_data && (www > 0 || rev)) {
1690 "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n");
1694 #ifndef OPENSSL_NO_SCTP
1695 if (protocol == IPPROTO_SCTP) {
1696 if (socket_type != SOCK_DGRAM) {
1697 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1700 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1701 socket_type = SOCK_STREAM;
1705 #ifndef OPENSSL_NO_KTLS
1706 if (use_sendfile && enable_ktls == 0) {
1707 BIO_printf(bio_out, "Warning: -sendfile depends on -ktls, enabling -ktls now.\n");
1711 if (use_sendfile && www <= 1) {
1712 BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n");
1717 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1718 BIO_printf(bio_err, "Error getting password\n");
1722 if (s_key_file == NULL)
1723 s_key_file = s_cert_file;
1725 if (s_key_file2 == NULL)
1726 s_key_file2 = s_cert_file2;
1728 if (!load_excert(&exc))
1732 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1733 "server certificate private key");
1737 s_cert = load_cert_pass(s_cert_file, s_cert_format, 1, pass,
1738 "server certificate");
1742 if (s_chain_file != NULL) {
1743 if (!load_certs(s_chain_file, 0, &s_chain, NULL,
1744 "server certificate chain"))
1748 if (tlsextcbp.servername != NULL) {
1749 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1750 "second server certificate private key");
1754 s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, 1, pass,
1755 "second server certificate");
1757 if (s_cert2 == NULL)
1761 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1762 if (next_proto_neg_in) {
1763 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1764 if (next_proto.data == NULL)
1768 alpn_ctx.data = NULL;
1770 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1771 if (alpn_ctx.data == NULL)
1775 if (crl_file != NULL) {
1777 crl = load_crl(crl_file, crl_format, 0, "CRL");
1780 crls = sk_X509_CRL_new_null();
1781 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1782 BIO_puts(bio_err, "Error adding CRL\n");
1783 ERR_print_errors(bio_err);
1789 if (s_dcert_file != NULL) {
1791 if (s_dkey_file == NULL)
1792 s_dkey_file = s_dcert_file;
1794 s_dkey = load_key(s_dkey_file, s_dkey_format,
1795 0, dpass, engine, "second certificate private key");
1799 s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, 1, dpass,
1800 "second server certificate");
1802 if (s_dcert == NULL) {
1803 ERR_print_errors(bio_err);
1806 if (s_dchain_file != NULL) {
1807 if (!load_certs(s_dchain_file, 0, &s_dchain, NULL,
1808 "second server certificate chain"))
1814 if (bio_s_out == NULL) {
1815 if (s_quiet && !s_debug) {
1816 bio_s_out = BIO_new(BIO_s_null());
1817 if (s_msg && bio_s_msg == NULL)
1818 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1820 if (bio_s_out == NULL)
1821 bio_s_out = dup_bio_out(FORMAT_TEXT);
1827 s_dcert_file = NULL;
1829 s_cert_file2 = NULL;
1833 ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1835 ERR_print_errors(bio_err);
1839 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1842 ssl_ctx_security_debug(ctx, sdebug);
1844 if (!config_ctx(cctx, ssl_args, ctx))
1848 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1849 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1851 ERR_print_errors(bio_err);
1855 #ifndef OPENSSL_NO_SCTP
1856 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1857 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1860 if (min_version != 0
1861 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1863 if (max_version != 0
1864 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1867 if (session_id_prefix) {
1868 if (strlen(session_id_prefix) >= 32)
1870 "warning: id_prefix is too long, only one new session will be possible\n");
1871 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1872 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1873 ERR_print_errors(bio_err);
1876 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1879 ssl_ctx_set_excert(ctx, exc);
1882 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1884 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1886 init_session_cache_ctx(ctx);
1888 SSL_CTX_sess_set_cache_size(ctx, 128);
1891 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1895 SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
1898 if (ignore_unexpected_eof)
1899 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1900 #ifndef OPENSSL_NO_KTLS
1902 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
1905 if (max_send_fragment > 0
1906 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1907 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1908 prog, max_send_fragment);
1912 if (split_send_fragment > 0
1913 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1914 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1915 prog, split_send_fragment);
1918 if (max_pipelines > 0
1919 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1920 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1921 prog, max_pipelines);
1925 if (read_buf_len > 0) {
1926 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1928 #ifndef OPENSSL_NO_SRTP
1929 if (srtp_profiles != NULL) {
1930 /* Returns 0 on success! */
1931 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1932 BIO_printf(bio_err, "Error setting SRTP profile\n");
1933 ERR_print_errors(bio_err);
1939 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1940 CAstore, noCAstore)) {
1941 ERR_print_errors(bio_err);
1944 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1945 BIO_printf(bio_err, "Error setting verify params\n");
1946 ERR_print_errors(bio_err);
1950 ssl_ctx_add_crls(ctx, crls, 0);
1952 if (!ssl_load_stores(ctx,
1953 vfyCApath, vfyCAfile, vfyCAstore,
1954 chCApath, chCAfile, chCAstore,
1955 crls, crl_download)) {
1956 BIO_printf(bio_err, "Error loading store locations\n");
1957 ERR_print_errors(bio_err);
1962 ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1964 ERR_print_errors(bio_err);
1970 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1973 ssl_ctx_security_debug(ctx2, sdebug);
1975 if (session_id_prefix) {
1976 if (strlen(session_id_prefix) >= 32)
1978 "warning: id_prefix is too long, only one new session will be possible\n");
1979 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1980 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1981 ERR_print_errors(bio_err);
1984 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1987 ssl_ctx_set_excert(ctx2, exc);
1990 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1993 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1995 init_session_cache_ctx(ctx2);
1997 SSL_CTX_sess_set_cache_size(ctx2, 128);
2000 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
2002 if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath,
2003 noCApath, CAstore, noCAstore)) {
2004 ERR_print_errors(bio_err);
2007 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
2008 BIO_printf(bio_err, "Error setting verify params\n");
2009 ERR_print_errors(bio_err);
2013 ssl_ctx_add_crls(ctx2, crls, 0);
2014 if (!config_ctx(cctx, ssl_args, ctx2))
2017 #ifndef OPENSSL_NO_NEXTPROTONEG
2018 if (next_proto.data)
2019 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
2023 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
2026 EVP_PKEY *dhpkey = NULL;
2029 dhpkey = load_keyparams(dhfile, FORMAT_UNDEF, 0, "DH", "DH parameters");
2030 else if (s_cert_file != NULL)
2031 dhpkey = load_keyparams_suppress(s_cert_file, FORMAT_UNDEF, 0, "DH",
2032 "DH parameters", 1);
2034 if (dhpkey != NULL) {
2035 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2037 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
2039 (void)BIO_flush(bio_s_out);
2041 if (dhpkey == NULL) {
2042 SSL_CTX_set_dh_auto(ctx, 1);
2045 * We need 2 references: one for use by ctx and one for use by
2048 if (!EVP_PKEY_up_ref(dhpkey)) {
2049 EVP_PKEY_free(dhpkey);
2052 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) {
2053 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2054 ERR_print_errors(bio_err);
2055 /* Free 2 references */
2056 EVP_PKEY_free(dhpkey);
2057 EVP_PKEY_free(dhpkey);
2063 if (dhfile != NULL) {
2064 EVP_PKEY *dhpkey2 = load_keyparams_suppress(s_cert_file2,
2067 "DH parameters", 1);
2069 if (dhpkey2 != NULL) {
2070 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2071 (void)BIO_flush(bio_s_out);
2073 EVP_PKEY_free(dhpkey);
2077 if (dhpkey == NULL) {
2078 SSL_CTX_set_dh_auto(ctx2, 1);
2079 } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) {
2080 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2081 ERR_print_errors(bio_err);
2082 EVP_PKEY_free(dhpkey);
2087 EVP_PKEY_free(dhpkey);
2090 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
2093 if (s_serverinfo_file != NULL
2094 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
2095 ERR_print_errors(bio_err);
2100 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
2103 if (s_dcert != NULL) {
2104 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
2108 if (no_resume_ephemeral) {
2109 SSL_CTX_set_not_resumable_session_callback(ctx,
2110 not_resumable_sess_cb);
2113 SSL_CTX_set_not_resumable_session_callback(ctx2,
2114 not_resumable_sess_cb);
2116 #ifndef OPENSSL_NO_PSK
2117 if (psk_key != NULL) {
2119 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
2120 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
2123 if (psk_identity_hint != NULL) {
2124 if (min_version == TLS1_3_VERSION) {
2125 BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n");
2127 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
2128 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
2129 ERR_print_errors(bio_err);
2135 if (psksessf != NULL) {
2136 BIO *stmp = BIO_new_file(psksessf, "r");
2139 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
2140 ERR_print_errors(bio_err);
2143 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2145 if (psksess == NULL) {
2146 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
2147 ERR_print_errors(bio_err);
2153 if (psk_key != NULL || psksess != NULL)
2154 SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb);
2156 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
2157 if (!SSL_CTX_set_session_id_context(ctx,
2158 (void *)&s_server_session_id_context,
2159 sizeof(s_server_session_id_context))) {
2160 BIO_printf(bio_err, "error setting session id context\n");
2161 ERR_print_errors(bio_err);
2165 /* Set DTLS cookie generation and verification callbacks */
2166 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
2167 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
2169 /* Set TLS1.3 cookie generation and verification callbacks */
2170 SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback);
2171 SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback);
2174 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
2175 if (!SSL_CTX_set_session_id_context(ctx2,
2176 (void *)&s_server_session_id_context,
2177 sizeof(s_server_session_id_context))) {
2178 BIO_printf(bio_err, "error setting session id context\n");
2179 ERR_print_errors(bio_err);
2182 tlsextcbp.biodebug = bio_s_out;
2183 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
2184 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
2185 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2186 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2189 #ifndef OPENSSL_NO_SRP
2190 if (srp_verifier_file != NULL) {
2191 if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed,
2196 if (CAfile != NULL) {
2197 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2200 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2202 #ifndef OPENSSL_NO_OCSP
2203 if (s_tlsextstatus) {
2204 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2205 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2207 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2208 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2212 if (set_keylog_file(ctx, keylog_file))
2215 if (max_early_data >= 0)
2216 SSL_CTX_set_max_early_data(ctx, max_early_data);
2217 if (recv_max_early_data >= 0)
2218 SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data);
2221 server_cb = rev_body;
2223 server_cb = www_body;
2225 server_cb = sv_body;
2227 if (socket_family == AF_UNIX
2228 && unlink_unix_path)
2231 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2232 server_cb, context, naccept, bio_s_out);
2233 print_stats(bio_s_out, ctx);
2237 SSL_SESSION_free(psksess);
2238 set_keylog_file(NULL, NULL);
2240 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2242 EVP_PKEY_free(s_key);
2243 EVP_PKEY_free(s_dkey);
2244 sk_X509_pop_free(s_chain, X509_free);
2245 sk_X509_pop_free(s_dchain, X509_free);
2247 OPENSSL_free(dpass);
2250 X509_VERIFY_PARAM_free(vpm);
2252 OPENSSL_free(tlscstatp.host);
2253 OPENSSL_free(tlscstatp.port);
2254 OPENSSL_free(tlscstatp.path);
2257 EVP_PKEY_free(s_key2);
2258 #ifndef OPENSSL_NO_NEXTPROTONEG
2259 OPENSSL_free(next_proto.data);
2261 OPENSSL_free(alpn_ctx.data);
2262 ssl_excert_free(exc);
2263 sk_OPENSSL_STRING_free(ssl_args);
2264 SSL_CONF_CTX_free(cctx);
2265 release_engine(engine);
2266 BIO_free(bio_s_out);
2268 BIO_free(bio_s_msg);
2270 #ifdef CHARSET_EBCDIC
2271 BIO_meth_free(methods_ebcdic);
2276 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2278 BIO_printf(bio, "%4ld items in the session cache\n",
2279 SSL_CTX_sess_number(ssl_ctx));
2280 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2281 SSL_CTX_sess_connect(ssl_ctx));
2282 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2283 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2284 BIO_printf(bio, "%4ld client connects that finished\n",
2285 SSL_CTX_sess_connect_good(ssl_ctx));
2286 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2287 SSL_CTX_sess_accept(ssl_ctx));
2288 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2289 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2290 BIO_printf(bio, "%4ld server accepts that finished\n",
2291 SSL_CTX_sess_accept_good(ssl_ctx));
2292 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2293 BIO_printf(bio, "%4ld session cache misses\n",
2294 SSL_CTX_sess_misses(ssl_ctx));
2295 BIO_printf(bio, "%4ld session cache timeouts\n",
2296 SSL_CTX_sess_timeouts(ssl_ctx));
2297 BIO_printf(bio, "%4ld callback cache hits\n",
2298 SSL_CTX_sess_cb_hits(ssl_ctx));
2299 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2300 SSL_CTX_sess_cache_full(ssl_ctx),
2301 SSL_CTX_sess_get_cache_size(ssl_ctx));
2304 static int sv_body(int s, int stype, int prot, unsigned char *context)
2313 struct timeval timeout;
2314 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
2315 struct timeval *timeoutp;
2317 #ifndef OPENSSL_NO_DTLS
2318 # ifndef OPENSSL_NO_SCTP
2319 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2321 int isdtls = (stype == SOCK_DGRAM);
2325 buf = app_malloc(bufsize, "server buffer");
2327 if (!BIO_socket_nbio(s, 1))
2328 ERR_print_errors(bio_err);
2330 BIO_printf(bio_err, "Turned on non blocking io\n");
2339 if (s_tlsextdebug) {
2340 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2341 SSL_set_tlsext_debug_arg(con, bio_s_out);
2345 && !SSL_set_session_id_context(con, context,
2346 strlen((char *)context))) {
2347 BIO_printf(bio_err, "Error setting session id context\n");
2352 if (!SSL_clear(con)) {
2353 BIO_printf(bio_err, "Error clearing SSL connection\n");
2357 #ifndef OPENSSL_NO_DTLS
2359 # ifndef OPENSSL_NO_SCTP
2360 if (prot == IPPROTO_SCTP)
2361 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2364 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2366 if (enable_timeouts) {
2368 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2369 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2372 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2373 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2377 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2378 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2379 DTLS_get_link_min_mtu(con));
2384 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2385 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2386 BIO_printf(bio_err, "Failed to set MTU\n");
2392 /* want to do MTU discovery */
2393 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2395 # ifndef OPENSSL_NO_SCTP
2396 if (prot != IPPROTO_SCTP)
2398 /* Turn on cookie exchange. Not necessary for SCTP */
2399 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2402 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2405 BIO_printf(bio_err, "Unable to create BIO\n");
2406 ERR_print_errors(bio_err);
2413 test = BIO_new(BIO_f_nbio_test());
2414 sbio = BIO_push(test, sbio);
2417 SSL_set_bio(con, sbio, sbio);
2418 SSL_set_accept_state(con);
2419 /* SSL_set_fd(con,s); */
2422 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
2423 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2426 #ifndef OPENSSL_NO_SSL_TRACE
2428 SSL_set_msg_callback(con, SSL_trace);
2431 SSL_set_msg_callback(con, msg_cb);
2432 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2435 if (s_tlsextdebug) {
2436 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2437 SSL_set_tlsext_debug_arg(con, bio_s_out);
2441 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2444 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2446 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2447 if (edret != SSL_READ_EARLY_DATA_ERROR)
2450 switch (SSL_get_error(con, 0)) {
2451 case SSL_ERROR_WANT_WRITE:
2452 case SSL_ERROR_WANT_ASYNC:
2453 case SSL_ERROR_WANT_READ:
2454 /* Just keep trying - busy waiting */
2457 BIO_printf(bio_err, "Error reading early data\n");
2458 ERR_print_errors(bio_err);
2462 if (readbytes > 0) {
2464 BIO_printf(bio_s_out, "Early data received:\n");
2467 raw_write_stdout(buf, (unsigned int)readbytes);
2468 (void)BIO_flush(bio_s_out);
2472 if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT)
2473 BIO_printf(bio_s_out, "No early data received\n");
2475 BIO_printf(bio_s_out, "Early data was rejected\n");
2477 BIO_printf(bio_s_out, "\nEnd of early data\n");
2479 if (SSL_is_init_finished(con))
2480 print_connection_info(con);
2483 if (fileno_stdin() > s)
2484 width = fileno_stdin() + 1;
2488 int read_from_terminal;
2489 int read_from_sslcon;
2491 read_from_terminal = 0;
2492 read_from_sslcon = SSL_has_pending(con)
2493 || (async && SSL_waiting_for_async(con));
2495 if (!read_from_sslcon) {
2497 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2498 openssl_fdset(fileno_stdin(), &readfds);
2500 openssl_fdset(s, &readfds);
2502 * Note: under VMS with SOCKETSHR the second parameter is
2503 * currently of type (int *) whereas under other systems it is
2504 * (void *) if you don't have a cast it will choke the compiler:
2505 * if you do have a cast then you can either go for (int *) or
2508 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2510 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2511 * only on sockets. As a workaround we timeout the select every
2512 * second and check for any keypress. In a proper Windows
2513 * application we wouldn't do this because it is inefficient.
2516 timeout.tv_usec = 0;
2517 i = select(width, (void *)&readfds, NULL, NULL, &timeout);
2518 if (has_stdin_waiting())
2519 read_from_terminal = 1;
2520 if ((i < 0) || (!i && !read_from_terminal))
2523 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2524 timeoutp = &timeout;
2528 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2530 if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
2531 BIO_printf(bio_err, "TIMEOUT occurred\n");
2535 if (FD_ISSET(fileno_stdin(), &readfds))
2536 read_from_terminal = 1;
2538 if (FD_ISSET(s, &readfds))
2539 read_from_sslcon = 1;
2541 if (read_from_terminal) {
2545 i = raw_read_stdin(buf, bufsize / 2);
2547 /* both loops are skipped when i <= 0 */
2548 for (j = 0; j < i; j++)
2551 for (j = i - 1; j >= 0; j--) {
2552 buf[j + lf_num] = buf[j];
2553 if (buf[j] == '\n') {
2556 buf[j + lf_num] = '\r';
2559 assert(lf_num == 0);
2561 i = raw_read_stdin(buf, bufsize);
2564 if (!s_quiet && !s_brief) {
2565 if ((i <= 0) || (buf[0] == 'Q')) {
2566 BIO_printf(bio_s_out, "DONE\n");
2567 (void)BIO_flush(bio_s_out);
2569 close_accept_socket();
2573 if ((i <= 0) || (buf[0] == 'q')) {
2574 BIO_printf(bio_s_out, "DONE\n");
2575 (void)BIO_flush(bio_s_out);
2576 if (SSL_version(con) != DTLS1_VERSION)
2579 * close_accept_socket(); ret= -11;
2583 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2584 SSL_renegotiate(con);
2585 i = SSL_do_handshake(con);
2586 printf("SSL_do_handshake -> %d\n", i);
2590 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2592 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2594 SSL_renegotiate(con);
2595 i = SSL_do_handshake(con);
2596 printf("SSL_do_handshake -> %d\n", i);
2600 if ((buf[0] == 'K' || buf[0] == 'k')
2601 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2602 SSL_key_update(con, buf[0] == 'K' ?
2603 SSL_KEY_UPDATE_REQUESTED
2604 : SSL_KEY_UPDATE_NOT_REQUESTED);
2605 i = SSL_do_handshake(con);
2606 printf("SSL_do_handshake -> %d\n", i);
2610 if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2611 SSL_set_verify(con, SSL_VERIFY_PEER, NULL);
2612 i = SSL_verify_client_post_handshake(con);
2614 printf("Failed to initiate request\n");
2615 ERR_print_errors(bio_err);
2617 i = SSL_do_handshake(con);
2618 printf("SSL_do_handshake -> %d\n", i);
2623 if (buf[0] == 'P') {
2624 static const char str[] = "Lets print some clear text\n";
2625 BIO_write(SSL_get_wbio(con), str, sizeof(str) -1);
2627 if (buf[0] == 'S') {
2628 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2631 #ifdef CHARSET_EBCDIC
2632 ebcdic2ascii(buf, buf, i);
2636 /* should do a select for the write */
2639 if (++count == 100) {
2641 SSL_renegotiate(con);
2644 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2645 #ifndef OPENSSL_NO_SRP
2646 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2647 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2649 lookup_srp_user(&srp_callback_parm, bio_s_out);
2651 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2654 switch (SSL_get_error(con, k)) {
2655 case SSL_ERROR_NONE:
2657 case SSL_ERROR_WANT_ASYNC:
2658 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2659 (void)BIO_flush(bio_s_out);
2660 wait_for_async(con);
2662 case SSL_ERROR_WANT_WRITE:
2663 case SSL_ERROR_WANT_READ:
2664 case SSL_ERROR_WANT_X509_LOOKUP:
2665 BIO_printf(bio_s_out, "Write BLOCK\n");
2666 (void)BIO_flush(bio_s_out);
2668 case SSL_ERROR_WANT_ASYNC_JOB:
2670 * This shouldn't ever happen in s_server. Treat as an error
2672 case SSL_ERROR_SYSCALL:
2674 BIO_printf(bio_s_out, "ERROR\n");
2675 (void)BIO_flush(bio_s_out);
2676 ERR_print_errors(bio_err);
2680 case SSL_ERROR_ZERO_RETURN:
2681 BIO_printf(bio_s_out, "DONE\n");
2682 (void)BIO_flush(bio_s_out);
2694 if (read_from_sslcon) {
2696 * init_ssl_connection handles all async events itself so if we're
2697 * waiting for async then we shouldn't go back into
2698 * init_ssl_connection
2700 if ((!async || !SSL_waiting_for_async(con))
2701 && !SSL_is_init_finished(con)) {
2702 i = init_ssl_connection(con);
2707 } else if (i == 0) {
2713 i = SSL_read(con, (char *)buf, bufsize);
2714 #ifndef OPENSSL_NO_SRP
2715 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2716 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2718 lookup_srp_user(&srp_callback_parm, bio_s_out);
2720 i = SSL_read(con, (char *)buf, bufsize);
2723 switch (SSL_get_error(con, i)) {
2724 case SSL_ERROR_NONE:
2725 #ifdef CHARSET_EBCDIC
2726 ascii2ebcdic(buf, buf, i);
2728 raw_write_stdout(buf, (unsigned int)i);
2729 (void)BIO_flush(bio_s_out);
2730 if (SSL_has_pending(con))
2733 case SSL_ERROR_WANT_ASYNC:
2734 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2735 (void)BIO_flush(bio_s_out);
2736 wait_for_async(con);
2738 case SSL_ERROR_WANT_WRITE:
2739 case SSL_ERROR_WANT_READ:
2740 BIO_printf(bio_s_out, "Read BLOCK\n");
2741 (void)BIO_flush(bio_s_out);
2743 case SSL_ERROR_WANT_ASYNC_JOB:
2745 * This shouldn't ever happen in s_server. Treat as an error
2747 case SSL_ERROR_SYSCALL:
2749 BIO_printf(bio_s_out, "ERROR\n");
2750 (void)BIO_flush(bio_s_out);
2751 ERR_print_errors(bio_err);
2754 case SSL_ERROR_ZERO_RETURN:
2755 BIO_printf(bio_s_out, "DONE\n");
2756 (void)BIO_flush(bio_s_out);
2765 BIO_printf(bio_s_out, "shutting down SSL\n");
2766 do_ssl_shutdown(con);
2769 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2770 OPENSSL_clear_free(buf, bufsize);
2774 static void close_accept_socket(void)
2776 BIO_printf(bio_err, "shutdown accept socket\n");
2777 if (accept_socket >= 0) {
2778 BIO_closesocket(accept_socket);
2782 static int is_retryable(SSL *con, int i)
2784 int err = SSL_get_error(con, i);
2786 /* If it's not a fatal error, it must be retryable */
2787 return (err != SSL_ERROR_SSL)
2788 && (err != SSL_ERROR_SYSCALL)
2789 && (err != SSL_ERROR_ZERO_RETURN);
2792 static int init_ssl_connection(SSL *con)
2798 if (dtlslisten || stateless) {
2799 BIO_ADDR *client = NULL;
2802 if ((client = BIO_ADDR_new()) == NULL) {
2803 BIO_printf(bio_err, "ERROR - memory\n");
2806 i = DTLSv1_listen(con, client);
2808 i = SSL_stateless(con);
2815 wbio = SSL_get_wbio(con);
2817 BIO_get_fd(wbio, &fd);
2820 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2821 BIO_printf(bio_err, "ERROR - unable to connect\n");
2822 BIO_ADDR_free(client);
2826 (void)BIO_ctrl_set_connected(wbio, client);
2827 BIO_ADDR_free(client);
2832 i = SSL_accept(con);
2834 BIO_ADDR_free(client);
2838 i = SSL_accept(con);
2841 retry = is_retryable(con, i);
2842 #ifdef CERT_CB_TEST_RETRY
2845 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2846 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2848 "LOOKUP from certificate callback during accept\n");
2849 i = SSL_accept(con);
2851 retry = is_retryable(con, i);
2856 #ifndef OPENSSL_NO_SRP
2858 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2859 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2860 srp_callback_parm.login);
2862 lookup_srp_user(&srp_callback_parm, bio_s_out);
2864 i = SSL_accept(con);
2866 retry = is_retryable(con, i);
2869 } while (i < 0 && SSL_waiting_for_async(con));
2873 if (((dtlslisten || stateless) && i == 0)
2874 || (!dtlslisten && !stateless && retry)) {
2875 BIO_printf(bio_s_out, "DELAY\n");
2879 BIO_printf(bio_err, "ERROR\n");
2881 verify_err = SSL_get_verify_result(con);
2882 if (verify_err != X509_V_OK) {
2883 BIO_printf(bio_err, "verify error:%s\n",
2884 X509_verify_cert_error_string(verify_err));
2886 /* Always print any error messages */
2887 ERR_print_errors(bio_err);
2891 print_connection_info(con);
2895 static void print_connection_info(SSL *con)
2900 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2901 const unsigned char *next_proto_neg;
2902 unsigned next_proto_neg_len;
2904 unsigned char *exportedkeymat;
2908 print_ssl_summary(con);
2910 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2912 peer = SSL_get0_peer_certificate(con);
2914 BIO_printf(bio_s_out, "Client certificate\n");
2915 PEM_write_bio_X509(bio_s_out, peer);
2916 dump_cert_text(bio_s_out, peer);
2920 if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
2921 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2922 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2923 ssl_print_sigalgs(bio_s_out, con);
2924 #ifndef OPENSSL_NO_EC
2925 ssl_print_point_formats(bio_s_out, con);
2926 ssl_print_groups(bio_s_out, con, 0);
2928 print_ca_names(bio_s_out, con);
2929 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2931 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2932 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2933 if (next_proto_neg) {
2934 BIO_printf(bio_s_out, "NEXTPROTO is ");
2935 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2936 BIO_printf(bio_s_out, "\n");
2939 #ifndef OPENSSL_NO_SRTP
2941 SRTP_PROTECTION_PROFILE *srtp_profile
2942 = SSL_get_selected_srtp_profile(con);
2945 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2946 srtp_profile->name);
2949 if (SSL_session_reused(con))
2950 BIO_printf(bio_s_out, "Reused session-id\n");
2952 ssl_print_secure_renegotiation_notes(bio_s_out, con);
2954 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
2955 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
2957 if (keymatexportlabel != NULL) {
2958 BIO_printf(bio_s_out, "Keying material exporter:\n");
2959 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2960 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2961 exportedkeymat = app_malloc(keymatexportlen, "export key");
2962 if (!SSL_export_keying_material(con, exportedkeymat,
2965 strlen(keymatexportlabel),
2967 BIO_printf(bio_s_out, " Error\n");
2969 BIO_printf(bio_s_out, " Keying material: ");
2970 for (i = 0; i < keymatexportlen; i++)
2971 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2972 BIO_printf(bio_s_out, "\n");
2974 OPENSSL_free(exportedkeymat);
2976 #ifndef OPENSSL_NO_KTLS
2977 if (BIO_get_ktls_send(SSL_get_wbio(con)))
2978 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
2979 if (BIO_get_ktls_recv(SSL_get_rbio(con)))
2980 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
2983 (void)BIO_flush(bio_s_out);
2986 static int www_body(int s, int stype, int prot, unsigned char *context)
2992 const SSL_CIPHER *c;
2993 BIO *io, *ssl_bio, *sbio;
2995 int total_bytes = 0;
3001 /* Set width for a select call if needed */
3004 buf = app_malloc(bufsize, "server www buffer");
3005 io = BIO_new(BIO_f_buffer());
3006 ssl_bio = BIO_new(BIO_f_ssl());
3007 if ((io == NULL) || (ssl_bio == NULL))
3011 if (!BIO_socket_nbio(s, 1))
3012 ERR_print_errors(bio_err);
3014 BIO_printf(bio_err, "Turned on non blocking io\n");
3017 /* lets make the output buffer a reasonable size */
3018 if (!BIO_set_write_buffer_size(io, bufsize))
3021 if ((con = SSL_new(ctx)) == NULL)
3024 if (s_tlsextdebug) {
3025 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3026 SSL_set_tlsext_debug_arg(con, bio_s_out);
3030 && !SSL_set_session_id_context(con, context,
3031 strlen((char *)context))) {
3036 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3040 test = BIO_new(BIO_f_nbio_test());
3041 sbio = BIO_push(test, sbio);
3043 SSL_set_bio(con, sbio, sbio);
3044 SSL_set_accept_state(con);
3046 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3047 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3048 BIO_push(io, ssl_bio);
3050 #ifdef CHARSET_EBCDIC
3051 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3055 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3056 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3059 #ifndef OPENSSL_NO_SSL_TRACE
3061 SSL_set_msg_callback(con, SSL_trace);
3064 SSL_set_msg_callback(con, msg_cb);
3065 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3069 i = BIO_gets(io, buf, bufsize - 1);
3070 if (i < 0) { /* error */
3071 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
3073 ERR_print_errors(bio_err);
3076 BIO_printf(bio_s_out, "read R BLOCK\n");
3077 #ifndef OPENSSL_NO_SRP
3078 if (BIO_should_io_special(io)
3079 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3080 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3082 lookup_srp_user(&srp_callback_parm, bio_s_out);
3090 } else if (i == 0) { /* end of input */
3095 /* else we have data */
3096 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
3097 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
3100 STACK_OF(SSL_CIPHER) *sk;
3101 static const char *space = " ";
3103 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
3104 if (strncmp("GET /renegcert", buf, 14) == 0)
3106 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
3108 i = SSL_renegotiate(con);
3109 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
3110 /* Send the HelloRequest */
3111 i = SSL_do_handshake(con);
3113 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
3114 SSL_get_error(con, i));
3115 ERR_print_errors(bio_err);
3118 /* Wait for a ClientHello to come back */
3120 openssl_fdset(s, &readfds);
3121 i = select(width, (void *)&readfds, NULL, NULL, NULL);
3122 if (i <= 0 || !FD_ISSET(s, &readfds)) {
3123 BIO_printf(bio_s_out,
3124 "Error waiting for client response\n");
3125 ERR_print_errors(bio_err);
3129 * We're not actually expecting any data here and we ignore
3130 * any that is sent. This is just to force the handshake that
3131 * we're expecting to come from the client. If they haven't
3132 * sent one there's not much we can do.
3134 BIO_gets(io, buf, bufsize - 1);
3138 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3139 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
3140 BIO_puts(io, "<pre>\n");
3141 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
3143 for (i = 0; i < local_argc; i++) {
3145 for (myp = local_argv[i]; *myp; myp++)
3148 BIO_puts(io, "<");
3151 BIO_puts(io, ">");
3154 BIO_puts(io, "&");
3157 BIO_write(io, myp, 1);
3160 BIO_write(io, " ", 1);
3164 ssl_print_secure_renegotiation_notes(io, con);
3167 * The following is evil and should not really be done
3169 BIO_printf(io, "Ciphers supported in s_server binary\n");
3170 sk = SSL_get_ciphers(con);
3171 j = sk_SSL_CIPHER_num(sk);
3172 for (i = 0; i < j; i++) {
3173 c = sk_SSL_CIPHER_value(sk, i);
3174 BIO_printf(io, "%-11s:%-25s ",
3175 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3176 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3180 p = SSL_get_shared_ciphers(con, buf, bufsize);
3183 "---\nCiphers common between both SSL end points:\n");
3187 BIO_write(io, space, 26 - j);
3190 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3192 BIO_write(io, p, 1);
3199 ssl_print_sigalgs(io, con);
3200 #ifndef OPENSSL_NO_EC
3201 ssl_print_groups(io, con, 0);
3203 print_ca_names(io, con);
3204 BIO_printf(io, (SSL_session_reused(con)
3205 ? "---\nReused, " : "---\nNew, "));
3206 c = SSL_get_current_cipher(con);
3207 BIO_printf(io, "%s, Cipher is %s\n",
3208 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3209 SSL_SESSION_print(io, SSL_get_session(con));
3210 BIO_printf(io, "---\n");
3211 print_stats(io, SSL_get_SSL_CTX(con));
3212 BIO_printf(io, "---\n");
3213 peer = SSL_get0_peer_certificate(con);
3215 BIO_printf(io, "Client certificate\n");
3216 X509_print(io, peer);
3217 PEM_write_bio_X509(io, peer);
3220 BIO_puts(io, "no client certificate available\n");
3222 BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
3224 } else if ((www == 2 || www == 3)
3225 && (strncmp("GET /", buf, 5) == 0)) {
3228 static const char *text =
3229 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3235 for (e = p; *e != '\0'; e++) {
3240 /* Windows drive. We treat this the same way as ".." */
3247 dot = (e[0] == '.') ? 2 : 0;
3250 dot = (e[0] == '.') ? 3 : 0;
3253 dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0;
3257 dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0;
3259 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3264 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3271 BIO_printf(io, "'%s' contains '..' or ':'\r\n", p);
3275 if (*p == '/' || *p == '\\') {
3277 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3281 /* if a directory, do the index thang */
3282 if (app_isdir(p) > 0) {
3284 BIO_printf(io, "'%s' is a directory\r\n", p);
3288 opmode = (http_server_binmode == 1) ? "rb" : "r";
3289 if ((file = BIO_new_file(p, opmode)) == NULL) {
3291 BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode);
3292 ERR_print_errors(io);
3297 BIO_printf(bio_err, "FILE:%s\n", p);
3301 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3302 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3303 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3305 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3308 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3311 #ifndef OPENSSL_NO_KTLS
3319 BIO_get_fp(file, &fp);
3321 if (fstat(fd, &st) < 0) {
3322 BIO_printf(io, "Error fstat '%s'\r\n", p);
3323 ERR_print_errors(io);
3327 filesize = st.st_size;
3328 if (((int)BIO_flush(io)) < 0)
3332 i = SSL_sendfile(con, fd, offset, filesize, 0);
3334 BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p);
3335 ERR_print_errors(io);
3342 if (filesize <= 0) {
3344 BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p);
3353 i = BIO_read(file, buf, bufsize);
3359 BIO_printf(bio_err, "%d\n", i);
3360 if (total_bytes > 3 * 1024) {
3362 BIO_printf(bio_err, "RENEGOTIATE\n");
3363 SSL_renegotiate(con);
3367 for (j = 0; j < i;) {
3371 SSL_renegotiate(con);
3373 k = BIO_write(io, &(buf[j]), i - j);
3375 if (!BIO_should_retry(io)
3376 && !SSL_waiting_for_async(con)) {
3379 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3394 i = (int)BIO_flush(io);
3396 if (!BIO_should_retry(io))
3402 /* make sure we re-use sessions */
3403 do_ssl_shutdown(con);
3412 static int rev_body(int s, int stype, int prot, unsigned char *context)
3418 BIO *io, *ssl_bio, *sbio;
3420 buf = app_malloc(bufsize, "server rev buffer");
3421 io = BIO_new(BIO_f_buffer());
3422 ssl_bio = BIO_new(BIO_f_ssl());
3423 if ((io == NULL) || (ssl_bio == NULL))
3426 /* lets make the output buffer a reasonable size */
3427 if (!BIO_set_write_buffer_size(io, bufsize))
3430 if ((con = SSL_new(ctx)) == NULL)
3433 if (s_tlsextdebug) {
3434 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3435 SSL_set_tlsext_debug_arg(con, bio_s_out);
3438 && !SSL_set_session_id_context(con, context,
3439 strlen((char *)context))) {
3441 ERR_print_errors(bio_err);
3445 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3446 SSL_set_bio(con, sbio, sbio);
3447 SSL_set_accept_state(con);
3449 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3450 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3451 BIO_push(io, ssl_bio);
3453 #ifdef CHARSET_EBCDIC
3454 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3458 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3459 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3462 #ifndef OPENSSL_NO_SSL_TRACE
3464 SSL_set_msg_callback(con, SSL_trace);
3467 SSL_set_msg_callback(con, msg_cb);
3468 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3472 i = BIO_do_handshake(io);
3475 if (!BIO_should_retry(io)) {
3476 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3477 ERR_print_errors(bio_err);
3480 #ifndef OPENSSL_NO_SRP
3481 if (BIO_should_io_special(io)
3482 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3483 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3485 lookup_srp_user(&srp_callback_parm, bio_s_out);
3491 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3492 print_ssl_summary(con);
3495 i = BIO_gets(io, buf, bufsize - 1);
3496 if (i < 0) { /* error */
3497 if (!BIO_should_retry(io)) {
3499 ERR_print_errors(bio_err);
3502 BIO_printf(bio_s_out, "read R BLOCK\n");
3503 #ifndef OPENSSL_NO_SRP
3504 if (BIO_should_io_special(io)
3505 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3506 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3508 lookup_srp_user(&srp_callback_parm, bio_s_out);
3516 } else if (i == 0) { /* end of input */
3518 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3521 char *p = buf + i - 1;
3522 while (i && (*p == '\n' || *p == '\r')) {
3526 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3528 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3531 BUF_reverse((unsigned char *)buf, NULL, i);
3533 BIO_write(io, buf, i + 1);
3538 if (!BIO_should_retry(io))
3544 /* make sure we re-use sessions */
3545 do_ssl_shutdown(con);
3555 #define MAX_SESSION_ID_ATTEMPTS 10
3556 static int generate_session_id(SSL *ssl, unsigned char *id,
3557 unsigned int *id_len)
3559 unsigned int count = 0;
3560 unsigned int session_id_prefix_len = strlen(session_id_prefix);
3563 if (RAND_bytes(id, *id_len) <= 0)
3566 * Prefix the session_id with the required prefix. NB: If our prefix
3567 * is too long, clip it - but there will be worse effects anyway, eg.
3568 * the server could only possibly create 1 session ID (ie. the
3569 * prefix!) so all future session negotiations will fail due to
3572 memcpy(id, session_id_prefix,
3573 (session_id_prefix_len < *id_len) ?
3574 session_id_prefix_len : *id_len);
3576 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3577 (++count < MAX_SESSION_ID_ATTEMPTS));
3578 if (count >= MAX_SESSION_ID_ATTEMPTS)
3584 * By default s_server uses an in-memory cache which caches SSL_SESSION
3585 * structures without any serialization. This hides some bugs which only
3586 * become apparent in deployed servers. By implementing a basic external
3587 * session cache some issues can be debugged using s_server.
3590 typedef struct simple_ssl_session_st {
3595 struct simple_ssl_session_st *next;
3596 } simple_ssl_session;
3598 static simple_ssl_session *first = NULL;
3600 static int add_session(SSL *ssl, SSL_SESSION *session)
3602 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3605 SSL_SESSION_get_id(session, &sess->idlen);
3606 sess->derlen = i2d_SSL_SESSION(session, NULL);
3607 if (sess->derlen < 0) {
3608 BIO_printf(bio_err, "Error encoding session\n");
3613 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3614 sess->der = app_malloc(sess->derlen, "get session buffer");
3616 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3617 OPENSSL_free(sess->id);
3618 OPENSSL_free(sess->der);
3624 /* Assume it still works. */
3625 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3626 BIO_printf(bio_err, "Unexpected session encoding length\n");
3627 OPENSSL_free(sess->id);
3628 OPENSSL_free(sess->der);
3635 BIO_printf(bio_err, "New session added to external cache\n");
3639 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3642 simple_ssl_session *sess;
3644 for (sess = first; sess; sess = sess->next) {
3645 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3646 const unsigned char *p = sess->der;
3647 BIO_printf(bio_err, "Lookup session: cache hit\n");
3648 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3651 BIO_printf(bio_err, "Lookup session: cache miss\n");
3655 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3657 simple_ssl_session *sess, *prev = NULL;
3658 const unsigned char *id;
3660 id = SSL_SESSION_get_id(session, &idlen);
3661 for (sess = first; sess; sess = sess->next) {
3662 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3664 prev->next = sess->next;
3667 OPENSSL_free(sess->id);
3668 OPENSSL_free(sess->der);
3676 static void init_session_cache_ctx(SSL_CTX *sctx)
3678 SSL_CTX_set_session_cache_mode(sctx,
3679 SSL_SESS_CACHE_NO_INTERNAL |
3680 SSL_SESS_CACHE_SERVER);
3681 SSL_CTX_sess_set_new_cb(sctx, add_session);
3682 SSL_CTX_sess_set_get_cb(sctx, get_session);
3683 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3686 static void free_sessions(void)
3688 simple_ssl_session *sess, *tsess;
3689 for (sess = first; sess;) {
3690 OPENSSL_free(sess->id);
3691 OPENSSL_free(sess->der);
3694 OPENSSL_free(tsess);
3699 #endif /* OPENSSL_NO_SOCK */