2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4 * Copyright 2005 Nokia. All rights reserved.
6 * Licensed under the OpenSSL license (the "License"). You may not use
7 * this file except in compliance with the License. You can obtain a copy
8 * in the file LICENSE in the source distribution or at
9 * https://www.openssl.org/source/license.html
17 /* Included before async.h to avoid some warnings */
21 #include <openssl/e_os2.h>
22 #include <openssl/async.h>
23 #include <openssl/ssl.h>
25 #ifndef OPENSSL_NO_SOCK
28 * With IPv6, it looks like Digital has mixed up the proper order of
29 * recursive header file inclusion, resulting in the compiler complaining
30 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
31 * needed to have fileno() declared correctly... So let's define u_int
33 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
35 typedef unsigned int u_int;
38 #include <openssl/lhash.h>
39 #include <openssl/bn.h>
42 #include <openssl/err.h>
43 #include <openssl/pem.h>
44 #include <openssl/x509.h>
45 #include <openssl/ssl.h>
46 #include <openssl/rand.h>
47 #include <openssl/ocsp.h>
49 # include <openssl/dh.h>
51 #ifndef OPENSSL_NO_RSA
52 # include <openssl/rsa.h>
54 #ifndef OPENSSL_NO_SRP
55 # include <openssl/srp.h>
60 #include <openssl/ebcdic.h>
63 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
64 static int sv_body(int s, int stype, int prot, unsigned char *context);
65 static int www_body(int s, int stype, int prot, unsigned char *context);
66 static int rev_body(int s, int stype, int prot, unsigned char *context);
67 static void close_accept_socket(void);
68 static int init_ssl_connection(SSL *s);
69 static void print_stats(BIO *bp, SSL_CTX *ctx);
70 static int generate_session_id(const SSL *ssl, unsigned char *id,
71 unsigned int *id_len);
72 static void init_session_cache_ctx(SSL_CTX *sctx);
73 static void free_sessions(void);
75 static DH *load_dh_param(const char *dhfile);
77 static void print_connection_info(SSL *con);
79 static const int bufsize = 16 * 1024;
80 static int accept_socket = -1;
82 #define TEST_CERT "server.pem"
83 #define TEST_CERT2 "server2.pem"
85 static int s_nbio = 0;
86 static int s_nbio_test = 0;
87 static int s_crlf = 0;
88 static SSL_CTX *ctx = NULL;
89 static SSL_CTX *ctx2 = NULL;
92 static BIO *bio_s_out = NULL;
93 static BIO *bio_s_msg = NULL;
94 static int s_debug = 0;
95 static int s_tlsextdebug = 0;
97 static int s_quiet = 0;
98 static int s_ign_eof = 0;
99 static int s_brief = 0;
101 static char *keymatexportlabel = NULL;
102 static int keymatexportlen = 20;
104 static int async = 0;
106 static const char *session_id_prefix = NULL;
108 #ifndef OPENSSL_NO_DTLS
109 static int enable_timeouts = 0;
110 static long socket_mtu;
114 * We define this but make it always be 0 in no-dtls builds to simplify the
117 static int dtlslisten = 0;
119 static int early_data = 0;
121 #ifndef OPENSSL_NO_PSK
122 static char *psk_identity = "Client_identity";
123 char *psk_key = NULL; /* by default PSK is not used */
125 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
127 unsigned int max_psk_len)
133 BIO_printf(bio_s_out, "psk_server_cb\n");
134 if (identity == NULL) {
135 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
139 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
140 (int)strlen(identity), identity);
142 /* here we could lookup the given identity e.g. from a database */
143 if (strcmp(identity, psk_identity) != 0) {
144 BIO_printf(bio_s_out, "PSK warning: client identity not what we expected"
145 " (got '%s' expected '%s')\n", identity, psk_identity);
148 BIO_printf(bio_s_out, "PSK client identity found\n");
151 /* convert the PSK key to binary */
152 key = OPENSSL_hexstr2buf(psk_key, &key_len);
154 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
158 if (key_len > (int)max_psk_len) {
160 "psk buffer of callback is too small (%d) for key (%ld)\n",
161 max_psk_len, key_len);
166 memcpy(psk, key, key_len);
170 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
174 BIO_printf(bio_err, "Error in PSK server callback\n");
175 (void)BIO_flush(bio_err);
176 (void)BIO_flush(bio_s_out);
181 #ifndef OPENSSL_NO_SRP
182 /* This is a context that we pass to callbacks */
183 typedef struct srpsrvparm_st {
190 * This callback pretends to require some asynchronous logic in order to
191 * obtain a verifier. When the callback is called for a new connection we
192 * return with a negative value. This will provoke the accept etc to return
193 * with an LOOKUP_X509. The main logic of the reinvokes the suspended call
194 * (which would normally occur after a worker has finished) and we set the
197 static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
199 srpsrvparm *p = (srpsrvparm *) arg;
200 int ret = SSL3_AL_FATAL;
202 if (p->login == NULL && p->user == NULL) {
203 p->login = SSL_get_srp_username(s);
204 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
208 if (p->user == NULL) {
209 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
213 if (SSL_set_srp_server_param
214 (s, p->user->N, p->user->g, p->user->s, p->user->v,
215 p->user->info) < 0) {
216 *ad = SSL_AD_INTERNAL_ERROR;
220 "SRP parameters set: username = \"%s\" info=\"%s\" \n",
221 p->login, p->user->info);
222 ret = SSL_ERROR_NONE;
225 SRP_user_pwd_free(p->user);
233 static int local_argc = 0;
234 static char **local_argv;
236 #ifdef CHARSET_EBCDIC
237 static int ebcdic_new(BIO *bi);
238 static int ebcdic_free(BIO *a);
239 static int ebcdic_read(BIO *b, char *out, int outl);
240 static int ebcdic_write(BIO *b, const char *in, int inl);
241 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
242 static int ebcdic_gets(BIO *bp, char *buf, int size);
243 static int ebcdic_puts(BIO *bp, const char *str);
245 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
246 static BIO_METHOD *methods_ebcdic = NULL;
248 /* This struct is "unwarranted chumminess with the compiler." */
254 static const BIO_METHOD *BIO_f_ebcdic_filter()
256 if (methods_ebcdic == NULL) {
257 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
258 "EBCDIC/ASCII filter");
259 if (methods_ebcdic == NULL
260 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
261 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
262 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
263 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
264 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
265 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
266 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
269 return methods_ebcdic;
272 static int ebcdic_new(BIO *bi)
274 EBCDIC_OUTBUFF *wbuf;
276 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
277 wbuf->alloced = 1024;
278 wbuf->buff[0] = '\0';
280 BIO_set_data(bi, wbuf);
285 static int ebcdic_free(BIO *a)
287 EBCDIC_OUTBUFF *wbuf;
291 wbuf = BIO_get_data(a);
293 BIO_set_data(a, NULL);
299 static int ebcdic_read(BIO *b, char *out, int outl)
302 BIO *next = BIO_next(b);
304 if (out == NULL || outl == 0)
309 ret = BIO_read(next, out, outl);
311 ascii2ebcdic(out, out, ret);
315 static int ebcdic_write(BIO *b, const char *in, int inl)
317 EBCDIC_OUTBUFF *wbuf;
318 BIO *next = BIO_next(b);
322 if ((in == NULL) || (inl <= 0))
327 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
329 if (inl > (num = wbuf->alloced)) {
330 num = num + num; /* double the size */
334 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
337 wbuf->buff[0] = '\0';
339 BIO_set_data(b, wbuf);
342 ebcdic2ascii(wbuf->buff, in, inl);
344 ret = BIO_write(next, wbuf->buff, inl);
349 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
352 BIO *next = BIO_next(b);
361 ret = BIO_ctrl(next, cmd, num, ptr);
367 static int ebcdic_gets(BIO *bp, char *buf, int size)
370 BIO *next = BIO_next(bp);
374 /* return(BIO_gets(bp->next_bio,buf,size));*/
375 for (i = 0; i < size - 1; ++i) {
376 ret = ebcdic_read(bp, &buf[i], 1);
379 else if (buf[i] == '\n') {
386 return (ret < 0 && i == 0) ? ret : i;
389 static int ebcdic_puts(BIO *bp, const char *str)
391 if (BIO_next(bp) == NULL)
393 return ebcdic_write(bp, str, strlen(str));
397 /* This is a context that we pass to callbacks */
398 typedef struct tlsextctx_st {
404 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
406 tlsextctx *p = (tlsextctx *) arg;
407 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
408 if (servername != NULL && p->biodebug != NULL)
409 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
412 if (p->servername == NULL)
413 return SSL_TLSEXT_ERR_NOACK;
415 if (servername != NULL) {
416 if (strcasecmp(servername, p->servername))
417 return p->extension_error;
419 BIO_printf(p->biodebug, "Switching server context.\n");
420 SSL_set_SSL_CTX(s, ctx2);
423 return SSL_TLSEXT_ERR_OK;
426 /* Structure passed to cert status callback */
427 typedef struct tlsextstatusctx_st {
429 /* File to load OCSP Response from (or NULL if no file) */
431 /* Default responder to use */
432 char *host, *path, *port;
437 static tlsextstatusctx tlscstatp = { -1 };
439 #ifndef OPENSSL_NO_OCSP
442 * Helper function to get an OCSP_RESPONSE from a responder. This is a
443 * simplified version. It examines certificates each time and makes one OCSP
444 * responder query for each request. A full version would store details such as
445 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
446 * them until they were considered "expired".
448 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
449 OCSP_RESPONSE **resp)
451 char *host = NULL, *port = NULL, *path = NULL;
453 STACK_OF(OPENSSL_STRING) *aia = NULL;
455 X509_STORE_CTX *inctx = NULL;
457 OCSP_REQUEST *req = NULL;
458 OCSP_CERTID *id = NULL;
459 STACK_OF(X509_EXTENSION) *exts;
460 int ret = SSL_TLSEXT_ERR_NOACK;
463 /* Build up OCSP query from server certificate */
464 x = SSL_get_certificate(s);
465 aia = X509_get1_ocsp(x);
467 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
468 &host, &port, &path, &use_ssl)) {
469 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
473 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
474 sk_OPENSSL_STRING_value(aia, 0));
476 if (srctx->host == NULL) {
478 "cert_status: no AIA and no default responder URL\n");
484 use_ssl = srctx->use_ssl;
487 inctx = X509_STORE_CTX_new();
490 if (!X509_STORE_CTX_init(inctx,
491 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
494 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509,
495 X509_get_issuer_name(x));
497 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
500 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
501 X509_OBJECT_free(obj);
504 req = OCSP_REQUEST_new();
507 if (!OCSP_request_add0_id(req, id))
510 /* Add any extensions to the request */
511 SSL_get_tlsext_status_exts(s, &exts);
512 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
513 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
514 if (!OCSP_REQUEST_add_ext(req, ext, -1))
517 *resp = process_responder(req, host, path, port, use_ssl, NULL,
520 BIO_puts(bio_err, "cert_status: error querying responder\n");
524 ret = SSL_TLSEXT_ERR_OK;
528 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
531 * If we parsed aia we need to free; otherwise they were copied and we
538 X509_email_free(aia);
540 OCSP_CERTID_free(id);
541 OCSP_REQUEST_free(req);
542 X509_STORE_CTX_free(inctx);
547 * Certificate Status callback. This is called when a client includes a
548 * certificate status request extension. The response is either obtained from a
549 * file, or from an OCSP responder.
551 static int cert_status_cb(SSL *s, void *arg)
553 tlsextstatusctx *srctx = arg;
554 OCSP_RESPONSE *resp = NULL;
555 unsigned char *rspder = NULL;
557 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
560 BIO_puts(bio_err, "cert_status: callback called\n");
562 if (srctx->respin != NULL) {
563 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
564 if (derbio == NULL) {
565 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
568 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
571 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
575 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
576 if (ret != SSL_TLSEXT_ERR_OK)
580 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
584 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
585 if (srctx->verbose) {
586 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
587 OCSP_RESPONSE_print(bio_err, resp, 2);
590 ret = SSL_TLSEXT_ERR_OK;
593 if (ret != SSL_TLSEXT_ERR_OK)
594 ERR_print_errors(bio_err);
596 OCSP_RESPONSE_free(resp);
602 #ifndef OPENSSL_NO_NEXTPROTONEG
603 /* This is the context that we pass to next_proto_cb */
604 typedef struct tlsextnextprotoctx_st {
607 } tlsextnextprotoctx;
609 static int next_proto_cb(SSL *s, const unsigned char **data,
610 unsigned int *len, void *arg)
612 tlsextnextprotoctx *next_proto = arg;
614 *data = next_proto->data;
615 *len = next_proto->len;
617 return SSL_TLSEXT_ERR_OK;
619 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
621 /* This the context that we pass to alpn_cb */
622 typedef struct tlsextalpnctx_st {
627 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
628 const unsigned char *in, unsigned int inlen, void *arg)
630 tlsextalpnctx *alpn_ctx = arg;
633 /* We can assume that |in| is syntactically valid. */
635 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
636 for (i = 0; i < inlen;) {
638 BIO_write(bio_s_out, ", ", 2);
639 BIO_write(bio_s_out, &in[i + 1], in[i]);
642 BIO_write(bio_s_out, "\n", 1);
645 if (SSL_select_next_proto
646 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
647 inlen) != OPENSSL_NPN_NEGOTIATED) {
648 return SSL_TLSEXT_ERR_NOACK;
652 BIO_printf(bio_s_out, "ALPN protocols selected: ");
653 BIO_write(bio_s_out, *out, *outlen);
654 BIO_write(bio_s_out, "\n", 1);
657 return SSL_TLSEXT_ERR_OK;
660 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
662 /* disable resumption for sessions with forward secure ciphers */
663 return is_forward_secure;
666 #ifndef OPENSSL_NO_SRP
667 static srpsrvparm srp_callback_parm;
669 #ifndef OPENSSL_NO_SRTP
670 static char *srtp_profiles = NULL;
673 typedef enum OPTION_choice {
674 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE,
675 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
676 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
677 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
678 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
679 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
680 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
681 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
682 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
683 OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
684 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
685 OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
686 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
687 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
688 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE,
689 OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC,
691 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
692 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
693 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN,
694 OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
695 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN,
696 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
697 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_EARLY_DATA,
703 const OPTIONS s_server_options[] = {
704 {"help", OPT_HELP, '-', "Display this summary"},
705 {"port", OPT_PORT, 'p',
706 "TCP/IP port to listen on for connections (default is " PORT ")"},
707 {"accept", OPT_ACCEPT, 's',
708 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
710 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
712 {"4", OPT_4, '-', "Use IPv4 only"},
713 {"6", OPT_6, '-', "Use IPv6 only"},
715 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
717 {"context", OPT_CONTEXT, 's', "Set session ID context"},
718 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
719 {"Verify", OPT_UPPER_V_VERIFY, 'n',
720 "Turn on peer certificate verification, must have a cert"},
721 {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT},
722 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
723 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
724 {"serverinfo", OPT_SERVERINFO, 's',
725 "PEM serverinfo file for certificate"},
726 {"certform", OPT_CERTFORM, 'F',
727 "Certificate format (PEM or DER) PEM default"},
728 {"key", OPT_KEY, '<',
729 "Private Key if not in -cert; default is " TEST_CERT},
730 {"keyform", OPT_KEYFORM, 'f',
731 "Key format (PEM, DER or ENGINE) PEM default"},
732 {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
733 {"dcert", OPT_DCERT, '<',
734 "Second certificate file to use (usually for DSA)"},
735 {"dcertform", OPT_DCERTFORM, 'F',
736 "Second certificate format (PEM or DER) PEM default"},
737 {"dkey", OPT_DKEY, '<',
738 "Second private key file to use (usually for DSA)"},
739 {"dkeyform", OPT_DKEYFORM, 'F',
740 "Second key format (PEM, DER or ENGINE) PEM default"},
741 {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"},
742 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
743 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
744 {"debug", OPT_DEBUG, '-', "Print more output"},
745 {"msg", OPT_MSG, '-', "Show protocol messages"},
746 {"msgfile", OPT_MSGFILE, '>',
747 "File to send output of -msg or -trace, instead of stdout"},
748 {"state", OPT_STATE, '-', "Print the SSL states"},
749 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
750 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
751 {"no-CAfile", OPT_NOCAFILE, '-',
752 "Do not load the default certificates file"},
753 {"no-CApath", OPT_NOCAPATH, '-',
754 "Do not load certificates from the default certificates directory"},
755 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
756 {"quiet", OPT_QUIET, '-', "No server output"},
757 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
758 "Disable caching and tickets if ephemeral (EC)DH is used"},
759 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
760 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
761 {"servername", OPT_SERVERNAME, 's',
762 "Servername for HostName TLS extension"},
763 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
764 "mismatch send fatal alert (default warning alert)"},
765 {"cert2", OPT_CERT2, '<',
766 "Certificate file to use for servername; default is" TEST_CERT2},
767 {"key2", OPT_KEY2, '<',
768 "-Private Key file to use for servername if not in -cert2"},
769 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
770 "Hex dump of all TLS extensions received"},
771 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
772 {"id_prefix", OPT_ID_PREFIX, 's',
773 "Generate SSL/TLS session IDs prefixed by arg"},
774 {"rand", OPT_RAND, 's',
775 "Load the file(s) into the random number generator"},
776 {"keymatexport", OPT_KEYMATEXPORT, 's',
777 "Export keying material using label"},
778 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
779 "Export len bytes of keying material (default 20)"},
780 {"CRL", OPT_CRL, '<', "CRL file to use"},
781 {"crl_download", OPT_CRL_DOWNLOAD, '-',
782 "Download CRL from distribution points"},
783 {"cert_chain", OPT_CERT_CHAIN, '<',
784 "certificate chain file in PEM format"},
785 {"dcert_chain", OPT_DCERT_CHAIN, '<',
786 "second certificate chain file in PEM format"},
787 {"chainCApath", OPT_CHAINCAPATH, '/',
788 "use dir as certificate store path to build CA certificate chain"},
789 {"verifyCApath", OPT_VERIFYCAPATH, '/',
790 "use dir as certificate store path to verify CA certificate"},
791 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
792 {"ext_cache", OPT_EXT_CACHE, '-',
793 "Disable internal cache, setup and use external cache"},
794 {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
795 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
796 "Close connection on verification error"},
797 {"verify_quiet", OPT_VERIFY_QUIET, '-',
798 "No verify output except verify errors"},
799 {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
800 {"chainCAfile", OPT_CHAINCAFILE, '<',
801 "CA file for certificate chain (PEM format)"},
802 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
803 "CA file for certificate verification (PEM format)"},
804 {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"},
805 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"},
806 #ifndef OPENSSL_NO_OCSP
807 {"status", OPT_STATUS, '-', "Request certificate status from server"},
808 {"status_verbose", OPT_STATUS_VERBOSE, '-',
809 "Print more output in certificate status callback"},
810 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
811 "Status request responder timeout"},
812 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
813 {"status_file", OPT_STATUS_FILE, '<',
814 "File containing DER encoded OCSP Response"},
816 #ifndef OPENSSL_NO_SSL_TRACE
817 {"trace", OPT_TRACE, '-', "trace protocol messages"},
819 {"security_debug", OPT_SECURITY_DEBUG, '-',
820 "Print output from SSL/TLS security framework"},
821 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
822 "Print more output from SSL/TLS security framework"},
823 {"brief", OPT_BRIEF, '-',
824 "Restrict output to brief summary of connection parameters"},
825 {"rev", OPT_REV, '-',
826 "act as a simple test server which just sends back with the received text reversed"},
827 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
828 {"ssl_config", OPT_SSL_CONFIG, 's',
829 "Configure SSL_CTX using the configuration 'val'"},
830 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
831 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
832 "Size used to split data for encrypt pipelines"},
833 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
834 "Maximum number of encrypt/decrypt pipelines to be used"},
835 {"read_buf", OPT_READ_BUF, 'p',
836 "Default read buffer size to be used for connections"},
840 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
841 #ifndef OPENSSL_NO_PSK
842 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
843 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
844 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
846 #ifndef OPENSSL_NO_SRP
847 {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"},
848 {"srpuserseed", OPT_SRPUSERSEED, 's',
849 "A seed string for a default user salt"},
851 #ifndef OPENSSL_NO_SSL3
852 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
854 #ifndef OPENSSL_NO_TLS1
855 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
857 #ifndef OPENSSL_NO_TLS1_1
858 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
860 #ifndef OPENSSL_NO_TLS1_2
861 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
863 #ifndef OPENSSL_NO_TLS1_3
864 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
866 #ifndef OPENSSL_NO_DTLS
867 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
868 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
869 {"mtu", OPT_MTU, 'p', "Set link layer MTU"},
870 {"listen", OPT_LISTEN, '-',
871 "Listen for a DTLS ClientHello with a cookie and then connect"},
873 #ifndef OPENSSL_NO_DTLS1
874 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
876 #ifndef OPENSSL_NO_DTLS1_2
877 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
879 #ifndef OPENSSL_NO_SCTP
880 {"sctp", OPT_SCTP, '-', "Use SCTP"},
882 #ifndef OPENSSL_NO_DH
883 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
885 #ifndef OPENSSL_NO_NEXTPROTONEG
886 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
887 "Set the advertised protocols for the NPN extension (comma-separated list)"},
889 #ifndef OPENSSL_NO_SRTP
890 {"use_srtp", OPT_SRTP_PROFILES, 's',
891 "Offer SRTP key management with a colon-separated profile list"},
893 {"alpn", OPT_ALPN, 's',
894 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
895 #ifndef OPENSSL_NO_ENGINE
896 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
898 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
899 {"max_early_data", OPT_MAX_EARLY, 'n',
900 "The maximum number of bytes of early data"},
901 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
902 {NULL, OPT_EOF, 0, NULL}
905 #define IS_PROT_FLAG(o) \
906 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
907 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
909 int s_server_main(int argc, char *argv[])
911 ENGINE *engine = NULL;
912 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
913 SSL_CONF_CTX *cctx = NULL;
914 const SSL_METHOD *meth = TLS_server_method();
915 SSL_EXCERT *exc = NULL;
916 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
917 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
918 STACK_OF(X509_CRL) *crls = NULL;
919 X509 *s_cert = NULL, *s_dcert = NULL;
920 X509_VERIFY_PARAM *vpm = NULL;
921 const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL;
922 char *dpassarg = NULL, *dpass = NULL, *inrand = NULL;
923 char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
924 char *crl_file = NULL, *prog;
926 int unlink_unix_path = 0;
928 do_server_cb server_cb;
929 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
930 #ifndef OPENSSL_NO_DH
934 int nocert = 0, ret = 1;
935 int noCApath = 0, noCAfile = 0;
936 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
937 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
938 int rev = 0, naccept = -1, sdebug = 0;
939 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
940 int state = 0, crl_format = FORMAT_PEM, crl_download = 0;
942 char *port = BUF_strdup(PORT);
943 unsigned char *context = NULL;
945 EVP_PKEY *s_key2 = NULL;
946 X509 *s_cert2 = NULL;
947 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
948 const char *ssl_config = NULL;
949 int read_buf_len = 0;
950 #ifndef OPENSSL_NO_NEXTPROTONEG
951 const char *next_proto_neg_in = NULL;
952 tlsextnextprotoctx next_proto = { NULL, 0 };
954 const char *alpn_in = NULL;
955 tlsextalpnctx alpn_ctx = { NULL, 0 };
956 #ifndef OPENSSL_NO_PSK
957 /* by default do not send a PSK identity hint */
958 char *psk_identity_hint = NULL;
961 #ifndef OPENSSL_NO_SRP
962 char *srpuserseed = NULL;
963 char *srp_verifier_file = NULL;
965 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
966 int s_server_verify = SSL_VERIFY_NONE;
967 int s_server_session_id_context = 1; /* anything will do */
968 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
969 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
970 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
971 #ifndef OPENSSL_NO_OCSP
972 int s_tlsextstatus = 0;
974 int no_resume_ephemeral = 0;
975 unsigned int max_send_fragment = 0;
976 unsigned int split_send_fragment = 0, max_pipelines = 0;
977 const char *s_serverinfo_file = NULL;
978 const char *keylog_file = NULL;
979 int max_early_data = -1;
981 /* Init of few remaining global variables */
986 s_nbio = s_nbio_test = 0;
995 cctx = SSL_CONF_CTX_new();
996 vpm = X509_VERIFY_PARAM_new();
997 if (cctx == NULL || vpm == NULL)
999 SSL_CONF_CTX_set_flags(cctx,
1000 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1002 prog = opt_init(argc, argv, s_server_options);
1003 while ((o = opt_next()) != OPT_EOF) {
1004 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1005 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1008 if (IS_NO_PROT_FLAG(o))
1010 if (prot_opt == 1 && no_prot_opt) {
1012 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1019 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1022 opt_help(s_server_options);
1028 if (socket_family == AF_UNIX) {
1029 OPENSSL_free(host); host = NULL;
1030 OPENSSL_free(port); port = NULL;
1033 socket_family = AF_INET;
1039 if (socket_family == AF_UNIX) {
1040 OPENSSL_free(host); host = NULL;
1041 OPENSSL_free(port); port = NULL;
1044 socket_family = AF_INET6;
1047 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1053 if (socket_family == AF_UNIX) {
1054 socket_family = AF_UNSPEC;
1057 OPENSSL_free(port); port = NULL;
1058 OPENSSL_free(host); host = NULL;
1059 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1061 "%s: -port argument malformed or ambiguous\n",
1068 if (socket_family == AF_UNIX) {
1069 socket_family = AF_UNSPEC;
1072 OPENSSL_free(port); port = NULL;
1073 OPENSSL_free(host); host = NULL;
1074 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1076 "%s: -accept argument malformed or ambiguous\n",
1083 socket_family = AF_UNIX;
1084 OPENSSL_free(host); host = BUF_strdup(opt_arg());
1085 OPENSSL_free(port); port = NULL;
1088 unlink_unix_path = 1;
1092 naccept = atol(opt_arg());
1095 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1096 verify_args.depth = atoi(opt_arg());
1098 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1100 case OPT_UPPER_V_VERIFY:
1102 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1103 SSL_VERIFY_CLIENT_ONCE;
1104 verify_args.depth = atoi(opt_arg());
1107 "verify depth is %d, must return a certificate\n",
1111 context = (unsigned char *)opt_arg();
1114 s_cert_file = opt_arg();
1117 if (!set_nameopt(opt_arg()))
1121 crl_file = opt_arg();
1123 case OPT_CRL_DOWNLOAD:
1126 case OPT_SERVERINFO:
1127 s_serverinfo_file = opt_arg();
1130 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format))
1134 s_key_file = opt_arg();
1137 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1141 passarg = opt_arg();
1143 case OPT_CERT_CHAIN:
1144 s_chain_file = opt_arg();
1147 #ifndef OPENSSL_NO_DH
1152 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format))
1156 s_dcert_file = opt_arg();
1159 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format))
1163 dpassarg = opt_arg();
1166 s_dkey_file = opt_arg();
1168 case OPT_DCERT_CHAIN:
1169 s_dchain_file = opt_arg();
1180 case OPT_CHAINCAPATH:
1181 chCApath = opt_arg();
1183 case OPT_VERIFYCAPATH:
1184 vfyCApath = opt_arg();
1193 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1197 if (ssl_args == NULL)
1198 ssl_args = sk_OPENSSL_STRING_new_null();
1199 if (ssl_args == NULL
1200 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1201 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1202 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1207 if (!opt_verify(o, vpm))
1212 if (!args_excert(o, &exc))
1215 case OPT_VERIFY_RET_ERROR:
1216 verify_args.return_error = 1;
1218 case OPT_VERIFY_QUIET:
1219 verify_args.quiet = 1;
1221 case OPT_BUILD_CHAIN:
1230 case OPT_CHAINCAFILE:
1231 chCAfile = opt_arg();
1233 case OPT_VERIFYCAFILE:
1234 vfyCAfile = opt_arg();
1240 s_nbio = s_nbio_test = 1;
1245 case OPT_NO_IGN_EOF:
1251 case OPT_TLSEXTDEBUG:
1255 #ifndef OPENSSL_NO_OCSP
1259 case OPT_STATUS_VERBOSE:
1260 #ifndef OPENSSL_NO_OCSP
1261 s_tlsextstatus = tlscstatp.verbose = 1;
1264 case OPT_STATUS_TIMEOUT:
1265 #ifndef OPENSSL_NO_OCSP
1267 tlscstatp.timeout = atoi(opt_arg());
1270 case OPT_STATUS_URL:
1271 #ifndef OPENSSL_NO_OCSP
1273 if (!OCSP_parse_url(opt_arg(),
1276 &tlscstatp.path, &tlscstatp.use_ssl)) {
1277 BIO_printf(bio_err, "Error parsing URL\n");
1282 case OPT_STATUS_FILE:
1283 #ifndef OPENSSL_NO_OCSP
1285 tlscstatp.respin = opt_arg();
1292 bio_s_msg = BIO_new_file(opt_arg(), "w");
1295 #ifndef OPENSSL_NO_SSL_TRACE
1299 case OPT_SECURITY_DEBUG:
1302 case OPT_SECURITY_DEBUG_VERBOSE:
1315 s_quiet = s_brief = verify_args.quiet = 1;
1318 #ifndef OPENSSL_NO_DH
1322 case OPT_NO_RESUME_EPHEMERAL:
1323 no_resume_ephemeral = 1;
1325 case OPT_PSK_IDENTITY:
1326 #ifndef OPENSSL_NO_PSK
1327 psk_identity = opt_arg();
1331 #ifndef OPENSSL_NO_PSK
1332 psk_identity_hint = opt_arg();
1336 #ifndef OPENSSL_NO_PSK
1337 for (p = psk_key = opt_arg(); *p; p++) {
1338 if (isxdigit(_UC(*p)))
1340 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1346 #ifndef OPENSSL_NO_SRP
1347 srp_verifier_file = opt_arg();
1348 if (min_version < TLS1_VERSION)
1349 min_version = TLS1_VERSION;
1352 case OPT_SRPUSERSEED:
1353 #ifndef OPENSSL_NO_SRP
1354 srpuserseed = opt_arg();
1355 if (min_version < TLS1_VERSION)
1356 min_version = TLS1_VERSION;
1371 case OPT_SSL_CONFIG:
1372 ssl_config = opt_arg();
1375 min_version = SSL3_VERSION;
1376 max_version = SSL3_VERSION;
1379 min_version = TLS1_3_VERSION;
1380 max_version = TLS1_3_VERSION;
1383 min_version = TLS1_2_VERSION;
1384 max_version = TLS1_2_VERSION;
1387 min_version = TLS1_1_VERSION;
1388 max_version = TLS1_1_VERSION;
1391 min_version = TLS1_VERSION;
1392 max_version = TLS1_VERSION;
1395 #ifndef OPENSSL_NO_DTLS
1396 meth = DTLS_server_method();
1397 socket_type = SOCK_DGRAM;
1401 #ifndef OPENSSL_NO_DTLS
1402 meth = DTLS_server_method();
1403 min_version = DTLS1_VERSION;
1404 max_version = DTLS1_VERSION;
1405 socket_type = SOCK_DGRAM;
1409 #ifndef OPENSSL_NO_DTLS
1410 meth = DTLS_server_method();
1411 min_version = DTLS1_2_VERSION;
1412 max_version = DTLS1_2_VERSION;
1413 socket_type = SOCK_DGRAM;
1417 #ifndef OPENSSL_NO_SCTP
1418 protocol = IPPROTO_SCTP;
1422 #ifndef OPENSSL_NO_DTLS
1423 enable_timeouts = 1;
1427 #ifndef OPENSSL_NO_DTLS
1428 socket_mtu = atol(opt_arg());
1432 #ifndef OPENSSL_NO_DTLS
1437 session_id_prefix = opt_arg();
1440 engine = setup_engine(opt_arg(), 1);
1445 case OPT_SERVERNAME:
1446 tlsextcbp.servername = opt_arg();
1448 case OPT_SERVERNAME_FATAL:
1449 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1452 s_cert_file2 = opt_arg();
1455 s_key_file2 = opt_arg();
1457 case OPT_NEXTPROTONEG:
1458 # ifndef OPENSSL_NO_NEXTPROTONEG
1459 next_proto_neg_in = opt_arg();
1463 alpn_in = opt_arg();
1465 case OPT_SRTP_PROFILES:
1466 #ifndef OPENSSL_NO_SRTP
1467 srtp_profiles = opt_arg();
1470 case OPT_KEYMATEXPORT:
1471 keymatexportlabel = opt_arg();
1473 case OPT_KEYMATEXPORTLEN:
1474 keymatexportlen = atoi(opt_arg());
1479 case OPT_MAX_SEND_FRAG:
1480 max_send_fragment = atoi(opt_arg());
1482 case OPT_SPLIT_SEND_FRAG:
1483 split_send_fragment = atoi(opt_arg());
1485 case OPT_MAX_PIPELINES:
1486 max_pipelines = atoi(opt_arg());
1489 read_buf_len = atoi(opt_arg());
1491 case OPT_KEYLOG_FILE:
1492 keylog_file = opt_arg();
1495 max_early_data = atoi(opt_arg());
1496 if (max_early_data < 0) {
1497 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1501 case OPT_EARLY_DATA:
1506 argc = opt_num_rest();
1509 #ifndef OPENSSL_NO_NEXTPROTONEG
1510 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1511 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1515 #ifndef OPENSSL_NO_DTLS
1516 if (www && socket_type == SOCK_DGRAM) {
1517 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1521 if (dtlslisten && socket_type != SOCK_DGRAM) {
1522 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1528 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1530 "Can't use unix sockets and datagrams together\n");
1535 #ifndef OPENSSL_NO_SCTP
1536 if (protocol == IPPROTO_SCTP) {
1537 if (socket_type != SOCK_DGRAM) {
1538 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1541 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1542 socket_type = SOCK_STREAM;
1546 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1547 BIO_printf(bio_err, "Error getting password\n");
1551 if (s_key_file == NULL)
1552 s_key_file = s_cert_file;
1554 if (s_key_file2 == NULL)
1555 s_key_file2 = s_cert_file2;
1557 if (!load_excert(&exc))
1561 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1562 "server certificate private key file");
1563 if (s_key == NULL) {
1564 ERR_print_errors(bio_err);
1568 s_cert = load_cert(s_cert_file, s_cert_format,
1569 "server certificate file");
1571 if (s_cert == NULL) {
1572 ERR_print_errors(bio_err);
1575 if (s_chain_file != NULL) {
1576 if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL,
1577 "server certificate chain"))
1581 if (tlsextcbp.servername != NULL) {
1582 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1583 "second server certificate private key file");
1584 if (s_key2 == NULL) {
1585 ERR_print_errors(bio_err);
1589 s_cert2 = load_cert(s_cert_file2, s_cert_format,
1590 "second server certificate file");
1592 if (s_cert2 == NULL) {
1593 ERR_print_errors(bio_err);
1598 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1599 if (next_proto_neg_in) {
1600 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1601 if (next_proto.data == NULL)
1605 alpn_ctx.data = NULL;
1607 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1608 if (alpn_ctx.data == NULL)
1612 if (crl_file != NULL) {
1614 crl = load_crl(crl_file, crl_format);
1616 BIO_puts(bio_err, "Error loading CRL\n");
1617 ERR_print_errors(bio_err);
1620 crls = sk_X509_CRL_new_null();
1621 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1622 BIO_puts(bio_err, "Error adding CRL\n");
1623 ERR_print_errors(bio_err);
1629 if (s_dcert_file != NULL) {
1631 if (s_dkey_file == NULL)
1632 s_dkey_file = s_dcert_file;
1634 s_dkey = load_key(s_dkey_file, s_dkey_format,
1635 0, dpass, engine, "second certificate private key file");
1636 if (s_dkey == NULL) {
1637 ERR_print_errors(bio_err);
1641 s_dcert = load_cert(s_dcert_file, s_dcert_format,
1642 "second server certificate file");
1644 if (s_dcert == NULL) {
1645 ERR_print_errors(bio_err);
1648 if (s_dchain_file != NULL) {
1649 if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL,
1650 "second server certificate chain"))
1656 if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1657 && !RAND_status()) {
1659 "warning, not much extra random data, consider using the -rand option\n");
1662 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
1663 app_RAND_load_files(inrand));
1665 if (bio_s_out == NULL) {
1666 if (s_quiet && !s_debug) {
1667 bio_s_out = BIO_new(BIO_s_null());
1668 if (s_msg && bio_s_msg == NULL)
1669 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1671 if (bio_s_out == NULL)
1672 bio_s_out = dup_bio_out(FORMAT_TEXT);
1675 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
1681 s_dcert_file = NULL;
1683 s_cert_file2 = NULL;
1687 ctx = SSL_CTX_new(meth);
1689 ERR_print_errors(bio_err);
1693 ssl_ctx_security_debug(ctx, sdebug);
1695 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1696 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1698 ERR_print_errors(bio_err);
1702 if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1704 if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1707 if (session_id_prefix) {
1708 if (strlen(session_id_prefix) >= 32)
1710 "warning: id_prefix is too long, only one new session will be possible\n");
1711 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1712 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1713 ERR_print_errors(bio_err);
1716 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1718 SSL_CTX_set_quiet_shutdown(ctx, 1);
1720 ssl_ctx_set_excert(ctx, exc);
1723 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1725 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1727 init_session_cache_ctx(ctx);
1729 SSL_CTX_sess_set_cache_size(ctx, 128);
1732 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1735 if (max_send_fragment > 0
1736 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1737 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1738 prog, max_send_fragment);
1742 if (split_send_fragment > 0
1743 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1744 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1745 prog, split_send_fragment);
1748 if (max_pipelines > 0
1749 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1750 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1751 prog, max_pipelines);
1755 if (read_buf_len > 0) {
1756 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1758 #ifndef OPENSSL_NO_SRTP
1759 if (srtp_profiles != NULL) {
1760 /* Returns 0 on success! */
1761 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1762 BIO_printf(bio_err, "Error setting SRTP profile\n");
1763 ERR_print_errors(bio_err);
1769 if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1770 ERR_print_errors(bio_err);
1773 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1774 BIO_printf(bio_err, "Error setting verify params\n");
1775 ERR_print_errors(bio_err);
1779 ssl_ctx_add_crls(ctx, crls, 0);
1780 if (!config_ctx(cctx, ssl_args, ctx))
1783 if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1784 crls, crl_download)) {
1785 BIO_printf(bio_err, "Error loading store locations\n");
1786 ERR_print_errors(bio_err);
1791 ctx2 = SSL_CTX_new(meth);
1793 ERR_print_errors(bio_err);
1799 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1802 ssl_ctx_security_debug(ctx, sdebug);
1804 if (session_id_prefix) {
1805 if (strlen(session_id_prefix) >= 32)
1807 "warning: id_prefix is too long, only one new session will be possible\n");
1808 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1809 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1810 ERR_print_errors(bio_err);
1813 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1815 SSL_CTX_set_quiet_shutdown(ctx2, 1);
1817 ssl_ctx_set_excert(ctx2, exc);
1820 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1823 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1825 init_session_cache_ctx(ctx2);
1827 SSL_CTX_sess_set_cache_size(ctx2, 128);
1830 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
1832 if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile,
1834 ERR_print_errors(bio_err);
1837 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
1838 BIO_printf(bio_err, "Error setting verify params\n");
1839 ERR_print_errors(bio_err);
1843 ssl_ctx_add_crls(ctx2, crls, 0);
1844 if (!config_ctx(cctx, ssl_args, ctx2))
1847 #ifndef OPENSSL_NO_NEXTPROTONEG
1848 if (next_proto.data)
1849 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
1853 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1855 #ifndef OPENSSL_NO_DH
1860 dh = load_dh_param(dhfile);
1861 else if (s_cert_file != NULL)
1862 dh = load_dh_param(s_cert_file);
1865 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1867 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1869 (void)BIO_flush(bio_s_out);
1872 SSL_CTX_set_dh_auto(ctx, 1);
1873 } else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
1874 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1875 ERR_print_errors(bio_err);
1882 DH *dh2 = load_dh_param(s_cert_file2);
1884 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1885 (void)BIO_flush(bio_s_out);
1892 SSL_CTX_set_dh_auto(ctx2, 1);
1893 } else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
1894 BIO_puts(bio_err, "Error setting temp DH parameters\n");
1895 ERR_print_errors(bio_err);
1904 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1907 if (s_serverinfo_file != NULL
1908 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
1909 ERR_print_errors(bio_err);
1914 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
1917 if (s_dcert != NULL) {
1918 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1922 if (no_resume_ephemeral) {
1923 SSL_CTX_set_not_resumable_session_callback(ctx,
1924 not_resumable_sess_cb);
1927 SSL_CTX_set_not_resumable_session_callback(ctx2,
1928 not_resumable_sess_cb);
1930 #ifndef OPENSSL_NO_PSK
1931 if (psk_key != NULL) {
1933 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
1934 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1937 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
1938 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
1939 ERR_print_errors(bio_err);
1944 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1945 if (!SSL_CTX_set_session_id_context(ctx,
1946 (void *)&s_server_session_id_context,
1947 sizeof s_server_session_id_context)) {
1948 BIO_printf(bio_err, "error setting session id context\n");
1949 ERR_print_errors(bio_err);
1953 /* Set DTLS cookie generation and verification callbacks */
1954 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1955 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1958 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1959 if (!SSL_CTX_set_session_id_context(ctx2,
1960 (void *)&s_server_session_id_context,
1961 sizeof s_server_session_id_context)) {
1962 BIO_printf(bio_err, "error setting session id context\n");
1963 ERR_print_errors(bio_err);
1966 tlsextcbp.biodebug = bio_s_out;
1967 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1968 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1969 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1970 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1973 #ifndef OPENSSL_NO_SRP
1974 if (srp_verifier_file != NULL) {
1975 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
1976 srp_callback_parm.user = NULL;
1977 srp_callback_parm.login = NULL;
1979 SRP_VBASE_init(srp_callback_parm.vb,
1980 srp_verifier_file)) != SRP_NO_ERROR) {
1982 "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1983 srp_verifier_file, ret);
1986 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
1987 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
1988 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1991 if (CAfile != NULL) {
1992 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
1995 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
1997 #ifndef OPENSSL_NO_OCSP
1998 if (s_tlsextstatus) {
1999 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2000 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2002 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2003 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2007 if (set_keylog_file(ctx, keylog_file))
2010 if (max_early_data >= 0)
2011 SSL_CTX_set_max_early_data(ctx, max_early_data);
2013 BIO_printf(bio_s_out, "ACCEPT\n");
2014 (void)BIO_flush(bio_s_out);
2016 server_cb = rev_body;
2018 server_cb = www_body;
2020 server_cb = sv_body;
2022 if (socket_family == AF_UNIX
2023 && unlink_unix_path)
2026 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2027 server_cb, context, naccept);
2028 print_stats(bio_s_out, ctx);
2032 set_keylog_file(NULL, NULL);
2034 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2036 EVP_PKEY_free(s_key);
2037 EVP_PKEY_free(s_dkey);
2038 sk_X509_pop_free(s_chain, X509_free);
2039 sk_X509_pop_free(s_dchain, X509_free);
2041 OPENSSL_free(dpass);
2044 X509_VERIFY_PARAM_free(vpm);
2046 OPENSSL_free(tlscstatp.host);
2047 OPENSSL_free(tlscstatp.port);
2048 OPENSSL_free(tlscstatp.path);
2051 EVP_PKEY_free(s_key2);
2052 #ifndef OPENSSL_NO_NEXTPROTONEG
2053 OPENSSL_free(next_proto.data);
2055 OPENSSL_free(alpn_ctx.data);
2056 ssl_excert_free(exc);
2057 sk_OPENSSL_STRING_free(ssl_args);
2058 SSL_CONF_CTX_free(cctx);
2059 release_engine(engine);
2060 BIO_free(bio_s_out);
2062 BIO_free(bio_s_msg);
2064 #ifdef CHARSET_EBCDIC
2065 BIO_meth_free(methods_ebcdic);
2070 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2072 BIO_printf(bio, "%4ld items in the session cache\n",
2073 SSL_CTX_sess_number(ssl_ctx));
2074 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2075 SSL_CTX_sess_connect(ssl_ctx));
2076 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2077 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2078 BIO_printf(bio, "%4ld client connects that finished\n",
2079 SSL_CTX_sess_connect_good(ssl_ctx));
2080 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2081 SSL_CTX_sess_accept(ssl_ctx));
2082 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2083 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2084 BIO_printf(bio, "%4ld server accepts that finished\n",
2085 SSL_CTX_sess_accept_good(ssl_ctx));
2086 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2087 BIO_printf(bio, "%4ld session cache misses\n",
2088 SSL_CTX_sess_misses(ssl_ctx));
2089 BIO_printf(bio, "%4ld session cache timeouts\n",
2090 SSL_CTX_sess_timeouts(ssl_ctx));
2091 BIO_printf(bio, "%4ld callback cache hits\n",
2092 SSL_CTX_sess_cb_hits(ssl_ctx));
2093 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2094 SSL_CTX_sess_cache_full(ssl_ctx),
2095 SSL_CTX_sess_get_cache_size(ssl_ctx));
2098 static int sv_body(int s, int stype, int prot, unsigned char *context)
2107 struct timeval timeout;
2108 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2111 struct timeval *timeoutp;
2113 #ifndef OPENSSL_NO_DTLS
2114 # ifndef OPENSSL_NO_SCTP
2115 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2117 int isdtls = (stype == SOCK_DGRAM);
2121 buf = app_malloc(bufsize, "server buffer");
2123 if (!BIO_socket_nbio(s, 1))
2124 ERR_print_errors(bio_err);
2126 BIO_printf(bio_err, "Turned on non blocking io\n");
2132 if (s_tlsextdebug) {
2133 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2134 SSL_set_tlsext_debug_arg(con, bio_s_out);
2138 && !SSL_set_session_id_context(con,
2139 context, strlen((char *)context))) {
2140 BIO_printf(bio_err, "Error setting session id context\n");
2145 if (!SSL_clear(con)) {
2146 BIO_printf(bio_err, "Error clearing SSL connection\n");
2150 #ifndef OPENSSL_NO_DTLS
2152 # ifndef OPENSSL_NO_SCTP
2153 if (prot == IPPROTO_SCTP)
2154 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2157 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2159 if (enable_timeouts) {
2161 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2162 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2165 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2166 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2170 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2171 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2172 DTLS_get_link_min_mtu(con));
2177 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2178 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2179 BIO_printf(bio_err, "Failed to set MTU\n");
2185 /* want to do MTU discovery */
2186 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2188 # ifndef OPENSSL_NO_SCTP
2189 if (prot != IPPROTO_SCTP) {
2190 /* Turn on cookie exchange. Not necessary for SCTP */
2191 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2196 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2199 BIO_printf(bio_err, "Unable to create BIO\n");
2200 ERR_print_errors(bio_err);
2207 test = BIO_new(BIO_f_nbio_test());
2208 sbio = BIO_push(test, sbio);
2211 SSL_set_bio(con, sbio, sbio);
2212 SSL_set_accept_state(con);
2213 /* SSL_set_fd(con,s); */
2216 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2217 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2220 #ifndef OPENSSL_NO_SSL_TRACE
2222 SSL_set_msg_callback(con, SSL_trace);
2225 SSL_set_msg_callback(con, msg_cb);
2226 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2229 if (s_tlsextdebug) {
2230 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2231 SSL_set_tlsext_debug_arg(con, bio_s_out);
2235 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2238 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2240 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2241 if (edret != SSL_READ_EARLY_DATA_ERROR)
2244 switch (SSL_get_error(con, 0)) {
2245 case SSL_ERROR_WANT_WRITE:
2246 case SSL_ERROR_WANT_ASYNC:
2247 case SSL_ERROR_WANT_READ:
2248 /* Just keep trying - busy waiting */
2251 BIO_printf(bio_err, "Error reading early data\n");
2252 ERR_print_errors(bio_err);
2256 if (readbytes > 0) {
2258 BIO_printf(bio_s_out, "Early data received:\n");
2261 raw_write_stdout(buf, (unsigned int)readbytes);
2262 (void)BIO_flush(bio_s_out);
2266 BIO_printf(bio_s_out, "No early data received\n");
2268 BIO_printf(bio_s_out, "\nEnd of early data\n");
2269 if (SSL_is_init_finished(con))
2270 print_connection_info(con);
2273 if (fileno_stdin() > s)
2274 width = fileno_stdin() + 1;
2278 int read_from_terminal;
2279 int read_from_sslcon;
2281 read_from_terminal = 0;
2282 read_from_sslcon = SSL_has_pending(con)
2283 || (async && SSL_waiting_for_async(con));
2285 if (!read_from_sslcon) {
2287 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2288 openssl_fdset(fileno_stdin(), &readfds);
2290 openssl_fdset(s, &readfds);
2292 * Note: under VMS with SOCKETSHR the second parameter is
2293 * currently of type (int *) whereas under other systems it is
2294 * (void *) if you don't have a cast it will choke the compiler:
2295 * if you do have a cast then you can either go for (int *) or
2298 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2300 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2301 * only on sockets. As a workaround we timeout the select every
2302 * second and check for any keypress. In a proper Windows
2303 * application we wouldn't do this because it is inefficient.
2307 i = select(width, (void *)&readfds, NULL, NULL, &tv);
2308 if (has_stdin_waiting())
2309 read_from_terminal = 1;
2310 if ((i < 0) || (!i && !read_from_terminal))
2313 if ((SSL_version(con) == DTLS1_VERSION) &&
2314 DTLSv1_get_timeout(con, &timeout))
2315 timeoutp = &timeout;
2319 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2321 if ((SSL_version(con) == DTLS1_VERSION)
2322 && DTLSv1_handle_timeout(con) > 0) {
2323 BIO_printf(bio_err, "TIMEOUT occurred\n");
2328 if (FD_ISSET(fileno_stdin(), &readfds))
2329 read_from_terminal = 1;
2331 if (FD_ISSET(s, &readfds))
2332 read_from_sslcon = 1;
2334 if (read_from_terminal) {
2338 i = raw_read_stdin(buf, bufsize / 2);
2340 /* both loops are skipped when i <= 0 */
2341 for (j = 0; j < i; j++)
2344 for (j = i - 1; j >= 0; j--) {
2345 buf[j + lf_num] = buf[j];
2346 if (buf[j] == '\n') {
2349 buf[j + lf_num] = '\r';
2352 assert(lf_num == 0);
2354 i = raw_read_stdin(buf, bufsize);
2357 if (!s_quiet && !s_brief) {
2358 if ((i <= 0) || (buf[0] == 'Q')) {
2359 BIO_printf(bio_s_out, "DONE\n");
2360 (void)BIO_flush(bio_s_out);
2362 close_accept_socket();
2366 if ((i <= 0) || (buf[0] == 'q')) {
2367 BIO_printf(bio_s_out, "DONE\n");
2368 (void)BIO_flush(bio_s_out);
2369 if (SSL_version(con) != DTLS1_VERSION)
2372 * close_accept_socket(); ret= -11;
2376 #ifndef OPENSSL_NO_HEARTBEATS
2377 if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2378 BIO_printf(bio_err, "HEARTBEATING\n");
2384 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2385 SSL_renegotiate(con);
2386 i = SSL_do_handshake(con);
2387 printf("SSL_do_handshake -> %d\n", i);
2391 * strcpy(buf,"server side RE-NEGOTIATE\n");
2394 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2396 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2398 SSL_renegotiate(con);
2399 i = SSL_do_handshake(con);
2400 printf("SSL_do_handshake -> %d\n", i);
2404 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2408 if ((buf[0] == 'K' || buf[0] == 'k')
2409 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2410 SSL_key_update(con, buf[0] == 'K' ?
2411 SSL_KEY_UPDATE_REQUESTED
2412 : SSL_KEY_UPDATE_NOT_REQUESTED);
2413 i = SSL_do_handshake(con);
2414 printf("SSL_do_handshake -> %d\n", i);
2418 * strcpy(buf,"server side RE-NEGOTIATE asking for client
2422 if (buf[0] == 'P') {
2423 static const char *str = "Lets print some clear text\n";
2424 BIO_write(SSL_get_wbio(con), str, strlen(str));
2426 if (buf[0] == 'S') {
2427 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2430 #ifdef CHARSET_EBCDIC
2431 ebcdic2ascii(buf, buf, i);
2435 /* should do a select for the write */
2438 if (++count == 100) {
2440 SSL_renegotiate(con);
2443 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2444 #ifndef OPENSSL_NO_SRP
2445 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2446 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2447 SRP_user_pwd_free(srp_callback_parm.user);
2448 srp_callback_parm.user =
2449 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2450 srp_callback_parm.login);
2451 if (srp_callback_parm.user)
2452 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2453 srp_callback_parm.user->info);
2455 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2456 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2459 switch (SSL_get_error(con, k)) {
2460 case SSL_ERROR_NONE:
2462 case SSL_ERROR_WANT_ASYNC:
2463 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2464 (void)BIO_flush(bio_s_out);
2465 wait_for_async(con);
2467 case SSL_ERROR_WANT_WRITE:
2468 case SSL_ERROR_WANT_READ:
2469 case SSL_ERROR_WANT_X509_LOOKUP:
2470 BIO_printf(bio_s_out, "Write BLOCK\n");
2471 (void)BIO_flush(bio_s_out);
2473 case SSL_ERROR_WANT_ASYNC_JOB:
2475 * This shouldn't ever happen in s_server. Treat as an error
2477 case SSL_ERROR_SYSCALL:
2479 BIO_printf(bio_s_out, "ERROR\n");
2480 (void)BIO_flush(bio_s_out);
2481 ERR_print_errors(bio_err);
2485 case SSL_ERROR_ZERO_RETURN:
2486 BIO_printf(bio_s_out, "DONE\n");
2487 (void)BIO_flush(bio_s_out);
2499 if (read_from_sslcon) {
2501 * init_ssl_connection handles all async events itself so if we're
2502 * waiting for async then we shouldn't go back into
2503 * init_ssl_connection
2505 if ((!async || !SSL_waiting_for_async(con))
2506 && !SSL_is_init_finished(con)) {
2507 i = init_ssl_connection(con);
2512 } else if (i == 0) {
2518 i = SSL_read(con, (char *)buf, bufsize);
2519 #ifndef OPENSSL_NO_SRP
2520 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2521 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2522 SRP_user_pwd_free(srp_callback_parm.user);
2523 srp_callback_parm.user =
2524 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2525 srp_callback_parm.login);
2526 if (srp_callback_parm.user)
2527 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2528 srp_callback_parm.user->info);
2530 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2531 i = SSL_read(con, (char *)buf, bufsize);
2534 switch (SSL_get_error(con, i)) {
2535 case SSL_ERROR_NONE:
2536 #ifdef CHARSET_EBCDIC
2537 ascii2ebcdic(buf, buf, i);
2539 raw_write_stdout(buf, (unsigned int)i);
2540 (void)BIO_flush(bio_s_out);
2541 if (SSL_has_pending(con))
2544 case SSL_ERROR_WANT_ASYNC:
2545 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2546 (void)BIO_flush(bio_s_out);
2547 wait_for_async(con);
2549 case SSL_ERROR_WANT_WRITE:
2550 case SSL_ERROR_WANT_READ:
2551 BIO_printf(bio_s_out, "Read BLOCK\n");
2552 (void)BIO_flush(bio_s_out);
2554 case SSL_ERROR_WANT_ASYNC_JOB:
2556 * This shouldn't ever happen in s_server. Treat as an error
2558 case SSL_ERROR_SYSCALL:
2560 BIO_printf(bio_s_out, "ERROR\n");
2561 (void)BIO_flush(bio_s_out);
2562 ERR_print_errors(bio_err);
2565 case SSL_ERROR_ZERO_RETURN:
2566 BIO_printf(bio_s_out, "DONE\n");
2567 (void)BIO_flush(bio_s_out);
2576 BIO_printf(bio_s_out, "shutting down SSL\n");
2577 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2580 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2581 OPENSSL_clear_free(buf, bufsize);
2583 BIO_printf(bio_s_out, "ACCEPT\n");
2584 (void)BIO_flush(bio_s_out);
2588 static void close_accept_socket(void)
2590 BIO_printf(bio_err, "shutdown accept socket\n");
2591 if (accept_socket >= 0) {
2592 BIO_closesocket(accept_socket);
2596 static int is_retryable(SSL *con, int i)
2598 int err = SSL_get_error(con, i);
2600 /* If it's not a fatal error, it must be retryable */
2601 return (err != SSL_ERROR_SSL)
2602 && (err != SSL_ERROR_SYSCALL)
2603 && (err != SSL_ERROR_ZERO_RETURN);
2606 static int init_ssl_connection(SSL *con)
2612 #ifndef OPENSSL_NO_DTLS
2614 BIO_ADDR *client = NULL;
2616 if ((client = BIO_ADDR_new()) == NULL) {
2617 BIO_printf(bio_err, "ERROR - memory\n");
2620 i = DTLSv1_listen(con, client);
2625 wbio = SSL_get_wbio(con);
2627 BIO_get_fd(wbio, &fd);
2630 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2631 BIO_printf(bio_err, "ERROR - unable to connect\n");
2632 BIO_ADDR_free(client);
2635 BIO_ADDR_free(client);
2637 i = SSL_accept(con);
2639 BIO_ADDR_free(client);
2645 i = SSL_accept(con);
2648 retry = is_retryable(con, i);
2649 #ifdef CERT_CB_TEST_RETRY
2652 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2653 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2655 "LOOKUP from certificate callback during accept\n");
2656 i = SSL_accept(con);
2658 retry = is_retryable(con, i);
2663 #ifndef OPENSSL_NO_SRP
2665 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2666 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
2667 srp_callback_parm.login);
2668 SRP_user_pwd_free(srp_callback_parm.user);
2669 srp_callback_parm.user =
2670 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2671 srp_callback_parm.login);
2672 if (srp_callback_parm.user)
2673 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2674 srp_callback_parm.user->info);
2676 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2677 i = SSL_accept(con);
2679 retry = is_retryable(con, i);
2682 } while (i < 0 && SSL_waiting_for_async(con));
2685 if ((dtlslisten && i == 0)
2686 || (!dtlslisten && retry)) {
2687 BIO_printf(bio_s_out, "DELAY\n");
2691 BIO_printf(bio_err, "ERROR\n");
2693 verify_err = SSL_get_verify_result(con);
2694 if (verify_err != X509_V_OK) {
2695 BIO_printf(bio_err, "verify error:%s\n",
2696 X509_verify_cert_error_string(verify_err));
2698 /* Always print any error messages */
2699 ERR_print_errors(bio_err);
2703 print_connection_info(con);
2707 static void print_connection_info(SSL *con)
2712 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2713 const unsigned char *next_proto_neg;
2714 unsigned next_proto_neg_len;
2716 unsigned char *exportedkeymat;
2720 print_ssl_summary(con);
2722 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
2724 peer = SSL_get_peer_certificate(con);
2726 BIO_printf(bio_s_out, "Client certificate\n");
2727 PEM_write_bio_X509(bio_s_out, peer);
2728 dump_cert_text(bio_s_out, peer);
2733 if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
2734 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
2735 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2736 ssl_print_sigalgs(bio_s_out, con);
2737 #ifndef OPENSSL_NO_EC
2738 ssl_print_point_formats(bio_s_out, con);
2739 ssl_print_groups(bio_s_out, con, 0);
2741 print_ca_names(bio_s_out, con);
2742 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
2744 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2745 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2746 if (next_proto_neg) {
2747 BIO_printf(bio_s_out, "NEXTPROTO is ");
2748 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2749 BIO_printf(bio_s_out, "\n");
2752 #ifndef OPENSSL_NO_SRTP
2754 SRTP_PROTECTION_PROFILE *srtp_profile
2755 = SSL_get_selected_srtp_profile(con);
2758 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
2759 srtp_profile->name);
2762 if (SSL_session_reused(con))
2763 BIO_printf(bio_s_out, "Reused session-id\n");
2764 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2765 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2766 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
2767 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
2769 if (keymatexportlabel != NULL) {
2770 BIO_printf(bio_s_out, "Keying material exporter:\n");
2771 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
2772 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
2773 exportedkeymat = app_malloc(keymatexportlen, "export key");
2774 if (!SSL_export_keying_material(con, exportedkeymat,
2777 strlen(keymatexportlabel),
2779 BIO_printf(bio_s_out, " Error\n");
2781 BIO_printf(bio_s_out, " Keying material: ");
2782 for (i = 0; i < keymatexportlen; i++)
2783 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
2784 BIO_printf(bio_s_out, "\n");
2786 OPENSSL_free(exportedkeymat);
2789 (void)BIO_flush(bio_s_out);
2792 #ifndef OPENSSL_NO_DH
2793 static DH *load_dh_param(const char *dhfile)
2798 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
2800 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2807 static int www_body(int s, int stype, int prot, unsigned char *context)
2813 const SSL_CIPHER *c;
2814 BIO *io, *ssl_bio, *sbio;
2816 int total_bytes = 0;
2821 /* Set width for a select call if needed */
2824 buf = app_malloc(bufsize, "server www buffer");
2825 io = BIO_new(BIO_f_buffer());
2826 ssl_bio = BIO_new(BIO_f_ssl());
2827 if ((io == NULL) || (ssl_bio == NULL))
2831 if (!BIO_socket_nbio(s, 1))
2832 ERR_print_errors(bio_err);
2834 BIO_printf(bio_err, "Turned on non blocking io\n");
2837 /* lets make the output buffer a reasonable size */
2838 if (!BIO_set_write_buffer_size(io, bufsize))
2841 if ((con = SSL_new(ctx)) == NULL)
2844 if (s_tlsextdebug) {
2845 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2846 SSL_set_tlsext_debug_arg(con, bio_s_out);
2850 && !SSL_set_session_id_context(con, context,
2851 strlen((char *)context)))
2854 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2858 test = BIO_new(BIO_f_nbio_test());
2859 sbio = BIO_push(test, sbio);
2861 SSL_set_bio(con, sbio, sbio);
2862 SSL_set_accept_state(con);
2864 /* SSL_set_fd(con,s); */
2865 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
2866 BIO_push(io, ssl_bio);
2867 #ifdef CHARSET_EBCDIC
2868 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
2872 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
2873 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
2876 #ifndef OPENSSL_NO_SSL_TRACE
2878 SSL_set_msg_callback(con, SSL_trace);
2881 SSL_set_msg_callback(con, msg_cb);
2882 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2886 i = BIO_gets(io, buf, bufsize - 1);
2887 if (i < 0) { /* error */
2888 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
2890 ERR_print_errors(bio_err);
2893 BIO_printf(bio_s_out, "read R BLOCK\n");
2894 #ifndef OPENSSL_NO_SRP
2895 if (BIO_should_io_special(io)
2896 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
2897 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2898 SRP_user_pwd_free(srp_callback_parm.user);
2899 srp_callback_parm.user =
2900 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
2901 srp_callback_parm.login);
2902 if (srp_callback_parm.user)
2903 BIO_printf(bio_s_out, "LOOKUP done %s\n",
2904 srp_callback_parm.user->info);
2906 BIO_printf(bio_s_out, "LOOKUP not successful\n");
2910 #if !defined(OPENSSL_SYS_MSDOS)
2915 } else if (i == 0) { /* end of input */
2920 /* else we have data */
2921 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
2922 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
2925 STACK_OF(SSL_CIPHER) *sk;
2926 static const char *space = " ";
2928 if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) {
2929 if (strncmp("GET /renegcert", buf, 14) == 0)
2931 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2933 i = SSL_renegotiate(con);
2934 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
2935 /* Send the HelloRequest */
2936 i = SSL_do_handshake(con);
2938 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
2939 SSL_get_error(con, i));
2940 ERR_print_errors(bio_err);
2943 /* Wait for a ClientHello to come back */
2945 openssl_fdset(s, &readfds);
2946 i = select(width, (void *)&readfds, NULL, NULL, NULL);
2947 if (i <= 0 || !FD_ISSET(s, &readfds)) {
2948 BIO_printf(bio_s_out,
2949 "Error waiting for client response\n");
2950 ERR_print_errors(bio_err);
2954 * We're not actually expecting any data here and we ignore
2955 * any that is sent. This is just to force the handshake that
2956 * we're expecting to come from the client. If they haven't
2957 * sent one there's not much we can do.
2959 BIO_gets(io, buf, bufsize - 1);
2963 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2964 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2965 BIO_puts(io, "<pre>\n");
2966 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
2968 for (i = 0; i < local_argc; i++) {
2970 for (myp = local_argv[i]; *myp; myp++)
2973 BIO_puts(io, "<");
2976 BIO_puts(io, ">");
2979 BIO_puts(io, "&");
2982 BIO_write(io, myp, 1);
2985 BIO_write(io, " ", 1);
2990 "Secure Renegotiation IS%s supported\n",
2991 SSL_get_secure_renegotiation_support(con) ?
2995 * The following is evil and should not really be done
2997 BIO_printf(io, "Ciphers supported in s_server binary\n");
2998 sk = SSL_get_ciphers(con);
2999 j = sk_SSL_CIPHER_num(sk);
3000 for (i = 0; i < j; i++) {
3001 c = sk_SSL_CIPHER_value(sk, i);
3002 BIO_printf(io, "%-11s:%-25s ",
3003 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3004 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3008 p = SSL_get_shared_ciphers(con, buf, bufsize);
3011 "---\nCiphers common between both SSL end points:\n");
3015 BIO_write(io, space, 26 - j);
3018 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3020 BIO_write(io, p, 1);
3027 ssl_print_sigalgs(io, con);
3028 #ifndef OPENSSL_NO_EC
3029 ssl_print_groups(io, con, 0);
3031 print_ca_names(io, con);
3032 BIO_printf(io, (SSL_session_reused(con)
3033 ? "---\nReused, " : "---\nNew, "));
3034 c = SSL_get_current_cipher(con);
3035 BIO_printf(io, "%s, Cipher is %s\n",
3036 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3037 SSL_SESSION_print(io, SSL_get_session(con));
3038 BIO_printf(io, "---\n");
3039 print_stats(io, SSL_get_SSL_CTX(con));
3040 BIO_printf(io, "---\n");
3041 peer = SSL_get_peer_certificate(con);
3043 BIO_printf(io, "Client certificate\n");
3044 X509_print(io, peer);
3045 PEM_write_bio_X509(io, peer);
3049 BIO_puts(io, "no client certificate available\n");
3050 BIO_puts(io, "</BODY></HTML>\r\n\r\n");
3052 } else if ((www == 2 || www == 3)
3053 && (strncmp("GET /", buf, 5) == 0)) {
3056 static const char *text =
3057 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3063 for (e = p; *e != '\0'; e++) {
3069 dot = (e[0] == '.') ? 2 : 0;
3072 dot = (e[0] == '.') ? 3 : 0;
3075 dot = (e[0] == '/') ? -1 : 0;
3079 dot = (e[0] == '/') ? 1 : 0;
3081 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3086 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3093 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
3099 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3103 /* if a directory, do the index thang */
3104 if (app_isdir(p) > 0) {
3106 BIO_printf(io, "'%s' is a directory\r\n", p);
3110 if ((file = BIO_new_file(p, "r")) == NULL) {
3112 BIO_printf(io, "Error opening '%s'\r\n", p);
3113 ERR_print_errors(io);
3118 BIO_printf(bio_err, "FILE:%s\n", p);
3122 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3123 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3124 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3126 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3129 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3133 i = BIO_read(file, buf, bufsize);
3139 BIO_printf(bio_err, "%d\n", i);
3140 if (total_bytes > 3 * 1024) {
3142 BIO_printf(bio_err, "RENEGOTIATE\n");
3143 SSL_renegotiate(con);
3147 for (j = 0; j < i;) {
3150 if (++count == 13) {
3151 SSL_renegotiate(con);
3154 k = BIO_write(io, &(buf[j]), i - j);
3156 if (!BIO_should_retry(io)
3157 && !SSL_waiting_for_async(con))
3160 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3174 i = (int)BIO_flush(io);
3176 if (!BIO_should_retry(io))
3182 /* make sure we re-use sessions */
3183 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3187 BIO_printf(bio_s_out, "ACCEPT\n");
3193 static int rev_body(int s, int stype, int prot, unsigned char *context)
3199 BIO *io, *ssl_bio, *sbio;
3201 buf = app_malloc(bufsize, "server rev buffer");
3202 io = BIO_new(BIO_f_buffer());
3203 ssl_bio = BIO_new(BIO_f_ssl());
3204 if ((io == NULL) || (ssl_bio == NULL))
3207 /* lets make the output buffer a reasonable size */
3208 if (!BIO_set_write_buffer_size(io, bufsize))
3211 if ((con = SSL_new(ctx)) == NULL)
3214 if (s_tlsextdebug) {
3215 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3216 SSL_set_tlsext_debug_arg(con, bio_s_out);
3219 && !SSL_set_session_id_context(con, context,
3220 strlen((char *)context))) {
3221 ERR_print_errors(bio_err);
3225 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3226 SSL_set_bio(con, sbio, sbio);
3227 SSL_set_accept_state(con);
3229 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3230 BIO_push(io, ssl_bio);
3231 #ifdef CHARSET_EBCDIC
3232 io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
3236 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
3237 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3240 #ifndef OPENSSL_NO_SSL_TRACE
3242 SSL_set_msg_callback(con, SSL_trace);
3245 SSL_set_msg_callback(con, msg_cb);
3246 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3250 i = BIO_do_handshake(io);
3253 if (!BIO_should_retry(io)) {
3254 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3255 ERR_print_errors(bio_err);
3258 #ifndef OPENSSL_NO_SRP
3259 if (BIO_should_io_special(io)
3260 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3261 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3262 SRP_user_pwd_free(srp_callback_parm.user);
3263 srp_callback_parm.user =
3264 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3265 srp_callback_parm.login);
3266 if (srp_callback_parm.user)
3267 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3268 srp_callback_parm.user->info);
3270 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3275 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3276 print_ssl_summary(con);
3279 i = BIO_gets(io, buf, bufsize - 1);
3280 if (i < 0) { /* error */
3281 if (!BIO_should_retry(io)) {
3283 ERR_print_errors(bio_err);
3286 BIO_printf(bio_s_out, "read R BLOCK\n");
3287 #ifndef OPENSSL_NO_SRP
3288 if (BIO_should_io_special(io)
3289 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3290 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3291 SRP_user_pwd_free(srp_callback_parm.user);
3292 srp_callback_parm.user =
3293 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
3294 srp_callback_parm.login);
3295 if (srp_callback_parm.user)
3296 BIO_printf(bio_s_out, "LOOKUP done %s\n",
3297 srp_callback_parm.user->info);
3299 BIO_printf(bio_s_out, "LOOKUP not successful\n");
3303 #if !defined(OPENSSL_SYS_MSDOS)
3308 } else if (i == 0) { /* end of input */
3310 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3313 char *p = buf + i - 1;
3314 while (i && (*p == '\n' || *p == '\r')) {
3318 if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) {
3320 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3323 BUF_reverse((unsigned char *)buf, NULL, i);
3325 BIO_write(io, buf, i + 1);
3330 if (!BIO_should_retry(io))
3336 /* make sure we re-use sessions */
3337 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
3346 #define MAX_SESSION_ID_ATTEMPTS 10
3347 static int generate_session_id(const SSL *ssl, unsigned char *id,
3348 unsigned int *id_len)
3350 unsigned int count = 0;
3352 if (RAND_bytes(id, *id_len) <= 0)
3355 * Prefix the session_id with the required prefix. NB: If our prefix
3356 * is too long, clip it - but there will be worse effects anyway, eg.
3357 * the server could only possibly create 1 session ID (ie. the
3358 * prefix!) so all future session negotiations will fail due to
3361 memcpy(id, session_id_prefix,
3362 (strlen(session_id_prefix) < *id_len) ?
3363 strlen(session_id_prefix) : *id_len);
3365 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3366 (++count < MAX_SESSION_ID_ATTEMPTS));
3367 if (count >= MAX_SESSION_ID_ATTEMPTS)
3373 * By default s_server uses an in-memory cache which caches SSL_SESSION
3374 * structures without any serialisation. This hides some bugs which only
3375 * become apparent in deployed servers. By implementing a basic external
3376 * session cache some issues can be debugged using s_server.
3379 typedef struct simple_ssl_session_st {
3384 struct simple_ssl_session_st *next;
3385 } simple_ssl_session;
3387 static simple_ssl_session *first = NULL;
3389 static int add_session(SSL *ssl, SSL_SESSION *session)
3391 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3394 SSL_SESSION_get_id(session, &sess->idlen);
3395 sess->derlen = i2d_SSL_SESSION(session, NULL);
3396 if (sess->derlen < 0) {
3397 BIO_printf(bio_err, "Error encoding session\n");
3402 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3403 sess->der = app_malloc(sess->derlen, "get session buffer");
3405 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3406 OPENSSL_free(sess->id);
3407 OPENSSL_free(sess->der);
3413 /* Assume it still works. */
3414 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3415 BIO_printf(bio_err, "Unexpected session encoding length\n");
3416 OPENSSL_free(sess->id);
3417 OPENSSL_free(sess->der);
3424 BIO_printf(bio_err, "New session added to external cache\n");
3428 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3431 simple_ssl_session *sess;
3433 for (sess = first; sess; sess = sess->next) {
3434 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3435 const unsigned char *p = sess->der;
3436 BIO_printf(bio_err, "Lookup session: cache hit\n");
3437 return d2i_SSL_SESSION(NULL, &p, sess->derlen);
3440 BIO_printf(bio_err, "Lookup session: cache miss\n");
3444 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3446 simple_ssl_session *sess, *prev = NULL;
3447 const unsigned char *id;
3449 id = SSL_SESSION_get_id(session, &idlen);
3450 for (sess = first; sess; sess = sess->next) {
3451 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3453 prev->next = sess->next;
3456 OPENSSL_free(sess->id);
3457 OPENSSL_free(sess->der);
3465 static void init_session_cache_ctx(SSL_CTX *sctx)
3467 SSL_CTX_set_session_cache_mode(sctx,
3468 SSL_SESS_CACHE_NO_INTERNAL |
3469 SSL_SESS_CACHE_SERVER);
3470 SSL_CTX_sess_set_new_cb(sctx, add_session);
3471 SSL_CTX_sess_set_get_cb(sctx, get_session);
3472 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3475 static void free_sessions(void)
3477 simple_ssl_session *sess, *tsess;
3478 for (sess = first; sess;) {
3479 OPENSSL_free(sess->id);
3480 OPENSSL_free(sess->der);
3483 OPENSSL_free(tsess);
3488 #endif /* OPENSSL_NO_SOCK */