2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* ====================================================================
11 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12 * ECC cipher suite support in OpenSSL originally developed by
13 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
15 /* ====================================================================
16 * Copyright 2005 Nokia. All rights reserved.
18 * The portions of the attached software ("Contribution") is developed by
19 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
22 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
23 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
24 * support (see RFC 4279) to OpenSSL.
26 * No patent licenses or other rights except those expressly stated in
27 * the OpenSSL open source license shall be deemed granted or received
28 * expressly, by implication, estoppel, or otherwise.
30 * No assurances are provided by Nokia that the Contribution does not
31 * infringe the patent or other intellectual property rights of any third
32 * party or that the license provides you with all the necessary rights
33 * to make use of the Contribution.
35 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
36 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
37 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
38 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
47 /* Included before async.h to avoid some warnings */
51 #include <openssl/e_os2.h>
52 #include <openssl/async.h>
53 #include <openssl/ssl.h>
55 #ifndef OPENSSL_NO_SOCK
58 * With IPv6, it looks like Digital has mixed up the proper order of
59 * recursive header file inclusion, resulting in the compiler complaining
60 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
61 * needed to have fileno() declared correctly... So let's define u_int
63 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
65 typedef unsigned int u_int;
68 #include <openssl/lhash.h>
69 #include <openssl/bn.h>
72 #include <openssl/err.h>
73 #include <openssl/pem.h>
74 #include <openssl/x509.h>
75 #include <openssl/ssl.h>
76 #include <openssl/rand.h>
77 #include <openssl/ocsp.h>
79 # include <openssl/dh.h>
81 #ifndef OPENSSL_NO_RSA
82 # include <openssl/rsa.h>
84 #ifndef OPENSSL_NO_SRP
85 # include <openssl/srp.h>
90 #include <openssl/ebcdic.h>
93 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
94 static int sv_body(int s, int stype, unsigned char *context);
95 static int www_body(int s, int stype, unsigned char *context);
96 static int rev_body(int s, int stype, unsigned char *context);
97 static void close_accept_socket(void);
98 static int init_ssl_connection(SSL *s);
99 static void print_stats(BIO *bp, SSL_CTX *ctx);
100 static int generate_session_id(const SSL *ssl, unsigned char *id,
101 unsigned int *id_len);
102 static void init_session_cache_ctx(SSL_CTX *sctx);
103 static void free_sessions(void);
104 #ifndef OPENSSL_NO_DH
105 static DH *load_dh_param(const char *dhfile);
108 /* static int load_CA(SSL_CTX *ctx, char *file);*/
110 static const int bufsize = 16 * 1024;
111 static int accept_socket = -1;
113 #define TEST_CERT "server.pem"
114 #define TEST_CERT2 "server2.pem"
116 static int s_nbio = 0;
117 static int s_nbio_test = 0;
118 static int s_crlf = 0;
119 static SSL_CTX *ctx = NULL;
120 static SSL_CTX *ctx2 = NULL;
123 static BIO *bio_s_out = NULL;
124 static BIO *bio_s_msg = NULL;
125 static int s_debug = 0;
126 static int s_tlsextdebug = 0;
127 static int s_msg = 0;
128 static int s_quiet = 0;
129 static int s_ign_eof = 0;
130 static int s_brief = 0;
132 static char *keymatexportlabel = NULL;
133 static int keymatexportlen = 20;
135 static int async = 0;
137 static const char *session_id_prefix = NULL;
139 #ifndef OPENSSL_NO_DTLS
140 static int enable_timeouts = 0;
141 static long socket_mtu;
144 static int dtlslisten = 0;
146 #ifndef OPENSSL_NO_PSK
147 static char *psk_identity = "Client_identity";
148 char *psk_key = NULL; /* by default PSK is not used */
150 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
152 unsigned int max_psk_len)
158 BIO_printf(bio_s_out, "psk_server_cb\n");
160 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
164 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
165 (int)strlen(identity), identity);
167 /* here we could lookup the given identity e.g. from a database */
168 if (strcmp(identity, psk_identity) != 0) {
169 BIO_printf(bio_s_out, "PSK error: client identity not found"
170 " (got '%s' expected '%s')\n", identity, psk_identity);
174 BIO_printf(bio_s_out, "PSK client identity found\n");
176 /* convert the PSK key to binary */
177 key = OPENSSL_hexstr2buf(psk_key, &key_len);
179 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
183 if (key_len > (int)max_psk_len) {
185 "psk buffer of callback is too small (%d) for key (%ld)\n",
186 max_psk_len, key_len);
191 memcpy(psk, key, key_len);
195 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
199 BIO_printf(bio_err, "Error in PSK server callback\n");
200 (void)BIO_flush(bio_err);
201 (void)BIO_flush(bio_s_out);
206 #ifndef OPENSSL_NO_SRP
207 /* This is a context that we pass to callbacks */
208 typedef struct srpsrvparm_st {
215 * This callback pretends to require some asynchronous logic in order to
216 * obtain a verifier. When the callback is called for a new connection we
217 * return with a negative value. This will provoke the accept etc to return
218 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
219 * (which would normally occur after a worker has finished) and we set the
222 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
224 srpsrvparm *p = (srpsrvparm *) arg;
225 int ret = SSL3_AL_FATAL;
227 if (p->login == NULL && p->user == NULL) {
228 p->login = SSL_get_srp_username(s);
229 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
233 if (p->user == NULL) {
234 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
238 if (SSL_set_srp_server_param
239 (s, p->user->N, p->user->g, p->user->s, p->user->v,
240 p->user->info) < 0) {
241 *ad = SSL_AD_INTERNAL_ERROR;
245 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
246 p->login, p->user->info);
247 ret = SSL_ERROR_NONE;
250 SRP_user_pwd_free(p->user);
258 static int local_argc = 0;
259 static char **local_argv;
261 #ifdef CHARSET_EBCDIC
262 static int ebcdic_new(BIO *bi);
263 static int ebcdic_free(BIO *a);
264 static int ebcdic_read(BIO *b, char *out, int outl);
265 static int ebcdic_write(BIO *b, const char *in, int inl);
266 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
267 static int ebcdic_gets(BIO *bp, char *buf, int size);
268 static int ebcdic_puts(BIO *bp, const char *str);
270 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
271 static BIO_METHOD *methods_ebcdic = NULL;
273 /* This struct is "unwarranted chumminess with the compiler." */
279 static const BIO_METHOD *BIO_f_ebcdic_filter()
281 if (methods_ebcdic == NULL) {
282 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
283 "EBCDIC/ASCII filter");
284 if (methods_ebcdic == NULL
285 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
286 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
287 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
288 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
289 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
290 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
291 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
294 return methods_ebcdic;
297 static int ebcdic_new(BIO *bi)
299 EBCDIC_OUTBUFF *wbuf;
301 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
302 wbuf->alloced = 1024;
303 wbuf->buff[0] = '\0';
305 BIO_set_data(bi, wbuf);
310 static int ebcdic_free(BIO *a)
312 EBCDIC_OUTBUFF *wbuf;
316 wbuf = BIO_get_data(a);
318 BIO_set_data(a, NULL);
324 static int ebcdic_read(BIO *b, char *out, int outl)
327 BIO *next = BIO_next(b);
329 if (out == NULL || outl == 0)
334 ret = BIO_read(next, out, outl);
336 ascii2ebcdic(out, out, ret);
340 static int ebcdic_write(BIO *b, const char *in, int inl)
342 EBCDIC_OUTBUFF *wbuf;
343 BIO *next = BIO_next(b);
347 if ((in == NULL) || (inl <= 0))
352 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
354 if (inl > (num = wbuf->alloced)) {
355 num = num + num; /* double the size */
359 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
362 wbuf->buff[0] = '\0';
364 BIO_set_data(b, wbuf);
367 ebcdic2ascii(wbuf->buff, in, inl);
369 ret = BIO_write(next, wbuf->buff, inl);
374 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
377 BIO *next = BIO_next(b);
386 ret = BIO_ctrl(next, cmd, num, ptr);
392 static int ebcdic_gets(BIO *bp, char *buf, int size)
395 BIO *next = BIO_next(bp);
399 /* return(BIO_gets(bp->next_bio,buf,size));*/
400 for (i = 0; i < size - 1; ++i) {
401 ret = ebcdic_read(bp, &buf[i], 1);
404 else if (buf[i] == '\n') {
411 return (ret < 0 && i == 0) ? ret : i;
414 static int ebcdic_puts(BIO *bp, const char *str)
416 if (BIO_next(bp) == NULL)
418 return ebcdic_write(bp, str, strlen(str));
422 /* This is a context that we pass to callbacks */
423 typedef struct tlsextctx_st {
429 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
431 tlsextctx *p = (tlsextctx *) arg;
432 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
433 if (servername && p->biodebug)
434 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
438 return SSL_TLSEXT_ERR_NOACK;
441 if (strcasecmp(servername, p->servername))
442 return p->extension_error;
444 BIO_printf(p->biodebug, "Switching server context.\n");
445 SSL_set_SSL_CTX(s, ctx2);
448 return SSL_TLSEXT_ERR_OK;
451 /* Structure passed to cert status callback */
453 typedef struct tlsextstatusctx_st {
455 /* File to load OCSP Response from (or NULL if no file) */
457 /* Default responder to use */
458 char *host, *path, *port;
463 static tlsextstatusctx tlscstatp = { -1 };
465 #ifndef OPENSSL_NO_OCSP
468 * Helper function to get an OCSP_RESPONSE from a responder. This is a
469 * simplified version. It examines certificates each time and makes one OCSP
470 * responder query for each request. A full version would store details such as
471 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
472 * them until they were considered "expired".
474 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
475 OCSP_RESPONSE **resp)
477 char *host = NULL, *port = NULL, *path = NULL;
479 STACK_OF(OPENSSL_STRING) *aia = NULL;
481 X509_STORE_CTX *inctx = NULL;
483 OCSP_REQUEST *req = NULL;
484 OCSP_CERTID *id = NULL;
485 STACK_OF(X509_EXTENSION) *exts;
486 int ret = SSL_TLSEXT_ERR_NOACK;
489 /* Build up OCSP query from server certificate */
490 x = SSL_get_certificate(s);
491 aia = X509_get1_ocsp(x);
493 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
494 &host, &port, &path, &use_ssl)) {
495 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
499 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
500 sk_OPENSSL_STRING_value(aia, 0));
504 "cert_status: no AIA and no default responder URL\n");
510 use_ssl = srctx->use_ssl;
513 inctx = X509_STORE_CTX_new();
516 if (!X509_STORE_CTX_init(inctx,
517 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
520 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
521 X509_get_issuer_name(x));
523 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
526 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
527 X509_OBJECT_free(obj);
530 req = OCSP_REQUEST_new();
533 if (!OCSP_request_add0_id(req, id))
536 /* Add any extensions to the request */
537 SSL_get_tlsext_status_exts(s, &exts);
538 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
539 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
540 if (!OCSP_REQUEST_add_ext(req, ext, -1))
543 *resp = process_responder(req, host, path, port, use_ssl, NULL,
546 BIO_puts(bio_err, "cert_status: error querying responder\n");
550 ret = SSL_TLSEXT_ERR_OK;
554 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
557 * If we parsed aia we need to free; otherwise they were copied and we
564 X509_email_free(aia);
566 OCSP_CERTID_free(id);
567 OCSP_REQUEST_free(req);
568 X509_STORE_CTX_free(inctx);
573 * Certificate Status callback. This is called when a client includes a
574 * certificate status request extension. The response is either obtained from a
575 * file, or from an OCSP responder.
577 static int cert_status_cb(SSL *s, void *arg)
579 tlsextstatusctx *srctx = arg;
580 OCSP_RESPONSE *resp = NULL;
581 unsigned char *rspder = NULL;
583 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
586 BIO_puts(bio_err, "cert_status: callback called\n");
588 if (srctx->respin != NULL) {
589 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
590 if (derbio == NULL) {
591 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
594 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
597 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
601 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
602 if (ret != SSL_TLSEXT_ERR_OK)
606 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
610 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
611 if (srctx->verbose) {
612 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
613 OCSP_RESPONSE_print(bio_err, resp, 2);
616 ret = SSL_TLSEXT_ERR_OK;
619 if (ret != SSL_TLSEXT_ERR_OK)
620 ERR_print_errors(bio_err);
622 OCSP_RESPONSE_free(resp);
628 #ifndef OPENSSL_NO_NEXTPROTONEG
629 /* This is the context that we pass to next_proto_cb */
630 typedef struct tlsextnextprotoctx_st {
633 } tlsextnextprotoctx;
635 static int next_proto_cb(SSL *s, const unsigned char **data,
636 unsigned int *len, void *arg)
638 tlsextnextprotoctx *next_proto = arg;
640 *data = next_proto->data;
641 *len = next_proto->len;
643 return SSL_TLSEXT_ERR_OK;
645 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
647 /* This the context that we pass to alpn_cb */
648 typedef struct tlsextalpnctx_st {
653 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
654 const unsigned char *in, unsigned int inlen, void *arg)
656 tlsextalpnctx *alpn_ctx = arg;
659 /* We can assume that |in| is syntactically valid. */
661 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
662 for (i = 0; i < inlen;) {
664 BIO_write(bio_s_out, ", ", 2);
665 BIO_write(bio_s_out, &in[i + 1], in[i]);
668 BIO_write(bio_s_out, "\n", 1);
671 if (SSL_select_next_proto
672 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
673 inlen) != OPENSSL_NPN_NEGOTIATED) {
674 return SSL_TLSEXT_ERR_NOACK;
678 BIO_printf(bio_s_out, "ALPN protocols selected: ");
679 BIO_write(bio_s_out, *out, *outlen);
680 BIO_write(bio_s_out, "\n", 1);
683 return SSL_TLSEXT_ERR_OK;
686 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
688 /* disable resumption for sessions with forward secure ciphers */
689 return is_forward_secure;
692 #ifndef OPENSSL_NO_SRP
693 static srpsrvparm srp_callback_parm;
695 #ifndef OPENSSL_NO_SRTP
696 static char *srtp_profiles = NULL;
699 typedef enum OPTION_choice {
700 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
701 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
702 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
703 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
704 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
705 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
706 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
707 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
708 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
709 OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
710 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
711 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
712 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
713 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
714 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
715 OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC,
716 OPT_SSL_CONFIG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
717 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
718 OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN,
719 OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
720 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN,
721 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
722 OPT_KEYLOG_FILE, OPT_MAX_EARLY,
728 const OPTIONS s_server_options[] = {
729 {"help", OPT_HELP, '-', "Display this summary"},
730 {"port", OPT_PORT, 'p',
731 "TCP/IP port to listen on for connections (default is " PORT ")"},
732 {"accept", OPT_ACCEPT, 's',
733 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
735 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
737 {"4", OPT_4, '-', "Use IPv4 only"},
738 {"6", OPT_6, '-', "Use IPv6 only"},
740 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
742 {"context", OPT_CONTEXT, 's', "Set session ID context"},
743 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
744 {"Verify", OPT_UPPER_V_VERIFY, 'n',
745 "Turn on peer certificate verification, must have a cert"},
746 {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
747 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
748 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
749 {"serverinfo", OPT_SERVERINFO, 's',
750 "PEM serverinfo file for certificate"},
751 {"certform", OPT_CERTFORM, 'F',
752 "Certificate format (PEM or DER) PEM default"},
753 {"key", OPT_KEY, '<',
754 "Private Key if not in -cert; default is " TEST_CERT},
755 {"keyform", OPT_KEYFORM, 'f',
756 "Key format (PEM, DER or ENGINE) PEM default"},
757 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
758 {"dcert", OPT_DCERT, '<',
759 "Second certificate file to use (usually for DSA)"},
760 {"dcertform", OPT_DCERTFORM, 'F',
761 "Second certificate format (PEM or DER) PEM default"},
762 {"dkey", OPT_DKEY, '<',
763 "Second private key file to use (usually for DSA)"},
764 {"dkeyform", OPT_DKEYFORM, 'F',
765 "Second key format (PEM, DER or ENGINE) PEM default"},
766 {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
767 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
768 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
769 {"debug", OPT_DEBUG, '-', "Print more output"},
770 {"msg", OPT_MSG, '-', "Show protocol messages"},
771 {"msgfile", OPT_MSGFILE, '>',
772 "File to send output of -msg or -trace, instead of stdout"},
773 {"state", OPT_STATE, '-', "Print the SSL states"},
774 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
775 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
776 {"no-CAfile", OPT_NOCAFILE, '-',
777 "Do not load the default certificates file"},
778 {"no-CApath", OPT_NOCAPATH, '-',
779 "Do not load certificates from the default certificates directory"},
780 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
781 {"quiet", OPT_QUIET, '-', "No server output"},
782 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
783 "Disable caching and tickets if ephemeral (EC)DH is used"},
784 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
785 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
786 {"servername", OPT_SERVERNAME, 's',
787 "Servername for HostName TLS extension"},
788 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
789 "mismatch send fatal alert (default warning alert)"},
790 {"cert2", OPT_CERT2, '<',
791 "Certificate file to use for servername; default is" TEST_CERT2},
792 {"key2", OPT_KEY2, '<',
793 "-Private Key file to use for servername if not in -cert2"},
794 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
795 "Hex dump of all TLS extensions received"},
796 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
797 {"id_prefix", OPT_ID_PREFIX, 's',
798 "Generate SSL/TLS session IDs prefixed by arg"},
799 {"rand", OPT_RAND, 's',
800 "Load the file(s) into the random number generator"},
801 {"keymatexport", OPT_KEYMATEXPORT, 's',
802 "Export keying material using label"},
803 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
804 "Export len bytes of keying material (default 20)"},
805 {"CRL", OPT_CRL, '<', "CRL file to use"},
806 {"crl_download", OPT_CRL_DOWNLOAD, '-',
807 "Download CRL from distribution points"},
808 {"cert_chain", OPT_CERT_CHAIN, '<',
809 "certificate chain file in PEM format"},
810 {"dcert_chain", OPT_DCERT_CHAIN, '<',
811 "second certificate chain file in PEM format"},
812 {"chainCApath", OPT_CHAINCAPATH, '/',
813 "use dir as certificate store path to build CA certificate chain"},
814 {"verifyCApath", OPT_VERIFYCAPATH, '/',
815 "use dir as certificate store path to verify CA certificate"},
816 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
817 {"ext_cache", OPT_EXT_CACHE, '-',
818 "Disable internal cache, setup and use external cache"},
819 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
820 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
821 "Close connection on verification error"},
822 {"verify_quiet", OPT_VERIFY_QUIET, '-',
823 "No verify output except verify errors"},
824 {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
825 {"chainCAfile", OPT_CHAINCAFILE, '<',
826 "CA file for certificate chain (PEM format)"},
827 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
828 "CA file for certificate verification (PEM format)"},
829 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
830 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
831 #ifndef OPENSSL_NO_OCSP
832 {"status", OPT_STATUS, '-', "Request certificate status from server"},
833 {"status_verbose", OPT_STATUS_VERBOSE, '-',
834 "Print more output in certificate status callback"},
835 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
836 "Status request responder timeout"},
837 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
838 {"status_file", OPT_STATUS_FILE, '<',
839 "File containing DER encoded OCSP Response"},
841 #ifndef OPENSSL_NO_SSL_TRACE
842 {"trace", OPT_TRACE, '-', "trace protocol messages"},
844 {"security_debug", OPT_SECURITY_DEBUG, '-',
845 "Print output from SSL/TLS security framework"},
846 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
847 "Print more output from SSL/TLS security framework"},
848 {"brief", OPT_BRIEF, '-',
849 "Restrict output to brief summary of connection parameters"},
850 {"rev", OPT_REV, '-',
851 "act as a simple test server which just sends back with the received text reversed"},
852 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
853 {"ssl_config", OPT_SSL_CONFIG, 's',
854 "Configure SSL_CTX using the configuration 'val'"},
855 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'n',
856 "Size used to split data for encrypt pipelines"},
857 {"max_pipelines", OPT_MAX_PIPELINES, 'n',
858 "Maximum number of encrypt/decrypt pipelines to be used"},
859 {"read_buf", OPT_READ_BUF, 'n',
860 "Default read buffer size to be used for connections"},
864 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
865 #ifndef OPENSSL_NO_PSK
866 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
867 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
869 #ifndef OPENSSL_NO_SRP
870 {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
871 {"srpuserseed", OPT_SRPUSERSEED, 's',
872 "A seed string for a default user salt"},
874 #ifndef OPENSSL_NO_SSL3
875 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
877 #ifndef OPENSSL_NO_TLS1
878 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
880 #ifndef OPENSSL_NO_TLS1_1
881 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
883 #ifndef OPENSSL_NO_TLS1_2
884 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
886 #ifndef OPENSSL_NO_TLS1_3
887 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
889 #ifndef OPENSSL_NO_DTLS
890 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
891 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
892 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
893 {"listen", OPT_LISTEN, '-',
894 "Listen for a DTLS ClientHello with a cookie and then connect"},
896 #ifndef OPENSSL_NO_DTLS1
897 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
899 #ifndef OPENSSL_NO_DTLS1_2
900 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
902 #ifndef OPENSSL_NO_DH
903 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
905 #ifndef OPENSSL_NO_NEXTPROTONEG
906 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
907 "Set the advertised protocols for the NPN extension (comma-separated list)"},
909 #ifndef OPENSSL_NO_SRTP
910 {"use_srtp", OPT_SRTP_PROFILES, 's',
911 "Offer SRTP key management with a colon-separated profile list"},
913 {"alpn", OPT_ALPN, 's',
914 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
915 #ifndef OPENSSL_NO_ENGINE
916 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
918 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
919 {"max_early_data", OPT_MAX_EARLY, 'p',
920 "The maximum number of bytes of early data"},
921 {NULL, OPT_EOF, 0, NULL}
924 #define IS_PROT_FLAG(o) \
925 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
926 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
928 int s_server_main(int argc, char *argv[])
930 ENGINE *engine = NULL;
931 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
932 SSL_CONF_CTX *cctx = NULL;
933 const SSL_METHOD *meth = TLS_server_method();
934 SSL_EXCERT *exc = NULL;
935 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
936 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
937 STACK_OF(X509_CRL) *crls = NULL;
938 X509 *s_cert = NULL, *s_dcert = NULL;
939 X509_VERIFY_PARAM *vpm = NULL;
940 const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
941 char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
942 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
943 char *crl_file = NULL, *prog;
945 int unlink_unix_path = 0;
947 do_server_cb server_cb;
948 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
949 #ifndef OPENSSL_NO_DH
953 int nocert = 0, ret = 1;
954 int noCApath = 0, noCAfile = 0;
955 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
956 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
957 int rev = 0, naccept = -1, sdebug = 0;
958 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM;
959 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
961 char *port = BUF_strdup(PORT);
962 unsigned char *context = NULL;
964 EVP_PKEY *s_key2 = NULL;
965 X509 *s_cert2 = NULL;
966 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
967 const char *ssl_config = NULL;
968 int read_buf_len = 0;
969 #ifndef OPENSSL_NO_NEXTPROTONEG
970 const char *next_proto_neg_in = NULL;
971 tlsextnextprotoctx next_proto = { NULL, 0 };
973 const char *alpn_in = NULL;
974 tlsextalpnctx alpn_ctx = { NULL, 0 };
975 #ifndef OPENSSL_NO_PSK
976 /* by default do not send a PSK identity hint */
977 static char *psk_identity_hint = NULL;
980 #ifndef OPENSSL_NO_SRP
981 char *srpuserseed = NULL;
982 char *srp_verifier_file = NULL;
984 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
985 int s_server_verify = SSL_VERIFY_NONE;
986 int s_server_session_id_context = 1; /* anything will do */
987 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
988 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
989 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
990 #ifndef OPENSSL_NO_OCSP
991 int s_tlsextstatus = 0;
993 int no_resume_ephemeral = 0;
994 unsigned int split_send_fragment = 0, max_pipelines = 0;
995 const char *s_serverinfo_file = NULL;
996 const char *keylog_file = NULL;
997 uint32_t max_early_data = 0;
999 /* Init of few remaining global variables */
1004 s_nbio = s_nbio_test = 0;
1013 cctx = SSL_CONF_CTX_new();
1014 vpm = X509_VERIFY_PARAM_new();
1015 if (cctx == NULL || vpm == NULL)
1017 SSL_CONF_CTX_set_flags(cctx,
1018 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1020 prog = opt_init(argc, argv, s_server_options);
1021 while ((o = opt_next()) != OPT_EOF) {
1022 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1023 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1026 if (IS_NO_PROT_FLAG(o))
1028 if (prot_opt == 1 && no_prot_opt) {
1030 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1037 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1040 opt_help(s_server_options);
1046 if (socket_family == AF_UNIX) {
1047 OPENSSL_free(host); host = NULL;
1048 OPENSSL_free(port); port = NULL;
1051 socket_family = AF_INET;
1057 if (socket_family == AF_UNIX) {
1058 OPENSSL_free(host); host = NULL;
1059 OPENSSL_free(port); port = NULL;
1062 socket_family = AF_INET6;
1065 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1071 if (socket_family == AF_UNIX) {
1072 socket_family = AF_UNSPEC;
1075 OPENSSL_free(port); port = NULL;
1076 OPENSSL_free(host); host = NULL;
1077 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1079 "%s: -port argument malformed or ambiguous\n",
1086 if (socket_family == AF_UNIX) {
1087 socket_family = AF_UNSPEC;
1090 OPENSSL_free(port); port = NULL;
1091 OPENSSL_free(host); host = NULL;
1092 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1094 "%s: -accept argument malformed or ambiguous\n",
1101 socket_family = AF_UNIX;
1102 OPENSSL_free(host); host = BUF_strdup(opt_arg());
1103 OPENSSL_free(port); port = NULL;
1106 unlink_unix_path = 1;
1110 naccept = atol(opt_arg());
1113 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1114 verify_args.depth = atoi(opt_arg());
1116 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1118 case OPT_UPPER_V_VERIFY:
1120 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1121 SSL_VERIFY_CLIENT_ONCE;
1122 verify_args.depth = atoi(opt_arg());
1125 "verify depth is %d, must return a certificate\n",
1129 context = (unsigned char *)opt_arg();
1132 s_cert_file = opt_arg();
1135 if (!set_nameopt(opt_arg()))
1139 crl_file = opt_arg();
1141 case OPT_CRL_DOWNLOAD:
1144 case OPT_SERVERINFO:
1145 s_serverinfo_file = opt_arg();
1148 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1152 s_key_file = opt_arg();
1155 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1159 passarg = opt_arg();
1161 case OPT_CERT_CHAIN:
1162 s_chain_file = opt_arg();
1165 #ifndef OPENSSL_NO_DH
1170 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1174 s_dcert_file = opt_arg();
1177 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1181 dpassarg = opt_arg();
1184 s_dkey_file = opt_arg();
1186 case OPT_DCERT_CHAIN:
1187 s_dchain_file = opt_arg();
1198 case OPT_CHAINCAPATH:
1199 chCApath = opt_arg();
1201 case OPT_VERIFYCAPATH:
1202 vfyCApath = opt_arg();
1211 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1215 if (ssl_args == NULL)
1216 ssl_args = sk_OPENSSL_STRING_new_null();
1217 if (ssl_args == NULL
1218 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1219 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1220 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1225 if (!opt_verify(o, vpm))
1230 if (!args_excert(o, &exc))
1233 case OPT_VERIFY_RET_ERROR:
1234 verify_args.return_error = 1;
1236 case OPT_VERIFY_QUIET:
1237 verify_args.quiet = 1;
1239 case OPT_BUILD_CHAIN:
1248 case OPT_CHAINCAFILE:
1249 chCAfile = opt_arg();
1251 case OPT_VERIFYCAFILE:
1252 vfyCAfile = opt_arg();
1258 s_nbio = s_nbio_test = 1;
1263 case OPT_NO_IGN_EOF:
1269 case OPT_TLSEXTDEBUG:
1273 #ifndef OPENSSL_NO_OCSP
1277 case OPT_STATUS_VERBOSE:
1278 #ifndef OPENSSL_NO_OCSP
1279 s_tlsextstatus = tlscstatp.verbose = 1;
1282 case OPT_STATUS_TIMEOUT:
1283 #ifndef OPENSSL_NO_OCSP
1285 tlscstatp.timeout = atoi(opt_arg());
1288 case OPT_STATUS_URL:
1289 #ifndef OPENSSL_NO_OCSP
1291 if (!OCSP_parse_url(opt_arg(),
1294 &tlscstatp.path, &tlscstatp.use_ssl)) {
1295 BIO_printf(bio_err, "Error parsing URL\n");
1300 case OPT_STATUS_FILE:
1301 #ifndef OPENSSL_NO_OCSP
1303 tlscstatp.respin = opt_arg();
1310 bio_s_msg = BIO_new_file(opt_arg(), "w");
1313 #ifndef OPENSSL_NO_SSL_TRACE
1317 case OPT_SECURITY_DEBUG:
1320 case OPT_SECURITY_DEBUG_VERBOSE:
1333 s_quiet = s_brief = verify_args.quiet = 1;
1336 #ifndef OPENSSL_NO_DH
1340 case OPT_NO_RESUME_EPHEMERAL:
1341 no_resume_ephemeral = 1;
1344 #ifndef OPENSSL_NO_PSK
1345 psk_identity_hint = opt_arg();
1349 #ifndef OPENSSL_NO_PSK
1350 for (p = psk_key = opt_arg(); *p; p++) {
1351 if (isxdigit(_UC(*p)))
1353 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1359 #ifndef OPENSSL_NO_SRP
1360 srp_verifier_file = opt_arg();
1361 if (min_version < TLS1_VERSION)
1362 min_version = TLS1_VERSION;
1365 case OPT_SRPUSERSEED:
1366 #ifndef OPENSSL_NO_SRP
1367 srpuserseed = opt_arg();
1368 if (min_version < TLS1_VERSION)
1369 min_version = TLS1_VERSION;
1384 case OPT_SSL_CONFIG:
1385 ssl_config = opt_arg();
1388 min_version = SSL3_VERSION;
1389 max_version = SSL3_VERSION;
1392 min_version = TLS1_3_VERSION;
1393 max_version = TLS1_3_VERSION;
1396 min_version = TLS1_2_VERSION;
1397 max_version = TLS1_2_VERSION;
1400 min_version = TLS1_1_VERSION;
1401 max_version = TLS1_1_VERSION;
1404 min_version = TLS1_VERSION;
1405 max_version = TLS1_VERSION;
1408 #ifndef OPENSSL_NO_DTLS
1409 meth = DTLS_server_method();
1410 socket_type = SOCK_DGRAM;
1414 #ifndef OPENSSL_NO_DTLS
1415 meth = DTLS_server_method();
1416 min_version = DTLS1_VERSION;
1417 max_version = DTLS1_VERSION;
1418 socket_type = SOCK_DGRAM;
1422 #ifndef OPENSSL_NO_DTLS
1423 meth = DTLS_server_method();
1424 min_version = DTLS1_2_VERSION;
1425 max_version = DTLS1_2_VERSION;
1426 socket_type = SOCK_DGRAM;
1430 #ifndef OPENSSL_NO_DTLS
1431 enable_timeouts = 1;
1435 #ifndef OPENSSL_NO_DTLS
1436 socket_mtu = atol(opt_arg());
1440 #ifndef OPENSSL_NO_DTLS
1445 session_id_prefix = opt_arg();
1448 engine = setup_engine(opt_arg(), 1);
1453 case OPT_SERVERNAME:
1454 tlsextcbp.servername = opt_arg();
1456 case OPT_SERVERNAME_FATAL:
1457 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1460 s_cert_file2 = opt_arg();
1463 s_key_file2 = opt_arg();
1465 case OPT_NEXTPROTONEG:
1466 # ifndef OPENSSL_NO_NEXTPROTONEG
1467 next_proto_neg_in = opt_arg();
1471 alpn_in = opt_arg();
1473 case OPT_SRTP_PROFILES:
1474 #ifndef OPENSSL_NO_SRTP
1475 srtp_profiles = opt_arg();
1478 case OPT_KEYMATEXPORT:
1479 keymatexportlabel = opt_arg();
1481 case OPT_KEYMATEXPORTLEN:
1482 keymatexportlen = atoi(opt_arg());
1487 case OPT_SPLIT_SEND_FRAG:
1488 split_send_fragment = atoi(opt_arg());
1489 if (split_send_fragment == 0) {
1491 * Not allowed - set to a deliberately bad value so we get an
1492 * error message below
1494 split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1;
1497 case OPT_MAX_PIPELINES:
1498 max_pipelines = atoi(opt_arg());
1501 read_buf_len = atoi(opt_arg());
1503 case OPT_KEYLOG_FILE:
1504 keylog_file = opt_arg();
1507 max_early_data = atoi(opt_arg());
1511 argc = opt_num_rest();
1514 #ifndef OPENSSL_NO_DTLS
1515 if (www && socket_type == SOCK_DGRAM) {
1516 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1520 if (dtlslisten && socket_type != SOCK_DGRAM) {
1521 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1527 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1529 "Can't use unix sockets and datagrams together\n");
1534 if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1535 BIO_printf(bio_err, "Bad split send fragment size\n");
1539 if (max_pipelines > SSL_MAX_PIPELINES) {
1540 BIO_printf(bio_err, "Bad max pipelines value\n");
1544 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1545 BIO_printf(bio_err, "Error getting password\n");
1549 if (s_key_file == NULL)
1550 s_key_file = s_cert_file;
1552 if (s_key_file2 == NULL)
1553 s_key_file2 = s_cert_file2;
1555 if (!load_excert(&exc))
1559 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1560 "server certificate private key file");
1562 ERR_print_errors(bio_err);
1566 s_cert = load_cert(s_cert_file, s_cert_format,
1567 "server certificate file");
1570 ERR_print_errors(bio_err);
1574 if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1575 "server certificate chain"))
1579 if (tlsextcbp.servername) {
1580 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1581 "second server certificate private key file");
1583 ERR_print_errors(bio_err);
1587 s_cert2 = load_cert(s_cert_file2, s_cert_format,
1588 "second server certificate file");
1591 ERR_print_errors(bio_err);
1596 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1597 if (next_proto_neg_in) {
1599 next_proto.data = next_protos_parse(&len, next_proto_neg_in);
1600 if (next_proto.data == NULL)
1602 next_proto.len = len;
1604 next_proto.data = NULL;
1607 alpn_ctx.data = NULL;
1610 alpn_ctx.data = next_protos_parse(&len, alpn_in);
1611 if (alpn_ctx.data == NULL)
1618 crl = load_crl(crl_file, crl_format);
1620 BIO_puts(bio_err, "Error loading CRL\n");
1621 ERR_print_errors(bio_err);
1624 crls = sk_X509_CRL_new_null();
1625 if (!crls || !sk_X509_CRL_push(crls, crl)) {
1626 BIO_puts(bio_err, "Error adding CRL\n");
1627 ERR_print_errors(bio_err);
1635 if (s_dkey_file == NULL)
1636 s_dkey_file = s_dcert_file;
1638 s_dkey = load_key(s_dkey_file, s_dkey_format,
1639 0, dpass, engine, "second certificate private key file");
1641 ERR_print_errors(bio_err);
1645 s_dcert = load_cert(s_dcert_file, s_dcert_format,
1646 "second server certificate file");
1649 ERR_print_errors(bio_err);
1652 if (s_dchain_file) {
1653 if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1654 "second server certificate chain"))
1660 if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1661 && !RAND_status()) {
1663 "warning, not much extra random data, consider using the -rand option\n");
1666 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1667 app_RAND_load_files(inrand));
1669 if (bio_s_out == NULL) {
1670 if (s_quiet && !s_debug) {
1671 bio_s_out = BIO_new(BIO_s_null());
1672 if (s_msg && !bio_s_msg)
1673 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1675 if (bio_s_out == NULL)
1676 bio_s_out = dup_bio_out(FORMAT_TEXT);
1679 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1685 s_dcert_file = NULL;
1687 s_cert_file2 = NULL;
1691 ctx = SSL_CTX_new(meth);
1693 ERR_print_errors(bio_err);
1697 ssl_ctx_security_debug(ctx, sdebug);
1699 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1700 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1702 ERR_print_errors(bio_err);
1706 if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1708 if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1711 if (session_id_prefix) {
1712 if (strlen(session_id_prefix) >= 32)
1714 "warning: id_prefix is too long, only one new session will be possible\n");
1715 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1716 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1717 ERR_print_errors(bio_err);
1720 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1722 SSL_CTX_set_quiet_shutdown(ctx, 1);
1724 ssl_ctx_set_excert(ctx, exc);
1727 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1729 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1731 init_session_cache_ctx(ctx);
1733 SSL_CTX_sess_set_cache_size(ctx, 128);
1736 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1738 if (split_send_fragment > 0) {
1739 SSL_CTX_set_split_send_fragment(ctx, split_send_fragment);
1741 if (max_pipelines > 0) {
1742 SSL_CTX_set_max_pipelines(ctx, max_pipelines);
1745 if (read_buf_len > 0) {
1746 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1748 #ifndef OPENSSL_NO_SRTP
1749 if (srtp_profiles != NULL) {
1750 /* Returns 0 on success! */
1751 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1752 BIO_printf(bio_err, "Error setting SRTP profile\n");
1753 ERR_print_errors(bio_err);
1759 if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1760 ERR_print_errors(bio_err);
1763 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1764 BIO_printf(bio_err, "Error setting verify params\n");
1765 ERR_print_errors(bio_err);
1769 ssl_ctx_add_crls(ctx, crls, 0);
1770 if (!config_ctx(cctx, ssl_args, ctx))
1773 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1774 crls, crl_download)) {
1775 BIO_printf(bio_err, "Error loading store locations\n");
1776 ERR_print_errors(bio_err);
1781 ctx2 = SSL_CTX_new(meth);
1783 ERR_print_errors(bio_err);
1789 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1792 ssl_ctx_security_debug(ctx, sdebug);
1794 if (session_id_prefix) {
1795 if (strlen(session_id_prefix) >= 32)
1797 "warning: id_prefix is too long, only one new session will be possible\n");
1798 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1799 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1800 ERR_print_errors(bio_err);
1803 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1805 SSL_CTX_set_quiet_shutdown(ctx2, 1);
1807 ssl_ctx_set_excert(ctx2, exc);
1810 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1813 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1815 init_session_cache_ctx(ctx2);
1817 SSL_CTX_sess_set_cache_size(ctx2, 128);
1820 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1822 if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1824 ERR_print_errors(bio_err);
1827 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1828 BIO_printf(bio_err, "Error setting verify params\n");
1829 ERR_print_errors(bio_err);
1833 ssl_ctx_add_crls(ctx2, crls, 0);
1834 if (!config_ctx(cctx, ssl_args, ctx2))
1837 #ifndef OPENSSL_NO_NEXTPROTONEG
1838 if (next_proto.data)
1839 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1843 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1845 #ifndef OPENSSL_NO_DH
1850 dh = load_dh_param(dhfile);
1851 else if (s_cert_file)
1852 dh = load_dh_param(s_cert_file);
1855 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1857 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1859 (void)BIO_flush(bio_s_out);
1862 SSL_CTX_set_dh_auto(ctx, 1);
1863 else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1864 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1865 ERR_print_errors(bio_err);
1872 DH *dh2 = load_dh_param(s_cert_file2);
1874 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1875 (void)BIO_flush(bio_s_out);
1882 SSL_CTX_set_dh_auto(ctx2, 1);
1883 else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1884 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1885 ERR_print_errors(bio_err);
1894 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1897 if (s_serverinfo_file != NULL
1898 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1899 ERR_print_errors(bio_err);
1903 if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1906 if (s_dcert != NULL) {
1907 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1911 if (no_resume_ephemeral) {
1912 SSL_CTX_set_not_resumable_session_callback(ctx,
1913 not_resumable_sess_cb);
1916 SSL_CTX_set_not_resumable_session_callback(ctx2,
1917 not_resumable_sess_cb);
1919 #ifndef OPENSSL_NO_PSK
1920 if (psk_key != NULL) {
1922 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
1923 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1926 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1927 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1928 ERR_print_errors(bio_err);
1933 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1934 if (!SSL_CTX_set_session_id_context(ctx,
1935 (void *)&s_server_session_id_context,
1936 sizeof s_server_session_id_context)) {
1937 BIO_printf(bio_err, "error setting session id context\n");
1938 ERR_print_errors(bio_err);
1942 /* Set DTLS cookie generation and verification callbacks */
1943 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1944 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1947 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1948 if (!SSL_CTX_set_session_id_context(ctx2,
1949 (void *)&s_server_session_id_context,
1950 sizeof s_server_session_id_context)) {
1951 BIO_printf(bio_err, "error setting session id context\n");
1952 ERR_print_errors(bio_err);
1955 tlsextcbp.biodebug = bio_s_out;
1956 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1957 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1958 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1959 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1962 #ifndef OPENSSL_NO_SRP
1963 if (srp_verifier_file != NULL) {
1964 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1965 srp_callback_parm.user = NULL;
1966 srp_callback_parm.login = NULL;
1968 SRP_VBASE_init(srp_callback_parm.vb,
1969 srp_verifier_file)) != SRP_NO_ERROR) {
1971 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1972 srp_verifier_file, ret);
1975 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
1976 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
1977 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1980 if (CAfile != NULL) {
1981 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
1984 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
1986 #ifndef OPENSSL_NO_OCSP
1987 if (s_tlsextstatus) {
1988 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1989 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1991 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
1992 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
1996 if (set_keylog_file(ctx, keylog_file))
1999 if (max_early_data > 0)
2000 SSL_CTX_set_max_early_data(ctx, max_early_data);
2002 BIO_printf(bio_s_out, "ACCEPT\n");
2003 (void)BIO_flush(bio_s_out);
2005 server_cb = rev_body;
2007 server_cb = www_body;
2009 server_cb = sv_body;
2011 if (socket_family == AF_UNIX
2012 && unlink_unix_path)
2015 do_server(&accept_socket, host, port, socket_family, socket_type,
2016 server_cb, context, naccept);
2017 print_stats(bio_s_out, ctx);
2021 set_keylog_file(NULL, NULL);
2023 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2025 EVP_PKEY_free(s_key);
2026 EVP_PKEY_free(s_dkey);
2027 sk_X509_pop_free(s_chain, X509_free);
2028 sk_X509_pop_free(s_dchain, X509_free);
2030 OPENSSL_free(dpass);
2033 X509_VERIFY_PARAM_free(vpm);
2035 OPENSSL_free(tlscstatp.host);
2036 OPENSSL_free(tlscstatp.port);
2037 OPENSSL_free(tlscstatp.path);
2040 EVP_PKEY_free(s_key2);
2041 #ifndef OPENSSL_NO_NEXTPROTONEG
2042 OPENSSL_free(next_proto.data);
2044 OPENSSL_free(alpn_ctx.data);
2045 ssl_excert_free(exc);
2046 sk_OPENSSL_STRING_free(ssl_args);
2047 SSL_CONF_CTX_free(cctx);
2048 release_engine(engine);
2049 BIO_free(bio_s_out);
2051 BIO_free(bio_s_msg);
2053 #ifdef CHARSET_EBCDIC
2054 BIO_meth_free(methods_ebcdic);
2059 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2061 BIO_printf(bio, "%4ld items in the session cache\n",
2062 SSL_CTX_sess_number(ssl_ctx));
2063 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2064 SSL_CTX_sess_connect(ssl_ctx));
2065 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2066 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2067 BIO_printf(bio, "%4ld client connects that finished\n",
2068 SSL_CTX_sess_connect_good(ssl_ctx));
2069 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2070 SSL_CTX_sess_accept(ssl_ctx));
2071 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2072 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2073 BIO_printf(bio, "%4ld server accepts that finished\n",
2074 SSL_CTX_sess_accept_good(ssl_ctx));
2075 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2076 BIO_printf(bio, "%4ld session cache misses\n",
2077 SSL_CTX_sess_misses(ssl_ctx));
2078 BIO_printf(bio, "%4ld session cache timeouts\n",
2079 SSL_CTX_sess_timeouts(ssl_ctx));
2080 BIO_printf(bio, "%4ld callback cache hits\n",
2081 SSL_CTX_sess_cb_hits(ssl_ctx));
2082 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2083 SSL_CTX_sess_cache_full(ssl_ctx),
2084 SSL_CTX_sess_get_cache_size(ssl_ctx));
2087 static int sv_body(int s, int stype, unsigned char *context)
2096 struct timeval timeout;
2097 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2100 struct timeval *timeoutp;
2103 buf = app_malloc(bufsize, "server buffer");
2105 if (!BIO_socket_nbio(s, 1))
2106 ERR_print_errors(bio_err);
2108 BIO_printf(bio_err, "Turned on non blocking io\n");
2114 if (s_tlsextdebug) {
2115 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2116 SSL_set_tlsext_debug_arg(con, bio_s_out);
2120 && !SSL_set_session_id_context(con,
2121 context, strlen((char *)context))) {
2122 BIO_printf(bio_err, "Error setting session id context\n");
2127 if (!SSL_clear(con)) {
2128 BIO_printf(bio_err, "Error clearing SSL connection\n");
2132 #ifndef OPENSSL_NO_DTLS
2133 if (stype == SOCK_DGRAM) {
2135 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2137 if (enable_timeouts) {
2139 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2140 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2143 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2144 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2148 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2149 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2150 DTLS_get_link_min_mtu(con));
2155 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2156 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2157 BIO_printf(bio_err, "Failed to set MTU\n");
2163 /* want to do MTU discovery */
2164 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2166 /* turn on cookie exchange */
2167 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2170 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2175 test = BIO_new(BIO_f_nbio_test());
2176 sbio = BIO_push(test, sbio);
2179 SSL_set_bio(con, sbio, sbio);
2180 SSL_set_accept_state(con);
2181 /* SSL_set_fd(con,s); */
2184 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2185 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2188 #ifndef OPENSSL_NO_SSL_TRACE
2190 SSL_set_msg_callback(con, SSL_trace);
2193 SSL_set_msg_callback(con, msg_cb);
2194 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2197 if (s_tlsextdebug) {
2198 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2199 SSL_set_tlsext_debug_arg(con, bio_s_out);
2202 if (fileno_stdin() > s)
2203 width = fileno_stdin() + 1;
2207 int read_from_terminal;
2208 int read_from_sslcon;
2210 read_from_terminal = 0;
2211 read_from_sslcon = SSL_has_pending(con)
2212 || (async && SSL_waiting_for_async(con));
2214 if (!read_from_sslcon) {
2216 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2217 openssl_fdset(fileno_stdin(), &readfds);
2219 openssl_fdset(s, &readfds);
2221 * Note: under VMS with SOCKETSHR the second parameter is
2222 * currently of type (int *) whereas under other systems it is
2223 * (void *) if you don't have a cast it will choke the compiler:
2224 * if you do have a cast then you can either go for (int *) or
2227 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2229 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2230 * only on sockets. As a workaround we timeout the select every
2231 * second and check for any keypress. In a proper Windows
2232 * application we wouldn't do this because it is inefficient.
2236 i = select(width, (void *)&readfds, NULL, NULL, &tv);
2237 if (has_stdin_waiting())
2238 read_from_terminal = 1;
2239 if ((i < 0) || (!i && !read_from_terminal))
2242 if ((SSL_version(con) == DTLS1_VERSION) &&
2243 DTLSv1_get_timeout(con, &timeout))
2244 timeoutp = &timeout;
2248 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2250 if ((SSL_version(con) == DTLS1_VERSION)
2251 && DTLSv1_handle_timeout(con) > 0) {
2252 BIO_printf(bio_err, "TIMEOUT occurred\n");
2257 if (FD_ISSET(fileno_stdin(), &readfds))
2258 read_from_terminal = 1;
2260 if (FD_ISSET(s, &readfds))
2261 read_from_sslcon = 1;
2263 if (read_from_terminal) {
2267 i = raw_read_stdin(buf, bufsize / 2);
2269 /* both loops are skipped when i <= 0 */
2270 for (j = 0; j < i; j++)
2273 for (j = i - 1; j >= 0; j--) {
2274 buf[j + lf_num] = buf[j];
2275 if (buf[j] == '\n') {
2278 buf[j + lf_num] = '\r';
2281 assert(lf_num == 0);
2283 i = raw_read_stdin(buf, bufsize);
2285 if (!s_quiet && !s_brief) {
2286 if ((i <= 0) || (buf[0] == 'Q')) {
2287 BIO_printf(bio_s_out, "DONE\n");
2288 (void)BIO_flush(bio_s_out);
2290 close_accept_socket();
2294 if ((i <= 0) || (buf[0] == 'q')) {
2295 BIO_printf(bio_s_out, "DONE\n");
2296 (void)BIO_flush(bio_s_out);
2297 if (SSL_version(con) != DTLS1_VERSION)
2300 * close_accept_socket(); ret= -11;
2304 #ifndef OPENSSL_NO_HEARTBEATS
2305 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2306 BIO_printf(bio_err, "HEARTBEATING\n");
2312 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2313 SSL_renegotiate(con);
2314 i = SSL_do_handshake(con);
2315 printf("SSL_do_handshake -> %d\n", i);
2319 * strcpy(buf,"server side RE-NEGOTIATE\n");
2322 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2324 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2326 SSL_renegotiate(con);
2327 i = SSL_do_handshake(con);
2328 printf("SSL_do_handshake -> %d\n", i);
2332 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2336 if ((buf[0] == 'K' || buf[0] == 'k')
2337 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2338 SSL_key_update(con, buf[0] == 'K' ?
2339 SSL_KEY_UPDATE_REQUESTED
2340 : SSL_KEY_UPDATE_NOT_REQUESTED);
2341 i = SSL_do_handshake(con);
2342 printf("SSL_do_handshake -> %d\n", i);
2346 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2350 if (buf[0] == 'P') {
2351 static const char *str = "Lets print some clear text\n";
2352 BIO_write(SSL_get_wbio(con), str, strlen(str));
2354 if (buf[0] == 'S') {
2355 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2358 #ifdef CHARSET_EBCDIC
2359 ebcdic2ascii(buf, buf, i);
2363 /* should do a select for the write */
2366 if (++count == 100) {
2368 SSL_renegotiate(con);
2371 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2372 #ifndef OPENSSL_NO_SRP
2373 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2374 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2375 SRP_user_pwd_free(srp_callback_parm.user);
2376 srp_callback_parm.user =
2377 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2378 srp_callback_parm.login);
2379 if (srp_callback_parm.user)
2380 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2381 srp_callback_parm.user->info);
2383 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2384 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2387 switch (SSL_get_error(con, k)) {
2388 case SSL_ERROR_NONE:
2390 case SSL_ERROR_WANT_ASYNC:
2391 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2392 (void)BIO_flush(bio_s_out);
2393 wait_for_async(con);
2395 case SSL_ERROR_WANT_WRITE:
2396 case SSL_ERROR_WANT_READ:
2397 case SSL_ERROR_WANT_X509_LOOKUP:
2398 BIO_printf(bio_s_out, "Write BLOCK\n");
2399 (void)BIO_flush(bio_s_out);
2401 case SSL_ERROR_WANT_ASYNC_JOB:
2403 * This shouldn't ever happen in s_server. Treat as an error
2405 case SSL_ERROR_SYSCALL:
2407 BIO_printf(bio_s_out, "ERROR\n");
2408 (void)BIO_flush(bio_s_out);
2409 ERR_print_errors(bio_err);
2413 case SSL_ERROR_ZERO_RETURN:
2414 BIO_printf(bio_s_out, "DONE\n");
2415 (void)BIO_flush(bio_s_out);
2427 if (read_from_sslcon) {
2429 * init_ssl_connection handles all async events itself so if we're
2430 * waiting for async then we shouldn't go back into
2431 * init_ssl_connection
2433 if ((!async || !SSL_waiting_for_async(con))
2434 && !SSL_is_init_finished(con)) {
2435 i = init_ssl_connection(con);
2440 } else if (i == 0) {
2446 i = SSL_read(con, (char *)buf, bufsize);
2447 #ifndef OPENSSL_NO_SRP
2448 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2449 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2450 SRP_user_pwd_free(srp_callback_parm.user);
2451 srp_callback_parm.user =
2452 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2453 srp_callback_parm.login);
2454 if (srp_callback_parm.user)
2455 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2456 srp_callback_parm.user->info);
2458 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2459 i = SSL_read(con, (char *)buf, bufsize);
2462 switch (SSL_get_error(con, i)) {
2463 case SSL_ERROR_NONE:
2464 #ifdef CHARSET_EBCDIC
2465 ascii2ebcdic(buf, buf, i);
2467 raw_write_stdout(buf, (unsigned int)i);
2468 (void)BIO_flush(bio_s_out);
2469 if (SSL_has_pending(con))
2472 case SSL_ERROR_WANT_ASYNC:
2473 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2474 (void)BIO_flush(bio_s_out);
2475 wait_for_async(con);
2477 case SSL_ERROR_WANT_WRITE:
2478 case SSL_ERROR_WANT_READ:
2479 BIO_printf(bio_s_out, "Read BLOCK\n");
2480 (void)BIO_flush(bio_s_out);
2482 case SSL_ERROR_WANT_ASYNC_JOB:
2484 * This shouldn't ever happen in s_server. Treat as an error
2486 case SSL_ERROR_SYSCALL:
2488 BIO_printf(bio_s_out, "ERROR\n");
2489 (void)BIO_flush(bio_s_out);
2490 ERR_print_errors(bio_err);
2493 case SSL_ERROR_ZERO_RETURN:
2494 BIO_printf(bio_s_out, "DONE\n");
2495 (void)BIO_flush(bio_s_out);
2504 BIO_printf(bio_s_out, "shutting down SSL\n");
2505 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2508 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2509 OPENSSL_clear_free(buf, bufsize);
2511 BIO_printf(bio_s_out, "ACCEPT\n");
2512 (void)BIO_flush(bio_s_out);
2516 static void close_accept_socket(void)
2518 BIO_printf(bio_err, "shutdown accept socket\n");
2519 if (accept_socket >= 0) {
2520 BIO_closesocket(accept_socket);
2524 static int init_ssl_connection(SSL *con)
2531 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2532 const unsigned char *next_proto_neg;
2533 unsigned next_proto_neg_len;
2535 unsigned char *exportedkeymat;
2538 #ifndef OPENSSL_NO_DTLS
2540 BIO_ADDR *client = NULL;
2542 if ((client = BIO_ADDR_new()) == NULL) {
2543 BIO_printf(bio_err, "ERROR - memory\n");
2546 i = DTLSv1_listen(con, client);
2551 wbio = SSL_get_wbio(con);
2553 BIO_get_fd(wbio, &fd);
2556 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2557 BIO_printf(bio_err, "ERROR - unable to connect\n");
2558 BIO_ADDR_free(client);
2561 BIO_ADDR_free(client);
2563 i = SSL_accept(con);
2565 BIO_ADDR_free(client);
2571 i = SSL_accept(con);
2574 retry = BIO_sock_should_retry(i);
2575 #ifdef CERT_CB_TEST_RETRY
2578 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2579 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2581 "LOOKUP from certificate callback during accept\n");
2582 i = SSL_accept(con);
2584 retry = BIO_sock_should_retry(i);
2589 #ifndef OPENSSL_NO_SRP
2591 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2592 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2593 srp_callback_parm.login);
2594 SRP_user_pwd_free(srp_callback_parm.user);
2595 srp_callback_parm.user =
2596 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2597 srp_callback_parm.login);
2598 if (srp_callback_parm.user)
2599 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2600 srp_callback_parm.user->info);
2602 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2603 i = SSL_accept(con);
2605 retry = BIO_sock_should_retry(i);
2608 } while (i < 0 && SSL_waiting_for_async(con));
2611 if ((dtlslisten && i == 0)
2612 || (!dtlslisten && retry)) {
2613 BIO_printf(bio_s_out, "DELAY\n");
2617 BIO_printf(bio_err, "ERROR\n");
2619 verify_err = SSL_get_verify_result(con);
2620 if (verify_err != X509_V_OK) {
2621 BIO_printf(bio_err, "verify error:%s\n",
2622 X509_verify_cert_error_string(verify_err));
2624 /* Always print any error messages */
2625 ERR_print_errors(bio_err);
2630 print_ssl_summary(con);
2632 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2634 peer = SSL_get_peer_certificate(con);
2636 BIO_printf(bio_s_out, "Client certificate\n");
2637 PEM_write_bio_X509(bio_s_out, peer);
2638 X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
2639 BIO_printf(bio_s_out, "subject=%s\n", buf);
2640 X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
2641 BIO_printf(bio_s_out, "issuer=%s\n", buf);
2646 if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2647 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2648 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2649 ssl_print_sigalgs(bio_s_out, con);
2650 #ifndef OPENSSL_NO_EC
2651 ssl_print_point_formats(bio_s_out, con);
2652 ssl_print_groups(bio_s_out, con, 0);
2654 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2656 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2657 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2658 if (next_proto_neg) {
2659 BIO_printf(bio_s_out, "NEXTPROTO is ");
2660 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2661 BIO_printf(bio_s_out, "\n");
2664 #ifndef OPENSSL_NO_SRTP
2666 SRTP_PROTECTION_PROFILE *srtp_profile
2667 = SSL_get_selected_srtp_profile(con);
2670 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2671 srtp_profile->name);
2674 if (SSL_session_reused(con))
2675 BIO_printf(bio_s_out, "Reused session-id\n");
2676 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2677 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2678 if (keymatexportlabel != NULL) {
2679 BIO_printf(bio_s_out, "Keying material exporter:\n");
2680 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2681 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2682 exportedkeymat = app_malloc(keymatexportlen, "export key");
2683 if (!SSL_export_keying_material(con, exportedkeymat,
2686 strlen(keymatexportlabel),
2688 BIO_printf(bio_s_out, " Error\n");
2690 BIO_printf(bio_s_out, " Keying material: ");
2691 for (i = 0; i < keymatexportlen; i++)
2692 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2693 BIO_printf(bio_s_out, "\n");
2695 OPENSSL_free(exportedkeymat);
2698 (void)BIO_flush(bio_s_out);
2702 #ifndef OPENSSL_NO_DH
2703 static DH *load_dh_param(const char *dhfile)
2708 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2710 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2717 static int www_body(int s, int stype, unsigned char *context)
2723 const SSL_CIPHER *c;
2724 BIO *io, *ssl_bio, *sbio;
2726 int total_bytes = 0;
2731 /* Set width for a select call if needed */
2734 buf = app_malloc(bufsize, "server www buffer");
2735 io = BIO_new(BIO_f_buffer());
2736 ssl_bio = BIO_new(BIO_f_ssl());
2737 if ((io == NULL) || (ssl_bio == NULL))
2741 if (!BIO_socket_nbio(s, 1))
2742 ERR_print_errors(bio_err);
2744 BIO_printf(bio_err, "Turned on non blocking io\n");
2747 /* lets make the output buffer a reasonable size */
2748 if (!BIO_set_write_buffer_size(io, bufsize))
2751 if ((con = SSL_new(ctx)) == NULL)
2754 if (s_tlsextdebug) {
2755 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2756 SSL_set_tlsext_debug_arg(con, bio_s_out);
2760 && !SSL_set_session_id_context(con, context,
2761 strlen((char *)context)))
2764 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2768 test = BIO_new(BIO_f_nbio_test());
2769 sbio = BIO_push(test, sbio);
2771 SSL_set_bio(con, sbio, sbio);
2772 SSL_set_accept_state(con);
2774 /* SSL_set_fd(con,s); */
2775 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2776 BIO_push(io, ssl_bio);
2777 #ifdef CHARSET_EBCDIC
2778 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2782 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2783 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2786 #ifndef OPENSSL_NO_SSL_TRACE
2788 SSL_set_msg_callback(con, SSL_trace);
2791 SSL_set_msg_callback(con, msg_cb);
2792 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2796 i = BIO_gets(io, buf, bufsize - 1);
2797 if (i < 0) { /* error */
2798 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2800 ERR_print_errors(bio_err);
2803 BIO_printf(bio_s_out, "read R BLOCK\n");
2804 #ifndef OPENSSL_NO_SRP
2805 if (BIO_should_io_special(io)
2806 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2807 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2808 SRP_user_pwd_free(srp_callback_parm.user);
2809 srp_callback_parm.user =
2810 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2811 srp_callback_parm.login);
2812 if (srp_callback_parm.user)
2813 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2814 srp_callback_parm.user->info);
2816 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2820 #if !defined(OPENSSL_SYS_MSDOS)
2825 } else if (i == 0) { /* end of input */
2830 /* else we have data */
2831 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2832 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2835 STACK_OF(SSL_CIPHER) *sk;
2836 static const char *space = " ";
2838 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2839 if (strncmp("GET /renegcert", buf, 14) == 0)
2841 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2843 i = SSL_renegotiate(con);
2844 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2845 /* Send the HelloRequest */
2846 i = SSL_do_handshake(con);
2848 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2849 SSL_get_error(con, i));
2850 ERR_print_errors(bio_err);
2853 /* Wait for a ClientHello to come back */
2855 openssl_fdset(s, &readfds);
2856 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2857 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2858 BIO_printf(bio_s_out,
2859 "Error waiting for client response\n");
2860 ERR_print_errors(bio_err);
2864 * We're not actually expecting any data here and we ignore
2865 * any that is sent. This is just to force the handshake that
2866 * we're expecting to come from the client. If they haven't
2867 * sent one there's not much we can do.
2869 BIO_gets(io, buf, bufsize - 1);
2873 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2874 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2875 BIO_puts(io, "<pre>\n");
2876 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2878 for (i = 0; i < local_argc; i++) {
2880 for (myp = local_argv[i]; *myp; myp++)
2883 BIO_puts(io, "<");
2886 BIO_puts(io, ">");
2889 BIO_puts(io, "&");
2892 BIO_write(io, myp, 1);
2895 BIO_write(io, " ", 1);
2900 "Secure Renegotiation IS%s supported\n",
2901 SSL_get_secure_renegotiation_support(con) ?
2905 * The following is evil and should not really be done
2907 BIO_printf(io, "Ciphers supported in s_server binary\n");
2908 sk = SSL_get_ciphers(con);
2909 j = sk_SSL_CIPHER_num(sk);
2910 for (i = 0; i < j; i++) {
2911 c = sk_SSL_CIPHER_value(sk, i);
2912 BIO_printf(io, "%-11s:%-25s ",
2913 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2914 if ((((i + 1) % 2) == 0) && (i + 1 != j))
2918 p = SSL_get_shared_ciphers(con, buf, bufsize);
2921 "---\nCiphers common between both SSL end points:\n");
2925 BIO_write(io, space, 26 - j);
2928 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
2930 BIO_write(io, p, 1);
2937 ssl_print_sigalgs(io, con);
2938 #ifndef OPENSSL_NO_EC
2939 ssl_print_groups(io, con, 0);
2941 BIO_printf(io, (SSL_session_reused(con)
2942 ? "---\nReused, " : "---\nNew, "));
2943 c = SSL_get_current_cipher(con);
2944 BIO_printf(io, "%s, Cipher is %s\n",
2945 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2946 SSL_SESSION_print(io, SSL_get_session(con));
2947 BIO_printf(io, "---\n");
2948 print_stats(io, SSL_get_SSL_CTX(con));
2949 BIO_printf(io, "---\n");
2950 peer = SSL_get_peer_certificate(con);
2952 BIO_printf(io, "Client certificate\n");
2953 X509_print(io, peer);
2954 PEM_write_bio_X509(io, peer);
2958 BIO_puts(io, "no client certificate available\n");
2959 BIO_puts(io, "</BODY></HTML>\r\n\r\n");
2961 } else if ((www == 2 || www == 3)
2962 && (strncmp("GET /", buf, 5) == 0)) {
2965 static const char *text =
2966 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2972 for (e = p; *e != '\0'; e++) {
2978 dot = (e[0] == '.') ? 2 : 0;
2981 dot = (e[0] == '.') ? 3 : 0;
2984 dot = (e[0] == '/') ? -1 : 0;
2988 dot = (e[0] == '/') ? 1 : 0;
2990 dot = (dot == 3) || (dot == -1); /* filename contains ".."
2995 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3002 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
3008 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3012 /* if a directory, do the index thang */
3013 if (app_isdir(p) > 0) {
3015 BIO_printf(io, "'%s' is a directory\r\n", p);
3019 if ((file = BIO_new_file(p, "r")) == NULL) {
3021 BIO_printf(io, "Error opening '%s'\r\n", p);
3022 ERR_print_errors(io);
3027 BIO_printf(bio_err, "FILE:%s\n", p);
3031 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3032 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3033 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3035 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3038 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3042 i = BIO_read(file, buf, bufsize);
3048 BIO_printf(bio_err, "%d\n", i);
3049 if (total_bytes > 3 * 1024) {
3051 BIO_printf(bio_err, "RENEGOTIATE\n");
3052 SSL_renegotiate(con);
3056 for (j = 0; j < i;) {
3059 if (++count == 13) {
3060 SSL_renegotiate(con);
3063 k = BIO_write(io, &(buf[j]), i - j);
3065 if (!BIO_should_retry(io)
3066 && !SSL_waiting_for_async(con))
3069 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3083 i = (int)BIO_flush(io);
3085 if (!BIO_should_retry(io))
3091 /* make sure we re-use sessions */
3092 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3096 BIO_printf(bio_s_out, "ACCEPT\n");
3102 static int rev_body(int s, int stype, unsigned char *context)
3108 BIO *io, *ssl_bio, *sbio;
3110 buf = app_malloc(bufsize, "server rev buffer");
3111 io = BIO_new(BIO_f_buffer());
3112 ssl_bio = BIO_new(BIO_f_ssl());
3113 if ((io == NULL) || (ssl_bio == NULL))
3116 /* lets make the output buffer a reasonable size */
3117 if (!BIO_set_write_buffer_size(io, bufsize))
3120 if ((con = SSL_new(ctx)) == NULL)
3123 if (s_tlsextdebug) {
3124 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3125 SSL_set_tlsext_debug_arg(con, bio_s_out);
3128 && !SSL_set_session_id_context(con, context,
3129 strlen((char *)context))) {
3130 ERR_print_errors(bio_err);
3134 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3135 SSL_set_bio(con, sbio, sbio);
3136 SSL_set_accept_state(con);
3138 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3139 BIO_push(io, ssl_bio);
3140 #ifdef CHARSET_EBCDIC
3141 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3145 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3146 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3149 #ifndef OPENSSL_NO_SSL_TRACE
3151 SSL_set_msg_callback(con, SSL_trace);
3154 SSL_set_msg_callback(con, msg_cb);
3155 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3159 i = BIO_do_handshake(io);
3162 if (!BIO_should_retry(io)) {
3163 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3164 ERR_print_errors(bio_err);
3167 #ifndef OPENSSL_NO_SRP
3168 if (BIO_should_io_special(io)
3169 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3170 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3171 SRP_user_pwd_free(srp_callback_parm.user);
3172 srp_callback_parm.user =
3173 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3174 srp_callback_parm.login);
3175 if (srp_callback_parm.user)
3176 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3177 srp_callback_parm.user->info);
3179 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3184 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3185 print_ssl_summary(con);
3188 i = BIO_gets(io, buf, bufsize - 1);
3189 if (i < 0) { /* error */
3190 if (!BIO_should_retry(io)) {
3192 ERR_print_errors(bio_err);
3195 BIO_printf(bio_s_out, "read R BLOCK\n");
3196 #ifndef OPENSSL_NO_SRP
3197 if (BIO_should_io_special(io)
3198 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3199 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3200 SRP_user_pwd_free(srp_callback_parm.user);
3201 srp_callback_parm.user =
3202 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3203 srp_callback_parm.login);
3204 if (srp_callback_parm.user)
3205 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3206 srp_callback_parm.user->info);
3208 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3212 #if !defined(OPENSSL_SYS_MSDOS)
3217 } else if (i == 0) { /* end of input */
3219 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3222 char *p = buf + i - 1;
3223 while (i && (*p == '\n' || *p == '\r')) {
3227 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3229 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3232 BUF_reverse((unsigned char *)buf, NULL, i);
3234 BIO_write(io, buf, i + 1);
3239 if (!BIO_should_retry(io))
3245 /* make sure we re-use sessions */
3246 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3255 #define MAX_SESSION_ID_ATTEMPTS 10
3256 static int generate_session_id(const SSL *ssl, unsigned char *id,
3257 unsigned int *id_len)
3259 unsigned int count = 0;
3261 if (RAND_bytes(id, *id_len) <= 0)
3264 * Prefix the session_id with the required prefix. NB: If our prefix
3265 * is too long, clip it - but there will be worse effects anyway, eg.
3266 * the server could only possibly create 1 session ID (ie. the
3267 * prefix!) so all future session negotiations will fail due to
3270 memcpy(id, session_id_prefix,
3271 (strlen(session_id_prefix) < *id_len) ?
3272 strlen(session_id_prefix) : *id_len);
3274 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3275 (++count < MAX_SESSION_ID_ATTEMPTS));
3276 if (count >= MAX_SESSION_ID_ATTEMPTS)
3282 * By default s_server uses an in-memory cache which caches SSL_SESSION
3283 * structures without any serialisation. This hides some bugs which only
3284 * become apparent in deployed servers. By implementing a basic external
3285 * session cache some issues can be debugged using s_server.
3288 typedef struct simple_ssl_session_st {
3293 struct simple_ssl_session_st *next;
3294 } simple_ssl_session;
3296 static simple_ssl_session *first = NULL;
3298 static int add_session(SSL *ssl, SSL_SESSION *session)
3300 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3303 SSL_SESSION_get_id(session, &sess->idlen);
3304 sess->derlen = i2d_SSL_SESSION(session, NULL);
3305 if (sess->derlen < 0) {
3306 BIO_printf(bio_err, "Error encoding session\n");
3311 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3312 sess->der = app_malloc(sess->derlen, "get session buffer");
3314 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3315 OPENSSL_free(sess->id);
3316 OPENSSL_free(sess->der);
3322 /* Assume it still works. */
3323 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3324 BIO_printf(bio_err, "Unexpected session encoding length\n");
3325 OPENSSL_free(sess->id);
3326 OPENSSL_free(sess->der);
3333 BIO_printf(bio_err, "New session added to external cache\n");
3337 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3340 simple_ssl_session *sess;
3342 for (sess = first; sess; sess = sess->next) {
3343 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3344 const unsigned char *p = sess->der;
3345 BIO_printf(bio_err, "Lookup session: cache hit\n");
3346 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3349 BIO_printf(bio_err, "Lookup session: cache miss\n");
3353 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3355 simple_ssl_session *sess, *prev = NULL;
3356 const unsigned char *id;
3358 id = SSL_SESSION_get_id(session, &idlen);
3359 for (sess = first; sess; sess = sess->next) {
3360 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3362 prev->next = sess->next;
3365 OPENSSL_free(sess->id);
3366 OPENSSL_free(sess->der);
3374 static void init_session_cache_ctx(SSL_CTX *sctx)
3376 SSL_CTX_set_session_cache_mode(sctx,
3377 SSL_SESS_CACHE_NO_INTERNAL |
3378 SSL_SESS_CACHE_SERVER);
3379 SSL_CTX_sess_set_new_cb(sctx, add_session);
3380 SSL_CTX_sess_set_get_cb(sctx, get_session);
3381 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3384 static void free_sessions(void)
3386 simple_ssl_session *sess, *tsess;
3387 for (sess = first; sess;) {
3388 OPENSSL_free(sess->id);
3389 OPENSSL_free(sess->der);
3392 OPENSSL_free(tsess);
3397 #endif /* OPENSSL_NO_SOCK */