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
46 #include <openssl/async.h>
48 #include <openssl/e_os2.h>
50 #ifndef OPENSSL_NO_SOCK
53 * With IPv6, it looks like Digital has mixed up the proper order of
54 * recursive header file inclusion, resulting in the compiler complaining
55 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
56 * needed to have fileno() declared correctly... So let's define u_int
58 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
60 typedef unsigned int u_int;
63 #include <openssl/lhash.h>
64 #include <openssl/bn.h>
67 #include <openssl/err.h>
68 #include <openssl/pem.h>
69 #include <openssl/x509.h>
70 #include <openssl/ssl.h>
71 #include <openssl/rand.h>
72 #include <openssl/ocsp.h>
74 # include <openssl/dh.h>
76 #ifndef OPENSSL_NO_RSA
77 # include <openssl/rsa.h>
79 #ifndef OPENSSL_NO_SRP
80 # include <openssl/srp.h>
85 #include <openssl/ebcdic.h>
88 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
89 static int sv_body(int s, int stype, unsigned char *context);
90 static int www_body(int s, int stype, unsigned char *context);
91 static int rev_body(int s, int stype, unsigned char *context);
92 static void close_accept_socket(void);
93 static int init_ssl_connection(SSL *s);
94 static void print_stats(BIO *bp, SSL_CTX *ctx);
95 static int generate_session_id(const SSL *ssl, unsigned char *id,
96 unsigned int *id_len);
97 static void init_session_cache_ctx(SSL_CTX *sctx);
98 static void free_sessions(void);
100 static DH *load_dh_param(const char *dhfile);
103 static void s_server_init(void);
105 /* static int load_CA(SSL_CTX *ctx, char *file);*/
108 #define BUFSIZZ 16*1024
109 static int bufsize = BUFSIZZ;
110 static int accept_socket = -1;
112 #define TEST_CERT "server.pem"
113 #define TEST_CERT2 "server2.pem"
115 extern int verify_depth, verify_return_error, verify_quiet;
117 static int s_server_verify = SSL_VERIFY_NONE;
118 static int s_server_session_id_context = 1; /* anything will do */
119 static const char *s_cert_file = TEST_CERT, *s_key_file =
120 NULL, *s_chain_file = NULL;
122 static const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
123 static char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
124 static int s_nbio = 0;
125 static int s_nbio_test = 0;
126 static int s_crlf = 0;
127 static SSL_CTX *ctx = NULL;
128 static SSL_CTX *ctx2 = NULL;
131 static BIO *bio_s_out = NULL;
132 static BIO *bio_s_msg = NULL;
133 static int s_debug = 0;
134 static int s_tlsextdebug = 0;
135 static int s_tlsextstatus = 0;
136 static int no_resume_ephemeral = 0;
137 static int s_msg = 0;
138 static int s_quiet = 0;
139 static int s_ign_eof = 0;
140 static int s_brief = 0;
142 static char *keymatexportlabel = NULL;
143 static int keymatexportlen = 20;
145 static int async = 0;
146 static unsigned int split_send_fragment = 0;
147 static unsigned int max_pipelines = 0;
149 static const char *session_id_prefix = NULL;
151 #ifndef OPENSSL_NO_DTLS
152 static int enable_timeouts = 0;
153 static long socket_mtu;
156 static int dtlslisten = 0;
158 static BIO *serverinfo_in = NULL;
159 static const char *s_serverinfo_file = NULL;
161 #ifndef OPENSSL_NO_PSK
162 static char *psk_identity = "Client_identity";
163 char *psk_key = NULL; /* by default PSK is not used */
165 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
167 unsigned int max_psk_len)
173 BIO_printf(bio_s_out, "psk_server_cb\n");
175 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
179 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
180 (int)strlen(identity), identity);
182 /* here we could lookup the given identity e.g. from a database */
183 if (strcmp(identity, psk_identity) != 0) {
184 BIO_printf(bio_s_out, "PSK error: client identity not found"
185 " (got '%s' expected '%s')\n", identity, psk_identity);
189 BIO_printf(bio_s_out, "PSK client identity found\n");
191 /* convert the PSK key to binary */
192 key = OPENSSL_hexstr2buf(psk_key, &key_len);
194 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
198 if (key_len > (int)max_psk_len) {
200 "psk buffer of callback is too small (%d) for key (%ld)\n",
201 max_psk_len, key_len);
206 memcpy(psk, key, key_len);
210 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
214 BIO_printf(bio_err, "Error in PSK server callback\n");
215 (void)BIO_flush(bio_err);
216 (void)BIO_flush(bio_s_out);
221 #ifndef OPENSSL_NO_SRP
222 /* This is a context that we pass to callbacks */
223 typedef struct srpsrvparm_st {
230 * This callback pretends to require some asynchronous logic in order to
231 * obtain a verifier. When the callback is called for a new connection we
232 * return with a negative value. This will provoke the accept etc to return
233 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
234 * (which would normally occur after a worker has finished) and we set the
237 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
239 srpsrvparm *p = (srpsrvparm *) arg;
240 int ret = SSL3_AL_FATAL;
242 if (p->login == NULL && p->user == NULL) {
243 p->login = SSL_get_srp_username(s);
244 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
248 if (p->user == NULL) {
249 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
253 if (SSL_set_srp_server_param
254 (s, p->user->N, p->user->g, p->user->s, p->user->v,
255 p->user->info) < 0) {
256 *ad = SSL_AD_INTERNAL_ERROR;
260 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
261 p->login, p->user->info);
262 ret = SSL_ERROR_NONE;
265 SRP_user_pwd_free(p->user);
273 static void s_server_init(void)
277 s_server_verify = SSL_VERIFY_NONE;
280 s_dchain_file = NULL;
281 s_cert_file = TEST_CERT;
284 s_cert_file2 = TEST_CERT2;
297 split_send_fragment = 0;
301 static int local_argc = 0;
302 static char **local_argv;
304 #ifdef CHARSET_EBCDIC
305 static int ebcdic_new(BIO *bi);
306 static int ebcdic_free(BIO *a);
307 static int ebcdic_read(BIO *b, char *out, int outl);
308 static int ebcdic_write(BIO *b, const char *in, int inl);
309 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
310 static int ebcdic_gets(BIO *bp, char *buf, int size);
311 static int ebcdic_puts(BIO *bp, const char *str);
313 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
314 static BIO_METHOD *methods_ebcdic = NULL;
316 /* This struct is "unwarranted chumminess with the compiler." */
322 static const BIO_METHOD *BIO_f_ebcdic_filter()
324 if (methods_ebcdic == NULL) {
325 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
326 "EBCDIC/ASCII filter");
327 if ( methods_ebcdic == NULL
328 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
329 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
330 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
331 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
332 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
333 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
334 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
337 return methods_ebcdic;
340 static int ebcdic_new(BIO *bi)
342 EBCDIC_OUTBUFF *wbuf;
344 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
345 wbuf->alloced = 1024;
346 wbuf->buff[0] = '\0';
348 BIO_set_data(bi, wbuf);
353 static int ebcdic_free(BIO *a)
355 EBCDIC_OUTBUFF *wbuf;
359 wbuf = BIO_get_data(a);
361 BIO_set_data(a, NULL);
367 static int ebcdic_read(BIO *b, char *out, int outl)
370 BIO *next = BIO_next(b);
372 if (out == NULL || outl == 0)
377 ret = BIO_read(next, out, outl);
379 ascii2ebcdic(out, out, ret);
383 static int ebcdic_write(BIO *b, const char *in, int inl)
385 EBCDIC_OUTBUFF *wbuf;
386 BIO *next = BIO_next(b);
390 if ((in == NULL) || (inl <= 0))
395 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
397 if (inl > (num = wbuf->alloced)) {
398 num = num + num; /* double the size */
402 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
405 wbuf->buff[0] = '\0';
407 BIO_set_data(b, wbuf);
410 ebcdic2ascii(wbuf->buff, in, inl);
412 ret = BIO_write(next, wbuf->buff, inl);
417 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
420 BIO *next = BIO_next(b);
429 ret = BIO_ctrl(next, cmd, num, ptr);
435 static int ebcdic_gets(BIO *bp, char *buf, int size)
438 BIO *next = BIO_next(bp);
442 /* return(BIO_gets(bp->next_bio,buf,size));*/
443 for (i = 0; i < size - 1; ++i) {
444 ret = ebcdic_read(bp, &buf[i], 1);
447 else if (buf[i] == '\n') {
454 return (ret < 0 && i == 0) ? ret : i;
457 static int ebcdic_puts(BIO *bp, const char *str)
459 if (BIO_next(bp) == NULL)
461 return ebcdic_write(bp, str, strlen(str));
465 /* This is a context that we pass to callbacks */
466 typedef struct tlsextctx_st {
472 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
474 tlsextctx *p = (tlsextctx *) arg;
475 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
476 if (servername && p->biodebug)
477 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
481 return SSL_TLSEXT_ERR_NOACK;
484 if (strcasecmp(servername, p->servername))
485 return p->extension_error;
487 BIO_printf(p->biodebug, "Switching server context.\n");
488 SSL_set_SSL_CTX(s, ctx2);
491 return SSL_TLSEXT_ERR_OK;
494 /* Structure passed to cert status callback */
496 typedef struct tlsextstatusctx_st {
497 /* Default responder to use */
498 char *host, *path, *port;
504 static tlsextstatusctx tlscstatp = { NULL, NULL, NULL, 0, -1, 0 };
506 #ifndef OPENSSL_NO_OCSP
508 * Certificate Status callback. This is called when a client includes a
509 * certificate status request extension. This is a simplified version. It
510 * examines certificates each time and makes one OCSP responder query for
511 * each request. A full version would store details such as the OCSP
512 * certificate IDs and minimise the number of OCSP responses by caching them
513 * until they were considered "expired".
516 static int cert_status_cb(SSL *s, void *arg)
518 tlsextstatusctx *srctx = arg;
519 char *host = NULL, *port = NULL, *path = NULL;
521 unsigned char *rspder = NULL;
523 STACK_OF(OPENSSL_STRING) *aia = NULL;
525 X509_STORE_CTX *inctx = NULL;
527 OCSP_REQUEST *req = NULL;
528 OCSP_RESPONSE *resp = NULL;
529 OCSP_CERTID *id = NULL;
530 STACK_OF(X509_EXTENSION) *exts;
531 int ret = SSL_TLSEXT_ERR_NOACK;
535 BIO_puts(bio_err, "cert_status: callback called\n");
536 /* Build up OCSP query from server certificate */
537 x = SSL_get_certificate(s);
538 aia = X509_get1_ocsp(x);
540 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
541 &host, &port, &path, &use_ssl)) {
542 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
546 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
547 sk_OPENSSL_STRING_value(aia, 0));
551 "cert_status: no AIA and no default responder URL\n");
557 use_ssl = srctx->use_ssl;
560 inctx = X509_STORE_CTX_new();
563 if (!X509_STORE_CTX_init(inctx,
564 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
567 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
568 X509_get_issuer_name(x));
570 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
573 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
574 X509_OBJECT_free(obj);
577 req = OCSP_REQUEST_new();
580 if (!OCSP_request_add0_id(req, id))
583 /* Add any extensions to the request */
584 SSL_get_tlsext_status_exts(s, &exts);
585 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
586 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
587 if (!OCSP_REQUEST_add_ext(req, ext, -1))
590 resp = process_responder(req, host, path, port, use_ssl, NULL,
593 BIO_puts(bio_err, "cert_status: error querying responder\n");
596 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
599 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
600 if (srctx->verbose) {
601 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
602 OCSP_RESPONSE_print(bio_err, resp, 2);
604 ret = SSL_TLSEXT_ERR_OK;
608 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
610 if (ret != SSL_TLSEXT_ERR_OK)
611 ERR_print_errors(bio_err);
616 X509_email_free(aia);
618 OCSP_CERTID_free(id);
619 OCSP_REQUEST_free(req);
620 OCSP_RESPONSE_free(resp);
621 X509_STORE_CTX_free(inctx);
626 #ifndef OPENSSL_NO_NEXTPROTONEG
627 /* This is the context that we pass to next_proto_cb */
628 typedef struct tlsextnextprotoctx_st {
631 } tlsextnextprotoctx;
633 static int next_proto_cb(SSL *s, const unsigned char **data,
634 unsigned int *len, void *arg)
636 tlsextnextprotoctx *next_proto = arg;
638 *data = next_proto->data;
639 *len = next_proto->len;
641 return SSL_TLSEXT_ERR_OK;
643 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
645 /* This the context that we pass to alpn_cb */
646 typedef struct tlsextalpnctx_st {
651 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
652 const unsigned char *in, unsigned int inlen, void *arg)
654 tlsextalpnctx *alpn_ctx = arg;
657 /* We can assume that |in| is syntactically valid. */
659 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
660 for (i = 0; i < inlen;) {
662 BIO_write(bio_s_out, ", ", 2);
663 BIO_write(bio_s_out, &in[i + 1], in[i]);
666 BIO_write(bio_s_out, "\n", 1);
669 if (SSL_select_next_proto
670 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
671 inlen) != OPENSSL_NPN_NEGOTIATED) {
672 return SSL_TLSEXT_ERR_NOACK;
676 BIO_printf(bio_s_out, "ALPN protocols selected: ");
677 BIO_write(bio_s_out, *out, *outlen);
678 BIO_write(bio_s_out, "\n", 1);
681 return SSL_TLSEXT_ERR_OK;
684 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
686 /* disable resumption for sessions with forward secure ciphers */
687 return is_forward_secure;
690 #ifndef OPENSSL_NO_SRP
691 static srpsrvparm srp_callback_parm;
693 #ifndef OPENSSL_NO_SRTP
694 static char *srtp_profiles = NULL;
697 typedef enum OPTION_choice {
698 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
699 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
700 OPT_VERIFY, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
701 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
702 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
703 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
704 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
705 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
706 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
707 OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
708 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
709 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_MSG, OPT_MSGFILE, OPT_TRACE,
710 OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF,
711 OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
712 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
713 OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC,
714 OPT_SSL_CONFIG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
715 OPT_SSL3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
716 OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN,
717 OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
718 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN,
719 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
725 OPTIONS s_server_options[] = {
726 {"help", OPT_HELP, '-', "Display this summary"},
727 {"port", OPT_PORT, 'p',
728 "TCP/IP port to listen on for connections (default is " PORT ")"},
729 {"accept", OPT_ACCEPT, 's',
730 "TCP/IP optional host and port to accept on (default is " PORT ")"},
732 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
734 {"4", OPT_4, '-', "Use IPv4 only"},
735 {"6", OPT_6, '-', "Use IPv6 only"},
737 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
739 {"context", OPT_CONTEXT, 's', "Set session ID context"},
740 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
741 {"Verify", OPT_UPPER_V_VERIFY, 'n',
742 "Turn on peer certificate verification, must have a cert"},
743 {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
744 {"naccept", OPT_NACCEPT, 'p', "Terminate after pnum connections"},
745 {"serverinfo", OPT_SERVERINFO, 's',
746 "PEM serverinfo file for certificate"},
747 {"certform", OPT_CERTFORM, 'F',
748 "Certificate format (PEM or DER) PEM default"},
749 {"key", OPT_KEY, '<',
750 "Private Key if not in -cert; default is " TEST_CERT},
751 {"keyform", OPT_KEYFORM, 'f',
752 "Key format (PEM, DER or ENGINE) PEM default"},
753 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
754 {"dcert", OPT_DCERT, '<',
755 "Second certificate file to use (usually for DSA)"},
756 {"dcertform", OPT_DCERTFORM, 'F',
757 "Second certificate format (PEM or DER) PEM default"},
758 {"dkey", OPT_DKEY, '<',
759 "Second private key file to use (usually for DSA)"},
760 {"dkeyform", OPT_DKEYFORM, 'F',
761 "Second key format (PEM, DER or ENGINE) PEM default"},
762 {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
763 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
764 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
765 {"debug", OPT_DEBUG, '-', "Print more output"},
766 {"msg", OPT_MSG, '-', "Show protocol messages"},
767 {"msgfile", OPT_MSGFILE, '>',
768 "File to send output of -msg or -trace, instead of stdout"},
769 {"state", OPT_STATE, '-', "Print the SSL states"},
770 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
771 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
772 {"no-CAfile", OPT_NOCAFILE, '-',
773 "Do not load the default certificates file"},
774 {"no-CApath", OPT_NOCAPATH, '-',
775 "Do not load certificates from the default certificates directory"},
776 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
777 {"quiet", OPT_QUIET, '-', "No server output"},
778 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
779 "Disable caching and tickets if ephemeral (EC)DH is used"},
780 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
781 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
782 {"servername", OPT_SERVERNAME, 's',
783 "Servername for HostName TLS extension"},
784 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
785 "mismatch send fatal alert (default warning alert)"},
786 {"cert2", OPT_CERT2, '<',
787 "Certificate file to use for servername; default is" TEST_CERT2},
788 {"key2", OPT_KEY2, '<',
789 "-Private Key file to use for servername if not in -cert2"},
790 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
791 "Hex dump of all TLS extensions received"},
792 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path incluedes HTTP headers"},
793 {"id_prefix", OPT_ID_PREFIX, 's',
794 "Generate SSL/TLS session IDs prefixed by arg"},
795 {"rand", OPT_RAND, 's',
796 "Load the file(s) into the random number generator"},
797 {"keymatexport", OPT_KEYMATEXPORT, 's',
798 "Export keying material using label"},
799 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
800 "Export len bytes of keying material (default 20)"},
801 {"CRL", OPT_CRL, '<', "CRL file to use"},
802 {"crl_download", OPT_CRL_DOWNLOAD, '-',
803 "Download CRL from distribution points"},
804 {"cert_chain", OPT_CERT_CHAIN, '<',
805 "certificate chain file in PEM format"},
806 {"dcert_chain", OPT_DCERT_CHAIN, '<',
807 "second certificate chain file in PEM format"},
808 {"chainCApath", OPT_CHAINCAPATH, '/',
809 "use dir as certificate store path to build CA certificate chain"},
810 {"verifyCApath", OPT_VERIFYCAPATH, '/',
811 "use dir as certificate store path to verify CA certificate"},
812 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
813 {"ext_cache", OPT_EXT_CACHE, '-',
814 "Disable internal cache, setup and use external cache"},
815 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default" },
816 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
817 "Close connection on verification error"},
818 {"verify_quiet", OPT_VERIFY_QUIET, '-',
819 "No verify output except verify errors"},
820 {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
821 {"chainCAfile", OPT_CHAINCAFILE, '<',
822 "CA file for certificate chain (PEM format)"},
823 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
824 "CA file for certificate verification (PEM format)"},
825 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
826 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
827 #ifndef OPENSSL_NO_OCSP
828 {"status", OPT_STATUS, '-', "Request certificate status from server"},
829 {"status_verbose", OPT_STATUS_VERBOSE, '-',
830 "Print more output in certificate status callback"},
831 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
832 "Status request responder timeout"},
833 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
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_DTLS
881 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
882 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
883 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
884 {"listen", OPT_LISTEN, '-',
885 "Listen for a DTLS ClientHello with a cookie and then connect"},
887 #ifndef OPENSSL_NO_DTLS1
888 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
890 #ifndef OPENSSL_NO_DTLS1_2
891 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
893 #ifndef OPENSSL_NO_DH
894 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
896 #ifndef OPENSSL_NO_NEXTPROTONEG
897 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
898 "Set the advertised protocols for the NPN extension (comma-separated list)"},
900 #ifndef OPENSSL_NO_SRTP
901 {"use_srtp", OPT_SRTP_PROFILES, 's',
902 "Offer SRTP key management with a colon-separated profile list"},
904 {"alpn", OPT_ALPN, 's',
905 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
906 #ifndef OPENSSL_NO_ENGINE
907 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
909 {NULL, OPT_EOF, 0, NULL}
912 #define IS_PROT_FLAG(o) \
913 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
914 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
916 int s_server_main(int argc, char *argv[])
918 ENGINE *engine = NULL;
919 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
920 SSL_CONF_CTX *cctx = NULL;
921 const SSL_METHOD *meth = TLS_server_method();
922 SSL_EXCERT *exc = NULL;
923 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
924 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
925 STACK_OF(X509_CRL) *crls = NULL;
926 X509 *s_cert = NULL, *s_dcert = NULL;
927 X509_VERIFY_PARAM *vpm = NULL;
928 char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
929 #ifndef OPENSSL_NO_DH
932 char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
933 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
934 char *crl_file = NULL, *prog;
935 #ifndef OPENSSL_NO_PSK
939 int unlink_unix_path = 0;
941 do_server_cb server_cb;
942 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
943 #ifndef OPENSSL_NO_DH
946 int nocert = 0, ret = 1;
947 int noCApath = 0, noCAfile = 0;
948 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
949 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
950 int rev = 0, naccept = -1, sdebug = 0;
951 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM;
952 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
954 char *port = BUF_strdup(PORT);
955 unsigned char *context = NULL;
957 EVP_PKEY *s_key2 = NULL;
958 X509 *s_cert2 = NULL;
959 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
960 const char *ssl_config = NULL;
961 int read_buf_len = 0;
962 #ifndef OPENSSL_NO_NEXTPROTONEG
963 const char *next_proto_neg_in = NULL;
964 tlsextnextprotoctx next_proto = { NULL, 0 };
966 const char *alpn_in = NULL;
967 tlsextalpnctx alpn_ctx = { NULL, 0 };
968 #ifndef OPENSSL_NO_PSK
969 /* by default do not send a PSK identity hint */
970 static char *psk_identity_hint = NULL;
972 #ifndef OPENSSL_NO_SRP
973 char *srpuserseed = NULL;
974 char *srp_verifier_file = NULL;
976 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
982 cctx = SSL_CONF_CTX_new();
983 vpm = X509_VERIFY_PARAM_new();
984 if (cctx == NULL || vpm == NULL)
986 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
988 prog = opt_init(argc, argv, s_server_options);
989 while ((o = opt_next()) != OPT_EOF) {
990 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
991 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
994 if (IS_NO_PROT_FLAG(o))
996 if (prot_opt == 1 && no_prot_opt) {
997 BIO_printf(bio_err, "Cannot supply both a protocol flag and "
1005 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1008 opt_help(s_server_options);
1014 if (socket_family == AF_UNIX) {
1015 OPENSSL_free(host); host = NULL;
1016 OPENSSL_free(port); port = NULL;
1019 socket_family = AF_INET;
1025 if (socket_family == AF_UNIX) {
1026 OPENSSL_free(host); host = NULL;
1027 OPENSSL_free(port); port = NULL;
1030 socket_family = AF_INET6;
1033 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1039 if (socket_family == AF_UNIX) {
1040 socket_family = AF_UNSPEC;
1043 OPENSSL_free(port); port = NULL;
1044 OPENSSL_free(host); host = NULL;
1045 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1047 "%s: -port argument malformed or ambiguous\n",
1054 if (socket_family == AF_UNIX) {
1055 socket_family = AF_UNSPEC;
1058 OPENSSL_free(port); port = NULL;
1059 OPENSSL_free(host); host = NULL;
1060 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1062 "%s: -accept argument malformed or ambiguous\n",
1069 socket_family = AF_UNIX;
1070 OPENSSL_free(host); host = BUF_strdup(opt_arg());
1071 OPENSSL_free(port); port = NULL;
1074 unlink_unix_path = 1;
1078 naccept = atol(opt_arg());
1081 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1082 verify_depth = atoi(opt_arg());
1084 BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
1086 case OPT_UPPER_V_VERIFY:
1088 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1089 SSL_VERIFY_CLIENT_ONCE;
1090 verify_depth = atoi(opt_arg());
1093 "verify depth is %d, must return a certificate\n",
1097 context = (unsigned char *)opt_arg();
1100 s_cert_file = opt_arg();
1103 crl_file = opt_arg();
1105 case OPT_CRL_DOWNLOAD:
1108 case OPT_SERVERINFO:
1109 s_serverinfo_file = opt_arg();
1112 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1116 s_key_file = opt_arg();
1119 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1123 passarg = opt_arg();
1125 case OPT_CERT_CHAIN:
1126 s_chain_file = opt_arg();
1129 #ifndef OPENSSL_NO_DH
1134 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1138 s_dcert_file = opt_arg();
1141 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1145 dpassarg = opt_arg();
1148 s_dkey_file = opt_arg();
1150 case OPT_DCERT_CHAIN:
1151 s_dchain_file = opt_arg();
1162 case OPT_CHAINCAPATH:
1163 chCApath = opt_arg();
1165 case OPT_VERIFYCAPATH:
1166 vfyCApath = opt_arg();
1175 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1179 if (ssl_args == NULL)
1180 ssl_args = sk_OPENSSL_STRING_new_null();
1181 if (ssl_args == NULL
1182 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1183 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1184 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1189 if (!opt_verify(o, vpm))
1194 if (!args_excert(o, &exc))
1197 case OPT_VERIFY_RET_ERROR:
1198 verify_return_error = 1;
1200 case OPT_VERIFY_QUIET:
1203 case OPT_BUILD_CHAIN:
1212 case OPT_CHAINCAFILE:
1213 chCAfile = opt_arg();
1215 case OPT_VERIFYCAFILE:
1216 vfyCAfile = opt_arg();
1222 s_nbio = s_nbio_test = 1;
1227 case OPT_NO_IGN_EOF:
1233 case OPT_TLSEXTDEBUG:
1239 case OPT_STATUS_VERBOSE:
1240 s_tlsextstatus = tlscstatp.verbose = 1;
1242 case OPT_STATUS_TIMEOUT:
1244 tlscstatp.timeout = atoi(opt_arg());
1246 case OPT_STATUS_URL:
1247 #ifndef OPENSSL_NO_OCSP
1249 if (!OCSP_parse_url(opt_arg(),
1252 &tlscstatp.path, &tlscstatp.use_ssl)) {
1253 BIO_printf(bio_err, "Error parsing URL\n");
1262 bio_s_msg = BIO_new_file(opt_arg(), "w");
1265 #ifndef OPENSSL_NO_SSL_TRACE
1269 case OPT_SECURITY_DEBUG:
1272 case OPT_SECURITY_DEBUG_VERBOSE:
1285 s_quiet = s_brief = verify_quiet = 1;
1288 #ifndef OPENSSL_NO_DH
1292 case OPT_NO_RESUME_EPHEMERAL:
1293 no_resume_ephemeral = 1;
1296 #ifndef OPENSSL_NO_PSK
1297 psk_identity_hint = opt_arg();
1301 #ifndef OPENSSL_NO_PSK
1302 for (p = psk_key = opt_arg(); *p; p++) {
1303 if (isxdigit(_UC(*p)))
1305 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1311 #ifndef OPENSSL_NO_SRP
1312 srp_verifier_file = opt_arg();
1313 if (min_version < TLS1_VERSION)
1314 min_version = TLS1_VERSION;
1317 case OPT_SRPUSERSEED:
1318 #ifndef OPENSSL_NO_SRP
1319 srpuserseed = opt_arg();
1320 if (min_version < TLS1_VERSION)
1321 min_version = TLS1_VERSION;
1336 case OPT_SSL_CONFIG:
1337 ssl_config = opt_arg();
1340 min_version = SSL3_VERSION;
1341 max_version = SSL3_VERSION;
1344 min_version = TLS1_2_VERSION;
1345 max_version = TLS1_2_VERSION;
1348 min_version = TLS1_1_VERSION;
1349 max_version = TLS1_1_VERSION;
1352 min_version = TLS1_VERSION;
1353 max_version = TLS1_VERSION;
1356 #ifndef OPENSSL_NO_DTLS
1357 meth = DTLS_server_method();
1358 socket_type = SOCK_DGRAM;
1362 #ifndef OPENSSL_NO_DTLS
1363 meth = DTLS_server_method();
1364 min_version = DTLS1_VERSION;
1365 max_version = DTLS1_VERSION;
1366 socket_type = SOCK_DGRAM;
1370 #ifndef OPENSSL_NO_DTLS
1371 meth = DTLS_server_method();
1372 min_version = DTLS1_2_VERSION;
1373 max_version = DTLS1_2_VERSION;
1374 socket_type = SOCK_DGRAM;
1378 #ifndef OPENSSL_NO_DTLS
1379 enable_timeouts = 1;
1383 #ifndef OPENSSL_NO_DTLS
1384 socket_mtu = atol(opt_arg());
1388 #ifndef OPENSSL_NO_DTLS
1393 session_id_prefix = opt_arg();
1396 engine = setup_engine(opt_arg(), 1);
1401 case OPT_SERVERNAME:
1402 tlsextcbp.servername = opt_arg();
1404 case OPT_SERVERNAME_FATAL:
1405 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1408 s_cert_file2 = opt_arg();
1411 s_key_file2 = opt_arg();
1413 case OPT_NEXTPROTONEG:
1414 # ifndef OPENSSL_NO_NEXTPROTONEG
1415 next_proto_neg_in = opt_arg();
1419 alpn_in = opt_arg();
1421 case OPT_SRTP_PROFILES:
1422 #ifndef OPENSSL_NO_SRTP
1423 srtp_profiles = opt_arg();
1426 case OPT_KEYMATEXPORT:
1427 keymatexportlabel = opt_arg();
1429 case OPT_KEYMATEXPORTLEN:
1430 keymatexportlen = atoi(opt_arg());
1435 case OPT_SPLIT_SEND_FRAG:
1436 split_send_fragment = atoi(opt_arg());
1437 if (split_send_fragment == 0) {
1439 * Not allowed - set to a deliberately bad value so we get an
1440 * error message below
1442 split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1;
1445 case OPT_MAX_PIPELINES:
1446 max_pipelines = atoi(opt_arg());
1449 read_buf_len = atoi(opt_arg());
1454 argc = opt_num_rest();
1457 #ifndef OPENSSL_NO_DTLS
1458 if (www && socket_type == SOCK_DGRAM) {
1459 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1463 if (dtlslisten && socket_type != SOCK_DGRAM) {
1464 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1470 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1472 "Can't use unix sockets and datagrams together\n");
1477 if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1478 BIO_printf(bio_err, "Bad split send fragment size\n");
1482 if (max_pipelines > SSL_MAX_PIPELINES) {
1483 BIO_printf(bio_err, "Bad max pipelines value\n");
1487 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1488 BIO_printf(bio_err, "Error getting password\n");
1492 if (s_key_file == NULL)
1493 s_key_file = s_cert_file;
1495 if (s_key_file2 == NULL)
1496 s_key_file2 = s_cert_file2;
1498 if (!load_excert(&exc))
1502 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1503 "server certificate private key file");
1505 ERR_print_errors(bio_err);
1509 s_cert = load_cert(s_cert_file, s_cert_format,
1510 "server certificate file");
1513 ERR_print_errors(bio_err);
1517 if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1518 "server certificate chain"))
1522 if (tlsextcbp.servername) {
1523 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1524 "second server certificate private key file");
1526 ERR_print_errors(bio_err);
1530 s_cert2 = load_cert(s_cert_file2, s_cert_format,
1531 "second server certificate file");
1534 ERR_print_errors(bio_err);
1539 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1540 if (next_proto_neg_in) {
1542 next_proto.data = next_protos_parse(&len, next_proto_neg_in);
1543 if (next_proto.data == NULL)
1545 next_proto.len = len;
1547 next_proto.data = NULL;
1550 alpn_ctx.data = NULL;
1553 alpn_ctx.data = next_protos_parse(&len, alpn_in);
1554 if (alpn_ctx.data == NULL)
1561 crl = load_crl(crl_file, crl_format);
1563 BIO_puts(bio_err, "Error loading CRL\n");
1564 ERR_print_errors(bio_err);
1567 crls = sk_X509_CRL_new_null();
1568 if (!crls || !sk_X509_CRL_push(crls, crl)) {
1569 BIO_puts(bio_err, "Error adding CRL\n");
1570 ERR_print_errors(bio_err);
1578 if (s_dkey_file == NULL)
1579 s_dkey_file = s_dcert_file;
1581 s_dkey = load_key(s_dkey_file, s_dkey_format,
1582 0, dpass, engine, "second certificate private key file");
1584 ERR_print_errors(bio_err);
1588 s_dcert = load_cert(s_dcert_file, s_dcert_format,
1589 "second server certificate file");
1592 ERR_print_errors(bio_err);
1595 if (s_dchain_file) {
1596 if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1597 "second server certificate chain"))
1603 if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1604 && !RAND_status()) {
1606 "warning, not much extra random data, consider using the -rand option\n");
1609 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1610 app_RAND_load_files(inrand));
1612 if (bio_s_out == NULL) {
1613 if (s_quiet && !s_debug) {
1614 bio_s_out = BIO_new(BIO_s_null());
1615 if (s_msg && !bio_s_msg)
1616 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1618 if (bio_s_out == NULL)
1619 bio_s_out = dup_bio_out(FORMAT_TEXT);
1622 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1628 s_dcert_file = NULL;
1630 s_cert_file2 = NULL;
1634 ctx = SSL_CTX_new(meth);
1636 ERR_print_errors(bio_err);
1640 ssl_ctx_security_debug(ctx, sdebug);
1642 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1643 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1645 ERR_print_errors(bio_err);
1649 if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1651 if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1654 if (session_id_prefix) {
1655 if (strlen(session_id_prefix) >= 32)
1657 "warning: id_prefix is too long, only one new session will be possible\n");
1658 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1659 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1660 ERR_print_errors(bio_err);
1663 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1665 SSL_CTX_set_quiet_shutdown(ctx, 1);
1667 ssl_ctx_set_excert(ctx, exc);
1670 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1672 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1674 init_session_cache_ctx(ctx);
1676 SSL_CTX_sess_set_cache_size(ctx, 128);
1679 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1681 if (split_send_fragment > 0) {
1682 SSL_CTX_set_split_send_fragment(ctx, split_send_fragment);
1684 if (max_pipelines > 0) {
1685 SSL_CTX_set_max_pipelines(ctx, max_pipelines);
1688 if (read_buf_len > 0) {
1689 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1692 #ifndef OPENSSL_NO_SRTP
1693 if (srtp_profiles != NULL) {
1694 /* Returns 0 on success! */
1695 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1696 BIO_printf(bio_err, "Error setting SRTP profile\n");
1697 ERR_print_errors(bio_err);
1703 if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1704 ERR_print_errors(bio_err);
1707 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1708 BIO_printf(bio_err, "Error setting verify params\n");
1709 ERR_print_errors(bio_err);
1713 ssl_ctx_add_crls(ctx, crls, 0);
1714 if (!config_ctx(cctx, ssl_args, ctx))
1717 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1718 crls, crl_download)) {
1719 BIO_printf(bio_err, "Error loading store locations\n");
1720 ERR_print_errors(bio_err);
1725 ctx2 = SSL_CTX_new(meth);
1727 ERR_print_errors(bio_err);
1733 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1736 ssl_ctx_security_debug(ctx, sdebug);
1738 if (session_id_prefix) {
1739 if (strlen(session_id_prefix) >= 32)
1741 "warning: id_prefix is too long, only one new session will be possible\n");
1742 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1743 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1744 ERR_print_errors(bio_err);
1747 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1749 SSL_CTX_set_quiet_shutdown(ctx2, 1);
1751 ssl_ctx_set_excert(ctx2, exc);
1754 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1757 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1759 init_session_cache_ctx(ctx2);
1761 SSL_CTX_sess_set_cache_size(ctx2, 128);
1764 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1766 if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1768 ERR_print_errors(bio_err);
1771 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1772 BIO_printf(bio_err, "Error setting verify params\n");
1773 ERR_print_errors(bio_err);
1777 ssl_ctx_add_crls(ctx2, crls, 0);
1778 if (!config_ctx(cctx, ssl_args, ctx2))
1781 #ifndef OPENSSL_NO_NEXTPROTONEG
1782 if (next_proto.data)
1783 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1787 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1789 #ifndef OPENSSL_NO_DH
1794 dh = load_dh_param(dhfile);
1795 else if (s_cert_file)
1796 dh = load_dh_param(s_cert_file);
1799 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1801 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1803 (void)BIO_flush(bio_s_out);
1806 SSL_CTX_set_dh_auto(ctx, 1);
1807 else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1808 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1809 ERR_print_errors(bio_err);
1816 DH *dh2 = load_dh_param(s_cert_file2);
1818 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1819 (void)BIO_flush(bio_s_out);
1826 SSL_CTX_set_dh_auto(ctx2, 1);
1827 else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1828 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1829 ERR_print_errors(bio_err);
1838 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1841 if (s_serverinfo_file != NULL
1842 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1843 ERR_print_errors(bio_err);
1847 if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1850 if (s_dcert != NULL) {
1851 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1855 if (no_resume_ephemeral) {
1856 SSL_CTX_set_not_resumable_session_callback(ctx,
1857 not_resumable_sess_cb);
1860 SSL_CTX_set_not_resumable_session_callback(ctx2,
1861 not_resumable_sess_cb);
1863 #ifndef OPENSSL_NO_PSK
1864 if (psk_key != NULL) {
1866 BIO_printf(bio_s_out,
1867 "PSK key given, setting server callback\n");
1868 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1871 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1872 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1873 ERR_print_errors(bio_err);
1878 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1879 if (!SSL_CTX_set_session_id_context(ctx,
1880 (void *)&s_server_session_id_context,
1881 sizeof s_server_session_id_context)) {
1882 BIO_printf(bio_err, "error setting session id context\n");
1883 ERR_print_errors(bio_err);
1887 /* Set DTLS cookie generation and verification callbacks */
1888 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1889 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1892 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1893 if (!SSL_CTX_set_session_id_context(ctx2,
1894 (void *)&s_server_session_id_context,
1895 sizeof s_server_session_id_context)) {
1896 BIO_printf(bio_err, "error setting session id context\n");
1897 ERR_print_errors(bio_err);
1900 tlsextcbp.biodebug = bio_s_out;
1901 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1902 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1903 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1904 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1907 #ifndef OPENSSL_NO_SRP
1908 if (srp_verifier_file != NULL) {
1909 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1910 srp_callback_parm.user = NULL;
1911 srp_callback_parm.login = NULL;
1913 SRP_VBASE_init(srp_callback_parm.vb,
1914 srp_verifier_file)) != SRP_NO_ERROR) {
1916 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1917 srp_verifier_file, ret);
1920 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
1921 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
1922 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1925 if (CAfile != NULL) {
1926 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
1929 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
1931 #ifndef OPENSSL_NO_OCSP
1932 if (s_tlsextstatus) {
1933 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1934 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1936 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
1937 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
1942 BIO_printf(bio_s_out, "ACCEPT\n");
1943 (void)BIO_flush(bio_s_out);
1945 server_cb = rev_body;
1947 server_cb = www_body;
1949 server_cb = sv_body;
1951 if (socket_family == AF_UNIX
1952 && unlink_unix_path)
1955 do_server(&accept_socket, host, port, socket_family, socket_type,
1956 server_cb, context, naccept);
1957 print_stats(bio_s_out, ctx);
1962 sk_X509_CRL_pop_free(crls, X509_CRL_free);
1964 EVP_PKEY_free(s_key);
1965 EVP_PKEY_free(s_dkey);
1966 sk_X509_pop_free(s_chain, X509_free);
1967 sk_X509_pop_free(s_dchain, X509_free);
1969 OPENSSL_free(dpass);
1972 X509_VERIFY_PARAM_free(vpm);
1974 OPENSSL_free(tlscstatp.host);
1975 OPENSSL_free(tlscstatp.port);
1976 OPENSSL_free(tlscstatp.path);
1979 EVP_PKEY_free(s_key2);
1980 BIO_free(serverinfo_in);
1981 #ifndef OPENSSL_NO_NEXTPROTONEG
1982 OPENSSL_free(next_proto.data);
1984 OPENSSL_free(alpn_ctx.data);
1985 ssl_excert_free(exc);
1986 sk_OPENSSL_STRING_free(ssl_args);
1987 SSL_CONF_CTX_free(cctx);
1988 BIO_free(bio_s_out);
1990 BIO_free(bio_s_msg);
1992 #ifdef CHARSET_EBCDIC
1993 BIO_meth_free(methods_ebcdic);
1998 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2000 BIO_printf(bio, "%4ld items in the session cache\n",
2001 SSL_CTX_sess_number(ssl_ctx));
2002 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2003 SSL_CTX_sess_connect(ssl_ctx));
2004 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2005 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2006 BIO_printf(bio, "%4ld client connects that finished\n",
2007 SSL_CTX_sess_connect_good(ssl_ctx));
2008 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2009 SSL_CTX_sess_accept(ssl_ctx));
2010 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2011 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2012 BIO_printf(bio, "%4ld server accepts that finished\n",
2013 SSL_CTX_sess_accept_good(ssl_ctx));
2014 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2015 BIO_printf(bio, "%4ld session cache misses\n",
2016 SSL_CTX_sess_misses(ssl_ctx));
2017 BIO_printf(bio, "%4ld session cache timeouts\n",
2018 SSL_CTX_sess_timeouts(ssl_ctx));
2019 BIO_printf(bio, "%4ld callback cache hits\n",
2020 SSL_CTX_sess_cb_hits(ssl_ctx));
2021 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2022 SSL_CTX_sess_cache_full(ssl_ctx),
2023 SSL_CTX_sess_get_cache_size(ssl_ctx));
2026 static int sv_body(int s, int stype, unsigned char *context)
2035 struct timeval timeout;
2036 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2039 struct timeval *timeoutp;
2042 buf = app_malloc(bufsize, "server buffer");
2044 if (!BIO_socket_nbio(s, 1))
2045 ERR_print_errors(bio_err);
2047 BIO_printf(bio_err, "Turned on non blocking io\n");
2053 if (s_tlsextdebug) {
2054 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2055 SSL_set_tlsext_debug_arg(con, bio_s_out);
2059 && !SSL_set_session_id_context(con,
2060 context, strlen((char *)context))) {
2061 BIO_printf(bio_err, "Error setting session id context\n");
2066 if (!SSL_clear(con)) {
2067 BIO_printf(bio_err, "Error clearing SSL connection\n");
2071 #ifndef OPENSSL_NO_DTLS
2072 if (stype == SOCK_DGRAM) {
2074 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2076 if (enable_timeouts) {
2078 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2079 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2082 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2083 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2087 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2088 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2089 DTLS_get_link_min_mtu(con));
2094 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2095 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2096 BIO_printf(bio_err, "Failed to set MTU\n");
2102 /* want to do MTU discovery */
2103 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2105 /* turn on cookie exchange */
2106 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2109 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2114 test = BIO_new(BIO_f_nbio_test());
2115 sbio = BIO_push(test, sbio);
2118 SSL_set_bio(con, sbio, sbio);
2119 SSL_set_accept_state(con);
2120 /* SSL_set_fd(con,s); */
2123 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2124 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2127 #ifndef OPENSSL_NO_SSL_TRACE
2129 SSL_set_msg_callback(con, SSL_trace);
2132 SSL_set_msg_callback(con, msg_cb);
2133 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2136 if (s_tlsextdebug) {
2137 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2138 SSL_set_tlsext_debug_arg(con, bio_s_out);
2143 int read_from_terminal;
2144 int read_from_sslcon;
2146 read_from_terminal = 0;
2147 read_from_sslcon = SSL_has_pending(con)
2148 || (async && SSL_waiting_for_async(con));
2150 if (!read_from_sslcon) {
2152 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2153 openssl_fdset(fileno(stdin), &readfds);
2155 openssl_fdset(s, &readfds);
2157 * Note: under VMS with SOCKETSHR the second parameter is
2158 * currently of type (int *) whereas under other systems it is
2159 * (void *) if you don't have a cast it will choke the compiler:
2160 * if you do have a cast then you can either go for (int *) or
2163 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2165 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2166 * only on sockets. As a workaround we timeout the select every
2167 * second and check for any keypress. In a proper Windows
2168 * application we wouldn't do this because it is inefficient.
2172 i = select(width, (void *)&readfds, NULL, NULL, &tv);
2173 if (has_stdin_waiting())
2174 read_from_terminal = 1;
2175 if ((i < 0) || (!i && !read_from_terminal))
2178 if ((SSL_version(con) == DTLS1_VERSION) &&
2179 DTLSv1_get_timeout(con, &timeout))
2180 timeoutp = &timeout;
2184 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2186 if ((SSL_version(con) == DTLS1_VERSION)
2187 && DTLSv1_handle_timeout(con) > 0) {
2188 BIO_printf(bio_err, "TIMEOUT occurred\n");
2193 if (FD_ISSET(fileno(stdin), &readfds))
2194 read_from_terminal = 1;
2196 if (FD_ISSET(s, &readfds))
2197 read_from_sslcon = 1;
2199 if (read_from_terminal) {
2203 i = raw_read_stdin(buf, bufsize / 2);
2205 /* both loops are skipped when i <= 0 */
2206 for (j = 0; j < i; j++)
2209 for (j = i - 1; j >= 0; j--) {
2210 buf[j + lf_num] = buf[j];
2211 if (buf[j] == '\n') {
2214 buf[j + lf_num] = '\r';
2217 assert(lf_num == 0);
2219 i = raw_read_stdin(buf, bufsize);
2220 if (!s_quiet && !s_brief) {
2221 if ((i <= 0) || (buf[0] == 'Q')) {
2222 BIO_printf(bio_s_out, "DONE\n");
2223 (void)BIO_flush(bio_s_out);
2225 close_accept_socket();
2229 if ((i <= 0) || (buf[0] == 'q')) {
2230 BIO_printf(bio_s_out, "DONE\n");
2231 (void)BIO_flush(bio_s_out);
2232 if (SSL_version(con) != DTLS1_VERSION)
2235 * close_accept_socket(); ret= -11;
2239 #ifndef OPENSSL_NO_HEARTBEATS
2240 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2241 BIO_printf(bio_err, "HEARTBEATING\n");
2247 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2248 SSL_renegotiate(con);
2249 i = SSL_do_handshake(con);
2250 printf("SSL_do_handshake -> %d\n", i);
2254 * strcpy(buf,"server side RE-NEGOTIATE\n");
2257 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2259 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2261 SSL_renegotiate(con);
2262 i = SSL_do_handshake(con);
2263 printf("SSL_do_handshake -> %d\n", i);
2267 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2271 if (buf[0] == 'P') {
2272 static const char *str = "Lets print some clear text\n";
2273 BIO_write(SSL_get_wbio(con), str, strlen(str));
2275 if (buf[0] == 'S') {
2276 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2279 #ifdef CHARSET_EBCDIC
2280 ebcdic2ascii(buf, buf, i);
2284 /* should do a select for the write */
2288 if (++count == 100) {
2290 SSL_renegotiate(con);
2294 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2295 #ifndef OPENSSL_NO_SRP
2296 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2297 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2298 SRP_user_pwd_free(srp_callback_parm.user);
2299 srp_callback_parm.user =
2300 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2301 srp_callback_parm.login);
2302 if (srp_callback_parm.user)
2303 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2304 srp_callback_parm.user->info);
2306 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2307 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2310 switch (SSL_get_error(con, k)) {
2311 case SSL_ERROR_NONE:
2313 case SSL_ERROR_WANT_ASYNC:
2314 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2315 (void)BIO_flush(bio_s_out);
2316 wait_for_async(con);
2318 case SSL_ERROR_WANT_WRITE:
2319 case SSL_ERROR_WANT_READ:
2320 case SSL_ERROR_WANT_X509_LOOKUP:
2321 BIO_printf(bio_s_out, "Write BLOCK\n");
2322 (void)BIO_flush(bio_s_out);
2324 case SSL_ERROR_WANT_ASYNC_JOB:
2326 * This shouldn't ever happen in s_server. Treat as an error
2328 case SSL_ERROR_SYSCALL:
2330 BIO_printf(bio_s_out, "ERROR\n");
2331 (void)BIO_flush(bio_s_out);
2332 ERR_print_errors(bio_err);
2336 case SSL_ERROR_ZERO_RETURN:
2337 BIO_printf(bio_s_out, "DONE\n");
2338 (void)BIO_flush(bio_s_out);
2350 if (read_from_sslcon) {
2352 * init_ssl_connection handles all async events itself so if we're
2353 * waiting for async then we shouldn't go back into
2354 * init_ssl_connection
2356 if ((!async || !SSL_waiting_for_async(con))
2357 && !SSL_is_init_finished(con)) {
2358 i = init_ssl_connection(con);
2363 } else if (i == 0) {
2369 i = SSL_read(con, (char *)buf, bufsize);
2370 #ifndef OPENSSL_NO_SRP
2371 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2372 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2373 SRP_user_pwd_free(srp_callback_parm.user);
2374 srp_callback_parm.user =
2375 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2376 srp_callback_parm.login);
2377 if (srp_callback_parm.user)
2378 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2379 srp_callback_parm.user->info);
2381 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2382 i = SSL_read(con, (char *)buf, bufsize);
2385 switch (SSL_get_error(con, i)) {
2386 case SSL_ERROR_NONE:
2387 #ifdef CHARSET_EBCDIC
2388 ascii2ebcdic(buf, buf, i);
2390 raw_write_stdout(buf, (unsigned int)i);
2391 (void)BIO_flush(bio_s_out);
2392 if (SSL_has_pending(con))
2395 case SSL_ERROR_WANT_ASYNC:
2396 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2397 (void)BIO_flush(bio_s_out);
2398 wait_for_async(con);
2400 case SSL_ERROR_WANT_WRITE:
2401 case SSL_ERROR_WANT_READ:
2402 BIO_printf(bio_s_out, "Read BLOCK\n");
2403 (void)BIO_flush(bio_s_out);
2405 case SSL_ERROR_WANT_ASYNC_JOB:
2407 * This shouldn't ever happen in s_server. Treat as an error
2409 case SSL_ERROR_SYSCALL:
2411 BIO_printf(bio_s_out, "ERROR\n");
2412 (void)BIO_flush(bio_s_out);
2413 ERR_print_errors(bio_err);
2416 case SSL_ERROR_ZERO_RETURN:
2417 BIO_printf(bio_s_out, "DONE\n");
2418 (void)BIO_flush(bio_s_out);
2427 BIO_printf(bio_s_out, "shutting down SSL\n");
2428 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2431 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2432 OPENSSL_clear_free(buf, bufsize);
2434 BIO_printf(bio_s_out, "ACCEPT\n");
2435 (void)BIO_flush(bio_s_out);
2439 static void close_accept_socket(void)
2441 BIO_printf(bio_err, "shutdown accept socket\n");
2442 if (accept_socket >= 0) {
2443 BIO_closesocket(accept_socket);
2447 static int init_ssl_connection(SSL *con)
2454 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2455 const unsigned char *next_proto_neg;
2456 unsigned next_proto_neg_len;
2458 unsigned char *exportedkeymat;
2461 #ifndef OPENSSL_NO_DTLS
2463 BIO_ADDR *client = NULL;
2465 if ((client = BIO_ADDR_new()) == NULL) {
2466 BIO_printf(bio_err, "ERROR - memory\n");
2469 i = DTLSv1_listen(con, client);
2474 wbio = SSL_get_wbio(con);
2476 BIO_get_fd(wbio, &fd);
2479 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2480 BIO_printf(bio_err, "ERROR - unable to connect\n");
2481 BIO_ADDR_free(client);
2484 BIO_ADDR_free(client);
2486 i = SSL_accept(con);
2488 BIO_ADDR_free(client);
2494 i = SSL_accept(con);
2497 retry = BIO_sock_should_retry(i);
2498 #ifdef CERT_CB_TEST_RETRY
2500 while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2501 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2503 "LOOKUP from certificate callback during accept\n");
2504 i = SSL_accept(con);
2506 retry = BIO_sock_should_retry(i);
2511 #ifndef OPENSSL_NO_SRP
2512 while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2513 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2514 srp_callback_parm.login);
2515 SRP_user_pwd_free(srp_callback_parm.user);
2516 srp_callback_parm.user =
2517 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2518 srp_callback_parm.login);
2519 if (srp_callback_parm.user)
2520 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2521 srp_callback_parm.user->info);
2523 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2524 i = SSL_accept(con);
2526 retry = BIO_sock_should_retry(i);
2529 } while (i < 0 && SSL_waiting_for_async(con));
2532 if ((dtlslisten && i == 0)
2533 || (!dtlslisten && retry)) {
2534 BIO_printf(bio_s_out, "DELAY\n");
2538 BIO_printf(bio_err, "ERROR\n");
2540 verify_err = SSL_get_verify_result(con);
2541 if (verify_err != X509_V_OK) {
2542 BIO_printf(bio_err, "verify error:%s\n",
2543 X509_verify_cert_error_string(verify_err));
2545 /* Always print any error messages */
2546 ERR_print_errors(bio_err);
2551 print_ssl_summary(con);
2553 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2555 peer = SSL_get_peer_certificate(con);
2557 BIO_printf(bio_s_out, "Client certificate\n");
2558 PEM_write_bio_X509(bio_s_out, peer);
2559 X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
2560 BIO_printf(bio_s_out, "subject=%s\n", buf);
2561 X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
2562 BIO_printf(bio_s_out, "issuer=%s\n", buf);
2567 if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2568 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2569 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2570 ssl_print_sigalgs(bio_s_out, con);
2571 #ifndef OPENSSL_NO_EC
2572 ssl_print_point_formats(bio_s_out, con);
2573 ssl_print_curves(bio_s_out, con, 0);
2575 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2577 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2578 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2579 if (next_proto_neg) {
2580 BIO_printf(bio_s_out, "NEXTPROTO is ");
2581 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2582 BIO_printf(bio_s_out, "\n");
2585 #ifndef OPENSSL_NO_SRTP
2587 SRTP_PROTECTION_PROFILE *srtp_profile
2588 = SSL_get_selected_srtp_profile(con);
2591 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2592 srtp_profile->name);
2595 if (SSL_session_reused(con))
2596 BIO_printf(bio_s_out, "Reused session-id\n");
2597 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2598 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2599 if (keymatexportlabel != NULL) {
2600 BIO_printf(bio_s_out, "Keying material exporter:\n");
2601 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2602 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2603 exportedkeymat = app_malloc(keymatexportlen, "export key");
2604 if (!SSL_export_keying_material(con, exportedkeymat,
2607 strlen(keymatexportlabel),
2609 BIO_printf(bio_s_out, " Error\n");
2611 BIO_printf(bio_s_out, " Keying material: ");
2612 for (i = 0; i < keymatexportlen; i++)
2613 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2614 BIO_printf(bio_s_out, "\n");
2616 OPENSSL_free(exportedkeymat);
2619 (void)BIO_flush(bio_s_out);
2623 #ifndef OPENSSL_NO_DH
2624 static DH *load_dh_param(const char *dhfile)
2629 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2631 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2638 static int www_body(int s, int stype, unsigned char *context)
2644 const SSL_CIPHER *c;
2645 BIO *io, *ssl_bio, *sbio;
2647 int total_bytes = 0;
2652 /* Set width for a select call if needed */
2655 buf = app_malloc(bufsize, "server www buffer");
2656 io = BIO_new(BIO_f_buffer());
2657 ssl_bio = BIO_new(BIO_f_ssl());
2658 if ((io == NULL) || (ssl_bio == NULL))
2662 if (!BIO_socket_nbio(s, 1))
2663 ERR_print_errors(bio_err);
2665 BIO_printf(bio_err, "Turned on non blocking io\n");
2668 /* lets make the output buffer a reasonable size */
2669 if (!BIO_set_write_buffer_size(io, bufsize))
2672 if ((con = SSL_new(ctx)) == NULL)
2675 if (s_tlsextdebug) {
2676 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2677 SSL_set_tlsext_debug_arg(con, bio_s_out);
2680 if (context && !SSL_set_session_id_context(con, context,
2681 strlen((char *)context)))
2684 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2688 test = BIO_new(BIO_f_nbio_test());
2689 sbio = BIO_push(test, sbio);
2691 SSL_set_bio(con, sbio, sbio);
2692 SSL_set_accept_state(con);
2694 /* SSL_set_fd(con,s); */
2695 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2696 BIO_push(io, ssl_bio);
2697 #ifdef CHARSET_EBCDIC
2698 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2702 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2703 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2706 #ifndef OPENSSL_NO_SSL_TRACE
2708 SSL_set_msg_callback(con, SSL_trace);
2711 SSL_set_msg_callback(con, msg_cb);
2712 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2716 i = BIO_gets(io, buf, bufsize - 1);
2717 if (i < 0) { /* error */
2718 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2720 ERR_print_errors(bio_err);
2723 BIO_printf(bio_s_out, "read R BLOCK\n");
2724 #ifndef OPENSSL_NO_SRP
2725 if (BIO_should_io_special(io)
2726 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2727 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2728 SRP_user_pwd_free(srp_callback_parm.user);
2729 srp_callback_parm.user =
2730 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2731 srp_callback_parm.login);
2732 if (srp_callback_parm.user)
2733 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2734 srp_callback_parm.user->info);
2736 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2740 #if !defined(OPENSSL_SYS_MSDOS)
2745 } else if (i == 0) { /* end of input */
2750 /* else we have data */
2751 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2752 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2755 STACK_OF(SSL_CIPHER) *sk;
2756 static const char *space = " ";
2758 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2759 if (strncmp("GET /renegcert", buf, 14) == 0)
2761 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2763 i = SSL_renegotiate(con);
2764 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2765 /* Send the HelloRequest */
2766 i = SSL_do_handshake(con);
2768 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2769 SSL_get_error(con, i));
2770 ERR_print_errors(bio_err);
2773 /* Wait for a ClientHello to come back */
2775 openssl_fdset(s, &readfds);
2776 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2777 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2778 BIO_printf(bio_s_out, "Error waiting for client response\n");
2779 ERR_print_errors(bio_err);
2783 * We're not actually expecting any data here and we ignore
2784 * any that is sent. This is just to force the handshake that
2785 * we're expecting to come from the client. If they haven't
2786 * sent one there's not much we can do.
2788 BIO_gets(io, buf, bufsize - 1);
2792 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2793 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2794 BIO_puts(io, "<pre>\n");
2795 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2797 for (i = 0; i < local_argc; i++) {
2799 for (myp = local_argv[i]; *myp; myp++)
2802 BIO_puts(io, "<");
2805 BIO_puts(io, ">");
2808 BIO_puts(io, "&");
2811 BIO_write(io, myp, 1);
2814 BIO_write(io, " ", 1);
2819 "Secure Renegotiation IS%s supported\n",
2820 SSL_get_secure_renegotiation_support(con) ?
2824 * The following is evil and should not really be done
2826 BIO_printf(io, "Ciphers supported in s_server binary\n");
2827 sk = SSL_get_ciphers(con);
2828 j = sk_SSL_CIPHER_num(sk);
2829 for (i = 0; i < j; i++) {
2830 c = sk_SSL_CIPHER_value(sk, i);
2831 BIO_printf(io, "%-11s:%-25s ",
2832 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2833 if ((((i + 1) % 2) == 0) && (i + 1 != j))
2837 p = SSL_get_shared_ciphers(con, buf, bufsize);
2840 "---\nCiphers common between both SSL end points:\n");
2844 BIO_write(io, space, 26 - j);
2847 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
2849 BIO_write(io, p, 1);
2856 ssl_print_sigalgs(io, con);
2857 #ifndef OPENSSL_NO_EC
2858 ssl_print_curves(io, con, 0);
2860 BIO_printf(io, (SSL_session_reused(con)
2861 ? "---\nReused, " : "---\nNew, "));
2862 c = SSL_get_current_cipher(con);
2863 BIO_printf(io, "%s, Cipher is %s\n",
2864 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2865 SSL_SESSION_print(io, SSL_get_session(con));
2866 BIO_printf(io, "---\n");
2867 print_stats(io, SSL_get_SSL_CTX(con));
2868 BIO_printf(io, "---\n");
2869 peer = SSL_get_peer_certificate(con);
2871 BIO_printf(io, "Client certificate\n");
2872 X509_print(io, peer);
2873 PEM_write_bio_X509(io, peer);
2877 BIO_puts(io, "no client certificate available\n");
2878 BIO_puts(io, "</BODY></HTML>\r\n\r\n");
2880 } else if ((www == 2 || www == 3)
2881 && (strncmp("GET /", buf, 5) == 0)) {
2884 static const char *text =
2885 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2891 for (e = p; *e != '\0'; e++) {
2897 dot = (e[0] == '.') ? 2 : 0;
2900 dot = (e[0] == '.') ? 3 : 0;
2903 dot = (e[0] == '/') ? -1 : 0;
2907 dot = (e[0] == '/') ? 1 : 0;
2909 dot = (dot == 3) || (dot == -1); /* filename contains ".."
2914 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
2921 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
2927 BIO_printf(io, "'%s' is an invalid path\r\n", p);
2931 /* if a directory, do the index thang */
2932 if (app_isdir(p) > 0) {
2934 BIO_printf(io, "'%s' is a directory\r\n", p);
2938 if ((file = BIO_new_file(p, "r")) == NULL) {
2940 BIO_printf(io, "Error opening '%s'\r\n", p);
2941 ERR_print_errors(io);
2946 BIO_printf(bio_err, "FILE:%s\n", p);
2950 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
2951 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
2952 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
2954 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2957 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2961 i = BIO_read(file, buf, bufsize);
2967 BIO_printf(bio_err, "%d\n", i);
2968 if (total_bytes > 3 * 1024) {
2970 BIO_printf(bio_err, "RENEGOTIATE\n");
2971 SSL_renegotiate(con);
2975 for (j = 0; j < i;) {
2979 if (++count == 13) {
2980 SSL_renegotiate(con);
2984 k = BIO_write(io, &(buf[j]), i - j);
2986 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con))
2989 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3003 i = (int)BIO_flush(io);
3005 if (!BIO_should_retry(io))
3011 /* make sure we re-use sessions */
3012 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3016 BIO_printf(bio_s_out, "ACCEPT\n");
3022 static int rev_body(int s, int stype, unsigned char *context)
3028 BIO *io, *ssl_bio, *sbio;
3030 buf = app_malloc(bufsize, "server rev buffer");
3031 io = BIO_new(BIO_f_buffer());
3032 ssl_bio = BIO_new(BIO_f_ssl());
3033 if ((io == NULL) || (ssl_bio == NULL))
3036 /* lets make the output buffer a reasonable size */
3037 if (!BIO_set_write_buffer_size(io, bufsize))
3040 if ((con = SSL_new(ctx)) == NULL)
3043 if (s_tlsextdebug) {
3044 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3045 SSL_set_tlsext_debug_arg(con, bio_s_out);
3047 if (context && !SSL_set_session_id_context(con, context,
3048 strlen((char *)context))) {
3049 ERR_print_errors(bio_err);
3053 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3054 SSL_set_bio(con, sbio, sbio);
3055 SSL_set_accept_state(con);
3057 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3058 BIO_push(io, ssl_bio);
3059 #ifdef CHARSET_EBCDIC
3060 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3064 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3065 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3068 #ifndef OPENSSL_NO_SSL_TRACE
3070 SSL_set_msg_callback(con, SSL_trace);
3073 SSL_set_msg_callback(con, msg_cb);
3074 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3078 i = BIO_do_handshake(io);
3081 if (!BIO_should_retry(io)) {
3082 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3083 ERR_print_errors(bio_err);
3086 #ifndef OPENSSL_NO_SRP
3087 if (BIO_should_io_special(io)
3088 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3089 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3090 SRP_user_pwd_free(srp_callback_parm.user);
3091 srp_callback_parm.user =
3092 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3093 srp_callback_parm.login);
3094 if (srp_callback_parm.user)
3095 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3096 srp_callback_parm.user->info);
3098 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3103 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3104 print_ssl_summary(con);
3107 i = BIO_gets(io, buf, bufsize - 1);
3108 if (i < 0) { /* error */
3109 if (!BIO_should_retry(io)) {
3111 ERR_print_errors(bio_err);
3114 BIO_printf(bio_s_out, "read R BLOCK\n");
3115 #ifndef OPENSSL_NO_SRP
3116 if (BIO_should_io_special(io)
3117 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3118 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3119 SRP_user_pwd_free(srp_callback_parm.user);
3120 srp_callback_parm.user =
3121 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3122 srp_callback_parm.login);
3123 if (srp_callback_parm.user)
3124 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3125 srp_callback_parm.user->info);
3127 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3131 #if !defined(OPENSSL_SYS_MSDOS)
3136 } else if (i == 0) { /* end of input */
3138 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3141 char *p = buf + i - 1;
3142 while (i && (*p == '\n' || *p == '\r')) {
3146 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3148 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3151 BUF_reverse((unsigned char *)buf, NULL, i);
3153 BIO_write(io, buf, i + 1);
3158 if (!BIO_should_retry(io))
3164 /* make sure we re-use sessions */
3165 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3174 #define MAX_SESSION_ID_ATTEMPTS 10
3175 static int generate_session_id(const SSL *ssl, unsigned char *id,
3176 unsigned int *id_len)
3178 unsigned int count = 0;
3180 if (RAND_bytes(id, *id_len) <= 0)
3183 * Prefix the session_id with the required prefix. NB: If our prefix
3184 * is too long, clip it - but there will be worse effects anyway, eg.
3185 * the server could only possibly create 1 session ID (ie. the
3186 * prefix!) so all future session negotiations will fail due to
3189 memcpy(id, session_id_prefix,
3190 (strlen(session_id_prefix) < *id_len) ?
3191 strlen(session_id_prefix) : *id_len);
3193 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3194 (++count < MAX_SESSION_ID_ATTEMPTS));
3195 if (count >= MAX_SESSION_ID_ATTEMPTS)
3201 * By default s_server uses an in-memory cache which caches SSL_SESSION
3202 * structures without any serialisation. This hides some bugs which only
3203 * become apparent in deployed servers. By implementing a basic external
3204 * session cache some issues can be debugged using s_server.
3207 typedef struct simple_ssl_session_st {
3212 struct simple_ssl_session_st *next;
3213 } simple_ssl_session;
3215 static simple_ssl_session *first = NULL;
3217 static int add_session(SSL *ssl, SSL_SESSION *session)
3219 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3222 SSL_SESSION_get_id(session, &sess->idlen);
3223 sess->derlen = i2d_SSL_SESSION(session, NULL);
3224 if (sess->derlen < 0) {
3225 BIO_printf(bio_err, "Error encoding session\n");
3230 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3231 sess->der = app_malloc(sess->derlen, "get session buffer");
3233 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3234 OPENSSL_free(sess->id);
3235 OPENSSL_free(sess->der);
3241 /* Assume it still works. */
3242 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3243 BIO_printf(bio_err, "Unexpected session encoding length\n");
3244 OPENSSL_free(sess->id);
3245 OPENSSL_free(sess->der);
3252 BIO_printf(bio_err, "New session added to external cache\n");
3256 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3259 simple_ssl_session *sess;
3261 for (sess = first; sess; sess = sess->next) {
3262 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3263 const unsigned char *p = sess->der;
3264 BIO_printf(bio_err, "Lookup session: cache hit\n");
3265 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3268 BIO_printf(bio_err, "Lookup session: cache miss\n");
3272 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3274 simple_ssl_session *sess, *prev = NULL;
3275 const unsigned char *id;
3277 id = SSL_SESSION_get_id(session, &idlen);
3278 for (sess = first; sess; sess = sess->next) {
3279 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3281 prev->next = sess->next;
3284 OPENSSL_free(sess->id);
3285 OPENSSL_free(sess->der);
3293 static void init_session_cache_ctx(SSL_CTX *sctx)
3295 SSL_CTX_set_session_cache_mode(sctx,
3296 SSL_SESS_CACHE_NO_INTERNAL |
3297 SSL_SESS_CACHE_SERVER);
3298 SSL_CTX_sess_set_new_cb(sctx, add_session);
3299 SSL_CTX_sess_set_get_cb(sctx, get_session);
3300 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3303 static void free_sessions(void)
3305 simple_ssl_session *sess, *tsess;
3306 for (sess = first; sess;) {
3307 OPENSSL_free(sess->id);
3308 OPENSSL_free(sess->der);
3311 OPENSSL_free(tsess);
3316 #endif /* OPENSSL_NO_SOCK */