2 * Copyright 1995-2022 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 #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))) {
232 SSL_SESSION_free(tmpsess);
241 #ifndef OPENSSL_NO_SRP
242 static srpsrvparm srp_callback_parm;
245 static int local_argc = 0;
246 static char **local_argv;
248 #ifdef CHARSET_EBCDIC
249 static int ebcdic_new(BIO *bi);
250 static int ebcdic_free(BIO *a);
251 static int ebcdic_read(BIO *b, char *out, int outl);
252 static int ebcdic_write(BIO *b, const char *in, int inl);
253 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
254 static int ebcdic_gets(BIO *bp, char *buf, int size);
255 static int ebcdic_puts(BIO *bp, const char *str);
257 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
258 static BIO_METHOD *methods_ebcdic = NULL;
260 /* This struct is "unwarranted chumminess with the compiler." */
266 static const BIO_METHOD *BIO_f_ebcdic_filter()
268 if (methods_ebcdic == NULL) {
269 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
270 "EBCDIC/ASCII filter");
271 if (methods_ebcdic == NULL
272 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
273 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
274 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
275 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
276 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
277 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
278 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
281 return methods_ebcdic;
284 static int ebcdic_new(BIO *bi)
286 EBCDIC_OUTBUFF *wbuf;
288 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
289 wbuf->alloced = 1024;
290 wbuf->buff[0] = '\0';
292 BIO_set_data(bi, wbuf);
297 static int ebcdic_free(BIO *a)
299 EBCDIC_OUTBUFF *wbuf;
303 wbuf = BIO_get_data(a);
305 BIO_set_data(a, NULL);
311 static int ebcdic_read(BIO *b, char *out, int outl)
314 BIO *next = BIO_next(b);
316 if (out == NULL || outl == 0)
321 ret = BIO_read(next, out, outl);
323 ascii2ebcdic(out, out, ret);
327 static int ebcdic_write(BIO *b, const char *in, int inl)
329 EBCDIC_OUTBUFF *wbuf;
330 BIO *next = BIO_next(b);
334 if ((in == NULL) || (inl <= 0))
339 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
341 if (inl > (num = wbuf->alloced)) {
342 num = num + num; /* double the size */
346 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
349 wbuf->buff[0] = '\0';
351 BIO_set_data(b, wbuf);
354 ebcdic2ascii(wbuf->buff, in, inl);
356 ret = BIO_write(next, wbuf->buff, inl);
361 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
364 BIO *next = BIO_next(b);
373 ret = BIO_ctrl(next, cmd, num, ptr);
379 static int ebcdic_gets(BIO *bp, char *buf, int size)
382 BIO *next = BIO_next(bp);
386 /* return(BIO_gets(bp->next_bio,buf,size));*/
387 for (i = 0; i < size - 1; ++i) {
388 ret = ebcdic_read(bp, &buf[i], 1);
391 else if (buf[i] == '\n') {
398 return (ret < 0 && i == 0) ? ret : i;
401 static int ebcdic_puts(BIO *bp, const char *str)
403 if (BIO_next(bp) == NULL)
405 return ebcdic_write(bp, str, strlen(str));
409 /* This is a context that we pass to callbacks */
410 typedef struct tlsextctx_st {
416 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
418 tlsextctx *p = (tlsextctx *) arg;
419 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
421 if (servername != NULL && p->biodebug != NULL) {
422 const char *cp = servername;
425 BIO_printf(p->biodebug, "Hostname in TLS extension: \"");
426 while ((uc = *cp++) != 0)
427 BIO_printf(p->biodebug,
428 (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc);
429 BIO_printf(p->biodebug, "\"\n");
432 if (p->servername == NULL)
433 return SSL_TLSEXT_ERR_NOACK;
435 if (servername != NULL) {
436 if (OPENSSL_strcasecmp(servername, p->servername))
437 return p->extension_error;
439 BIO_printf(p->biodebug, "Switching server context.\n");
440 SSL_set_SSL_CTX(s, ctx2);
443 return SSL_TLSEXT_ERR_OK;
446 /* Structure passed to cert status callback */
447 typedef struct tlsextstatusctx_st {
449 /* File to load OCSP Response from (or NULL if no file) */
451 /* Default responder to use */
452 char *host, *path, *port;
453 char *proxy, *no_proxy;
458 static tlsextstatusctx tlscstatp = { -1 };
460 #ifndef OPENSSL_NO_OCSP
463 * Helper function to get an OCSP_RESPONSE from a responder. This is a
464 * simplified version. It examines certificates each time and makes one OCSP
465 * responder query for each request. A full version would store details such as
466 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
467 * them until they were considered "expired".
469 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
470 OCSP_RESPONSE **resp)
472 char *host = NULL, *port = NULL, *path = NULL;
473 char *proxy = NULL, *no_proxy = NULL;
475 STACK_OF(OPENSSL_STRING) *aia = NULL;
477 X509_STORE_CTX *inctx = NULL;
479 OCSP_REQUEST *req = NULL;
480 OCSP_CERTID *id = NULL;
481 STACK_OF(X509_EXTENSION) *exts;
482 int ret = SSL_TLSEXT_ERR_NOACK;
485 /* Build up OCSP query from server certificate */
486 x = SSL_get_certificate(s);
487 aia = X509_get1_ocsp(x);
489 if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl,
490 NULL, &host, &port, NULL, &path, NULL, NULL)) {
491 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
495 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
496 sk_OPENSSL_STRING_value(aia, 0));
498 if (srctx->host == NULL) {
500 "cert_status: no AIA and no default responder URL\n");
506 use_ssl = srctx->use_ssl;
508 proxy = srctx->proxy;
509 no_proxy = srctx->no_proxy;
511 inctx = X509_STORE_CTX_new();
514 if (!X509_STORE_CTX_init(inctx,
515 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
518 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
519 X509_get_issuer_name(x));
521 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
524 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
525 X509_OBJECT_free(obj);
528 req = OCSP_REQUEST_new();
531 if (!OCSP_request_add0_id(req, id))
534 /* Add any extensions to the request */
535 SSL_get_tlsext_status_exts(s, &exts);
536 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
537 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
538 if (!OCSP_REQUEST_add_ext(req, ext, -1))
541 *resp = process_responder(req, host, port, path, proxy, no_proxy,
542 use_ssl, NULL /* headers */, srctx->timeout);
544 BIO_puts(bio_err, "cert_status: error querying responder\n");
548 ret = SSL_TLSEXT_ERR_OK;
552 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
555 * If we parsed aia we need to free; otherwise they were copied and we
562 X509_email_free(aia);
564 OCSP_CERTID_free(id);
565 OCSP_REQUEST_free(req);
566 X509_STORE_CTX_free(inctx);
571 * Certificate Status callback. This is called when a client includes a
572 * certificate status request extension. The response is either obtained from a
573 * file, or from an OCSP responder.
575 static int cert_status_cb(SSL *s, void *arg)
577 tlsextstatusctx *srctx = arg;
578 OCSP_RESPONSE *resp = NULL;
579 unsigned char *rspder = NULL;
581 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
584 BIO_puts(bio_err, "cert_status: callback called\n");
586 if (srctx->respin != NULL) {
587 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
588 if (derbio == NULL) {
589 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
592 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
595 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
599 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
600 if (ret != SSL_TLSEXT_ERR_OK)
604 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
608 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
609 if (srctx->verbose) {
610 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
611 OCSP_RESPONSE_print(bio_err, resp, 2);
614 ret = SSL_TLSEXT_ERR_OK;
617 if (ret != SSL_TLSEXT_ERR_OK)
618 ERR_print_errors(bio_err);
620 OCSP_RESPONSE_free(resp);
626 #ifndef OPENSSL_NO_NEXTPROTONEG
627 /* This is the context that we pass to next_proto_cb */
628 typedef struct tlsextnextprotoctx_st {
631 } tlsextnextprotoctx;
633 static int next_proto_cb(SSL *s, const unsigned char **data,
634 unsigned int *len, void *arg)
636 tlsextnextprotoctx *next_proto = arg;
638 *data = next_proto->data;
639 *len = next_proto->len;
641 return SSL_TLSEXT_ERR_OK;
643 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
645 /* This the context that we pass to alpn_cb */
646 typedef struct tlsextalpnctx_st {
651 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
652 const unsigned char *in, unsigned int inlen, void *arg)
654 tlsextalpnctx *alpn_ctx = arg;
657 /* We can assume that |in| is syntactically valid. */
659 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
660 for (i = 0; i < inlen;) {
662 BIO_write(bio_s_out, ", ", 2);
663 BIO_write(bio_s_out, &in[i + 1], in[i]);
666 BIO_write(bio_s_out, "\n", 1);
669 if (SSL_select_next_proto
670 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
671 inlen) != OPENSSL_NPN_NEGOTIATED) {
672 return SSL_TLSEXT_ERR_ALERT_FATAL;
676 BIO_printf(bio_s_out, "ALPN protocols selected: ");
677 BIO_write(bio_s_out, *out, *outlen);
678 BIO_write(bio_s_out, "\n", 1);
681 return SSL_TLSEXT_ERR_OK;
684 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
686 /* disable resumption for sessions with forward secure ciphers */
687 return is_forward_secure;
690 typedef enum OPTION_choice {
693 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
694 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
695 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
696 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
697 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
698 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
699 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
700 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
702 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
703 OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
704 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
705 OPT_STATUS_TIMEOUT, OPT_PROXY, OPT_NO_PROXY, OPT_STATUS_URL,
706 OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
707 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
708 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
709 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK,
710 OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW,
711 OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG,
712 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
713 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
714 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS,
715 OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
716 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE,
717 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
718 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA,
719 OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG,
720 OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF, OPT_KTLS,
722 OPT_TFO, OPT_CERT_COMP,
730 const OPTIONS s_server_options[] = {
731 OPT_SECTION("General"),
732 {"help", OPT_HELP, '-', "Display this summary"},
733 {"ssl_config", OPT_SSL_CONFIG, 's',
734 "Configure SSL_CTX using the given configuration value"},
735 #ifndef OPENSSL_NO_SSL_TRACE
736 {"trace", OPT_TRACE, '-', "trace protocol messages"},
738 #ifndef OPENSSL_NO_ENGINE
739 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
742 OPT_SECTION("Network"),
743 {"port", OPT_PORT, 'p',
744 "TCP/IP port to listen on for connections (default is " PORT ")"},
745 {"accept", OPT_ACCEPT, 's',
746 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
748 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
749 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
751 {"4", OPT_4, '-', "Use IPv4 only"},
752 {"6", OPT_6, '-', "Use IPv6 only"},
753 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
754 {"tfo", OPT_TFO, '-', "Listen for TCP Fast Open connections"},
757 OPT_SECTION("Identity"),
758 {"context", OPT_CONTEXT, 's', "Set session ID context"},
759 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
760 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
761 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
762 {"no-CAfile", OPT_NOCAFILE, '-',
763 "Do not load the default certificates file"},
764 {"no-CApath", OPT_NOCAPATH, '-',
765 "Do not load certificates from the default certificates directory"},
766 {"no-CAstore", OPT_NOCASTORE, '-',
767 "Do not load certificates from the default certificates store URI"},
768 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
769 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
770 {"Verify", OPT_UPPER_V_VERIFY, 'n',
771 "Turn on peer certificate verification, must have a cert"},
772 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
773 {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT},
774 {"cert2", OPT_CERT2, '<',
775 "Certificate file to use for servername; default " TEST_CERT2},
776 {"certform", OPT_CERTFORM, 'F',
777 "Server certificate file format (PEM/DER/P12); has no effect"},
778 {"cert_chain", OPT_CERT_CHAIN, '<',
779 "Server certificate chain file in PEM format"},
780 {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"},
781 {"serverinfo", OPT_SERVERINFO, 's',
782 "PEM serverinfo file for certificate"},
783 {"key", OPT_KEY, 's',
784 "Private key file to use; default is -cert file or else" TEST_CERT},
785 {"key2", OPT_KEY2, '<',
786 "-Private Key file to use for servername if not in -cert2"},
787 {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"},
788 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
789 {"dcert", OPT_DCERT, '<',
790 "Second server certificate file to use (usually for DSA)"},
791 {"dcertform", OPT_DCERTFORM, 'F',
792 "Second server certificate file format (PEM/DER/P12); has no effect"},
793 {"dcert_chain", OPT_DCERT_CHAIN, '<',
794 "second server certificate chain file in PEM format"},
795 {"dkey", OPT_DKEY, '<',
796 "Second private key file to use (usually for DSA)"},
797 {"dkeyform", OPT_DKEYFORM, 'F',
798 "Second key file format (ENGINE, other values ignored)"},
799 {"dpass", OPT_DPASS, 's',
800 "Second private key and cert file pass phrase source"},
801 {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
802 {"servername", OPT_SERVERNAME, 's',
803 "Servername for HostName TLS extension"},
804 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
805 "On servername mismatch send fatal alert (default warning alert)"},
806 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
807 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
808 {"quiet", OPT_QUIET, '-', "No server output"},
809 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
810 "Disable caching and tickets if ephemeral (EC)DH is used"},
811 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
812 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
813 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
814 "Do not treat lack of close_notify from a peer as an error"},
815 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
816 "Hex dump of all TLS extensions received"},
817 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
818 {"id_prefix", OPT_ID_PREFIX, 's',
819 "Generate SSL/TLS session IDs prefixed by arg"},
820 {"keymatexport", OPT_KEYMATEXPORT, 's',
821 "Export keying material using label"},
822 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
823 "Export len bytes of keying material; default 20"},
824 {"CRL", OPT_CRL, '<', "CRL file to use"},
825 {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"},
826 {"crl_download", OPT_CRL_DOWNLOAD, '-',
827 "Download CRLs from distribution points in certificate CDP entries"},
828 {"chainCAfile", OPT_CHAINCAFILE, '<',
829 "CA file for certificate chain (PEM format)"},
830 {"chainCApath", OPT_CHAINCAPATH, '/',
831 "use dir as certificate store path to build CA certificate chain"},
832 {"chainCAstore", OPT_CHAINCASTORE, ':',
833 "use URI as certificate store to build CA certificate chain"},
834 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
835 "CA file for certificate verification (PEM format)"},
836 {"verifyCApath", OPT_VERIFYCAPATH, '/',
837 "use dir as certificate store path to verify CA certificate"},
838 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
839 "use URI as certificate store to verify CA certificate"},
840 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
841 {"ext_cache", OPT_EXT_CACHE, '-',
842 "Disable internal cache, set up and use external cache"},
843 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
844 "Close connection on verification error"},
845 {"verify_quiet", OPT_VERIFY_QUIET, '-',
846 "No verify output except verify errors"},
847 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input EOF (default when -quiet)"},
848 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input EOF"},
849 #ifndef OPENSSL_NO_COMP_ALG
850 {"cert_comp", OPT_CERT_COMP, '-', "Pre-compress server certificates"},
853 #ifndef OPENSSL_NO_OCSP
855 {"status", OPT_STATUS, '-', "Request certificate status from server"},
856 {"status_verbose", OPT_STATUS_VERBOSE, '-',
857 "Print more output in certificate status callback"},
858 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
859 "Status request responder timeout"},
860 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
861 {"proxy", OPT_PROXY, 's',
862 "[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"},
863 {"no_proxy", OPT_NO_PROXY, 's',
864 "List of addresses of servers not to use HTTP(S) proxy for"},
866 "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
867 {"status_file", OPT_STATUS_FILE, '<',
868 "File containing DER encoded OCSP Response"},
871 OPT_SECTION("Debug"),
872 {"security_debug", OPT_SECURITY_DEBUG, '-',
873 "Print output from SSL/TLS security framework"},
874 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
875 "Print more output from SSL/TLS security framework"},
876 {"brief", OPT_BRIEF, '-',
877 "Restrict output to brief summary of connection parameters"},
878 {"rev", OPT_REV, '-',
879 "act as an echo server that sends back received text reversed"},
880 {"debug", OPT_DEBUG, '-', "Print more output"},
881 {"msg", OPT_MSG, '-', "Show protocol messages"},
882 {"msgfile", OPT_MSGFILE, '>',
883 "File to send output of -msg or -trace, instead of stdout"},
884 {"state", OPT_STATE, '-', "Print the SSL states"},
885 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
886 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
887 "Maximum number of encrypt/decrypt pipelines to be used"},
888 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
889 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
891 OPT_SECTION("Network"),
892 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
893 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
894 {"mtu", OPT_MTU, 'p', "Set link-layer MTU"},
895 {"read_buf", OPT_READ_BUF, 'p',
896 "Default read buffer size to be used for connections"},
897 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
898 "Size used to split data for encrypt pipelines"},
899 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
901 OPT_SECTION("Server identity"),
902 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
903 #ifndef OPENSSL_NO_PSK
904 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
906 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
907 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
908 #ifndef OPENSSL_NO_SRP
909 {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"},
910 {"srpuserseed", OPT_SRPUSERSEED, 's',
911 "(deprecated) A seed string for a default user salt"},
914 OPT_SECTION("Protocol and version"),
915 {"max_early_data", OPT_MAX_EARLY, 'n',
916 "The maximum number of bytes of early data as advertised in tickets"},
917 {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n',
918 "The maximum number of bytes of early data (hard limit)"},
919 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
920 {"num_tickets", OPT_S_NUM_TICKETS, 'n',
921 "The number of TLSv1.3 session tickets that a server will automatically issue" },
922 {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"},
923 {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"},
924 {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"},
925 {"no_ca_names", OPT_NOCANAMES, '-',
926 "Disable TLS Extension CA Names"},
927 {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"},
928 #ifndef OPENSSL_NO_SSL3
929 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
931 #ifndef OPENSSL_NO_TLS1
932 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
934 #ifndef OPENSSL_NO_TLS1_1
935 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
937 #ifndef OPENSSL_NO_TLS1_2
938 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
940 #ifndef OPENSSL_NO_TLS1_3
941 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
943 #ifndef OPENSSL_NO_DTLS
944 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
945 {"listen", OPT_LISTEN, '-',
946 "Listen for a DTLS ClientHello with a cookie and then connect"},
948 #ifndef OPENSSL_NO_DTLS1
949 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
951 #ifndef OPENSSL_NO_DTLS1_2
952 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
954 #ifndef OPENSSL_NO_SCTP
955 {"sctp", OPT_SCTP, '-', "Use SCTP"},
956 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
958 #ifndef OPENSSL_NO_SRTP
959 {"use_srtp", OPT_SRTP_PROFILES, 's',
960 "Offer SRTP key management with a colon-separated profile list"},
962 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
963 #ifndef OPENSSL_NO_NEXTPROTONEG
964 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
965 "Set the advertised protocols for the NPN extension (comma-separated list)"},
967 {"alpn", OPT_ALPN, 's',
968 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
969 #ifndef OPENSSL_NO_KTLS
970 {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"},
971 {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"},
972 {"zerocopy_sendfile", OPT_USE_ZC_SENDFILE, '-', "Use zerocopy mode of KTLS sendfile"},
983 #define IS_PROT_FLAG(o) \
984 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
985 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
987 int s_server_main(int argc, char *argv[])
989 ENGINE *engine = NULL;
990 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
991 SSL_CONF_CTX *cctx = NULL;
992 const SSL_METHOD *meth = TLS_server_method();
993 SSL_EXCERT *exc = NULL;
994 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
995 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
996 STACK_OF(X509_CRL) *crls = NULL;
997 X509 *s_cert = NULL, *s_dcert = NULL;
998 X509_VERIFY_PARAM *vpm = NULL;
999 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
1000 const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL;
1001 char *dpassarg = NULL, *dpass = NULL;
1002 char *passarg = NULL, *pass = NULL;
1003 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
1004 char *crl_file = NULL, *prog;
1006 int unlink_unix_path = 0;
1008 do_server_cb server_cb;
1009 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
1010 char *dhfile = NULL;
1012 int nocert = 0, ret = 1;
1013 int noCApath = 0, noCAfile = 0, noCAstore = 0;
1014 int s_cert_format = FORMAT_UNDEF, s_key_format = FORMAT_UNDEF;
1015 int s_dcert_format = FORMAT_UNDEF, s_dkey_format = FORMAT_UNDEF;
1016 int rev = 0, naccept = -1, sdebug = 0;
1017 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
1018 int state = 0, crl_format = FORMAT_UNDEF, crl_download = 0;
1021 unsigned char *context = NULL;
1023 EVP_PKEY *s_key2 = NULL;
1024 X509 *s_cert2 = NULL;
1025 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
1026 const char *ssl_config = NULL;
1027 int read_buf_len = 0;
1028 #ifndef OPENSSL_NO_NEXTPROTONEG
1029 const char *next_proto_neg_in = NULL;
1030 tlsextnextprotoctx next_proto = { NULL, 0 };
1032 const char *alpn_in = NULL;
1033 tlsextalpnctx alpn_ctx = { NULL, 0 };
1034 #ifndef OPENSSL_NO_PSK
1035 /* by default do not send a PSK identity hint */
1036 char *psk_identity_hint = NULL;
1039 #ifndef OPENSSL_NO_SRP
1040 char *srpuserseed = NULL;
1041 char *srp_verifier_file = NULL;
1043 #ifndef OPENSSL_NO_SRTP
1044 char *srtp_profiles = NULL;
1046 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1047 int s_server_verify = SSL_VERIFY_NONE;
1048 int s_server_session_id_context = 1; /* anything will do */
1049 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
1050 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
1051 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
1052 #ifndef OPENSSL_NO_OCSP
1053 int s_tlsextstatus = 0;
1055 int no_resume_ephemeral = 0;
1056 unsigned int max_send_fragment = 0;
1057 unsigned int split_send_fragment = 0, max_pipelines = 0;
1058 const char *s_serverinfo_file = NULL;
1059 const char *keylog_file = NULL;
1060 int max_early_data = -1, recv_max_early_data = -1;
1061 char *psksessf = NULL;
1062 int no_ca_names = 0;
1063 #ifndef OPENSSL_NO_SCTP
1064 int sctp_label_bug = 0;
1066 int ignore_unexpected_eof = 0;
1067 #ifndef OPENSSL_NO_KTLS
1068 int enable_ktls = 0;
1073 /* Init of few remaining global variables */
1078 s_nbio = s_nbio_test = 0;
1087 use_zc_sendfile = 0;
1089 port = OPENSSL_strdup(PORT);
1090 cctx = SSL_CONF_CTX_new();
1091 vpm = X509_VERIFY_PARAM_new();
1092 if (port == NULL || cctx == NULL || vpm == NULL)
1094 SSL_CONF_CTX_set_flags(cctx,
1095 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1097 prog = opt_init(argc, argv, s_server_options);
1098 while ((o = opt_next()) != OPT_EOF) {
1099 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1100 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1103 if (IS_NO_PROT_FLAG(o))
1105 if (prot_opt == 1 && no_prot_opt) {
1107 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1114 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1117 opt_help(s_server_options);
1123 if (socket_family == AF_UNIX) {
1124 OPENSSL_free(host); host = NULL;
1125 OPENSSL_free(port); port = NULL;
1128 socket_family = AF_INET;
1134 if (socket_family == AF_UNIX) {
1135 OPENSSL_free(host); host = NULL;
1136 OPENSSL_free(port); port = NULL;
1139 socket_family = AF_INET6;
1142 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1148 if (socket_family == AF_UNIX) {
1149 socket_family = AF_UNSPEC;
1152 OPENSSL_free(port); port = NULL;
1153 OPENSSL_free(host); host = NULL;
1154 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1156 "%s: -port argument malformed or ambiguous\n",
1163 if (socket_family == AF_UNIX) {
1164 socket_family = AF_UNSPEC;
1167 OPENSSL_free(port); port = NULL;
1168 OPENSSL_free(host); host = NULL;
1169 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1171 "%s: -accept argument malformed or ambiguous\n",
1178 socket_family = AF_UNIX;
1179 OPENSSL_free(host); host = OPENSSL_strdup(opt_arg());
1182 OPENSSL_free(port); port = NULL;
1185 unlink_unix_path = 1;
1189 naccept = atol(opt_arg());
1192 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1193 verify_args.depth = atoi(opt_arg());
1195 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1197 case OPT_UPPER_V_VERIFY:
1199 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1200 SSL_VERIFY_CLIENT_ONCE;
1201 verify_args.depth = atoi(opt_arg());
1204 "verify depth is %d, must return a certificate\n",
1208 context = (unsigned char *)opt_arg();
1211 s_cert_file = opt_arg();
1214 if (!set_nameopt(opt_arg()))
1218 crl_file = opt_arg();
1220 case OPT_CRL_DOWNLOAD:
1223 case OPT_SERVERINFO:
1224 s_serverinfo_file = opt_arg();
1227 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format))
1231 s_key_file = opt_arg();
1234 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1238 passarg = opt_arg();
1240 case OPT_CERT_CHAIN:
1241 s_chain_file = opt_arg();
1247 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format))
1251 s_dcert_file = opt_arg();
1254 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format))
1258 dpassarg = opt_arg();
1261 s_dkey_file = opt_arg();
1263 case OPT_DCERT_CHAIN:
1264 s_dchain_file = opt_arg();
1275 case OPT_CHAINCAPATH:
1276 chCApath = opt_arg();
1278 case OPT_VERIFYCAPATH:
1279 vfyCApath = opt_arg();
1282 CAstore = opt_arg();
1287 case OPT_CHAINCASTORE:
1288 chCAstore = opt_arg();
1290 case OPT_VERIFYCASTORE:
1291 vfyCAstore = opt_arg();
1300 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1304 case OPT_S_NUM_TICKETS:
1305 case OPT_ANTI_REPLAY:
1306 case OPT_NO_ANTI_REPLAY:
1307 if (ssl_args == NULL)
1308 ssl_args = sk_OPENSSL_STRING_new_null();
1309 if (ssl_args == NULL
1310 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1311 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1312 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1317 if (!opt_verify(o, vpm))
1322 if (!args_excert(o, &exc))
1325 case OPT_VERIFY_RET_ERROR:
1326 verify_args.return_error = 1;
1328 case OPT_VERIFY_QUIET:
1329 verify_args.quiet = 1;
1331 case OPT_BUILD_CHAIN:
1340 case OPT_CHAINCAFILE:
1341 chCAfile = opt_arg();
1343 case OPT_VERIFYCAFILE:
1344 vfyCAfile = opt_arg();
1350 s_nbio = s_nbio_test = 1;
1355 case OPT_NO_IGN_EOF:
1361 case OPT_TLSEXTDEBUG:
1365 #ifndef OPENSSL_NO_OCSP
1369 case OPT_STATUS_VERBOSE:
1370 #ifndef OPENSSL_NO_OCSP
1371 s_tlsextstatus = tlscstatp.verbose = 1;
1374 case OPT_STATUS_TIMEOUT:
1375 #ifndef OPENSSL_NO_OCSP
1377 tlscstatp.timeout = atoi(opt_arg());
1381 #ifndef OPENSSL_NO_OCSP
1382 tlscstatp.proxy = opt_arg();
1386 #ifndef OPENSSL_NO_OCSP
1387 tlscstatp.no_proxy = opt_arg();
1390 case OPT_STATUS_URL:
1391 #ifndef OPENSSL_NO_OCSP
1393 if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL,
1394 &tlscstatp.host, &tlscstatp.port, NULL,
1395 &tlscstatp.path, NULL, NULL)) {
1396 BIO_printf(bio_err, "Error parsing -status_url argument\n");
1401 case OPT_STATUS_FILE:
1402 #ifndef OPENSSL_NO_OCSP
1404 tlscstatp.respin = opt_arg();
1411 bio_s_msg = BIO_new_file(opt_arg(), "w");
1412 if (bio_s_msg == NULL) {
1413 BIO_printf(bio_err, "Error writing file %s\n", opt_arg());
1418 #ifndef OPENSSL_NO_SSL_TRACE
1422 case OPT_SECURITY_DEBUG:
1425 case OPT_SECURITY_DEBUG_VERBOSE:
1438 s_quiet = s_brief = verify_args.quiet = 1;
1443 case OPT_NO_RESUME_EPHEMERAL:
1444 no_resume_ephemeral = 1;
1446 case OPT_PSK_IDENTITY:
1447 psk_identity = opt_arg();
1450 #ifndef OPENSSL_NO_PSK
1451 psk_identity_hint = opt_arg();
1455 for (p = psk_key = opt_arg(); *p; p++) {
1456 if (isxdigit(_UC(*p)))
1458 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1463 psksessf = opt_arg();
1466 #ifndef OPENSSL_NO_SRP
1467 srp_verifier_file = opt_arg();
1468 if (min_version < TLS1_VERSION)
1469 min_version = TLS1_VERSION;
1472 case OPT_SRPUSERSEED:
1473 #ifndef OPENSSL_NO_SRP
1474 srpuserseed = opt_arg();
1475 if (min_version < TLS1_VERSION)
1476 min_version = TLS1_VERSION;
1491 case OPT_SSL_CONFIG:
1492 ssl_config = opt_arg();
1495 min_version = SSL3_VERSION;
1496 max_version = SSL3_VERSION;
1499 min_version = TLS1_3_VERSION;
1500 max_version = TLS1_3_VERSION;
1503 min_version = TLS1_2_VERSION;
1504 max_version = TLS1_2_VERSION;
1507 min_version = TLS1_1_VERSION;
1508 max_version = TLS1_1_VERSION;
1511 min_version = TLS1_VERSION;
1512 max_version = TLS1_VERSION;
1515 #ifndef OPENSSL_NO_DTLS
1516 meth = DTLS_server_method();
1517 socket_type = SOCK_DGRAM;
1521 #ifndef OPENSSL_NO_DTLS
1522 meth = DTLS_server_method();
1523 min_version = DTLS1_VERSION;
1524 max_version = DTLS1_VERSION;
1525 socket_type = SOCK_DGRAM;
1529 #ifndef OPENSSL_NO_DTLS
1530 meth = DTLS_server_method();
1531 min_version = DTLS1_2_VERSION;
1532 max_version = DTLS1_2_VERSION;
1533 socket_type = SOCK_DGRAM;
1537 #ifndef OPENSSL_NO_SCTP
1538 protocol = IPPROTO_SCTP;
1541 case OPT_SCTP_LABEL_BUG:
1542 #ifndef OPENSSL_NO_SCTP
1547 #ifndef OPENSSL_NO_DTLS
1548 enable_timeouts = 1;
1552 #ifndef OPENSSL_NO_DTLS
1553 socket_mtu = atol(opt_arg());
1557 #ifndef OPENSSL_NO_DTLS
1565 session_id_prefix = opt_arg();
1568 #ifndef OPENSSL_NO_ENGINE
1569 engine = setup_engine(opt_arg(), s_debug);
1576 case OPT_PROV_CASES:
1577 if (!opt_provider(o))
1580 case OPT_SERVERNAME:
1581 tlsextcbp.servername = opt_arg();
1583 case OPT_SERVERNAME_FATAL:
1584 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1587 s_cert_file2 = opt_arg();
1590 s_key_file2 = opt_arg();
1592 case OPT_NEXTPROTONEG:
1593 # ifndef OPENSSL_NO_NEXTPROTONEG
1594 next_proto_neg_in = opt_arg();
1598 alpn_in = opt_arg();
1600 case OPT_SRTP_PROFILES:
1601 #ifndef OPENSSL_NO_SRTP
1602 srtp_profiles = opt_arg();
1605 case OPT_KEYMATEXPORT:
1606 keymatexportlabel = opt_arg();
1608 case OPT_KEYMATEXPORTLEN:
1609 keymatexportlen = atoi(opt_arg());
1614 case OPT_MAX_SEND_FRAG:
1615 max_send_fragment = atoi(opt_arg());
1617 case OPT_SPLIT_SEND_FRAG:
1618 split_send_fragment = atoi(opt_arg());
1620 case OPT_MAX_PIPELINES:
1621 max_pipelines = atoi(opt_arg());
1624 read_buf_len = atoi(opt_arg());
1626 case OPT_KEYLOG_FILE:
1627 keylog_file = opt_arg();
1630 max_early_data = atoi(opt_arg());
1631 if (max_early_data < 0) {
1632 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1636 case OPT_RECV_MAX_EARLY:
1637 recv_max_early_data = atoi(opt_arg());
1638 if (recv_max_early_data < 0) {
1639 BIO_printf(bio_err, "Invalid value for recv_max_early_data\n");
1643 case OPT_EARLY_DATA:
1645 if (max_early_data == -1)
1646 max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
1648 case OPT_HTTP_SERVER_BINMODE:
1649 http_server_binmode = 1;
1655 #ifndef OPENSSL_NO_KTLS
1660 #ifndef OPENSSL_NO_KTLS
1664 case OPT_USE_ZC_SENDFILE:
1665 #ifndef OPENSSL_NO_KTLS
1666 use_zc_sendfile = 1;
1669 case OPT_IGNORE_UNEXPECTED_EOF:
1670 ignore_unexpected_eof = 1;
1681 /* No extra arguments. */
1682 if (!opt_check_rest_arg(NULL))
1685 if (!app_RAND_load())
1688 #ifndef OPENSSL_NO_NEXTPROTONEG
1689 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1690 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1694 #ifndef OPENSSL_NO_DTLS
1695 if (www && socket_type == SOCK_DGRAM) {
1696 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1700 if (dtlslisten && socket_type != SOCK_DGRAM) {
1701 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1706 if (tfo && socket_type != SOCK_STREAM) {
1707 BIO_printf(bio_err, "Can only use -tfo with TLS\n");
1711 if (stateless && socket_type != SOCK_STREAM) {
1712 BIO_printf(bio_err, "Can only use --stateless with TLS\n");
1717 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1719 "Can't use unix sockets and datagrams together\n");
1723 if (early_data && (www > 0 || rev)) {
1725 "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n");
1729 #ifndef OPENSSL_NO_SCTP
1730 if (protocol == IPPROTO_SCTP) {
1731 if (socket_type != SOCK_DGRAM) {
1732 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1735 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1736 socket_type = SOCK_STREAM;
1740 #ifndef OPENSSL_NO_KTLS
1741 if (use_zc_sendfile && !use_sendfile) {
1742 BIO_printf(bio_out, "Warning: -zerocopy_sendfile depends on -sendfile, enabling -sendfile now.\n");
1746 if (use_sendfile && enable_ktls == 0) {
1747 BIO_printf(bio_out, "Warning: -sendfile depends on -ktls, enabling -ktls now.\n");
1751 if (use_sendfile && www <= 1) {
1752 BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n");
1757 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1758 BIO_printf(bio_err, "Error getting password\n");
1762 if (s_key_file == NULL)
1763 s_key_file = s_cert_file;
1765 if (s_key_file2 == NULL)
1766 s_key_file2 = s_cert_file2;
1768 if (!load_excert(&exc))
1772 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1773 "server certificate private key");
1777 s_cert = load_cert_pass(s_cert_file, s_cert_format, 1, pass,
1778 "server certificate");
1782 if (s_chain_file != NULL) {
1783 if (!load_certs(s_chain_file, 0, &s_chain, NULL,
1784 "server certificate chain"))
1788 if (tlsextcbp.servername != NULL) {
1789 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1790 "second server certificate private key");
1794 s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, 1, pass,
1795 "second server certificate");
1797 if (s_cert2 == NULL)
1801 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1802 if (next_proto_neg_in) {
1803 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1804 if (next_proto.data == NULL)
1808 alpn_ctx.data = NULL;
1810 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1811 if (alpn_ctx.data == NULL)
1815 if (crl_file != NULL) {
1817 crl = load_crl(crl_file, crl_format, 0, "CRL");
1820 crls = sk_X509_CRL_new_null();
1821 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1822 BIO_puts(bio_err, "Error adding CRL\n");
1823 ERR_print_errors(bio_err);
1829 if (s_dcert_file != NULL) {
1831 if (s_dkey_file == NULL)
1832 s_dkey_file = s_dcert_file;
1834 s_dkey = load_key(s_dkey_file, s_dkey_format,
1835 0, dpass, engine, "second certificate private key");
1839 s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, 1, dpass,
1840 "second server certificate");
1842 if (s_dcert == NULL) {
1843 ERR_print_errors(bio_err);
1846 if (s_dchain_file != NULL) {
1847 if (!load_certs(s_dchain_file, 0, &s_dchain, NULL,
1848 "second server certificate chain"))
1854 if (bio_s_out == NULL) {
1855 if (s_quiet && !s_debug) {
1856 bio_s_out = BIO_new(BIO_s_null());
1857 if (s_msg && bio_s_msg == NULL) {
1858 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1859 if (bio_s_msg == NULL) {
1860 BIO_printf(bio_err, "Out of memory\n");
1865 bio_s_out = dup_bio_out(FORMAT_TEXT);
1869 if (bio_s_out == NULL)
1875 s_dcert_file = NULL;
1877 s_cert_file2 = NULL;
1881 ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1883 ERR_print_errors(bio_err);
1887 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1890 ssl_ctx_security_debug(ctx, sdebug);
1892 if (!config_ctx(cctx, ssl_args, ctx))
1896 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1897 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1899 ERR_print_errors(bio_err);
1903 #ifndef OPENSSL_NO_SCTP
1904 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1905 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1908 if (min_version != 0
1909 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1911 if (max_version != 0
1912 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1915 if (session_id_prefix) {
1916 if (strlen(session_id_prefix) >= 32)
1918 "warning: id_prefix is too long, only one new session will be possible\n");
1919 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1920 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1921 ERR_print_errors(bio_err);
1924 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1927 ssl_ctx_set_excert(ctx, exc);
1930 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1932 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1934 init_session_cache_ctx(ctx);
1936 SSL_CTX_sess_set_cache_size(ctx, 128);
1939 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1943 SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
1946 if (ignore_unexpected_eof)
1947 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1948 #ifndef OPENSSL_NO_KTLS
1950 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
1951 if (use_zc_sendfile)
1952 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE);
1955 if (max_send_fragment > 0
1956 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1957 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1958 prog, max_send_fragment);
1962 if (split_send_fragment > 0
1963 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1964 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1965 prog, split_send_fragment);
1968 if (max_pipelines > 0
1969 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1970 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1971 prog, max_pipelines);
1975 if (read_buf_len > 0) {
1976 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1978 #ifndef OPENSSL_NO_SRTP
1979 if (srtp_profiles != NULL) {
1980 /* Returns 0 on success! */
1981 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1982 BIO_printf(bio_err, "Error setting SRTP profile\n");
1983 ERR_print_errors(bio_err);
1989 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1990 CAstore, noCAstore)) {
1991 ERR_print_errors(bio_err);
1994 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1995 BIO_printf(bio_err, "Error setting verify params\n");
1996 ERR_print_errors(bio_err);
2000 ssl_ctx_add_crls(ctx, crls, 0);
2002 if (!ssl_load_stores(ctx,
2003 vfyCApath, vfyCAfile, vfyCAstore,
2004 chCApath, chCAfile, chCAstore,
2005 crls, crl_download)) {
2006 BIO_printf(bio_err, "Error loading store locations\n");
2007 ERR_print_errors(bio_err);
2012 ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
2014 ERR_print_errors(bio_err);
2020 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
2023 ssl_ctx_security_debug(ctx2, sdebug);
2025 if (session_id_prefix) {
2026 if (strlen(session_id_prefix) >= 32)
2028 "warning: id_prefix is too long, only one new session will be possible\n");
2029 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
2030 BIO_printf(bio_err, "error setting 'id_prefix'\n");
2031 ERR_print_errors(bio_err);
2034 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
2037 ssl_ctx_set_excert(ctx2, exc);
2040 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
2043 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
2045 init_session_cache_ctx(ctx2);
2047 SSL_CTX_sess_set_cache_size(ctx2, 128);
2050 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
2052 if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath,
2053 noCApath, CAstore, noCAstore)) {
2054 ERR_print_errors(bio_err);
2057 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
2058 BIO_printf(bio_err, "Error setting verify params\n");
2059 ERR_print_errors(bio_err);
2063 ssl_ctx_add_crls(ctx2, crls, 0);
2064 if (!config_ctx(cctx, ssl_args, ctx2))
2067 #ifndef OPENSSL_NO_NEXTPROTONEG
2068 if (next_proto.data)
2069 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
2073 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
2076 EVP_PKEY *dhpkey = NULL;
2079 dhpkey = load_keyparams(dhfile, FORMAT_UNDEF, 0, "DH", "DH parameters");
2080 else if (s_cert_file != NULL)
2081 dhpkey = load_keyparams_suppress(s_cert_file, FORMAT_UNDEF, 0, "DH",
2082 "DH parameters", 1);
2084 if (dhpkey != NULL) {
2085 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2087 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
2089 (void)BIO_flush(bio_s_out);
2091 if (dhpkey == NULL) {
2092 SSL_CTX_set_dh_auto(ctx, 1);
2095 * We need 2 references: one for use by ctx and one for use by
2098 if (!EVP_PKEY_up_ref(dhpkey)) {
2099 EVP_PKEY_free(dhpkey);
2102 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) {
2103 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2104 ERR_print_errors(bio_err);
2105 /* Free 2 references */
2106 EVP_PKEY_free(dhpkey);
2107 EVP_PKEY_free(dhpkey);
2113 if (dhfile != NULL) {
2114 EVP_PKEY *dhpkey2 = load_keyparams_suppress(s_cert_file2,
2117 "DH parameters", 1);
2119 if (dhpkey2 != NULL) {
2120 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2121 (void)BIO_flush(bio_s_out);
2123 EVP_PKEY_free(dhpkey);
2127 if (dhpkey == NULL) {
2128 SSL_CTX_set_dh_auto(ctx2, 1);
2129 } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) {
2130 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2131 ERR_print_errors(bio_err);
2132 EVP_PKEY_free(dhpkey);
2137 EVP_PKEY_free(dhpkey);
2140 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
2143 if (s_serverinfo_file != NULL
2144 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
2145 ERR_print_errors(bio_err);
2150 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
2153 if (s_dcert != NULL) {
2154 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
2158 if (no_resume_ephemeral) {
2159 SSL_CTX_set_not_resumable_session_callback(ctx,
2160 not_resumable_sess_cb);
2163 SSL_CTX_set_not_resumable_session_callback(ctx2,
2164 not_resumable_sess_cb);
2166 #ifndef OPENSSL_NO_PSK
2167 if (psk_key != NULL) {
2169 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
2170 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
2173 if (psk_identity_hint != NULL) {
2174 if (min_version == TLS1_3_VERSION) {
2175 BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n");
2177 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
2178 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
2179 ERR_print_errors(bio_err);
2185 if (psksessf != NULL) {
2186 BIO *stmp = BIO_new_file(psksessf, "r");
2189 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
2190 ERR_print_errors(bio_err);
2193 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2195 if (psksess == NULL) {
2196 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
2197 ERR_print_errors(bio_err);
2203 if (psk_key != NULL || psksess != NULL)
2204 SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb);
2206 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
2207 if (!SSL_CTX_set_session_id_context(ctx,
2208 (void *)&s_server_session_id_context,
2209 sizeof(s_server_session_id_context))) {
2210 BIO_printf(bio_err, "error setting session id context\n");
2211 ERR_print_errors(bio_err);
2215 /* Set DTLS cookie generation and verification callbacks */
2216 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
2217 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
2219 /* Set TLS1.3 cookie generation and verification callbacks */
2220 SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback);
2221 SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback);
2224 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
2225 if (!SSL_CTX_set_session_id_context(ctx2,
2226 (void *)&s_server_session_id_context,
2227 sizeof(s_server_session_id_context))) {
2228 BIO_printf(bio_err, "error setting session id context\n");
2229 ERR_print_errors(bio_err);
2232 tlsextcbp.biodebug = bio_s_out;
2233 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
2234 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
2235 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2236 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2239 #ifndef OPENSSL_NO_SRP
2240 if (srp_verifier_file != NULL) {
2241 if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed,
2246 if (CAfile != NULL) {
2247 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2250 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2252 #ifndef OPENSSL_NO_OCSP
2253 if (s_tlsextstatus) {
2254 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2255 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2257 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2258 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2262 if (set_keylog_file(ctx, keylog_file))
2265 if (max_early_data >= 0)
2266 SSL_CTX_set_max_early_data(ctx, max_early_data);
2267 if (recv_max_early_data >= 0)
2268 SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data);
2271 BIO_printf(bio_s_out, "Compressing certificates\n");
2272 if (!SSL_CTX_compress_certs(ctx, 0))
2273 BIO_printf(bio_s_out, "Error compressing certs on ctx\n");
2274 if (ctx2 != NULL && !SSL_CTX_compress_certs(ctx2, 0))
2275 BIO_printf(bio_s_out, "Error compressing certs on ctx2\n");
2279 server_cb = rev_body;
2281 server_cb = www_body;
2283 server_cb = sv_body;
2285 if (socket_family == AF_UNIX
2286 && unlink_unix_path)
2290 BIO_printf(bio_s_out, "Listening for TFO\n");
2291 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2292 server_cb, context, naccept, bio_s_out, tfo);
2293 print_stats(bio_s_out, ctx);
2297 SSL_SESSION_free(psksess);
2298 set_keylog_file(NULL, NULL);
2300 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2302 EVP_PKEY_free(s_key);
2303 EVP_PKEY_free(s_dkey);
2304 OSSL_STACK_OF_X509_free(s_chain);
2305 OSSL_STACK_OF_X509_free(s_dchain);
2307 OPENSSL_free(dpass);
2310 X509_VERIFY_PARAM_free(vpm);
2312 OPENSSL_free(tlscstatp.host);
2313 OPENSSL_free(tlscstatp.port);
2314 OPENSSL_free(tlscstatp.path);
2317 EVP_PKEY_free(s_key2);
2318 #ifndef OPENSSL_NO_NEXTPROTONEG
2319 OPENSSL_free(next_proto.data);
2321 OPENSSL_free(alpn_ctx.data);
2322 ssl_excert_free(exc);
2323 sk_OPENSSL_STRING_free(ssl_args);
2324 SSL_CONF_CTX_free(cctx);
2325 release_engine(engine);
2326 BIO_free(bio_s_out);
2328 BIO_free(bio_s_msg);
2330 #ifdef CHARSET_EBCDIC
2331 BIO_meth_free(methods_ebcdic);
2336 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2338 BIO_printf(bio, "%4ld items in the session cache\n",
2339 SSL_CTX_sess_number(ssl_ctx));
2340 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2341 SSL_CTX_sess_connect(ssl_ctx));
2342 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2343 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2344 BIO_printf(bio, "%4ld client connects that finished\n",
2345 SSL_CTX_sess_connect_good(ssl_ctx));
2346 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2347 SSL_CTX_sess_accept(ssl_ctx));
2348 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2349 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2350 BIO_printf(bio, "%4ld server accepts that finished\n",
2351 SSL_CTX_sess_accept_good(ssl_ctx));
2352 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2353 BIO_printf(bio, "%4ld session cache misses\n",
2354 SSL_CTX_sess_misses(ssl_ctx));
2355 BIO_printf(bio, "%4ld session cache timeouts\n",
2356 SSL_CTX_sess_timeouts(ssl_ctx));
2357 BIO_printf(bio, "%4ld callback cache hits\n",
2358 SSL_CTX_sess_cb_hits(ssl_ctx));
2359 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2360 SSL_CTX_sess_cache_full(ssl_ctx),
2361 SSL_CTX_sess_get_cache_size(ssl_ctx));
2364 static long int count_reads_callback(BIO *bio, int cmd, const char *argp, size_t len,
2365 int argi, long argl, int ret, size_t *processed)
2367 unsigned int *p_counter = (unsigned int *)BIO_get_callback_arg(bio);
2370 case BIO_CB_READ: /* No break here */
2372 if (p_counter != NULL)
2380 BIO_set_callback_arg(bio, (char *)bio_s_out);
2381 ret = (int)bio_dump_callback(bio, cmd, argp, len, argi, argl, ret, processed);
2382 BIO_set_callback_arg(bio, (char *)p_counter);
2388 static int sv_body(int s, int stype, int prot, unsigned char *context)
2397 struct timeval timeout;
2398 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
2399 struct timeval *timeoutp;
2401 #ifndef OPENSSL_NO_DTLS
2402 # ifndef OPENSSL_NO_SCTP
2403 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2405 int isdtls = (stype == SOCK_DGRAM);
2409 buf = app_malloc(bufsize, "server buffer");
2411 if (!BIO_socket_nbio(s, 1))
2412 ERR_print_errors(bio_err);
2414 BIO_printf(bio_err, "Turned on non blocking io\n");
2423 if (s_tlsextdebug) {
2424 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2425 SSL_set_tlsext_debug_arg(con, bio_s_out);
2429 && !SSL_set_session_id_context(con, context,
2430 strlen((char *)context))) {
2431 BIO_printf(bio_err, "Error setting session id context\n");
2436 if (!SSL_clear(con)) {
2437 BIO_printf(bio_err, "Error clearing SSL connection\n");
2441 #ifndef OPENSSL_NO_DTLS
2443 # ifndef OPENSSL_NO_SCTP
2444 if (prot == IPPROTO_SCTP)
2445 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2448 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2450 BIO_printf(bio_err, "Unable to create BIO\n");
2451 ERR_print_errors(bio_err);
2455 if (enable_timeouts) {
2457 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2458 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2461 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2462 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2466 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2467 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2468 DTLS_get_link_min_mtu(con));
2473 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2474 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2475 BIO_printf(bio_err, "Failed to set MTU\n");
2481 /* want to do MTU discovery */
2482 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2484 # ifndef OPENSSL_NO_SCTP
2485 if (prot != IPPROTO_SCTP)
2487 /* Turn on cookie exchange. Not necessary for SCTP */
2488 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2491 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2494 BIO_printf(bio_err, "Unable to create BIO\n");
2495 ERR_print_errors(bio_err);
2502 test = BIO_new(BIO_f_nbio_test());
2504 BIO_printf(bio_err, "Unable to create BIO\n");
2509 sbio = BIO_push(test, sbio);
2512 SSL_set_bio(con, sbio, sbio);
2513 SSL_set_accept_state(con);
2514 /* SSL_set_fd(con,s); */
2516 BIO_set_callback_ex(SSL_get_rbio(con), count_reads_callback);
2518 #ifndef OPENSSL_NO_SSL_TRACE
2520 SSL_set_msg_callback(con, SSL_trace);
2523 SSL_set_msg_callback(con, msg_cb);
2524 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2527 if (s_tlsextdebug) {
2528 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2529 SSL_set_tlsext_debug_arg(con, bio_s_out);
2533 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2536 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2538 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2539 if (edret != SSL_READ_EARLY_DATA_ERROR)
2542 switch (SSL_get_error(con, 0)) {
2543 case SSL_ERROR_WANT_WRITE:
2544 case SSL_ERROR_WANT_ASYNC:
2545 case SSL_ERROR_WANT_READ:
2546 /* Just keep trying - busy waiting */
2549 BIO_printf(bio_err, "Error reading early data\n");
2550 ERR_print_errors(bio_err);
2554 if (readbytes > 0) {
2556 BIO_printf(bio_s_out, "Early data received:\n");
2559 raw_write_stdout(buf, (unsigned int)readbytes);
2560 (void)BIO_flush(bio_s_out);
2564 if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT)
2565 BIO_printf(bio_s_out, "No early data received\n");
2567 BIO_printf(bio_s_out, "Early data was rejected\n");
2569 BIO_printf(bio_s_out, "\nEnd of early data\n");
2571 if (SSL_is_init_finished(con))
2572 print_connection_info(con);
2575 if (fileno_stdin() > s)
2576 width = fileno_stdin() + 1;
2580 int read_from_terminal;
2581 int read_from_sslcon;
2583 read_from_terminal = 0;
2584 read_from_sslcon = SSL_has_pending(con)
2585 || (async && SSL_waiting_for_async(con));
2587 if (!read_from_sslcon) {
2589 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2590 openssl_fdset(fileno_stdin(), &readfds);
2592 openssl_fdset(s, &readfds);
2594 * Note: under VMS with SOCKETSHR the second parameter is
2595 * currently of type (int *) whereas under other systems it is
2596 * (void *) if you don't have a cast it will choke the compiler:
2597 * if you do have a cast then you can either go for (int *) or
2600 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2602 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2603 * only on sockets. As a workaround we timeout the select every
2604 * second and check for any keypress. In a proper Windows
2605 * application we wouldn't do this because it is inefficient.
2608 timeout.tv_usec = 0;
2609 i = select(width, (void *)&readfds, NULL, NULL, &timeout);
2610 if (has_stdin_waiting())
2611 read_from_terminal = 1;
2612 if ((i < 0) || (!i && !read_from_terminal))
2615 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2616 timeoutp = &timeout;
2620 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2622 if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
2623 BIO_printf(bio_err, "TIMEOUT occurred\n");
2627 if (FD_ISSET(fileno_stdin(), &readfds))
2628 read_from_terminal = 1;
2630 if (FD_ISSET(s, &readfds))
2631 read_from_sslcon = 1;
2633 if (read_from_terminal) {
2637 i = raw_read_stdin(buf, bufsize / 2);
2639 /* both loops are skipped when i <= 0 */
2640 for (j = 0; j < i; j++)
2643 for (j = i - 1; j >= 0; j--) {
2644 buf[j + lf_num] = buf[j];
2645 if (buf[j] == '\n') {
2648 buf[j + lf_num] = '\r';
2651 assert(lf_num == 0);
2653 i = raw_read_stdin(buf, bufsize);
2656 if (!s_quiet && !s_brief) {
2657 if ((i <= 0) || (buf[0] == 'Q')) {
2658 BIO_printf(bio_s_out, "DONE\n");
2659 (void)BIO_flush(bio_s_out);
2661 close_accept_socket();
2665 if ((i <= 0) || (buf[0] == 'q')) {
2666 BIO_printf(bio_s_out, "DONE\n");
2667 (void)BIO_flush(bio_s_out);
2668 if (SSL_version(con) != DTLS1_VERSION)
2671 * close_accept_socket(); ret= -11;
2675 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2676 SSL_renegotiate(con);
2677 i = SSL_do_handshake(con);
2678 printf("SSL_do_handshake -> %d\n", i);
2682 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2684 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2686 SSL_renegotiate(con);
2687 i = SSL_do_handshake(con);
2688 printf("SSL_do_handshake -> %d\n", i);
2692 if ((buf[0] == 'K' || buf[0] == 'k')
2693 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2694 SSL_key_update(con, buf[0] == 'K' ?
2695 SSL_KEY_UPDATE_REQUESTED
2696 : SSL_KEY_UPDATE_NOT_REQUESTED);
2697 i = SSL_do_handshake(con);
2698 printf("SSL_do_handshake -> %d\n", i);
2702 if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2703 SSL_set_verify(con, SSL_VERIFY_PEER, NULL);
2704 i = SSL_verify_client_post_handshake(con);
2706 printf("Failed to initiate request\n");
2707 ERR_print_errors(bio_err);
2709 i = SSL_do_handshake(con);
2710 printf("SSL_do_handshake -> %d\n", i);
2715 if (buf[0] == 'P') {
2716 static const char str[] = "Lets print some clear text\n";
2717 BIO_write(SSL_get_wbio(con), str, sizeof(str) -1);
2719 if (buf[0] == 'S') {
2720 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2723 #ifdef CHARSET_EBCDIC
2724 ebcdic2ascii(buf, buf, i);
2728 /* should do a select for the write */
2731 if (++count == 100) {
2733 SSL_renegotiate(con);
2736 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2737 #ifndef OPENSSL_NO_SRP
2738 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2739 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2741 lookup_srp_user(&srp_callback_parm, bio_s_out);
2743 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2746 switch (SSL_get_error(con, k)) {
2747 case SSL_ERROR_NONE:
2749 case SSL_ERROR_WANT_ASYNC:
2750 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2751 (void)BIO_flush(bio_s_out);
2752 wait_for_async(con);
2754 case SSL_ERROR_WANT_WRITE:
2755 case SSL_ERROR_WANT_READ:
2756 case SSL_ERROR_WANT_X509_LOOKUP:
2757 BIO_printf(bio_s_out, "Write BLOCK\n");
2758 (void)BIO_flush(bio_s_out);
2760 case SSL_ERROR_WANT_ASYNC_JOB:
2762 * This shouldn't ever happen in s_server. Treat as an error
2764 case SSL_ERROR_SYSCALL:
2766 BIO_printf(bio_s_out, "ERROR\n");
2767 (void)BIO_flush(bio_s_out);
2768 ERR_print_errors(bio_err);
2772 case SSL_ERROR_ZERO_RETURN:
2773 BIO_printf(bio_s_out, "DONE\n");
2774 (void)BIO_flush(bio_s_out);
2786 if (read_from_sslcon) {
2788 * init_ssl_connection handles all async events itself so if we're
2789 * waiting for async then we shouldn't go back into
2790 * init_ssl_connection
2792 if ((!async || !SSL_waiting_for_async(con))
2793 && !SSL_is_init_finished(con)) {
2795 * Count number of reads during init_ssl_connection.
2796 * It helps us to distinguish configuration errors from errors
2797 * caused by a client.
2799 unsigned int read_counter = 0;
2801 BIO_set_callback_arg(SSL_get_rbio(con), (char *)&read_counter);
2802 i = init_ssl_connection(con);
2803 BIO_set_callback_arg(SSL_get_rbio(con), NULL);
2806 * If initialization fails without reads, then
2807 * there was a fatal error in configuration.
2809 if (i <= 0 && read_counter == 0) {
2816 } else if (i == 0) {
2822 i = SSL_read(con, (char *)buf, bufsize);
2823 #ifndef OPENSSL_NO_SRP
2824 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2825 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2827 lookup_srp_user(&srp_callback_parm, bio_s_out);
2829 i = SSL_read(con, (char *)buf, bufsize);
2832 switch (SSL_get_error(con, i)) {
2833 case SSL_ERROR_NONE:
2834 #ifdef CHARSET_EBCDIC
2835 ascii2ebcdic(buf, buf, i);
2837 raw_write_stdout(buf, (unsigned int)i);
2838 (void)BIO_flush(bio_s_out);
2839 if (SSL_has_pending(con))
2842 case SSL_ERROR_WANT_ASYNC:
2843 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2844 (void)BIO_flush(bio_s_out);
2845 wait_for_async(con);
2847 case SSL_ERROR_WANT_WRITE:
2848 case SSL_ERROR_WANT_READ:
2849 BIO_printf(bio_s_out, "Read BLOCK\n");
2850 (void)BIO_flush(bio_s_out);
2852 case SSL_ERROR_WANT_ASYNC_JOB:
2854 * This shouldn't ever happen in s_server. Treat as an error
2856 case SSL_ERROR_SYSCALL:
2858 BIO_printf(bio_s_out, "ERROR\n");
2859 (void)BIO_flush(bio_s_out);
2860 ERR_print_errors(bio_err);
2863 case SSL_ERROR_ZERO_RETURN:
2864 BIO_printf(bio_s_out, "DONE\n");
2865 (void)BIO_flush(bio_s_out);
2874 BIO_printf(bio_s_out, "shutting down SSL\n");
2875 do_ssl_shutdown(con);
2878 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2879 OPENSSL_clear_free(buf, bufsize);
2883 static void close_accept_socket(void)
2885 BIO_printf(bio_err, "shutdown accept socket\n");
2886 if (accept_socket >= 0) {
2887 BIO_closesocket(accept_socket);
2891 static int is_retryable(SSL *con, int i)
2893 int err = SSL_get_error(con, i);
2895 /* If it's not a fatal error, it must be retryable */
2896 return (err != SSL_ERROR_SSL)
2897 && (err != SSL_ERROR_SYSCALL)
2898 && (err != SSL_ERROR_ZERO_RETURN);
2901 static int init_ssl_connection(SSL *con)
2907 if (dtlslisten || stateless) {
2908 BIO_ADDR *client = NULL;
2911 if ((client = BIO_ADDR_new()) == NULL) {
2912 BIO_printf(bio_err, "ERROR - memory\n");
2915 i = DTLSv1_listen(con, client);
2917 i = SSL_stateless(con);
2924 wbio = SSL_get_wbio(con);
2926 BIO_get_fd(wbio, &fd);
2929 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2930 BIO_printf(bio_err, "ERROR - unable to connect\n");
2931 BIO_ADDR_free(client);
2935 (void)BIO_ctrl_set_connected(wbio, client);
2936 BIO_ADDR_free(client);
2941 i = SSL_accept(con);
2943 BIO_ADDR_free(client);
2947 i = SSL_accept(con);
2950 retry = is_retryable(con, i);
2951 #ifdef CERT_CB_TEST_RETRY
2954 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2955 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2957 "LOOKUP from certificate callback during accept\n");
2958 i = SSL_accept(con);
2960 retry = is_retryable(con, i);
2965 #ifndef OPENSSL_NO_SRP
2967 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2968 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2969 srp_callback_parm.login);
2971 lookup_srp_user(&srp_callback_parm, bio_s_out);
2973 i = SSL_accept(con);
2975 retry = is_retryable(con, i);
2978 } while (i < 0 && SSL_waiting_for_async(con));
2982 if (((dtlslisten || stateless) && i == 0)
2983 || (!dtlslisten && !stateless && retry)) {
2984 BIO_printf(bio_s_out, "DELAY\n");
2988 BIO_printf(bio_err, "ERROR\n");
2990 verify_err = SSL_get_verify_result(con);
2991 if (verify_err != X509_V_OK) {
2992 BIO_printf(bio_err, "verify error:%s\n",
2993 X509_verify_cert_error_string(verify_err));
2995 /* Always print any error messages */
2996 ERR_print_errors(bio_err);
3000 print_connection_info(con);
3004 static void print_connection_info(SSL *con)
3009 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3010 const unsigned char *next_proto_neg;
3011 unsigned next_proto_neg_len;
3013 unsigned char *exportedkeymat;
3017 print_ssl_summary(con);
3019 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
3021 peer = SSL_get0_peer_certificate(con);
3023 BIO_printf(bio_s_out, "Client certificate\n");
3024 PEM_write_bio_X509(bio_s_out, peer);
3025 dump_cert_text(bio_s_out, peer);
3029 if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
3030 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
3031 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
3032 ssl_print_sigalgs(bio_s_out, con);
3033 #ifndef OPENSSL_NO_EC
3034 ssl_print_point_formats(bio_s_out, con);
3035 ssl_print_groups(bio_s_out, con, 0);
3037 print_ca_names(bio_s_out, con);
3038 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
3040 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3041 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
3042 if (next_proto_neg) {
3043 BIO_printf(bio_s_out, "NEXTPROTO is ");
3044 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
3045 BIO_printf(bio_s_out, "\n");
3048 #ifndef OPENSSL_NO_SRTP
3050 SRTP_PROTECTION_PROFILE *srtp_profile
3051 = SSL_get_selected_srtp_profile(con);
3054 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
3055 srtp_profile->name);
3058 if (SSL_session_reused(con))
3059 BIO_printf(bio_s_out, "Reused session-id\n");
3061 ssl_print_secure_renegotiation_notes(bio_s_out, con);
3063 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
3064 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
3066 if (keymatexportlabel != NULL) {
3067 BIO_printf(bio_s_out, "Keying material exporter:\n");
3068 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
3069 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
3070 exportedkeymat = app_malloc(keymatexportlen, "export key");
3071 if (SSL_export_keying_material(con, exportedkeymat,
3074 strlen(keymatexportlabel),
3076 BIO_printf(bio_s_out, " Error\n");
3078 BIO_printf(bio_s_out, " Keying material: ");
3079 for (i = 0; i < keymatexportlen; i++)
3080 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
3081 BIO_printf(bio_s_out, "\n");
3083 OPENSSL_free(exportedkeymat);
3085 #ifndef OPENSSL_NO_KTLS
3086 if (BIO_get_ktls_send(SSL_get_wbio(con)))
3087 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3088 if (BIO_get_ktls_recv(SSL_get_rbio(con)))
3089 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3092 (void)BIO_flush(bio_s_out);
3095 static int www_body(int s, int stype, int prot, unsigned char *context)
3097 char *buf = NULL, *p;
3101 const SSL_CIPHER *c;
3102 BIO *io, *ssl_bio, *sbio;
3104 int total_bytes = 0;
3107 #ifndef OPENSSL_NO_KTLS
3108 int use_sendfile_for_req = use_sendfile;
3112 #ifdef CHARSET_EBCDIC
3116 /* Set width for a select call if needed */
3119 /* as we use BIO_gets(), and it always null terminates data, we need
3120 * to allocate 1 byte longer buffer to fit the full 2^14 byte record */
3121 p = buf = app_malloc(bufsize + 1, "server www buffer");
3122 io = BIO_new(BIO_f_buffer());
3123 ssl_bio = BIO_new(BIO_f_ssl());
3124 if ((io == NULL) || (ssl_bio == NULL))
3128 if (!BIO_socket_nbio(s, 1))
3129 ERR_print_errors(bio_err);
3131 BIO_printf(bio_err, "Turned on non blocking io\n");
3134 /* lets make the output buffer a reasonable size */
3135 if (BIO_set_write_buffer_size(io, bufsize) <= 0)
3138 if ((con = SSL_new(ctx)) == NULL)
3141 if (s_tlsextdebug) {
3142 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3143 SSL_set_tlsext_debug_arg(con, bio_s_out);
3147 && !SSL_set_session_id_context(con, context,
3148 strlen((char *)context))) {
3153 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3162 test = BIO_new(BIO_f_nbio_test());
3169 sbio = BIO_push(test, sbio);
3171 SSL_set_bio(con, sbio, sbio);
3172 SSL_set_accept_state(con);
3174 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3175 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3176 BIO_push(io, ssl_bio);
3178 #ifdef CHARSET_EBCDIC
3179 filter = BIO_new(BIO_f_ebcdic_filter());
3183 io = BIO_push(filter, io);
3187 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3188 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3191 #ifndef OPENSSL_NO_SSL_TRACE
3193 SSL_set_msg_callback(con, SSL_trace);
3196 SSL_set_msg_callback(con, msg_cb);
3197 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3201 i = BIO_gets(io, buf, bufsize + 1);
3202 if (i < 0) { /* error */
3203 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
3205 ERR_print_errors(bio_err);
3208 BIO_printf(bio_s_out, "read R BLOCK\n");
3209 #ifndef OPENSSL_NO_SRP
3210 if (BIO_should_io_special(io)
3211 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3212 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3214 lookup_srp_user(&srp_callback_parm, bio_s_out);
3222 } else if (i == 0) { /* end of input */
3227 /* else we have data */
3228 if ((www == 1 && HAS_PREFIX(buf, "GET "))
3229 || (www == 2 && HAS_PREFIX(buf, "GET /stats "))) {
3231 STACK_OF(SSL_CIPHER) *sk;
3232 static const char *space = " ";
3234 if (www == 1 && HAS_PREFIX(buf, "GET /reneg")) {
3235 if (HAS_PREFIX(buf, "GET /renegcert"))
3237 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
3239 i = SSL_renegotiate(con);
3240 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
3241 /* Send the HelloRequest */
3242 i = SSL_do_handshake(con);
3244 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
3245 SSL_get_error(con, i));
3246 ERR_print_errors(bio_err);
3249 /* Wait for a ClientHello to come back */
3251 openssl_fdset(s, &readfds);
3252 i = select(width, (void *)&readfds, NULL, NULL, NULL);
3253 if (i <= 0 || !FD_ISSET(s, &readfds)) {
3254 BIO_printf(bio_s_out,
3255 "Error waiting for client response\n");
3256 ERR_print_errors(bio_err);
3260 * We're not actually expecting any data here and we ignore
3261 * any that is sent. This is just to force the handshake that
3262 * we're expecting to come from the client. If they haven't
3263 * sent one there's not much we can do.
3265 BIO_gets(io, buf, bufsize + 1);
3269 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3270 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
3271 BIO_puts(io, "<pre>\n");
3272 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
3274 for (i = 0; i < local_argc; i++) {
3277 for (myp = local_argv[i]; *myp; myp++)
3280 BIO_puts(io, "<");
3283 BIO_puts(io, ">");
3286 BIO_puts(io, "&");
3289 BIO_write(io, myp, 1);
3292 BIO_write(io, " ", 1);
3296 ssl_print_secure_renegotiation_notes(io, con);
3299 * The following is evil and should not really be done
3301 BIO_printf(io, "Ciphers supported in s_server binary\n");
3302 sk = SSL_get_ciphers(con);
3303 j = sk_SSL_CIPHER_num(sk);
3304 for (i = 0; i < j; i++) {
3305 c = sk_SSL_CIPHER_value(sk, i);
3306 BIO_printf(io, "%-11s:%-25s ",
3307 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3308 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3312 p = SSL_get_shared_ciphers(con, buf, bufsize);
3315 "---\nCiphers common between both SSL end points:\n");
3319 BIO_write(io, space, 26 - j);
3322 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3324 BIO_write(io, p, 1);
3331 ssl_print_sigalgs(io, con);
3332 #ifndef OPENSSL_NO_EC
3333 ssl_print_groups(io, con, 0);
3335 print_ca_names(io, con);
3336 BIO_printf(io, (SSL_session_reused(con)
3337 ? "---\nReused, " : "---\nNew, "));
3338 c = SSL_get_current_cipher(con);
3339 BIO_printf(io, "%s, Cipher is %s\n",
3340 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3341 SSL_SESSION_print(io, SSL_get_session(con));
3342 BIO_printf(io, "---\n");
3343 print_stats(io, SSL_get_SSL_CTX(con));
3344 BIO_printf(io, "---\n");
3345 peer = SSL_get0_peer_certificate(con);
3347 BIO_printf(io, "Client certificate\n");
3348 X509_print(io, peer);
3349 PEM_write_bio_X509(io, peer);
3352 BIO_puts(io, "no client certificate available\n");
3354 BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
3356 } else if ((www == 2 || www == 3) && CHECK_AND_SKIP_PREFIX(p, "GET /")) {
3359 static const char *text =
3360 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3363 for (e = p; *e != '\0'; e++) {
3368 /* Windows drive. We treat this the same way as ".." */
3375 dot = (e[0] == '.') ? 2 : 0;
3378 dot = (e[0] == '.') ? 3 : 0;
3381 dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0;
3385 dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0;
3387 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3392 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3399 BIO_printf(io, "'%s' contains '..' or ':'\r\n", p);
3403 if (*p == '/' || *p == '\\') {
3405 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3409 /* if a directory, do the index thang */
3410 if (app_isdir(p) > 0) {
3412 BIO_printf(io, "'%s' is a directory\r\n", p);
3416 opmode = (http_server_binmode == 1) ? "rb" : "r";
3417 if ((file = BIO_new_file(p, opmode)) == NULL) {
3419 BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode);
3420 ERR_print_errors(io);
3425 BIO_printf(bio_err, "FILE:%s\n", p);
3429 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3430 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3431 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3433 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3436 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3439 #ifndef OPENSSL_NO_KTLS
3440 if (use_sendfile_for_req && !BIO_get_ktls_send(SSL_get_wbio(con))) {
3441 BIO_printf(bio_err, "Warning: sendfile requested but KTLS is not available\n");
3442 use_sendfile_for_req = 0;
3444 if (use_sendfile_for_req) {
3451 BIO_get_fp(file, &fp);
3453 if (fstat(fd, &st) < 0) {
3454 BIO_printf(io, "Error fstat '%s'\r\n", p);
3455 ERR_print_errors(io);
3459 filesize = st.st_size;
3460 if (((int)BIO_flush(io)) < 0)
3464 i = SSL_sendfile(con, fd, offset, filesize, 0);
3466 BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p);
3467 ERR_print_errors(io);
3474 if (filesize <= 0) {
3476 BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p);
3485 i = BIO_read(file, buf, bufsize);
3491 BIO_printf(bio_err, "%d\n", i);
3492 if (total_bytes > 3 * 1024) {
3494 BIO_printf(bio_err, "RENEGOTIATE\n");
3495 SSL_renegotiate(con);
3499 for (j = 0; j < i;) {
3503 SSL_renegotiate(con);
3505 k = BIO_write(io, &(buf[j]), i - j);
3507 if (!BIO_should_retry(io)
3508 && !SSL_waiting_for_async(con)) {
3511 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3526 i = (int)BIO_flush(io);
3528 if (!BIO_should_retry(io))
3534 /* make sure we re-use sessions */
3535 do_ssl_shutdown(con);
3544 static int rev_body(int s, int stype, int prot, unsigned char *context)
3550 BIO *io, *ssl_bio, *sbio;
3551 #ifdef CHARSET_EBCDIC
3555 /* as we use BIO_gets(), and it always null terminates data, we need
3556 * to allocate 1 byte longer buffer to fit the full 2^14 byte record */
3557 buf = app_malloc(bufsize + 1, "server rev buffer");
3558 io = BIO_new(BIO_f_buffer());
3559 ssl_bio = BIO_new(BIO_f_ssl());
3560 if ((io == NULL) || (ssl_bio == NULL))
3563 /* lets make the output buffer a reasonable size */
3564 if (BIO_set_write_buffer_size(io, bufsize) <= 0)
3567 if ((con = SSL_new(ctx)) == NULL)
3570 if (s_tlsextdebug) {
3571 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3572 SSL_set_tlsext_debug_arg(con, bio_s_out);
3575 && !SSL_set_session_id_context(con, context,
3576 strlen((char *)context))) {
3578 ERR_print_errors(bio_err);
3582 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3585 ERR_print_errors(bio_err);
3589 SSL_set_bio(con, sbio, sbio);
3590 SSL_set_accept_state(con);
3592 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3593 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3594 BIO_push(io, ssl_bio);
3596 #ifdef CHARSET_EBCDIC
3597 filter = BIO_new(BIO_f_ebcdic_filter());
3601 io = BIO_push(filter, io);
3605 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3606 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3609 #ifndef OPENSSL_NO_SSL_TRACE
3611 SSL_set_msg_callback(con, SSL_trace);
3614 SSL_set_msg_callback(con, msg_cb);
3615 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3619 i = BIO_do_handshake(io);
3622 if (!BIO_should_retry(io)) {
3623 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3624 ERR_print_errors(bio_err);
3627 #ifndef OPENSSL_NO_SRP
3628 if (BIO_should_io_special(io)
3629 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3630 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3632 lookup_srp_user(&srp_callback_parm, bio_s_out);
3638 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3639 print_ssl_summary(con);
3642 i = BIO_gets(io, buf, bufsize + 1);
3643 if (i < 0) { /* error */
3644 if (!BIO_should_retry(io)) {
3646 ERR_print_errors(bio_err);
3649 BIO_printf(bio_s_out, "read R BLOCK\n");
3650 #ifndef OPENSSL_NO_SRP
3651 if (BIO_should_io_special(io)
3652 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3653 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3655 lookup_srp_user(&srp_callback_parm, bio_s_out);
3663 } else if (i == 0) { /* end of input */
3665 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3668 char *p = buf + i - 1;
3669 while (i && (*p == '\n' || *p == '\r')) {
3673 if (!s_ign_eof && i == 5 && HAS_PREFIX(buf, "CLOSE")) {
3675 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3678 BUF_reverse((unsigned char *)buf, NULL, i);
3680 BIO_write(io, buf, i + 1);
3685 if (!BIO_should_retry(io))
3691 /* make sure we re-use sessions */
3692 do_ssl_shutdown(con);
3702 #define MAX_SESSION_ID_ATTEMPTS 10
3703 static int generate_session_id(SSL *ssl, unsigned char *id,
3704 unsigned int *id_len)
3706 unsigned int count = 0;
3707 unsigned int session_id_prefix_len = strlen(session_id_prefix);
3710 if (RAND_bytes(id, *id_len) <= 0)
3713 * Prefix the session_id with the required prefix. NB: If our prefix
3714 * is too long, clip it - but there will be worse effects anyway, eg.
3715 * the server could only possibly create 1 session ID (ie. the
3716 * prefix!) so all future session negotiations will fail due to
3719 memcpy(id, session_id_prefix,
3720 (session_id_prefix_len < *id_len) ?
3721 session_id_prefix_len : *id_len);
3723 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3724 (++count < MAX_SESSION_ID_ATTEMPTS));
3725 if (count >= MAX_SESSION_ID_ATTEMPTS)
3731 * By default s_server uses an in-memory cache which caches SSL_SESSION
3732 * structures without any serialization. This hides some bugs which only
3733 * become apparent in deployed servers. By implementing a basic external
3734 * session cache some issues can be debugged using s_server.
3737 typedef struct simple_ssl_session_st {
3742 struct simple_ssl_session_st *next;
3743 } simple_ssl_session;
3745 static simple_ssl_session *first = NULL;
3747 static int add_session(SSL *ssl, SSL_SESSION *session)
3749 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3752 SSL_SESSION_get_id(session, &sess->idlen);
3753 sess->derlen = i2d_SSL_SESSION(session, NULL);
3754 if (sess->derlen < 0) {
3755 BIO_printf(bio_err, "Error encoding session\n");
3760 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3761 sess->der = app_malloc(sess->derlen, "get session buffer");
3763 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3764 OPENSSL_free(sess->id);
3765 OPENSSL_free(sess->der);
3771 /* Assume it still works. */
3772 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3773 BIO_printf(bio_err, "Unexpected session encoding length\n");
3774 OPENSSL_free(sess->id);
3775 OPENSSL_free(sess->der);
3782 BIO_printf(bio_err, "New session added to external cache\n");
3786 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3789 simple_ssl_session *sess;
3791 for (sess = first; sess; sess = sess->next) {
3792 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3793 const unsigned char *p = sess->der;
3794 BIO_printf(bio_err, "Lookup session: cache hit\n");
3795 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3798 BIO_printf(bio_err, "Lookup session: cache miss\n");
3802 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3804 simple_ssl_session *sess, *prev = NULL;
3805 const unsigned char *id;
3807 id = SSL_SESSION_get_id(session, &idlen);
3808 for (sess = first; sess; sess = sess->next) {
3809 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3811 prev->next = sess->next;
3814 OPENSSL_free(sess->id);
3815 OPENSSL_free(sess->der);
3823 static void init_session_cache_ctx(SSL_CTX *sctx)
3825 SSL_CTX_set_session_cache_mode(sctx,
3826 SSL_SESS_CACHE_NO_INTERNAL |
3827 SSL_SESS_CACHE_SERVER);
3828 SSL_CTX_sess_set_new_cb(sctx, add_session);
3829 SSL_CTX_sess_set_get_cb(sctx, get_session);
3830 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3833 static void free_sessions(void)
3835 simple_ssl_session *sess, *tsess;
3836 for (sess = first; sess;) {
3837 OPENSSL_free(sess->id);
3838 OPENSSL_free(sess->der);
3841 OPENSSL_free(tsess);
3846 #endif /* OPENSSL_NO_SOCK */