2 * Copyright 1995-2023 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/rand.h>
46 #include <openssl/ocsp.h>
48 # include <openssl/dh.h>
50 #include <openssl/rsa.h>
54 #include <openssl/ebcdic.h>
56 #include "internal/sockets.h"
58 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
59 static int sv_body(int s, int stype, int prot, unsigned char *context);
60 static int www_body(int s, int stype, int prot, unsigned char *context);
61 static int rev_body(int s, int stype, int prot, unsigned char *context);
62 static void close_accept_socket(void);
63 static int init_ssl_connection(SSL *s);
64 static void print_stats(BIO *bp, SSL_CTX *ctx);
65 static int generate_session_id(SSL *ssl, unsigned char *id,
66 unsigned int *id_len);
67 static void init_session_cache_ctx(SSL_CTX *sctx);
68 static void free_sessions(void);
69 static void print_connection_info(SSL *con);
71 static const int bufsize = 16 * 1024;
72 static int accept_socket = -1;
74 #define TEST_CERT "server.pem"
75 #define TEST_CERT2 "server2.pem"
77 static int s_nbio = 0;
78 static int s_nbio_test = 0;
79 static int s_crlf = 0;
80 static SSL_CTX *ctx = NULL;
81 static SSL_CTX *ctx2 = NULL;
84 static BIO *bio_s_out = NULL;
85 static BIO *bio_s_msg = NULL;
86 static int s_debug = 0;
87 static int s_tlsextdebug = 0;
89 static int s_quiet = 0;
90 static int s_ign_eof = 0;
91 static int s_brief = 0;
93 static char *keymatexportlabel = NULL;
94 static int keymatexportlen = 20;
98 static int use_sendfile = 0;
99 static int use_zc_sendfile = 0;
101 static const char *session_id_prefix = NULL;
103 static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
104 static int enable_client_rpk = 0;
106 #ifndef OPENSSL_NO_DTLS
107 static int enable_timeouts = 0;
108 static long socket_mtu;
112 * We define this but make it always be 0 in no-dtls builds to simplify the
115 static int dtlslisten = 0;
116 static int stateless = 0;
118 static int early_data = 0;
119 static SSL_SESSION *psksess = NULL;
121 static char *psk_identity = "Client_identity";
122 char *psk_key = NULL; /* by default PSK is not used */
124 static char http_server_binmode = 0; /* for now: 0/1 = default/binary */
126 #ifndef OPENSSL_NO_PSK
127 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
129 unsigned int max_psk_len)
135 BIO_printf(bio_s_out, "psk_server_cb\n");
137 if (!SSL_is_dtls(ssl) && SSL_version(ssl) >= TLS1_3_VERSION) {
139 * This callback is designed for use in (D)TLSv1.2 (or below). It is
140 * possible to use a single callback for all protocol versions - but it
141 * is preferred to use a dedicated callback for TLSv1.3. For TLSv1.3 we
142 * have psk_find_session_cb.
147 if (identity == NULL) {
148 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
152 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
153 (int)strlen(identity), identity);
155 /* here we could lookup the given identity e.g. from a database */
156 if (strcmp(identity, psk_identity) != 0) {
157 BIO_printf(bio_s_out, "PSK warning: client identity not what we expected"
158 " (got '%s' expected '%s')\n", identity, psk_identity);
161 BIO_printf(bio_s_out, "PSK client identity found\n");
164 /* convert the PSK key to binary */
165 key = OPENSSL_hexstr2buf(psk_key, &key_len);
167 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
171 if (key_len > (int)max_psk_len) {
173 "psk buffer of callback is too small (%d) for key (%ld)\n",
174 max_psk_len, key_len);
179 memcpy(psk, key, key_len);
183 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
187 BIO_printf(bio_err, "Error in PSK server callback\n");
188 (void)BIO_flush(bio_err);
189 (void)BIO_flush(bio_s_out);
194 static int psk_find_session_cb(SSL *ssl, const unsigned char *identity,
195 size_t identity_len, SSL_SESSION **sess)
197 SSL_SESSION *tmpsess = NULL;
200 const SSL_CIPHER *cipher = NULL;
202 if (strlen(psk_identity) != identity_len
203 || memcmp(psk_identity, identity, identity_len) != 0) {
208 if (psksess != NULL) {
209 SSL_SESSION_up_ref(psksess);
214 key = OPENSSL_hexstr2buf(psk_key, &key_len);
216 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
221 /* We default to SHA256 */
222 cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id);
223 if (cipher == NULL) {
224 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
229 tmpsess = SSL_SESSION_new();
231 || !SSL_SESSION_set1_master_key(tmpsess, key, key_len)
232 || !SSL_SESSION_set_cipher(tmpsess, cipher)
233 || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) {
235 SSL_SESSION_free(tmpsess);
244 #ifndef OPENSSL_NO_SRP
245 static srpsrvparm srp_callback_parm;
248 static int local_argc = 0;
249 static char **local_argv;
251 #ifdef CHARSET_EBCDIC
252 static int ebcdic_new(BIO *bi);
253 static int ebcdic_free(BIO *a);
254 static int ebcdic_read(BIO *b, char *out, int outl);
255 static int ebcdic_write(BIO *b, const char *in, int inl);
256 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
257 static int ebcdic_gets(BIO *bp, char *buf, int size);
258 static int ebcdic_puts(BIO *bp, const char *str);
260 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
261 static BIO_METHOD *methods_ebcdic = NULL;
263 /* This struct is "unwarranted chumminess with the compiler." */
269 static const BIO_METHOD *BIO_f_ebcdic_filter(void)
271 if (methods_ebcdic == NULL) {
272 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
273 "EBCDIC/ASCII filter");
274 if (methods_ebcdic == NULL
275 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
276 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
277 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
278 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
279 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
280 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
281 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
284 return methods_ebcdic;
287 static int ebcdic_new(BIO *bi)
289 EBCDIC_OUTBUFF *wbuf;
291 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
292 wbuf->alloced = 1024;
293 wbuf->buff[0] = '\0';
295 BIO_set_data(bi, wbuf);
300 static int ebcdic_free(BIO *a)
302 EBCDIC_OUTBUFF *wbuf;
306 wbuf = BIO_get_data(a);
308 BIO_set_data(a, NULL);
314 static int ebcdic_read(BIO *b, char *out, int outl)
317 BIO *next = BIO_next(b);
319 if (out == NULL || outl == 0)
324 ret = BIO_read(next, out, outl);
326 ascii2ebcdic(out, out, ret);
330 static int ebcdic_write(BIO *b, const char *in, int inl)
332 EBCDIC_OUTBUFF *wbuf;
333 BIO *next = BIO_next(b);
337 if ((in == NULL) || (inl <= 0))
342 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
344 if (inl > (num = wbuf->alloced)) {
345 num = num + num; /* double the size */
349 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
352 wbuf->buff[0] = '\0';
354 BIO_set_data(b, wbuf);
357 ebcdic2ascii(wbuf->buff, in, inl);
359 ret = BIO_write(next, wbuf->buff, inl);
364 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
367 BIO *next = BIO_next(b);
376 ret = BIO_ctrl(next, cmd, num, ptr);
382 static int ebcdic_gets(BIO *bp, char *buf, int size)
385 BIO *next = BIO_next(bp);
389 /* return(BIO_gets(bp->next_bio,buf,size));*/
390 for (i = 0; i < size - 1; ++i) {
391 ret = ebcdic_read(bp, &buf[i], 1);
394 else if (buf[i] == '\n') {
401 return (ret < 0 && i == 0) ? ret : i;
404 static int ebcdic_puts(BIO *bp, const char *str)
406 if (BIO_next(bp) == NULL)
408 return ebcdic_write(bp, str, strlen(str));
412 /* This is a context that we pass to callbacks */
413 typedef struct tlsextctx_st {
419 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
421 tlsextctx *p = (tlsextctx *) arg;
422 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
424 if (servername != NULL && p->biodebug != NULL) {
425 const char *cp = servername;
428 BIO_printf(p->biodebug, "Hostname in TLS extension: \"");
429 while ((uc = *cp++) != 0)
430 BIO_printf(p->biodebug,
431 (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc);
432 BIO_printf(p->biodebug, "\"\n");
435 if (p->servername == NULL)
436 return SSL_TLSEXT_ERR_NOACK;
438 if (servername != NULL) {
439 if (OPENSSL_strcasecmp(servername, p->servername))
440 return p->extension_error;
442 BIO_printf(p->biodebug, "Switching server context.\n");
443 SSL_set_SSL_CTX(s, ctx2);
446 return SSL_TLSEXT_ERR_OK;
449 /* Structure passed to cert status callback */
450 typedef struct tlsextstatusctx_st {
452 /* File to load OCSP Response from (or NULL if no file) */
454 /* Default responder to use */
455 char *host, *path, *port;
456 char *proxy, *no_proxy;
461 static tlsextstatusctx tlscstatp = { -1 };
463 #ifndef OPENSSL_NO_OCSP
466 * Helper function to get an OCSP_RESPONSE from a responder. This is a
467 * simplified version. It examines certificates each time and makes one OCSP
468 * responder query for each request. A full version would store details such as
469 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
470 * them until they were considered "expired".
472 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
473 OCSP_RESPONSE **resp)
475 char *host = NULL, *port = NULL, *path = NULL;
476 char *proxy = NULL, *no_proxy = NULL;
478 STACK_OF(OPENSSL_STRING) *aia = NULL;
480 X509_STORE_CTX *inctx = NULL;
482 OCSP_REQUEST *req = NULL;
483 OCSP_CERTID *id = NULL;
484 STACK_OF(X509_EXTENSION) *exts;
485 int ret = SSL_TLSEXT_ERR_NOACK;
488 /* Build up OCSP query from server certificate */
489 x = SSL_get_certificate(s);
490 aia = X509_get1_ocsp(x);
492 if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl,
493 NULL, &host, &port, NULL, &path, NULL, NULL)) {
494 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
498 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
499 sk_OPENSSL_STRING_value(aia, 0));
501 if (srctx->host == NULL) {
503 "cert_status: no AIA and no default responder URL\n");
509 use_ssl = srctx->use_ssl;
511 proxy = srctx->proxy;
512 no_proxy = srctx->no_proxy;
514 inctx = X509_STORE_CTX_new();
517 if (!X509_STORE_CTX_init(inctx,
518 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
521 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
522 X509_get_issuer_name(x));
524 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
527 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
528 X509_OBJECT_free(obj);
531 req = OCSP_REQUEST_new();
534 if (!OCSP_request_add0_id(req, id))
537 /* Add any extensions to the request */
538 SSL_get_tlsext_status_exts(s, &exts);
539 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
540 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
541 if (!OCSP_REQUEST_add_ext(req, ext, -1))
544 *resp = process_responder(req, host, port, path, proxy, no_proxy,
545 use_ssl, NULL /* headers */, srctx->timeout);
547 BIO_puts(bio_err, "cert_status: error querying responder\n");
551 ret = SSL_TLSEXT_ERR_OK;
555 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
558 * If we parsed aia we need to free; otherwise they were copied and we
565 X509_email_free(aia);
567 OCSP_CERTID_free(id);
568 OCSP_REQUEST_free(req);
569 X509_STORE_CTX_free(inctx);
574 * Certificate Status callback. This is called when a client includes a
575 * certificate status request extension. The response is either obtained from a
576 * file, or from an OCSP responder.
578 static int cert_status_cb(SSL *s, void *arg)
580 tlsextstatusctx *srctx = arg;
581 OCSP_RESPONSE *resp = NULL;
582 unsigned char *rspder = NULL;
584 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
587 BIO_puts(bio_err, "cert_status: callback called\n");
589 if (srctx->respin != NULL) {
590 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
591 if (derbio == NULL) {
592 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
595 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
598 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
602 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
603 if (ret != SSL_TLSEXT_ERR_OK)
607 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
611 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
612 if (srctx->verbose) {
613 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
614 OCSP_RESPONSE_print(bio_err, resp, 2);
617 ret = SSL_TLSEXT_ERR_OK;
620 if (ret != SSL_TLSEXT_ERR_OK)
621 ERR_print_errors(bio_err);
623 OCSP_RESPONSE_free(resp);
629 #ifndef OPENSSL_NO_NEXTPROTONEG
630 /* This is the context that we pass to next_proto_cb */
631 typedef struct tlsextnextprotoctx_st {
634 } tlsextnextprotoctx;
636 static int next_proto_cb(SSL *s, const unsigned char **data,
637 unsigned int *len, void *arg)
639 tlsextnextprotoctx *next_proto = arg;
641 *data = next_proto->data;
642 *len = next_proto->len;
644 return SSL_TLSEXT_ERR_OK;
646 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
648 /* This the context that we pass to alpn_cb */
649 typedef struct tlsextalpnctx_st {
654 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
655 const unsigned char *in, unsigned int inlen, void *arg)
657 tlsextalpnctx *alpn_ctx = arg;
660 /* We can assume that |in| is syntactically valid. */
662 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
663 for (i = 0; i < inlen;) {
665 BIO_write(bio_s_out, ", ", 2);
666 BIO_write(bio_s_out, &in[i + 1], in[i]);
669 BIO_write(bio_s_out, "\n", 1);
672 if (SSL_select_next_proto
673 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
674 inlen) != OPENSSL_NPN_NEGOTIATED) {
675 return SSL_TLSEXT_ERR_ALERT_FATAL;
679 BIO_printf(bio_s_out, "ALPN protocols selected: ");
680 BIO_write(bio_s_out, *out, *outlen);
681 BIO_write(bio_s_out, "\n", 1);
684 return SSL_TLSEXT_ERR_OK;
687 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
689 /* disable resumption for sessions with forward secure ciphers */
690 return is_forward_secure;
693 typedef enum OPTION_choice {
696 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
697 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
698 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
699 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
700 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
701 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
702 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
703 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
705 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
706 OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
707 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
708 OPT_STATUS_TIMEOUT, OPT_PROXY, OPT_NO_PROXY, OPT_STATUS_URL,
709 OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
710 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
711 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
712 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK,
713 OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW,
714 OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG,
715 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
716 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
717 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS,
718 OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
719 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE,
720 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
721 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA,
722 OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG,
723 OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF, OPT_KTLS,
725 OPT_TFO, OPT_CERT_COMP,
726 OPT_ENABLE_SERVER_RPK,
727 OPT_ENABLE_CLIENT_RPK,
735 const OPTIONS s_server_options[] = {
736 OPT_SECTION("General"),
737 {"help", OPT_HELP, '-', "Display this summary"},
738 {"ssl_config", OPT_SSL_CONFIG, 's',
739 "Configure SSL_CTX using the given configuration value"},
740 #ifndef OPENSSL_NO_SSL_TRACE
741 {"trace", OPT_TRACE, '-', "trace protocol messages"},
743 #ifndef OPENSSL_NO_ENGINE
744 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
747 OPT_SECTION("Network"),
748 {"port", OPT_PORT, 'p',
749 "TCP/IP port to listen on for connections (default is " PORT ")"},
750 {"accept", OPT_ACCEPT, 's',
751 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
753 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
754 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
756 {"4", OPT_4, '-', "Use IPv4 only"},
757 {"6", OPT_6, '-', "Use IPv6 only"},
758 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
759 {"tfo", OPT_TFO, '-', "Listen for TCP Fast Open connections"},
762 OPT_SECTION("Identity"),
763 {"context", OPT_CONTEXT, 's', "Set session ID context"},
764 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
765 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
766 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
767 {"no-CAfile", OPT_NOCAFILE, '-',
768 "Do not load the default certificates file"},
769 {"no-CApath", OPT_NOCAPATH, '-',
770 "Do not load certificates from the default certificates directory"},
771 {"no-CAstore", OPT_NOCASTORE, '-',
772 "Do not load certificates from the default certificates store URI"},
773 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
774 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
775 {"Verify", OPT_UPPER_V_VERIFY, 'n',
776 "Turn on peer certificate verification, must have a cert"},
777 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
778 {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT},
779 {"cert2", OPT_CERT2, '<',
780 "Certificate file to use for servername; default " TEST_CERT2},
781 {"certform", OPT_CERTFORM, 'F',
782 "Server certificate file format (PEM/DER/P12); has no effect"},
783 {"cert_chain", OPT_CERT_CHAIN, '<',
784 "Server certificate chain file in PEM format"},
785 {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"},
786 {"serverinfo", OPT_SERVERINFO, 's',
787 "PEM serverinfo file for certificate"},
788 {"key", OPT_KEY, 's',
789 "Private key file to use; default is -cert file or else" TEST_CERT},
790 {"key2", OPT_KEY2, '<',
791 "-Private Key file to use for servername if not in -cert2"},
792 {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"},
793 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
794 {"dcert", OPT_DCERT, '<',
795 "Second server certificate file to use (usually for DSA)"},
796 {"dcertform", OPT_DCERTFORM, 'F',
797 "Second server certificate file format (PEM/DER/P12); has no effect"},
798 {"dcert_chain", OPT_DCERT_CHAIN, '<',
799 "second server certificate chain file in PEM format"},
800 {"dkey", OPT_DKEY, '<',
801 "Second private key file to use (usually for DSA)"},
802 {"dkeyform", OPT_DKEYFORM, 'f',
803 "Second key file format (ENGINE, other values ignored)"},
804 {"dpass", OPT_DPASS, 's',
805 "Second private key and cert file pass phrase source"},
806 {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
807 {"servername", OPT_SERVERNAME, 's',
808 "Servername for HostName TLS extension"},
809 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
810 "On servername mismatch send fatal alert (default warning alert)"},
811 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
812 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
813 {"quiet", OPT_QUIET, '-', "No server output"},
814 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
815 "Disable caching and tickets if ephemeral (EC)DH is used"},
816 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
817 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
818 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
819 "Do not treat lack of close_notify from a peer as an error"},
820 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
821 "Hex dump of all TLS extensions received"},
822 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
823 {"id_prefix", OPT_ID_PREFIX, 's',
824 "Generate SSL/TLS session IDs prefixed by arg"},
825 {"keymatexport", OPT_KEYMATEXPORT, 's',
826 "Export keying material using label"},
827 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
828 "Export len bytes of keying material; default 20"},
829 {"CRL", OPT_CRL, '<', "CRL file to use"},
830 {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"},
831 {"crl_download", OPT_CRL_DOWNLOAD, '-',
832 "Download CRLs from distribution points in certificate CDP entries"},
833 {"chainCAfile", OPT_CHAINCAFILE, '<',
834 "CA file for certificate chain (PEM format)"},
835 {"chainCApath", OPT_CHAINCAPATH, '/',
836 "use dir as certificate store path to build CA certificate chain"},
837 {"chainCAstore", OPT_CHAINCASTORE, ':',
838 "use URI as certificate store to build CA certificate chain"},
839 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
840 "CA file for certificate verification (PEM format)"},
841 {"verifyCApath", OPT_VERIFYCAPATH, '/',
842 "use dir as certificate store path to verify CA certificate"},
843 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
844 "use URI as certificate store to verify CA certificate"},
845 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
846 {"ext_cache", OPT_EXT_CACHE, '-',
847 "Disable internal cache, set up and use external cache"},
848 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
849 "Close connection on verification error"},
850 {"verify_quiet", OPT_VERIFY_QUIET, '-',
851 "No verify output except verify errors"},
852 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input EOF (default when -quiet)"},
853 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input EOF"},
854 #ifndef OPENSSL_NO_COMP_ALG
855 {"cert_comp", OPT_CERT_COMP, '-', "Pre-compress server certificates"},
858 #ifndef OPENSSL_NO_OCSP
860 {"status", OPT_STATUS, '-', "Request certificate status from server"},
861 {"status_verbose", OPT_STATUS_VERBOSE, '-',
862 "Print more output in certificate status callback"},
863 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
864 "Status request responder timeout"},
865 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
866 {"proxy", OPT_PROXY, 's',
867 "[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"},
868 {"no_proxy", OPT_NO_PROXY, 's',
869 "List of addresses of servers not to use HTTP(S) proxy for"},
871 "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
872 {"status_file", OPT_STATUS_FILE, '<',
873 "File containing DER encoded OCSP Response"},
876 OPT_SECTION("Debug"),
877 {"security_debug", OPT_SECURITY_DEBUG, '-',
878 "Print output from SSL/TLS security framework"},
879 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
880 "Print more output from SSL/TLS security framework"},
881 {"brief", OPT_BRIEF, '-',
882 "Restrict output to brief summary of connection parameters"},
883 {"rev", OPT_REV, '-',
884 "act as an echo server that sends back received text reversed"},
885 {"debug", OPT_DEBUG, '-', "Print more output"},
886 {"msg", OPT_MSG, '-', "Show protocol messages"},
887 {"msgfile", OPT_MSGFILE, '>',
888 "File to send output of -msg or -trace, instead of stdout"},
889 {"state", OPT_STATE, '-', "Print the SSL states"},
890 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
891 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
892 "Maximum number of encrypt/decrypt pipelines to be used"},
893 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
894 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
896 OPT_SECTION("Network"),
897 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
898 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
899 {"mtu", OPT_MTU, 'p', "Set link-layer MTU"},
900 {"read_buf", OPT_READ_BUF, 'p',
901 "Default read buffer size to be used for connections"},
902 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
903 "Size used to split data for encrypt pipelines"},
904 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
906 OPT_SECTION("Server identity"),
907 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
908 #ifndef OPENSSL_NO_PSK
909 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
911 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
912 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
913 #ifndef OPENSSL_NO_SRP
914 {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"},
915 {"srpuserseed", OPT_SRPUSERSEED, 's',
916 "(deprecated) A seed string for a default user salt"},
919 OPT_SECTION("Protocol and version"),
920 {"max_early_data", OPT_MAX_EARLY, 'n',
921 "The maximum number of bytes of early data as advertised in tickets"},
922 {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n',
923 "The maximum number of bytes of early data (hard limit)"},
924 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
925 {"num_tickets", OPT_S_NUM_TICKETS, 'n',
926 "The number of TLSv1.3 session tickets that a server will automatically issue" },
927 {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"},
928 {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"},
929 {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"},
930 {"no_ca_names", OPT_NOCANAMES, '-',
931 "Disable TLS Extension CA Names"},
932 {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"},
933 #ifndef OPENSSL_NO_SSL3
934 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
936 #ifndef OPENSSL_NO_TLS1
937 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
939 #ifndef OPENSSL_NO_TLS1_1
940 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
942 #ifndef OPENSSL_NO_TLS1_2
943 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
945 #ifndef OPENSSL_NO_TLS1_3
946 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
948 #ifndef OPENSSL_NO_DTLS
949 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
950 {"listen", OPT_LISTEN, '-',
951 "Listen for a DTLS ClientHello with a cookie and then connect"},
953 #ifndef OPENSSL_NO_DTLS1
954 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
956 #ifndef OPENSSL_NO_DTLS1_2
957 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
959 #ifndef OPENSSL_NO_SCTP
960 {"sctp", OPT_SCTP, '-', "Use SCTP"},
961 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
963 #ifndef OPENSSL_NO_SRTP
964 {"use_srtp", OPT_SRTP_PROFILES, 's',
965 "Offer SRTP key management with a colon-separated profile list"},
967 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
968 #ifndef OPENSSL_NO_NEXTPROTONEG
969 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
970 "Set the advertised protocols for the NPN extension (comma-separated list)"},
972 {"alpn", OPT_ALPN, 's',
973 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
974 #ifndef OPENSSL_NO_KTLS
975 {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"},
976 {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"},
977 {"zerocopy_sendfile", OPT_USE_ZC_SENDFILE, '-', "Use zerocopy mode of KTLS sendfile"},
979 {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"},
980 {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"},
989 #define IS_PROT_FLAG(o) \
990 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
991 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
993 int s_server_main(int argc, char *argv[])
995 ENGINE *engine = NULL;
996 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
997 SSL_CONF_CTX *cctx = NULL;
998 const SSL_METHOD *meth = TLS_server_method();
999 SSL_EXCERT *exc = NULL;
1000 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
1001 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
1002 STACK_OF(X509_CRL) *crls = NULL;
1003 X509 *s_cert = NULL, *s_dcert = NULL;
1004 X509_VERIFY_PARAM *vpm = NULL;
1005 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
1006 const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL;
1007 char *dpassarg = NULL, *dpass = NULL;
1008 char *passarg = NULL, *pass = NULL;
1009 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
1010 char *crl_file = NULL, *prog;
1012 int unlink_unix_path = 0;
1014 do_server_cb server_cb;
1015 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
1016 char *dhfile = NULL;
1018 int nocert = 0, ret = 1;
1019 int noCApath = 0, noCAfile = 0, noCAstore = 0;
1020 int s_cert_format = FORMAT_UNDEF, s_key_format = FORMAT_UNDEF;
1021 int s_dcert_format = FORMAT_UNDEF, s_dkey_format = FORMAT_UNDEF;
1022 int rev = 0, naccept = -1, sdebug = 0;
1023 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
1024 int state = 0, crl_format = FORMAT_UNDEF, crl_download = 0;
1027 unsigned char *context = NULL;
1029 EVP_PKEY *s_key2 = NULL;
1030 X509 *s_cert2 = NULL;
1031 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
1032 const char *ssl_config = NULL;
1033 int read_buf_len = 0;
1034 #ifndef OPENSSL_NO_NEXTPROTONEG
1035 const char *next_proto_neg_in = NULL;
1036 tlsextnextprotoctx next_proto = { NULL, 0 };
1038 const char *alpn_in = NULL;
1039 tlsextalpnctx alpn_ctx = { NULL, 0 };
1040 #ifndef OPENSSL_NO_PSK
1041 /* by default do not send a PSK identity hint */
1042 char *psk_identity_hint = NULL;
1045 #ifndef OPENSSL_NO_SRP
1046 char *srpuserseed = NULL;
1047 char *srp_verifier_file = NULL;
1049 #ifndef OPENSSL_NO_SRTP
1050 char *srtp_profiles = NULL;
1052 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1053 int s_server_verify = SSL_VERIFY_NONE;
1054 int s_server_session_id_context = 1; /* anything will do */
1055 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
1056 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
1057 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
1058 #ifndef OPENSSL_NO_OCSP
1059 int s_tlsextstatus = 0;
1061 int no_resume_ephemeral = 0;
1062 unsigned int max_send_fragment = 0;
1063 unsigned int split_send_fragment = 0, max_pipelines = 0;
1064 const char *s_serverinfo_file = NULL;
1065 const char *keylog_file = NULL;
1066 int max_early_data = -1, recv_max_early_data = -1;
1067 char *psksessf = NULL;
1068 int no_ca_names = 0;
1069 #ifndef OPENSSL_NO_SCTP
1070 int sctp_label_bug = 0;
1072 int ignore_unexpected_eof = 0;
1073 #ifndef OPENSSL_NO_KTLS
1074 int enable_ktls = 0;
1078 int enable_server_rpk = 0;
1080 /* Init of few remaining global variables */
1085 s_nbio = s_nbio_test = 0;
1094 use_zc_sendfile = 0;
1096 port = OPENSSL_strdup(PORT);
1097 cctx = SSL_CONF_CTX_new();
1098 vpm = X509_VERIFY_PARAM_new();
1099 if (port == NULL || cctx == NULL || vpm == NULL)
1101 SSL_CONF_CTX_set_flags(cctx,
1102 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1104 prog = opt_init(argc, argv, s_server_options);
1105 while ((o = opt_next()) != OPT_EOF) {
1106 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1107 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1110 if (IS_NO_PROT_FLAG(o))
1112 if (prot_opt == 1 && no_prot_opt) {
1114 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1121 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1124 opt_help(s_server_options);
1130 if (socket_family == AF_UNIX) {
1131 OPENSSL_free(host); host = NULL;
1132 OPENSSL_free(port); port = NULL;
1135 socket_family = AF_INET;
1141 if (socket_family == AF_UNIX) {
1142 OPENSSL_free(host); host = NULL;
1143 OPENSSL_free(port); port = NULL;
1146 socket_family = AF_INET6;
1149 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1155 if (socket_family == AF_UNIX) {
1156 socket_family = AF_UNSPEC;
1159 OPENSSL_free(port); port = NULL;
1160 OPENSSL_free(host); host = NULL;
1161 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1163 "%s: -port argument malformed or ambiguous\n",
1170 if (socket_family == AF_UNIX) {
1171 socket_family = AF_UNSPEC;
1174 OPENSSL_free(port); port = NULL;
1175 OPENSSL_free(host); host = NULL;
1176 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1178 "%s: -accept argument malformed or ambiguous\n",
1185 socket_family = AF_UNIX;
1186 OPENSSL_free(host); host = OPENSSL_strdup(opt_arg());
1189 OPENSSL_free(port); port = NULL;
1192 unlink_unix_path = 1;
1196 naccept = atol(opt_arg());
1199 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1200 verify_args.depth = atoi(opt_arg());
1202 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1204 case OPT_UPPER_V_VERIFY:
1206 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1207 SSL_VERIFY_CLIENT_ONCE;
1208 verify_args.depth = atoi(opt_arg());
1211 "verify depth is %d, must return a certificate\n",
1215 context = (unsigned char *)opt_arg();
1218 s_cert_file = opt_arg();
1221 if (!set_nameopt(opt_arg()))
1225 crl_file = opt_arg();
1227 case OPT_CRL_DOWNLOAD:
1230 case OPT_SERVERINFO:
1231 s_serverinfo_file = opt_arg();
1234 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format))
1238 s_key_file = opt_arg();
1241 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1245 passarg = opt_arg();
1247 case OPT_CERT_CHAIN:
1248 s_chain_file = opt_arg();
1254 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format))
1258 s_dcert_file = opt_arg();
1261 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format))
1265 dpassarg = opt_arg();
1268 s_dkey_file = opt_arg();
1270 case OPT_DCERT_CHAIN:
1271 s_dchain_file = opt_arg();
1282 case OPT_CHAINCAPATH:
1283 chCApath = opt_arg();
1285 case OPT_VERIFYCAPATH:
1286 vfyCApath = opt_arg();
1289 CAstore = opt_arg();
1294 case OPT_CHAINCASTORE:
1295 chCAstore = opt_arg();
1297 case OPT_VERIFYCASTORE:
1298 vfyCAstore = opt_arg();
1307 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1311 case OPT_S_NUM_TICKETS:
1312 case OPT_ANTI_REPLAY:
1313 case OPT_NO_ANTI_REPLAY:
1314 if (ssl_args == NULL)
1315 ssl_args = sk_OPENSSL_STRING_new_null();
1316 if (ssl_args == NULL
1317 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1318 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1319 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1324 if (!opt_verify(o, vpm))
1329 if (!args_excert(o, &exc))
1332 case OPT_VERIFY_RET_ERROR:
1333 verify_args.return_error = 1;
1335 case OPT_VERIFY_QUIET:
1336 verify_args.quiet = 1;
1338 case OPT_BUILD_CHAIN:
1347 case OPT_CHAINCAFILE:
1348 chCAfile = opt_arg();
1350 case OPT_VERIFYCAFILE:
1351 vfyCAfile = opt_arg();
1357 s_nbio = s_nbio_test = 1;
1362 case OPT_NO_IGN_EOF:
1368 case OPT_TLSEXTDEBUG:
1372 #ifndef OPENSSL_NO_OCSP
1376 case OPT_STATUS_VERBOSE:
1377 #ifndef OPENSSL_NO_OCSP
1378 s_tlsextstatus = tlscstatp.verbose = 1;
1381 case OPT_STATUS_TIMEOUT:
1382 #ifndef OPENSSL_NO_OCSP
1384 tlscstatp.timeout = atoi(opt_arg());
1388 #ifndef OPENSSL_NO_OCSP
1389 tlscstatp.proxy = opt_arg();
1393 #ifndef OPENSSL_NO_OCSP
1394 tlscstatp.no_proxy = opt_arg();
1397 case OPT_STATUS_URL:
1398 #ifndef OPENSSL_NO_OCSP
1400 if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL,
1401 &tlscstatp.host, &tlscstatp.port, NULL,
1402 &tlscstatp.path, NULL, NULL)) {
1403 BIO_printf(bio_err, "Error parsing -status_url argument\n");
1408 case OPT_STATUS_FILE:
1409 #ifndef OPENSSL_NO_OCSP
1411 tlscstatp.respin = opt_arg();
1418 bio_s_msg = BIO_new_file(opt_arg(), "w");
1419 if (bio_s_msg == NULL) {
1420 BIO_printf(bio_err, "Error writing file %s\n", opt_arg());
1425 #ifndef OPENSSL_NO_SSL_TRACE
1429 case OPT_SECURITY_DEBUG:
1432 case OPT_SECURITY_DEBUG_VERBOSE:
1445 s_quiet = s_brief = verify_args.quiet = 1;
1450 case OPT_NO_RESUME_EPHEMERAL:
1451 no_resume_ephemeral = 1;
1453 case OPT_PSK_IDENTITY:
1454 psk_identity = opt_arg();
1457 #ifndef OPENSSL_NO_PSK
1458 psk_identity_hint = opt_arg();
1462 for (p = psk_key = opt_arg(); *p; p++) {
1463 if (isxdigit(_UC(*p)))
1465 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1470 psksessf = opt_arg();
1473 #ifndef OPENSSL_NO_SRP
1474 srp_verifier_file = opt_arg();
1475 if (min_version < TLS1_VERSION)
1476 min_version = TLS1_VERSION;
1479 case OPT_SRPUSERSEED:
1480 #ifndef OPENSSL_NO_SRP
1481 srpuserseed = opt_arg();
1482 if (min_version < TLS1_VERSION)
1483 min_version = TLS1_VERSION;
1498 case OPT_SSL_CONFIG:
1499 ssl_config = opt_arg();
1502 min_version = SSL3_VERSION;
1503 max_version = SSL3_VERSION;
1506 min_version = TLS1_3_VERSION;
1507 max_version = TLS1_3_VERSION;
1510 min_version = TLS1_2_VERSION;
1511 max_version = TLS1_2_VERSION;
1514 min_version = TLS1_1_VERSION;
1515 max_version = TLS1_1_VERSION;
1518 min_version = TLS1_VERSION;
1519 max_version = TLS1_VERSION;
1522 #ifndef OPENSSL_NO_DTLS
1523 meth = DTLS_server_method();
1524 socket_type = SOCK_DGRAM;
1528 #ifndef OPENSSL_NO_DTLS
1529 meth = DTLS_server_method();
1530 min_version = DTLS1_VERSION;
1531 max_version = DTLS1_VERSION;
1532 socket_type = SOCK_DGRAM;
1536 #ifndef OPENSSL_NO_DTLS
1537 meth = DTLS_server_method();
1538 min_version = DTLS1_2_VERSION;
1539 max_version = DTLS1_2_VERSION;
1540 socket_type = SOCK_DGRAM;
1544 #ifndef OPENSSL_NO_SCTP
1545 protocol = IPPROTO_SCTP;
1548 case OPT_SCTP_LABEL_BUG:
1549 #ifndef OPENSSL_NO_SCTP
1554 #ifndef OPENSSL_NO_DTLS
1555 enable_timeouts = 1;
1559 #ifndef OPENSSL_NO_DTLS
1560 socket_mtu = atol(opt_arg());
1564 #ifndef OPENSSL_NO_DTLS
1572 session_id_prefix = opt_arg();
1575 #ifndef OPENSSL_NO_ENGINE
1576 engine = setup_engine(opt_arg(), s_debug);
1583 case OPT_PROV_CASES:
1584 if (!opt_provider(o))
1587 case OPT_SERVERNAME:
1588 tlsextcbp.servername = opt_arg();
1590 case OPT_SERVERNAME_FATAL:
1591 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1594 s_cert_file2 = opt_arg();
1597 s_key_file2 = opt_arg();
1599 case OPT_NEXTPROTONEG:
1600 # ifndef OPENSSL_NO_NEXTPROTONEG
1601 next_proto_neg_in = opt_arg();
1605 alpn_in = opt_arg();
1607 case OPT_SRTP_PROFILES:
1608 #ifndef OPENSSL_NO_SRTP
1609 srtp_profiles = opt_arg();
1612 case OPT_KEYMATEXPORT:
1613 keymatexportlabel = opt_arg();
1615 case OPT_KEYMATEXPORTLEN:
1616 keymatexportlen = atoi(opt_arg());
1621 case OPT_MAX_SEND_FRAG:
1622 max_send_fragment = atoi(opt_arg());
1624 case OPT_SPLIT_SEND_FRAG:
1625 split_send_fragment = atoi(opt_arg());
1627 case OPT_MAX_PIPELINES:
1628 max_pipelines = atoi(opt_arg());
1631 read_buf_len = atoi(opt_arg());
1633 case OPT_KEYLOG_FILE:
1634 keylog_file = opt_arg();
1637 max_early_data = atoi(opt_arg());
1638 if (max_early_data < 0) {
1639 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1643 case OPT_RECV_MAX_EARLY:
1644 recv_max_early_data = atoi(opt_arg());
1645 if (recv_max_early_data < 0) {
1646 BIO_printf(bio_err, "Invalid value for recv_max_early_data\n");
1650 case OPT_EARLY_DATA:
1652 if (max_early_data == -1)
1653 max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
1655 case OPT_HTTP_SERVER_BINMODE:
1656 http_server_binmode = 1;
1662 #ifndef OPENSSL_NO_KTLS
1667 #ifndef OPENSSL_NO_KTLS
1671 case OPT_USE_ZC_SENDFILE:
1672 #ifndef OPENSSL_NO_KTLS
1673 use_zc_sendfile = 1;
1676 case OPT_IGNORE_UNEXPECTED_EOF:
1677 ignore_unexpected_eof = 1;
1685 case OPT_ENABLE_SERVER_RPK:
1686 enable_server_rpk = 1;
1688 case OPT_ENABLE_CLIENT_RPK:
1689 enable_client_rpk = 1;
1694 /* No extra arguments. */
1695 if (!opt_check_rest_arg(NULL))
1698 if (!app_RAND_load())
1701 #ifndef OPENSSL_NO_NEXTPROTONEG
1702 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1703 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1707 #ifndef OPENSSL_NO_DTLS
1708 if (www && socket_type == SOCK_DGRAM) {
1709 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1713 if (dtlslisten && socket_type != SOCK_DGRAM) {
1714 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1719 if (tfo && socket_type != SOCK_STREAM) {
1720 BIO_printf(bio_err, "Can only use -tfo with TLS\n");
1724 if (stateless && socket_type != SOCK_STREAM) {
1725 BIO_printf(bio_err, "Can only use --stateless with TLS\n");
1730 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1732 "Can't use unix sockets and datagrams together\n");
1736 if (early_data && (www > 0 || rev)) {
1738 "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n");
1742 #ifndef OPENSSL_NO_SCTP
1743 if (protocol == IPPROTO_SCTP) {
1744 if (socket_type != SOCK_DGRAM) {
1745 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1748 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1749 socket_type = SOCK_STREAM;
1753 #ifndef OPENSSL_NO_KTLS
1754 if (use_zc_sendfile && !use_sendfile) {
1755 BIO_printf(bio_out, "Warning: -zerocopy_sendfile depends on -sendfile, enabling -sendfile now.\n");
1759 if (use_sendfile && enable_ktls == 0) {
1760 BIO_printf(bio_out, "Warning: -sendfile depends on -ktls, enabling -ktls now.\n");
1764 if (use_sendfile && www <= 1) {
1765 BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n");
1770 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1771 BIO_printf(bio_err, "Error getting password\n");
1775 if (s_key_file == NULL)
1776 s_key_file = s_cert_file;
1778 if (s_key_file2 == NULL)
1779 s_key_file2 = s_cert_file2;
1781 if (!load_excert(&exc))
1785 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1786 "server certificate private key");
1790 s_cert = load_cert_pass(s_cert_file, s_cert_format, 1, pass,
1791 "server certificate");
1795 if (s_chain_file != NULL) {
1796 if (!load_certs(s_chain_file, 0, &s_chain, NULL,
1797 "server certificate chain"))
1801 if (tlsextcbp.servername != NULL) {
1802 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1803 "second server certificate private key");
1807 s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, 1, pass,
1808 "second server certificate");
1810 if (s_cert2 == NULL)
1814 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1815 if (next_proto_neg_in) {
1816 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1817 if (next_proto.data == NULL)
1821 alpn_ctx.data = NULL;
1823 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1824 if (alpn_ctx.data == NULL)
1828 if (crl_file != NULL) {
1830 crl = load_crl(crl_file, crl_format, 0, "CRL");
1833 crls = sk_X509_CRL_new_null();
1834 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1835 BIO_puts(bio_err, "Error adding CRL\n");
1836 ERR_print_errors(bio_err);
1842 if (s_dcert_file != NULL) {
1844 if (s_dkey_file == NULL)
1845 s_dkey_file = s_dcert_file;
1847 s_dkey = load_key(s_dkey_file, s_dkey_format,
1848 0, dpass, engine, "second certificate private key");
1852 s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, 1, dpass,
1853 "second server certificate");
1855 if (s_dcert == NULL) {
1856 ERR_print_errors(bio_err);
1859 if (s_dchain_file != NULL) {
1860 if (!load_certs(s_dchain_file, 0, &s_dchain, NULL,
1861 "second server certificate chain"))
1867 if (bio_s_out == NULL) {
1868 if (s_quiet && !s_debug) {
1869 bio_s_out = BIO_new(BIO_s_null());
1870 if (s_msg && bio_s_msg == NULL) {
1871 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1872 if (bio_s_msg == NULL) {
1873 BIO_printf(bio_err, "Out of memory\n");
1878 bio_s_out = dup_bio_out(FORMAT_TEXT);
1882 if (bio_s_out == NULL)
1888 s_dcert_file = NULL;
1890 s_cert_file2 = NULL;
1894 ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1896 ERR_print_errors(bio_err);
1900 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1903 ssl_ctx_security_debug(ctx, sdebug);
1905 if (!config_ctx(cctx, ssl_args, ctx))
1909 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1910 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1912 ERR_print_errors(bio_err);
1916 #ifndef OPENSSL_NO_SCTP
1917 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1918 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1921 if (min_version != 0
1922 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1924 if (max_version != 0
1925 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1928 if (session_id_prefix) {
1929 if (strlen(session_id_prefix) >= 32)
1931 "warning: id_prefix is too long, only one new session will be possible\n");
1932 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1933 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1934 ERR_print_errors(bio_err);
1937 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1940 ssl_ctx_set_excert(ctx, exc);
1943 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1945 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1947 init_session_cache_ctx(ctx);
1949 SSL_CTX_sess_set_cache_size(ctx, 128);
1952 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1956 SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
1959 if (ignore_unexpected_eof)
1960 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1961 #ifndef OPENSSL_NO_KTLS
1963 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
1964 if (use_zc_sendfile)
1965 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE);
1968 if (max_send_fragment > 0
1969 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1970 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1971 prog, max_send_fragment);
1975 if (split_send_fragment > 0
1976 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1977 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1978 prog, split_send_fragment);
1981 if (max_pipelines > 0
1982 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1983 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1984 prog, max_pipelines);
1988 if (read_buf_len > 0) {
1989 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1991 #ifndef OPENSSL_NO_SRTP
1992 if (srtp_profiles != NULL) {
1993 /* Returns 0 on success! */
1994 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1995 BIO_printf(bio_err, "Error setting SRTP profile\n");
1996 ERR_print_errors(bio_err);
2002 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
2003 CAstore, noCAstore)) {
2004 ERR_print_errors(bio_err);
2007 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
2008 BIO_printf(bio_err, "Error setting verify params\n");
2009 ERR_print_errors(bio_err);
2013 ssl_ctx_add_crls(ctx, crls, 0);
2015 if (!ssl_load_stores(ctx,
2016 vfyCApath, vfyCAfile, vfyCAstore,
2017 chCApath, chCAfile, chCAstore,
2018 crls, crl_download)) {
2019 BIO_printf(bio_err, "Error loading store locations\n");
2020 ERR_print_errors(bio_err);
2025 ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
2027 ERR_print_errors(bio_err);
2033 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
2036 ssl_ctx_security_debug(ctx2, sdebug);
2038 if (session_id_prefix) {
2039 if (strlen(session_id_prefix) >= 32)
2041 "warning: id_prefix is too long, only one new session will be possible\n");
2042 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
2043 BIO_printf(bio_err, "error setting 'id_prefix'\n");
2044 ERR_print_errors(bio_err);
2047 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
2050 ssl_ctx_set_excert(ctx2, exc);
2053 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
2056 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
2058 init_session_cache_ctx(ctx2);
2060 SSL_CTX_sess_set_cache_size(ctx2, 128);
2063 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
2065 if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath,
2066 noCApath, CAstore, noCAstore)) {
2067 ERR_print_errors(bio_err);
2070 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
2071 BIO_printf(bio_err, "Error setting verify params\n");
2072 ERR_print_errors(bio_err);
2076 ssl_ctx_add_crls(ctx2, crls, 0);
2077 if (!config_ctx(cctx, ssl_args, ctx2))
2080 #ifndef OPENSSL_NO_NEXTPROTONEG
2081 if (next_proto.data)
2082 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
2086 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
2089 EVP_PKEY *dhpkey = NULL;
2092 dhpkey = load_keyparams(dhfile, FORMAT_UNDEF, 0, "DH", "DH parameters");
2093 else if (s_cert_file != NULL)
2094 dhpkey = load_keyparams_suppress(s_cert_file, FORMAT_UNDEF, 0, "DH",
2095 "DH parameters", 1);
2097 if (dhpkey != NULL) {
2098 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2100 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
2102 (void)BIO_flush(bio_s_out);
2104 if (dhpkey == NULL) {
2105 SSL_CTX_set_dh_auto(ctx, 1);
2108 * We need 2 references: one for use by ctx and one for use by
2111 if (!EVP_PKEY_up_ref(dhpkey)) {
2112 EVP_PKEY_free(dhpkey);
2115 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) {
2116 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2117 ERR_print_errors(bio_err);
2118 /* Free 2 references */
2119 EVP_PKEY_free(dhpkey);
2120 EVP_PKEY_free(dhpkey);
2126 if (dhfile != NULL) {
2127 EVP_PKEY *dhpkey2 = load_keyparams_suppress(s_cert_file2,
2130 "DH parameters", 1);
2132 if (dhpkey2 != NULL) {
2133 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2134 (void)BIO_flush(bio_s_out);
2136 EVP_PKEY_free(dhpkey);
2140 if (dhpkey == NULL) {
2141 SSL_CTX_set_dh_auto(ctx2, 1);
2142 } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) {
2143 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2144 ERR_print_errors(bio_err);
2145 EVP_PKEY_free(dhpkey);
2150 EVP_PKEY_free(dhpkey);
2153 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
2156 if (s_serverinfo_file != NULL
2157 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
2158 ERR_print_errors(bio_err);
2163 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
2166 if (s_dcert != NULL) {
2167 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
2171 if (no_resume_ephemeral) {
2172 SSL_CTX_set_not_resumable_session_callback(ctx,
2173 not_resumable_sess_cb);
2176 SSL_CTX_set_not_resumable_session_callback(ctx2,
2177 not_resumable_sess_cb);
2179 #ifndef OPENSSL_NO_PSK
2180 if (psk_key != NULL) {
2182 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
2183 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
2186 if (psk_identity_hint != NULL) {
2187 if (min_version == TLS1_3_VERSION) {
2188 BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n");
2190 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
2191 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
2192 ERR_print_errors(bio_err);
2198 if (psksessf != NULL) {
2199 BIO *stmp = BIO_new_file(psksessf, "r");
2202 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
2203 ERR_print_errors(bio_err);
2206 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2208 if (psksess == NULL) {
2209 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
2210 ERR_print_errors(bio_err);
2216 if (psk_key != NULL || psksess != NULL)
2217 SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb);
2219 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
2220 if (!SSL_CTX_set_session_id_context(ctx,
2221 (void *)&s_server_session_id_context,
2222 sizeof(s_server_session_id_context))) {
2223 BIO_printf(bio_err, "error setting session id context\n");
2224 ERR_print_errors(bio_err);
2228 /* Set DTLS cookie generation and verification callbacks */
2229 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
2230 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
2232 /* Set TLS1.3 cookie generation and verification callbacks */
2233 SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback);
2234 SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback);
2237 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
2238 if (!SSL_CTX_set_session_id_context(ctx2,
2239 (void *)&s_server_session_id_context,
2240 sizeof(s_server_session_id_context))) {
2241 BIO_printf(bio_err, "error setting session id context\n");
2242 ERR_print_errors(bio_err);
2245 tlsextcbp.biodebug = bio_s_out;
2246 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
2247 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
2248 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2249 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2252 #ifndef OPENSSL_NO_SRP
2253 if (srp_verifier_file != NULL) {
2254 if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed,
2259 if (CAfile != NULL) {
2260 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2263 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2265 #ifndef OPENSSL_NO_OCSP
2266 if (s_tlsextstatus) {
2267 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2268 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2270 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2271 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2275 if (set_keylog_file(ctx, keylog_file))
2278 if (max_early_data >= 0)
2279 SSL_CTX_set_max_early_data(ctx, max_early_data);
2280 if (recv_max_early_data >= 0)
2281 SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data);
2284 BIO_printf(bio_s_out, "Compressing certificates\n");
2285 if (!SSL_CTX_compress_certs(ctx, 0))
2286 BIO_printf(bio_s_out, "Error compressing certs on ctx\n");
2287 if (ctx2 != NULL && !SSL_CTX_compress_certs(ctx2, 0))
2288 BIO_printf(bio_s_out, "Error compressing certs on ctx2\n");
2290 if (enable_server_rpk)
2291 if (!SSL_CTX_set1_server_cert_type(ctx, cert_type_rpk, sizeof(cert_type_rpk))) {
2292 BIO_printf(bio_s_out, "Error setting server certificate types\n");
2295 if (enable_client_rpk)
2296 if (!SSL_CTX_set1_client_cert_type(ctx, cert_type_rpk, sizeof(cert_type_rpk))) {
2297 BIO_printf(bio_s_out, "Error setting server certificate types\n");
2302 server_cb = rev_body;
2304 server_cb = www_body;
2306 server_cb = sv_body;
2308 if (socket_family == AF_UNIX
2309 && unlink_unix_path)
2313 BIO_printf(bio_s_out, "Listening for TFO\n");
2314 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2315 server_cb, context, naccept, bio_s_out, tfo);
2316 print_stats(bio_s_out, ctx);
2320 SSL_SESSION_free(psksess);
2321 set_keylog_file(NULL, NULL);
2323 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2325 EVP_PKEY_free(s_key);
2326 EVP_PKEY_free(s_dkey);
2327 OSSL_STACK_OF_X509_free(s_chain);
2328 OSSL_STACK_OF_X509_free(s_dchain);
2330 OPENSSL_free(dpass);
2333 X509_VERIFY_PARAM_free(vpm);
2335 OPENSSL_free(tlscstatp.host);
2336 OPENSSL_free(tlscstatp.port);
2337 OPENSSL_free(tlscstatp.path);
2340 EVP_PKEY_free(s_key2);
2341 #ifndef OPENSSL_NO_NEXTPROTONEG
2342 OPENSSL_free(next_proto.data);
2344 OPENSSL_free(alpn_ctx.data);
2345 ssl_excert_free(exc);
2346 sk_OPENSSL_STRING_free(ssl_args);
2347 SSL_CONF_CTX_free(cctx);
2348 release_engine(engine);
2349 BIO_free(bio_s_out);
2351 BIO_free(bio_s_msg);
2353 #ifdef CHARSET_EBCDIC
2354 BIO_meth_free(methods_ebcdic);
2359 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2361 BIO_printf(bio, "%4ld items in the session cache\n",
2362 SSL_CTX_sess_number(ssl_ctx));
2363 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2364 SSL_CTX_sess_connect(ssl_ctx));
2365 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2366 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2367 BIO_printf(bio, "%4ld client connects that finished\n",
2368 SSL_CTX_sess_connect_good(ssl_ctx));
2369 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2370 SSL_CTX_sess_accept(ssl_ctx));
2371 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2372 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2373 BIO_printf(bio, "%4ld server accepts that finished\n",
2374 SSL_CTX_sess_accept_good(ssl_ctx));
2375 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2376 BIO_printf(bio, "%4ld session cache misses\n",
2377 SSL_CTX_sess_misses(ssl_ctx));
2378 BIO_printf(bio, "%4ld session cache timeouts\n",
2379 SSL_CTX_sess_timeouts(ssl_ctx));
2380 BIO_printf(bio, "%4ld callback cache hits\n",
2381 SSL_CTX_sess_cb_hits(ssl_ctx));
2382 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2383 SSL_CTX_sess_cache_full(ssl_ctx),
2384 SSL_CTX_sess_get_cache_size(ssl_ctx));
2387 static long int count_reads_callback(BIO *bio, int cmd, const char *argp, size_t len,
2388 int argi, long argl, int ret, size_t *processed)
2390 unsigned int *p_counter = (unsigned int *)BIO_get_callback_arg(bio);
2393 case BIO_CB_READ: /* No break here */
2395 if (p_counter != NULL)
2403 BIO_set_callback_arg(bio, (char *)bio_s_out);
2404 ret = (int)bio_dump_callback(bio, cmd, argp, len, argi, argl, ret, processed);
2405 BIO_set_callback_arg(bio, (char *)p_counter);
2411 static int sv_body(int s, int stype, int prot, unsigned char *context)
2420 struct timeval timeout;
2421 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
2422 struct timeval *timeoutp;
2424 #ifndef OPENSSL_NO_DTLS
2425 # ifndef OPENSSL_NO_SCTP
2426 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2428 int isdtls = (stype == SOCK_DGRAM);
2432 buf = app_malloc(bufsize, "server buffer");
2434 if (!BIO_socket_nbio(s, 1))
2435 ERR_print_errors(bio_err);
2437 BIO_printf(bio_err, "Turned on non blocking io\n");
2446 if (s_tlsextdebug) {
2447 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2448 SSL_set_tlsext_debug_arg(con, bio_s_out);
2452 && !SSL_set_session_id_context(con, context,
2453 strlen((char *)context))) {
2454 BIO_printf(bio_err, "Error setting session id context\n");
2459 if (!SSL_clear(con)) {
2460 BIO_printf(bio_err, "Error clearing SSL connection\n");
2464 #ifndef OPENSSL_NO_DTLS
2466 # ifndef OPENSSL_NO_SCTP
2467 if (prot == IPPROTO_SCTP)
2468 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2471 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2473 BIO_printf(bio_err, "Unable to create BIO\n");
2474 ERR_print_errors(bio_err);
2478 if (enable_timeouts) {
2480 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2481 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2484 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2485 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2489 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2490 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2491 DTLS_get_link_min_mtu(con));
2496 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2497 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2498 BIO_printf(bio_err, "Failed to set MTU\n");
2504 /* want to do MTU discovery */
2505 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2507 # ifndef OPENSSL_NO_SCTP
2508 if (prot != IPPROTO_SCTP)
2510 /* Turn on cookie exchange. Not necessary for SCTP */
2511 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2514 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2517 BIO_printf(bio_err, "Unable to create BIO\n");
2518 ERR_print_errors(bio_err);
2525 test = BIO_new(BIO_f_nbio_test());
2527 BIO_printf(bio_err, "Unable to create BIO\n");
2532 sbio = BIO_push(test, sbio);
2535 SSL_set_bio(con, sbio, sbio);
2536 SSL_set_accept_state(con);
2537 /* SSL_set_fd(con,s); */
2539 BIO_set_callback_ex(SSL_get_rbio(con), count_reads_callback);
2541 #ifndef OPENSSL_NO_SSL_TRACE
2543 SSL_set_msg_callback(con, SSL_trace);
2546 SSL_set_msg_callback(con, msg_cb);
2547 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2550 if (s_tlsextdebug) {
2551 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2552 SSL_set_tlsext_debug_arg(con, bio_s_out);
2556 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2559 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2561 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2562 if (edret != SSL_READ_EARLY_DATA_ERROR)
2565 switch (SSL_get_error(con, 0)) {
2566 case SSL_ERROR_WANT_WRITE:
2567 case SSL_ERROR_WANT_ASYNC:
2568 case SSL_ERROR_WANT_READ:
2569 /* Just keep trying - busy waiting */
2572 BIO_printf(bio_err, "Error reading early data\n");
2573 ERR_print_errors(bio_err);
2577 if (readbytes > 0) {
2579 BIO_printf(bio_s_out, "Early data received:\n");
2582 raw_write_stdout(buf, (unsigned int)readbytes);
2583 (void)BIO_flush(bio_s_out);
2587 if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT)
2588 BIO_printf(bio_s_out, "No early data received\n");
2590 BIO_printf(bio_s_out, "Early data was rejected\n");
2592 BIO_printf(bio_s_out, "\nEnd of early data\n");
2594 if (SSL_is_init_finished(con))
2595 print_connection_info(con);
2598 if (fileno_stdin() > s)
2599 width = fileno_stdin() + 1;
2604 int read_from_terminal;
2605 int read_from_sslcon;
2607 read_from_terminal = 0;
2608 read_from_sslcon = SSL_has_pending(con)
2609 || (async && SSL_waiting_for_async(con));
2611 if (!read_from_sslcon) {
2613 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2614 openssl_fdset(fileno_stdin(), &readfds);
2616 openssl_fdset(s, &readfds);
2618 * Note: under VMS with SOCKETSHR the second parameter is
2619 * currently of type (int *) whereas under other systems it is
2620 * (void *) if you don't have a cast it will choke the compiler:
2621 * if you do have a cast then you can either go for (int *) or
2624 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2626 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2627 * only on sockets. As a workaround we timeout the select every
2628 * second and check for any keypress. In a proper Windows
2629 * application we wouldn't do this because it is inefficient.
2632 timeout.tv_usec = 0;
2633 i = select(width, (void *)&readfds, NULL, NULL, &timeout);
2634 if (has_stdin_waiting())
2635 read_from_terminal = 1;
2636 if ((i < 0) || (!i && !read_from_terminal))
2639 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2640 timeoutp = &timeout;
2644 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2646 if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
2647 BIO_printf(bio_err, "TIMEOUT occurred\n");
2651 if (FD_ISSET(fileno_stdin(), &readfds))
2652 read_from_terminal = 1;
2654 if (FD_ISSET(s, &readfds))
2655 read_from_sslcon = 1;
2657 if (read_from_terminal) {
2661 i = raw_read_stdin(buf, bufsize / 2);
2663 /* both loops are skipped when i <= 0 */
2664 for (j = 0; j < i; j++)
2667 for (j = i - 1; j >= 0; j--) {
2668 buf[j + lf_num] = buf[j];
2669 if (buf[j] == '\n') {
2672 buf[j + lf_num] = '\r';
2675 assert(lf_num == 0);
2677 i = raw_read_stdin(buf, bufsize);
2680 if (!s_quiet && !s_brief) {
2681 if ((i <= 0) || (buf[0] == 'Q')) {
2682 BIO_printf(bio_s_out, "DONE\n");
2683 (void)BIO_flush(bio_s_out);
2685 close_accept_socket();
2689 if ((i <= 0) || (buf[0] == 'q')) {
2690 BIO_printf(bio_s_out, "DONE\n");
2691 (void)BIO_flush(bio_s_out);
2692 if (SSL_version(con) != DTLS1_VERSION)
2695 * close_accept_socket(); ret= -11;
2699 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2700 SSL_renegotiate(con);
2701 i = SSL_do_handshake(con);
2702 printf("SSL_do_handshake -> %d\n", i);
2705 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2707 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2709 SSL_renegotiate(con);
2710 i = SSL_do_handshake(con);
2711 printf("SSL_do_handshake -> %d\n", i);
2714 if ((buf[0] == 'K' || buf[0] == 'k')
2715 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2716 SSL_key_update(con, buf[0] == 'K' ?
2717 SSL_KEY_UPDATE_REQUESTED
2718 : SSL_KEY_UPDATE_NOT_REQUESTED);
2719 i = SSL_do_handshake(con);
2720 printf("SSL_do_handshake -> %d\n", i);
2723 if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2724 SSL_set_verify(con, SSL_VERIFY_PEER, NULL);
2725 i = SSL_verify_client_post_handshake(con);
2727 printf("Failed to initiate request\n");
2728 ERR_print_errors(bio_err);
2730 i = SSL_do_handshake(con);
2731 printf("SSL_do_handshake -> %d\n", i);
2735 if (buf[0] == 'P') {
2736 static const char str[] = "Lets print some clear text\n";
2737 BIO_write(SSL_get_wbio(con), str, sizeof(str) -1);
2739 if (buf[0] == 'S') {
2740 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2743 #ifdef CHARSET_EBCDIC
2744 ebcdic2ascii(buf, buf, i);
2748 /* should do a select for the write */
2751 if (++count == 100) {
2753 SSL_renegotiate(con);
2756 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2757 #ifndef OPENSSL_NO_SRP
2758 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2759 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2761 lookup_srp_user(&srp_callback_parm, bio_s_out);
2763 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2766 switch (SSL_get_error(con, k)) {
2767 case SSL_ERROR_NONE:
2769 case SSL_ERROR_WANT_ASYNC:
2770 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2771 (void)BIO_flush(bio_s_out);
2772 wait_for_async(con);
2774 case SSL_ERROR_WANT_WRITE:
2775 case SSL_ERROR_WANT_READ:
2776 case SSL_ERROR_WANT_X509_LOOKUP:
2777 BIO_printf(bio_s_out, "Write BLOCK\n");
2778 (void)BIO_flush(bio_s_out);
2780 case SSL_ERROR_WANT_ASYNC_JOB:
2782 * This shouldn't ever happen in s_server. Treat as an error
2784 case SSL_ERROR_SYSCALL:
2786 BIO_printf(bio_s_out, "ERROR\n");
2787 (void)BIO_flush(bio_s_out);
2788 ERR_print_errors(bio_err);
2792 case SSL_ERROR_ZERO_RETURN:
2793 BIO_printf(bio_s_out, "DONE\n");
2794 (void)BIO_flush(bio_s_out);
2806 if (read_from_sslcon) {
2808 * init_ssl_connection handles all async events itself so if we're
2809 * waiting for async then we shouldn't go back into
2810 * init_ssl_connection
2812 if ((!async || !SSL_waiting_for_async(con))
2813 && !SSL_is_init_finished(con)) {
2815 * Count number of reads during init_ssl_connection.
2816 * It helps us to distinguish configuration errors from errors
2817 * caused by a client.
2819 unsigned int read_counter = 0;
2821 BIO_set_callback_arg(SSL_get_rbio(con), (char *)&read_counter);
2822 i = init_ssl_connection(con);
2823 BIO_set_callback_arg(SSL_get_rbio(con), NULL);
2826 * If initialization fails without reads, then
2827 * there was a fatal error in configuration.
2829 if (i <= 0 && read_counter == 0) {
2836 } else if (i == 0) {
2842 i = SSL_read(con, (char *)buf, bufsize);
2843 #ifndef OPENSSL_NO_SRP
2844 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2845 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2847 lookup_srp_user(&srp_callback_parm, bio_s_out);
2849 i = SSL_read(con, (char *)buf, bufsize);
2852 switch (SSL_get_error(con, i)) {
2853 case SSL_ERROR_NONE:
2854 #ifdef CHARSET_EBCDIC
2855 ascii2ebcdic(buf, buf, i);
2857 raw_write_stdout(buf, (unsigned int)i);
2858 (void)BIO_flush(bio_s_out);
2859 if (SSL_has_pending(con))
2862 case SSL_ERROR_WANT_ASYNC:
2863 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2864 (void)BIO_flush(bio_s_out);
2865 wait_for_async(con);
2867 case SSL_ERROR_WANT_WRITE:
2868 case SSL_ERROR_WANT_READ:
2869 BIO_printf(bio_s_out, "Read BLOCK\n");
2870 (void)BIO_flush(bio_s_out);
2872 case SSL_ERROR_WANT_ASYNC_JOB:
2874 * This shouldn't ever happen in s_server. Treat as an error
2876 case SSL_ERROR_SYSCALL:
2878 BIO_printf(bio_s_out, "ERROR\n");
2879 (void)BIO_flush(bio_s_out);
2880 ERR_print_errors(bio_err);
2883 case SSL_ERROR_ZERO_RETURN:
2884 BIO_printf(bio_s_out, "DONE\n");
2885 (void)BIO_flush(bio_s_out);
2894 BIO_printf(bio_s_out, "shutting down SSL\n");
2895 do_ssl_shutdown(con);
2898 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2899 OPENSSL_clear_free(buf, bufsize);
2903 static void close_accept_socket(void)
2905 BIO_printf(bio_err, "shutdown accept socket\n");
2906 if (accept_socket >= 0) {
2907 BIO_closesocket(accept_socket);
2911 static int is_retryable(SSL *con, int i)
2913 int err = SSL_get_error(con, i);
2915 /* If it's not a fatal error, it must be retryable */
2916 return (err != SSL_ERROR_SSL)
2917 && (err != SSL_ERROR_SYSCALL)
2918 && (err != SSL_ERROR_ZERO_RETURN);
2921 static int init_ssl_connection(SSL *con)
2927 if (dtlslisten || stateless) {
2928 BIO_ADDR *client = NULL;
2931 if ((client = BIO_ADDR_new()) == NULL) {
2932 BIO_printf(bio_err, "ERROR - memory\n");
2935 i = DTLSv1_listen(con, client);
2937 i = SSL_stateless(con);
2944 wbio = SSL_get_wbio(con);
2946 BIO_get_fd(wbio, &fd);
2949 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2950 BIO_printf(bio_err, "ERROR - unable to connect\n");
2951 BIO_ADDR_free(client);
2955 (void)BIO_ctrl_set_connected(wbio, client);
2956 BIO_ADDR_free(client);
2961 i = SSL_accept(con);
2963 BIO_ADDR_free(client);
2967 i = SSL_accept(con);
2970 retry = is_retryable(con, i);
2971 #ifdef CERT_CB_TEST_RETRY
2974 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2975 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2977 "LOOKUP from certificate callback during accept\n");
2978 i = SSL_accept(con);
2980 retry = is_retryable(con, i);
2985 #ifndef OPENSSL_NO_SRP
2987 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2988 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2989 srp_callback_parm.login);
2991 lookup_srp_user(&srp_callback_parm, bio_s_out);
2993 i = SSL_accept(con);
2995 retry = is_retryable(con, i);
2998 } while (i < 0 && SSL_waiting_for_async(con));
3002 if (((dtlslisten || stateless) && i == 0)
3003 || (!dtlslisten && !stateless && retry)) {
3004 BIO_printf(bio_s_out, "DELAY\n");
3008 BIO_printf(bio_err, "ERROR\n");
3010 verify_err = SSL_get_verify_result(con);
3011 if (verify_err != X509_V_OK) {
3012 BIO_printf(bio_err, "verify error:%s\n",
3013 X509_verify_cert_error_string(verify_err));
3015 /* Always print any error messages */
3016 ERR_print_errors(bio_err);
3020 print_connection_info(con);
3024 static void print_connection_info(SSL *con)
3029 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3030 const unsigned char *next_proto_neg;
3031 unsigned next_proto_neg_len;
3033 unsigned char *exportedkeymat;
3037 print_ssl_summary(con);
3039 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
3041 peer = SSL_get0_peer_certificate(con);
3043 BIO_printf(bio_s_out, "Client certificate\n");
3044 PEM_write_bio_X509(bio_s_out, peer);
3045 dump_cert_text(bio_s_out, peer);
3048 /* Only display RPK information if configured */
3049 if (SSL_get_negotiated_server_cert_type(con) == TLSEXT_cert_type_rpk)
3050 BIO_printf(bio_s_out, "Server-to-client raw public key negotiated\n");
3051 if (SSL_get_negotiated_client_cert_type(con) == TLSEXT_cert_type_rpk)
3052 BIO_printf(bio_s_out, "Client-to-server raw public key negotiated\n");
3053 if (enable_client_rpk) {
3054 EVP_PKEY *client_rpk = SSL_get0_peer_rpk(con);
3056 if (client_rpk != NULL) {
3057 BIO_printf(bio_s_out, "Client raw public key\n");
3058 EVP_PKEY_print_public(bio_s_out, client_rpk, 2, NULL);
3062 if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
3063 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
3064 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
3065 ssl_print_sigalgs(bio_s_out, con);
3066 #ifndef OPENSSL_NO_EC
3067 ssl_print_point_formats(bio_s_out, con);
3068 ssl_print_groups(bio_s_out, con, 0);
3070 print_ca_names(bio_s_out, con);
3071 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
3073 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3074 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
3075 if (next_proto_neg) {
3076 BIO_printf(bio_s_out, "NEXTPROTO is ");
3077 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
3078 BIO_printf(bio_s_out, "\n");
3081 #ifndef OPENSSL_NO_SRTP
3083 SRTP_PROTECTION_PROFILE *srtp_profile
3084 = SSL_get_selected_srtp_profile(con);
3087 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
3088 srtp_profile->name);
3091 if (SSL_session_reused(con))
3092 BIO_printf(bio_s_out, "Reused session-id\n");
3094 ssl_print_secure_renegotiation_notes(bio_s_out, con);
3096 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
3097 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
3099 if (keymatexportlabel != NULL) {
3100 BIO_printf(bio_s_out, "Keying material exporter:\n");
3101 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
3102 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
3103 exportedkeymat = app_malloc(keymatexportlen, "export key");
3104 if (SSL_export_keying_material(con, exportedkeymat,
3107 strlen(keymatexportlabel),
3109 BIO_printf(bio_s_out, " Error\n");
3111 BIO_printf(bio_s_out, " Keying material: ");
3112 for (i = 0; i < keymatexportlen; i++)
3113 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
3114 BIO_printf(bio_s_out, "\n");
3116 OPENSSL_free(exportedkeymat);
3118 #ifndef OPENSSL_NO_KTLS
3119 if (BIO_get_ktls_send(SSL_get_wbio(con)))
3120 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3121 if (BIO_get_ktls_recv(SSL_get_rbio(con)))
3122 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3125 (void)BIO_flush(bio_s_out);
3128 static int www_body(int s, int stype, int prot, unsigned char *context)
3130 char *buf = NULL, *p;
3134 const SSL_CIPHER *c;
3135 BIO *io, *ssl_bio, *sbio;
3137 int total_bytes = 0;
3140 #ifndef OPENSSL_NO_KTLS
3141 int use_sendfile_for_req = use_sendfile;
3145 #ifdef CHARSET_EBCDIC
3149 /* Set width for a select call if needed */
3152 /* as we use BIO_gets(), and it always null terminates data, we need
3153 * to allocate 1 byte longer buffer to fit the full 2^14 byte record */
3154 p = buf = app_malloc(bufsize + 1, "server www buffer");
3155 io = BIO_new(BIO_f_buffer());
3156 ssl_bio = BIO_new(BIO_f_ssl());
3157 if ((io == NULL) || (ssl_bio == NULL))
3161 if (!BIO_socket_nbio(s, 1))
3162 ERR_print_errors(bio_err);
3164 BIO_printf(bio_err, "Turned on non blocking io\n");
3167 /* lets make the output buffer a reasonable size */
3168 if (BIO_set_write_buffer_size(io, bufsize) <= 0)
3171 if ((con = SSL_new(ctx)) == NULL)
3174 if (s_tlsextdebug) {
3175 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3176 SSL_set_tlsext_debug_arg(con, bio_s_out);
3180 && !SSL_set_session_id_context(con, context,
3181 strlen((char *)context))) {
3186 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3195 test = BIO_new(BIO_f_nbio_test());
3202 sbio = BIO_push(test, sbio);
3204 SSL_set_bio(con, sbio, sbio);
3205 SSL_set_accept_state(con);
3207 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3208 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3209 BIO_push(io, ssl_bio);
3211 #ifdef CHARSET_EBCDIC
3212 filter = BIO_new(BIO_f_ebcdic_filter());
3216 io = BIO_push(filter, io);
3220 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3221 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3224 #ifndef OPENSSL_NO_SSL_TRACE
3226 SSL_set_msg_callback(con, SSL_trace);
3229 SSL_set_msg_callback(con, msg_cb);
3230 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3234 i = BIO_gets(io, buf, bufsize + 1);
3235 if (i < 0) { /* error */
3236 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
3238 ERR_print_errors(bio_err);
3241 BIO_printf(bio_s_out, "read R BLOCK\n");
3242 #ifndef OPENSSL_NO_SRP
3243 if (BIO_should_io_special(io)
3244 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3245 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3247 lookup_srp_user(&srp_callback_parm, bio_s_out);
3255 } else if (i == 0) { /* end of input */
3260 /* else we have data */
3261 if ((www == 1 && HAS_PREFIX(buf, "GET "))
3262 || (www == 2 && HAS_PREFIX(buf, "GET /stats "))) {
3264 STACK_OF(SSL_CIPHER) *sk;
3265 static const char *space = " ";
3267 if (www == 1 && HAS_PREFIX(buf, "GET /reneg")) {
3268 if (HAS_PREFIX(buf, "GET /renegcert"))
3270 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
3272 i = SSL_renegotiate(con);
3273 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
3274 /* Send the HelloRequest */
3275 i = SSL_do_handshake(con);
3277 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
3278 SSL_get_error(con, i));
3279 ERR_print_errors(bio_err);
3282 /* Wait for a ClientHello to come back */
3284 openssl_fdset(s, &readfds);
3285 i = select(width, (void *)&readfds, NULL, NULL, NULL);
3286 if (i <= 0 || !FD_ISSET(s, &readfds)) {
3287 BIO_printf(bio_s_out,
3288 "Error waiting for client response\n");
3289 ERR_print_errors(bio_err);
3293 * We're not actually expecting any data here and we ignore
3294 * any that is sent. This is just to force the handshake that
3295 * we're expecting to come from the client. If they haven't
3296 * sent one there's not much we can do.
3298 BIO_gets(io, buf, bufsize + 1);
3302 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3303 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
3304 BIO_puts(io, "<pre>\n");
3305 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
3307 for (i = 0; i < local_argc; i++) {
3310 for (myp = local_argv[i]; *myp; myp++)
3313 BIO_puts(io, "<");
3316 BIO_puts(io, ">");
3319 BIO_puts(io, "&");
3322 BIO_write(io, myp, 1);
3325 BIO_write(io, " ", 1);
3329 ssl_print_secure_renegotiation_notes(io, con);
3332 * The following is evil and should not really be done
3334 BIO_printf(io, "Ciphers supported in s_server binary\n");
3335 sk = SSL_get_ciphers(con);
3336 j = sk_SSL_CIPHER_num(sk);
3337 for (i = 0; i < j; i++) {
3338 c = sk_SSL_CIPHER_value(sk, i);
3339 BIO_printf(io, "%-11s:%-25s ",
3340 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3341 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3345 p = SSL_get_shared_ciphers(con, buf, bufsize);
3348 "---\nCiphers common between both SSL end points:\n");
3352 BIO_write(io, space, 26 - j);
3355 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3357 BIO_write(io, p, 1);
3364 ssl_print_sigalgs(io, con);
3365 #ifndef OPENSSL_NO_EC
3366 ssl_print_groups(io, con, 0);
3368 print_ca_names(io, con);
3369 BIO_printf(io, (SSL_session_reused(con)
3370 ? "---\nReused, " : "---\nNew, "));
3371 c = SSL_get_current_cipher(con);
3372 BIO_printf(io, "%s, Cipher is %s\n",
3373 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3374 SSL_SESSION_print(io, SSL_get_session(con));
3375 BIO_printf(io, "---\n");
3376 print_stats(io, SSL_get_SSL_CTX(con));
3377 BIO_printf(io, "---\n");
3378 peer = SSL_get0_peer_certificate(con);
3380 BIO_printf(io, "Client certificate\n");
3381 X509_print(io, peer);
3382 PEM_write_bio_X509(io, peer);
3385 BIO_puts(io, "no client certificate available\n");
3387 BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
3389 } else if ((www == 2 || www == 3) && CHECK_AND_SKIP_PREFIX(p, "GET /")) {
3392 static const char *text =
3393 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3396 for (e = p; *e != '\0'; e++) {
3401 /* Windows drive. We treat this the same way as ".." */
3408 dot = (e[0] == '.') ? 2 : 0;
3411 dot = (e[0] == '.') ? 3 : 0;
3414 dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0;
3418 dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0;
3420 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3425 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3432 BIO_printf(io, "'%s' contains '..' or ':'\r\n", p);
3436 if (*p == '/' || *p == '\\') {
3438 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3442 /* if a directory, do the index thang */
3443 if (app_isdir(p) > 0) {
3445 BIO_printf(io, "'%s' is a directory\r\n", p);
3449 opmode = (http_server_binmode == 1) ? "rb" : "r";
3450 if ((file = BIO_new_file(p, opmode)) == NULL) {
3452 BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode);
3453 ERR_print_errors(io);
3458 BIO_printf(bio_err, "FILE:%s\n", p);
3462 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3463 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3464 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3466 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3469 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3472 #ifndef OPENSSL_NO_KTLS
3473 if (use_sendfile_for_req && !BIO_get_ktls_send(SSL_get_wbio(con))) {
3474 BIO_printf(bio_err, "Warning: sendfile requested but KTLS is not available\n");
3475 use_sendfile_for_req = 0;
3477 if (use_sendfile_for_req) {
3484 BIO_get_fp(file, &fp);
3486 if (fstat(fd, &st) < 0) {
3487 BIO_printf(io, "Error fstat '%s'\r\n", p);
3488 ERR_print_errors(io);
3492 filesize = st.st_size;
3493 if (((int)BIO_flush(io)) < 0)
3497 i = SSL_sendfile(con, fd, offset, filesize, 0);
3499 BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p);
3500 ERR_print_errors(io);
3507 if (filesize <= 0) {
3509 BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p);
3518 i = BIO_read(file, buf, bufsize);
3524 BIO_printf(bio_err, "%d\n", i);
3525 if (total_bytes > 3 * 1024) {
3527 BIO_printf(bio_err, "RENEGOTIATE\n");
3528 SSL_renegotiate(con);
3532 for (j = 0; j < i;) {
3536 SSL_renegotiate(con);
3538 k = BIO_write(io, &(buf[j]), i - j);
3540 if (!BIO_should_retry(io)
3541 && !SSL_waiting_for_async(con)) {
3544 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3559 i = (int)BIO_flush(io);
3561 if (!BIO_should_retry(io))
3567 /* make sure we reuse sessions */
3568 do_ssl_shutdown(con);
3577 static int rev_body(int s, int stype, int prot, unsigned char *context)
3583 BIO *io, *ssl_bio, *sbio;
3584 #ifdef CHARSET_EBCDIC
3588 /* as we use BIO_gets(), and it always null terminates data, we need
3589 * to allocate 1 byte longer buffer to fit the full 2^14 byte record */
3590 buf = app_malloc(bufsize + 1, "server rev buffer");
3591 io = BIO_new(BIO_f_buffer());
3592 ssl_bio = BIO_new(BIO_f_ssl());
3593 if ((io == NULL) || (ssl_bio == NULL))
3596 /* lets make the output buffer a reasonable size */
3597 if (BIO_set_write_buffer_size(io, bufsize) <= 0)
3600 if ((con = SSL_new(ctx)) == NULL)
3603 if (s_tlsextdebug) {
3604 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3605 SSL_set_tlsext_debug_arg(con, bio_s_out);
3608 && !SSL_set_session_id_context(con, context,
3609 strlen((char *)context))) {
3611 ERR_print_errors(bio_err);
3615 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3618 ERR_print_errors(bio_err);
3622 SSL_set_bio(con, sbio, sbio);
3623 SSL_set_accept_state(con);
3625 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3626 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3627 BIO_push(io, ssl_bio);
3629 #ifdef CHARSET_EBCDIC
3630 filter = BIO_new(BIO_f_ebcdic_filter());
3634 io = BIO_push(filter, io);
3638 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3639 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3642 #ifndef OPENSSL_NO_SSL_TRACE
3644 SSL_set_msg_callback(con, SSL_trace);
3647 SSL_set_msg_callback(con, msg_cb);
3648 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3652 i = BIO_do_handshake(io);
3655 if (!BIO_should_retry(io)) {
3656 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3657 ERR_print_errors(bio_err);
3660 #ifndef OPENSSL_NO_SRP
3661 if (BIO_should_io_special(io)
3662 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3663 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3665 lookup_srp_user(&srp_callback_parm, bio_s_out);
3671 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3672 print_ssl_summary(con);
3675 i = BIO_gets(io, buf, bufsize + 1);
3676 if (i < 0) { /* error */
3677 if (!BIO_should_retry(io)) {
3679 ERR_print_errors(bio_err);
3682 BIO_printf(bio_s_out, "read R BLOCK\n");
3683 #ifndef OPENSSL_NO_SRP
3684 if (BIO_should_io_special(io)
3685 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3686 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3688 lookup_srp_user(&srp_callback_parm, bio_s_out);
3696 } else if (i == 0) { /* end of input */
3698 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3701 char *p = buf + i - 1;
3702 while (i && (*p == '\n' || *p == '\r')) {
3706 if (!s_ign_eof && i == 5 && HAS_PREFIX(buf, "CLOSE")) {
3708 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3711 BUF_reverse((unsigned char *)buf, NULL, i);
3713 BIO_write(io, buf, i + 1);
3718 if (!BIO_should_retry(io))
3724 /* make sure we reuse sessions */
3725 do_ssl_shutdown(con);
3735 #define MAX_SESSION_ID_ATTEMPTS 10
3736 static int generate_session_id(SSL *ssl, unsigned char *id,
3737 unsigned int *id_len)
3739 unsigned int count = 0;
3740 unsigned int session_id_prefix_len = strlen(session_id_prefix);
3743 if (RAND_bytes(id, *id_len) <= 0)
3746 * Prefix the session_id with the required prefix. NB: If our prefix
3747 * is too long, clip it - but there will be worse effects anyway, eg.
3748 * the server could only possibly create 1 session ID (ie. the
3749 * prefix!) so all future session negotiations will fail due to
3752 memcpy(id, session_id_prefix,
3753 (session_id_prefix_len < *id_len) ?
3754 session_id_prefix_len : *id_len);
3756 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3757 (++count < MAX_SESSION_ID_ATTEMPTS));
3758 if (count >= MAX_SESSION_ID_ATTEMPTS)
3764 * By default s_server uses an in-memory cache which caches SSL_SESSION
3765 * structures without any serialization. This hides some bugs which only
3766 * become apparent in deployed servers. By implementing a basic external
3767 * session cache some issues can be debugged using s_server.
3770 typedef struct simple_ssl_session_st {
3775 struct simple_ssl_session_st *next;
3776 } simple_ssl_session;
3778 static simple_ssl_session *first = NULL;
3780 static int add_session(SSL *ssl, SSL_SESSION *session)
3782 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3785 SSL_SESSION_get_id(session, &sess->idlen);
3786 sess->derlen = i2d_SSL_SESSION(session, NULL);
3787 if (sess->derlen < 0) {
3788 BIO_printf(bio_err, "Error encoding session\n");
3793 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3794 sess->der = app_malloc(sess->derlen, "get session buffer");
3796 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3797 OPENSSL_free(sess->id);
3798 OPENSSL_free(sess->der);
3804 /* Assume it still works. */
3805 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3806 BIO_printf(bio_err, "Unexpected session encoding length\n");
3807 OPENSSL_free(sess->id);
3808 OPENSSL_free(sess->der);
3815 BIO_printf(bio_err, "New session added to external cache\n");
3819 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3822 simple_ssl_session *sess;
3824 for (sess = first; sess; sess = sess->next) {
3825 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3826 const unsigned char *p = sess->der;
3827 BIO_printf(bio_err, "Lookup session: cache hit\n");
3828 return d2i_SSL_SESSION_ex(NULL, &p, sess->derlen, app_get0_libctx(),
3832 BIO_printf(bio_err, "Lookup session: cache miss\n");
3836 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3838 simple_ssl_session *sess, *prev = NULL;
3839 const unsigned char *id;
3841 id = SSL_SESSION_get_id(session, &idlen);
3842 for (sess = first; sess; sess = sess->next) {
3843 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3845 prev->next = sess->next;
3848 OPENSSL_free(sess->id);
3849 OPENSSL_free(sess->der);
3857 static void init_session_cache_ctx(SSL_CTX *sctx)
3859 SSL_CTX_set_session_cache_mode(sctx,
3860 SSL_SESS_CACHE_NO_INTERNAL |
3861 SSL_SESS_CACHE_SERVER);
3862 SSL_CTX_sess_set_new_cb(sctx, add_session);
3863 SSL_CTX_sess_set_get_cb(sctx, get_session);
3864 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3867 static void free_sessions(void)
3869 simple_ssl_session *sess, *tsess;
3870 for (sess = first; sess;) {
3871 OPENSSL_free(sess->id);
3872 OPENSSL_free(sess->der);
3875 OPENSSL_free(tsess);
3880 #endif /* OPENSSL_NO_SOCK */