2 * Copyright 1995-2020 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>
25 #ifndef OPENSSL_NO_SOCK
28 * With IPv6, it looks like Digital has mixed up the proper order of
29 * recursive header file inclusion, resulting in the compiler complaining
30 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
31 * needed to have fileno() declared correctly... So let's define u_int
33 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
35 typedef unsigned int u_int;
38 #include <openssl/bn.h>
41 #include <openssl/err.h>
42 #include <openssl/pem.h>
43 #include <openssl/x509.h>
44 #include <openssl/ssl.h>
45 #include <openssl/rand.h>
46 #include <openssl/ocsp.h>
48 # include <openssl/dh.h>
50 #ifndef OPENSSL_NO_RSA
51 # include <openssl/rsa.h>
53 #ifndef OPENSSL_NO_SRP
54 # include <openssl/srp.h>
59 #include <openssl/ebcdic.h>
61 #include "internal/sockets.h"
63 DEFINE_STACK_OF_STRING()
65 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
66 static int sv_body(int s, int stype, int prot, unsigned char *context);
67 static int www_body(int s, int stype, int prot, unsigned char *context);
68 static int rev_body(int s, int stype, int prot, unsigned char *context);
69 static void close_accept_socket(void);
70 static int init_ssl_connection(SSL *s);
71 static void print_stats(BIO *bp, SSL_CTX *ctx);
72 static int generate_session_id(SSL *ssl, unsigned char *id,
73 unsigned int *id_len);
74 static void init_session_cache_ctx(SSL_CTX *sctx);
75 static void free_sessions(void);
77 static DH *load_dh_param(const char *dhfile);
79 static void print_connection_info(SSL *con);
81 static const int bufsize = 16 * 1024;
82 static int accept_socket = -1;
84 #define TEST_CERT "server.pem"
85 #define TEST_CERT2 "server2.pem"
87 static int s_nbio = 0;
88 static int s_nbio_test = 0;
89 static int s_crlf = 0;
90 static SSL_CTX *ctx = NULL;
91 static SSL_CTX *ctx2 = NULL;
94 static BIO *bio_s_out = NULL;
95 static BIO *bio_s_msg = NULL;
96 static int s_debug = 0;
97 static int s_tlsextdebug = 0;
99 static int s_quiet = 0;
100 static int s_ign_eof = 0;
101 static int s_brief = 0;
103 static char *keymatexportlabel = NULL;
104 static int keymatexportlen = 20;
106 static int async = 0;
108 static int use_sendfile = 0;
110 static const char *session_id_prefix = NULL;
112 #ifndef OPENSSL_NO_DTLS
113 static int enable_timeouts = 0;
114 static long socket_mtu;
118 * We define this but make it always be 0 in no-dtls builds to simplify the
121 static int dtlslisten = 0;
122 static int stateless = 0;
124 static int early_data = 0;
125 static SSL_SESSION *psksess = NULL;
127 static char *psk_identity = "Client_identity";
128 char *psk_key = NULL; /* by default PSK is not used */
130 static char http_server_binmode = 0; /* for now: 0/1 = default/binary */
132 #ifndef OPENSSL_NO_PSK
133 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
135 unsigned int max_psk_len)
141 BIO_printf(bio_s_out, "psk_server_cb\n");
142 if (identity == NULL) {
143 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
147 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
148 (int)strlen(identity), identity);
150 /* here we could lookup the given identity e.g. from a database */
151 if (strcmp(identity, psk_identity) != 0) {
152 BIO_printf(bio_s_out, "PSK warning: client identity not what we expected"
153 " (got '%s' expected '%s')\n", identity, psk_identity);
156 BIO_printf(bio_s_out, "PSK client identity found\n");
159 /* convert the PSK key to binary */
160 key = OPENSSL_hexstr2buf(psk_key, &key_len);
162 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
166 if (key_len > (int)max_psk_len) {
168 "psk buffer of callback is too small (%d) for key (%ld)\n",
169 max_psk_len, key_len);
174 memcpy(psk, key, key_len);
178 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
182 BIO_printf(bio_err, "Error in PSK server callback\n");
183 (void)BIO_flush(bio_err);
184 (void)BIO_flush(bio_s_out);
189 static int psk_find_session_cb(SSL *ssl, const unsigned char *identity,
190 size_t identity_len, SSL_SESSION **sess)
192 SSL_SESSION *tmpsess = NULL;
195 const SSL_CIPHER *cipher = NULL;
197 if (strlen(psk_identity) != identity_len
198 || memcmp(psk_identity, identity, identity_len) != 0) {
203 if (psksess != NULL) {
204 SSL_SESSION_up_ref(psksess);
209 key = OPENSSL_hexstr2buf(psk_key, &key_len);
211 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
216 /* We default to SHA256 */
217 cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id);
218 if (cipher == NULL) {
219 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
224 tmpsess = SSL_SESSION_new();
226 || !SSL_SESSION_set1_master_key(tmpsess, key, key_len)
227 || !SSL_SESSION_set_cipher(tmpsess, cipher)
228 || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) {
238 #ifndef OPENSSL_NO_SRP
239 /* This is a context that we pass to callbacks */
240 typedef struct srpsrvparm_st {
245 static srpsrvparm srp_callback_parm;
248 * This callback pretends to require some asynchronous logic in order to
249 * obtain a verifier. When the callback is called for a new connection we
250 * return with a negative value. This will provoke the accept etc to return
251 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
252 * (which would normally occur after a worker has finished) and we set the
255 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
257 srpsrvparm *p = (srpsrvparm *) arg;
258 int ret = SSL3_AL_FATAL;
260 if (p->login == NULL && p->user == NULL) {
261 p->login = SSL_get_srp_username(s);
262 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
266 if (p->user == NULL) {
267 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
271 if (SSL_set_srp_server_param
272 (s, p->user->N, p->user->g, p->user->s, p->user->v,
273 p->user->info) < 0) {
274 *ad = SSL_AD_INTERNAL_ERROR;
278 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
279 p->login, p->user->info);
280 ret = SSL_ERROR_NONE;
283 SRP_user_pwd_free(p->user);
291 static int local_argc = 0;
292 static char **local_argv;
294 #ifdef CHARSET_EBCDIC
295 static int ebcdic_new(BIO *bi);
296 static int ebcdic_free(BIO *a);
297 static int ebcdic_read(BIO *b, char *out, int outl);
298 static int ebcdic_write(BIO *b, const char *in, int inl);
299 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
300 static int ebcdic_gets(BIO *bp, char *buf, int size);
301 static int ebcdic_puts(BIO *bp, const char *str);
303 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
304 static BIO_METHOD *methods_ebcdic = NULL;
306 /* This struct is "unwarranted chumminess with the compiler." */
312 static const BIO_METHOD *BIO_f_ebcdic_filter()
314 if (methods_ebcdic == NULL) {
315 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
316 "EBCDIC/ASCII filter");
317 if (methods_ebcdic == NULL
318 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
319 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
320 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
321 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
322 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
323 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
324 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
327 return methods_ebcdic;
330 static int ebcdic_new(BIO *bi)
332 EBCDIC_OUTBUFF *wbuf;
334 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
335 wbuf->alloced = 1024;
336 wbuf->buff[0] = '\0';
338 BIO_set_data(bi, wbuf);
343 static int ebcdic_free(BIO *a)
345 EBCDIC_OUTBUFF *wbuf;
349 wbuf = BIO_get_data(a);
351 BIO_set_data(a, NULL);
357 static int ebcdic_read(BIO *b, char *out, int outl)
360 BIO *next = BIO_next(b);
362 if (out == NULL || outl == 0)
367 ret = BIO_read(next, out, outl);
369 ascii2ebcdic(out, out, ret);
373 static int ebcdic_write(BIO *b, const char *in, int inl)
375 EBCDIC_OUTBUFF *wbuf;
376 BIO *next = BIO_next(b);
380 if ((in == NULL) || (inl <= 0))
385 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
387 if (inl > (num = wbuf->alloced)) {
388 num = num + num; /* double the size */
392 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
395 wbuf->buff[0] = '\0';
397 BIO_set_data(b, wbuf);
400 ebcdic2ascii(wbuf->buff, in, inl);
402 ret = BIO_write(next, wbuf->buff, inl);
407 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
410 BIO *next = BIO_next(b);
419 ret = BIO_ctrl(next, cmd, num, ptr);
425 static int ebcdic_gets(BIO *bp, char *buf, int size)
428 BIO *next = BIO_next(bp);
432 /* return(BIO_gets(bp->next_bio,buf,size));*/
433 for (i = 0; i < size - 1; ++i) {
434 ret = ebcdic_read(bp, &buf[i], 1);
437 else if (buf[i] == '\n') {
444 return (ret < 0 && i == 0) ? ret : i;
447 static int ebcdic_puts(BIO *bp, const char *str)
449 if (BIO_next(bp) == NULL)
451 return ebcdic_write(bp, str, strlen(str));
455 /* This is a context that we pass to callbacks */
456 typedef struct tlsextctx_st {
462 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
464 tlsextctx *p = (tlsextctx *) arg;
465 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
467 if (servername != NULL && p->biodebug != NULL) {
468 const char *cp = servername;
471 BIO_printf(p->biodebug, "Hostname in TLS extension: \"");
472 while ((uc = *cp++) != 0)
473 BIO_printf(p->biodebug,
474 (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc);
475 BIO_printf(p->biodebug, "\"\n");
478 if (p->servername == NULL)
479 return SSL_TLSEXT_ERR_NOACK;
481 if (servername != NULL) {
482 if (strcasecmp(servername, p->servername))
483 return p->extension_error;
485 BIO_printf(p->biodebug, "Switching server context.\n");
486 SSL_set_SSL_CTX(s, ctx2);
489 return SSL_TLSEXT_ERR_OK;
492 /* Structure passed to cert status callback */
493 typedef struct tlsextstatusctx_st {
495 /* File to load OCSP Response from (or NULL if no file) */
497 /* Default responder to use */
498 char *host, *path, *port;
503 static tlsextstatusctx tlscstatp = { -1 };
505 #ifndef OPENSSL_NO_OCSP
508 * Helper function to get an OCSP_RESPONSE from a responder. This is a
509 * simplified version. It examines certificates each time and makes one OCSP
510 * responder query for each request. A full version would store details such as
511 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
512 * them until they were considered "expired".
514 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
515 OCSP_RESPONSE **resp)
517 char *host = NULL, *port = NULL, *path = NULL;
519 STACK_OF(OPENSSL_STRING) *aia = NULL;
521 X509_STORE_CTX *inctx = NULL;
523 OCSP_REQUEST *req = NULL;
524 OCSP_CERTID *id = NULL;
525 STACK_OF(X509_EXTENSION) *exts;
526 int ret = SSL_TLSEXT_ERR_NOACK;
529 /* Build up OCSP query from server certificate */
530 x = SSL_get_certificate(s);
531 aia = X509_get1_ocsp(x);
533 if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
534 &host, &port, NULL, &path, &use_ssl)) {
535 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
539 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
540 sk_OPENSSL_STRING_value(aia, 0));
542 if (srctx->host == NULL) {
544 "cert_status: no AIA and no default responder URL\n");
550 use_ssl = srctx->use_ssl;
553 inctx = X509_STORE_CTX_new();
556 if (!X509_STORE_CTX_init(inctx,
557 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
560 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
561 X509_get_issuer_name(x));
563 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
566 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
567 X509_OBJECT_free(obj);
570 req = OCSP_REQUEST_new();
573 if (!OCSP_request_add0_id(req, id))
576 /* Add any extensions to the request */
577 SSL_get_tlsext_status_exts(s, &exts);
578 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
579 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
580 if (!OCSP_REQUEST_add_ext(req, ext, -1))
583 *resp = process_responder(req, host, path, port, use_ssl, NULL,
586 BIO_puts(bio_err, "cert_status: error querying responder\n");
590 ret = SSL_TLSEXT_ERR_OK;
594 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
597 * If we parsed aia we need to free; otherwise they were copied and we
604 X509_email_free(aia);
606 OCSP_CERTID_free(id);
607 OCSP_REQUEST_free(req);
608 X509_STORE_CTX_free(inctx);
613 * Certificate Status callback. This is called when a client includes a
614 * certificate status request extension. The response is either obtained from a
615 * file, or from an OCSP responder.
617 static int cert_status_cb(SSL *s, void *arg)
619 tlsextstatusctx *srctx = arg;
620 OCSP_RESPONSE *resp = NULL;
621 unsigned char *rspder = NULL;
623 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
626 BIO_puts(bio_err, "cert_status: callback called\n");
628 if (srctx->respin != NULL) {
629 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
630 if (derbio == NULL) {
631 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
634 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
637 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
641 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
642 if (ret != SSL_TLSEXT_ERR_OK)
646 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
650 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
651 if (srctx->verbose) {
652 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
653 OCSP_RESPONSE_print(bio_err, resp, 2);
656 ret = SSL_TLSEXT_ERR_OK;
659 if (ret != SSL_TLSEXT_ERR_OK)
660 ERR_print_errors(bio_err);
662 OCSP_RESPONSE_free(resp);
668 #ifndef OPENSSL_NO_NEXTPROTONEG
669 /* This is the context that we pass to next_proto_cb */
670 typedef struct tlsextnextprotoctx_st {
673 } tlsextnextprotoctx;
675 static int next_proto_cb(SSL *s, const unsigned char **data,
676 unsigned int *len, void *arg)
678 tlsextnextprotoctx *next_proto = arg;
680 *data = next_proto->data;
681 *len = next_proto->len;
683 return SSL_TLSEXT_ERR_OK;
685 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
687 /* This the context that we pass to alpn_cb */
688 typedef struct tlsextalpnctx_st {
693 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
694 const unsigned char *in, unsigned int inlen, void *arg)
696 tlsextalpnctx *alpn_ctx = arg;
699 /* We can assume that |in| is syntactically valid. */
701 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
702 for (i = 0; i < inlen;) {
704 BIO_write(bio_s_out, ", ", 2);
705 BIO_write(bio_s_out, &in[i + 1], in[i]);
708 BIO_write(bio_s_out, "\n", 1);
711 if (SSL_select_next_proto
712 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
713 inlen) != OPENSSL_NPN_NEGOTIATED) {
714 return SSL_TLSEXT_ERR_ALERT_FATAL;
718 BIO_printf(bio_s_out, "ALPN protocols selected: ");
719 BIO_write(bio_s_out, *out, *outlen);
720 BIO_write(bio_s_out, "\n", 1);
723 return SSL_TLSEXT_ERR_OK;
726 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
728 /* disable resumption for sessions with forward secure ciphers */
729 return is_forward_secure;
732 typedef enum OPTION_choice {
733 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
734 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
735 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
736 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
737 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
738 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
739 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
740 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
741 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
743 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
744 OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
745 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
746 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
747 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
748 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
749 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK,
750 OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW,
751 OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG,
752 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
753 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
754 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS,
755 OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
756 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE,
757 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
758 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA,
759 OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG,
760 OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF,
768 const OPTIONS s_server_options[] = {
769 OPT_SECTION("General"),
770 {"help", OPT_HELP, '-', "Display this summary"},
771 {"ssl_config", OPT_SSL_CONFIG, 's',
772 "Configure SSL_CTX using the configuration 'val'"},
773 #ifndef OPENSSL_NO_SSL_TRACE
774 {"trace", OPT_TRACE, '-', "trace protocol messages"},
776 #ifndef OPENSSL_NO_ENGINE
777 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
780 OPT_SECTION("Network"),
781 {"port", OPT_PORT, 'p',
782 "TCP/IP port to listen on for connections (default is " PORT ")"},
783 {"accept", OPT_ACCEPT, 's',
784 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
786 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
787 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
789 {"4", OPT_4, '-', "Use IPv4 only"},
790 {"6", OPT_6, '-', "Use IPv6 only"},
792 OPT_SECTION("Identity"),
793 {"context", OPT_CONTEXT, 's', "Set session ID context"},
794 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
795 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
796 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
797 {"no-CAfile", OPT_NOCAFILE, '-',
798 "Do not load the default certificates file"},
799 {"no-CApath", OPT_NOCAPATH, '-',
800 "Do not load certificates from the default certificates directory"},
801 {"no-CAstore", OPT_NOCASTORE, '-',
802 "Do not load certificates from the default certificates store URI"},
803 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
804 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
805 {"Verify", OPT_UPPER_V_VERIFY, 'n',
806 "Turn on peer certificate verification, must have a cert"},
807 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
808 {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT},
809 {"cert2", OPT_CERT2, '<',
810 "Certificate file to use for servername; default " TEST_CERT2},
811 {"certform", OPT_CERTFORM, 'F',
812 "Server certificate file format (PEM/DER/P12); has no effect"},
813 {"cert_chain", OPT_CERT_CHAIN, '<',
814 "Server certificate chain file in PEM format"},
815 {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"},
816 {"serverinfo", OPT_SERVERINFO, 's',
817 "PEM serverinfo file for certificate"},
818 {"key", OPT_KEY, 's',
819 "Private key file to use; default is -cert file or else" TEST_CERT},
820 {"key2", OPT_KEY2, '<',
821 "-Private Key file to use for servername if not in -cert2"},
822 {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"},
823 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
824 {"dcert", OPT_DCERT, '<',
825 "Second server certificate file to use (usually for DSA)"},
826 {"dcertform", OPT_DCERTFORM, 'F',
827 "Second server certificate file format (PEM/DER/P12); has no effect"},
828 {"dcert_chain", OPT_DCERT_CHAIN, '<',
829 "second server certificate chain file in PEM format"},
830 {"dkey", OPT_DKEY, '<',
831 "Second private key file to use (usually for DSA)"},
832 {"dkeyform", OPT_DKEYFORM, 'F',
833 "Second key file format (ENGINE, other values ignored)"},
834 {"dpass", OPT_DPASS, 's', "Second private key and cert file pass phrase source"},
835 {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
836 {"servername", OPT_SERVERNAME, 's',
837 "Servername for HostName TLS extension"},
838 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
839 "mismatch send fatal alert (default warning alert)"},
840 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
841 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
842 {"quiet", OPT_QUIET, '-', "No server output"},
843 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
844 "Disable caching and tickets if ephemeral (EC)DH is used"},
845 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
846 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
847 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
848 "Do not treat lack of close_notify from a peer as an error"},
849 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
850 "Hex dump of all TLS extensions received"},
851 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
852 {"id_prefix", OPT_ID_PREFIX, 's',
853 "Generate SSL/TLS session IDs prefixed by arg"},
854 {"keymatexport", OPT_KEYMATEXPORT, 's',
855 "Export keying material using label"},
856 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
857 "Export len bytes of keying material; default 20"},
858 {"CRL", OPT_CRL, '<', "CRL file to use"},
859 {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"},
860 {"crl_download", OPT_CRL_DOWNLOAD, '-',
861 "Download CRLs from distribution points in certificate CDP entries"},
862 {"chainCAfile", OPT_CHAINCAFILE, '<',
863 "CA file for certificate chain (PEM format)"},
864 {"chainCApath", OPT_CHAINCAPATH, '/',
865 "use dir as certificate store path to build CA certificate chain"},
866 {"chainCAstore", OPT_CHAINCASTORE, ':',
867 "use URI as certificate store to build CA certificate chain"},
868 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
869 "CA file for certificate verification (PEM format)"},
870 {"verifyCApath", OPT_VERIFYCAPATH, '/',
871 "use dir as certificate store path to verify CA certificate"},
872 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
873 "use URI as certificate store to verify CA certificate"},
874 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
875 {"ext_cache", OPT_EXT_CACHE, '-',
876 "Disable internal cache, setup and use external cache"},
877 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
878 "Close connection on verification error"},
879 {"verify_quiet", OPT_VERIFY_QUIET, '-',
880 "No verify output except verify errors"},
881 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
882 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
884 #ifndef OPENSSL_NO_OCSP
886 {"status", OPT_STATUS, '-', "Request certificate status from server"},
887 {"status_verbose", OPT_STATUS_VERBOSE, '-',
888 "Print more output in certificate status callback"},
889 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
890 "Status request responder timeout"},
891 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
892 {"status_file", OPT_STATUS_FILE, '<',
893 "File containing DER encoded OCSP Response"},
896 OPT_SECTION("Debug"),
897 {"security_debug", OPT_SECURITY_DEBUG, '-',
898 "Print output from SSL/TLS security framework"},
899 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
900 "Print more output from SSL/TLS security framework"},
901 {"brief", OPT_BRIEF, '-',
902 "Restrict output to brief summary of connection parameters"},
903 {"rev", OPT_REV, '-',
904 "act as a simple test server which just sends back with the received text reversed"},
905 {"debug", OPT_DEBUG, '-', "Print more output"},
906 {"msg", OPT_MSG, '-', "Show protocol messages"},
907 {"msgfile", OPT_MSGFILE, '>',
908 "File to send output of -msg or -trace, instead of stdout"},
909 {"state", OPT_STATE, '-', "Print the SSL states"},
910 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
911 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
912 "Maximum number of encrypt/decrypt pipelines to be used"},
913 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
914 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
916 OPT_SECTION("Network"),
917 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
918 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
919 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
920 {"read_buf", OPT_READ_BUF, 'p',
921 "Default read buffer size to be used for connections"},
922 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
923 "Size used to split data for encrypt pipelines"},
924 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
926 OPT_SECTION("Server identity"),
927 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
928 #ifndef OPENSSL_NO_PSK
929 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
931 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
932 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
933 #ifndef OPENSSL_NO_SRP
934 {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
935 {"srpuserseed", OPT_SRPUSERSEED, 's',
936 "A seed string for a default user salt"},
939 OPT_SECTION("Protocol and version"),
940 {"max_early_data", OPT_MAX_EARLY, 'n',
941 "The maximum number of bytes of early data as advertised in tickets"},
942 {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n',
943 "The maximum number of bytes of early data (hard limit)"},
944 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
945 {"num_tickets", OPT_S_NUM_TICKETS, 'n',
946 "The number of TLSv1.3 session tickets that a server will automatically issue" },
947 {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"},
948 {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"},
949 {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"},
950 {"no_ca_names", OPT_NOCANAMES, '-',
951 "Disable TLS Extension CA Names"},
952 {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"},
953 #ifndef OPENSSL_NO_SSL3
954 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
956 #ifndef OPENSSL_NO_TLS1
957 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
959 #ifndef OPENSSL_NO_TLS1_1
960 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
962 #ifndef OPENSSL_NO_TLS1_2
963 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
965 #ifndef OPENSSL_NO_TLS1_3
966 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
968 #ifndef OPENSSL_NO_DTLS
969 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
970 {"listen", OPT_LISTEN, '-',
971 "Listen for a DTLS ClientHello with a cookie and then connect"},
973 #ifndef OPENSSL_NO_DTLS1
974 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
976 #ifndef OPENSSL_NO_DTLS1_2
977 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
979 #ifndef OPENSSL_NO_SCTP
980 {"sctp", OPT_SCTP, '-', "Use SCTP"},
981 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
983 #ifndef OPENSSL_NO_SRTP
984 {"use_srtp", OPT_SRTP_PROFILES, 's',
985 "Offer SRTP key management with a colon-separated profile list"},
987 #ifndef OPENSSL_NO_DH
988 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
990 #ifndef OPENSSL_NO_NEXTPROTONEG
991 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
992 "Set the advertised protocols for the NPN extension (comma-separated list)"},
994 {"alpn", OPT_ALPN, 's',
995 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
996 #ifndef OPENSSL_NO_KTLS
997 {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"},
1008 #define IS_PROT_FLAG(o) \
1009 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
1010 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
1012 int s_server_main(int argc, char *argv[])
1014 ENGINE *engine = NULL;
1015 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
1016 SSL_CONF_CTX *cctx = NULL;
1017 const SSL_METHOD *meth = TLS_server_method();
1018 SSL_EXCERT *exc = NULL;
1019 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
1020 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
1021 STACK_OF(X509_CRL) *crls = NULL;
1022 X509 *s_cert = NULL, *s_dcert = NULL;
1023 X509_VERIFY_PARAM *vpm = NULL;
1024 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
1025 const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL;
1026 char *dpassarg = NULL, *dpass = NULL;
1027 char *passarg = NULL, *pass = NULL;
1028 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
1029 char *crl_file = NULL, *prog;
1031 int unlink_unix_path = 0;
1033 do_server_cb server_cb;
1034 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
1035 #ifndef OPENSSL_NO_DH
1036 char *dhfile = NULL;
1039 int nocert = 0, ret = 1;
1040 int noCApath = 0, noCAfile = 0, noCAstore = 0;
1041 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
1042 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
1043 int rev = 0, naccept = -1, sdebug = 0;
1044 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
1045 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
1047 char *port = OPENSSL_strdup(PORT);
1048 unsigned char *context = NULL;
1050 EVP_PKEY *s_key2 = NULL;
1051 X509 *s_cert2 = NULL;
1052 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
1053 const char *ssl_config = NULL;
1054 int read_buf_len = 0;
1055 #ifndef OPENSSL_NO_NEXTPROTONEG
1056 const char *next_proto_neg_in = NULL;
1057 tlsextnextprotoctx next_proto = { NULL, 0 };
1059 const char *alpn_in = NULL;
1060 tlsextalpnctx alpn_ctx = { NULL, 0 };
1061 #ifndef OPENSSL_NO_PSK
1062 /* by default do not send a PSK identity hint */
1063 char *psk_identity_hint = NULL;
1066 #ifndef OPENSSL_NO_SRP
1067 char *srpuserseed = NULL;
1068 char *srp_verifier_file = NULL;
1070 #ifndef OPENSSL_NO_SRTP
1071 char *srtp_profiles = NULL;
1073 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1074 int s_server_verify = SSL_VERIFY_NONE;
1075 int s_server_session_id_context = 1; /* anything will do */
1076 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
1077 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
1078 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
1079 #ifndef OPENSSL_NO_OCSP
1080 int s_tlsextstatus = 0;
1082 int no_resume_ephemeral = 0;
1083 unsigned int max_send_fragment = 0;
1084 unsigned int split_send_fragment = 0, max_pipelines = 0;
1085 const char *s_serverinfo_file = NULL;
1086 const char *keylog_file = NULL;
1087 int max_early_data = -1, recv_max_early_data = -1;
1088 char *psksessf = NULL;
1089 int no_ca_names = 0;
1090 #ifndef OPENSSL_NO_SCTP
1091 int sctp_label_bug = 0;
1093 int ignore_unexpected_eof = 0;
1095 /* Init of few remaining global variables */
1100 s_nbio = s_nbio_test = 0;
1110 cctx = SSL_CONF_CTX_new();
1111 vpm = X509_VERIFY_PARAM_new();
1112 if (cctx == NULL || vpm == NULL)
1114 SSL_CONF_CTX_set_flags(cctx,
1115 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1117 prog = opt_init(argc, argv, s_server_options);
1118 while ((o = opt_next()) != OPT_EOF) {
1119 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1120 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1123 if (IS_NO_PROT_FLAG(o))
1125 if (prot_opt == 1 && no_prot_opt) {
1127 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1134 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1137 opt_help(s_server_options);
1143 if (socket_family == AF_UNIX) {
1144 OPENSSL_free(host); host = NULL;
1145 OPENSSL_free(port); port = NULL;
1148 socket_family = AF_INET;
1154 if (socket_family == AF_UNIX) {
1155 OPENSSL_free(host); host = NULL;
1156 OPENSSL_free(port); port = NULL;
1159 socket_family = AF_INET6;
1162 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1168 if (socket_family == AF_UNIX) {
1169 socket_family = AF_UNSPEC;
1172 OPENSSL_free(port); port = NULL;
1173 OPENSSL_free(host); host = NULL;
1174 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1176 "%s: -port argument malformed or ambiguous\n",
1183 if (socket_family == AF_UNIX) {
1184 socket_family = AF_UNSPEC;
1187 OPENSSL_free(port); port = NULL;
1188 OPENSSL_free(host); host = NULL;
1189 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1191 "%s: -accept argument malformed or ambiguous\n",
1198 socket_family = AF_UNIX;
1199 OPENSSL_free(host); host = OPENSSL_strdup(opt_arg());
1200 OPENSSL_free(port); port = NULL;
1203 unlink_unix_path = 1;
1207 naccept = atol(opt_arg());
1210 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1211 verify_args.depth = atoi(opt_arg());
1213 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1215 case OPT_UPPER_V_VERIFY:
1217 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1218 SSL_VERIFY_CLIENT_ONCE;
1219 verify_args.depth = atoi(opt_arg());
1222 "verify depth is %d, must return a certificate\n",
1226 context = (unsigned char *)opt_arg();
1229 s_cert_file = opt_arg();
1232 if (!set_nameopt(opt_arg()))
1236 crl_file = opt_arg();
1238 case OPT_CRL_DOWNLOAD:
1241 case OPT_SERVERINFO:
1242 s_serverinfo_file = opt_arg();
1245 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format))
1249 s_key_file = opt_arg();
1252 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1256 passarg = opt_arg();
1258 case OPT_CERT_CHAIN:
1259 s_chain_file = opt_arg();
1262 #ifndef OPENSSL_NO_DH
1267 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format))
1271 s_dcert_file = opt_arg();
1274 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format))
1278 dpassarg = opt_arg();
1281 s_dkey_file = opt_arg();
1283 case OPT_DCERT_CHAIN:
1284 s_dchain_file = opt_arg();
1295 case OPT_CHAINCAPATH:
1296 chCApath = opt_arg();
1298 case OPT_VERIFYCAPATH:
1299 vfyCApath = opt_arg();
1302 CAstore = opt_arg();
1307 case OPT_CHAINCASTORE:
1308 chCAstore = opt_arg();
1310 case OPT_VERIFYCASTORE:
1311 vfyCAstore = opt_arg();
1320 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1324 case OPT_S_NUM_TICKETS:
1325 case OPT_ANTI_REPLAY:
1326 case OPT_NO_ANTI_REPLAY:
1327 if (ssl_args == NULL)
1328 ssl_args = sk_OPENSSL_STRING_new_null();
1329 if (ssl_args == NULL
1330 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1331 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1332 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1337 if (!opt_verify(o, vpm))
1342 if (!args_excert(o, &exc))
1345 case OPT_VERIFY_RET_ERROR:
1346 verify_args.return_error = 1;
1348 case OPT_VERIFY_QUIET:
1349 verify_args.quiet = 1;
1351 case OPT_BUILD_CHAIN:
1360 case OPT_CHAINCAFILE:
1361 chCAfile = opt_arg();
1363 case OPT_VERIFYCAFILE:
1364 vfyCAfile = opt_arg();
1370 s_nbio = s_nbio_test = 1;
1375 case OPT_NO_IGN_EOF:
1381 case OPT_TLSEXTDEBUG:
1385 #ifndef OPENSSL_NO_OCSP
1389 case OPT_STATUS_VERBOSE:
1390 #ifndef OPENSSL_NO_OCSP
1391 s_tlsextstatus = tlscstatp.verbose = 1;
1394 case OPT_STATUS_TIMEOUT:
1395 #ifndef OPENSSL_NO_OCSP
1397 tlscstatp.timeout = atoi(opt_arg());
1400 case OPT_STATUS_URL:
1401 #ifndef OPENSSL_NO_OCSP
1403 if (!OSSL_HTTP_parse_url(opt_arg(),
1404 &tlscstatp.host, &tlscstatp.port, NULL,
1405 &tlscstatp.path, &tlscstatp.use_ssl)) {
1406 BIO_printf(bio_err, "Error parsing URL\n");
1411 case OPT_STATUS_FILE:
1412 #ifndef OPENSSL_NO_OCSP
1414 tlscstatp.respin = opt_arg();
1421 bio_s_msg = BIO_new_file(opt_arg(), "w");
1424 #ifndef OPENSSL_NO_SSL_TRACE
1428 case OPT_SECURITY_DEBUG:
1431 case OPT_SECURITY_DEBUG_VERBOSE:
1444 s_quiet = s_brief = verify_args.quiet = 1;
1447 #ifndef OPENSSL_NO_DH
1451 case OPT_NO_RESUME_EPHEMERAL:
1452 no_resume_ephemeral = 1;
1454 case OPT_PSK_IDENTITY:
1455 psk_identity = opt_arg();
1458 #ifndef OPENSSL_NO_PSK
1459 psk_identity_hint = opt_arg();
1463 for (p = psk_key = opt_arg(); *p; p++) {
1464 if (isxdigit(_UC(*p)))
1466 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1471 psksessf = opt_arg();
1474 #ifndef OPENSSL_NO_SRP
1475 srp_verifier_file = opt_arg();
1476 if (min_version < TLS1_VERSION)
1477 min_version = TLS1_VERSION;
1480 case OPT_SRPUSERSEED:
1481 #ifndef OPENSSL_NO_SRP
1482 srpuserseed = opt_arg();
1483 if (min_version < TLS1_VERSION)
1484 min_version = TLS1_VERSION;
1499 case OPT_SSL_CONFIG:
1500 ssl_config = opt_arg();
1503 min_version = SSL3_VERSION;
1504 max_version = SSL3_VERSION;
1507 min_version = TLS1_3_VERSION;
1508 max_version = TLS1_3_VERSION;
1511 min_version = TLS1_2_VERSION;
1512 max_version = TLS1_2_VERSION;
1515 min_version = TLS1_1_VERSION;
1516 max_version = TLS1_1_VERSION;
1519 min_version = TLS1_VERSION;
1520 max_version = TLS1_VERSION;
1523 #ifndef OPENSSL_NO_DTLS
1524 meth = DTLS_server_method();
1525 socket_type = SOCK_DGRAM;
1529 #ifndef OPENSSL_NO_DTLS
1530 meth = DTLS_server_method();
1531 min_version = DTLS1_VERSION;
1532 max_version = DTLS1_VERSION;
1533 socket_type = SOCK_DGRAM;
1537 #ifndef OPENSSL_NO_DTLS
1538 meth = DTLS_server_method();
1539 min_version = DTLS1_2_VERSION;
1540 max_version = DTLS1_2_VERSION;
1541 socket_type = SOCK_DGRAM;
1545 #ifndef OPENSSL_NO_SCTP
1546 protocol = IPPROTO_SCTP;
1549 case OPT_SCTP_LABEL_BUG:
1550 #ifndef OPENSSL_NO_SCTP
1555 #ifndef OPENSSL_NO_DTLS
1556 enable_timeouts = 1;
1560 #ifndef OPENSSL_NO_DTLS
1561 socket_mtu = atol(opt_arg());
1565 #ifndef OPENSSL_NO_DTLS
1573 session_id_prefix = opt_arg();
1576 #ifndef OPENSSL_NO_ENGINE
1577 engine = setup_engine(opt_arg(), s_debug);
1584 case OPT_PROV_CASES:
1585 if (!opt_provider(o))
1588 case OPT_SERVERNAME:
1589 tlsextcbp.servername = opt_arg();
1591 case OPT_SERVERNAME_FATAL:
1592 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1595 s_cert_file2 = opt_arg();
1598 s_key_file2 = opt_arg();
1600 case OPT_NEXTPROTONEG:
1601 # ifndef OPENSSL_NO_NEXTPROTONEG
1602 next_proto_neg_in = opt_arg();
1606 alpn_in = opt_arg();
1608 case OPT_SRTP_PROFILES:
1609 #ifndef OPENSSL_NO_SRTP
1610 srtp_profiles = opt_arg();
1613 case OPT_KEYMATEXPORT:
1614 keymatexportlabel = opt_arg();
1616 case OPT_KEYMATEXPORTLEN:
1617 keymatexportlen = atoi(opt_arg());
1622 case OPT_MAX_SEND_FRAG:
1623 max_send_fragment = atoi(opt_arg());
1625 case OPT_SPLIT_SEND_FRAG:
1626 split_send_fragment = atoi(opt_arg());
1628 case OPT_MAX_PIPELINES:
1629 max_pipelines = atoi(opt_arg());
1632 read_buf_len = atoi(opt_arg());
1634 case OPT_KEYLOG_FILE:
1635 keylog_file = opt_arg();
1638 max_early_data = atoi(opt_arg());
1639 if (max_early_data < 0) {
1640 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1644 case OPT_RECV_MAX_EARLY:
1645 recv_max_early_data = atoi(opt_arg());
1646 if (recv_max_early_data < 0) {
1647 BIO_printf(bio_err, "Invalid value for recv_max_early_data\n");
1651 case OPT_EARLY_DATA:
1653 if (max_early_data == -1)
1654 max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
1656 case OPT_HTTP_SERVER_BINMODE:
1657 http_server_binmode = 1;
1663 #ifndef OPENSSL_NO_KTLS
1667 case OPT_IGNORE_UNEXPECTED_EOF:
1668 ignore_unexpected_eof = 1;
1672 argc = opt_num_rest();
1675 #ifndef OPENSSL_NO_NEXTPROTONEG
1676 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1677 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1681 #ifndef OPENSSL_NO_DTLS
1682 if (www && socket_type == SOCK_DGRAM) {
1683 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1687 if (dtlslisten && socket_type != SOCK_DGRAM) {
1688 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1693 if (stateless && socket_type != SOCK_STREAM) {
1694 BIO_printf(bio_err, "Can only use --stateless with TLS\n");
1699 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1701 "Can't use unix sockets and datagrams together\n");
1705 if (early_data && (www > 0 || rev)) {
1707 "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n");
1711 #ifndef OPENSSL_NO_SCTP
1712 if (protocol == IPPROTO_SCTP) {
1713 if (socket_type != SOCK_DGRAM) {
1714 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1717 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1718 socket_type = SOCK_STREAM;
1722 #ifndef OPENSSL_NO_KTLS
1723 if (use_sendfile && www <= 1) {
1724 BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n");
1729 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1730 BIO_printf(bio_err, "Error getting password\n");
1734 if (s_key_file == NULL)
1735 s_key_file = s_cert_file;
1737 if (s_key_file2 == NULL)
1738 s_key_file2 = s_cert_file2;
1740 if (!load_excert(&exc))
1744 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1745 "server certificate private key file");
1749 s_cert = load_cert_pass(s_cert_file, s_cert_format, pass,
1750 "server certificate file");
1754 if (s_chain_file != NULL) {
1755 if (!load_certs(s_chain_file, &s_chain, NULL,
1756 "server certificate chain"))
1760 if (tlsextcbp.servername != NULL) {
1761 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1762 "second server certificate private key file");
1766 s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, pass,
1767 "second server certificate file");
1769 if (s_cert2 == NULL)
1773 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1774 if (next_proto_neg_in) {
1775 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1776 if (next_proto.data == NULL)
1780 alpn_ctx.data = NULL;
1782 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1783 if (alpn_ctx.data == NULL)
1787 if (crl_file != NULL) {
1789 crl = load_crl(crl_file, crl_format, "CRL");
1792 crls = sk_X509_CRL_new_null();
1793 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1794 BIO_puts(bio_err, "Error adding CRL\n");
1795 ERR_print_errors(bio_err);
1801 if (s_dcert_file != NULL) {
1803 if (s_dkey_file == NULL)
1804 s_dkey_file = s_dcert_file;
1806 s_dkey = load_key(s_dkey_file, s_dkey_format,
1807 0, dpass, engine, "second certificate private key file");
1811 s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, dpass,
1812 "second server certificate file");
1814 if (s_dcert == NULL) {
1815 ERR_print_errors(bio_err);
1818 if (s_dchain_file != NULL) {
1819 if (!load_certs(s_dchain_file, &s_dchain, NULL,
1820 "second server certificate chain"))
1826 if (bio_s_out == NULL) {
1827 if (s_quiet && !s_debug) {
1828 bio_s_out = BIO_new(BIO_s_null());
1829 if (s_msg && bio_s_msg == NULL)
1830 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1832 if (bio_s_out == NULL)
1833 bio_s_out = dup_bio_out(FORMAT_TEXT);
1836 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1842 s_dcert_file = NULL;
1844 s_cert_file2 = NULL;
1848 ctx = SSL_CTX_new(meth);
1850 ERR_print_errors(bio_err);
1854 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1857 ssl_ctx_security_debug(ctx, sdebug);
1859 if (!config_ctx(cctx, ssl_args, ctx))
1863 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1864 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1866 ERR_print_errors(bio_err);
1870 #ifndef OPENSSL_NO_SCTP
1871 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1872 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1875 if (min_version != 0
1876 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1878 if (max_version != 0
1879 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1882 if (session_id_prefix) {
1883 if (strlen(session_id_prefix) >= 32)
1885 "warning: id_prefix is too long, only one new session will be possible\n");
1886 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1887 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1888 ERR_print_errors(bio_err);
1891 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1894 ssl_ctx_set_excert(ctx, exc);
1897 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1899 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1901 init_session_cache_ctx(ctx);
1903 SSL_CTX_sess_set_cache_size(ctx, 128);
1906 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1910 SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
1913 if (ignore_unexpected_eof)
1914 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1916 if (max_send_fragment > 0
1917 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1918 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1919 prog, max_send_fragment);
1923 if (split_send_fragment > 0
1924 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1925 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1926 prog, split_send_fragment);
1929 if (max_pipelines > 0
1930 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1931 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1932 prog, max_pipelines);
1936 if (read_buf_len > 0) {
1937 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1939 #ifndef OPENSSL_NO_SRTP
1940 if (srtp_profiles != NULL) {
1941 /* Returns 0 on success! */
1942 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1943 BIO_printf(bio_err, "Error setting SRTP profile\n");
1944 ERR_print_errors(bio_err);
1950 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1951 CAstore, noCAstore)) {
1952 ERR_print_errors(bio_err);
1955 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1956 BIO_printf(bio_err, "Error setting verify params\n");
1957 ERR_print_errors(bio_err);
1961 ssl_ctx_add_crls(ctx, crls, 0);
1963 if (!ssl_load_stores(ctx,
1964 vfyCApath, vfyCAfile, vfyCAstore,
1965 chCApath, chCAfile, chCAstore,
1966 crls, crl_download)) {
1967 BIO_printf(bio_err, "Error loading store locations\n");
1968 ERR_print_errors(bio_err);
1973 ctx2 = SSL_CTX_new(meth);
1975 ERR_print_errors(bio_err);
1981 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1984 ssl_ctx_security_debug(ctx2, sdebug);
1986 if (session_id_prefix) {
1987 if (strlen(session_id_prefix) >= 32)
1989 "warning: id_prefix is too long, only one new session will be possible\n");
1990 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1991 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1992 ERR_print_errors(bio_err);
1995 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1998 ssl_ctx_set_excert(ctx2, exc);
2001 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
2004 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
2006 init_session_cache_ctx(ctx2);
2008 SSL_CTX_sess_set_cache_size(ctx2, 128);
2011 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
2013 if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath,
2014 noCApath, CAstore, noCAstore)) {
2015 ERR_print_errors(bio_err);
2018 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
2019 BIO_printf(bio_err, "Error setting verify params\n");
2020 ERR_print_errors(bio_err);
2024 ssl_ctx_add_crls(ctx2, crls, 0);
2025 if (!config_ctx(cctx, ssl_args, ctx2))
2028 #ifndef OPENSSL_NO_NEXTPROTONEG
2029 if (next_proto.data)
2030 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
2034 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
2036 #ifndef OPENSSL_NO_DH
2041 dh = load_dh_param(dhfile);
2042 else if (s_cert_file != NULL)
2043 dh = load_dh_param(s_cert_file);
2046 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2048 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
2050 (void)BIO_flush(bio_s_out);
2053 SSL_CTX_set_dh_auto(ctx, 1);
2054 } else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2055 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2056 ERR_print_errors(bio_err);
2063 DH *dh2 = load_dh_param(s_cert_file2);
2065 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2066 (void)BIO_flush(bio_s_out);
2073 SSL_CTX_set_dh_auto(ctx2, 1);
2074 } else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
2075 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2076 ERR_print_errors(bio_err);
2085 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
2088 if (s_serverinfo_file != NULL
2089 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
2090 ERR_print_errors(bio_err);
2095 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
2098 if (s_dcert != NULL) {
2099 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
2103 if (no_resume_ephemeral) {
2104 SSL_CTX_set_not_resumable_session_callback(ctx,
2105 not_resumable_sess_cb);
2108 SSL_CTX_set_not_resumable_session_callback(ctx2,
2109 not_resumable_sess_cb);
2111 #ifndef OPENSSL_NO_PSK
2112 if (psk_key != NULL) {
2114 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
2115 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
2118 if (psk_identity_hint != NULL) {
2119 if (min_version == TLS1_3_VERSION) {
2120 BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n");
2122 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
2123 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
2124 ERR_print_errors(bio_err);
2130 if (psksessf != NULL) {
2131 BIO *stmp = BIO_new_file(psksessf, "r");
2134 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
2135 ERR_print_errors(bio_err);
2138 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2140 if (psksess == NULL) {
2141 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
2142 ERR_print_errors(bio_err);
2148 if (psk_key != NULL || psksess != NULL)
2149 SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb);
2151 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
2152 if (!SSL_CTX_set_session_id_context(ctx,
2153 (void *)&s_server_session_id_context,
2154 sizeof(s_server_session_id_context))) {
2155 BIO_printf(bio_err, "error setting session id context\n");
2156 ERR_print_errors(bio_err);
2160 /* Set DTLS cookie generation and verification callbacks */
2161 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
2162 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
2164 /* Set TLS1.3 cookie generation and verification callbacks */
2165 SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback);
2166 SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback);
2169 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
2170 if (!SSL_CTX_set_session_id_context(ctx2,
2171 (void *)&s_server_session_id_context,
2172 sizeof(s_server_session_id_context))) {
2173 BIO_printf(bio_err, "error setting session id context\n");
2174 ERR_print_errors(bio_err);
2177 tlsextcbp.biodebug = bio_s_out;
2178 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
2179 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
2180 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2181 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2184 #ifndef OPENSSL_NO_SRP
2185 if (srp_verifier_file != NULL) {
2186 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
2187 srp_callback_parm.user = NULL;
2188 srp_callback_parm.login = NULL;
2190 SRP_VBASE_init(srp_callback_parm.vb,
2191 srp_verifier_file)) != SRP_NO_ERROR) {
2193 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
2194 srp_verifier_file, ret);
2197 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
2198 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
2199 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
2202 if (CAfile != NULL) {
2203 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2206 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2208 #ifndef OPENSSL_NO_OCSP
2209 if (s_tlsextstatus) {
2210 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2211 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2213 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2214 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2218 if (set_keylog_file(ctx, keylog_file))
2221 if (max_early_data >= 0)
2222 SSL_CTX_set_max_early_data(ctx, max_early_data);
2223 if (recv_max_early_data >= 0)
2224 SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data);
2227 server_cb = rev_body;
2229 server_cb = www_body;
2231 server_cb = sv_body;
2233 if (socket_family == AF_UNIX
2234 && unlink_unix_path)
2237 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2238 server_cb, context, naccept, bio_s_out);
2239 print_stats(bio_s_out, ctx);
2243 SSL_SESSION_free(psksess);
2244 set_keylog_file(NULL, NULL);
2246 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2248 EVP_PKEY_free(s_key);
2249 EVP_PKEY_free(s_dkey);
2250 sk_X509_pop_free(s_chain, X509_free);
2251 sk_X509_pop_free(s_dchain, X509_free);
2253 OPENSSL_free(dpass);
2256 X509_VERIFY_PARAM_free(vpm);
2258 OPENSSL_free(tlscstatp.host);
2259 OPENSSL_free(tlscstatp.port);
2260 OPENSSL_free(tlscstatp.path);
2263 EVP_PKEY_free(s_key2);
2264 #ifndef OPENSSL_NO_NEXTPROTONEG
2265 OPENSSL_free(next_proto.data);
2267 OPENSSL_free(alpn_ctx.data);
2268 ssl_excert_free(exc);
2269 sk_OPENSSL_STRING_free(ssl_args);
2270 SSL_CONF_CTX_free(cctx);
2271 release_engine(engine);
2272 BIO_free(bio_s_out);
2274 BIO_free(bio_s_msg);
2276 #ifdef CHARSET_EBCDIC
2277 BIO_meth_free(methods_ebcdic);
2282 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2284 BIO_printf(bio, "%4ld items in the session cache\n",
2285 SSL_CTX_sess_number(ssl_ctx));
2286 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2287 SSL_CTX_sess_connect(ssl_ctx));
2288 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2289 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2290 BIO_printf(bio, "%4ld client connects that finished\n",
2291 SSL_CTX_sess_connect_good(ssl_ctx));
2292 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2293 SSL_CTX_sess_accept(ssl_ctx));
2294 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2295 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2296 BIO_printf(bio, "%4ld server accepts that finished\n",
2297 SSL_CTX_sess_accept_good(ssl_ctx));
2298 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2299 BIO_printf(bio, "%4ld session cache misses\n",
2300 SSL_CTX_sess_misses(ssl_ctx));
2301 BIO_printf(bio, "%4ld session cache timeouts\n",
2302 SSL_CTX_sess_timeouts(ssl_ctx));
2303 BIO_printf(bio, "%4ld callback cache hits\n",
2304 SSL_CTX_sess_cb_hits(ssl_ctx));
2305 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2306 SSL_CTX_sess_cache_full(ssl_ctx),
2307 SSL_CTX_sess_get_cache_size(ssl_ctx));
2310 static int sv_body(int s, int stype, int prot, unsigned char *context)
2319 struct timeval timeout;
2320 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
2321 struct timeval *timeoutp;
2323 #ifndef OPENSSL_NO_DTLS
2324 # ifndef OPENSSL_NO_SCTP
2325 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2327 int isdtls = (stype == SOCK_DGRAM);
2331 buf = app_malloc(bufsize, "server buffer");
2333 if (!BIO_socket_nbio(s, 1))
2334 ERR_print_errors(bio_err);
2336 BIO_printf(bio_err, "Turned on non blocking io\n");
2345 if (s_tlsextdebug) {
2346 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2347 SSL_set_tlsext_debug_arg(con, bio_s_out);
2351 && !SSL_set_session_id_context(con, context,
2352 strlen((char *)context))) {
2353 BIO_printf(bio_err, "Error setting session id context\n");
2358 if (!SSL_clear(con)) {
2359 BIO_printf(bio_err, "Error clearing SSL connection\n");
2363 #ifndef OPENSSL_NO_DTLS
2365 # ifndef OPENSSL_NO_SCTP
2366 if (prot == IPPROTO_SCTP)
2367 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2370 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2372 if (enable_timeouts) {
2374 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2375 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2378 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2379 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2383 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2384 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2385 DTLS_get_link_min_mtu(con));
2390 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2391 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2392 BIO_printf(bio_err, "Failed to set MTU\n");
2398 /* want to do MTU discovery */
2399 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2401 # ifndef OPENSSL_NO_SCTP
2402 if (prot != IPPROTO_SCTP)
2404 /* Turn on cookie exchange. Not necessary for SCTP */
2405 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2408 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2411 BIO_printf(bio_err, "Unable to create BIO\n");
2412 ERR_print_errors(bio_err);
2419 test = BIO_new(BIO_f_nbio_test());
2420 sbio = BIO_push(test, sbio);
2423 SSL_set_bio(con, sbio, sbio);
2424 SSL_set_accept_state(con);
2425 /* SSL_set_fd(con,s); */
2428 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2429 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2432 #ifndef OPENSSL_NO_SSL_TRACE
2434 SSL_set_msg_callback(con, SSL_trace);
2437 SSL_set_msg_callback(con, msg_cb);
2438 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2441 if (s_tlsextdebug) {
2442 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2443 SSL_set_tlsext_debug_arg(con, bio_s_out);
2447 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2450 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2452 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2453 if (edret != SSL_READ_EARLY_DATA_ERROR)
2456 switch (SSL_get_error(con, 0)) {
2457 case SSL_ERROR_WANT_WRITE:
2458 case SSL_ERROR_WANT_ASYNC:
2459 case SSL_ERROR_WANT_READ:
2460 /* Just keep trying - busy waiting */
2463 BIO_printf(bio_err, "Error reading early data\n");
2464 ERR_print_errors(bio_err);
2468 if (readbytes > 0) {
2470 BIO_printf(bio_s_out, "Early data received:\n");
2473 raw_write_stdout(buf, (unsigned int)readbytes);
2474 (void)BIO_flush(bio_s_out);
2478 if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT)
2479 BIO_printf(bio_s_out, "No early data received\n");
2481 BIO_printf(bio_s_out, "Early data was rejected\n");
2483 BIO_printf(bio_s_out, "\nEnd of early data\n");
2485 if (SSL_is_init_finished(con))
2486 print_connection_info(con);
2489 if (fileno_stdin() > s)
2490 width = fileno_stdin() + 1;
2494 int read_from_terminal;
2495 int read_from_sslcon;
2497 read_from_terminal = 0;
2498 read_from_sslcon = SSL_has_pending(con)
2499 || (async && SSL_waiting_for_async(con));
2501 if (!read_from_sslcon) {
2503 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2504 openssl_fdset(fileno_stdin(), &readfds);
2506 openssl_fdset(s, &readfds);
2508 * Note: under VMS with SOCKETSHR the second parameter is
2509 * currently of type (int *) whereas under other systems it is
2510 * (void *) if you don't have a cast it will choke the compiler:
2511 * if you do have a cast then you can either go for (int *) or
2514 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2516 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2517 * only on sockets. As a workaround we timeout the select every
2518 * second and check for any keypress. In a proper Windows
2519 * application we wouldn't do this because it is inefficient.
2522 timeout.tv_usec = 0;
2523 i = select(width, (void *)&readfds, NULL, NULL, &timeout);
2524 if (has_stdin_waiting())
2525 read_from_terminal = 1;
2526 if ((i < 0) || (!i && !read_from_terminal))
2529 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2530 timeoutp = &timeout;
2534 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2536 if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
2537 BIO_printf(bio_err, "TIMEOUT occurred\n");
2541 if (FD_ISSET(fileno_stdin(), &readfds))
2542 read_from_terminal = 1;
2544 if (FD_ISSET(s, &readfds))
2545 read_from_sslcon = 1;
2547 if (read_from_terminal) {
2551 i = raw_read_stdin(buf, bufsize / 2);
2553 /* both loops are skipped when i <= 0 */
2554 for (j = 0; j < i; j++)
2557 for (j = i - 1; j >= 0; j--) {
2558 buf[j + lf_num] = buf[j];
2559 if (buf[j] == '\n') {
2562 buf[j + lf_num] = '\r';
2565 assert(lf_num == 0);
2567 i = raw_read_stdin(buf, bufsize);
2570 if (!s_quiet && !s_brief) {
2571 if ((i <= 0) || (buf[0] == 'Q')) {
2572 BIO_printf(bio_s_out, "DONE\n");
2573 (void)BIO_flush(bio_s_out);
2575 close_accept_socket();
2579 if ((i <= 0) || (buf[0] == 'q')) {
2580 BIO_printf(bio_s_out, "DONE\n");
2581 (void)BIO_flush(bio_s_out);
2582 if (SSL_version(con) != DTLS1_VERSION)
2585 * close_accept_socket(); ret= -11;
2589 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2590 SSL_renegotiate(con);
2591 i = SSL_do_handshake(con);
2592 printf("SSL_do_handshake -> %d\n", i);
2596 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2598 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2600 SSL_renegotiate(con);
2601 i = SSL_do_handshake(con);
2602 printf("SSL_do_handshake -> %d\n", i);
2606 if ((buf[0] == 'K' || buf[0] == 'k')
2607 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2608 SSL_key_update(con, buf[0] == 'K' ?
2609 SSL_KEY_UPDATE_REQUESTED
2610 : SSL_KEY_UPDATE_NOT_REQUESTED);
2611 i = SSL_do_handshake(con);
2612 printf("SSL_do_handshake -> %d\n", i);
2616 if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2617 SSL_set_verify(con, SSL_VERIFY_PEER, NULL);
2618 i = SSL_verify_client_post_handshake(con);
2620 printf("Failed to initiate request\n");
2621 ERR_print_errors(bio_err);
2623 i = SSL_do_handshake(con);
2624 printf("SSL_do_handshake -> %d\n", i);
2629 if (buf[0] == 'P') {
2630 static const char str[] = "Lets print some clear text\n";
2631 BIO_write(SSL_get_wbio(con), str, sizeof(str) -1);
2633 if (buf[0] == 'S') {
2634 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2637 #ifdef CHARSET_EBCDIC
2638 ebcdic2ascii(buf, buf, i);
2642 /* should do a select for the write */
2645 if (++count == 100) {
2647 SSL_renegotiate(con);
2650 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2651 #ifndef OPENSSL_NO_SRP
2652 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2653 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2654 SRP_user_pwd_free(srp_callback_parm.user);
2655 srp_callback_parm.user =
2656 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2657 srp_callback_parm.login);
2658 if (srp_callback_parm.user)
2659 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2660 srp_callback_parm.user->info);
2662 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2663 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2666 switch (SSL_get_error(con, k)) {
2667 case SSL_ERROR_NONE:
2669 case SSL_ERROR_WANT_ASYNC:
2670 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2671 (void)BIO_flush(bio_s_out);
2672 wait_for_async(con);
2674 case SSL_ERROR_WANT_WRITE:
2675 case SSL_ERROR_WANT_READ:
2676 case SSL_ERROR_WANT_X509_LOOKUP:
2677 BIO_printf(bio_s_out, "Write BLOCK\n");
2678 (void)BIO_flush(bio_s_out);
2680 case SSL_ERROR_WANT_ASYNC_JOB:
2682 * This shouldn't ever happen in s_server. Treat as an error
2684 case SSL_ERROR_SYSCALL:
2686 BIO_printf(bio_s_out, "ERROR\n");
2687 (void)BIO_flush(bio_s_out);
2688 ERR_print_errors(bio_err);
2692 case SSL_ERROR_ZERO_RETURN:
2693 BIO_printf(bio_s_out, "DONE\n");
2694 (void)BIO_flush(bio_s_out);
2706 if (read_from_sslcon) {
2708 * init_ssl_connection handles all async events itself so if we're
2709 * waiting for async then we shouldn't go back into
2710 * init_ssl_connection
2712 if ((!async || !SSL_waiting_for_async(con))
2713 && !SSL_is_init_finished(con)) {
2714 i = init_ssl_connection(con);
2719 } else if (i == 0) {
2725 i = SSL_read(con, (char *)buf, bufsize);
2726 #ifndef OPENSSL_NO_SRP
2727 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2728 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2729 SRP_user_pwd_free(srp_callback_parm.user);
2730 srp_callback_parm.user =
2731 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2732 srp_callback_parm.login);
2733 if (srp_callback_parm.user)
2734 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2735 srp_callback_parm.user->info);
2737 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2738 i = SSL_read(con, (char *)buf, bufsize);
2741 switch (SSL_get_error(con, i)) {
2742 case SSL_ERROR_NONE:
2743 #ifdef CHARSET_EBCDIC
2744 ascii2ebcdic(buf, buf, i);
2746 raw_write_stdout(buf, (unsigned int)i);
2747 (void)BIO_flush(bio_s_out);
2748 if (SSL_has_pending(con))
2751 case SSL_ERROR_WANT_ASYNC:
2752 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2753 (void)BIO_flush(bio_s_out);
2754 wait_for_async(con);
2756 case SSL_ERROR_WANT_WRITE:
2757 case SSL_ERROR_WANT_READ:
2758 BIO_printf(bio_s_out, "Read BLOCK\n");
2759 (void)BIO_flush(bio_s_out);
2761 case SSL_ERROR_WANT_ASYNC_JOB:
2763 * This shouldn't ever happen in s_server. Treat as an error
2765 case SSL_ERROR_SYSCALL:
2767 BIO_printf(bio_s_out, "ERROR\n");
2768 (void)BIO_flush(bio_s_out);
2769 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);
2783 BIO_printf(bio_s_out, "shutting down SSL\n");
2784 do_ssl_shutdown(con);
2787 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2788 OPENSSL_clear_free(buf, bufsize);
2792 static void close_accept_socket(void)
2794 BIO_printf(bio_err, "shutdown accept socket\n");
2795 if (accept_socket >= 0) {
2796 BIO_closesocket(accept_socket);
2800 static int is_retryable(SSL *con, int i)
2802 int err = SSL_get_error(con, i);
2804 /* If it's not a fatal error, it must be retryable */
2805 return (err != SSL_ERROR_SSL)
2806 && (err != SSL_ERROR_SYSCALL)
2807 && (err != SSL_ERROR_ZERO_RETURN);
2810 static int init_ssl_connection(SSL *con)
2816 if (dtlslisten || stateless) {
2817 BIO_ADDR *client = NULL;
2820 if ((client = BIO_ADDR_new()) == NULL) {
2821 BIO_printf(bio_err, "ERROR - memory\n");
2824 i = DTLSv1_listen(con, client);
2826 i = SSL_stateless(con);
2833 wbio = SSL_get_wbio(con);
2835 BIO_get_fd(wbio, &fd);
2838 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2839 BIO_printf(bio_err, "ERROR - unable to connect\n");
2840 BIO_ADDR_free(client);
2844 (void)BIO_ctrl_set_connected(wbio, client);
2845 BIO_ADDR_free(client);
2850 i = SSL_accept(con);
2852 BIO_ADDR_free(client);
2856 i = SSL_accept(con);
2859 retry = is_retryable(con, i);
2860 #ifdef CERT_CB_TEST_RETRY
2863 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2864 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2866 "LOOKUP from certificate callback during accept\n");
2867 i = SSL_accept(con);
2869 retry = is_retryable(con, i);
2874 #ifndef OPENSSL_NO_SRP
2876 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2877 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2878 srp_callback_parm.login);
2879 SRP_user_pwd_free(srp_callback_parm.user);
2880 srp_callback_parm.user =
2881 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2882 srp_callback_parm.login);
2883 if (srp_callback_parm.user)
2884 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2885 srp_callback_parm.user->info);
2887 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2888 i = SSL_accept(con);
2890 retry = is_retryable(con, i);
2893 } while (i < 0 && SSL_waiting_for_async(con));
2897 if (((dtlslisten || stateless) && i == 0)
2898 || (!dtlslisten && !stateless && retry)) {
2899 BIO_printf(bio_s_out, "DELAY\n");
2903 BIO_printf(bio_err, "ERROR\n");
2905 verify_err = SSL_get_verify_result(con);
2906 if (verify_err != X509_V_OK) {
2907 BIO_printf(bio_err, "verify error:%s\n",
2908 X509_verify_cert_error_string(verify_err));
2910 /* Always print any error messages */
2911 ERR_print_errors(bio_err);
2915 print_connection_info(con);
2919 static void print_connection_info(SSL *con)
2924 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2925 const unsigned char *next_proto_neg;
2926 unsigned next_proto_neg_len;
2928 unsigned char *exportedkeymat;
2932 print_ssl_summary(con);
2934 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2936 peer = SSL_get0_peer_certificate(con);
2938 BIO_printf(bio_s_out, "Client certificate\n");
2939 PEM_write_bio_X509(bio_s_out, peer);
2940 dump_cert_text(bio_s_out, peer);
2944 if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
2945 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2946 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2947 ssl_print_sigalgs(bio_s_out, con);
2948 #ifndef OPENSSL_NO_EC
2949 ssl_print_point_formats(bio_s_out, con);
2950 ssl_print_groups(bio_s_out, con, 0);
2952 print_ca_names(bio_s_out, con);
2953 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2955 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2956 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2957 if (next_proto_neg) {
2958 BIO_printf(bio_s_out, "NEXTPROTO is ");
2959 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2960 BIO_printf(bio_s_out, "\n");
2963 #ifndef OPENSSL_NO_SRTP
2965 SRTP_PROTECTION_PROFILE *srtp_profile
2966 = SSL_get_selected_srtp_profile(con);
2969 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2970 srtp_profile->name);
2973 if (SSL_session_reused(con))
2974 BIO_printf(bio_s_out, "Reused session-id\n");
2975 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2976 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2977 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
2978 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
2980 if (keymatexportlabel != NULL) {
2981 BIO_printf(bio_s_out, "Keying material exporter:\n");
2982 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2983 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2984 exportedkeymat = app_malloc(keymatexportlen, "export key");
2985 if (!SSL_export_keying_material(con, exportedkeymat,
2988 strlen(keymatexportlabel),
2990 BIO_printf(bio_s_out, " Error\n");
2992 BIO_printf(bio_s_out, " Keying material: ");
2993 for (i = 0; i < keymatexportlen; i++)
2994 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2995 BIO_printf(bio_s_out, "\n");
2997 OPENSSL_free(exportedkeymat);
2999 #ifndef OPENSSL_NO_KTLS
3000 if (BIO_get_ktls_send(SSL_get_wbio(con)))
3001 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3002 if (BIO_get_ktls_recv(SSL_get_rbio(con)))
3003 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3006 (void)BIO_flush(bio_s_out);
3009 #ifndef OPENSSL_NO_DH
3010 static DH *load_dh_param(const char *dhfile)
3015 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
3017 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3024 static int www_body(int s, int stype, int prot, unsigned char *context)
3030 const SSL_CIPHER *c;
3031 BIO *io, *ssl_bio, *sbio;
3033 int total_bytes = 0;
3039 /* Set width for a select call if needed */
3042 buf = app_malloc(bufsize, "server www buffer");
3043 io = BIO_new(BIO_f_buffer());
3044 ssl_bio = BIO_new(BIO_f_ssl());
3045 if ((io == NULL) || (ssl_bio == NULL))
3049 if (!BIO_socket_nbio(s, 1))
3050 ERR_print_errors(bio_err);
3052 BIO_printf(bio_err, "Turned on non blocking io\n");
3055 /* lets make the output buffer a reasonable size */
3056 if (!BIO_set_write_buffer_size(io, bufsize))
3059 if ((con = SSL_new(ctx)) == NULL)
3062 if (s_tlsextdebug) {
3063 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3064 SSL_set_tlsext_debug_arg(con, bio_s_out);
3068 && !SSL_set_session_id_context(con, context,
3069 strlen((char *)context))) {
3074 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3078 test = BIO_new(BIO_f_nbio_test());
3079 sbio = BIO_push(test, sbio);
3081 SSL_set_bio(con, sbio, sbio);
3082 SSL_set_accept_state(con);
3084 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3085 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3086 BIO_push(io, ssl_bio);
3087 #ifdef CHARSET_EBCDIC
3088 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3092 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3093 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3096 #ifndef OPENSSL_NO_SSL_TRACE
3098 SSL_set_msg_callback(con, SSL_trace);
3101 SSL_set_msg_callback(con, msg_cb);
3102 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3106 i = BIO_gets(io, buf, bufsize - 1);
3107 if (i < 0) { /* error */
3108 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
3110 ERR_print_errors(bio_err);
3113 BIO_printf(bio_s_out, "read R BLOCK\n");
3114 #ifndef OPENSSL_NO_SRP
3115 if (BIO_should_io_special(io)
3116 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3117 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3118 SRP_user_pwd_free(srp_callback_parm.user);
3119 srp_callback_parm.user =
3120 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3121 srp_callback_parm.login);
3122 if (srp_callback_parm.user)
3123 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3124 srp_callback_parm.user->info);
3126 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3130 #if !defined(OPENSSL_SYS_MSDOS)
3135 } else if (i == 0) { /* end of input */
3140 /* else we have data */
3141 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
3142 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
3145 STACK_OF(SSL_CIPHER) *sk;
3146 static const char *space = " ";
3148 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
3149 if (strncmp("GET /renegcert", buf, 14) == 0)
3151 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
3153 i = SSL_renegotiate(con);
3154 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
3155 /* Send the HelloRequest */
3156 i = SSL_do_handshake(con);
3158 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
3159 SSL_get_error(con, i));
3160 ERR_print_errors(bio_err);
3163 /* Wait for a ClientHello to come back */
3165 openssl_fdset(s, &readfds);
3166 i = select(width, (void *)&readfds, NULL, NULL, NULL);
3167 if (i <= 0 || !FD_ISSET(s, &readfds)) {
3168 BIO_printf(bio_s_out,
3169 "Error waiting for client response\n");
3170 ERR_print_errors(bio_err);
3174 * We're not actually expecting any data here and we ignore
3175 * any that is sent. This is just to force the handshake that
3176 * we're expecting to come from the client. If they haven't
3177 * sent one there's not much we can do.
3179 BIO_gets(io, buf, bufsize - 1);
3183 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3184 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
3185 BIO_puts(io, "<pre>\n");
3186 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
3188 for (i = 0; i < local_argc; i++) {
3190 for (myp = local_argv[i]; *myp; myp++)
3193 BIO_puts(io, "<");
3196 BIO_puts(io, ">");
3199 BIO_puts(io, "&");
3202 BIO_write(io, myp, 1);
3205 BIO_write(io, " ", 1);
3210 "Secure Renegotiation IS%s supported\n",
3211 SSL_get_secure_renegotiation_support(con) ?
3215 * The following is evil and should not really be done
3217 BIO_printf(io, "Ciphers supported in s_server binary\n");
3218 sk = SSL_get_ciphers(con);
3219 j = sk_SSL_CIPHER_num(sk);
3220 for (i = 0; i < j; i++) {
3221 c = sk_SSL_CIPHER_value(sk, i);
3222 BIO_printf(io, "%-11s:%-25s ",
3223 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3224 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3228 p = SSL_get_shared_ciphers(con, buf, bufsize);
3231 "---\nCiphers common between both SSL end points:\n");
3235 BIO_write(io, space, 26 - j);
3238 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3240 BIO_write(io, p, 1);
3247 ssl_print_sigalgs(io, con);
3248 #ifndef OPENSSL_NO_EC
3249 ssl_print_groups(io, con, 0);
3251 print_ca_names(io, con);
3252 BIO_printf(io, (SSL_session_reused(con)
3253 ? "---\nReused, " : "---\nNew, "));
3254 c = SSL_get_current_cipher(con);
3255 BIO_printf(io, "%s, Cipher is %s\n",
3256 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3257 SSL_SESSION_print(io, SSL_get_session(con));
3258 BIO_printf(io, "---\n");
3259 print_stats(io, SSL_get_SSL_CTX(con));
3260 BIO_printf(io, "---\n");
3261 peer = SSL_get0_peer_certificate(con);
3263 BIO_printf(io, "Client certificate\n");
3264 X509_print(io, peer);
3265 PEM_write_bio_X509(io, peer);
3268 BIO_puts(io, "no client certificate available\n");
3270 BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
3272 } else if ((www == 2 || www == 3)
3273 && (strncmp("GET /", buf, 5) == 0)) {
3276 static const char *text =
3277 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3283 for (e = p; *e != '\0'; e++) {
3288 /* Windows drive. We treat this the same way as ".." */
3295 dot = (e[0] == '.') ? 2 : 0;
3298 dot = (e[0] == '.') ? 3 : 0;
3301 dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0;
3305 dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0;
3307 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3312 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3319 BIO_printf(io, "'%s' contains '..' or ':'\r\n", p);
3323 if (*p == '/' || *p == '\\') {
3325 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3329 /* if a directory, do the index thang */
3330 if (app_isdir(p) > 0) {
3332 BIO_printf(io, "'%s' is a directory\r\n", p);
3336 opmode = (http_server_binmode == 1) ? "rb" : "r";
3337 if ((file = BIO_new_file(p, opmode)) == NULL) {
3339 BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode);
3340 ERR_print_errors(io);
3345 BIO_printf(bio_err, "FILE:%s\n", p);
3349 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3350 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3351 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3353 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3356 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3359 #ifndef OPENSSL_NO_KTLS
3367 BIO_get_fp(file, &fp);
3369 if (fstat(fd, &st) < 0) {
3370 BIO_printf(io, "Error fstat '%s'\r\n", p);
3371 ERR_print_errors(io);
3375 filesize = st.st_size;
3376 if (((int)BIO_flush(io)) < 0)
3380 i = SSL_sendfile(con, fd, offset, filesize, 0);
3382 BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p);
3383 ERR_print_errors(io);
3390 if (filesize <= 0) {
3392 BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p);
3401 i = BIO_read(file, buf, bufsize);
3407 BIO_printf(bio_err, "%d\n", i);
3408 if (total_bytes > 3 * 1024) {
3410 BIO_printf(bio_err, "RENEGOTIATE\n");
3411 SSL_renegotiate(con);
3415 for (j = 0; j < i;) {
3419 SSL_renegotiate(con);
3421 k = BIO_write(io, &(buf[j]), i - j);
3423 if (!BIO_should_retry(io)
3424 && !SSL_waiting_for_async(con)) {
3427 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3442 i = (int)BIO_flush(io);
3444 if (!BIO_should_retry(io))
3450 /* make sure we re-use sessions */
3451 do_ssl_shutdown(con);
3459 static int rev_body(int s, int stype, int prot, unsigned char *context)
3465 BIO *io, *ssl_bio, *sbio;
3467 buf = app_malloc(bufsize, "server rev buffer");
3468 io = BIO_new(BIO_f_buffer());
3469 ssl_bio = BIO_new(BIO_f_ssl());
3470 if ((io == NULL) || (ssl_bio == NULL))
3473 /* lets make the output buffer a reasonable size */
3474 if (!BIO_set_write_buffer_size(io, bufsize))
3477 if ((con = SSL_new(ctx)) == NULL)
3480 if (s_tlsextdebug) {
3481 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3482 SSL_set_tlsext_debug_arg(con, bio_s_out);
3485 && !SSL_set_session_id_context(con, context,
3486 strlen((char *)context))) {
3488 ERR_print_errors(bio_err);
3492 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3493 SSL_set_bio(con, sbio, sbio);
3494 SSL_set_accept_state(con);
3496 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3497 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3498 BIO_push(io, ssl_bio);
3499 #ifdef CHARSET_EBCDIC
3500 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3504 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3505 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3508 #ifndef OPENSSL_NO_SSL_TRACE
3510 SSL_set_msg_callback(con, SSL_trace);
3513 SSL_set_msg_callback(con, msg_cb);
3514 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3518 i = BIO_do_handshake(io);
3521 if (!BIO_should_retry(io)) {
3522 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3523 ERR_print_errors(bio_err);
3526 #ifndef OPENSSL_NO_SRP
3527 if (BIO_should_io_special(io)
3528 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3529 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3530 SRP_user_pwd_free(srp_callback_parm.user);
3531 srp_callback_parm.user =
3532 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3533 srp_callback_parm.login);
3534 if (srp_callback_parm.user)
3535 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3536 srp_callback_parm.user->info);
3538 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3543 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3544 print_ssl_summary(con);
3547 i = BIO_gets(io, buf, bufsize - 1);
3548 if (i < 0) { /* error */
3549 if (!BIO_should_retry(io)) {
3551 ERR_print_errors(bio_err);
3554 BIO_printf(bio_s_out, "read R BLOCK\n");
3555 #ifndef OPENSSL_NO_SRP
3556 if (BIO_should_io_special(io)
3557 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3558 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3559 SRP_user_pwd_free(srp_callback_parm.user);
3560 srp_callback_parm.user =
3561 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3562 srp_callback_parm.login);
3563 if (srp_callback_parm.user)
3564 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3565 srp_callback_parm.user->info);
3567 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3571 #if !defined(OPENSSL_SYS_MSDOS)
3576 } else if (i == 0) { /* end of input */
3578 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3581 char *p = buf + i - 1;
3582 while (i && (*p == '\n' || *p == '\r')) {
3586 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3588 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3591 BUF_reverse((unsigned char *)buf, NULL, i);
3593 BIO_write(io, buf, i + 1);
3598 if (!BIO_should_retry(io))
3604 /* make sure we re-use sessions */
3605 do_ssl_shutdown(con);
3614 #define MAX_SESSION_ID_ATTEMPTS 10
3615 static int generate_session_id(SSL *ssl, unsigned char *id,
3616 unsigned int *id_len)
3618 unsigned int count = 0;
3619 unsigned int session_id_prefix_len = strlen(session_id_prefix);
3622 if (RAND_bytes(id, *id_len) <= 0)
3625 * Prefix the session_id with the required prefix. NB: If our prefix
3626 * is too long, clip it - but there will be worse effects anyway, eg.
3627 * the server could only possibly create 1 session ID (ie. the
3628 * prefix!) so all future session negotiations will fail due to
3631 memcpy(id, session_id_prefix,
3632 (session_id_prefix_len < *id_len) ?
3633 session_id_prefix_len : *id_len);
3635 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3636 (++count < MAX_SESSION_ID_ATTEMPTS));
3637 if (count >= MAX_SESSION_ID_ATTEMPTS)
3643 * By default s_server uses an in-memory cache which caches SSL_SESSION
3644 * structures without any serialization. This hides some bugs which only
3645 * become apparent in deployed servers. By implementing a basic external
3646 * session cache some issues can be debugged using s_server.
3649 typedef struct simple_ssl_session_st {
3654 struct simple_ssl_session_st *next;
3655 } simple_ssl_session;
3657 static simple_ssl_session *first = NULL;
3659 static int add_session(SSL *ssl, SSL_SESSION *session)
3661 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3664 SSL_SESSION_get_id(session, &sess->idlen);
3665 sess->derlen = i2d_SSL_SESSION(session, NULL);
3666 if (sess->derlen < 0) {
3667 BIO_printf(bio_err, "Error encoding session\n");
3672 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3673 sess->der = app_malloc(sess->derlen, "get session buffer");
3675 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3676 OPENSSL_free(sess->id);
3677 OPENSSL_free(sess->der);
3683 /* Assume it still works. */
3684 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3685 BIO_printf(bio_err, "Unexpected session encoding length\n");
3686 OPENSSL_free(sess->id);
3687 OPENSSL_free(sess->der);
3694 BIO_printf(bio_err, "New session added to external cache\n");
3698 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3701 simple_ssl_session *sess;
3703 for (sess = first; sess; sess = sess->next) {
3704 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3705 const unsigned char *p = sess->der;
3706 BIO_printf(bio_err, "Lookup session: cache hit\n");
3707 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3710 BIO_printf(bio_err, "Lookup session: cache miss\n");
3714 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3716 simple_ssl_session *sess, *prev = NULL;
3717 const unsigned char *id;
3719 id = SSL_SESSION_get_id(session, &idlen);
3720 for (sess = first; sess; sess = sess->next) {
3721 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3723 prev->next = sess->next;
3726 OPENSSL_free(sess->id);
3727 OPENSSL_free(sess->der);
3735 static void init_session_cache_ctx(SSL_CTX *sctx)
3737 SSL_CTX_set_session_cache_mode(sctx,
3738 SSL_SESS_CACHE_NO_INTERNAL |
3739 SSL_SESS_CACHE_SERVER);
3740 SSL_CTX_sess_set_new_cb(sctx, add_session);
3741 SSL_CTX_sess_set_get_cb(sctx, get_session);
3742 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3745 static void free_sessions(void)
3747 simple_ssl_session *sess, *tsess;
3748 for (sess = first; sess;) {
3749 OPENSSL_free(sess->id);
3750 OPENSSL_free(sess->der);
3753 OPENSSL_free(tsess);
3758 #endif /* OPENSSL_NO_SOCK */