2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* ====================================================================
11 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12 * ECC cipher suite support in OpenSSL originally developed by
13 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
15 /* ====================================================================
16 * Copyright 2005 Nokia. All rights reserved.
18 * The portions of the attached software ("Contribution") is developed by
19 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
22 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
23 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
24 * support (see RFC 4279) to OpenSSL.
26 * No patent licenses or other rights except those expressly stated in
27 * the OpenSSL open source license shall be deemed granted or received
28 * expressly, by implication, estoppel, or otherwise.
30 * No assurances are provided by Nokia that the Contribution does not
31 * infringe the patent or other intellectual property rights of any third
32 * party or that the license provides you with all the necessary rights
33 * to make use of the Contribution.
35 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
36 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
37 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
38 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
47 /* Included before async.h to avoid some warnings */
51 #include <openssl/e_os2.h>
52 #include <openssl/async.h>
53 #include <openssl/ssl.h>
55 #ifndef OPENSSL_NO_SOCK
58 * With IPv6, it looks like Digital has mixed up the proper order of
59 * recursive header file inclusion, resulting in the compiler complaining
60 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
61 * needed to have fileno() declared correctly... So let's define u_int
63 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
65 typedef unsigned int u_int;
68 #include <openssl/lhash.h>
69 #include <openssl/bn.h>
72 #include <openssl/err.h>
73 #include <openssl/pem.h>
74 #include <openssl/x509.h>
75 #include <openssl/ssl.h>
76 #include <openssl/rand.h>
77 #include <openssl/ocsp.h>
79 # include <openssl/dh.h>
81 #ifndef OPENSSL_NO_RSA
82 # include <openssl/rsa.h>
84 #ifndef OPENSSL_NO_SRP
85 # include <openssl/srp.h>
90 #include <openssl/ebcdic.h>
93 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
94 static int sv_body(int s, int stype, int prot, unsigned char *context);
95 static int www_body(int s, int stype, int prot, unsigned char *context);
96 static int rev_body(int s, int stype, int prot, unsigned char *context);
97 static void close_accept_socket(void);
98 static int init_ssl_connection(SSL *s);
99 static void print_stats(BIO *bp, SSL_CTX *ctx);
100 static int generate_session_id(const SSL *ssl, unsigned char *id,
101 unsigned int *id_len);
102 static void init_session_cache_ctx(SSL_CTX *sctx);
103 static void free_sessions(void);
104 #ifndef OPENSSL_NO_DH
105 static DH *load_dh_param(const char *dhfile);
107 static void print_connection_info(SSL *con);
109 static const int bufsize = 16 * 1024;
110 static int accept_socket = -1;
112 #define TEST_CERT "server.pem"
113 #define TEST_CERT2 "server2.pem"
115 static int s_nbio = 0;
116 static int s_nbio_test = 0;
117 static int s_crlf = 0;
118 static SSL_CTX *ctx = NULL;
119 static SSL_CTX *ctx2 = NULL;
122 static BIO *bio_s_out = NULL;
123 static BIO *bio_s_msg = NULL;
124 static int s_debug = 0;
125 static int s_tlsextdebug = 0;
126 static int s_msg = 0;
127 static int s_quiet = 0;
128 static int s_ign_eof = 0;
129 static int s_brief = 0;
131 static char *keymatexportlabel = NULL;
132 static int keymatexportlen = 20;
134 static int async = 0;
136 static const char *session_id_prefix = NULL;
138 #ifndef OPENSSL_NO_DTLS
139 static int enable_timeouts = 0;
140 static long socket_mtu;
144 * We define this but make it always be 0 in no-dtls builds to simplify the
147 static int dtlslisten = 0;
149 static int early_data = 0;
151 #ifndef OPENSSL_NO_PSK
152 static const char psk_identity[] = "Client_identity";
153 char *psk_key = NULL; /* by default PSK is not used */
155 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
157 unsigned int max_psk_len)
163 BIO_printf(bio_s_out, "psk_server_cb\n");
165 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
169 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
170 (int)strlen(identity), identity);
172 /* here we could lookup the given identity e.g. from a database */
173 if (strcmp(identity, psk_identity) != 0) {
174 BIO_printf(bio_s_out, "PSK error: client identity not found"
175 " (got '%s' expected '%s')\n", identity, psk_identity);
179 BIO_printf(bio_s_out, "PSK client identity found\n");
181 /* convert the PSK key to binary */
182 key = OPENSSL_hexstr2buf(psk_key, &key_len);
184 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
188 if (key_len > (int)max_psk_len) {
190 "psk buffer of callback is too small (%d) for key (%ld)\n",
191 max_psk_len, key_len);
196 memcpy(psk, key, key_len);
200 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
204 BIO_printf(bio_err, "Error in PSK server callback\n");
205 (void)BIO_flush(bio_err);
206 (void)BIO_flush(bio_s_out);
211 #ifndef OPENSSL_NO_SRP
212 /* This is a context that we pass to callbacks */
213 typedef struct srpsrvparm_st {
220 * This callback pretends to require some asynchronous logic in order to
221 * obtain a verifier. When the callback is called for a new connection we
222 * return with a negative value. This will provoke the accept etc to return
223 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
224 * (which would normally occur after a worker has finished) and we set the
227 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
229 srpsrvparm *p = (srpsrvparm *) arg;
230 int ret = SSL3_AL_FATAL;
232 if (p->login == NULL && p->user == NULL) {
233 p->login = SSL_get_srp_username(s);
234 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
238 if (p->user == NULL) {
239 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
243 if (SSL_set_srp_server_param
244 (s, p->user->N, p->user->g, p->user->s, p->user->v,
245 p->user->info) < 0) {
246 *ad = SSL_AD_INTERNAL_ERROR;
250 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
251 p->login, p->user->info);
252 ret = SSL_ERROR_NONE;
255 SRP_user_pwd_free(p->user);
263 static int local_argc = 0;
264 static char **local_argv;
266 #ifdef CHARSET_EBCDIC
267 static int ebcdic_new(BIO *bi);
268 static int ebcdic_free(BIO *a);
269 static int ebcdic_read(BIO *b, char *out, int outl);
270 static int ebcdic_write(BIO *b, const char *in, int inl);
271 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
272 static int ebcdic_gets(BIO *bp, char *buf, int size);
273 static int ebcdic_puts(BIO *bp, const char *str);
275 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
276 static BIO_METHOD *methods_ebcdic = NULL;
278 /* This struct is "unwarranted chumminess with the compiler." */
284 static const BIO_METHOD *BIO_f_ebcdic_filter()
286 if (methods_ebcdic == NULL) {
287 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
288 "EBCDIC/ASCII filter");
289 if (methods_ebcdic == NULL
290 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
291 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
292 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
293 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
294 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
295 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
296 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
299 return methods_ebcdic;
302 static int ebcdic_new(BIO *bi)
304 EBCDIC_OUTBUFF *wbuf;
306 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
307 wbuf->alloced = 1024;
308 wbuf->buff[0] = '\0';
310 BIO_set_data(bi, wbuf);
315 static int ebcdic_free(BIO *a)
317 EBCDIC_OUTBUFF *wbuf;
321 wbuf = BIO_get_data(a);
323 BIO_set_data(a, NULL);
329 static int ebcdic_read(BIO *b, char *out, int outl)
332 BIO *next = BIO_next(b);
334 if (out == NULL || outl == 0)
339 ret = BIO_read(next, out, outl);
341 ascii2ebcdic(out, out, ret);
345 static int ebcdic_write(BIO *b, const char *in, int inl)
347 EBCDIC_OUTBUFF *wbuf;
348 BIO *next = BIO_next(b);
352 if ((in == NULL) || (inl <= 0))
357 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
359 if (inl > (num = wbuf->alloced)) {
360 num = num + num; /* double the size */
364 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
367 wbuf->buff[0] = '\0';
369 BIO_set_data(b, wbuf);
372 ebcdic2ascii(wbuf->buff, in, inl);
374 ret = BIO_write(next, wbuf->buff, inl);
379 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
382 BIO *next = BIO_next(b);
391 ret = BIO_ctrl(next, cmd, num, ptr);
397 static int ebcdic_gets(BIO *bp, char *buf, int size)
400 BIO *next = BIO_next(bp);
404 /* return(BIO_gets(bp->next_bio,buf,size));*/
405 for (i = 0; i < size - 1; ++i) {
406 ret = ebcdic_read(bp, &buf[i], 1);
409 else if (buf[i] == '\n') {
416 return (ret < 0 && i == 0) ? ret : i;
419 static int ebcdic_puts(BIO *bp, const char *str)
421 if (BIO_next(bp) == NULL)
423 return ebcdic_write(bp, str, strlen(str));
427 /* This is a context that we pass to callbacks */
428 typedef struct tlsextctx_st {
434 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
436 tlsextctx *p = (tlsextctx *) arg;
437 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
438 if (servername && p->biodebug)
439 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
443 return SSL_TLSEXT_ERR_NOACK;
446 if (strcasecmp(servername, p->servername))
447 return p->extension_error;
449 BIO_printf(p->biodebug, "Switching server context.\n");
450 SSL_set_SSL_CTX(s, ctx2);
453 return SSL_TLSEXT_ERR_OK;
456 /* Structure passed to cert status callback */
457 typedef struct tlsextstatusctx_st {
459 /* File to load OCSP Response from (or NULL if no file) */
461 /* Default responder to use */
462 char *host, *path, *port;
467 static tlsextstatusctx tlscstatp = { -1 };
469 #ifndef OPENSSL_NO_OCSP
472 * Helper function to get an OCSP_RESPONSE from a responder. This is a
473 * simplified version. It examines certificates each time and makes one OCSP
474 * responder query for each request. A full version would store details such as
475 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
476 * them until they were considered "expired".
478 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
479 OCSP_RESPONSE **resp)
481 char *host = NULL, *port = NULL, *path = NULL;
483 STACK_OF(OPENSSL_STRING) *aia = NULL;
485 X509_STORE_CTX *inctx = NULL;
487 OCSP_REQUEST *req = NULL;
488 OCSP_CERTID *id = NULL;
489 STACK_OF(X509_EXTENSION) *exts;
490 int ret = SSL_TLSEXT_ERR_NOACK;
493 /* Build up OCSP query from server certificate */
494 x = SSL_get_certificate(s);
495 aia = X509_get1_ocsp(x);
497 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
498 &host, &port, &path, &use_ssl)) {
499 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
503 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
504 sk_OPENSSL_STRING_value(aia, 0));
508 "cert_status: no AIA and no default responder URL\n");
514 use_ssl = srctx->use_ssl;
517 inctx = X509_STORE_CTX_new();
520 if (!X509_STORE_CTX_init(inctx,
521 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
524 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
525 X509_get_issuer_name(x));
527 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
530 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
531 X509_OBJECT_free(obj);
534 req = OCSP_REQUEST_new();
537 if (!OCSP_request_add0_id(req, id))
540 /* Add any extensions to the request */
541 SSL_get_tlsext_status_exts(s, &exts);
542 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
543 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
544 if (!OCSP_REQUEST_add_ext(req, ext, -1))
547 *resp = process_responder(req, host, path, port, use_ssl, NULL,
550 BIO_puts(bio_err, "cert_status: error querying responder\n");
554 ret = SSL_TLSEXT_ERR_OK;
558 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
561 * If we parsed aia we need to free; otherwise they were copied and we
568 X509_email_free(aia);
570 OCSP_CERTID_free(id);
571 OCSP_REQUEST_free(req);
572 X509_STORE_CTX_free(inctx);
577 * Certificate Status callback. This is called when a client includes a
578 * certificate status request extension. The response is either obtained from a
579 * file, or from an OCSP responder.
581 static int cert_status_cb(SSL *s, void *arg)
583 tlsextstatusctx *srctx = arg;
584 OCSP_RESPONSE *resp = NULL;
585 unsigned char *rspder = NULL;
587 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
590 BIO_puts(bio_err, "cert_status: callback called\n");
592 if (srctx->respin != NULL) {
593 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
594 if (derbio == NULL) {
595 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
598 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
601 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
605 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
606 if (ret != SSL_TLSEXT_ERR_OK)
610 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
614 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
615 if (srctx->verbose) {
616 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
617 OCSP_RESPONSE_print(bio_err, resp, 2);
620 ret = SSL_TLSEXT_ERR_OK;
623 if (ret != SSL_TLSEXT_ERR_OK)
624 ERR_print_errors(bio_err);
626 OCSP_RESPONSE_free(resp);
632 #ifndef OPENSSL_NO_NEXTPROTONEG
633 /* This is the context that we pass to next_proto_cb */
634 typedef struct tlsextnextprotoctx_st {
637 } tlsextnextprotoctx;
639 static int next_proto_cb(SSL *s, const unsigned char **data,
640 unsigned int *len, void *arg)
642 tlsextnextprotoctx *next_proto = arg;
644 *data = next_proto->data;
645 *len = next_proto->len;
647 return SSL_TLSEXT_ERR_OK;
649 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
651 /* This the context that we pass to alpn_cb */
652 typedef struct tlsextalpnctx_st {
657 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
658 const unsigned char *in, unsigned int inlen, void *arg)
660 tlsextalpnctx *alpn_ctx = arg;
663 /* We can assume that |in| is syntactically valid. */
665 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
666 for (i = 0; i < inlen;) {
668 BIO_write(bio_s_out, ", ", 2);
669 BIO_write(bio_s_out, &in[i + 1], in[i]);
672 BIO_write(bio_s_out, "\n", 1);
675 if (SSL_select_next_proto
676 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
677 inlen) != OPENSSL_NPN_NEGOTIATED) {
678 return SSL_TLSEXT_ERR_NOACK;
682 BIO_printf(bio_s_out, "ALPN protocols selected: ");
683 BIO_write(bio_s_out, *out, *outlen);
684 BIO_write(bio_s_out, "\n", 1);
687 return SSL_TLSEXT_ERR_OK;
690 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
692 /* disable resumption for sessions with forward secure ciphers */
693 return is_forward_secure;
696 #ifndef OPENSSL_NO_SRP
697 static srpsrvparm srp_callback_parm;
699 #ifndef OPENSSL_NO_SRTP
700 static char *srtp_profiles = NULL;
703 typedef enum OPTION_choice {
704 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
705 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
706 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
707 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
708 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
709 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
710 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
711 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
712 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
713 OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
714 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
715 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
716 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
717 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
718 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
719 OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC,
720 OPT_SSL_CONFIG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
721 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
722 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN,
723 OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
724 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN,
725 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
726 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_EARLY_DATA,
732 const OPTIONS s_server_options[] = {
733 {"help", OPT_HELP, '-', "Display this summary"},
734 {"port", OPT_PORT, 'p',
735 "TCP/IP port to listen on for connections (default is " PORT ")"},
736 {"accept", OPT_ACCEPT, 's',
737 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
739 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
741 {"4", OPT_4, '-', "Use IPv4 only"},
742 {"6", OPT_6, '-', "Use IPv6 only"},
744 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
746 {"context", OPT_CONTEXT, 's', "Set session ID context"},
747 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
748 {"Verify", OPT_UPPER_V_VERIFY, 'n',
749 "Turn on peer certificate verification, must have a cert"},
750 {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
751 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
752 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
753 {"serverinfo", OPT_SERVERINFO, 's',
754 "PEM serverinfo file for certificate"},
755 {"certform", OPT_CERTFORM, 'F',
756 "Certificate format (PEM or DER) PEM default"},
757 {"key", OPT_KEY, '<',
758 "Private Key if not in -cert; default is " TEST_CERT},
759 {"keyform", OPT_KEYFORM, 'f',
760 "Key format (PEM, DER or ENGINE) PEM default"},
761 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
762 {"dcert", OPT_DCERT, '<',
763 "Second certificate file to use (usually for DSA)"},
764 {"dcertform", OPT_DCERTFORM, 'F',
765 "Second certificate format (PEM or DER) PEM default"},
766 {"dkey", OPT_DKEY, '<',
767 "Second private key file to use (usually for DSA)"},
768 {"dkeyform", OPT_DKEYFORM, 'F',
769 "Second key format (PEM, DER or ENGINE) PEM default"},
770 {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
771 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
772 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
773 {"debug", OPT_DEBUG, '-', "Print more output"},
774 {"msg", OPT_MSG, '-', "Show protocol messages"},
775 {"msgfile", OPT_MSGFILE, '>',
776 "File to send output of -msg or -trace, instead of stdout"},
777 {"state", OPT_STATE, '-', "Print the SSL states"},
778 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
779 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
780 {"no-CAfile", OPT_NOCAFILE, '-',
781 "Do not load the default certificates file"},
782 {"no-CApath", OPT_NOCAPATH, '-',
783 "Do not load certificates from the default certificates directory"},
784 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
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 {"servername", OPT_SERVERNAME, 's',
791 "Servername for HostName TLS extension"},
792 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
793 "mismatch send fatal alert (default warning alert)"},
794 {"cert2", OPT_CERT2, '<',
795 "Certificate file to use for servername; default is" TEST_CERT2},
796 {"key2", OPT_KEY2, '<',
797 "-Private Key file to use for servername if not in -cert2"},
798 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
799 "Hex dump of all TLS extensions received"},
800 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
801 {"id_prefix", OPT_ID_PREFIX, 's',
802 "Generate SSL/TLS session IDs prefixed by arg"},
803 {"rand", OPT_RAND, 's',
804 "Load the file(s) into the random number generator"},
805 {"keymatexport", OPT_KEYMATEXPORT, 's',
806 "Export keying material using label"},
807 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
808 "Export len bytes of keying material (default 20)"},
809 {"CRL", OPT_CRL, '<', "CRL file to use"},
810 {"crl_download", OPT_CRL_DOWNLOAD, '-',
811 "Download CRL from distribution points"},
812 {"cert_chain", OPT_CERT_CHAIN, '<',
813 "certificate chain file in PEM format"},
814 {"dcert_chain", OPT_DCERT_CHAIN, '<',
815 "second certificate chain file in PEM format"},
816 {"chainCApath", OPT_CHAINCAPATH, '/',
817 "use dir as certificate store path to build CA certificate chain"},
818 {"verifyCApath", OPT_VERIFYCAPATH, '/',
819 "use dir as certificate store path to verify CA certificate"},
820 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
821 {"ext_cache", OPT_EXT_CACHE, '-',
822 "Disable internal cache, setup and use external cache"},
823 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
824 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
825 "Close connection on verification error"},
826 {"verify_quiet", OPT_VERIFY_QUIET, '-',
827 "No verify output except verify errors"},
828 {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
829 {"chainCAfile", OPT_CHAINCAFILE, '<',
830 "CA file for certificate chain (PEM format)"},
831 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
832 "CA file for certificate verification (PEM format)"},
833 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
834 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
835 #ifndef OPENSSL_NO_OCSP
836 {"status", OPT_STATUS, '-', "Request certificate status from server"},
837 {"status_verbose", OPT_STATUS_VERBOSE, '-',
838 "Print more output in certificate status callback"},
839 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
840 "Status request responder timeout"},
841 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
842 {"status_file", OPT_STATUS_FILE, '<',
843 "File containing DER encoded OCSP Response"},
845 #ifndef OPENSSL_NO_SSL_TRACE
846 {"trace", OPT_TRACE, '-', "trace protocol messages"},
848 {"security_debug", OPT_SECURITY_DEBUG, '-',
849 "Print output from SSL/TLS security framework"},
850 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
851 "Print more output from SSL/TLS security framework"},
852 {"brief", OPT_BRIEF, '-',
853 "Restrict output to brief summary of connection parameters"},
854 {"rev", OPT_REV, '-',
855 "act as a simple test server which just sends back with the received text reversed"},
856 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
857 {"ssl_config", OPT_SSL_CONFIG, 's',
858 "Configure SSL_CTX using the configuration 'val'"},
859 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'n',
860 "Size used to split data for encrypt pipelines"},
861 {"max_pipelines", OPT_MAX_PIPELINES, 'n',
862 "Maximum number of encrypt/decrypt pipelines to be used"},
863 {"read_buf", OPT_READ_BUF, 'n',
864 "Default read buffer size to be used for connections"},
868 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
869 #ifndef OPENSSL_NO_PSK
870 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
871 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
873 #ifndef OPENSSL_NO_SRP
874 {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
875 {"srpuserseed", OPT_SRPUSERSEED, 's',
876 "A seed string for a default user salt"},
878 #ifndef OPENSSL_NO_SSL3
879 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
881 #ifndef OPENSSL_NO_TLS1
882 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
884 #ifndef OPENSSL_NO_TLS1_1
885 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
887 #ifndef OPENSSL_NO_TLS1_2
888 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
890 #ifndef OPENSSL_NO_TLS1_3
891 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
893 #ifndef OPENSSL_NO_DTLS
894 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
895 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
896 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
897 {"listen", OPT_LISTEN, '-',
898 "Listen for a DTLS ClientHello with a cookie and then connect"},
900 #ifndef OPENSSL_NO_DTLS1
901 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
903 #ifndef OPENSSL_NO_DTLS1_2
904 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
906 #ifndef OPENSSL_NO_SCTP
907 {"sctp", OPT_SCTP, '-', "Use SCTP"},
909 #ifndef OPENSSL_NO_DH
910 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
912 #ifndef OPENSSL_NO_NEXTPROTONEG
913 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
914 "Set the advertised protocols for the NPN extension (comma-separated list)"},
916 #ifndef OPENSSL_NO_SRTP
917 {"use_srtp", OPT_SRTP_PROFILES, 's',
918 "Offer SRTP key management with a colon-separated profile list"},
920 {"alpn", OPT_ALPN, 's',
921 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
922 #ifndef OPENSSL_NO_ENGINE
923 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
925 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
926 {"max_early_data", OPT_MAX_EARLY, 'n',
927 "The maximum number of bytes of early data"},
928 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
929 {NULL, OPT_EOF, 0, NULL}
932 #define IS_PROT_FLAG(o) \
933 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
934 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
936 int s_server_main(int argc, char *argv[])
938 ENGINE *engine = NULL;
939 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
940 SSL_CONF_CTX *cctx = NULL;
941 const SSL_METHOD *meth = TLS_server_method();
942 SSL_EXCERT *exc = NULL;
943 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
944 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
945 STACK_OF(X509_CRL) *crls = NULL;
946 X509 *s_cert = NULL, *s_dcert = NULL;
947 X509_VERIFY_PARAM *vpm = NULL;
948 const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
949 char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
950 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
951 char *crl_file = NULL, *prog;
953 int unlink_unix_path = 0;
955 do_server_cb server_cb;
956 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
957 #ifndef OPENSSL_NO_DH
961 int nocert = 0, ret = 1;
962 int noCApath = 0, noCAfile = 0;
963 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
964 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
965 int rev = 0, naccept = -1, sdebug = 0;
966 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
967 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
969 char *port = BUF_strdup(PORT);
970 unsigned char *context = NULL;
972 EVP_PKEY *s_key2 = NULL;
973 X509 *s_cert2 = NULL;
974 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
975 const char *ssl_config = NULL;
976 int read_buf_len = 0;
977 #ifndef OPENSSL_NO_NEXTPROTONEG
978 const char *next_proto_neg_in = NULL;
979 tlsextnextprotoctx next_proto = { NULL, 0 };
981 const char *alpn_in = NULL;
982 tlsextalpnctx alpn_ctx = { NULL, 0 };
983 #ifndef OPENSSL_NO_PSK
984 /* by default do not send a PSK identity hint */
985 char *psk_identity_hint = NULL;
988 #ifndef OPENSSL_NO_SRP
989 char *srpuserseed = NULL;
990 char *srp_verifier_file = NULL;
992 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
993 int s_server_verify = SSL_VERIFY_NONE;
994 int s_server_session_id_context = 1; /* anything will do */
995 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
996 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
997 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
998 #ifndef OPENSSL_NO_OCSP
999 int s_tlsextstatus = 0;
1001 int no_resume_ephemeral = 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;
1352 #ifndef OPENSSL_NO_PSK
1353 psk_identity_hint = opt_arg();
1357 #ifndef OPENSSL_NO_PSK
1358 for (p = psk_key = opt_arg(); *p; p++) {
1359 if (isxdigit(_UC(*p)))
1361 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1367 #ifndef OPENSSL_NO_SRP
1368 srp_verifier_file = opt_arg();
1369 if (min_version < TLS1_VERSION)
1370 min_version = TLS1_VERSION;
1373 case OPT_SRPUSERSEED:
1374 #ifndef OPENSSL_NO_SRP
1375 srpuserseed = opt_arg();
1376 if (min_version < TLS1_VERSION)
1377 min_version = TLS1_VERSION;
1392 case OPT_SSL_CONFIG:
1393 ssl_config = opt_arg();
1396 min_version = SSL3_VERSION;
1397 max_version = SSL3_VERSION;
1400 min_version = TLS1_3_VERSION;
1401 max_version = TLS1_3_VERSION;
1404 min_version = TLS1_2_VERSION;
1405 max_version = TLS1_2_VERSION;
1408 min_version = TLS1_1_VERSION;
1409 max_version = TLS1_1_VERSION;
1412 min_version = TLS1_VERSION;
1413 max_version = TLS1_VERSION;
1416 #ifndef OPENSSL_NO_DTLS
1417 meth = DTLS_server_method();
1418 socket_type = SOCK_DGRAM;
1422 #ifndef OPENSSL_NO_DTLS
1423 meth = DTLS_server_method();
1424 min_version = DTLS1_VERSION;
1425 max_version = DTLS1_VERSION;
1426 socket_type = SOCK_DGRAM;
1430 #ifndef OPENSSL_NO_DTLS
1431 meth = DTLS_server_method();
1432 min_version = DTLS1_2_VERSION;
1433 max_version = DTLS1_2_VERSION;
1434 socket_type = SOCK_DGRAM;
1438 #ifndef OPENSSL_NO_SCTP
1439 protocol = IPPROTO_SCTP;
1443 #ifndef OPENSSL_NO_DTLS
1444 enable_timeouts = 1;
1448 #ifndef OPENSSL_NO_DTLS
1449 socket_mtu = atol(opt_arg());
1453 #ifndef OPENSSL_NO_DTLS
1458 session_id_prefix = opt_arg();
1461 engine = setup_engine(opt_arg(), 1);
1466 case OPT_SERVERNAME:
1467 tlsextcbp.servername = opt_arg();
1469 case OPT_SERVERNAME_FATAL:
1470 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1473 s_cert_file2 = opt_arg();
1476 s_key_file2 = opt_arg();
1478 case OPT_NEXTPROTONEG:
1479 # ifndef OPENSSL_NO_NEXTPROTONEG
1480 next_proto_neg_in = opt_arg();
1484 alpn_in = opt_arg();
1486 case OPT_SRTP_PROFILES:
1487 #ifndef OPENSSL_NO_SRTP
1488 srtp_profiles = opt_arg();
1491 case OPT_KEYMATEXPORT:
1492 keymatexportlabel = opt_arg();
1494 case OPT_KEYMATEXPORTLEN:
1495 keymatexportlen = atoi(opt_arg());
1500 case OPT_SPLIT_SEND_FRAG:
1501 split_send_fragment = atoi(opt_arg());
1502 if (split_send_fragment == 0) {
1504 * Not allowed - set to a deliberately bad value so we get an
1505 * error message below
1507 split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1;
1510 case OPT_MAX_PIPELINES:
1511 max_pipelines = atoi(opt_arg());
1514 read_buf_len = atoi(opt_arg());
1516 case OPT_KEYLOG_FILE:
1517 keylog_file = opt_arg();
1520 max_early_data = atoi(opt_arg());
1521 if (max_early_data < 0) {
1522 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1526 case OPT_EARLY_DATA:
1531 argc = opt_num_rest();
1534 #ifndef OPENSSL_NO_DTLS
1535 if (www && socket_type == SOCK_DGRAM) {
1536 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1540 if (dtlslisten && socket_type != SOCK_DGRAM) {
1541 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1547 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1549 "Can't use unix sockets and datagrams together\n");
1554 #ifndef OPENSSL_NO_SCTP
1555 if (protocol == IPPROTO_SCTP) {
1556 if (socket_type != SOCK_DGRAM) {
1557 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1560 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1561 socket_type = SOCK_STREAM;
1565 if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1566 BIO_printf(bio_err, "Bad split send fragment size\n");
1570 if (max_pipelines > SSL_MAX_PIPELINES) {
1571 BIO_printf(bio_err, "Bad max pipelines value\n");
1575 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1576 BIO_printf(bio_err, "Error getting password\n");
1580 if (s_key_file == NULL)
1581 s_key_file = s_cert_file;
1583 if (s_key_file2 == NULL)
1584 s_key_file2 = s_cert_file2;
1586 if (!load_excert(&exc))
1590 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1591 "server certificate private key file");
1593 ERR_print_errors(bio_err);
1597 s_cert = load_cert(s_cert_file, s_cert_format,
1598 "server certificate file");
1601 ERR_print_errors(bio_err);
1605 if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1606 "server certificate chain"))
1610 if (tlsextcbp.servername) {
1611 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1612 "second server certificate private key file");
1614 ERR_print_errors(bio_err);
1618 s_cert2 = load_cert(s_cert_file2, s_cert_format,
1619 "second server certificate file");
1622 ERR_print_errors(bio_err);
1627 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1628 if (next_proto_neg_in) {
1629 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1630 if (next_proto.data == NULL)
1634 alpn_ctx.data = NULL;
1636 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1637 if (alpn_ctx.data == NULL)
1643 crl = load_crl(crl_file, crl_format);
1645 BIO_puts(bio_err, "Error loading CRL\n");
1646 ERR_print_errors(bio_err);
1649 crls = sk_X509_CRL_new_null();
1650 if (!crls || !sk_X509_CRL_push(crls, crl)) {
1651 BIO_puts(bio_err, "Error adding CRL\n");
1652 ERR_print_errors(bio_err);
1660 if (s_dkey_file == NULL)
1661 s_dkey_file = s_dcert_file;
1663 s_dkey = load_key(s_dkey_file, s_dkey_format,
1664 0, dpass, engine, "second certificate private key file");
1666 ERR_print_errors(bio_err);
1670 s_dcert = load_cert(s_dcert_file, s_dcert_format,
1671 "second server certificate file");
1674 ERR_print_errors(bio_err);
1677 if (s_dchain_file) {
1678 if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1679 "second server certificate chain"))
1685 if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1686 && !RAND_status()) {
1688 "warning, not much extra random data, consider using the -rand option\n");
1691 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1692 app_RAND_load_files(inrand));
1694 if (bio_s_out == NULL) {
1695 if (s_quiet && !s_debug) {
1696 bio_s_out = BIO_new(BIO_s_null());
1697 if (s_msg && !bio_s_msg)
1698 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1700 if (bio_s_out == NULL)
1701 bio_s_out = dup_bio_out(FORMAT_TEXT);
1704 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1710 s_dcert_file = NULL;
1712 s_cert_file2 = NULL;
1716 ctx = SSL_CTX_new(meth);
1718 ERR_print_errors(bio_err);
1722 ssl_ctx_security_debug(ctx, sdebug);
1724 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1725 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1727 ERR_print_errors(bio_err);
1731 if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1733 if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1736 if (session_id_prefix) {
1737 if (strlen(session_id_prefix) >= 32)
1739 "warning: id_prefix is too long, only one new session will be possible\n");
1740 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1741 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1742 ERR_print_errors(bio_err);
1745 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1747 SSL_CTX_set_quiet_shutdown(ctx, 1);
1749 ssl_ctx_set_excert(ctx, exc);
1752 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1754 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1756 init_session_cache_ctx(ctx);
1758 SSL_CTX_sess_set_cache_size(ctx, 128);
1761 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1763 if (split_send_fragment > 0) {
1764 SSL_CTX_set_split_send_fragment(ctx, split_send_fragment);
1766 if (max_pipelines > 0) {
1767 SSL_CTX_set_max_pipelines(ctx, max_pipelines);
1770 if (read_buf_len > 0) {
1771 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1773 #ifndef OPENSSL_NO_SRTP
1774 if (srtp_profiles != NULL) {
1775 /* Returns 0 on success! */
1776 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1777 BIO_printf(bio_err, "Error setting SRTP profile\n");
1778 ERR_print_errors(bio_err);
1784 if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1785 ERR_print_errors(bio_err);
1788 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1789 BIO_printf(bio_err, "Error setting verify params\n");
1790 ERR_print_errors(bio_err);
1794 ssl_ctx_add_crls(ctx, crls, 0);
1795 if (!config_ctx(cctx, ssl_args, ctx))
1798 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1799 crls, crl_download)) {
1800 BIO_printf(bio_err, "Error loading store locations\n");
1801 ERR_print_errors(bio_err);
1806 ctx2 = SSL_CTX_new(meth);
1808 ERR_print_errors(bio_err);
1814 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1817 ssl_ctx_security_debug(ctx, sdebug);
1819 if (session_id_prefix) {
1820 if (strlen(session_id_prefix) >= 32)
1822 "warning: id_prefix is too long, only one new session will be possible\n");
1823 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1824 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1825 ERR_print_errors(bio_err);
1828 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1830 SSL_CTX_set_quiet_shutdown(ctx2, 1);
1832 ssl_ctx_set_excert(ctx2, exc);
1835 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1838 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1840 init_session_cache_ctx(ctx2);
1842 SSL_CTX_sess_set_cache_size(ctx2, 128);
1845 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1847 if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1849 ERR_print_errors(bio_err);
1852 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1853 BIO_printf(bio_err, "Error setting verify params\n");
1854 ERR_print_errors(bio_err);
1858 ssl_ctx_add_crls(ctx2, crls, 0);
1859 if (!config_ctx(cctx, ssl_args, ctx2))
1862 #ifndef OPENSSL_NO_NEXTPROTONEG
1863 if (next_proto.data)
1864 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1868 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1870 #ifndef OPENSSL_NO_DH
1875 dh = load_dh_param(dhfile);
1876 else if (s_cert_file)
1877 dh = load_dh_param(s_cert_file);
1880 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1882 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1884 (void)BIO_flush(bio_s_out);
1887 SSL_CTX_set_dh_auto(ctx, 1);
1888 else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1889 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1890 ERR_print_errors(bio_err);
1897 DH *dh2 = load_dh_param(s_cert_file2);
1899 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1900 (void)BIO_flush(bio_s_out);
1907 SSL_CTX_set_dh_auto(ctx2, 1);
1908 else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1909 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1910 ERR_print_errors(bio_err);
1919 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1922 if (s_serverinfo_file != NULL
1923 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1924 ERR_print_errors(bio_err);
1928 if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1931 if (s_dcert != NULL) {
1932 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1936 if (no_resume_ephemeral) {
1937 SSL_CTX_set_not_resumable_session_callback(ctx,
1938 not_resumable_sess_cb);
1941 SSL_CTX_set_not_resumable_session_callback(ctx2,
1942 not_resumable_sess_cb);
1944 #ifndef OPENSSL_NO_PSK
1945 if (psk_key != NULL) {
1947 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
1948 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1951 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1952 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1953 ERR_print_errors(bio_err);
1958 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1959 if (!SSL_CTX_set_session_id_context(ctx,
1960 (void *)&s_server_session_id_context,
1961 sizeof s_server_session_id_context)) {
1962 BIO_printf(bio_err, "error setting session id context\n");
1963 ERR_print_errors(bio_err);
1967 /* Set DTLS cookie generation and verification callbacks */
1968 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1969 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1972 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1973 if (!SSL_CTX_set_session_id_context(ctx2,
1974 (void *)&s_server_session_id_context,
1975 sizeof s_server_session_id_context)) {
1976 BIO_printf(bio_err, "error setting session id context\n");
1977 ERR_print_errors(bio_err);
1980 tlsextcbp.biodebug = bio_s_out;
1981 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1982 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1983 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1984 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1987 #ifndef OPENSSL_NO_SRP
1988 if (srp_verifier_file != NULL) {
1989 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1990 srp_callback_parm.user = NULL;
1991 srp_callback_parm.login = NULL;
1993 SRP_VBASE_init(srp_callback_parm.vb,
1994 srp_verifier_file)) != SRP_NO_ERROR) {
1996 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1997 srp_verifier_file, ret);
2000 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
2001 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
2002 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
2005 if (CAfile != NULL) {
2006 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2009 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2011 #ifndef OPENSSL_NO_OCSP
2012 if (s_tlsextstatus) {
2013 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2014 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2016 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2017 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2021 if (set_keylog_file(ctx, keylog_file))
2024 if (max_early_data >= 0)
2025 SSL_CTX_set_max_early_data(ctx, max_early_data);
2027 BIO_printf(bio_s_out, "ACCEPT\n");
2028 (void)BIO_flush(bio_s_out);
2030 server_cb = rev_body;
2032 server_cb = www_body;
2034 server_cb = sv_body;
2036 if (socket_family == AF_UNIX
2037 && unlink_unix_path)
2040 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2041 server_cb, context, naccept);
2042 print_stats(bio_s_out, ctx);
2046 set_keylog_file(NULL, NULL);
2048 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2050 EVP_PKEY_free(s_key);
2051 EVP_PKEY_free(s_dkey);
2052 sk_X509_pop_free(s_chain, X509_free);
2053 sk_X509_pop_free(s_dchain, X509_free);
2055 OPENSSL_free(dpass);
2058 X509_VERIFY_PARAM_free(vpm);
2060 OPENSSL_free(tlscstatp.host);
2061 OPENSSL_free(tlscstatp.port);
2062 OPENSSL_free(tlscstatp.path);
2065 EVP_PKEY_free(s_key2);
2066 #ifndef OPENSSL_NO_NEXTPROTONEG
2067 OPENSSL_free(next_proto.data);
2069 OPENSSL_free(alpn_ctx.data);
2070 ssl_excert_free(exc);
2071 sk_OPENSSL_STRING_free(ssl_args);
2072 SSL_CONF_CTX_free(cctx);
2073 release_engine(engine);
2074 BIO_free(bio_s_out);
2076 BIO_free(bio_s_msg);
2078 #ifdef CHARSET_EBCDIC
2079 BIO_meth_free(methods_ebcdic);
2084 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2086 BIO_printf(bio, "%4ld items in the session cache\n",
2087 SSL_CTX_sess_number(ssl_ctx));
2088 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2089 SSL_CTX_sess_connect(ssl_ctx));
2090 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2091 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2092 BIO_printf(bio, "%4ld client connects that finished\n",
2093 SSL_CTX_sess_connect_good(ssl_ctx));
2094 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2095 SSL_CTX_sess_accept(ssl_ctx));
2096 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2097 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2098 BIO_printf(bio, "%4ld server accepts that finished\n",
2099 SSL_CTX_sess_accept_good(ssl_ctx));
2100 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2101 BIO_printf(bio, "%4ld session cache misses\n",
2102 SSL_CTX_sess_misses(ssl_ctx));
2103 BIO_printf(bio, "%4ld session cache timeouts\n",
2104 SSL_CTX_sess_timeouts(ssl_ctx));
2105 BIO_printf(bio, "%4ld callback cache hits\n",
2106 SSL_CTX_sess_cb_hits(ssl_ctx));
2107 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2108 SSL_CTX_sess_cache_full(ssl_ctx),
2109 SSL_CTX_sess_get_cache_size(ssl_ctx));
2112 static int sv_body(int s, int stype, int prot, unsigned char *context)
2121 struct timeval timeout;
2122 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2125 struct timeval *timeoutp;
2127 #ifndef OPENSSL_NO_DTLS
2128 # ifndef OPENSSL_NO_SCTP
2129 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2131 int isdtls = (stype == SOCK_DGRAM);
2135 buf = app_malloc(bufsize, "server buffer");
2137 if (!BIO_socket_nbio(s, 1))
2138 ERR_print_errors(bio_err);
2140 BIO_printf(bio_err, "Turned on non blocking io\n");
2146 if (s_tlsextdebug) {
2147 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2148 SSL_set_tlsext_debug_arg(con, bio_s_out);
2152 && !SSL_set_session_id_context(con,
2153 context, strlen((char *)context))) {
2154 BIO_printf(bio_err, "Error setting session id context\n");
2159 if (!SSL_clear(con)) {
2160 BIO_printf(bio_err, "Error clearing SSL connection\n");
2164 #ifndef OPENSSL_NO_DTLS
2166 # ifndef OPENSSL_NO_SCTP
2167 if (prot == IPPROTO_SCTP)
2168 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2171 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2173 if (enable_timeouts) {
2175 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2176 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2179 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2180 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2184 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2185 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2186 DTLS_get_link_min_mtu(con));
2191 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2192 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2193 BIO_printf(bio_err, "Failed to set MTU\n");
2199 /* want to do MTU discovery */
2200 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2202 # ifndef OPENSSL_NO_SCTP
2203 if (prot != IPPROTO_SCTP) {
2204 /* Turn on cookie exchange. Not necessary for SCTP */
2205 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2210 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2213 BIO_printf(bio_err, "Unable to create BIO\n");
2214 ERR_print_errors(bio_err);
2221 test = BIO_new(BIO_f_nbio_test());
2222 sbio = BIO_push(test, sbio);
2225 SSL_set_bio(con, sbio, sbio);
2226 SSL_set_accept_state(con);
2227 /* SSL_set_fd(con,s); */
2230 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2231 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2234 #ifndef OPENSSL_NO_SSL_TRACE
2236 SSL_set_msg_callback(con, SSL_trace);
2239 SSL_set_msg_callback(con, msg_cb);
2240 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2243 if (s_tlsextdebug) {
2244 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2245 SSL_set_tlsext_debug_arg(con, bio_s_out);
2249 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2252 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2254 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2255 if (edret != SSL_READ_EARLY_DATA_ERROR)
2258 switch (SSL_get_error(con, 0)) {
2259 case SSL_ERROR_WANT_WRITE:
2260 case SSL_ERROR_WANT_ASYNC:
2261 case SSL_ERROR_WANT_READ:
2262 /* Just keep trying - busy waiting */
2265 BIO_printf(bio_err, "Error reading early data\n");
2266 ERR_print_errors(bio_err);
2270 if (readbytes > 0) {
2272 BIO_printf(bio_s_out, "Early data received:\n");
2275 raw_write_stdout(buf, (unsigned int)readbytes);
2276 (void)BIO_flush(bio_s_out);
2280 BIO_printf(bio_s_out, "No early data received\n");
2282 BIO_printf(bio_s_out, "\nEnd of early data\n");
2283 if (SSL_is_init_finished(con))
2284 print_connection_info(con);
2287 if (fileno_stdin() > s)
2288 width = fileno_stdin() + 1;
2292 int read_from_terminal;
2293 int read_from_sslcon;
2295 read_from_terminal = 0;
2296 read_from_sslcon = SSL_has_pending(con)
2297 || (async && SSL_waiting_for_async(con));
2299 if (!read_from_sslcon) {
2301 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2302 openssl_fdset(fileno_stdin(), &readfds);
2304 openssl_fdset(s, &readfds);
2306 * Note: under VMS with SOCKETSHR the second parameter is
2307 * currently of type (int *) whereas under other systems it is
2308 * (void *) if you don't have a cast it will choke the compiler:
2309 * if you do have a cast then you can either go for (int *) or
2312 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2314 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2315 * only on sockets. As a workaround we timeout the select every
2316 * second and check for any keypress. In a proper Windows
2317 * application we wouldn't do this because it is inefficient.
2321 i = select(width, (void *)&readfds, NULL, NULL, &tv);
2322 if (has_stdin_waiting())
2323 read_from_terminal = 1;
2324 if ((i < 0) || (!i && !read_from_terminal))
2327 if ((SSL_version(con) == DTLS1_VERSION) &&
2328 DTLSv1_get_timeout(con, &timeout))
2329 timeoutp = &timeout;
2333 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2335 if ((SSL_version(con) == DTLS1_VERSION)
2336 && DTLSv1_handle_timeout(con) > 0) {
2337 BIO_printf(bio_err, "TIMEOUT occurred\n");
2342 if (FD_ISSET(fileno_stdin(), &readfds))
2343 read_from_terminal = 1;
2345 if (FD_ISSET(s, &readfds))
2346 read_from_sslcon = 1;
2348 if (read_from_terminal) {
2352 i = raw_read_stdin(buf, bufsize / 2);
2354 /* both loops are skipped when i <= 0 */
2355 for (j = 0; j < i; j++)
2358 for (j = i - 1; j >= 0; j--) {
2359 buf[j + lf_num] = buf[j];
2360 if (buf[j] == '\n') {
2363 buf[j + lf_num] = '\r';
2366 assert(lf_num == 0);
2368 i = raw_read_stdin(buf, bufsize);
2370 if (!s_quiet && !s_brief) {
2371 if ((i <= 0) || (buf[0] == 'Q')) {
2372 BIO_printf(bio_s_out, "DONE\n");
2373 (void)BIO_flush(bio_s_out);
2375 close_accept_socket();
2379 if ((i <= 0) || (buf[0] == 'q')) {
2380 BIO_printf(bio_s_out, "DONE\n");
2381 (void)BIO_flush(bio_s_out);
2382 if (SSL_version(con) != DTLS1_VERSION)
2385 * close_accept_socket(); ret= -11;
2389 #ifndef OPENSSL_NO_HEARTBEATS
2390 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2391 BIO_printf(bio_err, "HEARTBEATING\n");
2397 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2398 SSL_renegotiate(con);
2399 i = SSL_do_handshake(con);
2400 printf("SSL_do_handshake -> %d\n", i);
2404 * strcpy(buf,"server side RE-NEGOTIATE\n");
2407 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2409 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
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 asking for client
2421 if ((buf[0] == 'K' || buf[0] == 'k')
2422 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2423 SSL_key_update(con, buf[0] == 'K' ?
2424 SSL_KEY_UPDATE_REQUESTED
2425 : SSL_KEY_UPDATE_NOT_REQUESTED);
2426 i = SSL_do_handshake(con);
2427 printf("SSL_do_handshake -> %d\n", i);
2431 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2435 if (buf[0] == 'P') {
2436 static const char *str = "Lets print some clear text\n";
2437 BIO_write(SSL_get_wbio(con), str, strlen(str));
2439 if (buf[0] == 'S') {
2440 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2443 #ifdef CHARSET_EBCDIC
2444 ebcdic2ascii(buf, buf, i);
2448 /* should do a select for the write */
2451 if (++count == 100) {
2453 SSL_renegotiate(con);
2456 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2457 #ifndef OPENSSL_NO_SRP
2458 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2459 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2460 SRP_user_pwd_free(srp_callback_parm.user);
2461 srp_callback_parm.user =
2462 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2463 srp_callback_parm.login);
2464 if (srp_callback_parm.user)
2465 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2466 srp_callback_parm.user->info);
2468 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2469 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2472 switch (SSL_get_error(con, k)) {
2473 case SSL_ERROR_NONE:
2475 case SSL_ERROR_WANT_ASYNC:
2476 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2477 (void)BIO_flush(bio_s_out);
2478 wait_for_async(con);
2480 case SSL_ERROR_WANT_WRITE:
2481 case SSL_ERROR_WANT_READ:
2482 case SSL_ERROR_WANT_X509_LOOKUP:
2483 BIO_printf(bio_s_out, "Write BLOCK\n");
2484 (void)BIO_flush(bio_s_out);
2486 case SSL_ERROR_WANT_ASYNC_JOB:
2488 * This shouldn't ever happen in s_server. Treat as an error
2490 case SSL_ERROR_SYSCALL:
2492 BIO_printf(bio_s_out, "ERROR\n");
2493 (void)BIO_flush(bio_s_out);
2494 ERR_print_errors(bio_err);
2498 case SSL_ERROR_ZERO_RETURN:
2499 BIO_printf(bio_s_out, "DONE\n");
2500 (void)BIO_flush(bio_s_out);
2512 if (read_from_sslcon) {
2514 * init_ssl_connection handles all async events itself so if we're
2515 * waiting for async then we shouldn't go back into
2516 * init_ssl_connection
2518 if ((!async || !SSL_waiting_for_async(con))
2519 && !SSL_is_init_finished(con)) {
2520 i = init_ssl_connection(con);
2525 } else if (i == 0) {
2531 i = SSL_read(con, (char *)buf, bufsize);
2532 #ifndef OPENSSL_NO_SRP
2533 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2534 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2535 SRP_user_pwd_free(srp_callback_parm.user);
2536 srp_callback_parm.user =
2537 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2538 srp_callback_parm.login);
2539 if (srp_callback_parm.user)
2540 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2541 srp_callback_parm.user->info);
2543 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2544 i = SSL_read(con, (char *)buf, bufsize);
2547 switch (SSL_get_error(con, i)) {
2548 case SSL_ERROR_NONE:
2549 #ifdef CHARSET_EBCDIC
2550 ascii2ebcdic(buf, buf, i);
2552 raw_write_stdout(buf, (unsigned int)i);
2553 (void)BIO_flush(bio_s_out);
2554 if (SSL_has_pending(con))
2557 case SSL_ERROR_WANT_ASYNC:
2558 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2559 (void)BIO_flush(bio_s_out);
2560 wait_for_async(con);
2562 case SSL_ERROR_WANT_WRITE:
2563 case SSL_ERROR_WANT_READ:
2564 BIO_printf(bio_s_out, "Read BLOCK\n");
2565 (void)BIO_flush(bio_s_out);
2567 case SSL_ERROR_WANT_ASYNC_JOB:
2569 * This shouldn't ever happen in s_server. Treat as an error
2571 case SSL_ERROR_SYSCALL:
2573 BIO_printf(bio_s_out, "ERROR\n");
2574 (void)BIO_flush(bio_s_out);
2575 ERR_print_errors(bio_err);
2578 case SSL_ERROR_ZERO_RETURN:
2579 BIO_printf(bio_s_out, "DONE\n");
2580 (void)BIO_flush(bio_s_out);
2589 BIO_printf(bio_s_out, "shutting down SSL\n");
2590 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2593 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2594 OPENSSL_clear_free(buf, bufsize);
2596 BIO_printf(bio_s_out, "ACCEPT\n");
2597 (void)BIO_flush(bio_s_out);
2601 static void close_accept_socket(void)
2603 BIO_printf(bio_err, "shutdown accept socket\n");
2604 if (accept_socket >= 0) {
2605 BIO_closesocket(accept_socket);
2609 static int init_ssl_connection(SSL *con)
2615 #ifndef OPENSSL_NO_DTLS
2617 BIO_ADDR *client = NULL;
2619 if ((client = BIO_ADDR_new()) == NULL) {
2620 BIO_printf(bio_err, "ERROR - memory\n");
2623 i = DTLSv1_listen(con, client);
2628 wbio = SSL_get_wbio(con);
2630 BIO_get_fd(wbio, &fd);
2633 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2634 BIO_printf(bio_err, "ERROR - unable to connect\n");
2635 BIO_ADDR_free(client);
2638 BIO_ADDR_free(client);
2640 i = SSL_accept(con);
2642 BIO_ADDR_free(client);
2648 i = SSL_accept(con);
2651 retry = !SSL_want_nothing(con);
2652 #ifdef CERT_CB_TEST_RETRY
2655 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2656 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2658 "LOOKUP from certificate callback during accept\n");
2659 i = SSL_accept(con);
2661 retry = !SSL_want_nothing(con);
2666 #ifndef OPENSSL_NO_SRP
2668 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2669 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2670 srp_callback_parm.login);
2671 SRP_user_pwd_free(srp_callback_parm.user);
2672 srp_callback_parm.user =
2673 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2674 srp_callback_parm.login);
2675 if (srp_callback_parm.user)
2676 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2677 srp_callback_parm.user->info);
2679 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2680 i = SSL_accept(con);
2682 retry = !SSL_want_nothing(con);
2685 } while (i < 0 && SSL_waiting_for_async(con));
2688 if ((dtlslisten && i == 0)
2689 || (!dtlslisten && retry)) {
2690 BIO_printf(bio_s_out, "DELAY\n");
2694 BIO_printf(bio_err, "ERROR\n");
2696 verify_err = SSL_get_verify_result(con);
2697 if (verify_err != X509_V_OK) {
2698 BIO_printf(bio_err, "verify error:%s\n",
2699 X509_verify_cert_error_string(verify_err));
2701 /* Always print any error messages */
2702 ERR_print_errors(bio_err);
2706 print_connection_info(con);
2710 static void print_connection_info(SSL *con)
2715 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2716 const unsigned char *next_proto_neg;
2717 unsigned next_proto_neg_len;
2719 unsigned char *exportedkeymat;
2723 print_ssl_summary(con);
2725 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2727 peer = SSL_get_peer_certificate(con);
2729 BIO_printf(bio_s_out, "Client certificate\n");
2730 PEM_write_bio_X509(bio_s_out, peer);
2731 X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
2732 BIO_printf(bio_s_out, "subject=%s\n", buf);
2733 X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
2734 BIO_printf(bio_s_out, "issuer=%s\n", buf);
2739 if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2740 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2741 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2742 ssl_print_sigalgs(bio_s_out, con);
2743 #ifndef OPENSSL_NO_EC
2744 ssl_print_point_formats(bio_s_out, con);
2745 ssl_print_groups(bio_s_out, con, 0);
2747 print_ca_names(bio_s_out, con);
2748 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2750 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2751 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2752 if (next_proto_neg) {
2753 BIO_printf(bio_s_out, "NEXTPROTO is ");
2754 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2755 BIO_printf(bio_s_out, "\n");
2758 #ifndef OPENSSL_NO_SRTP
2760 SRTP_PROTECTION_PROFILE *srtp_profile
2761 = SSL_get_selected_srtp_profile(con);
2764 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2765 srtp_profile->name);
2768 if (SSL_session_reused(con))
2769 BIO_printf(bio_s_out, "Reused session-id\n");
2770 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2771 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2772 if (keymatexportlabel != NULL) {
2773 BIO_printf(bio_s_out, "Keying material exporter:\n");
2774 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2775 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2776 exportedkeymat = app_malloc(keymatexportlen, "export key");
2777 if (!SSL_export_keying_material(con, exportedkeymat,
2780 strlen(keymatexportlabel),
2782 BIO_printf(bio_s_out, " Error\n");
2784 BIO_printf(bio_s_out, " Keying material: ");
2785 for (i = 0; i < keymatexportlen; i++)
2786 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2787 BIO_printf(bio_s_out, "\n");
2789 OPENSSL_free(exportedkeymat);
2792 (void)BIO_flush(bio_s_out);
2795 #ifndef OPENSSL_NO_DH
2796 static DH *load_dh_param(const char *dhfile)
2801 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2803 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2810 static int www_body(int s, int stype, int prot, unsigned char *context)
2816 const SSL_CIPHER *c;
2817 BIO *io, *ssl_bio, *sbio;
2819 int total_bytes = 0;
2824 /* Set width for a select call if needed */
2827 buf = app_malloc(bufsize, "server www buffer");
2828 io = BIO_new(BIO_f_buffer());
2829 ssl_bio = BIO_new(BIO_f_ssl());
2830 if ((io == NULL) || (ssl_bio == NULL))
2834 if (!BIO_socket_nbio(s, 1))
2835 ERR_print_errors(bio_err);
2837 BIO_printf(bio_err, "Turned on non blocking io\n");
2840 /* lets make the output buffer a reasonable size */
2841 if (!BIO_set_write_buffer_size(io, bufsize))
2844 if ((con = SSL_new(ctx)) == NULL)
2847 if (s_tlsextdebug) {
2848 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2849 SSL_set_tlsext_debug_arg(con, bio_s_out);
2853 && !SSL_set_session_id_context(con, context,
2854 strlen((char *)context)))
2857 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2861 test = BIO_new(BIO_f_nbio_test());
2862 sbio = BIO_push(test, sbio);
2864 SSL_set_bio(con, sbio, sbio);
2865 SSL_set_accept_state(con);
2867 /* SSL_set_fd(con,s); */
2868 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2869 BIO_push(io, ssl_bio);
2870 #ifdef CHARSET_EBCDIC
2871 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2875 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2876 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2879 #ifndef OPENSSL_NO_SSL_TRACE
2881 SSL_set_msg_callback(con, SSL_trace);
2884 SSL_set_msg_callback(con, msg_cb);
2885 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2889 i = BIO_gets(io, buf, bufsize - 1);
2890 if (i < 0) { /* error */
2891 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2893 ERR_print_errors(bio_err);
2896 BIO_printf(bio_s_out, "read R BLOCK\n");
2897 #ifndef OPENSSL_NO_SRP
2898 if (BIO_should_io_special(io)
2899 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2900 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2901 SRP_user_pwd_free(srp_callback_parm.user);
2902 srp_callback_parm.user =
2903 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2904 srp_callback_parm.login);
2905 if (srp_callback_parm.user)
2906 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2907 srp_callback_parm.user->info);
2909 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2913 #if !defined(OPENSSL_SYS_MSDOS)
2918 } else if (i == 0) { /* end of input */
2923 /* else we have data */
2924 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2925 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2928 STACK_OF(SSL_CIPHER) *sk;
2929 static const char *space = " ";
2931 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2932 if (strncmp("GET /renegcert", buf, 14) == 0)
2934 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2936 i = SSL_renegotiate(con);
2937 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2938 /* Send the HelloRequest */
2939 i = SSL_do_handshake(con);
2941 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2942 SSL_get_error(con, i));
2943 ERR_print_errors(bio_err);
2946 /* Wait for a ClientHello to come back */
2948 openssl_fdset(s, &readfds);
2949 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2950 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2951 BIO_printf(bio_s_out,
2952 "Error waiting for client response\n");
2953 ERR_print_errors(bio_err);
2957 * We're not actually expecting any data here and we ignore
2958 * any that is sent. This is just to force the handshake that
2959 * we're expecting to come from the client. If they haven't
2960 * sent one there's not much we can do.
2962 BIO_gets(io, buf, bufsize - 1);
2966 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2967 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2968 BIO_puts(io, "<pre>\n");
2969 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2971 for (i = 0; i < local_argc; i++) {
2973 for (myp = local_argv[i]; *myp; myp++)
2976 BIO_puts(io, "<");
2979 BIO_puts(io, ">");
2982 BIO_puts(io, "&");
2985 BIO_write(io, myp, 1);
2988 BIO_write(io, " ", 1);
2993 "Secure Renegotiation IS%s supported\n",
2994 SSL_get_secure_renegotiation_support(con) ?
2998 * The following is evil and should not really be done
3000 BIO_printf(io, "Ciphers supported in s_server binary\n");
3001 sk = SSL_get_ciphers(con);
3002 j = sk_SSL_CIPHER_num(sk);
3003 for (i = 0; i < j; i++) {
3004 c = sk_SSL_CIPHER_value(sk, i);
3005 BIO_printf(io, "%-11s:%-25s ",
3006 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3007 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3011 p = SSL_get_shared_ciphers(con, buf, bufsize);
3014 "---\nCiphers common between both SSL end points:\n");
3018 BIO_write(io, space, 26 - j);
3021 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3023 BIO_write(io, p, 1);
3030 ssl_print_sigalgs(io, con);
3031 #ifndef OPENSSL_NO_EC
3032 ssl_print_groups(io, con, 0);
3034 print_ca_names(io, con);
3035 BIO_printf(io, (SSL_session_reused(con)
3036 ? "---\nReused, " : "---\nNew, "));
3037 c = SSL_get_current_cipher(con);
3038 BIO_printf(io, "%s, Cipher is %s\n",
3039 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3040 SSL_SESSION_print(io, SSL_get_session(con));
3041 BIO_printf(io, "---\n");
3042 print_stats(io, SSL_get_SSL_CTX(con));
3043 BIO_printf(io, "---\n");
3044 peer = SSL_get_peer_certificate(con);
3046 BIO_printf(io, "Client certificate\n");
3047 X509_print(io, peer);
3048 PEM_write_bio_X509(io, peer);
3052 BIO_puts(io, "no client certificate available\n");
3053 BIO_puts(io, "</BODY></HTML>\r\n\r\n");
3055 } else if ((www == 2 || www == 3)
3056 && (strncmp("GET /", buf, 5) == 0)) {
3059 static const char *text =
3060 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3066 for (e = p; *e != '\0'; e++) {
3072 dot = (e[0] == '.') ? 2 : 0;
3075 dot = (e[0] == '.') ? 3 : 0;
3078 dot = (e[0] == '/') ? -1 : 0;
3082 dot = (e[0] == '/') ? 1 : 0;
3084 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3089 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3096 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
3102 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3106 /* if a directory, do the index thang */
3107 if (app_isdir(p) > 0) {
3109 BIO_printf(io, "'%s' is a directory\r\n", p);
3113 if ((file = BIO_new_file(p, "r")) == NULL) {
3115 BIO_printf(io, "Error opening '%s'\r\n", p);
3116 ERR_print_errors(io);
3121 BIO_printf(bio_err, "FILE:%s\n", p);
3125 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3126 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3127 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3129 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3132 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3136 i = BIO_read(file, buf, bufsize);
3142 BIO_printf(bio_err, "%d\n", i);
3143 if (total_bytes > 3 * 1024) {
3145 BIO_printf(bio_err, "RENEGOTIATE\n");
3146 SSL_renegotiate(con);
3150 for (j = 0; j < i;) {
3153 if (++count == 13) {
3154 SSL_renegotiate(con);
3157 k = BIO_write(io, &(buf[j]), i - j);
3159 if (!BIO_should_retry(io)
3160 && !SSL_waiting_for_async(con))
3163 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3177 i = (int)BIO_flush(io);
3179 if (!BIO_should_retry(io))
3185 /* make sure we re-use sessions */
3186 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3190 BIO_printf(bio_s_out, "ACCEPT\n");
3196 static int rev_body(int s, int stype, int prot, unsigned char *context)
3202 BIO *io, *ssl_bio, *sbio;
3204 buf = app_malloc(bufsize, "server rev buffer");
3205 io = BIO_new(BIO_f_buffer());
3206 ssl_bio = BIO_new(BIO_f_ssl());
3207 if ((io == NULL) || (ssl_bio == NULL))
3210 /* lets make the output buffer a reasonable size */
3211 if (!BIO_set_write_buffer_size(io, bufsize))
3214 if ((con = SSL_new(ctx)) == NULL)
3217 if (s_tlsextdebug) {
3218 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3219 SSL_set_tlsext_debug_arg(con, bio_s_out);
3222 && !SSL_set_session_id_context(con, context,
3223 strlen((char *)context))) {
3224 ERR_print_errors(bio_err);
3228 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3229 SSL_set_bio(con, sbio, sbio);
3230 SSL_set_accept_state(con);
3232 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3233 BIO_push(io, ssl_bio);
3234 #ifdef CHARSET_EBCDIC
3235 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3239 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3240 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3243 #ifndef OPENSSL_NO_SSL_TRACE
3245 SSL_set_msg_callback(con, SSL_trace);
3248 SSL_set_msg_callback(con, msg_cb);
3249 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3253 i = BIO_do_handshake(io);
3256 if (!BIO_should_retry(io)) {
3257 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3258 ERR_print_errors(bio_err);
3261 #ifndef OPENSSL_NO_SRP
3262 if (BIO_should_io_special(io)
3263 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3264 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3265 SRP_user_pwd_free(srp_callback_parm.user);
3266 srp_callback_parm.user =
3267 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3268 srp_callback_parm.login);
3269 if (srp_callback_parm.user)
3270 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3271 srp_callback_parm.user->info);
3273 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3278 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3279 print_ssl_summary(con);
3282 i = BIO_gets(io, buf, bufsize - 1);
3283 if (i < 0) { /* error */
3284 if (!BIO_should_retry(io)) {
3286 ERR_print_errors(bio_err);
3289 BIO_printf(bio_s_out, "read R BLOCK\n");
3290 #ifndef OPENSSL_NO_SRP
3291 if (BIO_should_io_special(io)
3292 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3293 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3294 SRP_user_pwd_free(srp_callback_parm.user);
3295 srp_callback_parm.user =
3296 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3297 srp_callback_parm.login);
3298 if (srp_callback_parm.user)
3299 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3300 srp_callback_parm.user->info);
3302 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3306 #if !defined(OPENSSL_SYS_MSDOS)
3311 } else if (i == 0) { /* end of input */
3313 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3316 char *p = buf + i - 1;
3317 while (i && (*p == '\n' || *p == '\r')) {
3321 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3323 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3326 BUF_reverse((unsigned char *)buf, NULL, i);
3328 BIO_write(io, buf, i + 1);
3333 if (!BIO_should_retry(io))
3339 /* make sure we re-use sessions */
3340 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3349 #define MAX_SESSION_ID_ATTEMPTS 10
3350 static int generate_session_id(const SSL *ssl, unsigned char *id,
3351 unsigned int *id_len)
3353 unsigned int count = 0;
3355 if (RAND_bytes(id, *id_len) <= 0)
3358 * Prefix the session_id with the required prefix. NB: If our prefix
3359 * is too long, clip it - but there will be worse effects anyway, eg.
3360 * the server could only possibly create 1 session ID (ie. the
3361 * prefix!) so all future session negotiations will fail due to
3364 memcpy(id, session_id_prefix,
3365 (strlen(session_id_prefix) < *id_len) ?
3366 strlen(session_id_prefix) : *id_len);
3368 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3369 (++count < MAX_SESSION_ID_ATTEMPTS));
3370 if (count >= MAX_SESSION_ID_ATTEMPTS)
3376 * By default s_server uses an in-memory cache which caches SSL_SESSION
3377 * structures without any serialisation. This hides some bugs which only
3378 * become apparent in deployed servers. By implementing a basic external
3379 * session cache some issues can be debugged using s_server.
3382 typedef struct simple_ssl_session_st {
3387 struct simple_ssl_session_st *next;
3388 } simple_ssl_session;
3390 static simple_ssl_session *first = NULL;
3392 static int add_session(SSL *ssl, SSL_SESSION *session)
3394 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3397 SSL_SESSION_get_id(session, &sess->idlen);
3398 sess->derlen = i2d_SSL_SESSION(session, NULL);
3399 if (sess->derlen < 0) {
3400 BIO_printf(bio_err, "Error encoding session\n");
3405 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3406 sess->der = app_malloc(sess->derlen, "get session buffer");
3408 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3409 OPENSSL_free(sess->id);
3410 OPENSSL_free(sess->der);
3416 /* Assume it still works. */
3417 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3418 BIO_printf(bio_err, "Unexpected session encoding length\n");
3419 OPENSSL_free(sess->id);
3420 OPENSSL_free(sess->der);
3427 BIO_printf(bio_err, "New session added to external cache\n");
3431 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3434 simple_ssl_session *sess;
3436 for (sess = first; sess; sess = sess->next) {
3437 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3438 const unsigned char *p = sess->der;
3439 BIO_printf(bio_err, "Lookup session: cache hit\n");
3440 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3443 BIO_printf(bio_err, "Lookup session: cache miss\n");
3447 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3449 simple_ssl_session *sess, *prev = NULL;
3450 const unsigned char *id;
3452 id = SSL_SESSION_get_id(session, &idlen);
3453 for (sess = first; sess; sess = sess->next) {
3454 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3456 prev->next = sess->next;
3459 OPENSSL_free(sess->id);
3460 OPENSSL_free(sess->der);
3468 static void init_session_cache_ctx(SSL_CTX *sctx)
3470 SSL_CTX_set_session_cache_mode(sctx,
3471 SSL_SESS_CACHE_NO_INTERNAL |
3472 SSL_SESS_CACHE_SERVER);
3473 SSL_CTX_sess_set_new_cb(sctx, add_session);
3474 SSL_CTX_sess_set_get_cb(sctx, get_session);
3475 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3478 static void free_sessions(void)
3480 simple_ssl_session *sess, *tsess;
3481 for (sess = first; sess;) {
3482 OPENSSL_free(sess->id);
3483 OPENSSL_free(sess->der);
3486 OPENSSL_free(tsess);
3491 #endif /* OPENSSL_NO_SOCK */