2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2020 Matt Schatz <genius3000@g3k.solutions>
5 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6 * Copyright (C) 2017 Wade Cline <wadecline@hotmail.com>
7 * Copyright (C) 2014, 2016 Adam <Adam@anope.org>
8 * Copyright (C) 2014 Julien Vehent <julien@linuxwall.info>
9 * Copyright (C) 2013-2014, 2016-2021 Sadie Powell <sadie@witchery.services>
10 * Copyright (C) 2012-2017 Attila Molnar <attilamolnar@hush.com>
11 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
12 * Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
13 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
14 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
15 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
16 * Copyright (C) 2006-2008, 2010 Craig Edwards <brain@inspircd.org>
17 * Copyright (C) 2006 Oliver Lupton <om@inspircd.org>
19 * This file is part of InspIRCd. InspIRCd is free software: you can
20 * redistribute it and/or modify it under the terms of the GNU General Public
21 * License as published by the Free Software Foundation, version 2.
23 * This program is distributed in the hope that it will be useful, but WITHOUT
24 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
25 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 /// $CompilerFlags: find_compiler_flags("openssl" "")
33 /// $LinkerFlags: find_linker_flags("openssl" "-lssl -lcrypto")
35 /// $PackageInfo: require_system("arch") openssl pkgconf
36 /// $PackageInfo: require_system("centos") openssl-devel pkgconfig
37 /// $PackageInfo: require_system("darwin") openssl pkg-config
38 /// $PackageInfo: require_system("debian") libssl-dev openssl pkg-config
39 /// $PackageInfo: require_system("ubuntu") libssl-dev openssl pkg-config
44 #include "modules/ssl.h"
47 # pragma GCC diagnostic push
50 // Ignore OpenSSL deprecation warnings on OS X Lion and newer.
52 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
55 // LibreSSL lies about the version of OpenSSL it is compatible with and is a general pain
56 // to support. Support for it was removed in the master branch at the same time that
57 // support for OpenSSL pre-1.1 was.
58 #if defined __GNUC__ && defined LIBRESSL_VERSION_NUMBER
59 # warning LibreSSL support will be discontinued in the future. Consider using the ssl_gnutls or ssl_mbedtls modules instead.
62 // Fix warnings about the use of `long long` on C++03.
64 # pragma clang diagnostic ignored "-Wc++11-long-long"
65 #elif defined __GNUC__
66 # pragma GCC diagnostic ignored "-Wlong-long"
69 #include <openssl/ssl.h>
70 #include <openssl/err.h>
71 #include <openssl/dh.h>
74 # pragma GCC diagnostic pop
78 # pragma comment(lib, "ssleay32.lib")
79 # pragma comment(lib, "libeay32.lib")
82 // Compatibility layer to allow OpenSSL 1.0 to use the 1.1 API.
83 #if ((defined LIBRESSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x10100000L))
85 // BIO is opaque in OpenSSL 1.1 but the access API does not exist in 1.0.
86 # define BIO_get_data(BIO) BIO->ptr
87 # define BIO_set_data(BIO, VALUE) BIO->ptr = VALUE;
88 # define BIO_set_init(BIO, VALUE) BIO->init = VALUE;
90 // These functions have been renamed in OpenSSL 1.1.
91 # define OpenSSL_version SSLeay_version
92 # define X509_getm_notAfter X509_get_notAfter
93 # define X509_getm_notBefore X509_get_notBefore
94 # define OPENSSL_init_ssl(OPTIONS, SETTINGS) \
96 SSL_load_error_strings();
98 // These macros have been renamed in OpenSSL 1.1.
99 # define OPENSSL_VERSION SSLEAY_VERSION
102 # define INSPIRCD_OPENSSL_OPAQUE_BIO
105 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
107 static bool SelfSigned = false;
108 static int exdataindex;
112 return ERR_error_string(ERR_get_error(), NULL);
115 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
116 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
120 class Exception : public ModuleException
123 Exception(const std::string& reason)
124 : ModuleException(reason) { }
132 DHParams(const std::string& filename)
134 BIO* dhpfile = BIO_new_file(filename.c_str(), "r");
136 throw Exception("Couldn't open DH file " + filename);
138 dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
142 throw Exception("Couldn't read DH params from file " + filename);
162 Context(SSL_CTX* context)
165 // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
166 // and when choosing a cipher, use the server's preferences instead of the client preferences.
167 long opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE;
168 // Only turn options on if they exist
169 #ifdef SSL_OP_SINGLE_ECDH_USE
170 opts |= SSL_OP_SINGLE_ECDH_USE;
172 #ifdef SSL_OP_NO_TICKET
173 opts |= SSL_OP_NO_TICKET;
176 ctx_options = SSL_CTX_set_options(ctx, opts);
178 long mode = SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
179 #ifdef SSL_MODE_RELEASE_BUFFERS
180 mode |= SSL_MODE_RELEASE_BUFFERS;
182 SSL_CTX_set_mode(ctx, mode);
183 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
184 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
185 SSL_CTX_set_info_callback(ctx, StaticSSLInfoCallback);
193 bool SetDH(DHParams& dh)
196 return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
199 #ifndef OPENSSL_NO_ECDH
200 void SetECDH(const std::string& curvename)
202 int nid = OBJ_sn2nid(curvename.c_str());
204 throw Exception("Unknown curve: " + curvename);
206 EC_KEY* eckey = EC_KEY_new_by_curve_name(nid);
208 throw Exception("Unable to create EC key object");
211 bool ret = (SSL_CTX_set_tmp_ecdh(ctx, eckey) >= 0);
214 throw Exception("Couldn't set ECDH parameters");
218 bool SetCiphers(const std::string& ciphers)
220 // TLSv1 to TLSv1.2 ciphers.
222 return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
225 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
226 bool SetCiphersuites(const std::string& ciphers)
230 return SSL_CTX_set_ciphersuites(ctx, ciphers.c_str());
234 bool SetCerts(const std::string& filename)
237 return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
240 bool SetPrivateKey(const std::string& filename)
243 return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
246 bool SetCA(const std::string& filename)
249 return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
252 void SetCRL(const std::string& crlfile, const std::string& crlpath, const std::string& crlmode)
254 if (crlfile.empty() && crlpath.empty())
258 unsigned long crlflags = X509_V_FLAG_CRL_CHECK;
259 if (stdalgo::string::equalsci(crlmode, "chain"))
261 crlflags |= X509_V_FLAG_CRL_CHECK_ALL;
263 else if (!stdalgo::string::equalsci(crlmode, "leaf"))
265 throw ModuleException("Unknown mode '" + crlmode + "'; expected either 'chain' (default) or 'leaf'");
269 X509_STORE* store = SSL_CTX_get_cert_store(ctx);
272 throw ModuleException("Unable to get X509_STORE from TLS (SSL) context; this should never happen");
275 if (!X509_STORE_load_locations(store,
276 crlfile.empty() ? NULL : crlfile.c_str(),
277 crlpath.empty() ? NULL : crlpath.c_str()))
279 int err = ERR_get_error();
280 throw ModuleException("Unable to load CRL file '" + crlfile + "' or CRL path '" + crlpath + "': '" + (err ? ERR_error_string(err, NULL) : "unknown") + "'");
284 if (X509_STORE_set_flags(store, crlflags) != 1)
286 throw ModuleException("Unable to set X509 CRL flags");
291 long GetDefaultContextOptions() const
296 long SetRawContextOptions(long setoptions, long clearoptions)
299 SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
301 // Set the default options and what is in the conf
302 SSL_CTX_set_options(ctx, ctx_options | setoptions);
303 return SSL_CTX_clear_options(ctx, clearoptions);
308 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
311 SSL* CreateServerSession()
313 SSL* sess = SSL_new(ctx);
314 SSL_set_accept_state(sess); // Act as server
318 SSL* CreateClientSession()
320 SSL* sess = SSL_new(ctx);
321 SSL_set_connect_state(sess); // Act as client
328 /** Name of this profile
330 const std::string name;
332 /** DH parameters in use
336 /** OpenSSL makes us have two contexts, one for servers and one for clients
341 /** Digest to use when generating fingerprints
343 const EVP_MD* digest;
345 /** Last error, set by error_callback()
349 /** True if renegotiations are allowed, false if not
351 const bool allowrenego;
353 /** Rough max size of records to send
355 const unsigned int outrecsize;
357 static int error_callback(const char* str, size_t len, void* u)
359 Profile* profile = reinterpret_cast<Profile*>(u);
360 profile->lasterr = std::string(str, len - 1);
364 /** Set raw OpenSSL context (SSL_CTX) options from a config tag
365 * @param ctxname Name of the context, client or server
366 * @param tag Config tag defining this profile
367 * @param context Context object to manipulate
369 void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context)
371 long setoptions = tag->getInt(ctxname + "setoptions", 0);
372 long clearoptions = tag->getInt(ctxname + "clearoptions", 0);
374 #ifdef SSL_OP_NO_COMPRESSION
375 // Disable compression by default
376 if (!tag->getBool("compression", false))
377 setoptions |= SSL_OP_NO_COMPRESSION;
380 // Disable TLSv1.0 by default.
381 if (!tag->getBool("tlsv1", false))
382 setoptions |= SSL_OP_NO_TLSv1;
384 #ifdef SSL_OP_NO_TLSv1_1
385 // Enable TLSv1.1 by default.
386 if (!tag->getBool("tlsv11", true))
387 setoptions |= SSL_OP_NO_TLSv1_1;
390 #ifdef SSL_OP_NO_TLSv1_2
391 // Enable TLSv1.2 by default.
392 if (!tag->getBool("tlsv12", true))
393 setoptions |= SSL_OP_NO_TLSv1_2;
396 if (!setoptions && !clearoptions)
397 return; // Nothing to do
399 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Setting %s %s context options, default: %ld set: %ld clear: %ld", name.c_str(), ctxname.c_str(), ctx.GetDefaultContextOptions(), setoptions, clearoptions);
400 long final = context.SetRawContextOptions(setoptions, clearoptions);
401 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final);
405 Profile(const std::string& profilename, ConfigTag* tag)
407 , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dhparams.pem", 1)))
408 , ctx(SSL_CTX_new(SSLv23_server_method()))
409 , clictx(SSL_CTX_new(SSLv23_client_method()))
410 , allowrenego(tag->getBool("renegotiation")) // Disallow by default
411 , outrecsize(tag->getUInt("outrecsize", 2048, 512, 16384))
413 if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
414 throw Exception("Couldn't set DH parameters");
416 const std::string hash = tag->getString("hash", "md5", 1);
417 digest = EVP_get_digestbyname(hash.c_str());
419 throw Exception("Unknown hash type " + hash);
421 const std::string ciphers = tag->getString("ciphers");
422 if (!ciphers.empty())
424 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
426 ERR_print_errors_cb(error_callback, this);
427 throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
431 const std::string ciphersuites = tag->getString("ciphersuites");
432 if (!ciphers.empty())
434 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
435 if ((!ctx.SetCiphersuites(ciphersuites)) || (!clictx.SetCiphersuites(ciphersuites)))
437 ERR_print_errors_cb(error_callback, this);
438 throw Exception("Can't set ciphersuite list to \"" + ciphersuites + "\" " + lasterr);
441 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "You have configured <sslprofile:ciphersuites> but your version of OpenSSL does not support TLSv1.3+");
445 #ifndef OPENSSL_NO_ECDH
446 const std::string curvename = tag->getString("ecdhcurve", "prime256v1", 1);
447 if (!curvename.empty())
448 ctx.SetECDH(curvename);
451 SetContextOptions("server", tag, ctx);
452 SetContextOptions("client", tag, clictx);
454 /* Load our keys and certificates
455 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
457 std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem", 1));
458 if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
460 ERR_print_errors_cb(error_callback, this);
461 throw Exception("Can't read certificate file: " + lasterr);
464 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem", 1));
465 if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
467 ERR_print_errors_cb(error_callback, this);
468 throw Exception("Can't read key file: " + lasterr);
471 // Load the CAs we trust
472 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem", 1));
473 if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
475 ERR_print_errors_cb(error_callback, this);
476 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Can't read CA list from %s. This is only a problem if you want to verify client certificates, otherwise it's safe to ignore this message. Error: %s", filename.c_str(), lasterr.c_str());
480 const std::string crlfile = tag->getString("crlfile");
481 const std::string crlpath = tag->getString("crlpath");
482 const std::string crlmode = tag->getString("crlmode", "chain", 1);
483 ctx.SetCRL(crlfile, crlpath, crlmode);
485 clictx.SetVerifyCert();
486 if (tag->getBool("requestclientcert", true))
490 const std::string& GetName() const { return name; }
491 SSL* CreateServerSession() { return ctx.CreateServerSession(); }
492 SSL* CreateClientSession() { return clictx.CreateClientSession(); }
493 const EVP_MD* GetDigest() { return digest; }
494 bool AllowRenegotiation() const { return allowrenego; }
495 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
500 static int create(BIO* bio)
502 BIO_set_init(bio, 1);
506 static int destroy(BIO* bio)
508 // XXX: Dummy function to avoid a memory leak in OpenSSL.
509 // The memory leak happens in BIO_free() (bio_lib.c) when the destroy func of the BIO is NULL.
510 // This is fixed in OpenSSL but some distros still ship the unpatched version hence we provide this workaround.
514 static long ctrl(BIO* bio, int cmd, long num, void* ptr)
516 if (cmd == BIO_CTRL_FLUSH)
521 static int read(BIO* bio, char* buf, int len);
522 static int write(BIO* bio, const char* buf, int len);
524 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
525 static BIO_METHOD* alloc()
527 BIO_METHOD* meth = BIO_meth_new(100 | BIO_TYPE_SOURCE_SINK, "inspircd");
528 BIO_meth_set_write(meth, OpenSSL::BIOMethod::write);
529 BIO_meth_set_read(meth, OpenSSL::BIOMethod::read);
530 BIO_meth_set_ctrl(meth, OpenSSL::BIOMethod::ctrl);
531 BIO_meth_set_create(meth, OpenSSL::BIOMethod::create);
532 BIO_meth_set_destroy(meth, OpenSSL::BIOMethod::destroy);
539 // BIO_METHOD is opaque in OpenSSL 1.1 so we can't do this.
540 // See OpenSSL::BIOMethod::alloc for the new method.
541 #ifndef INSPIRCD_OPENSSL_OPAQUE_BIO
542 static BIO_METHOD biomethods =
544 (100 | BIO_TYPE_SOURCE_SINK),
546 OpenSSL::BIOMethod::write,
547 OpenSSL::BIOMethod::read,
550 OpenSSL::BIOMethod::ctrl,
551 OpenSSL::BIOMethod::create,
552 OpenSSL::BIOMethod::destroy, // destroy, does nothing, see function body for more info
553 NULL // callback_ctrl
556 static BIO_METHOD* biomethods;
559 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
561 /* XXX: This will allow self signed certificates.
562 * In the future if we want an option to not allow this,
563 * we can just return preverify_ok here, and openssl
564 * will boot off self-signed and invalid peer certs.
566 int ve = X509_STORE_CTX_get_error(ctx);
568 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
573 class OpenSSLIOHook : public SSLIOHook
580 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
581 int Handshake(StreamSocket* user)
584 int ret = SSL_do_handshake(sess);
587 int err = SSL_get_error(sess, ret);
589 if (err == SSL_ERROR_WANT_READ)
591 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
592 this->status = ISSL_HANDSHAKING;
595 else if (err == SSL_ERROR_WANT_WRITE)
597 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
598 this->status = ISSL_HANDSHAKING;
609 // Handshake complete.
614 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
637 void VerifyCertificate()
640 ssl_cert* certinfo = new ssl_cert;
641 this->certificate = certinfo;
643 unsigned char md[EVP_MAX_MD_SIZE];
645 cert = SSL_get_peer_certificate(sess);
649 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
653 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
657 certinfo->unknownsigner = false;
658 certinfo->trusted = true;
662 certinfo->unknownsigner = true;
663 certinfo->trusted = false;
667 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
669 // Make sure there are no chars in the string that we consider invalid
670 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
671 certinfo->dn.clear();
673 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
674 certinfo->issuer = buf;
675 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
676 certinfo->issuer.clear();
678 if (!X509_digest(cert, GetProfile().GetDigest(), md, &n))
680 certinfo->error = "Out of memory generating fingerprint";
684 certinfo->fingerprint = BinToHex(md, n);
687 if ((ASN1_UTCTIME_cmp_time_t(X509_getm_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_getm_notBefore(cert), ServerInstance->Time()) == 0))
689 certinfo->error = "Not activated, or expired certificate";
695 void SSLInfoCallback(int where, int rc)
697 if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN))
699 if (GetProfile().AllowRenegotiation())
702 // The other side is trying to renegotiate, kill the connection and change status
703 // to ISSL_NONE so CheckRenego() closes the session
705 BIO* bio = SSL_get_rbio(sess);
706 EventHandler* eh = static_cast<StreamSocket*>(BIO_get_data(bio));
707 SocketEngine::Shutdown(eh, 2);
711 bool CheckRenego(StreamSocket* sock)
713 if (status != ISSL_NONE)
716 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess);
718 sock->SetError("Renegotiation is not allowed");
722 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
723 int PrepareIO(StreamSocket* sock)
725 if (status == ISSL_OPEN)
727 else if (status == ISSL_HANDSHAKING)
729 // The handshake isn't finished, try to finish it
730 return Handshake(sock);
737 // Calls our private SSLInfoCallback()
738 friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
741 OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, SSL* session)
742 : SSLIOHook(hookprov)
745 , data_to_write(false)
747 // Create BIO instance and store a pointer to the socket in it which will be used by the read and write functions
748 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
749 BIO* bio = BIO_new(biomethods);
751 BIO* bio = BIO_new(&biomethods);
753 BIO_set_data(bio, sock);
754 SSL_set_bio(sess, bio, bio);
756 SSL_set_ex_data(sess, exdataindex, this);
757 sock->AddIOHook(this);
761 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
766 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
768 // Finish handshake if needed
769 int prepret = PrepareIO(user);
773 // If we resumed the handshake then this->status will be ISSL_OPEN
776 char* buffer = ServerInstance->GetReadBuffer();
777 size_t bufsiz = ServerInstance->Config->NetBufferSize;
778 int ret = SSL_read(sess, buffer, bufsiz);
780 if (!CheckRenego(user))
785 recvq.append(buffer, ret);
787 // Schedule a read if there is still data in the OpenSSL buffer
788 if (SSL_pending(sess) > 0)
789 mask |= FD_ADD_TRIAL_READ;
791 mask |= FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE;
793 SocketEngine::ChangeEventMask(user, mask);
798 // Client closed connection.
800 user->SetError("Connection closed");
805 int err = SSL_get_error(sess, ret);
807 if (err == SSL_ERROR_WANT_READ)
809 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
812 else if (err == SSL_ERROR_WANT_WRITE)
814 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
826 int OnStreamSocketWrite(StreamSocket* user, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
828 // Finish handshake if needed
829 int prepret = PrepareIO(user);
833 data_to_write = true;
835 // Session is ready for transferring application data
836 while (!sendq.empty())
839 FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
840 const StreamSocket::SendQueue::Element& buffer = sendq.front();
841 int ret = SSL_write(sess, buffer.data(), buffer.size());
843 if (!CheckRenego(user))
846 if (ret == (int)buffer.length())
848 // Wrote entire record, continue sending
853 sendq.erase_front(ret);
854 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
864 int err = SSL_get_error(sess, ret);
866 if (err == SSL_ERROR_WANT_WRITE)
868 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
871 else if (err == SSL_ERROR_WANT_READ)
873 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
884 data_to_write = false;
885 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
889 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
891 if (!IsHandshakeDone())
893 out.append(SSL_get_version(sess)).push_back('-');
894 out.append(SSL_get_cipher(sess));
897 bool GetServerName(std::string& out) const CXX11_OVERRIDE
899 const char* name = SSL_get_servername(sess, TLSEXT_NAMETYPE_host_name);
907 bool IsHandshakeDone() const { return (status == ISSL_OPEN); }
908 OpenSSL::Profile& GetProfile();
911 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc)
913 OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex));
914 hook->SSLInfoCallback(where, rc);
917 static int OpenSSL::BIOMethod::write(BIO* bio, const char* buffer, int size)
919 BIO_clear_retry_flags(bio);
921 StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
922 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
924 // Writes blocked earlier, don't retry syscall
925 BIO_set_retry_write(bio);
929 int ret = SocketEngine::Send(sock, buffer, size, 0);
930 if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
932 // Blocked, set retry flag for OpenSSL
933 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
934 BIO_set_retry_write(bio);
940 static int OpenSSL::BIOMethod::read(BIO* bio, char* buffer, int size)
942 BIO_clear_retry_flags(bio);
944 StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
945 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
947 // Reads blocked earlier, don't retry syscall
948 BIO_set_retry_read(bio);
952 int ret = SocketEngine::Recv(sock, buffer, size, 0);
953 if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
955 // Blocked, set retry flag for OpenSSL
956 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
957 BIO_set_retry_read(bio);
963 class OpenSSLIOHookProvider : public SSLIOHookProvider
965 OpenSSL::Profile profile;
968 OpenSSLIOHookProvider(Module* mod, const std::string& profilename, ConfigTag* tag)
969 : SSLIOHookProvider(mod, profilename)
970 , profile(profilename, tag)
972 ServerInstance->Modules->AddService(*this);
975 ~OpenSSLIOHookProvider()
977 ServerInstance->Modules->DelService(*this);
980 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
982 new OpenSSLIOHook(this, sock, profile.CreateServerSession());
985 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
987 new OpenSSLIOHook(this, sock, profile.CreateClientSession());
990 OpenSSL::Profile& GetProfile() { return profile; }
993 OpenSSL::Profile& OpenSSLIOHook::GetProfile()
995 IOHookProvider* hookprov = prov;
996 return static_cast<OpenSSLIOHookProvider*>(hookprov)->GetProfile();
999 class ModuleSSLOpenSSL : public Module
1001 typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
1003 ProfileList profiles;
1007 ProfileList newprofiles;
1008 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
1009 if (tags.first == tags.second)
1011 // Create a default profile named "openssl"
1012 const std::string defname = "openssl";
1013 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
1014 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the deprecated <openssl> tag");
1018 newprofiles.push_back(new OpenSSLIOHookProvider(this, defname, tag));
1020 catch (OpenSSL::Exception& ex)
1022 throw ModuleException("Error while initializing the default TLS (SSL) profile - " + ex.GetReason());
1027 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "You have defined an <sslprofile> tag; you should use this in place of \"openssl\" when configuring TLS (SSL) connections in <bind:sslprofile> or <link:sslprofile>");
1028 for (ConfigIter i = tags.first; i != tags.second; ++i)
1030 ConfigTag* tag = i->second;
1031 if (!stdalgo::string::equalsci(tag->getString("provider"), "openssl"))
1033 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring non-OpenSSL <sslprofile> tag at " + tag->getTagLocation());
1037 std::string name = tag->getString("name");
1040 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
1044 reference<OpenSSLIOHookProvider> prov;
1047 prov = new OpenSSLIOHookProvider(this, name, tag);
1049 catch (CoreException& ex)
1051 throw ModuleException("Error while initializing TLS (SSL) profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
1054 newprofiles.push_back(prov);
1058 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
1060 OpenSSLIOHookProvider& prov = **i;
1061 ServerInstance->Modules.DelService(prov);
1064 profiles.swap(newprofiles);
1070 // Initialize OpenSSL
1071 OPENSSL_init_ssl(0, NULL);
1072 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
1073 biomethods = OpenSSL::BIOMethod::alloc();
1078 BIO_meth_free(biomethods);
1082 void init() CXX11_OVERRIDE
1084 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "OpenSSL lib version \"%s\" module was compiled for \"" OPENSSL_VERSION_TEXT "\"", OpenSSL_version(OPENSSL_VERSION));
1086 // Register application specific data
1087 char exdatastr[] = "inspircd";
1088 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
1089 if (exdataindex < 0)
1090 throw ModuleException("Failed to register application specific data");
1095 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
1097 if (!irc::equals(param, "tls") && !irc::equals(param, "ssl"))
1103 ServerInstance->SNO->WriteToSnoMask('a', "OpenSSL TLS (SSL) profiles have been reloaded.");
1105 catch (ModuleException& ex)
1107 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
1111 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
1113 if (type == ExtensionItem::EXT_USER)
1115 LocalUser* user = IS_LOCAL((User*)item);
1117 if ((user) && (user->eh.GetModHook(this)))
1119 // User is using TLS (SSL), they're a local user, and they're using one of *our* TLS (SSL) ports.
1120 // Potentially there could be multiple TLS (SSL) modules loaded at once on different ports.
1121 ServerInstance->Users->QuitUser(user, "OpenSSL module unloading");
1126 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
1128 const OpenSSLIOHook* const iohook = static_cast<OpenSSLIOHook*>(user->eh.GetModHook(this));
1129 if ((iohook) && (!iohook->IsHandshakeDone()))
1130 return MOD_RES_DENY;
1131 return MOD_RES_PASSTHRU;
1134 Version GetVersion() CXX11_OVERRIDE
1136 return Version("Allows TLS (SSL) encrypted connections using the OpenSSL library.", VF_VENDOR);
1140 MODULE_INIT(ModuleSSLOpenSSL)