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, unsigned char *context);
95 static int www_body(int s, int stype, unsigned char *context);
96 static int rev_body(int s, int stype, 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);
108 /* static int load_CA(SSL_CTX *ctx, char *file);*/
110 static const int bufsize = 16 * 1024;
111 static int accept_socket = -1;
113 #define TEST_CERT "server.pem"
114 #define TEST_CERT2 "server2.pem"
116 static int s_nbio = 0;
117 static int s_nbio_test = 0;
118 static int s_crlf = 0;
119 static SSL_CTX *ctx = NULL;
120 static SSL_CTX *ctx2 = NULL;
123 static BIO *bio_s_out = NULL;
124 static BIO *bio_s_msg = NULL;
125 static int s_debug = 0;
126 static int s_tlsextdebug = 0;
127 static int s_msg = 0;
128 static int s_quiet = 0;
129 static int s_ign_eof = 0;
130 static int s_brief = 0;
132 static char *keymatexportlabel = NULL;
133 static int keymatexportlen = 20;
135 static int async = 0;
137 static const char *session_id_prefix = NULL;
139 #ifndef OPENSSL_NO_DTLS
140 static int enable_timeouts = 0;
141 static long socket_mtu;
144 static int dtlslisten = 0;
146 #ifndef OPENSSL_NO_PSK
147 static char *psk_identity = "Client_identity";
148 char *psk_key = NULL; /* by default PSK is not used */
150 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
152 unsigned int max_psk_len)
158 BIO_printf(bio_s_out, "psk_server_cb\n");
160 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
164 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
165 (int)strlen(identity), identity);
167 /* here we could lookup the given identity e.g. from a database */
168 if (strcmp(identity, psk_identity) != 0) {
169 BIO_printf(bio_s_out, "PSK error: client identity not found"
170 " (got '%s' expected '%s')\n", identity, psk_identity);
174 BIO_printf(bio_s_out, "PSK client identity found\n");
176 /* convert the PSK key to binary */
177 key = OPENSSL_hexstr2buf(psk_key, &key_len);
179 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
183 if (key_len > (int)max_psk_len) {
185 "psk buffer of callback is too small (%d) for key (%ld)\n",
186 max_psk_len, key_len);
191 memcpy(psk, key, key_len);
195 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
199 BIO_printf(bio_err, "Error in PSK server callback\n");
200 (void)BIO_flush(bio_err);
201 (void)BIO_flush(bio_s_out);
206 #ifndef OPENSSL_NO_SRP
207 /* This is a context that we pass to callbacks */
208 typedef struct srpsrvparm_st {
215 * This callback pretends to require some asynchronous logic in order to
216 * obtain a verifier. When the callback is called for a new connection we
217 * return with a negative value. This will provoke the accept etc to return
218 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
219 * (which would normally occur after a worker has finished) and we set the
222 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
224 srpsrvparm *p = (srpsrvparm *) arg;
225 int ret = SSL3_AL_FATAL;
227 if (p->login == NULL && p->user == NULL) {
228 p->login = SSL_get_srp_username(s);
229 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
233 if (p->user == NULL) {
234 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
238 if (SSL_set_srp_server_param
239 (s, p->user->N, p->user->g, p->user->s, p->user->v,
240 p->user->info) < 0) {
241 *ad = SSL_AD_INTERNAL_ERROR;
245 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
246 p->login, p->user->info);
247 ret = SSL_ERROR_NONE;
250 SRP_user_pwd_free(p->user);
258 static int local_argc = 0;
259 static char **local_argv;
261 #ifdef CHARSET_EBCDIC
262 static int ebcdic_new(BIO *bi);
263 static int ebcdic_free(BIO *a);
264 static int ebcdic_read(BIO *b, char *out, int outl);
265 static int ebcdic_write(BIO *b, const char *in, int inl);
266 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
267 static int ebcdic_gets(BIO *bp, char *buf, int size);
268 static int ebcdic_puts(BIO *bp, const char *str);
270 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
271 static BIO_METHOD *methods_ebcdic = NULL;
273 /* This struct is "unwarranted chumminess with the compiler." */
279 static const BIO_METHOD *BIO_f_ebcdic_filter()
281 if (methods_ebcdic == NULL) {
282 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
283 "EBCDIC/ASCII filter");
284 if (methods_ebcdic == NULL
285 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
286 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
287 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
288 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
289 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
290 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
291 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
294 return methods_ebcdic;
297 static int ebcdic_new(BIO *bi)
299 EBCDIC_OUTBUFF *wbuf;
301 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
302 wbuf->alloced = 1024;
303 wbuf->buff[0] = '\0';
305 BIO_set_data(bi, wbuf);
310 static int ebcdic_free(BIO *a)
312 EBCDIC_OUTBUFF *wbuf;
316 wbuf = BIO_get_data(a);
318 BIO_set_data(a, NULL);
324 static int ebcdic_read(BIO *b, char *out, int outl)
327 BIO *next = BIO_next(b);
329 if (out == NULL || outl == 0)
334 ret = BIO_read(next, out, outl);
336 ascii2ebcdic(out, out, ret);
340 static int ebcdic_write(BIO *b, const char *in, int inl)
342 EBCDIC_OUTBUFF *wbuf;
343 BIO *next = BIO_next(b);
347 if ((in == NULL) || (inl <= 0))
352 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
354 if (inl > (num = wbuf->alloced)) {
355 num = num + num; /* double the size */
359 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
362 wbuf->buff[0] = '\0';
364 BIO_set_data(b, wbuf);
367 ebcdic2ascii(wbuf->buff, in, inl);
369 ret = BIO_write(next, wbuf->buff, inl);
374 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
377 BIO *next = BIO_next(b);
386 ret = BIO_ctrl(next, cmd, num, ptr);
392 static int ebcdic_gets(BIO *bp, char *buf, int size)
395 BIO *next = BIO_next(bp);
399 /* return(BIO_gets(bp->next_bio,buf,size));*/
400 for (i = 0; i < size - 1; ++i) {
401 ret = ebcdic_read(bp, &buf[i], 1);
404 else if (buf[i] == '\n') {
411 return (ret < 0 && i == 0) ? ret : i;
414 static int ebcdic_puts(BIO *bp, const char *str)
416 if (BIO_next(bp) == NULL)
418 return ebcdic_write(bp, str, strlen(str));
422 /* This is a context that we pass to callbacks */
423 typedef struct tlsextctx_st {
429 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
431 tlsextctx *p = (tlsextctx *) arg;
432 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
433 if (servername && p->biodebug)
434 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
438 return SSL_TLSEXT_ERR_NOACK;
441 if (strcasecmp(servername, p->servername))
442 return p->extension_error;
444 BIO_printf(p->biodebug, "Switching server context.\n");
445 SSL_set_SSL_CTX(s, ctx2);
448 return SSL_TLSEXT_ERR_OK;
451 /* 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));
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;
560 X509_email_free(aia);
562 OCSP_CERTID_free(id);
563 OCSP_REQUEST_free(req);
564 X509_STORE_CTX_free(inctx);
569 * Certificate Status callback. This is called when a client includes a
570 * certificate status request extension. The response is either obtained from a
571 * file, or from an OCSP responder.
573 static int cert_status_cb(SSL *s, void *arg)
575 tlsextstatusctx *srctx = arg;
576 OCSP_RESPONSE *resp = NULL;
577 unsigned char *rspder = NULL;
579 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
582 BIO_puts(bio_err, "cert_status: callback called\n");
584 if (srctx->respin != NULL) {
585 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
586 if (derbio == NULL) {
587 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
590 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
593 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
597 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
598 if (ret != SSL_TLSEXT_ERR_OK)
602 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
606 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
607 if (srctx->verbose) {
608 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
609 OCSP_RESPONSE_print(bio_err, resp, 2);
612 ret = SSL_TLSEXT_ERR_OK;
615 if (ret != SSL_TLSEXT_ERR_OK)
616 ERR_print_errors(bio_err);
618 OCSP_RESPONSE_free(resp);
624 #ifndef OPENSSL_NO_NEXTPROTONEG
625 /* This is the context that we pass to next_proto_cb */
626 typedef struct tlsextnextprotoctx_st {
629 } tlsextnextprotoctx;
631 static int next_proto_cb(SSL *s, const unsigned char **data,
632 unsigned int *len, void *arg)
634 tlsextnextprotoctx *next_proto = arg;
636 *data = next_proto->data;
637 *len = next_proto->len;
639 return SSL_TLSEXT_ERR_OK;
641 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
643 /* This the context that we pass to alpn_cb */
644 typedef struct tlsextalpnctx_st {
649 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
650 const unsigned char *in, unsigned int inlen, void *arg)
652 tlsextalpnctx *alpn_ctx = arg;
655 /* We can assume that |in| is syntactically valid. */
657 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
658 for (i = 0; i < inlen;) {
660 BIO_write(bio_s_out, ", ", 2);
661 BIO_write(bio_s_out, &in[i + 1], in[i]);
664 BIO_write(bio_s_out, "\n", 1);
667 if (SSL_select_next_proto
668 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
669 inlen) != OPENSSL_NPN_NEGOTIATED) {
670 return SSL_TLSEXT_ERR_NOACK;
674 BIO_printf(bio_s_out, "ALPN protocols selected: ");
675 BIO_write(bio_s_out, *out, *outlen);
676 BIO_write(bio_s_out, "\n", 1);
679 return SSL_TLSEXT_ERR_OK;
682 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
684 /* disable resumption for sessions with forward secure ciphers */
685 return is_forward_secure;
688 #ifndef OPENSSL_NO_SRP
689 static srpsrvparm srp_callback_parm;
691 #ifndef OPENSSL_NO_SRTP
692 static char *srtp_profiles = NULL;
695 typedef enum OPTION_choice {
696 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
697 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
698 OPT_VERIFY, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
699 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
700 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
701 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
702 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
703 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
704 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
705 OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
706 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
707 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
708 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
709 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
710 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
711 OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC,
712 OPT_SSL_CONFIG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
713 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
714 OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN,
715 OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
716 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN,
717 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
723 const OPTIONS s_server_options[] = {
724 {"help", OPT_HELP, '-', "Display this summary"},
725 {"port", OPT_PORT, 'p',
726 "TCP/IP port to listen on for connections (default is " PORT ")"},
727 {"accept", OPT_ACCEPT, 's',
728 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
730 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
732 {"4", OPT_4, '-', "Use IPv4 only"},
733 {"6", OPT_6, '-', "Use IPv6 only"},
735 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
737 {"context", OPT_CONTEXT, 's', "Set session ID context"},
738 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
739 {"Verify", OPT_UPPER_V_VERIFY, 'n',
740 "Turn on peer certificate verification, must have a cert"},
741 {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
742 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
743 {"serverinfo", OPT_SERVERINFO, 's',
744 "PEM serverinfo file for certificate"},
745 {"certform", OPT_CERTFORM, 'F',
746 "Certificate format (PEM or DER) PEM default"},
747 {"key", OPT_KEY, '<',
748 "Private Key if not in -cert; default is " TEST_CERT},
749 {"keyform", OPT_KEYFORM, 'f',
750 "Key format (PEM, DER or ENGINE) PEM default"},
751 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
752 {"dcert", OPT_DCERT, '<',
753 "Second certificate file to use (usually for DSA)"},
754 {"dcertform", OPT_DCERTFORM, 'F',
755 "Second certificate format (PEM or DER) PEM default"},
756 {"dkey", OPT_DKEY, '<',
757 "Second private key file to use (usually for DSA)"},
758 {"dkeyform", OPT_DKEYFORM, 'F',
759 "Second key format (PEM, DER or ENGINE) PEM default"},
760 {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
761 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
762 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
763 {"debug", OPT_DEBUG, '-', "Print more output"},
764 {"msg", OPT_MSG, '-', "Show protocol messages"},
765 {"msgfile", OPT_MSGFILE, '>',
766 "File to send output of -msg or -trace, instead of stdout"},
767 {"state", OPT_STATE, '-', "Print the SSL states"},
768 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
769 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
770 {"no-CAfile", OPT_NOCAFILE, '-',
771 "Do not load the default certificates file"},
772 {"no-CApath", OPT_NOCAPATH, '-',
773 "Do not load certificates from the default certificates directory"},
774 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
775 {"quiet", OPT_QUIET, '-', "No server output"},
776 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
777 "Disable caching and tickets if ephemeral (EC)DH is used"},
778 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
779 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
780 {"servername", OPT_SERVERNAME, 's',
781 "Servername for HostName TLS extension"},
782 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
783 "mismatch send fatal alert (default warning alert)"},
784 {"cert2", OPT_CERT2, '<',
785 "Certificate file to use for servername; default is" TEST_CERT2},
786 {"key2", OPT_KEY2, '<',
787 "-Private Key file to use for servername if not in -cert2"},
788 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
789 "Hex dump of all TLS extensions received"},
790 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
791 {"id_prefix", OPT_ID_PREFIX, 's',
792 "Generate SSL/TLS session IDs prefixed by arg"},
793 {"rand", OPT_RAND, 's',
794 "Load the file(s) into the random number generator"},
795 {"keymatexport", OPT_KEYMATEXPORT, 's',
796 "Export keying material using label"},
797 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
798 "Export len bytes of keying material (default 20)"},
799 {"CRL", OPT_CRL, '<', "CRL file to use"},
800 {"crl_download", OPT_CRL_DOWNLOAD, '-',
801 "Download CRL from distribution points"},
802 {"cert_chain", OPT_CERT_CHAIN, '<',
803 "certificate chain file in PEM format"},
804 {"dcert_chain", OPT_DCERT_CHAIN, '<',
805 "second certificate chain file in PEM format"},
806 {"chainCApath", OPT_CHAINCAPATH, '/',
807 "use dir as certificate store path to build CA certificate chain"},
808 {"verifyCApath", OPT_VERIFYCAPATH, '/',
809 "use dir as certificate store path to verify CA certificate"},
810 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
811 {"ext_cache", OPT_EXT_CACHE, '-',
812 "Disable internal cache, setup and use external cache"},
813 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
814 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
815 "Close connection on verification error"},
816 {"verify_quiet", OPT_VERIFY_QUIET, '-',
817 "No verify output except verify errors"},
818 {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
819 {"chainCAfile", OPT_CHAINCAFILE, '<',
820 "CA file for certificate chain (PEM format)"},
821 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
822 "CA file for certificate verification (PEM format)"},
823 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
824 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
825 #ifndef OPENSSL_NO_OCSP
826 {"status", OPT_STATUS, '-', "Request certificate status from server"},
827 {"status_verbose", OPT_STATUS_VERBOSE, '-',
828 "Print more output in certificate status callback"},
829 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
830 "Status request responder timeout"},
831 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
832 {"status_file", OPT_STATUS_FILE, '<',
833 "File containing DER encoded OCSP Response"},
835 #ifndef OPENSSL_NO_SSL_TRACE
836 {"trace", OPT_TRACE, '-', "trace protocol messages"},
838 {"security_debug", OPT_SECURITY_DEBUG, '-',
839 "Print output from SSL/TLS security framework"},
840 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
841 "Print more output from SSL/TLS security framework"},
842 {"brief", OPT_BRIEF, '-',
843 "Restrict output to brief summary of connection parameters"},
844 {"rev", OPT_REV, '-',
845 "act as a simple test server which just sends back with the received text reversed"},
846 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
847 {"ssl_config", OPT_SSL_CONFIG, 's',
848 "Configure SSL_CTX using the configuration 'val'"},
849 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'n',
850 "Size used to split data for encrypt pipelines"},
851 {"max_pipelines", OPT_MAX_PIPELINES, 'n',
852 "Maximum number of encrypt/decrypt pipelines to be used"},
853 {"read_buf", OPT_READ_BUF, 'n',
854 "Default read buffer size to be used for connections"},
858 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
859 #ifndef OPENSSL_NO_PSK
860 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
861 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
863 #ifndef OPENSSL_NO_SRP
864 {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
865 {"srpuserseed", OPT_SRPUSERSEED, 's',
866 "A seed string for a default user salt"},
868 #ifndef OPENSSL_NO_SSL3
869 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
871 #ifndef OPENSSL_NO_TLS1
872 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
874 #ifndef OPENSSL_NO_TLS1_1
875 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
877 #ifndef OPENSSL_NO_TLS1_2
878 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
880 #ifndef OPENSSL_NO_TLS1_3
881 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
883 #ifndef OPENSSL_NO_DTLS
884 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
885 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
886 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
887 {"listen", OPT_LISTEN, '-',
888 "Listen for a DTLS ClientHello with a cookie and then connect"},
890 #ifndef OPENSSL_NO_DTLS1
891 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
893 #ifndef OPENSSL_NO_DTLS1_2
894 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
896 #ifndef OPENSSL_NO_DH
897 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
899 #ifndef OPENSSL_NO_NEXTPROTONEG
900 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
901 "Set the advertised protocols for the NPN extension (comma-separated list)"},
903 #ifndef OPENSSL_NO_SRTP
904 {"use_srtp", OPT_SRTP_PROFILES, 's',
905 "Offer SRTP key management with a colon-separated profile list"},
907 {"alpn", OPT_ALPN, 's',
908 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
909 #ifndef OPENSSL_NO_ENGINE
910 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
912 {NULL, OPT_EOF, 0, NULL}
915 #define IS_PROT_FLAG(o) \
916 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
917 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
919 int s_server_main(int argc, char *argv[])
921 ENGINE *engine = NULL;
922 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
923 SSL_CONF_CTX *cctx = NULL;
924 const SSL_METHOD *meth = TLS_server_method();
925 SSL_EXCERT *exc = NULL;
926 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
927 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
928 STACK_OF(X509_CRL) *crls = NULL;
929 X509 *s_cert = NULL, *s_dcert = NULL;
930 X509_VERIFY_PARAM *vpm = NULL;
931 const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
932 char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
933 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
934 char *crl_file = NULL, *prog;
936 int unlink_unix_path = 0;
938 do_server_cb server_cb;
939 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
940 #ifndef OPENSSL_NO_DH
944 int nocert = 0, ret = 1;
945 int noCApath = 0, noCAfile = 0;
946 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
947 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
948 int rev = 0, naccept = -1, sdebug = 0;
949 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM;
950 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
952 char *port = BUF_strdup(PORT);
953 unsigned char *context = NULL;
955 EVP_PKEY *s_key2 = NULL;
956 X509 *s_cert2 = NULL;
957 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
958 const char *ssl_config = NULL;
959 int read_buf_len = 0;
960 #ifndef OPENSSL_NO_NEXTPROTONEG
961 const char *next_proto_neg_in = NULL;
962 tlsextnextprotoctx next_proto = { NULL, 0 };
964 const char *alpn_in = NULL;
965 tlsextalpnctx alpn_ctx = { NULL, 0 };
966 #ifndef OPENSSL_NO_PSK
967 /* by default do not send a PSK identity hint */
968 static char *psk_identity_hint = NULL;
971 #ifndef OPENSSL_NO_SRP
972 char *srpuserseed = NULL;
973 char *srp_verifier_file = NULL;
975 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
976 int s_server_verify = SSL_VERIFY_NONE;
977 int s_server_session_id_context = 1; /* anything will do */
978 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
979 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
980 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
981 #ifndef OPENSSL_NO_OCSP
982 int s_tlsextstatus = 0;
984 int no_resume_ephemeral = 0;
985 unsigned int split_send_fragment = 0, max_pipelines = 0;
986 const char *s_serverinfo_file = NULL;
988 /* Init of few remaining global variables */
993 s_nbio = s_nbio_test = 0;
1002 cctx = SSL_CONF_CTX_new();
1003 vpm = X509_VERIFY_PARAM_new();
1004 if (cctx == NULL || vpm == NULL)
1006 SSL_CONF_CTX_set_flags(cctx,
1007 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1009 prog = opt_init(argc, argv, s_server_options);
1010 while ((o = opt_next()) != OPT_EOF) {
1011 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1012 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1015 if (IS_NO_PROT_FLAG(o))
1017 if (prot_opt == 1 && no_prot_opt) {
1019 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1026 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1029 opt_help(s_server_options);
1035 if (socket_family == AF_UNIX) {
1036 OPENSSL_free(host); host = NULL;
1037 OPENSSL_free(port); port = NULL;
1040 socket_family = AF_INET;
1046 if (socket_family == AF_UNIX) {
1047 OPENSSL_free(host); host = NULL;
1048 OPENSSL_free(port); port = NULL;
1051 socket_family = AF_INET6;
1054 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1060 if (socket_family == AF_UNIX) {
1061 socket_family = AF_UNSPEC;
1064 OPENSSL_free(port); port = NULL;
1065 OPENSSL_free(host); host = NULL;
1066 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1068 "%s: -port argument malformed or ambiguous\n",
1075 if (socket_family == AF_UNIX) {
1076 socket_family = AF_UNSPEC;
1079 OPENSSL_free(port); port = NULL;
1080 OPENSSL_free(host); host = NULL;
1081 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1083 "%s: -accept argument malformed or ambiguous\n",
1090 socket_family = AF_UNIX;
1091 OPENSSL_free(host); host = BUF_strdup(opt_arg());
1092 OPENSSL_free(port); port = NULL;
1095 unlink_unix_path = 1;
1099 naccept = atol(opt_arg());
1102 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1103 verify_args.depth = atoi(opt_arg());
1105 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1107 case OPT_UPPER_V_VERIFY:
1109 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1110 SSL_VERIFY_CLIENT_ONCE;
1111 verify_args.depth = atoi(opt_arg());
1114 "verify depth is %d, must return a certificate\n",
1118 context = (unsigned char *)opt_arg();
1121 s_cert_file = opt_arg();
1124 crl_file = opt_arg();
1126 case OPT_CRL_DOWNLOAD:
1129 case OPT_SERVERINFO:
1130 s_serverinfo_file = opt_arg();
1133 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1137 s_key_file = opt_arg();
1140 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1144 passarg = opt_arg();
1146 case OPT_CERT_CHAIN:
1147 s_chain_file = opt_arg();
1150 #ifndef OPENSSL_NO_DH
1155 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1159 s_dcert_file = opt_arg();
1162 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1166 dpassarg = opt_arg();
1169 s_dkey_file = opt_arg();
1171 case OPT_DCERT_CHAIN:
1172 s_dchain_file = opt_arg();
1183 case OPT_CHAINCAPATH:
1184 chCApath = opt_arg();
1186 case OPT_VERIFYCAPATH:
1187 vfyCApath = opt_arg();
1196 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1200 if (ssl_args == NULL)
1201 ssl_args = sk_OPENSSL_STRING_new_null();
1202 if (ssl_args == NULL
1203 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1204 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1205 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1210 if (!opt_verify(o, vpm))
1215 if (!args_excert(o, &exc))
1218 case OPT_VERIFY_RET_ERROR:
1219 verify_args.return_error = 1;
1221 case OPT_VERIFY_QUIET:
1222 verify_args.quiet = 1;
1224 case OPT_BUILD_CHAIN:
1233 case OPT_CHAINCAFILE:
1234 chCAfile = opt_arg();
1236 case OPT_VERIFYCAFILE:
1237 vfyCAfile = opt_arg();
1243 s_nbio = s_nbio_test = 1;
1248 case OPT_NO_IGN_EOF:
1254 case OPT_TLSEXTDEBUG:
1258 #ifndef OPENSSL_NO_OCSP
1262 case OPT_STATUS_VERBOSE:
1263 #ifndef OPENSSL_NO_OCSP
1264 s_tlsextstatus = tlscstatp.verbose = 1;
1267 case OPT_STATUS_TIMEOUT:
1268 #ifndef OPENSSL_NO_OCSP
1270 tlscstatp.timeout = atoi(opt_arg());
1273 case OPT_STATUS_URL:
1274 #ifndef OPENSSL_NO_OCSP
1276 if (!OCSP_parse_url(opt_arg(),
1279 &tlscstatp.path, &tlscstatp.use_ssl)) {
1280 BIO_printf(bio_err, "Error parsing URL\n");
1285 case OPT_STATUS_FILE:
1286 #ifndef OPENSSL_NO_OCSP
1288 tlscstatp.respin = opt_arg();
1295 bio_s_msg = BIO_new_file(opt_arg(), "w");
1298 #ifndef OPENSSL_NO_SSL_TRACE
1302 case OPT_SECURITY_DEBUG:
1305 case OPT_SECURITY_DEBUG_VERBOSE:
1318 s_quiet = s_brief = verify_args.quiet = 1;
1321 #ifndef OPENSSL_NO_DH
1325 case OPT_NO_RESUME_EPHEMERAL:
1326 no_resume_ephemeral = 1;
1329 #ifndef OPENSSL_NO_PSK
1330 psk_identity_hint = opt_arg();
1334 #ifndef OPENSSL_NO_PSK
1335 for (p = psk_key = opt_arg(); *p; p++) {
1336 if (isxdigit(_UC(*p)))
1338 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1344 #ifndef OPENSSL_NO_SRP
1345 srp_verifier_file = opt_arg();
1346 if (min_version < TLS1_VERSION)
1347 min_version = TLS1_VERSION;
1350 case OPT_SRPUSERSEED:
1351 #ifndef OPENSSL_NO_SRP
1352 srpuserseed = opt_arg();
1353 if (min_version < TLS1_VERSION)
1354 min_version = TLS1_VERSION;
1369 case OPT_SSL_CONFIG:
1370 ssl_config = opt_arg();
1373 min_version = SSL3_VERSION;
1374 max_version = SSL3_VERSION;
1377 min_version = TLS1_3_VERSION;
1378 max_version = TLS1_3_VERSION;
1381 min_version = TLS1_2_VERSION;
1382 max_version = TLS1_2_VERSION;
1385 min_version = TLS1_1_VERSION;
1386 max_version = TLS1_1_VERSION;
1389 min_version = TLS1_VERSION;
1390 max_version = TLS1_VERSION;
1393 #ifndef OPENSSL_NO_DTLS
1394 meth = DTLS_server_method();
1395 socket_type = SOCK_DGRAM;
1399 #ifndef OPENSSL_NO_DTLS
1400 meth = DTLS_server_method();
1401 min_version = DTLS1_VERSION;
1402 max_version = DTLS1_VERSION;
1403 socket_type = SOCK_DGRAM;
1407 #ifndef OPENSSL_NO_DTLS
1408 meth = DTLS_server_method();
1409 min_version = DTLS1_2_VERSION;
1410 max_version = DTLS1_2_VERSION;
1411 socket_type = SOCK_DGRAM;
1415 #ifndef OPENSSL_NO_DTLS
1416 enable_timeouts = 1;
1420 #ifndef OPENSSL_NO_DTLS
1421 socket_mtu = atol(opt_arg());
1425 #ifndef OPENSSL_NO_DTLS
1430 session_id_prefix = opt_arg();
1433 engine = setup_engine(opt_arg(), 1);
1438 case OPT_SERVERNAME:
1439 tlsextcbp.servername = opt_arg();
1441 case OPT_SERVERNAME_FATAL:
1442 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1445 s_cert_file2 = opt_arg();
1448 s_key_file2 = opt_arg();
1450 case OPT_NEXTPROTONEG:
1451 # ifndef OPENSSL_NO_NEXTPROTONEG
1452 next_proto_neg_in = opt_arg();
1456 alpn_in = opt_arg();
1458 case OPT_SRTP_PROFILES:
1459 #ifndef OPENSSL_NO_SRTP
1460 srtp_profiles = opt_arg();
1463 case OPT_KEYMATEXPORT:
1464 keymatexportlabel = opt_arg();
1466 case OPT_KEYMATEXPORTLEN:
1467 keymatexportlen = atoi(opt_arg());
1472 case OPT_SPLIT_SEND_FRAG:
1473 split_send_fragment = atoi(opt_arg());
1474 if (split_send_fragment == 0) {
1476 * Not allowed - set to a deliberately bad value so we get an
1477 * error message below
1479 split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1;
1482 case OPT_MAX_PIPELINES:
1483 max_pipelines = atoi(opt_arg());
1486 read_buf_len = atoi(opt_arg());
1491 argc = opt_num_rest();
1494 #ifndef OPENSSL_NO_DTLS
1495 if (www && socket_type == SOCK_DGRAM) {
1496 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1500 if (dtlslisten && socket_type != SOCK_DGRAM) {
1501 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1507 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1509 "Can't use unix sockets and datagrams together\n");
1514 if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1515 BIO_printf(bio_err, "Bad split send fragment size\n");
1519 if (max_pipelines > SSL_MAX_PIPELINES) {
1520 BIO_printf(bio_err, "Bad max pipelines value\n");
1524 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1525 BIO_printf(bio_err, "Error getting password\n");
1529 if (s_key_file == NULL)
1530 s_key_file = s_cert_file;
1532 if (s_key_file2 == NULL)
1533 s_key_file2 = s_cert_file2;
1535 if (!load_excert(&exc))
1539 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1540 "server certificate private key file");
1542 ERR_print_errors(bio_err);
1546 s_cert = load_cert(s_cert_file, s_cert_format,
1547 "server certificate file");
1550 ERR_print_errors(bio_err);
1554 if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1555 "server certificate chain"))
1559 if (tlsextcbp.servername) {
1560 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1561 "second server certificate private key file");
1563 ERR_print_errors(bio_err);
1567 s_cert2 = load_cert(s_cert_file2, s_cert_format,
1568 "second server certificate file");
1571 ERR_print_errors(bio_err);
1576 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1577 if (next_proto_neg_in) {
1579 next_proto.data = next_protos_parse(&len, next_proto_neg_in);
1580 if (next_proto.data == NULL)
1582 next_proto.len = len;
1584 next_proto.data = NULL;
1587 alpn_ctx.data = NULL;
1590 alpn_ctx.data = next_protos_parse(&len, alpn_in);
1591 if (alpn_ctx.data == NULL)
1598 crl = load_crl(crl_file, crl_format);
1600 BIO_puts(bio_err, "Error loading CRL\n");
1601 ERR_print_errors(bio_err);
1604 crls = sk_X509_CRL_new_null();
1605 if (!crls || !sk_X509_CRL_push(crls, crl)) {
1606 BIO_puts(bio_err, "Error adding CRL\n");
1607 ERR_print_errors(bio_err);
1615 if (s_dkey_file == NULL)
1616 s_dkey_file = s_dcert_file;
1618 s_dkey = load_key(s_dkey_file, s_dkey_format,
1619 0, dpass, engine, "second certificate private key file");
1621 ERR_print_errors(bio_err);
1625 s_dcert = load_cert(s_dcert_file, s_dcert_format,
1626 "second server certificate file");
1629 ERR_print_errors(bio_err);
1632 if (s_dchain_file) {
1633 if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1634 "second server certificate chain"))
1640 if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1641 && !RAND_status()) {
1643 "warning, not much extra random data, consider using the -rand option\n");
1646 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1647 app_RAND_load_files(inrand));
1649 if (bio_s_out == NULL) {
1650 if (s_quiet && !s_debug) {
1651 bio_s_out = BIO_new(BIO_s_null());
1652 if (s_msg && !bio_s_msg)
1653 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1655 if (bio_s_out == NULL)
1656 bio_s_out = dup_bio_out(FORMAT_TEXT);
1659 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1665 s_dcert_file = NULL;
1667 s_cert_file2 = NULL;
1671 ctx = SSL_CTX_new(meth);
1673 ERR_print_errors(bio_err);
1677 ssl_ctx_security_debug(ctx, sdebug);
1679 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1680 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1682 ERR_print_errors(bio_err);
1686 if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1688 if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1691 if (session_id_prefix) {
1692 if (strlen(session_id_prefix) >= 32)
1694 "warning: id_prefix is too long, only one new session will be possible\n");
1695 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1696 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1697 ERR_print_errors(bio_err);
1700 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1702 SSL_CTX_set_quiet_shutdown(ctx, 1);
1704 ssl_ctx_set_excert(ctx, exc);
1707 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1709 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1711 init_session_cache_ctx(ctx);
1713 SSL_CTX_sess_set_cache_size(ctx, 128);
1716 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1718 if (split_send_fragment > 0) {
1719 SSL_CTX_set_split_send_fragment(ctx, split_send_fragment);
1721 if (max_pipelines > 0) {
1722 SSL_CTX_set_max_pipelines(ctx, max_pipelines);
1725 if (read_buf_len > 0) {
1726 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1728 #ifndef OPENSSL_NO_SRTP
1729 if (srtp_profiles != NULL) {
1730 /* Returns 0 on success! */
1731 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1732 BIO_printf(bio_err, "Error setting SRTP profile\n");
1733 ERR_print_errors(bio_err);
1739 if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1740 ERR_print_errors(bio_err);
1743 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1744 BIO_printf(bio_err, "Error setting verify params\n");
1745 ERR_print_errors(bio_err);
1749 ssl_ctx_add_crls(ctx, crls, 0);
1750 if (!config_ctx(cctx, ssl_args, ctx))
1753 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1754 crls, crl_download)) {
1755 BIO_printf(bio_err, "Error loading store locations\n");
1756 ERR_print_errors(bio_err);
1761 ctx2 = SSL_CTX_new(meth);
1763 ERR_print_errors(bio_err);
1769 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1772 ssl_ctx_security_debug(ctx, sdebug);
1774 if (session_id_prefix) {
1775 if (strlen(session_id_prefix) >= 32)
1777 "warning: id_prefix is too long, only one new session will be possible\n");
1778 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1779 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1780 ERR_print_errors(bio_err);
1783 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1785 SSL_CTX_set_quiet_shutdown(ctx2, 1);
1787 ssl_ctx_set_excert(ctx2, exc);
1790 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1793 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1795 init_session_cache_ctx(ctx2);
1797 SSL_CTX_sess_set_cache_size(ctx2, 128);
1800 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1802 if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1804 ERR_print_errors(bio_err);
1807 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1808 BIO_printf(bio_err, "Error setting verify params\n");
1809 ERR_print_errors(bio_err);
1813 ssl_ctx_add_crls(ctx2, crls, 0);
1814 if (!config_ctx(cctx, ssl_args, ctx2))
1817 #ifndef OPENSSL_NO_NEXTPROTONEG
1818 if (next_proto.data)
1819 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1823 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1825 #ifndef OPENSSL_NO_DH
1830 dh = load_dh_param(dhfile);
1831 else if (s_cert_file)
1832 dh = load_dh_param(s_cert_file);
1835 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1837 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1839 (void)BIO_flush(bio_s_out);
1842 SSL_CTX_set_dh_auto(ctx, 1);
1843 else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1844 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1845 ERR_print_errors(bio_err);
1852 DH *dh2 = load_dh_param(s_cert_file2);
1854 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1855 (void)BIO_flush(bio_s_out);
1862 SSL_CTX_set_dh_auto(ctx2, 1);
1863 else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1864 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1865 ERR_print_errors(bio_err);
1874 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1877 if (s_serverinfo_file != NULL
1878 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1879 ERR_print_errors(bio_err);
1883 if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1886 if (s_dcert != NULL) {
1887 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1891 if (no_resume_ephemeral) {
1892 SSL_CTX_set_not_resumable_session_callback(ctx,
1893 not_resumable_sess_cb);
1896 SSL_CTX_set_not_resumable_session_callback(ctx2,
1897 not_resumable_sess_cb);
1899 #ifndef OPENSSL_NO_PSK
1900 if (psk_key != NULL) {
1902 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
1903 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1906 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1907 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1908 ERR_print_errors(bio_err);
1913 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1914 if (!SSL_CTX_set_session_id_context(ctx,
1915 (void *)&s_server_session_id_context,
1916 sizeof s_server_session_id_context)) {
1917 BIO_printf(bio_err, "error setting session id context\n");
1918 ERR_print_errors(bio_err);
1922 /* Set DTLS cookie generation and verification callbacks */
1923 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1924 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1927 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1928 if (!SSL_CTX_set_session_id_context(ctx2,
1929 (void *)&s_server_session_id_context,
1930 sizeof s_server_session_id_context)) {
1931 BIO_printf(bio_err, "error setting session id context\n");
1932 ERR_print_errors(bio_err);
1935 tlsextcbp.biodebug = bio_s_out;
1936 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1937 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1938 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1939 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1942 #ifndef OPENSSL_NO_SRP
1943 if (srp_verifier_file != NULL) {
1944 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1945 srp_callback_parm.user = NULL;
1946 srp_callback_parm.login = NULL;
1948 SRP_VBASE_init(srp_callback_parm.vb,
1949 srp_verifier_file)) != SRP_NO_ERROR) {
1951 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1952 srp_verifier_file, ret);
1955 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
1956 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
1957 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1960 if (CAfile != NULL) {
1961 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
1964 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
1966 #ifndef OPENSSL_NO_OCSP
1967 if (s_tlsextstatus) {
1968 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1969 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1971 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
1972 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
1977 BIO_printf(bio_s_out, "ACCEPT\n");
1978 (void)BIO_flush(bio_s_out);
1980 server_cb = rev_body;
1982 server_cb = www_body;
1984 server_cb = sv_body;
1986 if (socket_family == AF_UNIX
1987 && unlink_unix_path)
1990 do_server(&accept_socket, host, port, socket_family, socket_type,
1991 server_cb, context, naccept);
1992 print_stats(bio_s_out, ctx);
1997 sk_X509_CRL_pop_free(crls, X509_CRL_free);
1999 EVP_PKEY_free(s_key);
2000 EVP_PKEY_free(s_dkey);
2001 sk_X509_pop_free(s_chain, X509_free);
2002 sk_X509_pop_free(s_dchain, X509_free);
2004 OPENSSL_free(dpass);
2007 X509_VERIFY_PARAM_free(vpm);
2009 OPENSSL_free(tlscstatp.host);
2010 OPENSSL_free(tlscstatp.port);
2011 OPENSSL_free(tlscstatp.path);
2014 EVP_PKEY_free(s_key2);
2015 #ifndef OPENSSL_NO_NEXTPROTONEG
2016 OPENSSL_free(next_proto.data);
2018 OPENSSL_free(alpn_ctx.data);
2019 ssl_excert_free(exc);
2020 sk_OPENSSL_STRING_free(ssl_args);
2021 SSL_CONF_CTX_free(cctx);
2022 release_engine(engine);
2023 BIO_free(bio_s_out);
2025 BIO_free(bio_s_msg);
2027 #ifdef CHARSET_EBCDIC
2028 BIO_meth_free(methods_ebcdic);
2033 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2035 BIO_printf(bio, "%4ld items in the session cache\n",
2036 SSL_CTX_sess_number(ssl_ctx));
2037 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2038 SSL_CTX_sess_connect(ssl_ctx));
2039 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2040 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2041 BIO_printf(bio, "%4ld client connects that finished\n",
2042 SSL_CTX_sess_connect_good(ssl_ctx));
2043 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2044 SSL_CTX_sess_accept(ssl_ctx));
2045 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2046 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2047 BIO_printf(bio, "%4ld server accepts that finished\n",
2048 SSL_CTX_sess_accept_good(ssl_ctx));
2049 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2050 BIO_printf(bio, "%4ld session cache misses\n",
2051 SSL_CTX_sess_misses(ssl_ctx));
2052 BIO_printf(bio, "%4ld session cache timeouts\n",
2053 SSL_CTX_sess_timeouts(ssl_ctx));
2054 BIO_printf(bio, "%4ld callback cache hits\n",
2055 SSL_CTX_sess_cb_hits(ssl_ctx));
2056 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2057 SSL_CTX_sess_cache_full(ssl_ctx),
2058 SSL_CTX_sess_get_cache_size(ssl_ctx));
2061 static int sv_body(int s, int stype, unsigned char *context)
2070 struct timeval timeout;
2071 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2074 struct timeval *timeoutp;
2077 buf = app_malloc(bufsize, "server buffer");
2079 if (!BIO_socket_nbio(s, 1))
2080 ERR_print_errors(bio_err);
2082 BIO_printf(bio_err, "Turned on non blocking io\n");
2088 if (s_tlsextdebug) {
2089 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2090 SSL_set_tlsext_debug_arg(con, bio_s_out);
2094 && !SSL_set_session_id_context(con,
2095 context, strlen((char *)context))) {
2096 BIO_printf(bio_err, "Error setting session id context\n");
2101 if (!SSL_clear(con)) {
2102 BIO_printf(bio_err, "Error clearing SSL connection\n");
2106 #ifndef OPENSSL_NO_DTLS
2107 if (stype == SOCK_DGRAM) {
2109 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2111 if (enable_timeouts) {
2113 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2114 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2117 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2118 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2122 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2123 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2124 DTLS_get_link_min_mtu(con));
2129 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2130 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2131 BIO_printf(bio_err, "Failed to set MTU\n");
2137 /* want to do MTU discovery */
2138 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2140 /* turn on cookie exchange */
2141 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2144 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2149 test = BIO_new(BIO_f_nbio_test());
2150 sbio = BIO_push(test, sbio);
2153 SSL_set_bio(con, sbio, sbio);
2154 SSL_set_accept_state(con);
2155 /* SSL_set_fd(con,s); */
2158 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2159 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2162 #ifndef OPENSSL_NO_SSL_TRACE
2164 SSL_set_msg_callback(con, SSL_trace);
2167 SSL_set_msg_callback(con, msg_cb);
2168 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2171 if (s_tlsextdebug) {
2172 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2173 SSL_set_tlsext_debug_arg(con, bio_s_out);
2176 if (fileno_stdin() > s)
2177 width = fileno_stdin() + 1;
2181 int read_from_terminal;
2182 int read_from_sslcon;
2184 read_from_terminal = 0;
2185 read_from_sslcon = SSL_has_pending(con)
2186 || (async && SSL_waiting_for_async(con));
2188 if (!read_from_sslcon) {
2190 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2191 openssl_fdset(fileno_stdin(), &readfds);
2193 openssl_fdset(s, &readfds);
2195 * Note: under VMS with SOCKETSHR the second parameter is
2196 * currently of type (int *) whereas under other systems it is
2197 * (void *) if you don't have a cast it will choke the compiler:
2198 * if you do have a cast then you can either go for (int *) or
2201 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2203 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2204 * only on sockets. As a workaround we timeout the select every
2205 * second and check for any keypress. In a proper Windows
2206 * application we wouldn't do this because it is inefficient.
2210 i = select(width, (void *)&readfds, NULL, NULL, &tv);
2211 if (has_stdin_waiting())
2212 read_from_terminal = 1;
2213 if ((i < 0) || (!i && !read_from_terminal))
2216 if ((SSL_version(con) == DTLS1_VERSION) &&
2217 DTLSv1_get_timeout(con, &timeout))
2218 timeoutp = &timeout;
2222 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2224 if ((SSL_version(con) == DTLS1_VERSION)
2225 && DTLSv1_handle_timeout(con) > 0) {
2226 BIO_printf(bio_err, "TIMEOUT occurred\n");
2231 if (FD_ISSET(fileno_stdin(), &readfds))
2232 read_from_terminal = 1;
2234 if (FD_ISSET(s, &readfds))
2235 read_from_sslcon = 1;
2237 if (read_from_terminal) {
2241 i = raw_read_stdin(buf, bufsize / 2);
2243 /* both loops are skipped when i <= 0 */
2244 for (j = 0; j < i; j++)
2247 for (j = i - 1; j >= 0; j--) {
2248 buf[j + lf_num] = buf[j];
2249 if (buf[j] == '\n') {
2252 buf[j + lf_num] = '\r';
2255 assert(lf_num == 0);
2257 i = raw_read_stdin(buf, bufsize);
2259 if (!s_quiet && !s_brief) {
2260 if ((i <= 0) || (buf[0] == 'Q')) {
2261 BIO_printf(bio_s_out, "DONE\n");
2262 (void)BIO_flush(bio_s_out);
2264 close_accept_socket();
2268 if ((i <= 0) || (buf[0] == 'q')) {
2269 BIO_printf(bio_s_out, "DONE\n");
2270 (void)BIO_flush(bio_s_out);
2271 if (SSL_version(con) != DTLS1_VERSION)
2274 * close_accept_socket(); ret= -11;
2278 #ifndef OPENSSL_NO_HEARTBEATS
2279 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2280 BIO_printf(bio_err, "HEARTBEATING\n");
2286 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2287 SSL_renegotiate(con);
2288 i = SSL_do_handshake(con);
2289 printf("SSL_do_handshake -> %d\n", i);
2293 * strcpy(buf,"server side RE-NEGOTIATE\n");
2296 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2298 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2300 SSL_renegotiate(con);
2301 i = SSL_do_handshake(con);
2302 printf("SSL_do_handshake -> %d\n", i);
2306 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2310 if (buf[0] == 'P') {
2311 static const char *str = "Lets print some clear text\n";
2312 BIO_write(SSL_get_wbio(con), str, strlen(str));
2314 if (buf[0] == 'S') {
2315 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2318 #ifdef CHARSET_EBCDIC
2319 ebcdic2ascii(buf, buf, i);
2323 /* should do a select for the write */
2326 if (++count == 100) {
2328 SSL_renegotiate(con);
2331 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2332 #ifndef OPENSSL_NO_SRP
2333 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2334 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2335 SRP_user_pwd_free(srp_callback_parm.user);
2336 srp_callback_parm.user =
2337 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2338 srp_callback_parm.login);
2339 if (srp_callback_parm.user)
2340 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2341 srp_callback_parm.user->info);
2343 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2344 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2347 switch (SSL_get_error(con, k)) {
2348 case SSL_ERROR_NONE:
2350 case SSL_ERROR_WANT_ASYNC:
2351 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2352 (void)BIO_flush(bio_s_out);
2353 wait_for_async(con);
2355 case SSL_ERROR_WANT_WRITE:
2356 case SSL_ERROR_WANT_READ:
2357 case SSL_ERROR_WANT_X509_LOOKUP:
2358 BIO_printf(bio_s_out, "Write BLOCK\n");
2359 (void)BIO_flush(bio_s_out);
2361 case SSL_ERROR_WANT_ASYNC_JOB:
2363 * This shouldn't ever happen in s_server. Treat as an error
2365 case SSL_ERROR_SYSCALL:
2367 BIO_printf(bio_s_out, "ERROR\n");
2368 (void)BIO_flush(bio_s_out);
2369 ERR_print_errors(bio_err);
2373 case SSL_ERROR_ZERO_RETURN:
2374 BIO_printf(bio_s_out, "DONE\n");
2375 (void)BIO_flush(bio_s_out);
2387 if (read_from_sslcon) {
2389 * init_ssl_connection handles all async events itself so if we're
2390 * waiting for async then we shouldn't go back into
2391 * init_ssl_connection
2393 if ((!async || !SSL_waiting_for_async(con))
2394 && !SSL_is_init_finished(con)) {
2395 i = init_ssl_connection(con);
2400 } else if (i == 0) {
2406 i = SSL_read(con, (char *)buf, bufsize);
2407 #ifndef OPENSSL_NO_SRP
2408 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2409 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2410 SRP_user_pwd_free(srp_callback_parm.user);
2411 srp_callback_parm.user =
2412 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2413 srp_callback_parm.login);
2414 if (srp_callback_parm.user)
2415 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2416 srp_callback_parm.user->info);
2418 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2419 i = SSL_read(con, (char *)buf, bufsize);
2422 switch (SSL_get_error(con, i)) {
2423 case SSL_ERROR_NONE:
2424 #ifdef CHARSET_EBCDIC
2425 ascii2ebcdic(buf, buf, i);
2427 raw_write_stdout(buf, (unsigned int)i);
2428 (void)BIO_flush(bio_s_out);
2429 if (SSL_has_pending(con))
2432 case SSL_ERROR_WANT_ASYNC:
2433 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2434 (void)BIO_flush(bio_s_out);
2435 wait_for_async(con);
2437 case SSL_ERROR_WANT_WRITE:
2438 case SSL_ERROR_WANT_READ:
2439 BIO_printf(bio_s_out, "Read BLOCK\n");
2440 (void)BIO_flush(bio_s_out);
2442 case SSL_ERROR_WANT_ASYNC_JOB:
2444 * This shouldn't ever happen in s_server. Treat as an error
2446 case SSL_ERROR_SYSCALL:
2448 BIO_printf(bio_s_out, "ERROR\n");
2449 (void)BIO_flush(bio_s_out);
2450 ERR_print_errors(bio_err);
2453 case SSL_ERROR_ZERO_RETURN:
2454 BIO_printf(bio_s_out, "DONE\n");
2455 (void)BIO_flush(bio_s_out);
2464 BIO_printf(bio_s_out, "shutting down SSL\n");
2465 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2468 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2469 OPENSSL_clear_free(buf, bufsize);
2471 BIO_printf(bio_s_out, "ACCEPT\n");
2472 (void)BIO_flush(bio_s_out);
2476 static void close_accept_socket(void)
2478 BIO_printf(bio_err, "shutdown accept socket\n");
2479 if (accept_socket >= 0) {
2480 BIO_closesocket(accept_socket);
2484 static int init_ssl_connection(SSL *con)
2491 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2492 const unsigned char *next_proto_neg;
2493 unsigned next_proto_neg_len;
2495 unsigned char *exportedkeymat;
2498 #ifndef OPENSSL_NO_DTLS
2500 BIO_ADDR *client = NULL;
2502 if ((client = BIO_ADDR_new()) == NULL) {
2503 BIO_printf(bio_err, "ERROR - memory\n");
2506 i = DTLSv1_listen(con, client);
2511 wbio = SSL_get_wbio(con);
2513 BIO_get_fd(wbio, &fd);
2516 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2517 BIO_printf(bio_err, "ERROR - unable to connect\n");
2518 BIO_ADDR_free(client);
2521 BIO_ADDR_free(client);
2523 i = SSL_accept(con);
2525 BIO_ADDR_free(client);
2531 i = SSL_accept(con);
2534 retry = BIO_sock_should_retry(i);
2535 #ifdef CERT_CB_TEST_RETRY
2538 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2539 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2541 "LOOKUP from certificate callback during accept\n");
2542 i = SSL_accept(con);
2544 retry = BIO_sock_should_retry(i);
2549 #ifndef OPENSSL_NO_SRP
2551 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2552 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2553 srp_callback_parm.login);
2554 SRP_user_pwd_free(srp_callback_parm.user);
2555 srp_callback_parm.user =
2556 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2557 srp_callback_parm.login);
2558 if (srp_callback_parm.user)
2559 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2560 srp_callback_parm.user->info);
2562 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2563 i = SSL_accept(con);
2565 retry = BIO_sock_should_retry(i);
2568 } while (i < 0 && SSL_waiting_for_async(con));
2571 if ((dtlslisten && i == 0)
2572 || (!dtlslisten && retry)) {
2573 BIO_printf(bio_s_out, "DELAY\n");
2577 BIO_printf(bio_err, "ERROR\n");
2579 verify_err = SSL_get_verify_result(con);
2580 if (verify_err != X509_V_OK) {
2581 BIO_printf(bio_err, "verify error:%s\n",
2582 X509_verify_cert_error_string(verify_err));
2584 /* Always print any error messages */
2585 ERR_print_errors(bio_err);
2590 print_ssl_summary(con);
2592 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2594 peer = SSL_get_peer_certificate(con);
2596 BIO_printf(bio_s_out, "Client certificate\n");
2597 PEM_write_bio_X509(bio_s_out, peer);
2598 X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
2599 BIO_printf(bio_s_out, "subject=%s\n", buf);
2600 X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
2601 BIO_printf(bio_s_out, "issuer=%s\n", buf);
2606 if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2607 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2608 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2609 ssl_print_sigalgs(bio_s_out, con);
2610 #ifndef OPENSSL_NO_EC
2611 ssl_print_point_formats(bio_s_out, con);
2612 ssl_print_groups(bio_s_out, con, 0);
2614 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2616 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2617 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2618 if (next_proto_neg) {
2619 BIO_printf(bio_s_out, "NEXTPROTO is ");
2620 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2621 BIO_printf(bio_s_out, "\n");
2624 #ifndef OPENSSL_NO_SRTP
2626 SRTP_PROTECTION_PROFILE *srtp_profile
2627 = SSL_get_selected_srtp_profile(con);
2630 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2631 srtp_profile->name);
2634 if (SSL_session_reused(con))
2635 BIO_printf(bio_s_out, "Reused session-id\n");
2636 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2637 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2638 if (keymatexportlabel != NULL) {
2639 BIO_printf(bio_s_out, "Keying material exporter:\n");
2640 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2641 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2642 exportedkeymat = app_malloc(keymatexportlen, "export key");
2643 if (!SSL_export_keying_material(con, exportedkeymat,
2646 strlen(keymatexportlabel),
2648 BIO_printf(bio_s_out, " Error\n");
2650 BIO_printf(bio_s_out, " Keying material: ");
2651 for (i = 0; i < keymatexportlen; i++)
2652 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2653 BIO_printf(bio_s_out, "\n");
2655 OPENSSL_free(exportedkeymat);
2658 (void)BIO_flush(bio_s_out);
2662 #ifndef OPENSSL_NO_DH
2663 static DH *load_dh_param(const char *dhfile)
2668 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2670 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2677 static int www_body(int s, int stype, unsigned char *context)
2683 const SSL_CIPHER *c;
2684 BIO *io, *ssl_bio, *sbio;
2686 int total_bytes = 0;
2691 /* Set width for a select call if needed */
2694 buf = app_malloc(bufsize, "server www buffer");
2695 io = BIO_new(BIO_f_buffer());
2696 ssl_bio = BIO_new(BIO_f_ssl());
2697 if ((io == NULL) || (ssl_bio == NULL))
2701 if (!BIO_socket_nbio(s, 1))
2702 ERR_print_errors(bio_err);
2704 BIO_printf(bio_err, "Turned on non blocking io\n");
2707 /* lets make the output buffer a reasonable size */
2708 if (!BIO_set_write_buffer_size(io, bufsize))
2711 if ((con = SSL_new(ctx)) == NULL)
2714 if (s_tlsextdebug) {
2715 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2716 SSL_set_tlsext_debug_arg(con, bio_s_out);
2720 && !SSL_set_session_id_context(con, context,
2721 strlen((char *)context)))
2724 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2728 test = BIO_new(BIO_f_nbio_test());
2729 sbio = BIO_push(test, sbio);
2731 SSL_set_bio(con, sbio, sbio);
2732 SSL_set_accept_state(con);
2734 /* SSL_set_fd(con,s); */
2735 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2736 BIO_push(io, ssl_bio);
2737 #ifdef CHARSET_EBCDIC
2738 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2742 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2743 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2746 #ifndef OPENSSL_NO_SSL_TRACE
2748 SSL_set_msg_callback(con, SSL_trace);
2751 SSL_set_msg_callback(con, msg_cb);
2752 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2756 i = BIO_gets(io, buf, bufsize - 1);
2757 if (i < 0) { /* error */
2758 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2760 ERR_print_errors(bio_err);
2763 BIO_printf(bio_s_out, "read R BLOCK\n");
2764 #ifndef OPENSSL_NO_SRP
2765 if (BIO_should_io_special(io)
2766 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2767 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2768 SRP_user_pwd_free(srp_callback_parm.user);
2769 srp_callback_parm.user =
2770 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2771 srp_callback_parm.login);
2772 if (srp_callback_parm.user)
2773 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2774 srp_callback_parm.user->info);
2776 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2780 #if !defined(OPENSSL_SYS_MSDOS)
2785 } else if (i == 0) { /* end of input */
2790 /* else we have data */
2791 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2792 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2795 STACK_OF(SSL_CIPHER) *sk;
2796 static const char *space = " ";
2798 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2799 if (strncmp("GET /renegcert", buf, 14) == 0)
2801 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2803 i = SSL_renegotiate(con);
2804 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2805 /* Send the HelloRequest */
2806 i = SSL_do_handshake(con);
2808 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2809 SSL_get_error(con, i));
2810 ERR_print_errors(bio_err);
2813 /* Wait for a ClientHello to come back */
2815 openssl_fdset(s, &readfds);
2816 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2817 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2818 BIO_printf(bio_s_out,
2819 "Error waiting for client response\n");
2820 ERR_print_errors(bio_err);
2824 * We're not actually expecting any data here and we ignore
2825 * any that is sent. This is just to force the handshake that
2826 * we're expecting to come from the client. If they haven't
2827 * sent one there's not much we can do.
2829 BIO_gets(io, buf, bufsize - 1);
2833 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2834 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2835 BIO_puts(io, "<pre>\n");
2836 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2838 for (i = 0; i < local_argc; i++) {
2840 for (myp = local_argv[i]; *myp; myp++)
2843 BIO_puts(io, "<");
2846 BIO_puts(io, ">");
2849 BIO_puts(io, "&");
2852 BIO_write(io, myp, 1);
2855 BIO_write(io, " ", 1);
2860 "Secure Renegotiation IS%s supported\n",
2861 SSL_get_secure_renegotiation_support(con) ?
2865 * The following is evil and should not really be done
2867 BIO_printf(io, "Ciphers supported in s_server binary\n");
2868 sk = SSL_get_ciphers(con);
2869 j = sk_SSL_CIPHER_num(sk);
2870 for (i = 0; i < j; i++) {
2871 c = sk_SSL_CIPHER_value(sk, i);
2872 BIO_printf(io, "%-11s:%-25s ",
2873 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2874 if ((((i + 1) % 2) == 0) && (i + 1 != j))
2878 p = SSL_get_shared_ciphers(con, buf, bufsize);
2881 "---\nCiphers common between both SSL end points:\n");
2885 BIO_write(io, space, 26 - j);
2888 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
2890 BIO_write(io, p, 1);
2897 ssl_print_sigalgs(io, con);
2898 #ifndef OPENSSL_NO_EC
2899 ssl_print_groups(io, con, 0);
2901 BIO_printf(io, (SSL_session_reused(con)
2902 ? "---\nReused, " : "---\nNew, "));
2903 c = SSL_get_current_cipher(con);
2904 BIO_printf(io, "%s, Cipher is %s\n",
2905 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2906 SSL_SESSION_print(io, SSL_get_session(con));
2907 BIO_printf(io, "---\n");
2908 print_stats(io, SSL_get_SSL_CTX(con));
2909 BIO_printf(io, "---\n");
2910 peer = SSL_get_peer_certificate(con);
2912 BIO_printf(io, "Client certificate\n");
2913 X509_print(io, peer);
2914 PEM_write_bio_X509(io, peer);
2918 BIO_puts(io, "no client certificate available\n");
2919 BIO_puts(io, "</BODY></HTML>\r\n\r\n");
2921 } else if ((www == 2 || www == 3)
2922 && (strncmp("GET /", buf, 5) == 0)) {
2925 static const char *text =
2926 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2932 for (e = p; *e != '\0'; e++) {
2938 dot = (e[0] == '.') ? 2 : 0;
2941 dot = (e[0] == '.') ? 3 : 0;
2944 dot = (e[0] == '/') ? -1 : 0;
2948 dot = (e[0] == '/') ? 1 : 0;
2950 dot = (dot == 3) || (dot == -1); /* filename contains ".."
2955 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
2962 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
2968 BIO_printf(io, "'%s' is an invalid path\r\n", p);
2972 /* if a directory, do the index thang */
2973 if (app_isdir(p) > 0) {
2975 BIO_printf(io, "'%s' is a directory\r\n", p);
2979 if ((file = BIO_new_file(p, "r")) == NULL) {
2981 BIO_printf(io, "Error opening '%s'\r\n", p);
2982 ERR_print_errors(io);
2987 BIO_printf(bio_err, "FILE:%s\n", p);
2991 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
2992 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
2993 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
2995 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2998 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3002 i = BIO_read(file, buf, bufsize);
3008 BIO_printf(bio_err, "%d\n", i);
3009 if (total_bytes > 3 * 1024) {
3011 BIO_printf(bio_err, "RENEGOTIATE\n");
3012 SSL_renegotiate(con);
3016 for (j = 0; j < i;) {
3019 if (++count == 13) {
3020 SSL_renegotiate(con);
3023 k = BIO_write(io, &(buf[j]), i - j);
3025 if (!BIO_should_retry(io)
3026 && !SSL_waiting_for_async(con))
3029 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3043 i = (int)BIO_flush(io);
3045 if (!BIO_should_retry(io))
3051 /* make sure we re-use sessions */
3052 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3056 BIO_printf(bio_s_out, "ACCEPT\n");
3062 static int rev_body(int s, int stype, unsigned char *context)
3068 BIO *io, *ssl_bio, *sbio;
3070 buf = app_malloc(bufsize, "server rev buffer");
3071 io = BIO_new(BIO_f_buffer());
3072 ssl_bio = BIO_new(BIO_f_ssl());
3073 if ((io == NULL) || (ssl_bio == NULL))
3076 /* lets make the output buffer a reasonable size */
3077 if (!BIO_set_write_buffer_size(io, bufsize))
3080 if ((con = SSL_new(ctx)) == NULL)
3083 if (s_tlsextdebug) {
3084 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3085 SSL_set_tlsext_debug_arg(con, bio_s_out);
3088 && !SSL_set_session_id_context(con, context,
3089 strlen((char *)context))) {
3090 ERR_print_errors(bio_err);
3094 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3095 SSL_set_bio(con, sbio, sbio);
3096 SSL_set_accept_state(con);
3098 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3099 BIO_push(io, ssl_bio);
3100 #ifdef CHARSET_EBCDIC
3101 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3105 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3106 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3109 #ifndef OPENSSL_NO_SSL_TRACE
3111 SSL_set_msg_callback(con, SSL_trace);
3114 SSL_set_msg_callback(con, msg_cb);
3115 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3119 i = BIO_do_handshake(io);
3122 if (!BIO_should_retry(io)) {
3123 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3124 ERR_print_errors(bio_err);
3127 #ifndef OPENSSL_NO_SRP
3128 if (BIO_should_io_special(io)
3129 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3130 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3131 SRP_user_pwd_free(srp_callback_parm.user);
3132 srp_callback_parm.user =
3133 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3134 srp_callback_parm.login);
3135 if (srp_callback_parm.user)
3136 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3137 srp_callback_parm.user->info);
3139 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3144 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3145 print_ssl_summary(con);
3148 i = BIO_gets(io, buf, bufsize - 1);
3149 if (i < 0) { /* error */
3150 if (!BIO_should_retry(io)) {
3152 ERR_print_errors(bio_err);
3155 BIO_printf(bio_s_out, "read R BLOCK\n");
3156 #ifndef OPENSSL_NO_SRP
3157 if (BIO_should_io_special(io)
3158 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3159 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3160 SRP_user_pwd_free(srp_callback_parm.user);
3161 srp_callback_parm.user =
3162 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3163 srp_callback_parm.login);
3164 if (srp_callback_parm.user)
3165 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3166 srp_callback_parm.user->info);
3168 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3172 #if !defined(OPENSSL_SYS_MSDOS)
3177 } else if (i == 0) { /* end of input */
3179 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3182 char *p = buf + i - 1;
3183 while (i && (*p == '\n' || *p == '\r')) {
3187 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3189 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3192 BUF_reverse((unsigned char *)buf, NULL, i);
3194 BIO_write(io, buf, i + 1);
3199 if (!BIO_should_retry(io))
3205 /* make sure we re-use sessions */
3206 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3215 #define MAX_SESSION_ID_ATTEMPTS 10
3216 static int generate_session_id(const SSL *ssl, unsigned char *id,
3217 unsigned int *id_len)
3219 unsigned int count = 0;
3221 if (RAND_bytes(id, *id_len) <= 0)
3224 * Prefix the session_id with the required prefix. NB: If our prefix
3225 * is too long, clip it - but there will be worse effects anyway, eg.
3226 * the server could only possibly create 1 session ID (ie. the
3227 * prefix!) so all future session negotiations will fail due to
3230 memcpy(id, session_id_prefix,
3231 (strlen(session_id_prefix) < *id_len) ?
3232 strlen(session_id_prefix) : *id_len);
3234 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3235 (++count < MAX_SESSION_ID_ATTEMPTS));
3236 if (count >= MAX_SESSION_ID_ATTEMPTS)
3242 * By default s_server uses an in-memory cache which caches SSL_SESSION
3243 * structures without any serialisation. This hides some bugs which only
3244 * become apparent in deployed servers. By implementing a basic external
3245 * session cache some issues can be debugged using s_server.
3248 typedef struct simple_ssl_session_st {
3253 struct simple_ssl_session_st *next;
3254 } simple_ssl_session;
3256 static simple_ssl_session *first = NULL;
3258 static int add_session(SSL *ssl, SSL_SESSION *session)
3260 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3263 SSL_SESSION_get_id(session, &sess->idlen);
3264 sess->derlen = i2d_SSL_SESSION(session, NULL);
3265 if (sess->derlen < 0) {
3266 BIO_printf(bio_err, "Error encoding session\n");
3271 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3272 sess->der = app_malloc(sess->derlen, "get session buffer");
3274 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3275 OPENSSL_free(sess->id);
3276 OPENSSL_free(sess->der);
3282 /* Assume it still works. */
3283 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3284 BIO_printf(bio_err, "Unexpected session encoding length\n");
3285 OPENSSL_free(sess->id);
3286 OPENSSL_free(sess->der);
3293 BIO_printf(bio_err, "New session added to external cache\n");
3297 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3300 simple_ssl_session *sess;
3302 for (sess = first; sess; sess = sess->next) {
3303 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3304 const unsigned char *p = sess->der;
3305 BIO_printf(bio_err, "Lookup session: cache hit\n");
3306 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3309 BIO_printf(bio_err, "Lookup session: cache miss\n");
3313 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3315 simple_ssl_session *sess, *prev = NULL;
3316 const unsigned char *id;
3318 id = SSL_SESSION_get_id(session, &idlen);
3319 for (sess = first; sess; sess = sess->next) {
3320 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3322 prev->next = sess->next;
3325 OPENSSL_free(sess->id);
3326 OPENSSL_free(sess->der);
3334 static void init_session_cache_ctx(SSL_CTX *sctx)
3336 SSL_CTX_set_session_cache_mode(sctx,
3337 SSL_SESS_CACHE_NO_INTERNAL |
3338 SSL_SESS_CACHE_SERVER);
3339 SSL_CTX_sess_set_new_cb(sctx, add_session);
3340 SSL_CTX_sess_set_get_cb(sctx, get_session);
3341 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3344 static void free_sessions(void)
3346 simple_ssl_session *sess, *tsess;
3347 for (sess = first; sess;) {
3348 OPENSSL_free(sess->id);
3349 OPENSSL_free(sess->der);
3352 OPENSSL_free(tsess);
3357 #endif /* OPENSSL_NO_SOCK */