2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
5 * Licensed under the OpenSSL license (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
11 /* ====================================================================
12 * Copyright 2005 Nokia. All rights reserved.
14 * The portions of the attached software ("Contribution") is developed by
15 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
18 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
19 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
20 * support (see RFC 4279) to OpenSSL.
22 * No patent licenses or other rights except those expressly stated in
23 * the OpenSSL open source license shall be deemed granted or received
24 * expressly, by implication, estoppel, or otherwise.
26 * No assurances are provided by Nokia that the Contribution does not
27 * infringe the patent or other intellectual property rights of any third
28 * party or that the license provides you with all the necessary rights
29 * to make use of the Contribution.
31 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
32 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
33 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
34 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
43 /* Included before async.h to avoid some warnings */
47 #include <openssl/e_os2.h>
48 #include <openssl/async.h>
49 #include <openssl/ssl.h>
51 #ifndef OPENSSL_NO_SOCK
54 * With IPv6, it looks like Digital has mixed up the proper order of
55 * recursive header file inclusion, resulting in the compiler complaining
56 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
57 * needed to have fileno() declared correctly... So let's define u_int
59 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
61 typedef unsigned int u_int;
64 #include <openssl/lhash.h>
65 #include <openssl/bn.h>
68 #include <openssl/err.h>
69 #include <openssl/pem.h>
70 #include <openssl/x509.h>
71 #include <openssl/ssl.h>
72 #include <openssl/rand.h>
73 #include <openssl/ocsp.h>
75 # include <openssl/dh.h>
77 #ifndef OPENSSL_NO_RSA
78 # include <openssl/rsa.h>
80 #ifndef OPENSSL_NO_SRP
81 # include <openssl/srp.h>
86 #include <openssl/ebcdic.h>
89 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
90 static int sv_body(int s, int stype, int prot, unsigned char *context);
91 static int www_body(int s, int stype, int prot, unsigned char *context);
92 static int rev_body(int s, int stype, int prot, unsigned char *context);
93 static void close_accept_socket(void);
94 static int init_ssl_connection(SSL *s);
95 static void print_stats(BIO *bp, SSL_CTX *ctx);
96 static int generate_session_id(const SSL *ssl, unsigned char *id,
97 unsigned int *id_len);
98 static void init_session_cache_ctx(SSL_CTX *sctx);
99 static void free_sessions(void);
100 #ifndef OPENSSL_NO_DH
101 static DH *load_dh_param(const char *dhfile);
103 static void print_connection_info(SSL *con);
105 static const int bufsize = 16 * 1024;
106 static int accept_socket = -1;
108 #define TEST_CERT "server.pem"
109 #define TEST_CERT2 "server2.pem"
111 static int s_nbio = 0;
112 static int s_nbio_test = 0;
113 static int s_crlf = 0;
114 static SSL_CTX *ctx = NULL;
115 static SSL_CTX *ctx2 = NULL;
118 static BIO *bio_s_out = NULL;
119 static BIO *bio_s_msg = NULL;
120 static int s_debug = 0;
121 static int s_tlsextdebug = 0;
122 static int s_msg = 0;
123 static int s_quiet = 0;
124 static int s_ign_eof = 0;
125 static int s_brief = 0;
127 static char *keymatexportlabel = NULL;
128 static int keymatexportlen = 20;
130 static int async = 0;
132 static const char *session_id_prefix = NULL;
134 #ifndef OPENSSL_NO_DTLS
135 static int enable_timeouts = 0;
136 static long socket_mtu;
140 * We define this but make it always be 0 in no-dtls builds to simplify the
143 static int dtlslisten = 0;
145 static int early_data = 0;
147 #ifndef OPENSSL_NO_PSK
148 static char *psk_identity = "Client_identity";
149 char *psk_key = NULL; /* by default PSK is not used */
151 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
153 unsigned int max_psk_len)
159 BIO_printf(bio_s_out, "psk_server_cb\n");
160 if (identity == NULL) {
161 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
165 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
166 (int)strlen(identity), identity);
168 /* here we could lookup the given identity e.g. from a database */
169 if (strcmp(identity, psk_identity) != 0) {
170 BIO_printf(bio_s_out, "PSK warning: client identity not what we expected"
171 " (got '%s' expected '%s')\n", identity, psk_identity);
174 BIO_printf(bio_s_out, "PSK client identity found\n");
177 /* convert the PSK key to binary */
178 key = OPENSSL_hexstr2buf(psk_key, &key_len);
180 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
184 if (key_len > (int)max_psk_len) {
186 "psk buffer of callback is too small (%d) for key (%ld)\n",
187 max_psk_len, key_len);
192 memcpy(psk, key, key_len);
196 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
200 BIO_printf(bio_err, "Error in PSK server callback\n");
201 (void)BIO_flush(bio_err);
202 (void)BIO_flush(bio_s_out);
207 #ifndef OPENSSL_NO_SRP
208 /* This is a context that we pass to callbacks */
209 typedef struct srpsrvparm_st {
216 * This callback pretends to require some asynchronous logic in order to
217 * obtain a verifier. When the callback is called for a new connection we
218 * return with a negative value. This will provoke the accept etc to return
219 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
220 * (which would normally occur after a worker has finished) and we set the
223 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
225 srpsrvparm *p = (srpsrvparm *) arg;
226 int ret = SSL3_AL_FATAL;
228 if (p->login == NULL && p->user == NULL) {
229 p->login = SSL_get_srp_username(s);
230 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
234 if (p->user == NULL) {
235 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
239 if (SSL_set_srp_server_param
240 (s, p->user->N, p->user->g, p->user->s, p->user->v,
241 p->user->info) < 0) {
242 *ad = SSL_AD_INTERNAL_ERROR;
246 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
247 p->login, p->user->info);
248 ret = SSL_ERROR_NONE;
251 SRP_user_pwd_free(p->user);
259 static int local_argc = 0;
260 static char **local_argv;
262 #ifdef CHARSET_EBCDIC
263 static int ebcdic_new(BIO *bi);
264 static int ebcdic_free(BIO *a);
265 static int ebcdic_read(BIO *b, char *out, int outl);
266 static int ebcdic_write(BIO *b, const char *in, int inl);
267 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
268 static int ebcdic_gets(BIO *bp, char *buf, int size);
269 static int ebcdic_puts(BIO *bp, const char *str);
271 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
272 static BIO_METHOD *methods_ebcdic = NULL;
274 /* This struct is "unwarranted chumminess with the compiler." */
280 static const BIO_METHOD *BIO_f_ebcdic_filter()
282 if (methods_ebcdic == NULL) {
283 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
284 "EBCDIC/ASCII filter");
285 if (methods_ebcdic == NULL
286 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
287 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
288 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
289 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
290 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
291 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
292 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
295 return methods_ebcdic;
298 static int ebcdic_new(BIO *bi)
300 EBCDIC_OUTBUFF *wbuf;
302 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
303 wbuf->alloced = 1024;
304 wbuf->buff[0] = '\0';
306 BIO_set_data(bi, wbuf);
311 static int ebcdic_free(BIO *a)
313 EBCDIC_OUTBUFF *wbuf;
317 wbuf = BIO_get_data(a);
319 BIO_set_data(a, NULL);
325 static int ebcdic_read(BIO *b, char *out, int outl)
328 BIO *next = BIO_next(b);
330 if (out == NULL || outl == 0)
335 ret = BIO_read(next, out, outl);
337 ascii2ebcdic(out, out, ret);
341 static int ebcdic_write(BIO *b, const char *in, int inl)
343 EBCDIC_OUTBUFF *wbuf;
344 BIO *next = BIO_next(b);
348 if ((in == NULL) || (inl <= 0))
353 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
355 if (inl > (num = wbuf->alloced)) {
356 num = num + num; /* double the size */
360 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
363 wbuf->buff[0] = '\0';
365 BIO_set_data(b, wbuf);
368 ebcdic2ascii(wbuf->buff, in, inl);
370 ret = BIO_write(next, wbuf->buff, inl);
375 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
378 BIO *next = BIO_next(b);
387 ret = BIO_ctrl(next, cmd, num, ptr);
393 static int ebcdic_gets(BIO *bp, char *buf, int size)
396 BIO *next = BIO_next(bp);
400 /* return(BIO_gets(bp->next_bio,buf,size));*/
401 for (i = 0; i < size - 1; ++i) {
402 ret = ebcdic_read(bp, &buf[i], 1);
405 else if (buf[i] == '\n') {
412 return (ret < 0 && i == 0) ? ret : i;
415 static int ebcdic_puts(BIO *bp, const char *str)
417 if (BIO_next(bp) == NULL)
419 return ebcdic_write(bp, str, strlen(str));
423 /* This is a context that we pass to callbacks */
424 typedef struct tlsextctx_st {
430 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
432 tlsextctx *p = (tlsextctx *) arg;
433 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
434 if (servername != NULL && p->biodebug != NULL)
435 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
438 if (p->servername == NULL)
439 return SSL_TLSEXT_ERR_NOACK;
441 if (servername != NULL) {
442 if (strcasecmp(servername, p->servername))
443 return p->extension_error;
445 BIO_printf(p->biodebug, "Switching server context.\n");
446 SSL_set_SSL_CTX(s, ctx2);
449 return SSL_TLSEXT_ERR_OK;
452 /* Structure passed to cert status callback */
453 typedef struct tlsextstatusctx_st {
455 /* File to load OCSP Response from (or NULL if no file) */
457 /* Default responder to use */
458 char *host, *path, *port;
463 static tlsextstatusctx tlscstatp = { -1 };
465 #ifndef OPENSSL_NO_OCSP
468 * Helper function to get an OCSP_RESPONSE from a responder. This is a
469 * simplified version. It examines certificates each time and makes one OCSP
470 * responder query for each request. A full version would store details such as
471 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
472 * them until they were considered "expired".
474 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
475 OCSP_RESPONSE **resp)
477 char *host = NULL, *port = NULL, *path = NULL;
479 STACK_OF(OPENSSL_STRING) *aia = NULL;
481 X509_STORE_CTX *inctx = NULL;
483 OCSP_REQUEST *req = NULL;
484 OCSP_CERTID *id = NULL;
485 STACK_OF(X509_EXTENSION) *exts;
486 int ret = SSL_TLSEXT_ERR_NOACK;
489 /* Build up OCSP query from server certificate */
490 x = SSL_get_certificate(s);
491 aia = X509_get1_ocsp(x);
493 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
494 &host, &port, &path, &use_ssl)) {
495 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
499 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
500 sk_OPENSSL_STRING_value(aia, 0));
502 if (srctx->host == NULL) {
504 "cert_status: no AIA and no default responder URL\n");
510 use_ssl = srctx->use_ssl;
513 inctx = X509_STORE_CTX_new();
516 if (!X509_STORE_CTX_init(inctx,
517 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
520 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
521 X509_get_issuer_name(x));
523 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
526 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
527 X509_OBJECT_free(obj);
530 req = OCSP_REQUEST_new();
533 if (!OCSP_request_add0_id(req, id))
536 /* Add any extensions to the request */
537 SSL_get_tlsext_status_exts(s, &exts);
538 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
539 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
540 if (!OCSP_REQUEST_add_ext(req, ext, -1))
543 *resp = process_responder(req, host, path, port, use_ssl, NULL,
546 BIO_puts(bio_err, "cert_status: error querying responder\n");
550 ret = SSL_TLSEXT_ERR_OK;
554 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
557 * If we parsed aia we need to free; otherwise they were copied and we
564 X509_email_free(aia);
566 OCSP_CERTID_free(id);
567 OCSP_REQUEST_free(req);
568 X509_STORE_CTX_free(inctx);
573 * Certificate Status callback. This is called when a client includes a
574 * certificate status request extension. The response is either obtained from a
575 * file, or from an OCSP responder.
577 static int cert_status_cb(SSL *s, void *arg)
579 tlsextstatusctx *srctx = arg;
580 OCSP_RESPONSE *resp = NULL;
581 unsigned char *rspder = NULL;
583 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
586 BIO_puts(bio_err, "cert_status: callback called\n");
588 if (srctx->respin != NULL) {
589 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
590 if (derbio == NULL) {
591 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
594 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
597 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
601 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
602 if (ret != SSL_TLSEXT_ERR_OK)
606 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
610 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
611 if (srctx->verbose) {
612 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
613 OCSP_RESPONSE_print(bio_err, resp, 2);
616 ret = SSL_TLSEXT_ERR_OK;
619 if (ret != SSL_TLSEXT_ERR_OK)
620 ERR_print_errors(bio_err);
622 OCSP_RESPONSE_free(resp);
628 #ifndef OPENSSL_NO_NEXTPROTONEG
629 /* This is the context that we pass to next_proto_cb */
630 typedef struct tlsextnextprotoctx_st {
633 } tlsextnextprotoctx;
635 static int next_proto_cb(SSL *s, const unsigned char **data,
636 unsigned int *len, void *arg)
638 tlsextnextprotoctx *next_proto = arg;
640 *data = next_proto->data;
641 *len = next_proto->len;
643 return SSL_TLSEXT_ERR_OK;
645 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
647 /* This the context that we pass to alpn_cb */
648 typedef struct tlsextalpnctx_st {
653 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
654 const unsigned char *in, unsigned int inlen, void *arg)
656 tlsextalpnctx *alpn_ctx = arg;
659 /* We can assume that |in| is syntactically valid. */
661 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
662 for (i = 0; i < inlen;) {
664 BIO_write(bio_s_out, ", ", 2);
665 BIO_write(bio_s_out, &in[i + 1], in[i]);
668 BIO_write(bio_s_out, "\n", 1);
671 if (SSL_select_next_proto
672 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
673 inlen) != OPENSSL_NPN_NEGOTIATED) {
674 return SSL_TLSEXT_ERR_NOACK;
678 BIO_printf(bio_s_out, "ALPN protocols selected: ");
679 BIO_write(bio_s_out, *out, *outlen);
680 BIO_write(bio_s_out, "\n", 1);
683 return SSL_TLSEXT_ERR_OK;
686 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
688 /* disable resumption for sessions with forward secure ciphers */
689 return is_forward_secure;
692 #ifndef OPENSSL_NO_SRP
693 static srpsrvparm srp_callback_parm;
695 #ifndef OPENSSL_NO_SRTP
696 static char *srtp_profiles = NULL;
699 typedef enum OPTION_choice {
700 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
701 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
702 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
703 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
704 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
705 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
706 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
707 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
708 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
709 OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
710 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
711 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
712 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
713 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
714 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
715 OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC,
717 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
718 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
719 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN,
720 OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
721 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN,
722 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
723 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_EARLY_DATA,
729 const OPTIONS s_server_options[] = {
730 {"help", OPT_HELP, '-', "Display this summary"},
731 {"port", OPT_PORT, 'p',
732 "TCP/IP port to listen on for connections (default is " PORT ")"},
733 {"accept", OPT_ACCEPT, 's',
734 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
736 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
738 {"4", OPT_4, '-', "Use IPv4 only"},
739 {"6", OPT_6, '-', "Use IPv6 only"},
741 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
743 {"context", OPT_CONTEXT, 's', "Set session ID context"},
744 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
745 {"Verify", OPT_UPPER_V_VERIFY, 'n',
746 "Turn on peer certificate verification, must have a cert"},
747 {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
748 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
749 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
750 {"serverinfo", OPT_SERVERINFO, 's',
751 "PEM serverinfo file for certificate"},
752 {"certform", OPT_CERTFORM, 'F',
753 "Certificate format (PEM or DER) PEM default"},
754 {"key", OPT_KEY, '<',
755 "Private Key if not in -cert; default is " TEST_CERT},
756 {"keyform", OPT_KEYFORM, 'f',
757 "Key format (PEM, DER or ENGINE) PEM default"},
758 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
759 {"dcert", OPT_DCERT, '<',
760 "Second certificate file to use (usually for DSA)"},
761 {"dcertform", OPT_DCERTFORM, 'F',
762 "Second certificate format (PEM or DER) PEM default"},
763 {"dkey", OPT_DKEY, '<',
764 "Second private key file to use (usually for DSA)"},
765 {"dkeyform", OPT_DKEYFORM, 'F',
766 "Second key format (PEM, DER or ENGINE) PEM default"},
767 {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
768 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
769 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
770 {"debug", OPT_DEBUG, '-', "Print more output"},
771 {"msg", OPT_MSG, '-', "Show protocol messages"},
772 {"msgfile", OPT_MSGFILE, '>',
773 "File to send output of -msg or -trace, instead of stdout"},
774 {"state", OPT_STATE, '-', "Print the SSL states"},
775 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
776 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
777 {"no-CAfile", OPT_NOCAFILE, '-',
778 "Do not load the default certificates file"},
779 {"no-CApath", OPT_NOCAPATH, '-',
780 "Do not load certificates from the default certificates directory"},
781 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
782 {"quiet", OPT_QUIET, '-', "No server output"},
783 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
784 "Disable caching and tickets if ephemeral (EC)DH is used"},
785 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
786 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
787 {"servername", OPT_SERVERNAME, 's',
788 "Servername for HostName TLS extension"},
789 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
790 "mismatch send fatal alert (default warning alert)"},
791 {"cert2", OPT_CERT2, '<',
792 "Certificate file to use for servername; default is" TEST_CERT2},
793 {"key2", OPT_KEY2, '<',
794 "-Private Key file to use for servername if not in -cert2"},
795 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
796 "Hex dump of all TLS extensions received"},
797 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
798 {"id_prefix", OPT_ID_PREFIX, 's',
799 "Generate SSL/TLS session IDs prefixed by arg"},
800 {"rand", OPT_RAND, 's',
801 "Load the file(s) into the random number generator"},
802 {"keymatexport", OPT_KEYMATEXPORT, 's',
803 "Export keying material using label"},
804 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
805 "Export len bytes of keying material (default 20)"},
806 {"CRL", OPT_CRL, '<', "CRL file to use"},
807 {"crl_download", OPT_CRL_DOWNLOAD, '-',
808 "Download CRL from distribution points"},
809 {"cert_chain", OPT_CERT_CHAIN, '<',
810 "certificate chain file in PEM format"},
811 {"dcert_chain", OPT_DCERT_CHAIN, '<',
812 "second certificate chain file in PEM format"},
813 {"chainCApath", OPT_CHAINCAPATH, '/',
814 "use dir as certificate store path to build CA certificate chain"},
815 {"verifyCApath", OPT_VERIFYCAPATH, '/',
816 "use dir as certificate store path 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 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
821 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
822 "Close connection on verification error"},
823 {"verify_quiet", OPT_VERIFY_QUIET, '-',
824 "No verify output except verify errors"},
825 {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
826 {"chainCAfile", OPT_CHAINCAFILE, '<',
827 "CA file for certificate chain (PEM format)"},
828 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
829 "CA file for certificate verification (PEM format)"},
830 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
831 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
832 #ifndef OPENSSL_NO_OCSP
833 {"status", OPT_STATUS, '-', "Request certificate status from server"},
834 {"status_verbose", OPT_STATUS_VERBOSE, '-',
835 "Print more output in certificate status callback"},
836 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
837 "Status request responder timeout"},
838 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
839 {"status_file", OPT_STATUS_FILE, '<',
840 "File containing DER encoded OCSP Response"},
842 #ifndef OPENSSL_NO_SSL_TRACE
843 {"trace", OPT_TRACE, '-', "trace protocol messages"},
845 {"security_debug", OPT_SECURITY_DEBUG, '-',
846 "Print output from SSL/TLS security framework"},
847 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
848 "Print more output from SSL/TLS security framework"},
849 {"brief", OPT_BRIEF, '-',
850 "Restrict output to brief summary of connection parameters"},
851 {"rev", OPT_REV, '-',
852 "act as a simple test server which just sends back with the received text reversed"},
853 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
854 {"ssl_config", OPT_SSL_CONFIG, 's',
855 "Configure SSL_CTX using the configuration 'val'"},
856 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
857 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
858 "Size used to split data for encrypt pipelines"},
859 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
860 "Maximum number of encrypt/decrypt pipelines to be used"},
861 {"read_buf", OPT_READ_BUF, 'p',
862 "Default read buffer size to be used for connections"},
866 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
867 #ifndef OPENSSL_NO_PSK
868 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
869 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
870 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
872 #ifndef OPENSSL_NO_SRP
873 {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
874 {"srpuserseed", OPT_SRPUSERSEED, 's',
875 "A seed string for a default user salt"},
877 #ifndef OPENSSL_NO_SSL3
878 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
880 #ifndef OPENSSL_NO_TLS1
881 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
883 #ifndef OPENSSL_NO_TLS1_1
884 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
886 #ifndef OPENSSL_NO_TLS1_2
887 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
889 #ifndef OPENSSL_NO_TLS1_3
890 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
892 #ifndef OPENSSL_NO_DTLS
893 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
894 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
895 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
896 {"listen", OPT_LISTEN, '-',
897 "Listen for a DTLS ClientHello with a cookie and then connect"},
899 #ifndef OPENSSL_NO_DTLS1
900 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
902 #ifndef OPENSSL_NO_DTLS1_2
903 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
905 #ifndef OPENSSL_NO_SCTP
906 {"sctp", OPT_SCTP, '-', "Use SCTP"},
908 #ifndef OPENSSL_NO_DH
909 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
911 #ifndef OPENSSL_NO_NEXTPROTONEG
912 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
913 "Set the advertised protocols for the NPN extension (comma-separated list)"},
915 #ifndef OPENSSL_NO_SRTP
916 {"use_srtp", OPT_SRTP_PROFILES, 's',
917 "Offer SRTP key management with a colon-separated profile list"},
919 {"alpn", OPT_ALPN, 's',
920 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
921 #ifndef OPENSSL_NO_ENGINE
922 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
924 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
925 {"max_early_data", OPT_MAX_EARLY, 'n',
926 "The maximum number of bytes of early data"},
927 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
928 {NULL, OPT_EOF, 0, NULL}
931 #define IS_PROT_FLAG(o) \
932 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
933 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
935 int s_server_main(int argc, char *argv[])
937 ENGINE *engine = NULL;
938 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
939 SSL_CONF_CTX *cctx = NULL;
940 const SSL_METHOD *meth = TLS_server_method();
941 SSL_EXCERT *exc = NULL;
942 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
943 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
944 STACK_OF(X509_CRL) *crls = NULL;
945 X509 *s_cert = NULL, *s_dcert = NULL;
946 X509_VERIFY_PARAM *vpm = NULL;
947 const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
948 char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
949 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
950 char *crl_file = NULL, *prog;
952 int unlink_unix_path = 0;
954 do_server_cb server_cb;
955 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
956 #ifndef OPENSSL_NO_DH
960 int nocert = 0, ret = 1;
961 int noCApath = 0, noCAfile = 0;
962 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
963 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
964 int rev = 0, naccept = -1, sdebug = 0;
965 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
966 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
968 char *port = BUF_strdup(PORT);
969 unsigned char *context = NULL;
971 EVP_PKEY *s_key2 = NULL;
972 X509 *s_cert2 = NULL;
973 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
974 const char *ssl_config = NULL;
975 int read_buf_len = 0;
976 #ifndef OPENSSL_NO_NEXTPROTONEG
977 const char *next_proto_neg_in = NULL;
978 tlsextnextprotoctx next_proto = { NULL, 0 };
980 const char *alpn_in = NULL;
981 tlsextalpnctx alpn_ctx = { NULL, 0 };
982 #ifndef OPENSSL_NO_PSK
983 /* by default do not send a PSK identity hint */
984 char *psk_identity_hint = NULL;
987 #ifndef OPENSSL_NO_SRP
988 char *srpuserseed = NULL;
989 char *srp_verifier_file = NULL;
991 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
992 int s_server_verify = SSL_VERIFY_NONE;
993 int s_server_session_id_context = 1; /* anything will do */
994 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
995 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
996 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
997 #ifndef OPENSSL_NO_OCSP
998 int s_tlsextstatus = 0;
1000 int no_resume_ephemeral = 0;
1001 unsigned int max_send_fragment = 0;
1002 unsigned int split_send_fragment = 0, max_pipelines = 0;
1003 const char *s_serverinfo_file = NULL;
1004 const char *keylog_file = NULL;
1005 int max_early_data = -1;
1007 /* Init of few remaining global variables */
1012 s_nbio = s_nbio_test = 0;
1021 cctx = SSL_CONF_CTX_new();
1022 vpm = X509_VERIFY_PARAM_new();
1023 if (cctx == NULL || vpm == NULL)
1025 SSL_CONF_CTX_set_flags(cctx,
1026 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1028 prog = opt_init(argc, argv, s_server_options);
1029 while ((o = opt_next()) != OPT_EOF) {
1030 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1031 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1034 if (IS_NO_PROT_FLAG(o))
1036 if (prot_opt == 1 && no_prot_opt) {
1038 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1045 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1048 opt_help(s_server_options);
1054 if (socket_family == AF_UNIX) {
1055 OPENSSL_free(host); host = NULL;
1056 OPENSSL_free(port); port = NULL;
1059 socket_family = AF_INET;
1065 if (socket_family == AF_UNIX) {
1066 OPENSSL_free(host); host = NULL;
1067 OPENSSL_free(port); port = NULL;
1070 socket_family = AF_INET6;
1073 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1079 if (socket_family == AF_UNIX) {
1080 socket_family = AF_UNSPEC;
1083 OPENSSL_free(port); port = NULL;
1084 OPENSSL_free(host); host = NULL;
1085 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1087 "%s: -port argument malformed or ambiguous\n",
1094 if (socket_family == AF_UNIX) {
1095 socket_family = AF_UNSPEC;
1098 OPENSSL_free(port); port = NULL;
1099 OPENSSL_free(host); host = NULL;
1100 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1102 "%s: -accept argument malformed or ambiguous\n",
1109 socket_family = AF_UNIX;
1110 OPENSSL_free(host); host = BUF_strdup(opt_arg());
1111 OPENSSL_free(port); port = NULL;
1114 unlink_unix_path = 1;
1118 naccept = atol(opt_arg());
1121 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1122 verify_args.depth = atoi(opt_arg());
1124 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1126 case OPT_UPPER_V_VERIFY:
1128 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1129 SSL_VERIFY_CLIENT_ONCE;
1130 verify_args.depth = atoi(opt_arg());
1133 "verify depth is %d, must return a certificate\n",
1137 context = (unsigned char *)opt_arg();
1140 s_cert_file = opt_arg();
1143 if (!set_nameopt(opt_arg()))
1147 crl_file = opt_arg();
1149 case OPT_CRL_DOWNLOAD:
1152 case OPT_SERVERINFO:
1153 s_serverinfo_file = opt_arg();
1156 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1160 s_key_file = opt_arg();
1163 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1167 passarg = opt_arg();
1169 case OPT_CERT_CHAIN:
1170 s_chain_file = opt_arg();
1173 #ifndef OPENSSL_NO_DH
1178 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1182 s_dcert_file = opt_arg();
1185 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1189 dpassarg = opt_arg();
1192 s_dkey_file = opt_arg();
1194 case OPT_DCERT_CHAIN:
1195 s_dchain_file = opt_arg();
1206 case OPT_CHAINCAPATH:
1207 chCApath = opt_arg();
1209 case OPT_VERIFYCAPATH:
1210 vfyCApath = opt_arg();
1219 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1223 if (ssl_args == NULL)
1224 ssl_args = sk_OPENSSL_STRING_new_null();
1225 if (ssl_args == NULL
1226 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1227 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1228 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1233 if (!opt_verify(o, vpm))
1238 if (!args_excert(o, &exc))
1241 case OPT_VERIFY_RET_ERROR:
1242 verify_args.return_error = 1;
1244 case OPT_VERIFY_QUIET:
1245 verify_args.quiet = 1;
1247 case OPT_BUILD_CHAIN:
1256 case OPT_CHAINCAFILE:
1257 chCAfile = opt_arg();
1259 case OPT_VERIFYCAFILE:
1260 vfyCAfile = opt_arg();
1266 s_nbio = s_nbio_test = 1;
1271 case OPT_NO_IGN_EOF:
1277 case OPT_TLSEXTDEBUG:
1281 #ifndef OPENSSL_NO_OCSP
1285 case OPT_STATUS_VERBOSE:
1286 #ifndef OPENSSL_NO_OCSP
1287 s_tlsextstatus = tlscstatp.verbose = 1;
1290 case OPT_STATUS_TIMEOUT:
1291 #ifndef OPENSSL_NO_OCSP
1293 tlscstatp.timeout = atoi(opt_arg());
1296 case OPT_STATUS_URL:
1297 #ifndef OPENSSL_NO_OCSP
1299 if (!OCSP_parse_url(opt_arg(),
1302 &tlscstatp.path, &tlscstatp.use_ssl)) {
1303 BIO_printf(bio_err, "Error parsing URL\n");
1308 case OPT_STATUS_FILE:
1309 #ifndef OPENSSL_NO_OCSP
1311 tlscstatp.respin = opt_arg();
1318 bio_s_msg = BIO_new_file(opt_arg(), "w");
1321 #ifndef OPENSSL_NO_SSL_TRACE
1325 case OPT_SECURITY_DEBUG:
1328 case OPT_SECURITY_DEBUG_VERBOSE:
1341 s_quiet = s_brief = verify_args.quiet = 1;
1344 #ifndef OPENSSL_NO_DH
1348 case OPT_NO_RESUME_EPHEMERAL:
1349 no_resume_ephemeral = 1;
1351 case OPT_PSK_IDENTITY:
1352 #ifndef OPENSSL_NO_PSK
1353 psk_identity = opt_arg();
1357 #ifndef OPENSSL_NO_PSK
1358 psk_identity_hint = opt_arg();
1362 #ifndef OPENSSL_NO_PSK
1363 for (p = psk_key = opt_arg(); *p; p++) {
1364 if (isxdigit(_UC(*p)))
1366 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1372 #ifndef OPENSSL_NO_SRP
1373 srp_verifier_file = opt_arg();
1374 if (min_version < TLS1_VERSION)
1375 min_version = TLS1_VERSION;
1378 case OPT_SRPUSERSEED:
1379 #ifndef OPENSSL_NO_SRP
1380 srpuserseed = opt_arg();
1381 if (min_version < TLS1_VERSION)
1382 min_version = TLS1_VERSION;
1397 case OPT_SSL_CONFIG:
1398 ssl_config = opt_arg();
1401 min_version = SSL3_VERSION;
1402 max_version = SSL3_VERSION;
1405 min_version = TLS1_3_VERSION;
1406 max_version = TLS1_3_VERSION;
1409 min_version = TLS1_2_VERSION;
1410 max_version = TLS1_2_VERSION;
1413 min_version = TLS1_1_VERSION;
1414 max_version = TLS1_1_VERSION;
1417 min_version = TLS1_VERSION;
1418 max_version = TLS1_VERSION;
1421 #ifndef OPENSSL_NO_DTLS
1422 meth = DTLS_server_method();
1423 socket_type = SOCK_DGRAM;
1427 #ifndef OPENSSL_NO_DTLS
1428 meth = DTLS_server_method();
1429 min_version = DTLS1_VERSION;
1430 max_version = DTLS1_VERSION;
1431 socket_type = SOCK_DGRAM;
1435 #ifndef OPENSSL_NO_DTLS
1436 meth = DTLS_server_method();
1437 min_version = DTLS1_2_VERSION;
1438 max_version = DTLS1_2_VERSION;
1439 socket_type = SOCK_DGRAM;
1443 #ifndef OPENSSL_NO_SCTP
1444 protocol = IPPROTO_SCTP;
1448 #ifndef OPENSSL_NO_DTLS
1449 enable_timeouts = 1;
1453 #ifndef OPENSSL_NO_DTLS
1454 socket_mtu = atol(opt_arg());
1458 #ifndef OPENSSL_NO_DTLS
1463 session_id_prefix = opt_arg();
1466 engine = setup_engine(opt_arg(), 1);
1471 case OPT_SERVERNAME:
1472 tlsextcbp.servername = opt_arg();
1474 case OPT_SERVERNAME_FATAL:
1475 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1478 s_cert_file2 = opt_arg();
1481 s_key_file2 = opt_arg();
1483 case OPT_NEXTPROTONEG:
1484 # ifndef OPENSSL_NO_NEXTPROTONEG
1485 next_proto_neg_in = opt_arg();
1489 alpn_in = opt_arg();
1491 case OPT_SRTP_PROFILES:
1492 #ifndef OPENSSL_NO_SRTP
1493 srtp_profiles = opt_arg();
1496 case OPT_KEYMATEXPORT:
1497 keymatexportlabel = opt_arg();
1499 case OPT_KEYMATEXPORTLEN:
1500 keymatexportlen = atoi(opt_arg());
1505 case OPT_MAX_SEND_FRAG:
1506 max_send_fragment = atoi(opt_arg());
1508 case OPT_SPLIT_SEND_FRAG:
1509 split_send_fragment = atoi(opt_arg());
1511 case OPT_MAX_PIPELINES:
1512 max_pipelines = atoi(opt_arg());
1515 read_buf_len = atoi(opt_arg());
1517 case OPT_KEYLOG_FILE:
1518 keylog_file = opt_arg();
1521 max_early_data = atoi(opt_arg());
1522 if (max_early_data < 0) {
1523 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1527 case OPT_EARLY_DATA:
1532 argc = opt_num_rest();
1535 #ifndef OPENSSL_NO_NEXTPROTONEG
1536 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1537 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1541 #ifndef OPENSSL_NO_DTLS
1542 if (www && socket_type == SOCK_DGRAM) {
1543 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1547 if (dtlslisten && socket_type != SOCK_DGRAM) {
1548 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1554 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1556 "Can't use unix sockets and datagrams together\n");
1561 #ifndef OPENSSL_NO_SCTP
1562 if (protocol == IPPROTO_SCTP) {
1563 if (socket_type != SOCK_DGRAM) {
1564 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1567 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1568 socket_type = SOCK_STREAM;
1572 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1573 BIO_printf(bio_err, "Error getting password\n");
1577 if (s_key_file == NULL)
1578 s_key_file = s_cert_file;
1580 if (s_key_file2 == NULL)
1581 s_key_file2 = s_cert_file2;
1583 if (!load_excert(&exc))
1587 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1588 "server certificate private key file");
1589 if (s_key == NULL) {
1590 ERR_print_errors(bio_err);
1594 s_cert = load_cert(s_cert_file, s_cert_format,
1595 "server certificate file");
1597 if (s_cert == NULL) {
1598 ERR_print_errors(bio_err);
1601 if (s_chain_file != NULL) {
1602 if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1603 "server certificate chain"))
1607 if (tlsextcbp.servername != NULL) {
1608 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1609 "second server certificate private key file");
1610 if (s_key2 == NULL) {
1611 ERR_print_errors(bio_err);
1615 s_cert2 = load_cert(s_cert_file2, s_cert_format,
1616 "second server certificate file");
1618 if (s_cert2 == NULL) {
1619 ERR_print_errors(bio_err);
1624 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1625 if (next_proto_neg_in) {
1626 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1627 if (next_proto.data == NULL)
1631 alpn_ctx.data = NULL;
1633 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1634 if (alpn_ctx.data == NULL)
1638 if (crl_file != NULL) {
1640 crl = load_crl(crl_file, crl_format);
1642 BIO_puts(bio_err, "Error loading CRL\n");
1643 ERR_print_errors(bio_err);
1646 crls = sk_X509_CRL_new_null();
1647 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1648 BIO_puts(bio_err, "Error adding CRL\n");
1649 ERR_print_errors(bio_err);
1655 if (s_dcert_file != NULL) {
1657 if (s_dkey_file == NULL)
1658 s_dkey_file = s_dcert_file;
1660 s_dkey = load_key(s_dkey_file, s_dkey_format,
1661 0, dpass, engine, "second certificate private key file");
1662 if (s_dkey == NULL) {
1663 ERR_print_errors(bio_err);
1667 s_dcert = load_cert(s_dcert_file, s_dcert_format,
1668 "second server certificate file");
1670 if (s_dcert == NULL) {
1671 ERR_print_errors(bio_err);
1674 if (s_dchain_file != NULL) {
1675 if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1676 "second server certificate chain"))
1682 if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1683 && !RAND_status()) {
1685 "warning, not much extra random data, consider using the -rand option\n");
1688 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1689 app_RAND_load_files(inrand));
1691 if (bio_s_out == NULL) {
1692 if (s_quiet && !s_debug) {
1693 bio_s_out = BIO_new(BIO_s_null());
1694 if (s_msg && bio_s_msg == NULL)
1695 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1697 if (bio_s_out == NULL)
1698 bio_s_out = dup_bio_out(FORMAT_TEXT);
1701 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1707 s_dcert_file = NULL;
1709 s_cert_file2 = NULL;
1713 ctx = SSL_CTX_new(meth);
1715 ERR_print_errors(bio_err);
1719 ssl_ctx_security_debug(ctx, sdebug);
1721 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1722 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1724 ERR_print_errors(bio_err);
1728 if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1730 if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1733 if (session_id_prefix) {
1734 if (strlen(session_id_prefix) >= 32)
1736 "warning: id_prefix is too long, only one new session will be possible\n");
1737 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1738 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1739 ERR_print_errors(bio_err);
1742 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1744 SSL_CTX_set_quiet_shutdown(ctx, 1);
1746 ssl_ctx_set_excert(ctx, exc);
1749 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1751 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1753 init_session_cache_ctx(ctx);
1755 SSL_CTX_sess_set_cache_size(ctx, 128);
1758 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1761 if (max_send_fragment > 0
1762 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1763 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1764 prog, max_send_fragment);
1768 if (split_send_fragment > 0
1769 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1770 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1771 prog, split_send_fragment);
1774 if (max_pipelines > 0
1775 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1776 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1777 prog, max_pipelines);
1781 if (read_buf_len > 0) {
1782 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1784 #ifndef OPENSSL_NO_SRTP
1785 if (srtp_profiles != NULL) {
1786 /* Returns 0 on success! */
1787 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1788 BIO_printf(bio_err, "Error setting SRTP profile\n");
1789 ERR_print_errors(bio_err);
1795 if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1796 ERR_print_errors(bio_err);
1799 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1800 BIO_printf(bio_err, "Error setting verify params\n");
1801 ERR_print_errors(bio_err);
1805 ssl_ctx_add_crls(ctx, crls, 0);
1806 if (!config_ctx(cctx, ssl_args, ctx))
1809 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1810 crls, crl_download)) {
1811 BIO_printf(bio_err, "Error loading store locations\n");
1812 ERR_print_errors(bio_err);
1817 ctx2 = SSL_CTX_new(meth);
1819 ERR_print_errors(bio_err);
1825 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1828 ssl_ctx_security_debug(ctx, sdebug);
1830 if (session_id_prefix) {
1831 if (strlen(session_id_prefix) >= 32)
1833 "warning: id_prefix is too long, only one new session will be possible\n");
1834 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1835 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1836 ERR_print_errors(bio_err);
1839 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1841 SSL_CTX_set_quiet_shutdown(ctx2, 1);
1843 ssl_ctx_set_excert(ctx2, exc);
1846 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1849 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1851 init_session_cache_ctx(ctx2);
1853 SSL_CTX_sess_set_cache_size(ctx2, 128);
1856 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1858 if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1860 ERR_print_errors(bio_err);
1863 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1864 BIO_printf(bio_err, "Error setting verify params\n");
1865 ERR_print_errors(bio_err);
1869 ssl_ctx_add_crls(ctx2, crls, 0);
1870 if (!config_ctx(cctx, ssl_args, ctx2))
1873 #ifndef OPENSSL_NO_NEXTPROTONEG
1874 if (next_proto.data)
1875 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1879 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1881 #ifndef OPENSSL_NO_DH
1886 dh = load_dh_param(dhfile);
1887 else if (s_cert_file != NULL)
1888 dh = load_dh_param(s_cert_file);
1891 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1893 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1895 (void)BIO_flush(bio_s_out);
1898 SSL_CTX_set_dh_auto(ctx, 1);
1899 } else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1900 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1901 ERR_print_errors(bio_err);
1908 DH *dh2 = load_dh_param(s_cert_file2);
1910 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1911 (void)BIO_flush(bio_s_out);
1918 SSL_CTX_set_dh_auto(ctx2, 1);
1919 } else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1920 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1921 ERR_print_errors(bio_err);
1930 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1933 if (s_serverinfo_file != NULL
1934 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1935 ERR_print_errors(bio_err);
1940 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1943 if (s_dcert != NULL) {
1944 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1948 if (no_resume_ephemeral) {
1949 SSL_CTX_set_not_resumable_session_callback(ctx,
1950 not_resumable_sess_cb);
1953 SSL_CTX_set_not_resumable_session_callback(ctx2,
1954 not_resumable_sess_cb);
1956 #ifndef OPENSSL_NO_PSK
1957 if (psk_key != NULL) {
1959 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
1960 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1963 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1964 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1965 ERR_print_errors(bio_err);
1970 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1971 if (!SSL_CTX_set_session_id_context(ctx,
1972 (void *)&s_server_session_id_context,
1973 sizeof s_server_session_id_context)) {
1974 BIO_printf(bio_err, "error setting session id context\n");
1975 ERR_print_errors(bio_err);
1979 /* Set DTLS cookie generation and verification callbacks */
1980 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1981 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1984 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1985 if (!SSL_CTX_set_session_id_context(ctx2,
1986 (void *)&s_server_session_id_context,
1987 sizeof s_server_session_id_context)) {
1988 BIO_printf(bio_err, "error setting session id context\n");
1989 ERR_print_errors(bio_err);
1992 tlsextcbp.biodebug = bio_s_out;
1993 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1994 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1995 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1996 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1999 #ifndef OPENSSL_NO_SRP
2000 if (srp_verifier_file != NULL) {
2001 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
2002 srp_callback_parm.user = NULL;
2003 srp_callback_parm.login = NULL;
2005 SRP_VBASE_init(srp_callback_parm.vb,
2006 srp_verifier_file)) != SRP_NO_ERROR) {
2008 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
2009 srp_verifier_file, ret);
2012 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
2013 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
2014 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
2017 if (CAfile != NULL) {
2018 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2021 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2023 #ifndef OPENSSL_NO_OCSP
2024 if (s_tlsextstatus) {
2025 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2026 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2028 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2029 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2033 if (set_keylog_file(ctx, keylog_file))
2036 if (max_early_data >= 0)
2037 SSL_CTX_set_max_early_data(ctx, max_early_data);
2039 BIO_printf(bio_s_out, "ACCEPT\n");
2040 (void)BIO_flush(bio_s_out);
2042 server_cb = rev_body;
2044 server_cb = www_body;
2046 server_cb = sv_body;
2048 if (socket_family == AF_UNIX
2049 && unlink_unix_path)
2052 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2053 server_cb, context, naccept);
2054 print_stats(bio_s_out, ctx);
2058 set_keylog_file(NULL, NULL);
2060 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2062 EVP_PKEY_free(s_key);
2063 EVP_PKEY_free(s_dkey);
2064 sk_X509_pop_free(s_chain, X509_free);
2065 sk_X509_pop_free(s_dchain, X509_free);
2067 OPENSSL_free(dpass);
2070 X509_VERIFY_PARAM_free(vpm);
2072 OPENSSL_free(tlscstatp.host);
2073 OPENSSL_free(tlscstatp.port);
2074 OPENSSL_free(tlscstatp.path);
2077 EVP_PKEY_free(s_key2);
2078 #ifndef OPENSSL_NO_NEXTPROTONEG
2079 OPENSSL_free(next_proto.data);
2081 OPENSSL_free(alpn_ctx.data);
2082 ssl_excert_free(exc);
2083 sk_OPENSSL_STRING_free(ssl_args);
2084 SSL_CONF_CTX_free(cctx);
2085 release_engine(engine);
2086 BIO_free(bio_s_out);
2088 BIO_free(bio_s_msg);
2090 #ifdef CHARSET_EBCDIC
2091 BIO_meth_free(methods_ebcdic);
2096 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2098 BIO_printf(bio, "%4ld items in the session cache\n",
2099 SSL_CTX_sess_number(ssl_ctx));
2100 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2101 SSL_CTX_sess_connect(ssl_ctx));
2102 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2103 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2104 BIO_printf(bio, "%4ld client connects that finished\n",
2105 SSL_CTX_sess_connect_good(ssl_ctx));
2106 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2107 SSL_CTX_sess_accept(ssl_ctx));
2108 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2109 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2110 BIO_printf(bio, "%4ld server accepts that finished\n",
2111 SSL_CTX_sess_accept_good(ssl_ctx));
2112 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2113 BIO_printf(bio, "%4ld session cache misses\n",
2114 SSL_CTX_sess_misses(ssl_ctx));
2115 BIO_printf(bio, "%4ld session cache timeouts\n",
2116 SSL_CTX_sess_timeouts(ssl_ctx));
2117 BIO_printf(bio, "%4ld callback cache hits\n",
2118 SSL_CTX_sess_cb_hits(ssl_ctx));
2119 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2120 SSL_CTX_sess_cache_full(ssl_ctx),
2121 SSL_CTX_sess_get_cache_size(ssl_ctx));
2124 static int sv_body(int s, int stype, int prot, unsigned char *context)
2133 struct timeval timeout;
2134 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2137 struct timeval *timeoutp;
2139 #ifndef OPENSSL_NO_DTLS
2140 # ifndef OPENSSL_NO_SCTP
2141 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2143 int isdtls = (stype == SOCK_DGRAM);
2147 buf = app_malloc(bufsize, "server buffer");
2149 if (!BIO_socket_nbio(s, 1))
2150 ERR_print_errors(bio_err);
2152 BIO_printf(bio_err, "Turned on non blocking io\n");
2158 if (s_tlsextdebug) {
2159 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2160 SSL_set_tlsext_debug_arg(con, bio_s_out);
2164 && !SSL_set_session_id_context(con,
2165 context, strlen((char *)context))) {
2166 BIO_printf(bio_err, "Error setting session id context\n");
2171 if (!SSL_clear(con)) {
2172 BIO_printf(bio_err, "Error clearing SSL connection\n");
2176 #ifndef OPENSSL_NO_DTLS
2178 # ifndef OPENSSL_NO_SCTP
2179 if (prot == IPPROTO_SCTP)
2180 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2183 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2185 if (enable_timeouts) {
2187 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2188 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2191 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2192 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2196 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2197 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2198 DTLS_get_link_min_mtu(con));
2203 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2204 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2205 BIO_printf(bio_err, "Failed to set MTU\n");
2211 /* want to do MTU discovery */
2212 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2214 # ifndef OPENSSL_NO_SCTP
2215 if (prot != IPPROTO_SCTP) {
2216 /* Turn on cookie exchange. Not necessary for SCTP */
2217 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2222 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2225 BIO_printf(bio_err, "Unable to create BIO\n");
2226 ERR_print_errors(bio_err);
2233 test = BIO_new(BIO_f_nbio_test());
2234 sbio = BIO_push(test, sbio);
2237 SSL_set_bio(con, sbio, sbio);
2238 SSL_set_accept_state(con);
2239 /* SSL_set_fd(con,s); */
2242 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2243 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2246 #ifndef OPENSSL_NO_SSL_TRACE
2248 SSL_set_msg_callback(con, SSL_trace);
2251 SSL_set_msg_callback(con, msg_cb);
2252 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2255 if (s_tlsextdebug) {
2256 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2257 SSL_set_tlsext_debug_arg(con, bio_s_out);
2261 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2264 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2266 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2267 if (edret != SSL_READ_EARLY_DATA_ERROR)
2270 switch (SSL_get_error(con, 0)) {
2271 case SSL_ERROR_WANT_WRITE:
2272 case SSL_ERROR_WANT_ASYNC:
2273 case SSL_ERROR_WANT_READ:
2274 /* Just keep trying - busy waiting */
2277 BIO_printf(bio_err, "Error reading early data\n");
2278 ERR_print_errors(bio_err);
2282 if (readbytes > 0) {
2284 BIO_printf(bio_s_out, "Early data received:\n");
2287 raw_write_stdout(buf, (unsigned int)readbytes);
2288 (void)BIO_flush(bio_s_out);
2292 BIO_printf(bio_s_out, "No early data received\n");
2294 BIO_printf(bio_s_out, "\nEnd of early data\n");
2295 if (SSL_is_init_finished(con))
2296 print_connection_info(con);
2299 if (fileno_stdin() > s)
2300 width = fileno_stdin() + 1;
2304 int read_from_terminal;
2305 int read_from_sslcon;
2307 read_from_terminal = 0;
2308 read_from_sslcon = SSL_has_pending(con)
2309 || (async && SSL_waiting_for_async(con));
2311 if (!read_from_sslcon) {
2313 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2314 openssl_fdset(fileno_stdin(), &readfds);
2316 openssl_fdset(s, &readfds);
2318 * Note: under VMS with SOCKETSHR the second parameter is
2319 * currently of type (int *) whereas under other systems it is
2320 * (void *) if you don't have a cast it will choke the compiler:
2321 * if you do have a cast then you can either go for (int *) or
2324 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2326 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2327 * only on sockets. As a workaround we timeout the select every
2328 * second and check for any keypress. In a proper Windows
2329 * application we wouldn't do this because it is inefficient.
2333 i = select(width, (void *)&readfds, NULL, NULL, &tv);
2334 if (has_stdin_waiting())
2335 read_from_terminal = 1;
2336 if ((i < 0) || (!i && !read_from_terminal))
2339 if ((SSL_version(con) == DTLS1_VERSION) &&
2340 DTLSv1_get_timeout(con, &timeout))
2341 timeoutp = &timeout;
2345 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2347 if ((SSL_version(con) == DTLS1_VERSION)
2348 && DTLSv1_handle_timeout(con) > 0) {
2349 BIO_printf(bio_err, "TIMEOUT occurred\n");
2354 if (FD_ISSET(fileno_stdin(), &readfds))
2355 read_from_terminal = 1;
2357 if (FD_ISSET(s, &readfds))
2358 read_from_sslcon = 1;
2360 if (read_from_terminal) {
2364 i = raw_read_stdin(buf, bufsize / 2);
2366 /* both loops are skipped when i <= 0 */
2367 for (j = 0; j < i; j++)
2370 for (j = i - 1; j >= 0; j--) {
2371 buf[j + lf_num] = buf[j];
2372 if (buf[j] == '\n') {
2375 buf[j + lf_num] = '\r';
2378 assert(lf_num == 0);
2380 i = raw_read_stdin(buf, bufsize);
2383 if (!s_quiet && !s_brief) {
2384 if ((i <= 0) || (buf[0] == 'Q')) {
2385 BIO_printf(bio_s_out, "DONE\n");
2386 (void)BIO_flush(bio_s_out);
2388 close_accept_socket();
2392 if ((i <= 0) || (buf[0] == 'q')) {
2393 BIO_printf(bio_s_out, "DONE\n");
2394 (void)BIO_flush(bio_s_out);
2395 if (SSL_version(con) != DTLS1_VERSION)
2398 * close_accept_socket(); ret= -11;
2402 #ifndef OPENSSL_NO_HEARTBEATS
2403 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2404 BIO_printf(bio_err, "HEARTBEATING\n");
2410 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2411 SSL_renegotiate(con);
2412 i = SSL_do_handshake(con);
2413 printf("SSL_do_handshake -> %d\n", i);
2417 * strcpy(buf,"server side RE-NEGOTIATE\n");
2420 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2422 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2424 SSL_renegotiate(con);
2425 i = SSL_do_handshake(con);
2426 printf("SSL_do_handshake -> %d\n", i);
2430 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2434 if ((buf[0] == 'K' || buf[0] == 'k')
2435 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2436 SSL_key_update(con, buf[0] == 'K' ?
2437 SSL_KEY_UPDATE_REQUESTED
2438 : SSL_KEY_UPDATE_NOT_REQUESTED);
2439 i = SSL_do_handshake(con);
2440 printf("SSL_do_handshake -> %d\n", i);
2444 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2448 if (buf[0] == 'P') {
2449 static const char *str = "Lets print some clear text\n";
2450 BIO_write(SSL_get_wbio(con), str, strlen(str));
2452 if (buf[0] == 'S') {
2453 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2456 #ifdef CHARSET_EBCDIC
2457 ebcdic2ascii(buf, buf, i);
2461 /* should do a select for the write */
2464 if (++count == 100) {
2466 SSL_renegotiate(con);
2469 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2470 #ifndef OPENSSL_NO_SRP
2471 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2472 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2473 SRP_user_pwd_free(srp_callback_parm.user);
2474 srp_callback_parm.user =
2475 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2476 srp_callback_parm.login);
2477 if (srp_callback_parm.user)
2478 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2479 srp_callback_parm.user->info);
2481 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2482 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2485 switch (SSL_get_error(con, k)) {
2486 case SSL_ERROR_NONE:
2488 case SSL_ERROR_WANT_ASYNC:
2489 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2490 (void)BIO_flush(bio_s_out);
2491 wait_for_async(con);
2493 case SSL_ERROR_WANT_WRITE:
2494 case SSL_ERROR_WANT_READ:
2495 case SSL_ERROR_WANT_X509_LOOKUP:
2496 BIO_printf(bio_s_out, "Write BLOCK\n");
2497 (void)BIO_flush(bio_s_out);
2499 case SSL_ERROR_WANT_ASYNC_JOB:
2501 * This shouldn't ever happen in s_server. Treat as an error
2503 case SSL_ERROR_SYSCALL:
2505 BIO_printf(bio_s_out, "ERROR\n");
2506 (void)BIO_flush(bio_s_out);
2507 ERR_print_errors(bio_err);
2511 case SSL_ERROR_ZERO_RETURN:
2512 BIO_printf(bio_s_out, "DONE\n");
2513 (void)BIO_flush(bio_s_out);
2525 if (read_from_sslcon) {
2527 * init_ssl_connection handles all async events itself so if we're
2528 * waiting for async then we shouldn't go back into
2529 * init_ssl_connection
2531 if ((!async || !SSL_waiting_for_async(con))
2532 && !SSL_is_init_finished(con)) {
2533 i = init_ssl_connection(con);
2538 } else if (i == 0) {
2544 i = SSL_read(con, (char *)buf, bufsize);
2545 #ifndef OPENSSL_NO_SRP
2546 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2547 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2548 SRP_user_pwd_free(srp_callback_parm.user);
2549 srp_callback_parm.user =
2550 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2551 srp_callback_parm.login);
2552 if (srp_callback_parm.user)
2553 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2554 srp_callback_parm.user->info);
2556 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2557 i = SSL_read(con, (char *)buf, bufsize);
2560 switch (SSL_get_error(con, i)) {
2561 case SSL_ERROR_NONE:
2562 #ifdef CHARSET_EBCDIC
2563 ascii2ebcdic(buf, buf, i);
2565 raw_write_stdout(buf, (unsigned int)i);
2566 (void)BIO_flush(bio_s_out);
2567 if (SSL_has_pending(con))
2570 case SSL_ERROR_WANT_ASYNC:
2571 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2572 (void)BIO_flush(bio_s_out);
2573 wait_for_async(con);
2575 case SSL_ERROR_WANT_WRITE:
2576 case SSL_ERROR_WANT_READ:
2577 BIO_printf(bio_s_out, "Read BLOCK\n");
2578 (void)BIO_flush(bio_s_out);
2580 case SSL_ERROR_WANT_ASYNC_JOB:
2582 * This shouldn't ever happen in s_server. Treat as an error
2584 case SSL_ERROR_SYSCALL:
2586 BIO_printf(bio_s_out, "ERROR\n");
2587 (void)BIO_flush(bio_s_out);
2588 ERR_print_errors(bio_err);
2591 case SSL_ERROR_ZERO_RETURN:
2592 BIO_printf(bio_s_out, "DONE\n");
2593 (void)BIO_flush(bio_s_out);
2602 BIO_printf(bio_s_out, "shutting down SSL\n");
2603 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2606 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2607 OPENSSL_clear_free(buf, bufsize);
2609 BIO_printf(bio_s_out, "ACCEPT\n");
2610 (void)BIO_flush(bio_s_out);
2614 static void close_accept_socket(void)
2616 BIO_printf(bio_err, "shutdown accept socket\n");
2617 if (accept_socket >= 0) {
2618 BIO_closesocket(accept_socket);
2622 static int is_retryable(SSL *con, int i)
2624 int err = SSL_get_error(con, i);
2626 /* If it's not a fatal error, it must be retryable */
2627 return (err != SSL_ERROR_SSL)
2628 && (err != SSL_ERROR_SYSCALL)
2629 && (err != SSL_ERROR_ZERO_RETURN);
2632 static int init_ssl_connection(SSL *con)
2638 #ifndef OPENSSL_NO_DTLS
2640 BIO_ADDR *client = NULL;
2642 if ((client = BIO_ADDR_new()) == NULL) {
2643 BIO_printf(bio_err, "ERROR - memory\n");
2646 i = DTLSv1_listen(con, client);
2651 wbio = SSL_get_wbio(con);
2653 BIO_get_fd(wbio, &fd);
2656 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2657 BIO_printf(bio_err, "ERROR - unable to connect\n");
2658 BIO_ADDR_free(client);
2661 BIO_ADDR_free(client);
2663 i = SSL_accept(con);
2665 BIO_ADDR_free(client);
2671 i = SSL_accept(con);
2674 retry = is_retryable(con, i);
2675 #ifdef CERT_CB_TEST_RETRY
2678 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2679 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2681 "LOOKUP from certificate callback during accept\n");
2682 i = SSL_accept(con);
2684 retry = is_retryable(con, i);
2689 #ifndef OPENSSL_NO_SRP
2691 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2692 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2693 srp_callback_parm.login);
2694 SRP_user_pwd_free(srp_callback_parm.user);
2695 srp_callback_parm.user =
2696 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2697 srp_callback_parm.login);
2698 if (srp_callback_parm.user)
2699 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2700 srp_callback_parm.user->info);
2702 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2703 i = SSL_accept(con);
2705 retry = is_retryable(con, i);
2708 } while (i < 0 && SSL_waiting_for_async(con));
2711 if ((dtlslisten && i == 0)
2712 || (!dtlslisten && retry)) {
2713 BIO_printf(bio_s_out, "DELAY\n");
2717 BIO_printf(bio_err, "ERROR\n");
2719 verify_err = SSL_get_verify_result(con);
2720 if (verify_err != X509_V_OK) {
2721 BIO_printf(bio_err, "verify error:%s\n",
2722 X509_verify_cert_error_string(verify_err));
2724 /* Always print any error messages */
2725 ERR_print_errors(bio_err);
2729 print_connection_info(con);
2733 static void print_connection_info(SSL *con)
2738 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2739 const unsigned char *next_proto_neg;
2740 unsigned next_proto_neg_len;
2742 unsigned char *exportedkeymat;
2746 print_ssl_summary(con);
2748 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2750 peer = SSL_get_peer_certificate(con);
2752 BIO_printf(bio_s_out, "Client certificate\n");
2753 PEM_write_bio_X509(bio_s_out, peer);
2754 dump_cert_text(bio_s_out, peer);
2759 if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2760 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2761 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2762 ssl_print_sigalgs(bio_s_out, con);
2763 #ifndef OPENSSL_NO_EC
2764 ssl_print_point_formats(bio_s_out, con);
2765 ssl_print_groups(bio_s_out, con, 0);
2767 print_ca_names(bio_s_out, con);
2768 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2770 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2771 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2772 if (next_proto_neg) {
2773 BIO_printf(bio_s_out, "NEXTPROTO is ");
2774 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2775 BIO_printf(bio_s_out, "\n");
2778 #ifndef OPENSSL_NO_SRTP
2780 SRTP_PROTECTION_PROFILE *srtp_profile
2781 = SSL_get_selected_srtp_profile(con);
2784 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2785 srtp_profile->name);
2788 if (SSL_session_reused(con))
2789 BIO_printf(bio_s_out, "Reused session-id\n");
2790 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2791 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2792 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
2793 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
2795 if (keymatexportlabel != NULL) {
2796 BIO_printf(bio_s_out, "Keying material exporter:\n");
2797 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2798 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2799 exportedkeymat = app_malloc(keymatexportlen, "export key");
2800 if (!SSL_export_keying_material(con, exportedkeymat,
2803 strlen(keymatexportlabel),
2805 BIO_printf(bio_s_out, " Error\n");
2807 BIO_printf(bio_s_out, " Keying material: ");
2808 for (i = 0; i < keymatexportlen; i++)
2809 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2810 BIO_printf(bio_s_out, "\n");
2812 OPENSSL_free(exportedkeymat);
2815 (void)BIO_flush(bio_s_out);
2818 #ifndef OPENSSL_NO_DH
2819 static DH *load_dh_param(const char *dhfile)
2824 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2826 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2833 static int www_body(int s, int stype, int prot, unsigned char *context)
2839 const SSL_CIPHER *c;
2840 BIO *io, *ssl_bio, *sbio;
2842 int total_bytes = 0;
2847 /* Set width for a select call if needed */
2850 buf = app_malloc(bufsize, "server www buffer");
2851 io = BIO_new(BIO_f_buffer());
2852 ssl_bio = BIO_new(BIO_f_ssl());
2853 if ((io == NULL) || (ssl_bio == NULL))
2857 if (!BIO_socket_nbio(s, 1))
2858 ERR_print_errors(bio_err);
2860 BIO_printf(bio_err, "Turned on non blocking io\n");
2863 /* lets make the output buffer a reasonable size */
2864 if (!BIO_set_write_buffer_size(io, bufsize))
2867 if ((con = SSL_new(ctx)) == NULL)
2870 if (s_tlsextdebug) {
2871 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2872 SSL_set_tlsext_debug_arg(con, bio_s_out);
2876 && !SSL_set_session_id_context(con, context,
2877 strlen((char *)context)))
2880 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2884 test = BIO_new(BIO_f_nbio_test());
2885 sbio = BIO_push(test, sbio);
2887 SSL_set_bio(con, sbio, sbio);
2888 SSL_set_accept_state(con);
2890 /* SSL_set_fd(con,s); */
2891 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2892 BIO_push(io, ssl_bio);
2893 #ifdef CHARSET_EBCDIC
2894 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2898 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2899 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2902 #ifndef OPENSSL_NO_SSL_TRACE
2904 SSL_set_msg_callback(con, SSL_trace);
2907 SSL_set_msg_callback(con, msg_cb);
2908 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2912 i = BIO_gets(io, buf, bufsize - 1);
2913 if (i < 0) { /* error */
2914 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2916 ERR_print_errors(bio_err);
2919 BIO_printf(bio_s_out, "read R BLOCK\n");
2920 #ifndef OPENSSL_NO_SRP
2921 if (BIO_should_io_special(io)
2922 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2923 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2924 SRP_user_pwd_free(srp_callback_parm.user);
2925 srp_callback_parm.user =
2926 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2927 srp_callback_parm.login);
2928 if (srp_callback_parm.user)
2929 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2930 srp_callback_parm.user->info);
2932 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2936 #if !defined(OPENSSL_SYS_MSDOS)
2941 } else if (i == 0) { /* end of input */
2946 /* else we have data */
2947 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2948 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2951 STACK_OF(SSL_CIPHER) *sk;
2952 static const char *space = " ";
2954 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2955 if (strncmp("GET /renegcert", buf, 14) == 0)
2957 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2959 i = SSL_renegotiate(con);
2960 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2961 /* Send the HelloRequest */
2962 i = SSL_do_handshake(con);
2964 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2965 SSL_get_error(con, i));
2966 ERR_print_errors(bio_err);
2969 /* Wait for a ClientHello to come back */
2971 openssl_fdset(s, &readfds);
2972 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2973 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2974 BIO_printf(bio_s_out,
2975 "Error waiting for client response\n");
2976 ERR_print_errors(bio_err);
2980 * We're not actually expecting any data here and we ignore
2981 * any that is sent. This is just to force the handshake that
2982 * we're expecting to come from the client. If they haven't
2983 * sent one there's not much we can do.
2985 BIO_gets(io, buf, bufsize - 1);
2989 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2990 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2991 BIO_puts(io, "<pre>\n");
2992 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2994 for (i = 0; i < local_argc; i++) {
2996 for (myp = local_argv[i]; *myp; myp++)
2999 BIO_puts(io, "<");
3002 BIO_puts(io, ">");
3005 BIO_puts(io, "&");
3008 BIO_write(io, myp, 1);
3011 BIO_write(io, " ", 1);
3016 "Secure Renegotiation IS%s supported\n",
3017 SSL_get_secure_renegotiation_support(con) ?
3021 * The following is evil and should not really be done
3023 BIO_printf(io, "Ciphers supported in s_server binary\n");
3024 sk = SSL_get_ciphers(con);
3025 j = sk_SSL_CIPHER_num(sk);
3026 for (i = 0; i < j; i++) {
3027 c = sk_SSL_CIPHER_value(sk, i);
3028 BIO_printf(io, "%-11s:%-25s ",
3029 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3030 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3034 p = SSL_get_shared_ciphers(con, buf, bufsize);
3037 "---\nCiphers common between both SSL end points:\n");
3041 BIO_write(io, space, 26 - j);
3044 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3046 BIO_write(io, p, 1);
3053 ssl_print_sigalgs(io, con);
3054 #ifndef OPENSSL_NO_EC
3055 ssl_print_groups(io, con, 0);
3057 print_ca_names(io, con);
3058 BIO_printf(io, (SSL_session_reused(con)
3059 ? "---\nReused, " : "---\nNew, "));
3060 c = SSL_get_current_cipher(con);
3061 BIO_printf(io, "%s, Cipher is %s\n",
3062 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3063 SSL_SESSION_print(io, SSL_get_session(con));
3064 BIO_printf(io, "---\n");
3065 print_stats(io, SSL_get_SSL_CTX(con));
3066 BIO_printf(io, "---\n");
3067 peer = SSL_get_peer_certificate(con);
3069 BIO_printf(io, "Client certificate\n");
3070 X509_print(io, peer);
3071 PEM_write_bio_X509(io, peer);
3075 BIO_puts(io, "no client certificate available\n");
3076 BIO_puts(io, "</BODY></HTML>\r\n\r\n");
3078 } else if ((www == 2 || www == 3)
3079 && (strncmp("GET /", buf, 5) == 0)) {
3082 static const char *text =
3083 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3089 for (e = p; *e != '\0'; e++) {
3095 dot = (e[0] == '.') ? 2 : 0;
3098 dot = (e[0] == '.') ? 3 : 0;
3101 dot = (e[0] == '/') ? -1 : 0;
3105 dot = (e[0] == '/') ? 1 : 0;
3107 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3112 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3119 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
3125 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3129 /* if a directory, do the index thang */
3130 if (app_isdir(p) > 0) {
3132 BIO_printf(io, "'%s' is a directory\r\n", p);
3136 if ((file = BIO_new_file(p, "r")) == NULL) {
3138 BIO_printf(io, "Error opening '%s'\r\n", p);
3139 ERR_print_errors(io);
3144 BIO_printf(bio_err, "FILE:%s\n", p);
3148 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3149 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3150 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3152 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3155 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3159 i = BIO_read(file, buf, bufsize);
3165 BIO_printf(bio_err, "%d\n", i);
3166 if (total_bytes > 3 * 1024) {
3168 BIO_printf(bio_err, "RENEGOTIATE\n");
3169 SSL_renegotiate(con);
3173 for (j = 0; j < i;) {
3176 if (++count == 13) {
3177 SSL_renegotiate(con);
3180 k = BIO_write(io, &(buf[j]), i - j);
3182 if (!BIO_should_retry(io)
3183 && !SSL_waiting_for_async(con))
3186 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3200 i = (int)BIO_flush(io);
3202 if (!BIO_should_retry(io))
3208 /* make sure we re-use sessions */
3209 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3213 BIO_printf(bio_s_out, "ACCEPT\n");
3219 static int rev_body(int s, int stype, int prot, unsigned char *context)
3225 BIO *io, *ssl_bio, *sbio;
3227 buf = app_malloc(bufsize, "server rev buffer");
3228 io = BIO_new(BIO_f_buffer());
3229 ssl_bio = BIO_new(BIO_f_ssl());
3230 if ((io == NULL) || (ssl_bio == NULL))
3233 /* lets make the output buffer a reasonable size */
3234 if (!BIO_set_write_buffer_size(io, bufsize))
3237 if ((con = SSL_new(ctx)) == NULL)
3240 if (s_tlsextdebug) {
3241 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3242 SSL_set_tlsext_debug_arg(con, bio_s_out);
3245 && !SSL_set_session_id_context(con, context,
3246 strlen((char *)context))) {
3247 ERR_print_errors(bio_err);
3251 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3252 SSL_set_bio(con, sbio, sbio);
3253 SSL_set_accept_state(con);
3255 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3256 BIO_push(io, ssl_bio);
3257 #ifdef CHARSET_EBCDIC
3258 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3262 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3263 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3266 #ifndef OPENSSL_NO_SSL_TRACE
3268 SSL_set_msg_callback(con, SSL_trace);
3271 SSL_set_msg_callback(con, msg_cb);
3272 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3276 i = BIO_do_handshake(io);
3279 if (!BIO_should_retry(io)) {
3280 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3281 ERR_print_errors(bio_err);
3284 #ifndef OPENSSL_NO_SRP
3285 if (BIO_should_io_special(io)
3286 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3287 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3288 SRP_user_pwd_free(srp_callback_parm.user);
3289 srp_callback_parm.user =
3290 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3291 srp_callback_parm.login);
3292 if (srp_callback_parm.user)
3293 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3294 srp_callback_parm.user->info);
3296 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3301 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3302 print_ssl_summary(con);
3305 i = BIO_gets(io, buf, bufsize - 1);
3306 if (i < 0) { /* error */
3307 if (!BIO_should_retry(io)) {
3309 ERR_print_errors(bio_err);
3312 BIO_printf(bio_s_out, "read R BLOCK\n");
3313 #ifndef OPENSSL_NO_SRP
3314 if (BIO_should_io_special(io)
3315 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3316 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3317 SRP_user_pwd_free(srp_callback_parm.user);
3318 srp_callback_parm.user =
3319 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3320 srp_callback_parm.login);
3321 if (srp_callback_parm.user)
3322 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3323 srp_callback_parm.user->info);
3325 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3329 #if !defined(OPENSSL_SYS_MSDOS)
3334 } else if (i == 0) { /* end of input */
3336 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3339 char *p = buf + i - 1;
3340 while (i && (*p == '\n' || *p == '\r')) {
3344 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3346 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3349 BUF_reverse((unsigned char *)buf, NULL, i);
3351 BIO_write(io, buf, i + 1);
3356 if (!BIO_should_retry(io))
3362 /* make sure we re-use sessions */
3363 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3372 #define MAX_SESSION_ID_ATTEMPTS 10
3373 static int generate_session_id(const SSL *ssl, unsigned char *id,
3374 unsigned int *id_len)
3376 unsigned int count = 0;
3378 if (RAND_bytes(id, *id_len) <= 0)
3381 * Prefix the session_id with the required prefix. NB: If our prefix
3382 * is too long, clip it - but there will be worse effects anyway, eg.
3383 * the server could only possibly create 1 session ID (ie. the
3384 * prefix!) so all future session negotiations will fail due to
3387 memcpy(id, session_id_prefix,
3388 (strlen(session_id_prefix) < *id_len) ?
3389 strlen(session_id_prefix) : *id_len);
3391 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3392 (++count < MAX_SESSION_ID_ATTEMPTS));
3393 if (count >= MAX_SESSION_ID_ATTEMPTS)
3399 * By default s_server uses an in-memory cache which caches SSL_SESSION
3400 * structures without any serialisation. This hides some bugs which only
3401 * become apparent in deployed servers. By implementing a basic external
3402 * session cache some issues can be debugged using s_server.
3405 typedef struct simple_ssl_session_st {
3410 struct simple_ssl_session_st *next;
3411 } simple_ssl_session;
3413 static simple_ssl_session *first = NULL;
3415 static int add_session(SSL *ssl, SSL_SESSION *session)
3417 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3420 SSL_SESSION_get_id(session, &sess->idlen);
3421 sess->derlen = i2d_SSL_SESSION(session, NULL);
3422 if (sess->derlen < 0) {
3423 BIO_printf(bio_err, "Error encoding session\n");
3428 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3429 sess->der = app_malloc(sess->derlen, "get session buffer");
3431 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3432 OPENSSL_free(sess->id);
3433 OPENSSL_free(sess->der);
3439 /* Assume it still works. */
3440 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3441 BIO_printf(bio_err, "Unexpected session encoding length\n");
3442 OPENSSL_free(sess->id);
3443 OPENSSL_free(sess->der);
3450 BIO_printf(bio_err, "New session added to external cache\n");
3454 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3457 simple_ssl_session *sess;
3459 for (sess = first; sess; sess = sess->next) {
3460 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3461 const unsigned char *p = sess->der;
3462 BIO_printf(bio_err, "Lookup session: cache hit\n");
3463 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3466 BIO_printf(bio_err, "Lookup session: cache miss\n");
3470 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3472 simple_ssl_session *sess, *prev = NULL;
3473 const unsigned char *id;
3475 id = SSL_SESSION_get_id(session, &idlen);
3476 for (sess = first; sess; sess = sess->next) {
3477 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3479 prev->next = sess->next;
3482 OPENSSL_free(sess->id);
3483 OPENSSL_free(sess->der);
3491 static void init_session_cache_ctx(SSL_CTX *sctx)
3493 SSL_CTX_set_session_cache_mode(sctx,
3494 SSL_SESS_CACHE_NO_INTERNAL |
3495 SSL_SESS_CACHE_SERVER);
3496 SSL_CTX_sess_set_new_cb(sctx, add_session);
3497 SSL_CTX_sess_set_get_cb(sctx, get_session);
3498 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3501 static void free_sessions(void)
3503 simple_ssl_session *sess, *tsess;
3504 for (sess = first; sess;) {
3505 OPENSSL_free(sess->id);
3506 OPENSSL_free(sess->der);
3509 OPENSSL_free(tsess);
3514 #endif /* OPENSSL_NO_SOCK */