2 * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4 * Copyright 2005 Nokia. All rights reserved.
6 * Licensed under the Apache License 2.0 (the "License"). You may not use
7 * this file except in compliance with the License. You can obtain a copy
8 * in the file LICENSE in the source distribution or at
9 * https://www.openssl.org/source/license.html
17 /* Included before async.h to avoid some warnings */
21 #include <openssl/e_os2.h>
22 #include <openssl/async.h>
23 #include <openssl/ssl.h>
24 #include <openssl/decoder.h>
26 #ifndef OPENSSL_NO_SOCK
29 * With IPv6, it looks like Digital has mixed up the proper order of
30 * recursive header file inclusion, resulting in the compiler complaining
31 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
32 * needed to have fileno() declared correctly... So let's define u_int
34 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
36 typedef unsigned int u_int;
39 #include <openssl/bn.h>
42 #include <openssl/err.h>
43 #include <openssl/pem.h>
44 #include <openssl/x509.h>
45 #include <openssl/ssl.h>
46 #include <openssl/rand.h>
47 #include <openssl/ocsp.h>
49 # include <openssl/dh.h>
51 #include <openssl/rsa.h>
55 #include <openssl/ebcdic.h>
57 #include "internal/sockets.h"
59 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
60 static int sv_body(int s, int stype, int prot, unsigned char *context);
61 static int www_body(int s, int stype, int prot, unsigned char *context);
62 static int rev_body(int s, int stype, int prot, unsigned char *context);
63 static void close_accept_socket(void);
64 static int init_ssl_connection(SSL *s);
65 static void print_stats(BIO *bp, SSL_CTX *ctx);
66 static int generate_session_id(SSL *ssl, unsigned char *id,
67 unsigned int *id_len);
68 static void init_session_cache_ctx(SSL_CTX *sctx);
69 static void free_sessions(void);
70 static void print_connection_info(SSL *con);
72 static const int bufsize = 16 * 1024;
73 static int accept_socket = -1;
75 #define TEST_CERT "server.pem"
76 #define TEST_CERT2 "server2.pem"
78 static int s_nbio = 0;
79 static int s_nbio_test = 0;
80 static int s_crlf = 0;
81 static SSL_CTX *ctx = NULL;
82 static SSL_CTX *ctx2 = NULL;
85 static BIO *bio_s_out = NULL;
86 static BIO *bio_s_msg = NULL;
87 static int s_debug = 0;
88 static int s_tlsextdebug = 0;
90 static int s_quiet = 0;
91 static int s_ign_eof = 0;
92 static int s_brief = 0;
94 static char *keymatexportlabel = NULL;
95 static int keymatexportlen = 20;
99 static int use_sendfile = 0;
101 static const char *session_id_prefix = NULL;
103 #ifndef OPENSSL_NO_DTLS
104 static int enable_timeouts = 0;
105 static long socket_mtu;
109 * We define this but make it always be 0 in no-dtls builds to simplify the
112 static int dtlslisten = 0;
113 static int stateless = 0;
115 static int early_data = 0;
116 static SSL_SESSION *psksess = NULL;
118 static char *psk_identity = "Client_identity";
119 char *psk_key = NULL; /* by default PSK is not used */
121 static char http_server_binmode = 0; /* for now: 0/1 = default/binary */
123 #ifndef OPENSSL_NO_PSK
124 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
126 unsigned int max_psk_len)
132 BIO_printf(bio_s_out, "psk_server_cb\n");
133 if (identity == NULL) {
134 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
138 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
139 (int)strlen(identity), identity);
141 /* here we could lookup the given identity e.g. from a database */
142 if (strcmp(identity, psk_identity) != 0) {
143 BIO_printf(bio_s_out, "PSK warning: client identity not what we expected"
144 " (got '%s' expected '%s')\n", identity, psk_identity);
147 BIO_printf(bio_s_out, "PSK client identity found\n");
150 /* convert the PSK key to binary */
151 key = OPENSSL_hexstr2buf(psk_key, &key_len);
153 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
157 if (key_len > (int)max_psk_len) {
159 "psk buffer of callback is too small (%d) for key (%ld)\n",
160 max_psk_len, key_len);
165 memcpy(psk, key, key_len);
169 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
173 BIO_printf(bio_err, "Error in PSK server callback\n");
174 (void)BIO_flush(bio_err);
175 (void)BIO_flush(bio_s_out);
180 static int psk_find_session_cb(SSL *ssl, const unsigned char *identity,
181 size_t identity_len, SSL_SESSION **sess)
183 SSL_SESSION *tmpsess = NULL;
186 const SSL_CIPHER *cipher = NULL;
188 if (strlen(psk_identity) != identity_len
189 || memcmp(psk_identity, identity, identity_len) != 0) {
194 if (psksess != NULL) {
195 SSL_SESSION_up_ref(psksess);
200 key = OPENSSL_hexstr2buf(psk_key, &key_len);
202 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
207 /* We default to SHA256 */
208 cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id);
209 if (cipher == NULL) {
210 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
215 tmpsess = SSL_SESSION_new();
217 || !SSL_SESSION_set1_master_key(tmpsess, key, key_len)
218 || !SSL_SESSION_set_cipher(tmpsess, cipher)
219 || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) {
229 #ifndef OPENSSL_NO_SRP
230 static srpsrvparm srp_callback_parm;
233 static int local_argc = 0;
234 static char **local_argv;
236 #ifdef CHARSET_EBCDIC
237 static int ebcdic_new(BIO *bi);
238 static int ebcdic_free(BIO *a);
239 static int ebcdic_read(BIO *b, char *out, int outl);
240 static int ebcdic_write(BIO *b, const char *in, int inl);
241 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
242 static int ebcdic_gets(BIO *bp, char *buf, int size);
243 static int ebcdic_puts(BIO *bp, const char *str);
245 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
246 static BIO_METHOD *methods_ebcdic = NULL;
248 /* This struct is "unwarranted chumminess with the compiler." */
254 static const BIO_METHOD *BIO_f_ebcdic_filter()
256 if (methods_ebcdic == NULL) {
257 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
258 "EBCDIC/ASCII filter");
259 if (methods_ebcdic == NULL
260 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
261 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
262 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
263 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
264 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
265 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
266 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
269 return methods_ebcdic;
272 static int ebcdic_new(BIO *bi)
274 EBCDIC_OUTBUFF *wbuf;
276 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
277 wbuf->alloced = 1024;
278 wbuf->buff[0] = '\0';
280 BIO_set_data(bi, wbuf);
285 static int ebcdic_free(BIO *a)
287 EBCDIC_OUTBUFF *wbuf;
291 wbuf = BIO_get_data(a);
293 BIO_set_data(a, NULL);
299 static int ebcdic_read(BIO *b, char *out, int outl)
302 BIO *next = BIO_next(b);
304 if (out == NULL || outl == 0)
309 ret = BIO_read(next, out, outl);
311 ascii2ebcdic(out, out, ret);
315 static int ebcdic_write(BIO *b, const char *in, int inl)
317 EBCDIC_OUTBUFF *wbuf;
318 BIO *next = BIO_next(b);
322 if ((in == NULL) || (inl <= 0))
327 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
329 if (inl > (num = wbuf->alloced)) {
330 num = num + num; /* double the size */
334 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
337 wbuf->buff[0] = '\0';
339 BIO_set_data(b, wbuf);
342 ebcdic2ascii(wbuf->buff, in, inl);
344 ret = BIO_write(next, wbuf->buff, inl);
349 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
352 BIO *next = BIO_next(b);
361 ret = BIO_ctrl(next, cmd, num, ptr);
367 static int ebcdic_gets(BIO *bp, char *buf, int size)
370 BIO *next = BIO_next(bp);
374 /* return(BIO_gets(bp->next_bio,buf,size));*/
375 for (i = 0; i < size - 1; ++i) {
376 ret = ebcdic_read(bp, &buf[i], 1);
379 else if (buf[i] == '\n') {
386 return (ret < 0 && i == 0) ? ret : i;
389 static int ebcdic_puts(BIO *bp, const char *str)
391 if (BIO_next(bp) == NULL)
393 return ebcdic_write(bp, str, strlen(str));
397 /* This is a context that we pass to callbacks */
398 typedef struct tlsextctx_st {
404 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
406 tlsextctx *p = (tlsextctx *) arg;
407 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
409 if (servername != NULL && p->biodebug != NULL) {
410 const char *cp = servername;
413 BIO_printf(p->biodebug, "Hostname in TLS extension: \"");
414 while ((uc = *cp++) != 0)
415 BIO_printf(p->biodebug,
416 (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc);
417 BIO_printf(p->biodebug, "\"\n");
420 if (p->servername == NULL)
421 return SSL_TLSEXT_ERR_NOACK;
423 if (servername != NULL) {
424 if (strcasecmp(servername, p->servername))
425 return p->extension_error;
427 BIO_printf(p->biodebug, "Switching server context.\n");
428 SSL_set_SSL_CTX(s, ctx2);
431 return SSL_TLSEXT_ERR_OK;
434 /* Structure passed to cert status callback */
435 typedef struct tlsextstatusctx_st {
437 /* File to load OCSP Response from (or NULL if no file) */
439 /* Default responder to use */
440 char *host, *path, *port;
445 static tlsextstatusctx tlscstatp = { -1 };
447 #ifndef OPENSSL_NO_OCSP
450 * Helper function to get an OCSP_RESPONSE from a responder. This is a
451 * simplified version. It examines certificates each time and makes one OCSP
452 * responder query for each request. A full version would store details such as
453 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
454 * them until they were considered "expired".
456 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
457 OCSP_RESPONSE **resp)
459 char *host = NULL, *port = NULL, *path = NULL;
461 STACK_OF(OPENSSL_STRING) *aia = NULL;
463 X509_STORE_CTX *inctx = NULL;
465 OCSP_REQUEST *req = NULL;
466 OCSP_CERTID *id = NULL;
467 STACK_OF(X509_EXTENSION) *exts;
468 int ret = SSL_TLSEXT_ERR_NOACK;
471 /* Build up OCSP query from server certificate */
472 x = SSL_get_certificate(s);
473 aia = X509_get1_ocsp(x);
475 if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl,
476 NULL, &host, &port, NULL, &path, NULL, NULL)) {
477 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
481 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
482 sk_OPENSSL_STRING_value(aia, 0));
484 if (srctx->host == NULL) {
486 "cert_status: no AIA and no default responder URL\n");
492 use_ssl = srctx->use_ssl;
495 inctx = X509_STORE_CTX_new();
498 if (!X509_STORE_CTX_init(inctx,
499 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
502 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
503 X509_get_issuer_name(x));
505 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
508 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
509 X509_OBJECT_free(obj);
512 req = OCSP_REQUEST_new();
515 if (!OCSP_request_add0_id(req, id))
518 /* Add any extensions to the request */
519 SSL_get_tlsext_status_exts(s, &exts);
520 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
521 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
522 if (!OCSP_REQUEST_add_ext(req, ext, -1))
525 *resp = process_responder(req, host, path, port, use_ssl, NULL,
528 BIO_puts(bio_err, "cert_status: error querying responder\n");
532 ret = SSL_TLSEXT_ERR_OK;
536 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
539 * If we parsed aia we need to free; otherwise they were copied and we
546 X509_email_free(aia);
548 OCSP_CERTID_free(id);
549 OCSP_REQUEST_free(req);
550 X509_STORE_CTX_free(inctx);
555 * Certificate Status callback. This is called when a client includes a
556 * certificate status request extension. The response is either obtained from a
557 * file, or from an OCSP responder.
559 static int cert_status_cb(SSL *s, void *arg)
561 tlsextstatusctx *srctx = arg;
562 OCSP_RESPONSE *resp = NULL;
563 unsigned char *rspder = NULL;
565 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
568 BIO_puts(bio_err, "cert_status: callback called\n");
570 if (srctx->respin != NULL) {
571 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
572 if (derbio == NULL) {
573 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
576 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
579 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
583 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
584 if (ret != SSL_TLSEXT_ERR_OK)
588 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
592 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
593 if (srctx->verbose) {
594 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
595 OCSP_RESPONSE_print(bio_err, resp, 2);
598 ret = SSL_TLSEXT_ERR_OK;
601 if (ret != SSL_TLSEXT_ERR_OK)
602 ERR_print_errors(bio_err);
604 OCSP_RESPONSE_free(resp);
610 #ifndef OPENSSL_NO_NEXTPROTONEG
611 /* This is the context that we pass to next_proto_cb */
612 typedef struct tlsextnextprotoctx_st {
615 } tlsextnextprotoctx;
617 static int next_proto_cb(SSL *s, const unsigned char **data,
618 unsigned int *len, void *arg)
620 tlsextnextprotoctx *next_proto = arg;
622 *data = next_proto->data;
623 *len = next_proto->len;
625 return SSL_TLSEXT_ERR_OK;
627 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
629 /* This the context that we pass to alpn_cb */
630 typedef struct tlsextalpnctx_st {
635 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
636 const unsigned char *in, unsigned int inlen, void *arg)
638 tlsextalpnctx *alpn_ctx = arg;
641 /* We can assume that |in| is syntactically valid. */
643 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
644 for (i = 0; i < inlen;) {
646 BIO_write(bio_s_out, ", ", 2);
647 BIO_write(bio_s_out, &in[i + 1], in[i]);
650 BIO_write(bio_s_out, "\n", 1);
653 if (SSL_select_next_proto
654 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
655 inlen) != OPENSSL_NPN_NEGOTIATED) {
656 return SSL_TLSEXT_ERR_ALERT_FATAL;
660 BIO_printf(bio_s_out, "ALPN protocols selected: ");
661 BIO_write(bio_s_out, *out, *outlen);
662 BIO_write(bio_s_out, "\n", 1);
665 return SSL_TLSEXT_ERR_OK;
668 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
670 /* disable resumption for sessions with forward secure ciphers */
671 return is_forward_secure;
674 typedef enum OPTION_choice {
675 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
676 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
677 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
678 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
679 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
680 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
681 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
682 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
683 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
685 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
686 OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
687 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
688 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
689 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
690 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
691 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK,
692 OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW,
693 OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG,
694 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
695 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
696 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS,
697 OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
698 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE,
699 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
700 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA,
701 OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG,
702 OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF,
710 const OPTIONS s_server_options[] = {
711 OPT_SECTION("General"),
712 {"help", OPT_HELP, '-', "Display this summary"},
713 {"ssl_config", OPT_SSL_CONFIG, 's',
714 "Configure SSL_CTX using the configuration 'val'"},
715 #ifndef OPENSSL_NO_SSL_TRACE
716 {"trace", OPT_TRACE, '-', "trace protocol messages"},
718 #ifndef OPENSSL_NO_ENGINE
719 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
722 OPT_SECTION("Network"),
723 {"port", OPT_PORT, 'p',
724 "TCP/IP port to listen on for connections (default is " PORT ")"},
725 {"accept", OPT_ACCEPT, 's',
726 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
728 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
729 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
731 {"4", OPT_4, '-', "Use IPv4 only"},
732 {"6", OPT_6, '-', "Use IPv6 only"},
734 OPT_SECTION("Identity"),
735 {"context", OPT_CONTEXT, 's', "Set session ID context"},
736 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
737 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
738 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
739 {"no-CAfile", OPT_NOCAFILE, '-',
740 "Do not load the default certificates file"},
741 {"no-CApath", OPT_NOCAPATH, '-',
742 "Do not load certificates from the default certificates directory"},
743 {"no-CAstore", OPT_NOCASTORE, '-',
744 "Do not load certificates from the default certificates store URI"},
745 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
746 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
747 {"Verify", OPT_UPPER_V_VERIFY, 'n',
748 "Turn on peer certificate verification, must have a cert"},
749 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
750 {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT},
751 {"cert2", OPT_CERT2, '<',
752 "Certificate file to use for servername; default " TEST_CERT2},
753 {"certform", OPT_CERTFORM, 'F',
754 "Server certificate file format (PEM/DER/P12); has no effect"},
755 {"cert_chain", OPT_CERT_CHAIN, '<',
756 "Server certificate chain file in PEM format"},
757 {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"},
758 {"serverinfo", OPT_SERVERINFO, 's',
759 "PEM serverinfo file for certificate"},
760 {"key", OPT_KEY, 's',
761 "Private key file to use; default is -cert file or else" TEST_CERT},
762 {"key2", OPT_KEY2, '<',
763 "-Private Key file to use for servername if not in -cert2"},
764 {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"},
765 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
766 {"dcert", OPT_DCERT, '<',
767 "Second server certificate file to use (usually for DSA)"},
768 {"dcertform", OPT_DCERTFORM, 'F',
769 "Second server certificate file format (PEM/DER/P12); has no effect"},
770 {"dcert_chain", OPT_DCERT_CHAIN, '<',
771 "second server certificate chain file in PEM format"},
772 {"dkey", OPT_DKEY, '<',
773 "Second private key file to use (usually for DSA)"},
774 {"dkeyform", OPT_DKEYFORM, 'F',
775 "Second key file format (ENGINE, other values ignored)"},
776 {"dpass", OPT_DPASS, 's',
777 "Second private key and cert file pass phrase source"},
778 {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
779 {"servername", OPT_SERVERNAME, 's',
780 "Servername for HostName TLS extension"},
781 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
782 "mismatch send fatal alert (default warning alert)"},
783 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
784 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
785 {"quiet", OPT_QUIET, '-', "No server output"},
786 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
787 "Disable caching and tickets if ephemeral (EC)DH is used"},
788 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
789 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
790 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
791 "Do not treat lack of close_notify from a peer as an error"},
792 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
793 "Hex dump of all TLS extensions received"},
794 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
795 {"id_prefix", OPT_ID_PREFIX, 's',
796 "Generate SSL/TLS session IDs prefixed by arg"},
797 {"keymatexport", OPT_KEYMATEXPORT, 's',
798 "Export keying material using label"},
799 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
800 "Export len bytes of keying material; default 20"},
801 {"CRL", OPT_CRL, '<', "CRL file to use"},
802 {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"},
803 {"crl_download", OPT_CRL_DOWNLOAD, '-',
804 "Download CRLs from distribution points in certificate CDP entries"},
805 {"chainCAfile", OPT_CHAINCAFILE, '<',
806 "CA file for certificate chain (PEM format)"},
807 {"chainCApath", OPT_CHAINCAPATH, '/',
808 "use dir as certificate store path to build CA certificate chain"},
809 {"chainCAstore", OPT_CHAINCASTORE, ':',
810 "use URI as certificate store to build CA certificate chain"},
811 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
812 "CA file for certificate verification (PEM format)"},
813 {"verifyCApath", OPT_VERIFYCAPATH, '/',
814 "use dir as certificate store path to verify CA certificate"},
815 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
816 "use URI as certificate store to verify CA certificate"},
817 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
818 {"ext_cache", OPT_EXT_CACHE, '-',
819 "Disable internal cache, setup and use external cache"},
820 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
821 "Close connection on verification error"},
822 {"verify_quiet", OPT_VERIFY_QUIET, '-',
823 "No verify output except verify errors"},
824 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
825 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
827 #ifndef OPENSSL_NO_OCSP
829 {"status", OPT_STATUS, '-', "Request certificate status from server"},
830 {"status_verbose", OPT_STATUS_VERBOSE, '-',
831 "Print more output in certificate status callback"},
832 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
833 "Status request responder timeout"},
834 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
835 {"status_file", OPT_STATUS_FILE, '<',
836 "File containing DER encoded OCSP Response"},
839 OPT_SECTION("Debug"),
840 {"security_debug", OPT_SECURITY_DEBUG, '-',
841 "Print output from SSL/TLS security framework"},
842 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
843 "Print more output from SSL/TLS security framework"},
844 {"brief", OPT_BRIEF, '-',
845 "Restrict output to brief summary of connection parameters"},
846 {"rev", OPT_REV, '-',
847 "act as a simple test server which just sends back with the received text reversed"},
848 {"debug", OPT_DEBUG, '-', "Print more output"},
849 {"msg", OPT_MSG, '-', "Show protocol messages"},
850 {"msgfile", OPT_MSGFILE, '>',
851 "File to send output of -msg or -trace, instead of stdout"},
852 {"state", OPT_STATE, '-', "Print the SSL states"},
853 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
854 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
855 "Maximum number of encrypt/decrypt pipelines to be used"},
856 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
857 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
859 OPT_SECTION("Network"),
860 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
861 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
862 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
863 {"read_buf", OPT_READ_BUF, 'p',
864 "Default read buffer size to be used for connections"},
865 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
866 "Size used to split data for encrypt pipelines"},
867 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
869 OPT_SECTION("Server identity"),
870 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
871 #ifndef OPENSSL_NO_PSK
872 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
874 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
875 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
876 #ifndef OPENSSL_NO_SRP
877 {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"},
878 {"srpuserseed", OPT_SRPUSERSEED, 's',
879 "(deprecated) A seed string for a default user salt"},
882 OPT_SECTION("Protocol and version"),
883 {"max_early_data", OPT_MAX_EARLY, 'n',
884 "The maximum number of bytes of early data as advertised in tickets"},
885 {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n',
886 "The maximum number of bytes of early data (hard limit)"},
887 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
888 {"num_tickets", OPT_S_NUM_TICKETS, 'n',
889 "The number of TLSv1.3 session tickets that a server will automatically issue" },
890 {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"},
891 {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"},
892 {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"},
893 {"no_ca_names", OPT_NOCANAMES, '-',
894 "Disable TLS Extension CA Names"},
895 {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"},
896 #ifndef OPENSSL_NO_SSL3
897 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
899 #ifndef OPENSSL_NO_TLS1
900 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
902 #ifndef OPENSSL_NO_TLS1_1
903 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
905 #ifndef OPENSSL_NO_TLS1_2
906 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
908 #ifndef OPENSSL_NO_TLS1_3
909 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
911 #ifndef OPENSSL_NO_DTLS
912 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
913 {"listen", OPT_LISTEN, '-',
914 "Listen for a DTLS ClientHello with a cookie and then connect"},
916 #ifndef OPENSSL_NO_DTLS1
917 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
919 #ifndef OPENSSL_NO_DTLS1_2
920 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
922 #ifndef OPENSSL_NO_SCTP
923 {"sctp", OPT_SCTP, '-', "Use SCTP"},
924 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
926 #ifndef OPENSSL_NO_SRTP
927 {"use_srtp", OPT_SRTP_PROFILES, 's',
928 "Offer SRTP key management with a colon-separated profile list"},
930 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
931 #ifndef OPENSSL_NO_NEXTPROTONEG
932 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
933 "Set the advertised protocols for the NPN extension (comma-separated list)"},
935 {"alpn", OPT_ALPN, 's',
936 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
937 #ifndef OPENSSL_NO_KTLS
938 {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"},
949 #define IS_PROT_FLAG(o) \
950 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
951 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
953 int s_server_main(int argc, char *argv[])
955 ENGINE *engine = NULL;
956 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
957 SSL_CONF_CTX *cctx = NULL;
958 const SSL_METHOD *meth = TLS_server_method();
959 SSL_EXCERT *exc = NULL;
960 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
961 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
962 STACK_OF(X509_CRL) *crls = NULL;
963 X509 *s_cert = NULL, *s_dcert = NULL;
964 X509_VERIFY_PARAM *vpm = NULL;
965 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
966 const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL;
967 char *dpassarg = NULL, *dpass = NULL;
968 char *passarg = NULL, *pass = NULL;
969 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
970 char *crl_file = NULL, *prog;
972 int unlink_unix_path = 0;
974 do_server_cb server_cb;
975 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
978 int nocert = 0, ret = 1;
979 int noCApath = 0, noCAfile = 0, noCAstore = 0;
980 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
981 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
982 int rev = 0, naccept = -1, sdebug = 0;
983 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
984 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
986 char *port = OPENSSL_strdup(PORT);
987 unsigned char *context = NULL;
989 EVP_PKEY *s_key2 = NULL;
990 X509 *s_cert2 = NULL;
991 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
992 const char *ssl_config = NULL;
993 int read_buf_len = 0;
994 #ifndef OPENSSL_NO_NEXTPROTONEG
995 const char *next_proto_neg_in = NULL;
996 tlsextnextprotoctx next_proto = { NULL, 0 };
998 const char *alpn_in = NULL;
999 tlsextalpnctx alpn_ctx = { NULL, 0 };
1000 #ifndef OPENSSL_NO_PSK
1001 /* by default do not send a PSK identity hint */
1002 char *psk_identity_hint = NULL;
1005 #ifndef OPENSSL_NO_SRP
1006 char *srpuserseed = NULL;
1007 char *srp_verifier_file = NULL;
1009 #ifndef OPENSSL_NO_SRTP
1010 char *srtp_profiles = NULL;
1012 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1013 int s_server_verify = SSL_VERIFY_NONE;
1014 int s_server_session_id_context = 1; /* anything will do */
1015 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
1016 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
1017 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
1018 #ifndef OPENSSL_NO_OCSP
1019 int s_tlsextstatus = 0;
1021 int no_resume_ephemeral = 0;
1022 unsigned int max_send_fragment = 0;
1023 unsigned int split_send_fragment = 0, max_pipelines = 0;
1024 const char *s_serverinfo_file = NULL;
1025 const char *keylog_file = NULL;
1026 int max_early_data = -1, recv_max_early_data = -1;
1027 char *psksessf = NULL;
1028 int no_ca_names = 0;
1029 #ifndef OPENSSL_NO_SCTP
1030 int sctp_label_bug = 0;
1032 int ignore_unexpected_eof = 0;
1034 /* Init of few remaining global variables */
1039 s_nbio = s_nbio_test = 0;
1049 cctx = SSL_CONF_CTX_new();
1050 vpm = X509_VERIFY_PARAM_new();
1051 if (cctx == NULL || vpm == NULL)
1053 SSL_CONF_CTX_set_flags(cctx,
1054 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1056 prog = opt_init(argc, argv, s_server_options);
1057 while ((o = opt_next()) != OPT_EOF) {
1058 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1059 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1062 if (IS_NO_PROT_FLAG(o))
1064 if (prot_opt == 1 && no_prot_opt) {
1066 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1073 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1076 opt_help(s_server_options);
1082 if (socket_family == AF_UNIX) {
1083 OPENSSL_free(host); host = NULL;
1084 OPENSSL_free(port); port = NULL;
1087 socket_family = AF_INET;
1093 if (socket_family == AF_UNIX) {
1094 OPENSSL_free(host); host = NULL;
1095 OPENSSL_free(port); port = NULL;
1098 socket_family = AF_INET6;
1101 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1107 if (socket_family == AF_UNIX) {
1108 socket_family = AF_UNSPEC;
1111 OPENSSL_free(port); port = NULL;
1112 OPENSSL_free(host); host = NULL;
1113 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1115 "%s: -port argument malformed or ambiguous\n",
1122 if (socket_family == AF_UNIX) {
1123 socket_family = AF_UNSPEC;
1126 OPENSSL_free(port); port = NULL;
1127 OPENSSL_free(host); host = NULL;
1128 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1130 "%s: -accept argument malformed or ambiguous\n",
1137 socket_family = AF_UNIX;
1138 OPENSSL_free(host); host = OPENSSL_strdup(opt_arg());
1139 OPENSSL_free(port); port = NULL;
1142 unlink_unix_path = 1;
1146 naccept = atol(opt_arg());
1149 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1150 verify_args.depth = atoi(opt_arg());
1152 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1154 case OPT_UPPER_V_VERIFY:
1156 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1157 SSL_VERIFY_CLIENT_ONCE;
1158 verify_args.depth = atoi(opt_arg());
1161 "verify depth is %d, must return a certificate\n",
1165 context = (unsigned char *)opt_arg();
1168 s_cert_file = opt_arg();
1171 if (!set_nameopt(opt_arg()))
1175 crl_file = opt_arg();
1177 case OPT_CRL_DOWNLOAD:
1180 case OPT_SERVERINFO:
1181 s_serverinfo_file = opt_arg();
1184 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format))
1188 s_key_file = opt_arg();
1191 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1195 passarg = opt_arg();
1197 case OPT_CERT_CHAIN:
1198 s_chain_file = opt_arg();
1204 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format))
1208 s_dcert_file = opt_arg();
1211 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format))
1215 dpassarg = opt_arg();
1218 s_dkey_file = opt_arg();
1220 case OPT_DCERT_CHAIN:
1221 s_dchain_file = opt_arg();
1232 case OPT_CHAINCAPATH:
1233 chCApath = opt_arg();
1235 case OPT_VERIFYCAPATH:
1236 vfyCApath = opt_arg();
1239 CAstore = opt_arg();
1244 case OPT_CHAINCASTORE:
1245 chCAstore = opt_arg();
1247 case OPT_VERIFYCASTORE:
1248 vfyCAstore = opt_arg();
1257 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1261 case OPT_S_NUM_TICKETS:
1262 case OPT_ANTI_REPLAY:
1263 case OPT_NO_ANTI_REPLAY:
1264 if (ssl_args == NULL)
1265 ssl_args = sk_OPENSSL_STRING_new_null();
1266 if (ssl_args == NULL
1267 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1268 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1269 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1274 if (!opt_verify(o, vpm))
1279 if (!args_excert(o, &exc))
1282 case OPT_VERIFY_RET_ERROR:
1283 verify_args.return_error = 1;
1285 case OPT_VERIFY_QUIET:
1286 verify_args.quiet = 1;
1288 case OPT_BUILD_CHAIN:
1297 case OPT_CHAINCAFILE:
1298 chCAfile = opt_arg();
1300 case OPT_VERIFYCAFILE:
1301 vfyCAfile = opt_arg();
1307 s_nbio = s_nbio_test = 1;
1312 case OPT_NO_IGN_EOF:
1318 case OPT_TLSEXTDEBUG:
1322 #ifndef OPENSSL_NO_OCSP
1326 case OPT_STATUS_VERBOSE:
1327 #ifndef OPENSSL_NO_OCSP
1328 s_tlsextstatus = tlscstatp.verbose = 1;
1331 case OPT_STATUS_TIMEOUT:
1332 #ifndef OPENSSL_NO_OCSP
1334 tlscstatp.timeout = atoi(opt_arg());
1337 case OPT_STATUS_URL:
1338 #ifndef OPENSSL_NO_OCSP
1340 if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL,
1341 &tlscstatp.host, &tlscstatp.port, NULL,
1342 &tlscstatp.path, NULL, NULL)) {
1343 BIO_printf(bio_err, "Error parsing -status_url argument\n");
1348 case OPT_STATUS_FILE:
1349 #ifndef OPENSSL_NO_OCSP
1351 tlscstatp.respin = opt_arg();
1358 bio_s_msg = BIO_new_file(opt_arg(), "w");
1361 #ifndef OPENSSL_NO_SSL_TRACE
1365 case OPT_SECURITY_DEBUG:
1368 case OPT_SECURITY_DEBUG_VERBOSE:
1381 s_quiet = s_brief = verify_args.quiet = 1;
1386 case OPT_NO_RESUME_EPHEMERAL:
1387 no_resume_ephemeral = 1;
1389 case OPT_PSK_IDENTITY:
1390 psk_identity = opt_arg();
1393 #ifndef OPENSSL_NO_PSK
1394 psk_identity_hint = opt_arg();
1398 for (p = psk_key = opt_arg(); *p; p++) {
1399 if (isxdigit(_UC(*p)))
1401 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1406 psksessf = opt_arg();
1409 #ifndef OPENSSL_NO_SRP
1410 srp_verifier_file = opt_arg();
1411 if (min_version < TLS1_VERSION)
1412 min_version = TLS1_VERSION;
1415 case OPT_SRPUSERSEED:
1416 #ifndef OPENSSL_NO_SRP
1417 srpuserseed = opt_arg();
1418 if (min_version < TLS1_VERSION)
1419 min_version = TLS1_VERSION;
1434 case OPT_SSL_CONFIG:
1435 ssl_config = opt_arg();
1438 min_version = SSL3_VERSION;
1439 max_version = SSL3_VERSION;
1442 min_version = TLS1_3_VERSION;
1443 max_version = TLS1_3_VERSION;
1446 min_version = TLS1_2_VERSION;
1447 max_version = TLS1_2_VERSION;
1450 min_version = TLS1_1_VERSION;
1451 max_version = TLS1_1_VERSION;
1454 min_version = TLS1_VERSION;
1455 max_version = TLS1_VERSION;
1458 #ifndef OPENSSL_NO_DTLS
1459 meth = DTLS_server_method();
1460 socket_type = SOCK_DGRAM;
1464 #ifndef OPENSSL_NO_DTLS
1465 meth = DTLS_server_method();
1466 min_version = DTLS1_VERSION;
1467 max_version = DTLS1_VERSION;
1468 socket_type = SOCK_DGRAM;
1472 #ifndef OPENSSL_NO_DTLS
1473 meth = DTLS_server_method();
1474 min_version = DTLS1_2_VERSION;
1475 max_version = DTLS1_2_VERSION;
1476 socket_type = SOCK_DGRAM;
1480 #ifndef OPENSSL_NO_SCTP
1481 protocol = IPPROTO_SCTP;
1484 case OPT_SCTP_LABEL_BUG:
1485 #ifndef OPENSSL_NO_SCTP
1490 #ifndef OPENSSL_NO_DTLS
1491 enable_timeouts = 1;
1495 #ifndef OPENSSL_NO_DTLS
1496 socket_mtu = atol(opt_arg());
1500 #ifndef OPENSSL_NO_DTLS
1508 session_id_prefix = opt_arg();
1511 #ifndef OPENSSL_NO_ENGINE
1512 engine = setup_engine(opt_arg(), s_debug);
1519 case OPT_PROV_CASES:
1520 if (!opt_provider(o))
1523 case OPT_SERVERNAME:
1524 tlsextcbp.servername = opt_arg();
1526 case OPT_SERVERNAME_FATAL:
1527 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1530 s_cert_file2 = opt_arg();
1533 s_key_file2 = opt_arg();
1535 case OPT_NEXTPROTONEG:
1536 # ifndef OPENSSL_NO_NEXTPROTONEG
1537 next_proto_neg_in = opt_arg();
1541 alpn_in = opt_arg();
1543 case OPT_SRTP_PROFILES:
1544 #ifndef OPENSSL_NO_SRTP
1545 srtp_profiles = opt_arg();
1548 case OPT_KEYMATEXPORT:
1549 keymatexportlabel = opt_arg();
1551 case OPT_KEYMATEXPORTLEN:
1552 keymatexportlen = atoi(opt_arg());
1557 case OPT_MAX_SEND_FRAG:
1558 max_send_fragment = atoi(opt_arg());
1560 case OPT_SPLIT_SEND_FRAG:
1561 split_send_fragment = atoi(opt_arg());
1563 case OPT_MAX_PIPELINES:
1564 max_pipelines = atoi(opt_arg());
1567 read_buf_len = atoi(opt_arg());
1569 case OPT_KEYLOG_FILE:
1570 keylog_file = opt_arg();
1573 max_early_data = atoi(opt_arg());
1574 if (max_early_data < 0) {
1575 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1579 case OPT_RECV_MAX_EARLY:
1580 recv_max_early_data = atoi(opt_arg());
1581 if (recv_max_early_data < 0) {
1582 BIO_printf(bio_err, "Invalid value for recv_max_early_data\n");
1586 case OPT_EARLY_DATA:
1588 if (max_early_data == -1)
1589 max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
1591 case OPT_HTTP_SERVER_BINMODE:
1592 http_server_binmode = 1;
1598 #ifndef OPENSSL_NO_KTLS
1602 case OPT_IGNORE_UNEXPECTED_EOF:
1603 ignore_unexpected_eof = 1;
1608 /* No extra arguments. */
1609 argc = opt_num_rest();
1614 #ifndef OPENSSL_NO_NEXTPROTONEG
1615 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1616 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1620 #ifndef OPENSSL_NO_DTLS
1621 if (www && socket_type == SOCK_DGRAM) {
1622 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1626 if (dtlslisten && socket_type != SOCK_DGRAM) {
1627 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1632 if (stateless && socket_type != SOCK_STREAM) {
1633 BIO_printf(bio_err, "Can only use --stateless with TLS\n");
1638 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1640 "Can't use unix sockets and datagrams together\n");
1644 if (early_data && (www > 0 || rev)) {
1646 "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n");
1650 #ifndef OPENSSL_NO_SCTP
1651 if (protocol == IPPROTO_SCTP) {
1652 if (socket_type != SOCK_DGRAM) {
1653 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1656 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1657 socket_type = SOCK_STREAM;
1661 #ifndef OPENSSL_NO_KTLS
1662 if (use_sendfile && www <= 1) {
1663 BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n");
1668 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1669 BIO_printf(bio_err, "Error getting password\n");
1673 if (s_key_file == NULL)
1674 s_key_file = s_cert_file;
1676 if (s_key_file2 == NULL)
1677 s_key_file2 = s_cert_file2;
1679 if (!load_excert(&exc))
1683 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1684 "server certificate private key");
1688 s_cert = load_cert_pass(s_cert_file, 1, pass, "server certificate");
1692 if (s_chain_file != NULL) {
1693 if (!load_certs(s_chain_file, &s_chain, NULL,
1694 "server certificate chain"))
1698 if (tlsextcbp.servername != NULL) {
1699 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1700 "second server certificate private key");
1704 s_cert2 = load_cert_pass(s_cert_file2, 1, pass,
1705 "second server certificate");
1707 if (s_cert2 == NULL)
1711 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1712 if (next_proto_neg_in) {
1713 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1714 if (next_proto.data == NULL)
1718 alpn_ctx.data = NULL;
1720 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1721 if (alpn_ctx.data == NULL)
1725 if (crl_file != NULL) {
1727 crl = load_crl(crl_file, "CRL");
1730 crls = sk_X509_CRL_new_null();
1731 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1732 BIO_puts(bio_err, "Error adding CRL\n");
1733 ERR_print_errors(bio_err);
1739 if (s_dcert_file != NULL) {
1741 if (s_dkey_file == NULL)
1742 s_dkey_file = s_dcert_file;
1744 s_dkey = load_key(s_dkey_file, s_dkey_format,
1745 0, dpass, engine, "second certificate private key");
1749 s_dcert = load_cert_pass(s_dcert_file, 1, dpass,
1750 "second server certificate");
1752 if (s_dcert == NULL) {
1753 ERR_print_errors(bio_err);
1756 if (s_dchain_file != NULL) {
1757 if (!load_certs(s_dchain_file, &s_dchain, NULL,
1758 "second server certificate chain"))
1764 if (bio_s_out == NULL) {
1765 if (s_quiet && !s_debug) {
1766 bio_s_out = BIO_new(BIO_s_null());
1767 if (s_msg && bio_s_msg == NULL)
1768 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1770 if (bio_s_out == NULL)
1771 bio_s_out = dup_bio_out(FORMAT_TEXT);
1777 s_dcert_file = NULL;
1779 s_cert_file2 = NULL;
1783 ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1785 ERR_print_errors(bio_err);
1789 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1792 ssl_ctx_security_debug(ctx, sdebug);
1794 if (!config_ctx(cctx, ssl_args, ctx))
1798 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1799 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1801 ERR_print_errors(bio_err);
1805 #ifndef OPENSSL_NO_SCTP
1806 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1807 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1810 if (min_version != 0
1811 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1813 if (max_version != 0
1814 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1817 if (session_id_prefix) {
1818 if (strlen(session_id_prefix) >= 32)
1820 "warning: id_prefix is too long, only one new session will be possible\n");
1821 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1822 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1823 ERR_print_errors(bio_err);
1826 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1829 ssl_ctx_set_excert(ctx, exc);
1832 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1834 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1836 init_session_cache_ctx(ctx);
1838 SSL_CTX_sess_set_cache_size(ctx, 128);
1841 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1845 SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
1848 if (ignore_unexpected_eof)
1849 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1851 if (max_send_fragment > 0
1852 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1853 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1854 prog, max_send_fragment);
1858 if (split_send_fragment > 0
1859 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1860 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1861 prog, split_send_fragment);
1864 if (max_pipelines > 0
1865 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1866 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1867 prog, max_pipelines);
1871 if (read_buf_len > 0) {
1872 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1874 #ifndef OPENSSL_NO_SRTP
1875 if (srtp_profiles != NULL) {
1876 /* Returns 0 on success! */
1877 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1878 BIO_printf(bio_err, "Error setting SRTP profile\n");
1879 ERR_print_errors(bio_err);
1885 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
1886 CAstore, noCAstore)) {
1887 ERR_print_errors(bio_err);
1890 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1891 BIO_printf(bio_err, "Error setting verify params\n");
1892 ERR_print_errors(bio_err);
1896 ssl_ctx_add_crls(ctx, crls, 0);
1898 if (!ssl_load_stores(ctx,
1899 vfyCApath, vfyCAfile, vfyCAstore,
1900 chCApath, chCAfile, chCAstore,
1901 crls, crl_download)) {
1902 BIO_printf(bio_err, "Error loading store locations\n");
1903 ERR_print_errors(bio_err);
1908 ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1910 ERR_print_errors(bio_err);
1916 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1919 ssl_ctx_security_debug(ctx2, sdebug);
1921 if (session_id_prefix) {
1922 if (strlen(session_id_prefix) >= 32)
1924 "warning: id_prefix is too long, only one new session will be possible\n");
1925 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1926 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1927 ERR_print_errors(bio_err);
1930 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1933 ssl_ctx_set_excert(ctx2, exc);
1936 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1939 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1941 init_session_cache_ctx(ctx2);
1943 SSL_CTX_sess_set_cache_size(ctx2, 128);
1946 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1948 if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath,
1949 noCApath, CAstore, noCAstore)) {
1950 ERR_print_errors(bio_err);
1953 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1954 BIO_printf(bio_err, "Error setting verify params\n");
1955 ERR_print_errors(bio_err);
1959 ssl_ctx_add_crls(ctx2, crls, 0);
1960 if (!config_ctx(cctx, ssl_args, ctx2))
1963 #ifndef OPENSSL_NO_NEXTPROTONEG
1964 if (next_proto.data)
1965 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1969 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1972 EVP_PKEY *dhpkey = NULL;
1975 dhpkey = load_keyparams(dhfile, 0, "DH", "DH parameters");
1976 else if (s_cert_file != NULL)
1977 dhpkey = load_keyparams(s_cert_file, 0, "DH", "DH parameters");
1979 if (dhpkey != NULL) {
1980 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1982 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1984 (void)BIO_flush(bio_s_out);
1986 if (dhpkey == NULL) {
1987 SSL_CTX_set_dh_auto(ctx, 1);
1990 * We need 2 references: one for use by ctx and one for use by
1993 if (!EVP_PKEY_up_ref(dhpkey)) {
1994 EVP_PKEY_free(dhpkey);
1997 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) {
1998 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1999 ERR_print_errors(bio_err);
2000 /* Free 2 references */
2001 EVP_PKEY_free(dhpkey);
2002 EVP_PKEY_free(dhpkey);
2008 if (dhfile != NULL) {
2009 EVP_PKEY *dhpkey2 = load_keyparams(s_cert_file2, 0, "DH",
2012 if (dhpkey2 != NULL) {
2013 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2014 (void)BIO_flush(bio_s_out);
2016 EVP_PKEY_free(dhpkey);
2020 if (dhpkey == NULL) {
2021 SSL_CTX_set_dh_auto(ctx2, 1);
2022 } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) {
2023 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2024 ERR_print_errors(bio_err);
2025 EVP_PKEY_free(dhpkey);
2030 EVP_PKEY_free(dhpkey);
2033 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
2036 if (s_serverinfo_file != NULL
2037 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
2038 ERR_print_errors(bio_err);
2043 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
2046 if (s_dcert != NULL) {
2047 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
2051 if (no_resume_ephemeral) {
2052 SSL_CTX_set_not_resumable_session_callback(ctx,
2053 not_resumable_sess_cb);
2056 SSL_CTX_set_not_resumable_session_callback(ctx2,
2057 not_resumable_sess_cb);
2059 #ifndef OPENSSL_NO_PSK
2060 if (psk_key != NULL) {
2062 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
2063 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
2066 if (psk_identity_hint != NULL) {
2067 if (min_version == TLS1_3_VERSION) {
2068 BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n");
2070 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
2071 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
2072 ERR_print_errors(bio_err);
2078 if (psksessf != NULL) {
2079 BIO *stmp = BIO_new_file(psksessf, "r");
2082 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
2083 ERR_print_errors(bio_err);
2086 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2088 if (psksess == NULL) {
2089 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
2090 ERR_print_errors(bio_err);
2096 if (psk_key != NULL || psksess != NULL)
2097 SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb);
2099 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
2100 if (!SSL_CTX_set_session_id_context(ctx,
2101 (void *)&s_server_session_id_context,
2102 sizeof(s_server_session_id_context))) {
2103 BIO_printf(bio_err, "error setting session id context\n");
2104 ERR_print_errors(bio_err);
2108 /* Set DTLS cookie generation and verification callbacks */
2109 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
2110 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
2112 /* Set TLS1.3 cookie generation and verification callbacks */
2113 SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback);
2114 SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback);
2117 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
2118 if (!SSL_CTX_set_session_id_context(ctx2,
2119 (void *)&s_server_session_id_context,
2120 sizeof(s_server_session_id_context))) {
2121 BIO_printf(bio_err, "error setting session id context\n");
2122 ERR_print_errors(bio_err);
2125 tlsextcbp.biodebug = bio_s_out;
2126 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
2127 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
2128 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2129 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2132 #ifndef OPENSSL_NO_SRP
2133 if (srp_verifier_file != NULL) {
2134 if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed,
2139 if (CAfile != NULL) {
2140 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2143 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2145 #ifndef OPENSSL_NO_OCSP
2146 if (s_tlsextstatus) {
2147 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2148 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2150 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2151 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2155 if (set_keylog_file(ctx, keylog_file))
2158 if (max_early_data >= 0)
2159 SSL_CTX_set_max_early_data(ctx, max_early_data);
2160 if (recv_max_early_data >= 0)
2161 SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data);
2164 server_cb = rev_body;
2166 server_cb = www_body;
2168 server_cb = sv_body;
2170 if (socket_family == AF_UNIX
2171 && unlink_unix_path)
2174 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2175 server_cb, context, naccept, bio_s_out);
2176 print_stats(bio_s_out, ctx);
2180 SSL_SESSION_free(psksess);
2181 set_keylog_file(NULL, NULL);
2183 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2185 EVP_PKEY_free(s_key);
2186 EVP_PKEY_free(s_dkey);
2187 sk_X509_pop_free(s_chain, X509_free);
2188 sk_X509_pop_free(s_dchain, X509_free);
2190 OPENSSL_free(dpass);
2193 X509_VERIFY_PARAM_free(vpm);
2195 OPENSSL_free(tlscstatp.host);
2196 OPENSSL_free(tlscstatp.port);
2197 OPENSSL_free(tlscstatp.path);
2200 EVP_PKEY_free(s_key2);
2201 #ifndef OPENSSL_NO_NEXTPROTONEG
2202 OPENSSL_free(next_proto.data);
2204 OPENSSL_free(alpn_ctx.data);
2205 ssl_excert_free(exc);
2206 sk_OPENSSL_STRING_free(ssl_args);
2207 SSL_CONF_CTX_free(cctx);
2208 release_engine(engine);
2209 BIO_free(bio_s_out);
2211 BIO_free(bio_s_msg);
2213 #ifdef CHARSET_EBCDIC
2214 BIO_meth_free(methods_ebcdic);
2219 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2221 BIO_printf(bio, "%4ld items in the session cache\n",
2222 SSL_CTX_sess_number(ssl_ctx));
2223 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2224 SSL_CTX_sess_connect(ssl_ctx));
2225 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2226 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2227 BIO_printf(bio, "%4ld client connects that finished\n",
2228 SSL_CTX_sess_connect_good(ssl_ctx));
2229 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2230 SSL_CTX_sess_accept(ssl_ctx));
2231 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2232 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2233 BIO_printf(bio, "%4ld server accepts that finished\n",
2234 SSL_CTX_sess_accept_good(ssl_ctx));
2235 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2236 BIO_printf(bio, "%4ld session cache misses\n",
2237 SSL_CTX_sess_misses(ssl_ctx));
2238 BIO_printf(bio, "%4ld session cache timeouts\n",
2239 SSL_CTX_sess_timeouts(ssl_ctx));
2240 BIO_printf(bio, "%4ld callback cache hits\n",
2241 SSL_CTX_sess_cb_hits(ssl_ctx));
2242 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2243 SSL_CTX_sess_cache_full(ssl_ctx),
2244 SSL_CTX_sess_get_cache_size(ssl_ctx));
2247 static int sv_body(int s, int stype, int prot, unsigned char *context)
2256 struct timeval timeout;
2257 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
2258 struct timeval *timeoutp;
2260 #ifndef OPENSSL_NO_DTLS
2261 # ifndef OPENSSL_NO_SCTP
2262 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2264 int isdtls = (stype == SOCK_DGRAM);
2268 buf = app_malloc(bufsize, "server buffer");
2270 if (!BIO_socket_nbio(s, 1))
2271 ERR_print_errors(bio_err);
2273 BIO_printf(bio_err, "Turned on non blocking io\n");
2282 if (s_tlsextdebug) {
2283 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2284 SSL_set_tlsext_debug_arg(con, bio_s_out);
2288 && !SSL_set_session_id_context(con, context,
2289 strlen((char *)context))) {
2290 BIO_printf(bio_err, "Error setting session id context\n");
2295 if (!SSL_clear(con)) {
2296 BIO_printf(bio_err, "Error clearing SSL connection\n");
2300 #ifndef OPENSSL_NO_DTLS
2302 # ifndef OPENSSL_NO_SCTP
2303 if (prot == IPPROTO_SCTP)
2304 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2307 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2309 if (enable_timeouts) {
2311 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2312 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2315 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2316 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2320 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2321 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2322 DTLS_get_link_min_mtu(con));
2327 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2328 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2329 BIO_printf(bio_err, "Failed to set MTU\n");
2335 /* want to do MTU discovery */
2336 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2338 # ifndef OPENSSL_NO_SCTP
2339 if (prot != IPPROTO_SCTP)
2341 /* Turn on cookie exchange. Not necessary for SCTP */
2342 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2345 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2348 BIO_printf(bio_err, "Unable to create BIO\n");
2349 ERR_print_errors(bio_err);
2356 test = BIO_new(BIO_f_nbio_test());
2357 sbio = BIO_push(test, sbio);
2360 SSL_set_bio(con, sbio, sbio);
2361 SSL_set_accept_state(con);
2362 /* SSL_set_fd(con,s); */
2365 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2366 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2369 #ifndef OPENSSL_NO_SSL_TRACE
2371 SSL_set_msg_callback(con, SSL_trace);
2374 SSL_set_msg_callback(con, msg_cb);
2375 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2378 if (s_tlsextdebug) {
2379 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2380 SSL_set_tlsext_debug_arg(con, bio_s_out);
2384 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2387 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2389 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2390 if (edret != SSL_READ_EARLY_DATA_ERROR)
2393 switch (SSL_get_error(con, 0)) {
2394 case SSL_ERROR_WANT_WRITE:
2395 case SSL_ERROR_WANT_ASYNC:
2396 case SSL_ERROR_WANT_READ:
2397 /* Just keep trying - busy waiting */
2400 BIO_printf(bio_err, "Error reading early data\n");
2401 ERR_print_errors(bio_err);
2405 if (readbytes > 0) {
2407 BIO_printf(bio_s_out, "Early data received:\n");
2410 raw_write_stdout(buf, (unsigned int)readbytes);
2411 (void)BIO_flush(bio_s_out);
2415 if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT)
2416 BIO_printf(bio_s_out, "No early data received\n");
2418 BIO_printf(bio_s_out, "Early data was rejected\n");
2420 BIO_printf(bio_s_out, "\nEnd of early data\n");
2422 if (SSL_is_init_finished(con))
2423 print_connection_info(con);
2426 if (fileno_stdin() > s)
2427 width = fileno_stdin() + 1;
2431 int read_from_terminal;
2432 int read_from_sslcon;
2434 read_from_terminal = 0;
2435 read_from_sslcon = SSL_has_pending(con)
2436 || (async && SSL_waiting_for_async(con));
2438 if (!read_from_sslcon) {
2440 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2441 openssl_fdset(fileno_stdin(), &readfds);
2443 openssl_fdset(s, &readfds);
2445 * Note: under VMS with SOCKETSHR the second parameter is
2446 * currently of type (int *) whereas under other systems it is
2447 * (void *) if you don't have a cast it will choke the compiler:
2448 * if you do have a cast then you can either go for (int *) or
2451 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2453 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2454 * only on sockets. As a workaround we timeout the select every
2455 * second and check for any keypress. In a proper Windows
2456 * application we wouldn't do this because it is inefficient.
2459 timeout.tv_usec = 0;
2460 i = select(width, (void *)&readfds, NULL, NULL, &timeout);
2461 if (has_stdin_waiting())
2462 read_from_terminal = 1;
2463 if ((i < 0) || (!i && !read_from_terminal))
2466 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2467 timeoutp = &timeout;
2471 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2473 if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
2474 BIO_printf(bio_err, "TIMEOUT occurred\n");
2478 if (FD_ISSET(fileno_stdin(), &readfds))
2479 read_from_terminal = 1;
2481 if (FD_ISSET(s, &readfds))
2482 read_from_sslcon = 1;
2484 if (read_from_terminal) {
2488 i = raw_read_stdin(buf, bufsize / 2);
2490 /* both loops are skipped when i <= 0 */
2491 for (j = 0; j < i; j++)
2494 for (j = i - 1; j >= 0; j--) {
2495 buf[j + lf_num] = buf[j];
2496 if (buf[j] == '\n') {
2499 buf[j + lf_num] = '\r';
2502 assert(lf_num == 0);
2504 i = raw_read_stdin(buf, bufsize);
2507 if (!s_quiet && !s_brief) {
2508 if ((i <= 0) || (buf[0] == 'Q')) {
2509 BIO_printf(bio_s_out, "DONE\n");
2510 (void)BIO_flush(bio_s_out);
2512 close_accept_socket();
2516 if ((i <= 0) || (buf[0] == 'q')) {
2517 BIO_printf(bio_s_out, "DONE\n");
2518 (void)BIO_flush(bio_s_out);
2519 if (SSL_version(con) != DTLS1_VERSION)
2522 * close_accept_socket(); ret= -11;
2526 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2527 SSL_renegotiate(con);
2528 i = SSL_do_handshake(con);
2529 printf("SSL_do_handshake -> %d\n", i);
2533 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2535 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2537 SSL_renegotiate(con);
2538 i = SSL_do_handshake(con);
2539 printf("SSL_do_handshake -> %d\n", i);
2543 if ((buf[0] == 'K' || buf[0] == 'k')
2544 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2545 SSL_key_update(con, buf[0] == 'K' ?
2546 SSL_KEY_UPDATE_REQUESTED
2547 : SSL_KEY_UPDATE_NOT_REQUESTED);
2548 i = SSL_do_handshake(con);
2549 printf("SSL_do_handshake -> %d\n", i);
2553 if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2554 SSL_set_verify(con, SSL_VERIFY_PEER, NULL);
2555 i = SSL_verify_client_post_handshake(con);
2557 printf("Failed to initiate request\n");
2558 ERR_print_errors(bio_err);
2560 i = SSL_do_handshake(con);
2561 printf("SSL_do_handshake -> %d\n", i);
2566 if (buf[0] == 'P') {
2567 static const char str[] = "Lets print some clear text\n";
2568 BIO_write(SSL_get_wbio(con), str, sizeof(str) -1);
2570 if (buf[0] == 'S') {
2571 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2574 #ifdef CHARSET_EBCDIC
2575 ebcdic2ascii(buf, buf, i);
2579 /* should do a select for the write */
2582 if (++count == 100) {
2584 SSL_renegotiate(con);
2587 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2588 #ifndef OPENSSL_NO_SRP
2589 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2590 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2592 lookup_srp_user(&srp_callback_parm, bio_s_out);
2594 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2597 switch (SSL_get_error(con, k)) {
2598 case SSL_ERROR_NONE:
2600 case SSL_ERROR_WANT_ASYNC:
2601 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2602 (void)BIO_flush(bio_s_out);
2603 wait_for_async(con);
2605 case SSL_ERROR_WANT_WRITE:
2606 case SSL_ERROR_WANT_READ:
2607 case SSL_ERROR_WANT_X509_LOOKUP:
2608 BIO_printf(bio_s_out, "Write BLOCK\n");
2609 (void)BIO_flush(bio_s_out);
2611 case SSL_ERROR_WANT_ASYNC_JOB:
2613 * This shouldn't ever happen in s_server. Treat as an error
2615 case SSL_ERROR_SYSCALL:
2617 BIO_printf(bio_s_out, "ERROR\n");
2618 (void)BIO_flush(bio_s_out);
2619 ERR_print_errors(bio_err);
2623 case SSL_ERROR_ZERO_RETURN:
2624 BIO_printf(bio_s_out, "DONE\n");
2625 (void)BIO_flush(bio_s_out);
2637 if (read_from_sslcon) {
2639 * init_ssl_connection handles all async events itself so if we're
2640 * waiting for async then we shouldn't go back into
2641 * init_ssl_connection
2643 if ((!async || !SSL_waiting_for_async(con))
2644 && !SSL_is_init_finished(con)) {
2645 i = init_ssl_connection(con);
2650 } else if (i == 0) {
2656 i = SSL_read(con, (char *)buf, bufsize);
2657 #ifndef OPENSSL_NO_SRP
2658 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2659 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2661 lookup_srp_user(&srp_callback_parm, bio_s_out);
2663 i = SSL_read(con, (char *)buf, bufsize);
2666 switch (SSL_get_error(con, i)) {
2667 case SSL_ERROR_NONE:
2668 #ifdef CHARSET_EBCDIC
2669 ascii2ebcdic(buf, buf, i);
2671 raw_write_stdout(buf, (unsigned int)i);
2672 (void)BIO_flush(bio_s_out);
2673 if (SSL_has_pending(con))
2676 case SSL_ERROR_WANT_ASYNC:
2677 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2678 (void)BIO_flush(bio_s_out);
2679 wait_for_async(con);
2681 case SSL_ERROR_WANT_WRITE:
2682 case SSL_ERROR_WANT_READ:
2683 BIO_printf(bio_s_out, "Read BLOCK\n");
2684 (void)BIO_flush(bio_s_out);
2686 case SSL_ERROR_WANT_ASYNC_JOB:
2688 * This shouldn't ever happen in s_server. Treat as an error
2690 case SSL_ERROR_SYSCALL:
2692 BIO_printf(bio_s_out, "ERROR\n");
2693 (void)BIO_flush(bio_s_out);
2694 ERR_print_errors(bio_err);
2697 case SSL_ERROR_ZERO_RETURN:
2698 BIO_printf(bio_s_out, "DONE\n");
2699 (void)BIO_flush(bio_s_out);
2708 BIO_printf(bio_s_out, "shutting down SSL\n");
2709 do_ssl_shutdown(con);
2712 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2713 OPENSSL_clear_free(buf, bufsize);
2717 static void close_accept_socket(void)
2719 BIO_printf(bio_err, "shutdown accept socket\n");
2720 if (accept_socket >= 0) {
2721 BIO_closesocket(accept_socket);
2725 static int is_retryable(SSL *con, int i)
2727 int err = SSL_get_error(con, i);
2729 /* If it's not a fatal error, it must be retryable */
2730 return (err != SSL_ERROR_SSL)
2731 && (err != SSL_ERROR_SYSCALL)
2732 && (err != SSL_ERROR_ZERO_RETURN);
2735 static int init_ssl_connection(SSL *con)
2741 if (dtlslisten || stateless) {
2742 BIO_ADDR *client = NULL;
2745 if ((client = BIO_ADDR_new()) == NULL) {
2746 BIO_printf(bio_err, "ERROR - memory\n");
2749 i = DTLSv1_listen(con, client);
2751 i = SSL_stateless(con);
2758 wbio = SSL_get_wbio(con);
2760 BIO_get_fd(wbio, &fd);
2763 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2764 BIO_printf(bio_err, "ERROR - unable to connect\n");
2765 BIO_ADDR_free(client);
2769 (void)BIO_ctrl_set_connected(wbio, client);
2770 BIO_ADDR_free(client);
2775 i = SSL_accept(con);
2777 BIO_ADDR_free(client);
2781 i = SSL_accept(con);
2784 retry = is_retryable(con, i);
2785 #ifdef CERT_CB_TEST_RETRY
2788 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2789 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2791 "LOOKUP from certificate callback during accept\n");
2792 i = SSL_accept(con);
2794 retry = is_retryable(con, i);
2799 #ifndef OPENSSL_NO_SRP
2801 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2802 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2803 srp_callback_parm.login);
2805 lookup_srp_user(&srp_callback_parm, bio_s_out);
2807 i = SSL_accept(con);
2809 retry = is_retryable(con, i);
2812 } while (i < 0 && SSL_waiting_for_async(con));
2816 if (((dtlslisten || stateless) && i == 0)
2817 || (!dtlslisten && !stateless && retry)) {
2818 BIO_printf(bio_s_out, "DELAY\n");
2822 BIO_printf(bio_err, "ERROR\n");
2824 verify_err = SSL_get_verify_result(con);
2825 if (verify_err != X509_V_OK) {
2826 BIO_printf(bio_err, "verify error:%s\n",
2827 X509_verify_cert_error_string(verify_err));
2829 /* Always print any error messages */
2830 ERR_print_errors(bio_err);
2834 print_connection_info(con);
2838 static void print_connection_info(SSL *con)
2843 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2844 const unsigned char *next_proto_neg;
2845 unsigned next_proto_neg_len;
2847 unsigned char *exportedkeymat;
2851 print_ssl_summary(con);
2853 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2855 peer = SSL_get0_peer_certificate(con);
2857 BIO_printf(bio_s_out, "Client certificate\n");
2858 PEM_write_bio_X509(bio_s_out, peer);
2859 dump_cert_text(bio_s_out, peer);
2863 if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
2864 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2865 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2866 ssl_print_sigalgs(bio_s_out, con);
2867 #ifndef OPENSSL_NO_EC
2868 ssl_print_point_formats(bio_s_out, con);
2869 ssl_print_groups(bio_s_out, con, 0);
2871 print_ca_names(bio_s_out, con);
2872 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2874 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2875 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2876 if (next_proto_neg) {
2877 BIO_printf(bio_s_out, "NEXTPROTO is ");
2878 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2879 BIO_printf(bio_s_out, "\n");
2882 #ifndef OPENSSL_NO_SRTP
2884 SRTP_PROTECTION_PROFILE *srtp_profile
2885 = SSL_get_selected_srtp_profile(con);
2888 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2889 srtp_profile->name);
2892 if (SSL_session_reused(con))
2893 BIO_printf(bio_s_out, "Reused session-id\n");
2894 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2895 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2896 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
2897 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
2899 if (keymatexportlabel != NULL) {
2900 BIO_printf(bio_s_out, "Keying material exporter:\n");
2901 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2902 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2903 exportedkeymat = app_malloc(keymatexportlen, "export key");
2904 if (!SSL_export_keying_material(con, exportedkeymat,
2907 strlen(keymatexportlabel),
2909 BIO_printf(bio_s_out, " Error\n");
2911 BIO_printf(bio_s_out, " Keying material: ");
2912 for (i = 0; i < keymatexportlen; i++)
2913 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2914 BIO_printf(bio_s_out, "\n");
2916 OPENSSL_free(exportedkeymat);
2918 #ifndef OPENSSL_NO_KTLS
2919 if (BIO_get_ktls_send(SSL_get_wbio(con)))
2920 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
2921 if (BIO_get_ktls_recv(SSL_get_rbio(con)))
2922 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
2925 (void)BIO_flush(bio_s_out);
2928 static int www_body(int s, int stype, int prot, unsigned char *context)
2934 const SSL_CIPHER *c;
2935 BIO *io, *ssl_bio, *sbio;
2937 int total_bytes = 0;
2943 /* Set width for a select call if needed */
2946 buf = app_malloc(bufsize, "server www buffer");
2947 io = BIO_new(BIO_f_buffer());
2948 ssl_bio = BIO_new(BIO_f_ssl());
2949 if ((io == NULL) || (ssl_bio == NULL))
2953 if (!BIO_socket_nbio(s, 1))
2954 ERR_print_errors(bio_err);
2956 BIO_printf(bio_err, "Turned on non blocking io\n");
2959 /* lets make the output buffer a reasonable size */
2960 if (!BIO_set_write_buffer_size(io, bufsize))
2963 if ((con = SSL_new(ctx)) == NULL)
2966 if (s_tlsextdebug) {
2967 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2968 SSL_set_tlsext_debug_arg(con, bio_s_out);
2972 && !SSL_set_session_id_context(con, context,
2973 strlen((char *)context))) {
2978 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2982 test = BIO_new(BIO_f_nbio_test());
2983 sbio = BIO_push(test, sbio);
2985 SSL_set_bio(con, sbio, sbio);
2986 SSL_set_accept_state(con);
2988 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
2989 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2990 BIO_push(io, ssl_bio);
2991 #ifdef CHARSET_EBCDIC
2992 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2996 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2997 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3000 #ifndef OPENSSL_NO_SSL_TRACE
3002 SSL_set_msg_callback(con, SSL_trace);
3005 SSL_set_msg_callback(con, msg_cb);
3006 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3010 i = BIO_gets(io, buf, bufsize - 1);
3011 if (i < 0) { /* error */
3012 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
3014 ERR_print_errors(bio_err);
3017 BIO_printf(bio_s_out, "read R BLOCK\n");
3018 #ifndef OPENSSL_NO_SRP
3019 if (BIO_should_io_special(io)
3020 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3021 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3023 lookup_srp_user(&srp_callback_parm, bio_s_out);
3028 #if !defined(OPENSSL_SYS_MSDOS)
3033 } else if (i == 0) { /* end of input */
3038 /* else we have data */
3039 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
3040 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
3043 STACK_OF(SSL_CIPHER) *sk;
3044 static const char *space = " ";
3046 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
3047 if (strncmp("GET /renegcert", buf, 14) == 0)
3049 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
3051 i = SSL_renegotiate(con);
3052 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
3053 /* Send the HelloRequest */
3054 i = SSL_do_handshake(con);
3056 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
3057 SSL_get_error(con, i));
3058 ERR_print_errors(bio_err);
3061 /* Wait for a ClientHello to come back */
3063 openssl_fdset(s, &readfds);
3064 i = select(width, (void *)&readfds, NULL, NULL, NULL);
3065 if (i <= 0 || !FD_ISSET(s, &readfds)) {
3066 BIO_printf(bio_s_out,
3067 "Error waiting for client response\n");
3068 ERR_print_errors(bio_err);
3072 * We're not actually expecting any data here and we ignore
3073 * any that is sent. This is just to force the handshake that
3074 * we're expecting to come from the client. If they haven't
3075 * sent one there's not much we can do.
3077 BIO_gets(io, buf, bufsize - 1);
3081 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3082 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
3083 BIO_puts(io, "<pre>\n");
3084 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
3086 for (i = 0; i < local_argc; i++) {
3088 for (myp = local_argv[i]; *myp; myp++)
3091 BIO_puts(io, "<");
3094 BIO_puts(io, ">");
3097 BIO_puts(io, "&");
3100 BIO_write(io, myp, 1);
3103 BIO_write(io, " ", 1);
3108 "Secure Renegotiation IS%s supported\n",
3109 SSL_get_secure_renegotiation_support(con) ?
3113 * The following is evil and should not really be done
3115 BIO_printf(io, "Ciphers supported in s_server binary\n");
3116 sk = SSL_get_ciphers(con);
3117 j = sk_SSL_CIPHER_num(sk);
3118 for (i = 0; i < j; i++) {
3119 c = sk_SSL_CIPHER_value(sk, i);
3120 BIO_printf(io, "%-11s:%-25s ",
3121 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3122 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3126 p = SSL_get_shared_ciphers(con, buf, bufsize);
3129 "---\nCiphers common between both SSL end points:\n");
3133 BIO_write(io, space, 26 - j);
3136 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3138 BIO_write(io, p, 1);
3145 ssl_print_sigalgs(io, con);
3146 #ifndef OPENSSL_NO_EC
3147 ssl_print_groups(io, con, 0);
3149 print_ca_names(io, con);
3150 BIO_printf(io, (SSL_session_reused(con)
3151 ? "---\nReused, " : "---\nNew, "));
3152 c = SSL_get_current_cipher(con);
3153 BIO_printf(io, "%s, Cipher is %s\n",
3154 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3155 SSL_SESSION_print(io, SSL_get_session(con));
3156 BIO_printf(io, "---\n");
3157 print_stats(io, SSL_get_SSL_CTX(con));
3158 BIO_printf(io, "---\n");
3159 peer = SSL_get0_peer_certificate(con);
3161 BIO_printf(io, "Client certificate\n");
3162 X509_print(io, peer);
3163 PEM_write_bio_X509(io, peer);
3166 BIO_puts(io, "no client certificate available\n");
3168 BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
3170 } else if ((www == 2 || www == 3)
3171 && (strncmp("GET /", buf, 5) == 0)) {
3174 static const char *text =
3175 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3181 for (e = p; *e != '\0'; e++) {
3186 /* Windows drive. We treat this the same way as ".." */
3193 dot = (e[0] == '.') ? 2 : 0;
3196 dot = (e[0] == '.') ? 3 : 0;
3199 dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0;
3203 dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0;
3205 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3210 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3217 BIO_printf(io, "'%s' contains '..' or ':'\r\n", p);
3221 if (*p == '/' || *p == '\\') {
3223 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3227 /* if a directory, do the index thang */
3228 if (app_isdir(p) > 0) {
3230 BIO_printf(io, "'%s' is a directory\r\n", p);
3234 opmode = (http_server_binmode == 1) ? "rb" : "r";
3235 if ((file = BIO_new_file(p, opmode)) == NULL) {
3237 BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode);
3238 ERR_print_errors(io);
3243 BIO_printf(bio_err, "FILE:%s\n", p);
3247 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3248 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3249 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3251 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3254 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3257 #ifndef OPENSSL_NO_KTLS
3265 BIO_get_fp(file, &fp);
3267 if (fstat(fd, &st) < 0) {
3268 BIO_printf(io, "Error fstat '%s'\r\n", p);
3269 ERR_print_errors(io);
3273 filesize = st.st_size;
3274 if (((int)BIO_flush(io)) < 0)
3278 i = SSL_sendfile(con, fd, offset, filesize, 0);
3280 BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p);
3281 ERR_print_errors(io);
3288 if (filesize <= 0) {
3290 BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p);
3299 i = BIO_read(file, buf, bufsize);
3305 BIO_printf(bio_err, "%d\n", i);
3306 if (total_bytes > 3 * 1024) {
3308 BIO_printf(bio_err, "RENEGOTIATE\n");
3309 SSL_renegotiate(con);
3313 for (j = 0; j < i;) {
3317 SSL_renegotiate(con);
3319 k = BIO_write(io, &(buf[j]), i - j);
3321 if (!BIO_should_retry(io)
3322 && !SSL_waiting_for_async(con)) {
3325 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3340 i = (int)BIO_flush(io);
3342 if (!BIO_should_retry(io))
3348 /* make sure we re-use sessions */
3349 do_ssl_shutdown(con);
3357 static int rev_body(int s, int stype, int prot, unsigned char *context)
3363 BIO *io, *ssl_bio, *sbio;
3365 buf = app_malloc(bufsize, "server rev buffer");
3366 io = BIO_new(BIO_f_buffer());
3367 ssl_bio = BIO_new(BIO_f_ssl());
3368 if ((io == NULL) || (ssl_bio == NULL))
3371 /* lets make the output buffer a reasonable size */
3372 if (!BIO_set_write_buffer_size(io, bufsize))
3375 if ((con = SSL_new(ctx)) == NULL)
3378 if (s_tlsextdebug) {
3379 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3380 SSL_set_tlsext_debug_arg(con, bio_s_out);
3383 && !SSL_set_session_id_context(con, context,
3384 strlen((char *)context))) {
3386 ERR_print_errors(bio_err);
3390 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3391 SSL_set_bio(con, sbio, sbio);
3392 SSL_set_accept_state(con);
3394 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3395 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3396 BIO_push(io, ssl_bio);
3397 #ifdef CHARSET_EBCDIC
3398 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3402 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3403 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3406 #ifndef OPENSSL_NO_SSL_TRACE
3408 SSL_set_msg_callback(con, SSL_trace);
3411 SSL_set_msg_callback(con, msg_cb);
3412 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3416 i = BIO_do_handshake(io);
3419 if (!BIO_should_retry(io)) {
3420 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3421 ERR_print_errors(bio_err);
3424 #ifndef OPENSSL_NO_SRP
3425 if (BIO_should_io_special(io)
3426 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3427 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3429 lookup_srp_user(&srp_callback_parm, bio_s_out);
3435 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3436 print_ssl_summary(con);
3439 i = BIO_gets(io, buf, bufsize - 1);
3440 if (i < 0) { /* error */
3441 if (!BIO_should_retry(io)) {
3443 ERR_print_errors(bio_err);
3446 BIO_printf(bio_s_out, "read R BLOCK\n");
3447 #ifndef OPENSSL_NO_SRP
3448 if (BIO_should_io_special(io)
3449 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3450 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3452 lookup_srp_user(&srp_callback_parm, bio_s_out);
3457 #if !defined(OPENSSL_SYS_MSDOS)
3462 } else if (i == 0) { /* end of input */
3464 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3467 char *p = buf + i - 1;
3468 while (i && (*p == '\n' || *p == '\r')) {
3472 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3474 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3477 BUF_reverse((unsigned char *)buf, NULL, i);
3479 BIO_write(io, buf, i + 1);
3484 if (!BIO_should_retry(io))
3490 /* make sure we re-use sessions */
3491 do_ssl_shutdown(con);
3500 #define MAX_SESSION_ID_ATTEMPTS 10
3501 static int generate_session_id(SSL *ssl, unsigned char *id,
3502 unsigned int *id_len)
3504 unsigned int count = 0;
3505 unsigned int session_id_prefix_len = strlen(session_id_prefix);
3508 if (RAND_bytes(id, *id_len) <= 0)
3511 * Prefix the session_id with the required prefix. NB: If our prefix
3512 * is too long, clip it - but there will be worse effects anyway, eg.
3513 * the server could only possibly create 1 session ID (ie. the
3514 * prefix!) so all future session negotiations will fail due to
3517 memcpy(id, session_id_prefix,
3518 (session_id_prefix_len < *id_len) ?
3519 session_id_prefix_len : *id_len);
3521 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3522 (++count < MAX_SESSION_ID_ATTEMPTS));
3523 if (count >= MAX_SESSION_ID_ATTEMPTS)
3529 * By default s_server uses an in-memory cache which caches SSL_SESSION
3530 * structures without any serialization. This hides some bugs which only
3531 * become apparent in deployed servers. By implementing a basic external
3532 * session cache some issues can be debugged using s_server.
3535 typedef struct simple_ssl_session_st {
3540 struct simple_ssl_session_st *next;
3541 } simple_ssl_session;
3543 static simple_ssl_session *first = NULL;
3545 static int add_session(SSL *ssl, SSL_SESSION *session)
3547 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3550 SSL_SESSION_get_id(session, &sess->idlen);
3551 sess->derlen = i2d_SSL_SESSION(session, NULL);
3552 if (sess->derlen < 0) {
3553 BIO_printf(bio_err, "Error encoding session\n");
3558 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3559 sess->der = app_malloc(sess->derlen, "get session buffer");
3561 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3562 OPENSSL_free(sess->id);
3563 OPENSSL_free(sess->der);
3569 /* Assume it still works. */
3570 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3571 BIO_printf(bio_err, "Unexpected session encoding length\n");
3572 OPENSSL_free(sess->id);
3573 OPENSSL_free(sess->der);
3580 BIO_printf(bio_err, "New session added to external cache\n");
3584 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3587 simple_ssl_session *sess;
3589 for (sess = first; sess; sess = sess->next) {
3590 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3591 const unsigned char *p = sess->der;
3592 BIO_printf(bio_err, "Lookup session: cache hit\n");
3593 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3596 BIO_printf(bio_err, "Lookup session: cache miss\n");
3600 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3602 simple_ssl_session *sess, *prev = NULL;
3603 const unsigned char *id;
3605 id = SSL_SESSION_get_id(session, &idlen);
3606 for (sess = first; sess; sess = sess->next) {
3607 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3609 prev->next = sess->next;
3612 OPENSSL_free(sess->id);
3613 OPENSSL_free(sess->der);
3621 static void init_session_cache_ctx(SSL_CTX *sctx)
3623 SSL_CTX_set_session_cache_mode(sctx,
3624 SSL_SESS_CACHE_NO_INTERNAL |
3625 SSL_SESS_CACHE_SERVER);
3626 SSL_CTX_sess_set_new_cb(sctx, add_session);
3627 SSL_CTX_sess_set_get_cb(sctx, get_session);
3628 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3631 static void free_sessions(void)
3633 simple_ssl_session *sess, *tsess;
3634 for (sess = first; sess;) {
3635 OPENSSL_free(sess->id);
3636 OPENSSL_free(sess->der);
3639 OPENSSL_free(tsess);
3644 #endif /* OPENSSL_NO_SOCK */