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 const int bufsize = 16 * 1024;
109 static int accept_socket = -1;
111 #define TEST_CERT "server.pem"
112 #define TEST_CERT2 "server2.pem"
114 static int s_nbio = 0;
115 static int s_nbio_test = 0;
116 static int s_crlf = 0;
117 static SSL_CTX *ctx = NULL;
118 static SSL_CTX *ctx2 = NULL;
121 static BIO *bio_s_out = NULL;
122 static BIO *bio_s_msg = NULL;
123 static int s_debug = 0;
124 static int s_tlsextdebug = 0;
125 static int s_msg = 0;
126 static int s_quiet = 0;
127 static int s_ign_eof = 0;
128 static int s_brief = 0;
130 static char *keymatexportlabel = NULL;
131 static int keymatexportlen = 20;
133 static int async = 0;
135 static const char *session_id_prefix = NULL;
137 #ifndef OPENSSL_NO_DTLS
138 static int enable_timeouts = 0;
139 static long socket_mtu;
143 * We define this but make it always be 0 in no-dtls builds to simplify the
146 static int dtlslisten = 0;
148 #ifndef OPENSSL_NO_PSK
149 static const char psk_identity[] = "Client_identity";
150 char *psk_key = NULL; /* by default PSK is not used */
152 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
154 unsigned int max_psk_len)
160 BIO_printf(bio_s_out, "psk_server_cb\n");
162 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
166 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
167 (int)strlen(identity), identity);
169 /* here we could lookup the given identity e.g. from a database */
170 if (strcmp(identity, psk_identity) != 0) {
171 BIO_printf(bio_s_out, "PSK error: client identity not found"
172 " (got '%s' expected '%s')\n", identity, psk_identity);
176 BIO_printf(bio_s_out, "PSK client identity found\n");
178 /* convert the PSK key to binary */
179 key = OPENSSL_hexstr2buf(psk_key, &key_len);
181 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
185 if (key_len > (int)max_psk_len) {
187 "psk buffer of callback is too small (%d) for key (%ld)\n",
188 max_psk_len, key_len);
193 memcpy(psk, key, key_len);
197 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
201 BIO_printf(bio_err, "Error in PSK server callback\n");
202 (void)BIO_flush(bio_err);
203 (void)BIO_flush(bio_s_out);
208 #ifndef OPENSSL_NO_SRP
209 /* This is a context that we pass to callbacks */
210 typedef struct srpsrvparm_st {
217 * This callback pretends to require some asynchronous logic in order to
218 * obtain a verifier. When the callback is called for a new connection we
219 * return with a negative value. This will provoke the accept etc to return
220 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
221 * (which would normally occur after a worker has finished) and we set the
224 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
226 srpsrvparm *p = (srpsrvparm *) arg;
227 int ret = SSL3_AL_FATAL;
229 if (p->login == NULL && p->user == NULL) {
230 p->login = SSL_get_srp_username(s);
231 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
235 if (p->user == NULL) {
236 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
240 if (SSL_set_srp_server_param
241 (s, p->user->N, p->user->g, p->user->s, p->user->v,
242 p->user->info) < 0) {
243 *ad = SSL_AD_INTERNAL_ERROR;
247 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
248 p->login, p->user->info);
249 ret = SSL_ERROR_NONE;
252 SRP_user_pwd_free(p->user);
260 static int local_argc = 0;
261 static char **local_argv;
263 #ifdef CHARSET_EBCDIC
264 static int ebcdic_new(BIO *bi);
265 static int ebcdic_free(BIO *a);
266 static int ebcdic_read(BIO *b, char *out, int outl);
267 static int ebcdic_write(BIO *b, const char *in, int inl);
268 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
269 static int ebcdic_gets(BIO *bp, char *buf, int size);
270 static int ebcdic_puts(BIO *bp, const char *str);
272 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
273 static BIO_METHOD *methods_ebcdic = NULL;
275 /* This struct is "unwarranted chumminess with the compiler." */
281 static const BIO_METHOD *BIO_f_ebcdic_filter()
283 if (methods_ebcdic == NULL) {
284 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
285 "EBCDIC/ASCII filter");
286 if (methods_ebcdic == NULL
287 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
288 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
289 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
290 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
291 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
292 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
293 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
296 return methods_ebcdic;
299 static int ebcdic_new(BIO *bi)
301 EBCDIC_OUTBUFF *wbuf;
303 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
304 wbuf->alloced = 1024;
305 wbuf->buff[0] = '\0';
307 BIO_set_data(bi, wbuf);
312 static int ebcdic_free(BIO *a)
314 EBCDIC_OUTBUFF *wbuf;
318 wbuf = BIO_get_data(a);
320 BIO_set_data(a, NULL);
326 static int ebcdic_read(BIO *b, char *out, int outl)
329 BIO *next = BIO_next(b);
331 if (out == NULL || outl == 0)
336 ret = BIO_read(next, out, outl);
338 ascii2ebcdic(out, out, ret);
342 static int ebcdic_write(BIO *b, const char *in, int inl)
344 EBCDIC_OUTBUFF *wbuf;
345 BIO *next = BIO_next(b);
349 if ((in == NULL) || (inl <= 0))
354 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
356 if (inl > (num = wbuf->alloced)) {
357 num = num + num; /* double the size */
361 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
364 wbuf->buff[0] = '\0';
366 BIO_set_data(b, wbuf);
369 ebcdic2ascii(wbuf->buff, in, inl);
371 ret = BIO_write(next, wbuf->buff, inl);
376 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
379 BIO *next = BIO_next(b);
388 ret = BIO_ctrl(next, cmd, num, ptr);
394 static int ebcdic_gets(BIO *bp, char *buf, int size)
397 BIO *next = BIO_next(bp);
401 /* return(BIO_gets(bp->next_bio,buf,size));*/
402 for (i = 0; i < size - 1; ++i) {
403 ret = ebcdic_read(bp, &buf[i], 1);
406 else if (buf[i] == '\n') {
413 return (ret < 0 && i == 0) ? ret : i;
416 static int ebcdic_puts(BIO *bp, const char *str)
418 if (BIO_next(bp) == NULL)
420 return ebcdic_write(bp, str, strlen(str));
424 /* This is a context that we pass to callbacks */
425 typedef struct tlsextctx_st {
431 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
433 tlsextctx *p = (tlsextctx *) arg;
434 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
435 if (servername && p->biodebug)
436 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
440 return SSL_TLSEXT_ERR_NOACK;
443 if (strcasecmp(servername, p->servername))
444 return p->extension_error;
446 BIO_printf(p->biodebug, "Switching server context.\n");
447 SSL_set_SSL_CTX(s, ctx2);
450 return SSL_TLSEXT_ERR_OK;
453 /* Structure passed to cert status callback */
454 typedef struct tlsextstatusctx_st {
455 /* Default responder to use */
456 char *host, *path, *port;
462 static tlsextstatusctx tlscstatp = { NULL, NULL, NULL, 0, -1, 0 };
464 #ifndef OPENSSL_NO_OCSP
466 * Certificate Status callback. This is called when a client includes a
467 * certificate status request extension. This is a simplified version. It
468 * examines certificates each time and makes one OCSP responder query for
469 * each request. A full version would store details such as the OCSP
470 * certificate IDs and minimise the number of OCSP responses by caching them
471 * until they were considered "expired".
474 static int cert_status_cb(SSL *s, void *arg)
476 tlsextstatusctx *srctx = arg;
477 char *host = NULL, *port = NULL, *path = NULL;
479 unsigned char *rspder = NULL;
481 STACK_OF(OPENSSL_STRING) *aia = NULL;
483 X509_STORE_CTX *inctx = NULL;
485 OCSP_REQUEST *req = NULL;
486 OCSP_RESPONSE *resp = NULL;
487 OCSP_CERTID *id = NULL;
488 STACK_OF(X509_EXTENSION) *exts;
489 int ret = SSL_TLSEXT_ERR_NOACK;
493 BIO_puts(bio_err, "cert_status: callback called\n");
494 /* Build up OCSP query from server certificate */
495 x = SSL_get_certificate(s);
496 aia = X509_get1_ocsp(x);
498 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
499 &host, &port, &path, &use_ssl)) {
500 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
504 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
505 sk_OPENSSL_STRING_value(aia, 0));
509 "cert_status: no AIA and no default responder URL\n");
515 use_ssl = srctx->use_ssl;
518 inctx = X509_STORE_CTX_new();
521 if (!X509_STORE_CTX_init(inctx,
522 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
525 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
526 X509_get_issuer_name(x));
528 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
531 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
532 X509_OBJECT_free(obj);
535 req = OCSP_REQUEST_new();
538 if (!OCSP_request_add0_id(req, id))
541 /* Add any extensions to the request */
542 SSL_get_tlsext_status_exts(s, &exts);
543 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
544 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
545 if (!OCSP_REQUEST_add_ext(req, ext, -1))
548 resp = process_responder(req, host, path, port, use_ssl, NULL,
551 BIO_puts(bio_err, "cert_status: error querying responder\n");
554 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
557 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
558 if (srctx->verbose) {
559 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
560 OCSP_RESPONSE_print(bio_err, resp, 2);
562 ret = SSL_TLSEXT_ERR_OK;
566 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
568 if (ret != SSL_TLSEXT_ERR_OK)
569 ERR_print_errors(bio_err);
574 X509_email_free(aia);
576 OCSP_CERTID_free(id);
577 OCSP_REQUEST_free(req);
578 OCSP_RESPONSE_free(resp);
579 X509_STORE_CTX_free(inctx);
584 #ifndef OPENSSL_NO_NEXTPROTONEG
585 /* This is the context that we pass to next_proto_cb */
586 typedef struct tlsextnextprotoctx_st {
589 } tlsextnextprotoctx;
591 static int next_proto_cb(SSL *s, const unsigned char **data,
592 unsigned int *len, void *arg)
594 tlsextnextprotoctx *next_proto = arg;
596 *data = next_proto->data;
597 *len = next_proto->len;
599 return SSL_TLSEXT_ERR_OK;
601 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
603 /* This the context that we pass to alpn_cb */
604 typedef struct tlsextalpnctx_st {
609 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
610 const unsigned char *in, unsigned int inlen, void *arg)
612 tlsextalpnctx *alpn_ctx = arg;
615 /* We can assume that |in| is syntactically valid. */
617 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
618 for (i = 0; i < inlen;) {
620 BIO_write(bio_s_out, ", ", 2);
621 BIO_write(bio_s_out, &in[i + 1], in[i]);
624 BIO_write(bio_s_out, "\n", 1);
627 if (SSL_select_next_proto
628 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
629 inlen) != OPENSSL_NPN_NEGOTIATED) {
630 return SSL_TLSEXT_ERR_NOACK;
634 BIO_printf(bio_s_out, "ALPN protocols selected: ");
635 BIO_write(bio_s_out, *out, *outlen);
636 BIO_write(bio_s_out, "\n", 1);
639 return SSL_TLSEXT_ERR_OK;
642 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
644 /* disable resumption for sessions with forward secure ciphers */
645 return is_forward_secure;
648 #ifndef OPENSSL_NO_SRP
649 static srpsrvparm srp_callback_parm;
651 #ifndef OPENSSL_NO_SRTP
652 static char *srtp_profiles = NULL;
655 typedef enum OPTION_choice {
656 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
657 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
658 OPT_VERIFY, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
659 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
660 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
661 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
662 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
663 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
664 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
665 OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
666 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
667 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_MSG, OPT_MSGFILE, OPT_TRACE,
668 OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF,
669 OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
670 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
671 OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC,
672 OPT_SSL_CONFIG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
673 OPT_SSL3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
674 OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN,
675 OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
676 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN,
677 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
683 OPTIONS s_server_options[] = {
684 {"help", OPT_HELP, '-', "Display this summary"},
685 {"port", OPT_PORT, 'p',
686 "TCP/IP port to listen on for connections (default is " PORT ")"},
687 {"accept", OPT_ACCEPT, 's',
688 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
690 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
692 {"4", OPT_4, '-', "Use IPv4 only"},
693 {"6", OPT_6, '-', "Use IPv6 only"},
695 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
697 {"context", OPT_CONTEXT, 's', "Set session ID context"},
698 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
699 {"Verify", OPT_UPPER_V_VERIFY, 'n',
700 "Turn on peer certificate verification, must have a cert"},
701 {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
702 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
703 {"serverinfo", OPT_SERVERINFO, 's',
704 "PEM serverinfo file for certificate"},
705 {"certform", OPT_CERTFORM, 'F',
706 "Certificate format (PEM or DER) PEM default"},
707 {"key", OPT_KEY, 's',
708 "Private Key if not in -cert; default is " TEST_CERT},
709 {"keyform", OPT_KEYFORM, 'f',
710 "Key format (PEM, DER or ENGINE) PEM default"},
711 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
712 {"dcert", OPT_DCERT, '<',
713 "Second certificate file to use (usually for DSA)"},
714 {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
715 {"dcertform", OPT_DCERTFORM, 'F',
716 "Second certificate format (PEM or DER) PEM default"},
717 {"dkey", OPT_DKEY, '<',
718 "Second private key file to use (usually for DSA)"},
719 {"dkeyform", OPT_DKEYFORM, 'F',
720 "Second key format (PEM, DER or ENGINE) PEM default"},
721 {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
722 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
723 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
724 {"debug", OPT_DEBUG, '-', "Print more output"},
725 {"msg", OPT_MSG, '-', "Show protocol messages"},
726 {"msgfile", OPT_MSGFILE, '>',
727 "File to send output of -msg or -trace, instead of stdout"},
728 {"state", OPT_STATE, '-', "Print the SSL states"},
729 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
730 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
731 {"no-CAfile", OPT_NOCAFILE, '-',
732 "Do not load the default certificates file"},
733 {"no-CApath", OPT_NOCAPATH, '-',
734 "Do not load certificates from the default certificates directory"},
735 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
736 {"quiet", OPT_QUIET, '-', "No server output"},
737 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
738 "Disable caching and tickets if ephemeral (EC)DH is used"},
739 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
740 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
741 {"servername", OPT_SERVERNAME, 's',
742 "Servername for HostName TLS extension"},
743 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
744 "mismatch send fatal alert (default warning alert)"},
745 {"cert2", OPT_CERT2, '<',
746 "Certificate file to use for servername; default is" TEST_CERT2},
747 {"key2", OPT_KEY2, '<',
748 "-Private Key file to use for servername if not in -cert2"},
749 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
750 "Hex dump of all TLS extensions received"},
751 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
752 {"id_prefix", OPT_ID_PREFIX, 's',
753 "Generate SSL/TLS session IDs prefixed by arg"},
754 {"rand", OPT_RAND, 's',
755 "Load the file(s) into the random number generator"},
756 {"keymatexport", OPT_KEYMATEXPORT, 's',
757 "Export keying material using label"},
758 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
759 "Export len bytes of keying material (default 20)"},
760 {"CRL", OPT_CRL, '<', "CRL file to use"},
761 {"crl_download", OPT_CRL_DOWNLOAD, '-',
762 "Download CRL from distribution points"},
763 {"cert_chain", OPT_CERT_CHAIN, '<',
764 "certificate chain file in PEM format"},
765 {"dcert_chain", OPT_DCERT_CHAIN, '<',
766 "second certificate chain file in PEM format"},
767 {"chainCApath", OPT_CHAINCAPATH, '/',
768 "use dir as certificate store path to build CA certificate chain"},
769 {"verifyCApath", OPT_VERIFYCAPATH, '/',
770 "use dir as certificate store path to verify CA certificate"},
771 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
772 {"ext_cache", OPT_EXT_CACHE, '-',
773 "Disable internal cache, setup and use external cache"},
774 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
775 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
776 "Close connection on verification error"},
777 {"verify_quiet", OPT_VERIFY_QUIET, '-',
778 "No verify output except verify errors"},
779 {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
780 {"chainCAfile", OPT_CHAINCAFILE, '<',
781 "CA file for certificate chain (PEM format)"},
782 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
783 "CA file for certificate verification (PEM format)"},
784 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
785 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
786 #ifndef OPENSSL_NO_OCSP
787 {"status", OPT_STATUS, '-', "Request certificate status from server"},
788 {"status_verbose", OPT_STATUS_VERBOSE, '-',
789 "Print more output in certificate status callback"},
790 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
791 "Status request responder timeout"},
792 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
794 #ifndef OPENSSL_NO_SSL_TRACE
795 {"trace", OPT_TRACE, '-', "trace protocol messages"},
797 {"security_debug", OPT_SECURITY_DEBUG, '-',
798 "Print output from SSL/TLS security framework"},
799 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
800 "Print more output from SSL/TLS security framework"},
801 {"brief", OPT_BRIEF, '-',
802 "Restrict output to brief summary of connection parameters"},
803 {"rev", OPT_REV, '-',
804 "act as a simple test server which just sends back with the received text reversed"},
805 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
806 {"ssl_config", OPT_SSL_CONFIG, 's',
807 "Configure SSL_CTX using the configuration 'val'"},
808 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'n',
809 "Size used to split data for encrypt pipelines"},
810 {"max_pipelines", OPT_MAX_PIPELINES, 'n',
811 "Maximum number of encrypt/decrypt pipelines to be used"},
812 {"read_buf", OPT_READ_BUF, 'n',
813 "Default read buffer size to be used for connections"},
817 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
818 #ifndef OPENSSL_NO_PSK
819 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
820 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
822 #ifndef OPENSSL_NO_SRP
823 {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
824 {"srpuserseed", OPT_SRPUSERSEED, 's',
825 "A seed string for a default user salt"},
827 #ifndef OPENSSL_NO_SSL3
828 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
830 #ifndef OPENSSL_NO_TLS1
831 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
833 #ifndef OPENSSL_NO_TLS1_1
834 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
836 #ifndef OPENSSL_NO_TLS1_2
837 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
839 #ifndef OPENSSL_NO_DTLS
840 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
841 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
842 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
843 {"listen", OPT_LISTEN, '-',
844 "Listen for a DTLS ClientHello with a cookie and then connect"},
846 #ifndef OPENSSL_NO_DTLS1
847 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
849 #ifndef OPENSSL_NO_DTLS1_2
850 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
852 #ifndef OPENSSL_NO_DH
853 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
855 #ifndef OPENSSL_NO_NEXTPROTONEG
856 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
857 "Set the advertised protocols for the NPN extension (comma-separated list)"},
859 #ifndef OPENSSL_NO_SRTP
860 {"use_srtp", OPT_SRTP_PROFILES, 's',
861 "Offer SRTP key management with a colon-separated profile list"},
863 {"alpn", OPT_ALPN, 's',
864 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
865 #ifndef OPENSSL_NO_ENGINE
866 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
868 {NULL, OPT_EOF, 0, NULL}
871 #define IS_PROT_FLAG(o) \
872 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
873 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
875 int s_server_main(int argc, char *argv[])
877 ENGINE *engine = NULL;
878 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
879 SSL_CONF_CTX *cctx = NULL;
880 const SSL_METHOD *meth = TLS_server_method();
881 SSL_EXCERT *exc = NULL;
882 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
883 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
884 STACK_OF(X509_CRL) *crls = NULL;
885 X509 *s_cert = NULL, *s_dcert = NULL;
886 X509_VERIFY_PARAM *vpm = NULL;
887 const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
888 char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
889 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
890 char *crl_file = NULL, *prog;
892 int unlink_unix_path = 0;
894 do_server_cb server_cb;
895 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
896 #ifndef OPENSSL_NO_DH
900 int nocert = 0, ret = 1;
901 int noCApath = 0, noCAfile = 0;
902 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
903 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
904 int rev = 0, naccept = -1, sdebug = 0;
905 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM;
906 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
908 char *port = BUF_strdup(PORT);
909 unsigned char *context = NULL;
911 EVP_PKEY *s_key2 = NULL;
912 X509 *s_cert2 = NULL;
913 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
914 const char *ssl_config = NULL;
915 int read_buf_len = 0;
916 #ifndef OPENSSL_NO_NEXTPROTONEG
917 const char *next_proto_neg_in = NULL;
918 tlsextnextprotoctx next_proto = { NULL, 0 };
920 const char *alpn_in = NULL;
921 tlsextalpnctx alpn_ctx = { NULL, 0 };
922 #ifndef OPENSSL_NO_PSK
923 /* by default do not send a PSK identity hint */
924 char *psk_identity_hint = NULL;
927 #ifndef OPENSSL_NO_SRP
928 char *srpuserseed = NULL;
929 char *srp_verifier_file = NULL;
931 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
932 int s_server_verify = SSL_VERIFY_NONE;
933 int s_server_session_id_context = 1; /* anything will do */
934 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
935 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
936 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
937 #ifndef OPENSSL_NO_OCSP
938 int s_tlsextstatus = 0;
940 int no_resume_ephemeral = 0;
941 unsigned int split_send_fragment = 0, max_pipelines = 0;
942 const char *s_serverinfo_file = NULL;
944 /* Init of few remaining global variables */
949 s_nbio = s_nbio_test = 0;
958 cctx = SSL_CONF_CTX_new();
959 vpm = X509_VERIFY_PARAM_new();
960 if (cctx == NULL || vpm == NULL)
962 SSL_CONF_CTX_set_flags(cctx,
963 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
965 prog = opt_init(argc, argv, s_server_options);
966 while ((o = opt_next()) != OPT_EOF) {
967 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
968 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
971 if (IS_NO_PROT_FLAG(o))
973 if (prot_opt == 1 && no_prot_opt) {
975 "Cannot supply both a protocol flag and '-no_<prot>'\n");
982 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
985 opt_help(s_server_options);
991 if (socket_family == AF_UNIX) {
992 OPENSSL_free(host); host = NULL;
993 OPENSSL_free(port); port = NULL;
996 socket_family = AF_INET;
1002 if (socket_family == AF_UNIX) {
1003 OPENSSL_free(host); host = NULL;
1004 OPENSSL_free(port); port = NULL;
1007 socket_family = AF_INET6;
1010 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1016 if (socket_family == AF_UNIX) {
1017 socket_family = AF_UNSPEC;
1020 OPENSSL_free(port); port = NULL;
1021 OPENSSL_free(host); host = NULL;
1022 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1024 "%s: -port argument malformed or ambiguous\n",
1031 if (socket_family == AF_UNIX) {
1032 socket_family = AF_UNSPEC;
1035 OPENSSL_free(port); port = NULL;
1036 OPENSSL_free(host); host = NULL;
1037 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1039 "%s: -accept argument malformed or ambiguous\n",
1046 socket_family = AF_UNIX;
1047 OPENSSL_free(host); host = BUF_strdup(opt_arg());
1048 OPENSSL_free(port); port = NULL;
1051 unlink_unix_path = 1;
1055 naccept = atol(opt_arg());
1058 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1059 verify_args.depth = atoi(opt_arg());
1061 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1063 case OPT_UPPER_V_VERIFY:
1065 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1066 SSL_VERIFY_CLIENT_ONCE;
1067 verify_args.depth = atoi(opt_arg());
1070 "verify depth is %d, must return a certificate\n",
1074 context = (unsigned char *)opt_arg();
1077 s_cert_file = opt_arg();
1080 crl_file = opt_arg();
1082 case OPT_CRL_DOWNLOAD:
1085 case OPT_SERVERINFO:
1086 s_serverinfo_file = opt_arg();
1089 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1093 s_key_file = opt_arg();
1096 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1100 passarg = opt_arg();
1102 case OPT_CERT_CHAIN:
1103 s_chain_file = opt_arg();
1106 #ifndef OPENSSL_NO_DH
1111 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1115 s_dcert_file = opt_arg();
1118 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1122 dpassarg = opt_arg();
1125 s_dkey_file = opt_arg();
1127 case OPT_DCERT_CHAIN:
1128 s_dchain_file = opt_arg();
1139 case OPT_CHAINCAPATH:
1140 chCApath = opt_arg();
1142 case OPT_VERIFYCAPATH:
1143 vfyCApath = opt_arg();
1152 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1156 if (ssl_args == NULL)
1157 ssl_args = sk_OPENSSL_STRING_new_null();
1158 if (ssl_args == NULL
1159 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1160 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1161 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1166 if (!opt_verify(o, vpm))
1171 if (!args_excert(o, &exc))
1174 case OPT_VERIFY_RET_ERROR:
1175 verify_args.return_error = 1;
1177 case OPT_VERIFY_QUIET:
1178 verify_args.quiet = 1;
1180 case OPT_BUILD_CHAIN:
1189 case OPT_CHAINCAFILE:
1190 chCAfile = opt_arg();
1192 case OPT_VERIFYCAFILE:
1193 vfyCAfile = opt_arg();
1199 s_nbio = s_nbio_test = 1;
1204 case OPT_NO_IGN_EOF:
1210 case OPT_TLSEXTDEBUG:
1214 #ifndef OPENSSL_NO_OCSP
1218 case OPT_STATUS_VERBOSE:
1219 #ifndef OPENSSL_NO_OCSP
1220 s_tlsextstatus = tlscstatp.verbose = 1;
1223 case OPT_STATUS_TIMEOUT:
1224 #ifndef OPENSSL_NO_OCSP
1226 tlscstatp.timeout = atoi(opt_arg());
1229 case OPT_STATUS_URL:
1230 #ifndef OPENSSL_NO_OCSP
1232 if (!OCSP_parse_url(opt_arg(),
1235 &tlscstatp.path, &tlscstatp.use_ssl)) {
1236 BIO_printf(bio_err, "Error parsing URL\n");
1245 bio_s_msg = BIO_new_file(opt_arg(), "w");
1248 #ifndef OPENSSL_NO_SSL_TRACE
1252 case OPT_SECURITY_DEBUG:
1255 case OPT_SECURITY_DEBUG_VERBOSE:
1268 s_quiet = s_brief = verify_args.quiet = 1;
1271 #ifndef OPENSSL_NO_DH
1275 case OPT_NO_RESUME_EPHEMERAL:
1276 no_resume_ephemeral = 1;
1279 #ifndef OPENSSL_NO_PSK
1280 psk_identity_hint = opt_arg();
1284 #ifndef OPENSSL_NO_PSK
1285 for (p = psk_key = opt_arg(); *p; p++) {
1286 if (isxdigit(_UC(*p)))
1288 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1294 #ifndef OPENSSL_NO_SRP
1295 srp_verifier_file = opt_arg();
1296 if (min_version < TLS1_VERSION)
1297 min_version = TLS1_VERSION;
1300 case OPT_SRPUSERSEED:
1301 #ifndef OPENSSL_NO_SRP
1302 srpuserseed = opt_arg();
1303 if (min_version < TLS1_VERSION)
1304 min_version = TLS1_VERSION;
1319 case OPT_SSL_CONFIG:
1320 ssl_config = opt_arg();
1323 min_version = SSL3_VERSION;
1324 max_version = SSL3_VERSION;
1327 min_version = TLS1_2_VERSION;
1328 max_version = TLS1_2_VERSION;
1331 min_version = TLS1_1_VERSION;
1332 max_version = TLS1_1_VERSION;
1335 min_version = TLS1_VERSION;
1336 max_version = TLS1_VERSION;
1339 #ifndef OPENSSL_NO_DTLS
1340 meth = DTLS_server_method();
1341 socket_type = SOCK_DGRAM;
1345 #ifndef OPENSSL_NO_DTLS
1346 meth = DTLS_server_method();
1347 min_version = DTLS1_VERSION;
1348 max_version = DTLS1_VERSION;
1349 socket_type = SOCK_DGRAM;
1353 #ifndef OPENSSL_NO_DTLS
1354 meth = DTLS_server_method();
1355 min_version = DTLS1_2_VERSION;
1356 max_version = DTLS1_2_VERSION;
1357 socket_type = SOCK_DGRAM;
1361 #ifndef OPENSSL_NO_DTLS
1362 enable_timeouts = 1;
1366 #ifndef OPENSSL_NO_DTLS
1367 socket_mtu = atol(opt_arg());
1371 #ifndef OPENSSL_NO_DTLS
1376 session_id_prefix = opt_arg();
1379 engine = setup_engine(opt_arg(), 1);
1384 case OPT_SERVERNAME:
1385 tlsextcbp.servername = opt_arg();
1387 case OPT_SERVERNAME_FATAL:
1388 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1391 s_cert_file2 = opt_arg();
1394 s_key_file2 = opt_arg();
1396 case OPT_NEXTPROTONEG:
1397 # ifndef OPENSSL_NO_NEXTPROTONEG
1398 next_proto_neg_in = opt_arg();
1402 alpn_in = opt_arg();
1404 case OPT_SRTP_PROFILES:
1405 #ifndef OPENSSL_NO_SRTP
1406 srtp_profiles = opt_arg();
1409 case OPT_KEYMATEXPORT:
1410 keymatexportlabel = opt_arg();
1412 case OPT_KEYMATEXPORTLEN:
1413 keymatexportlen = atoi(opt_arg());
1418 case OPT_SPLIT_SEND_FRAG:
1419 split_send_fragment = atoi(opt_arg());
1420 if (split_send_fragment == 0) {
1422 * Not allowed - set to a deliberately bad value so we get an
1423 * error message below
1425 split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1;
1428 case OPT_MAX_PIPELINES:
1429 max_pipelines = atoi(opt_arg());
1432 read_buf_len = atoi(opt_arg());
1437 argc = opt_num_rest();
1440 #ifndef OPENSSL_NO_DTLS
1441 if (www && socket_type == SOCK_DGRAM) {
1442 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1446 if (dtlslisten && socket_type != SOCK_DGRAM) {
1447 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1453 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1455 "Can't use unix sockets and datagrams together\n");
1460 if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1461 BIO_printf(bio_err, "Bad split send fragment size\n");
1465 if (max_pipelines > SSL_MAX_PIPELINES) {
1466 BIO_printf(bio_err, "Bad max pipelines value\n");
1470 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1471 BIO_printf(bio_err, "Error getting password\n");
1475 if (s_key_file == NULL)
1476 s_key_file = s_cert_file;
1478 if (s_key_file2 == NULL)
1479 s_key_file2 = s_cert_file2;
1481 if (!load_excert(&exc))
1485 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1486 "server certificate private key file");
1488 ERR_print_errors(bio_err);
1492 s_cert = load_cert(s_cert_file, s_cert_format,
1493 "server certificate file");
1496 ERR_print_errors(bio_err);
1500 if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1501 "server certificate chain"))
1505 if (tlsextcbp.servername) {
1506 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1507 "second server certificate private key file");
1509 ERR_print_errors(bio_err);
1513 s_cert2 = load_cert(s_cert_file2, s_cert_format,
1514 "second server certificate file");
1517 ERR_print_errors(bio_err);
1522 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1523 if (next_proto_neg_in) {
1524 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1525 if (next_proto.data == NULL)
1529 alpn_ctx.data = NULL;
1531 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1532 if (alpn_ctx.data == NULL)
1538 crl = load_crl(crl_file, crl_format);
1540 BIO_puts(bio_err, "Error loading CRL\n");
1541 ERR_print_errors(bio_err);
1544 crls = sk_X509_CRL_new_null();
1545 if (!crls || !sk_X509_CRL_push(crls, crl)) {
1546 BIO_puts(bio_err, "Error adding CRL\n");
1547 ERR_print_errors(bio_err);
1555 if (s_dkey_file == NULL)
1556 s_dkey_file = s_dcert_file;
1558 s_dkey = load_key(s_dkey_file, s_dkey_format,
1559 0, dpass, engine, "second certificate private key file");
1561 ERR_print_errors(bio_err);
1565 s_dcert = load_cert(s_dcert_file, s_dcert_format,
1566 "second server certificate file");
1569 ERR_print_errors(bio_err);
1572 if (s_dchain_file) {
1573 if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1574 "second server certificate chain"))
1580 if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1581 && !RAND_status()) {
1583 "warning, not much extra random data, consider using the -rand option\n");
1586 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1587 app_RAND_load_files(inrand));
1589 if (bio_s_out == NULL) {
1590 if (s_quiet && !s_debug) {
1591 bio_s_out = BIO_new(BIO_s_null());
1592 if (s_msg && !bio_s_msg)
1593 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1595 if (bio_s_out == NULL)
1596 bio_s_out = dup_bio_out(FORMAT_TEXT);
1599 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1605 s_dcert_file = NULL;
1607 s_cert_file2 = NULL;
1611 ctx = SSL_CTX_new(meth);
1613 ERR_print_errors(bio_err);
1617 ssl_ctx_security_debug(ctx, sdebug);
1619 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1620 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1622 ERR_print_errors(bio_err);
1626 if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1628 if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1631 if (session_id_prefix) {
1632 if (strlen(session_id_prefix) >= 32)
1634 "warning: id_prefix is too long, only one new session will be possible\n");
1635 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1636 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1637 ERR_print_errors(bio_err);
1640 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1642 SSL_CTX_set_quiet_shutdown(ctx, 1);
1644 ssl_ctx_set_excert(ctx, exc);
1647 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1649 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1651 init_session_cache_ctx(ctx);
1653 SSL_CTX_sess_set_cache_size(ctx, 128);
1656 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1658 if (split_send_fragment > 0) {
1659 SSL_CTX_set_split_send_fragment(ctx, split_send_fragment);
1661 if (max_pipelines > 0) {
1662 SSL_CTX_set_max_pipelines(ctx, max_pipelines);
1665 if (read_buf_len > 0) {
1666 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1668 #ifndef OPENSSL_NO_SRTP
1669 if (srtp_profiles != NULL) {
1670 /* Returns 0 on success! */
1671 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1672 BIO_printf(bio_err, "Error setting SRTP profile\n");
1673 ERR_print_errors(bio_err);
1679 if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1680 ERR_print_errors(bio_err);
1683 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1684 BIO_printf(bio_err, "Error setting verify params\n");
1685 ERR_print_errors(bio_err);
1689 ssl_ctx_add_crls(ctx, crls, 0);
1690 if (!config_ctx(cctx, ssl_args, ctx))
1693 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1694 crls, crl_download)) {
1695 BIO_printf(bio_err, "Error loading store locations\n");
1696 ERR_print_errors(bio_err);
1701 ctx2 = SSL_CTX_new(meth);
1703 ERR_print_errors(bio_err);
1709 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1712 ssl_ctx_security_debug(ctx, sdebug);
1714 if (session_id_prefix) {
1715 if (strlen(session_id_prefix) >= 32)
1717 "warning: id_prefix is too long, only one new session will be possible\n");
1718 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1719 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1720 ERR_print_errors(bio_err);
1723 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1725 SSL_CTX_set_quiet_shutdown(ctx2, 1);
1727 ssl_ctx_set_excert(ctx2, exc);
1730 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1733 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1735 init_session_cache_ctx(ctx2);
1737 SSL_CTX_sess_set_cache_size(ctx2, 128);
1740 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1742 if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1744 ERR_print_errors(bio_err);
1747 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1748 BIO_printf(bio_err, "Error setting verify params\n");
1749 ERR_print_errors(bio_err);
1753 ssl_ctx_add_crls(ctx2, crls, 0);
1754 if (!config_ctx(cctx, ssl_args, ctx2))
1757 #ifndef OPENSSL_NO_NEXTPROTONEG
1758 if (next_proto.data)
1759 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1763 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1765 #ifndef OPENSSL_NO_DH
1770 dh = load_dh_param(dhfile);
1771 else if (s_cert_file)
1772 dh = load_dh_param(s_cert_file);
1775 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1777 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1779 (void)BIO_flush(bio_s_out);
1782 SSL_CTX_set_dh_auto(ctx, 1);
1783 else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1784 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1785 ERR_print_errors(bio_err);
1792 DH *dh2 = load_dh_param(s_cert_file2);
1794 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1795 (void)BIO_flush(bio_s_out);
1802 SSL_CTX_set_dh_auto(ctx2, 1);
1803 else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1804 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1805 ERR_print_errors(bio_err);
1814 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1817 if (s_serverinfo_file != NULL
1818 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1819 ERR_print_errors(bio_err);
1823 if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1826 if (s_dcert != NULL) {
1827 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1831 if (no_resume_ephemeral) {
1832 SSL_CTX_set_not_resumable_session_callback(ctx,
1833 not_resumable_sess_cb);
1836 SSL_CTX_set_not_resumable_session_callback(ctx2,
1837 not_resumable_sess_cb);
1839 #ifndef OPENSSL_NO_PSK
1840 if (psk_key != NULL) {
1842 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
1843 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1846 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1847 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1848 ERR_print_errors(bio_err);
1853 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1854 if (!SSL_CTX_set_session_id_context(ctx,
1855 (void *)&s_server_session_id_context,
1856 sizeof(s_server_session_id_context))) {
1857 BIO_printf(bio_err, "error setting session id context\n");
1858 ERR_print_errors(bio_err);
1862 /* Set DTLS cookie generation and verification callbacks */
1863 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1864 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1867 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1868 if (!SSL_CTX_set_session_id_context(ctx2,
1869 (void *)&s_server_session_id_context,
1870 sizeof(s_server_session_id_context))) {
1871 BIO_printf(bio_err, "error setting session id context\n");
1872 ERR_print_errors(bio_err);
1875 tlsextcbp.biodebug = bio_s_out;
1876 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1877 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1878 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1879 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1882 #ifndef OPENSSL_NO_SRP
1883 if (srp_verifier_file != NULL) {
1884 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1885 srp_callback_parm.user = NULL;
1886 srp_callback_parm.login = NULL;
1888 SRP_VBASE_init(srp_callback_parm.vb,
1889 srp_verifier_file)) != SRP_NO_ERROR) {
1891 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1892 srp_verifier_file, ret);
1895 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
1896 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
1897 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1900 if (CAfile != NULL) {
1901 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
1904 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
1906 #ifndef OPENSSL_NO_OCSP
1907 if (s_tlsextstatus) {
1908 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1909 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1911 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
1912 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
1917 BIO_printf(bio_s_out, "ACCEPT\n");
1918 (void)BIO_flush(bio_s_out);
1920 server_cb = rev_body;
1922 server_cb = www_body;
1924 server_cb = sv_body;
1926 if (socket_family == AF_UNIX
1927 && unlink_unix_path)
1930 do_server(&accept_socket, host, port, socket_family, socket_type,
1931 server_cb, context, naccept);
1932 print_stats(bio_s_out, ctx);
1937 sk_X509_CRL_pop_free(crls, X509_CRL_free);
1939 EVP_PKEY_free(s_key);
1940 EVP_PKEY_free(s_dkey);
1941 sk_X509_pop_free(s_chain, X509_free);
1942 sk_X509_pop_free(s_dchain, X509_free);
1944 OPENSSL_free(dpass);
1947 X509_VERIFY_PARAM_free(vpm);
1949 OPENSSL_free(tlscstatp.host);
1950 OPENSSL_free(tlscstatp.port);
1951 OPENSSL_free(tlscstatp.path);
1954 EVP_PKEY_free(s_key2);
1955 #ifndef OPENSSL_NO_NEXTPROTONEG
1956 OPENSSL_free(next_proto.data);
1958 OPENSSL_free(alpn_ctx.data);
1959 ssl_excert_free(exc);
1960 sk_OPENSSL_STRING_free(ssl_args);
1961 SSL_CONF_CTX_free(cctx);
1962 release_engine(engine);
1963 BIO_free(bio_s_out);
1965 BIO_free(bio_s_msg);
1967 #ifdef CHARSET_EBCDIC
1968 BIO_meth_free(methods_ebcdic);
1973 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
1975 BIO_printf(bio, "%4ld items in the session cache\n",
1976 SSL_CTX_sess_number(ssl_ctx));
1977 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
1978 SSL_CTX_sess_connect(ssl_ctx));
1979 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
1980 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
1981 BIO_printf(bio, "%4ld client connects that finished\n",
1982 SSL_CTX_sess_connect_good(ssl_ctx));
1983 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
1984 SSL_CTX_sess_accept(ssl_ctx));
1985 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
1986 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
1987 BIO_printf(bio, "%4ld server accepts that finished\n",
1988 SSL_CTX_sess_accept_good(ssl_ctx));
1989 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
1990 BIO_printf(bio, "%4ld session cache misses\n",
1991 SSL_CTX_sess_misses(ssl_ctx));
1992 BIO_printf(bio, "%4ld session cache timeouts\n",
1993 SSL_CTX_sess_timeouts(ssl_ctx));
1994 BIO_printf(bio, "%4ld callback cache hits\n",
1995 SSL_CTX_sess_cb_hits(ssl_ctx));
1996 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
1997 SSL_CTX_sess_cache_full(ssl_ctx),
1998 SSL_CTX_sess_get_cache_size(ssl_ctx));
2001 static int sv_body(int s, int stype, unsigned char *context)
2010 struct timeval timeout;
2011 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2014 struct timeval *timeoutp;
2017 buf = app_malloc(bufsize, "server buffer");
2019 if (!BIO_socket_nbio(s, 1))
2020 ERR_print_errors(bio_err);
2022 BIO_printf(bio_err, "Turned on non blocking io\n");
2028 if (s_tlsextdebug) {
2029 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2030 SSL_set_tlsext_debug_arg(con, bio_s_out);
2034 && !SSL_set_session_id_context(con,
2035 context, strlen((char *)context))) {
2036 BIO_printf(bio_err, "Error setting session id context\n");
2041 if (!SSL_clear(con)) {
2042 BIO_printf(bio_err, "Error clearing SSL connection\n");
2046 #ifndef OPENSSL_NO_DTLS
2047 if (stype == SOCK_DGRAM) {
2049 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2051 if (enable_timeouts) {
2053 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2054 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2057 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2058 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2062 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2063 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2064 DTLS_get_link_min_mtu(con));
2069 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2070 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2071 BIO_printf(bio_err, "Failed to set MTU\n");
2077 /* want to do MTU discovery */
2078 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2080 /* turn on cookie exchange */
2081 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2084 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2089 test = BIO_new(BIO_f_nbio_test());
2090 sbio = BIO_push(test, sbio);
2093 SSL_set_bio(con, sbio, sbio);
2094 SSL_set_accept_state(con);
2095 /* SSL_set_fd(con,s); */
2098 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2099 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2102 #ifndef OPENSSL_NO_SSL_TRACE
2104 SSL_set_msg_callback(con, SSL_trace);
2107 SSL_set_msg_callback(con, msg_cb);
2108 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2111 if (s_tlsextdebug) {
2112 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2113 SSL_set_tlsext_debug_arg(con, bio_s_out);
2116 if (fileno_stdin() > s)
2117 width = fileno_stdin() + 1;
2121 int read_from_terminal;
2122 int read_from_sslcon;
2124 read_from_terminal = 0;
2125 read_from_sslcon = SSL_has_pending(con)
2126 || (async && SSL_waiting_for_async(con));
2128 if (!read_from_sslcon) {
2130 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2131 openssl_fdset(fileno_stdin(), &readfds);
2133 openssl_fdset(s, &readfds);
2135 * Note: under VMS with SOCKETSHR the second parameter is
2136 * currently of type (int *) whereas under other systems it is
2137 * (void *) if you don't have a cast it will choke the compiler:
2138 * if you do have a cast then you can either go for (int *) or
2141 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2143 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2144 * only on sockets. As a workaround we timeout the select every
2145 * second and check for any keypress. In a proper Windows
2146 * application we wouldn't do this because it is inefficient.
2150 i = select(width, (void *)&readfds, NULL, NULL, &tv);
2151 if (has_stdin_waiting())
2152 read_from_terminal = 1;
2153 if ((i < 0) || (!i && !read_from_terminal))
2156 if ((SSL_version(con) == DTLS1_VERSION) &&
2157 DTLSv1_get_timeout(con, &timeout))
2158 timeoutp = &timeout;
2162 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2164 if ((SSL_version(con) == DTLS1_VERSION)
2165 && DTLSv1_handle_timeout(con) > 0) {
2166 BIO_printf(bio_err, "TIMEOUT occurred\n");
2171 if (FD_ISSET(fileno_stdin(), &readfds))
2172 read_from_terminal = 1;
2174 if (FD_ISSET(s, &readfds))
2175 read_from_sslcon = 1;
2177 if (read_from_terminal) {
2181 i = raw_read_stdin(buf, bufsize / 2);
2183 /* both loops are skipped when i <= 0 */
2184 for (j = 0; j < i; j++)
2187 for (j = i - 1; j >= 0; j--) {
2188 buf[j + lf_num] = buf[j];
2189 if (buf[j] == '\n') {
2192 buf[j + lf_num] = '\r';
2195 assert(lf_num == 0);
2197 i = raw_read_stdin(buf, bufsize);
2199 if (!s_quiet && !s_brief) {
2200 if ((i <= 0) || (buf[0] == 'Q')) {
2201 BIO_printf(bio_s_out, "DONE\n");
2202 (void)BIO_flush(bio_s_out);
2204 close_accept_socket();
2208 if ((i <= 0) || (buf[0] == 'q')) {
2209 BIO_printf(bio_s_out, "DONE\n");
2210 (void)BIO_flush(bio_s_out);
2211 if (SSL_version(con) != DTLS1_VERSION)
2214 * close_accept_socket(); ret= -11;
2218 #ifndef OPENSSL_NO_HEARTBEATS
2219 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2220 BIO_printf(bio_err, "HEARTBEATING\n");
2226 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2227 SSL_renegotiate(con);
2228 i = SSL_do_handshake(con);
2229 printf("SSL_do_handshake -> %d\n", i);
2233 * strcpy(buf,"server side RE-NEGOTIATE\n");
2236 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2238 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2240 SSL_renegotiate(con);
2241 i = SSL_do_handshake(con);
2242 printf("SSL_do_handshake -> %d\n", i);
2246 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2250 if (buf[0] == 'P') {
2251 static const char *str = "Lets print some clear text\n";
2252 BIO_write(SSL_get_wbio(con), str, strlen(str));
2254 if (buf[0] == 'S') {
2255 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2258 #ifdef CHARSET_EBCDIC
2259 ebcdic2ascii(buf, buf, i);
2263 /* should do a select for the write */
2266 if (++count == 100) {
2268 SSL_renegotiate(con);
2271 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2272 #ifndef OPENSSL_NO_SRP
2273 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2274 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2275 SRP_user_pwd_free(srp_callback_parm.user);
2276 srp_callback_parm.user =
2277 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2278 srp_callback_parm.login);
2279 if (srp_callback_parm.user)
2280 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2281 srp_callback_parm.user->info);
2283 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2284 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2287 switch (SSL_get_error(con, k)) {
2288 case SSL_ERROR_NONE:
2290 case SSL_ERROR_WANT_ASYNC:
2291 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2292 (void)BIO_flush(bio_s_out);
2293 wait_for_async(con);
2295 case SSL_ERROR_WANT_WRITE:
2296 case SSL_ERROR_WANT_READ:
2297 case SSL_ERROR_WANT_X509_LOOKUP:
2298 BIO_printf(bio_s_out, "Write BLOCK\n");
2299 (void)BIO_flush(bio_s_out);
2301 case SSL_ERROR_WANT_ASYNC_JOB:
2303 * This shouldn't ever happen in s_server. Treat as an error
2305 case SSL_ERROR_SYSCALL:
2307 BIO_printf(bio_s_out, "ERROR\n");
2308 (void)BIO_flush(bio_s_out);
2309 ERR_print_errors(bio_err);
2313 case SSL_ERROR_ZERO_RETURN:
2314 BIO_printf(bio_s_out, "DONE\n");
2315 (void)BIO_flush(bio_s_out);
2327 if (read_from_sslcon) {
2329 * init_ssl_connection handles all async events itself so if we're
2330 * waiting for async then we shouldn't go back into
2331 * init_ssl_connection
2333 if ((!async || !SSL_waiting_for_async(con))
2334 && !SSL_is_init_finished(con)) {
2335 i = init_ssl_connection(con);
2340 } else if (i == 0) {
2346 i = SSL_read(con, (char *)buf, bufsize);
2347 #ifndef OPENSSL_NO_SRP
2348 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2349 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2350 SRP_user_pwd_free(srp_callback_parm.user);
2351 srp_callback_parm.user =
2352 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2353 srp_callback_parm.login);
2354 if (srp_callback_parm.user)
2355 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2356 srp_callback_parm.user->info);
2358 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2359 i = SSL_read(con, (char *)buf, bufsize);
2362 switch (SSL_get_error(con, i)) {
2363 case SSL_ERROR_NONE:
2364 #ifdef CHARSET_EBCDIC
2365 ascii2ebcdic(buf, buf, i);
2367 raw_write_stdout(buf, (unsigned int)i);
2368 (void)BIO_flush(bio_s_out);
2369 if (SSL_has_pending(con))
2372 case SSL_ERROR_WANT_ASYNC:
2373 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2374 (void)BIO_flush(bio_s_out);
2375 wait_for_async(con);
2377 case SSL_ERROR_WANT_WRITE:
2378 case SSL_ERROR_WANT_READ:
2379 BIO_printf(bio_s_out, "Read BLOCK\n");
2380 (void)BIO_flush(bio_s_out);
2382 case SSL_ERROR_WANT_ASYNC_JOB:
2384 * This shouldn't ever happen in s_server. Treat as an error
2386 case SSL_ERROR_SYSCALL:
2388 BIO_printf(bio_s_out, "ERROR\n");
2389 (void)BIO_flush(bio_s_out);
2390 ERR_print_errors(bio_err);
2393 case SSL_ERROR_ZERO_RETURN:
2394 BIO_printf(bio_s_out, "DONE\n");
2395 (void)BIO_flush(bio_s_out);
2404 BIO_printf(bio_s_out, "shutting down SSL\n");
2405 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2408 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2409 OPENSSL_clear_free(buf, bufsize);
2411 BIO_printf(bio_s_out, "ACCEPT\n");
2412 (void)BIO_flush(bio_s_out);
2416 static void close_accept_socket(void)
2418 BIO_printf(bio_err, "shutdown accept socket\n");
2419 if (accept_socket >= 0) {
2420 BIO_closesocket(accept_socket);
2424 static int init_ssl_connection(SSL *con)
2431 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2432 const unsigned char *next_proto_neg;
2433 unsigned next_proto_neg_len;
2435 unsigned char *exportedkeymat;
2438 #ifndef OPENSSL_NO_DTLS
2440 BIO_ADDR *client = NULL;
2442 if ((client = BIO_ADDR_new()) == NULL) {
2443 BIO_printf(bio_err, "ERROR - memory\n");
2446 i = DTLSv1_listen(con, client);
2451 wbio = SSL_get_wbio(con);
2453 BIO_get_fd(wbio, &fd);
2456 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2457 BIO_printf(bio_err, "ERROR - unable to connect\n");
2458 BIO_ADDR_free(client);
2461 BIO_ADDR_free(client);
2463 i = SSL_accept(con);
2465 BIO_ADDR_free(client);
2471 i = SSL_accept(con);
2474 retry = BIO_sock_should_retry(i);
2475 #ifdef CERT_CB_TEST_RETRY
2478 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2479 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2481 "LOOKUP from certificate callback during accept\n");
2482 i = SSL_accept(con);
2484 retry = BIO_sock_should_retry(i);
2489 #ifndef OPENSSL_NO_SRP
2491 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2492 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2493 srp_callback_parm.login);
2494 SRP_user_pwd_free(srp_callback_parm.user);
2495 srp_callback_parm.user =
2496 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2497 srp_callback_parm.login);
2498 if (srp_callback_parm.user)
2499 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2500 srp_callback_parm.user->info);
2502 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2503 i = SSL_accept(con);
2505 retry = BIO_sock_should_retry(i);
2508 } while (i < 0 && SSL_waiting_for_async(con));
2511 if ((dtlslisten && i == 0)
2512 || (!dtlslisten && retry)) {
2513 BIO_printf(bio_s_out, "DELAY\n");
2517 BIO_printf(bio_err, "ERROR\n");
2519 verify_err = SSL_get_verify_result(con);
2520 if (verify_err != X509_V_OK) {
2521 BIO_printf(bio_err, "verify error:%s\n",
2522 X509_verify_cert_error_string(verify_err));
2524 /* Always print any error messages */
2525 ERR_print_errors(bio_err);
2530 print_ssl_summary(con);
2532 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2534 peer = SSL_get_peer_certificate(con);
2536 BIO_printf(bio_s_out, "Client certificate\n");
2537 PEM_write_bio_X509(bio_s_out, peer);
2538 X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof(buf));
2539 BIO_printf(bio_s_out, "subject=%s\n", buf);
2540 X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf));
2541 BIO_printf(bio_s_out, "issuer=%s\n", buf);
2546 if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
2547 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2548 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2549 ssl_print_sigalgs(bio_s_out, con);
2550 #ifndef OPENSSL_NO_EC
2551 ssl_print_point_formats(bio_s_out, con);
2552 ssl_print_curves(bio_s_out, con, 0);
2554 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2556 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2557 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2558 if (next_proto_neg) {
2559 BIO_printf(bio_s_out, "NEXTPROTO is ");
2560 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2561 BIO_printf(bio_s_out, "\n");
2564 #ifndef OPENSSL_NO_SRTP
2566 SRTP_PROTECTION_PROFILE *srtp_profile
2567 = SSL_get_selected_srtp_profile(con);
2570 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2571 srtp_profile->name);
2574 if (SSL_session_reused(con))
2575 BIO_printf(bio_s_out, "Reused session-id\n");
2576 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2577 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2578 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
2579 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
2581 if (keymatexportlabel != NULL) {
2582 BIO_printf(bio_s_out, "Keying material exporter:\n");
2583 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2584 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2585 exportedkeymat = app_malloc(keymatexportlen, "export key");
2586 if (!SSL_export_keying_material(con, exportedkeymat,
2589 strlen(keymatexportlabel),
2591 BIO_printf(bio_s_out, " Error\n");
2593 BIO_printf(bio_s_out, " Keying material: ");
2594 for (i = 0; i < keymatexportlen; i++)
2595 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2596 BIO_printf(bio_s_out, "\n");
2598 OPENSSL_free(exportedkeymat);
2601 (void)BIO_flush(bio_s_out);
2605 #ifndef OPENSSL_NO_DH
2606 static DH *load_dh_param(const char *dhfile)
2611 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2613 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2620 static int www_body(int s, int stype, unsigned char *context)
2626 const SSL_CIPHER *c;
2627 BIO *io, *ssl_bio, *sbio;
2629 int total_bytes = 0;
2634 /* Set width for a select call if needed */
2637 buf = app_malloc(bufsize, "server www buffer");
2638 io = BIO_new(BIO_f_buffer());
2639 ssl_bio = BIO_new(BIO_f_ssl());
2640 if ((io == NULL) || (ssl_bio == NULL))
2644 if (!BIO_socket_nbio(s, 1))
2645 ERR_print_errors(bio_err);
2647 BIO_printf(bio_err, "Turned on non blocking io\n");
2650 /* lets make the output buffer a reasonable size */
2651 if (!BIO_set_write_buffer_size(io, bufsize))
2654 if ((con = SSL_new(ctx)) == NULL)
2657 if (s_tlsextdebug) {
2658 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2659 SSL_set_tlsext_debug_arg(con, bio_s_out);
2663 && !SSL_set_session_id_context(con, context,
2664 strlen((char *)context)))
2667 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2671 test = BIO_new(BIO_f_nbio_test());
2672 sbio = BIO_push(test, sbio);
2674 SSL_set_bio(con, sbio, sbio);
2675 SSL_set_accept_state(con);
2677 /* SSL_set_fd(con,s); */
2678 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2679 BIO_push(io, ssl_bio);
2680 #ifdef CHARSET_EBCDIC
2681 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2685 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2686 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2689 #ifndef OPENSSL_NO_SSL_TRACE
2691 SSL_set_msg_callback(con, SSL_trace);
2694 SSL_set_msg_callback(con, msg_cb);
2695 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2699 i = BIO_gets(io, buf, bufsize - 1);
2700 if (i < 0) { /* error */
2701 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2703 ERR_print_errors(bio_err);
2706 BIO_printf(bio_s_out, "read R BLOCK\n");
2707 #ifndef OPENSSL_NO_SRP
2708 if (BIO_should_io_special(io)
2709 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2710 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2711 SRP_user_pwd_free(srp_callback_parm.user);
2712 srp_callback_parm.user =
2713 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2714 srp_callback_parm.login);
2715 if (srp_callback_parm.user)
2716 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2717 srp_callback_parm.user->info);
2719 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2723 #if !defined(OPENSSL_SYS_MSDOS)
2728 } else if (i == 0) { /* end of input */
2733 /* else we have data */
2734 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2735 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2738 STACK_OF(SSL_CIPHER) *sk;
2739 static const char *space = " ";
2741 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2742 if (strncmp("GET /renegcert", buf, 14) == 0)
2744 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2746 i = SSL_renegotiate(con);
2747 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2748 /* Send the HelloRequest */
2749 i = SSL_do_handshake(con);
2751 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2752 SSL_get_error(con, i));
2753 ERR_print_errors(bio_err);
2756 /* Wait for a ClientHello to come back */
2758 openssl_fdset(s, &readfds);
2759 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2760 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2761 BIO_printf(bio_s_out,
2762 "Error waiting for client response\n");
2763 ERR_print_errors(bio_err);
2767 * We're not actually expecting any data here and we ignore
2768 * any that is sent. This is just to force the handshake that
2769 * we're expecting to come from the client. If they haven't
2770 * sent one there's not much we can do.
2772 BIO_gets(io, buf, bufsize - 1);
2776 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2777 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2778 BIO_puts(io, "<pre>\n");
2779 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2781 for (i = 0; i < local_argc; i++) {
2783 for (myp = local_argv[i]; *myp; myp++)
2786 BIO_puts(io, "<");
2789 BIO_puts(io, ">");
2792 BIO_puts(io, "&");
2795 BIO_write(io, myp, 1);
2798 BIO_write(io, " ", 1);
2803 "Secure Renegotiation IS%s supported\n",
2804 SSL_get_secure_renegotiation_support(con) ?
2808 * The following is evil and should not really be done
2810 BIO_printf(io, "Ciphers supported in s_server binary\n");
2811 sk = SSL_get_ciphers(con);
2812 j = sk_SSL_CIPHER_num(sk);
2813 for (i = 0; i < j; i++) {
2814 c = sk_SSL_CIPHER_value(sk, i);
2815 BIO_printf(io, "%-11s:%-25s ",
2816 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2817 if ((((i + 1) % 2) == 0) && (i + 1 != j))
2821 p = SSL_get_shared_ciphers(con, buf, bufsize);
2824 "---\nCiphers common between both SSL end points:\n");
2828 BIO_write(io, space, 26 - j);
2831 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
2833 BIO_write(io, p, 1);
2840 ssl_print_sigalgs(io, con);
2841 #ifndef OPENSSL_NO_EC
2842 ssl_print_curves(io, con, 0);
2844 BIO_printf(io, (SSL_session_reused(con)
2845 ? "---\nReused, " : "---\nNew, "));
2846 c = SSL_get_current_cipher(con);
2847 BIO_printf(io, "%s, Cipher is %s\n",
2848 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2849 SSL_SESSION_print(io, SSL_get_session(con));
2850 BIO_printf(io, "---\n");
2851 print_stats(io, SSL_get_SSL_CTX(con));
2852 BIO_printf(io, "---\n");
2853 peer = SSL_get_peer_certificate(con);
2855 BIO_printf(io, "Client certificate\n");
2856 X509_print(io, peer);
2857 PEM_write_bio_X509(io, peer);
2861 BIO_puts(io, "no client certificate available\n");
2863 BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
2865 } else if ((www == 2 || www == 3)
2866 && (strncmp("GET /", buf, 5) == 0)) {
2869 static const char *text =
2870 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2876 for (e = p; *e != '\0'; e++) {
2882 dot = (e[0] == '.') ? 2 : 0;
2885 dot = (e[0] == '.') ? 3 : 0;
2888 dot = (e[0] == '/') ? -1 : 0;
2892 dot = (e[0] == '/') ? 1 : 0;
2894 dot = (dot == 3) || (dot == -1); /* filename contains ".."
2899 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
2906 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
2912 BIO_printf(io, "'%s' is an invalid path\r\n", p);
2916 /* if a directory, do the index thang */
2917 if (app_isdir(p) > 0) {
2919 BIO_printf(io, "'%s' is a directory\r\n", p);
2923 if ((file = BIO_new_file(p, "r")) == NULL) {
2925 BIO_printf(io, "Error opening '%s'\r\n", p);
2926 ERR_print_errors(io);
2931 BIO_printf(bio_err, "FILE:%s\n", p);
2935 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
2936 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
2937 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
2939 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2942 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2946 i = BIO_read(file, buf, bufsize);
2952 BIO_printf(bio_err, "%d\n", i);
2953 if (total_bytes > 3 * 1024) {
2955 BIO_printf(bio_err, "RENEGOTIATE\n");
2956 SSL_renegotiate(con);
2960 for (j = 0; j < i;) {
2963 if (++count == 13) {
2964 SSL_renegotiate(con);
2967 k = BIO_write(io, &(buf[j]), i - j);
2969 if (!BIO_should_retry(io)
2970 && !SSL_waiting_for_async(con))
2973 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
2987 i = (int)BIO_flush(io);
2989 if (!BIO_should_retry(io))
2995 /* make sure we re-use sessions */
2996 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3000 BIO_printf(bio_s_out, "ACCEPT\n");
3006 static int rev_body(int s, int stype, unsigned char *context)
3012 BIO *io, *ssl_bio, *sbio;
3014 buf = app_malloc(bufsize, "server rev buffer");
3015 io = BIO_new(BIO_f_buffer());
3016 ssl_bio = BIO_new(BIO_f_ssl());
3017 if ((io == NULL) || (ssl_bio == NULL))
3020 /* lets make the output buffer a reasonable size */
3021 if (!BIO_set_write_buffer_size(io, bufsize))
3024 if ((con = SSL_new(ctx)) == NULL)
3027 if (s_tlsextdebug) {
3028 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3029 SSL_set_tlsext_debug_arg(con, bio_s_out);
3032 && !SSL_set_session_id_context(con, context,
3033 strlen((char *)context))) {
3034 ERR_print_errors(bio_err);
3038 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3039 SSL_set_bio(con, sbio, sbio);
3040 SSL_set_accept_state(con);
3042 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3043 BIO_push(io, ssl_bio);
3044 #ifdef CHARSET_EBCDIC
3045 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3049 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3050 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3053 #ifndef OPENSSL_NO_SSL_TRACE
3055 SSL_set_msg_callback(con, SSL_trace);
3058 SSL_set_msg_callback(con, msg_cb);
3059 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3063 i = BIO_do_handshake(io);
3066 if (!BIO_should_retry(io)) {
3067 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3068 ERR_print_errors(bio_err);
3071 #ifndef OPENSSL_NO_SRP
3072 if (BIO_should_io_special(io)
3073 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3074 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3075 SRP_user_pwd_free(srp_callback_parm.user);
3076 srp_callback_parm.user =
3077 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3078 srp_callback_parm.login);
3079 if (srp_callback_parm.user)
3080 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3081 srp_callback_parm.user->info);
3083 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3088 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3089 print_ssl_summary(con);
3092 i = BIO_gets(io, buf, bufsize - 1);
3093 if (i < 0) { /* error */
3094 if (!BIO_should_retry(io)) {
3096 ERR_print_errors(bio_err);
3099 BIO_printf(bio_s_out, "read R BLOCK\n");
3100 #ifndef OPENSSL_NO_SRP
3101 if (BIO_should_io_special(io)
3102 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3103 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3104 SRP_user_pwd_free(srp_callback_parm.user);
3105 srp_callback_parm.user =
3106 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3107 srp_callback_parm.login);
3108 if (srp_callback_parm.user)
3109 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3110 srp_callback_parm.user->info);
3112 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3116 #if !defined(OPENSSL_SYS_MSDOS)
3121 } else if (i == 0) { /* end of input */
3123 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3126 char *p = buf + i - 1;
3127 while (i && (*p == '\n' || *p == '\r')) {
3131 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3133 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3136 BUF_reverse((unsigned char *)buf, NULL, i);
3138 BIO_write(io, buf, i + 1);
3143 if (!BIO_should_retry(io))
3149 /* make sure we re-use sessions */
3150 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3159 #define MAX_SESSION_ID_ATTEMPTS 10
3160 static int generate_session_id(const SSL *ssl, unsigned char *id,
3161 unsigned int *id_len)
3163 unsigned int count = 0;
3165 if (RAND_bytes(id, *id_len) <= 0)
3168 * Prefix the session_id with the required prefix. NB: If our prefix
3169 * is too long, clip it - but there will be worse effects anyway, eg.
3170 * the server could only possibly create 1 session ID (ie. the
3171 * prefix!) so all future session negotiations will fail due to
3174 memcpy(id, session_id_prefix,
3175 (strlen(session_id_prefix) < *id_len) ?
3176 strlen(session_id_prefix) : *id_len);
3178 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3179 (++count < MAX_SESSION_ID_ATTEMPTS));
3180 if (count >= MAX_SESSION_ID_ATTEMPTS)
3186 * By default s_server uses an in-memory cache which caches SSL_SESSION
3187 * structures without any serialisation. This hides some bugs which only
3188 * become apparent in deployed servers. By implementing a basic external
3189 * session cache some issues can be debugged using s_server.
3192 typedef struct simple_ssl_session_st {
3197 struct simple_ssl_session_st *next;
3198 } simple_ssl_session;
3200 static simple_ssl_session *first = NULL;
3202 static int add_session(SSL *ssl, SSL_SESSION *session)
3204 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3207 SSL_SESSION_get_id(session, &sess->idlen);
3208 sess->derlen = i2d_SSL_SESSION(session, NULL);
3209 if (sess->derlen < 0) {
3210 BIO_printf(bio_err, "Error encoding session\n");
3215 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3216 sess->der = app_malloc(sess->derlen, "get session buffer");
3218 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3219 OPENSSL_free(sess->id);
3220 OPENSSL_free(sess->der);
3226 /* Assume it still works. */
3227 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3228 BIO_printf(bio_err, "Unexpected session encoding length\n");
3229 OPENSSL_free(sess->id);
3230 OPENSSL_free(sess->der);
3237 BIO_printf(bio_err, "New session added to external cache\n");
3241 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3244 simple_ssl_session *sess;
3246 for (sess = first; sess; sess = sess->next) {
3247 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3248 const unsigned char *p = sess->der;
3249 BIO_printf(bio_err, "Lookup session: cache hit\n");
3250 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3253 BIO_printf(bio_err, "Lookup session: cache miss\n");
3257 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3259 simple_ssl_session *sess, *prev = NULL;
3260 const unsigned char *id;
3262 id = SSL_SESSION_get_id(session, &idlen);
3263 for (sess = first; sess; sess = sess->next) {
3264 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3266 prev->next = sess->next;
3269 OPENSSL_free(sess->id);
3270 OPENSSL_free(sess->der);
3278 static void init_session_cache_ctx(SSL_CTX *sctx)
3280 SSL_CTX_set_session_cache_mode(sctx,
3281 SSL_SESS_CACHE_NO_INTERNAL |
3282 SSL_SESS_CACHE_SERVER);
3283 SSL_CTX_sess_set_new_cb(sctx, add_session);
3284 SSL_CTX_sess_set_get_cb(sctx, get_session);
3285 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3288 static void free_sessions(void)
3290 simple_ssl_session *sess, *tsess;
3291 for (sess = first; sess;) {
3292 OPENSSL_free(sess->id);
3293 OPENSSL_free(sess->der);
3296 OPENSSL_free(tsess);
3301 #endif /* OPENSSL_NO_SOCK */