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-2008, 2010 Craig Edwards <brain@inspircd.org>
16 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
18 * This file is part of InspIRCd. InspIRCd is free software: you can
19 * redistribute it and/or modify it under the terms of the GNU General Public
20 * License as published by the Free Software Foundation, version 2.
22 * This program is distributed in the hope that it will be useful, but WITHOUT
23 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
24 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 /// $CompilerFlags: find_compiler_flags("openssl" "")
32 /// $LinkerFlags: find_linker_flags("openssl" "-lssl -lcrypto")
34 /// $PackageInfo: require_system("arch") openssl pkgconf
35 /// $PackageInfo: require_system("centos") openssl-devel pkgconfig
36 /// $PackageInfo: require_system("darwin") openssl pkg-config
37 /// $PackageInfo: require_system("debian") libssl-dev openssl pkg-config
38 /// $PackageInfo: require_system("ubuntu") libssl-dev openssl pkg-config
43 #include "modules/ssl.h"
46 # pragma GCC diagnostic push
49 // Ignore OpenSSL deprecation warnings on OS X Lion and newer.
51 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
54 // LibreSSL lies about the version of OpenSSL it is compatible with and is a general pain
55 // to support. Support for it was removed in the master branch at the same time that
56 // support for OpenSSL pre-1.1 was.
57 #if defined __GNUC__ && defined LIBRESSL_VERSION_NUMBER
58 # warning LibreSSL support will be discontinued in the future. Consider using the ssl_gnutls or ssl_mbedtls modules instead.
61 // Fix warnings about the use of `long long` on C++03.
63 # pragma clang diagnostic ignored "-Wc++11-long-long"
64 #elif defined __GNUC__
65 # pragma GCC diagnostic ignored "-Wlong-long"
68 #include <openssl/ssl.h>
69 #include <openssl/err.h>
70 #include <openssl/dh.h>
73 # pragma GCC diagnostic pop
77 # pragma comment(lib, "ssleay32.lib")
78 # pragma comment(lib, "libeay32.lib")
81 // Compatibility layer to allow OpenSSL 1.0 to use the 1.1 API.
82 #if ((defined LIBRESSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x10100000L))
84 // BIO is opaque in OpenSSL 1.1 but the access API does not exist in 1.0.
85 # define BIO_get_data(BIO) BIO->ptr
86 # define BIO_set_data(BIO, VALUE) BIO->ptr = VALUE;
87 # define BIO_set_init(BIO, VALUE) BIO->init = VALUE;
89 // These functions have been renamed in OpenSSL 1.1.
90 # define OpenSSL_version SSLeay_version
91 # define X509_getm_notAfter X509_get_notAfter
92 # define X509_getm_notBefore X509_get_notBefore
93 # define OPENSSL_init_ssl(OPTIONS, SETTINGS) \
95 SSL_load_error_strings();
97 // These macros have been renamed in OpenSSL 1.1.
98 # define OPENSSL_VERSION SSLEAY_VERSION
101 # define INSPIRCD_OPENSSL_OPAQUE_BIO
104 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
106 static bool SelfSigned = false;
107 static int exdataindex;
111 return ERR_error_string(ERR_get_error(), NULL);
114 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
115 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
119 class Exception : public ModuleException
122 Exception(const std::string& reason)
123 : ModuleException(reason) { }
131 DHParams(const std::string& filename)
133 BIO* dhpfile = BIO_new_file(filename.c_str(), "r");
135 throw Exception("Couldn't open DH file " + filename);
137 dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
141 throw Exception("Couldn't read DH params from file " + filename);
161 Context(SSL_CTX* context)
164 // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
165 // and when choosing a cipher, use the server's preferences instead of the client preferences.
166 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;
167 // Only turn options on if they exist
168 #ifdef SSL_OP_SINGLE_ECDH_USE
169 opts |= SSL_OP_SINGLE_ECDH_USE;
171 #ifdef SSL_OP_NO_TICKET
172 opts |= SSL_OP_NO_TICKET;
175 ctx_options = SSL_CTX_set_options(ctx, opts);
177 long mode = SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
178 #ifdef SSL_MODE_RELEASE_BUFFERS
179 mode |= SSL_MODE_RELEASE_BUFFERS;
181 SSL_CTX_set_mode(ctx, mode);
182 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
183 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
184 SSL_CTX_set_info_callback(ctx, StaticSSLInfoCallback);
192 bool SetDH(DHParams& dh)
195 return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
198 #ifndef OPENSSL_NO_ECDH
199 void SetECDH(const std::string& curvename)
201 int nid = OBJ_sn2nid(curvename.c_str());
203 throw Exception("Unknown curve: " + curvename);
205 EC_KEY* eckey = EC_KEY_new_by_curve_name(nid);
207 throw Exception("Unable to create EC key object");
210 bool ret = (SSL_CTX_set_tmp_ecdh(ctx, eckey) >= 0);
213 throw Exception("Couldn't set ECDH parameters");
217 bool SetCiphers(const std::string& ciphers)
220 return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
223 bool SetCerts(const std::string& filename)
226 return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
229 bool SetPrivateKey(const std::string& filename)
232 return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
235 bool SetCA(const std::string& filename)
238 return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
241 void SetCRL(const std::string& crlfile, const std::string& crlpath, const std::string& crlmode)
243 if (crlfile.empty() && crlpath.empty())
247 unsigned long crlflags = X509_V_FLAG_CRL_CHECK;
248 if (stdalgo::string::equalsci(crlmode, "chain"))
250 crlflags |= X509_V_FLAG_CRL_CHECK_ALL;
252 else if (!stdalgo::string::equalsci(crlmode, "leaf"))
254 throw ModuleException("Unknown mode '" + crlmode + "'; expected either 'chain' (default) or 'leaf'");
258 X509_STORE* store = SSL_CTX_get_cert_store(ctx);
261 throw ModuleException("Unable to get X509_STORE from TLS (SSL) context; this should never happen");
264 if (!X509_STORE_load_locations(store,
265 crlfile.empty() ? NULL : crlfile.c_str(),
266 crlpath.empty() ? NULL : crlpath.c_str()))
268 int err = ERR_get_error();
269 throw ModuleException("Unable to load CRL file '" + crlfile + "' or CRL path '" + crlpath + "': '" + (err ? ERR_error_string(err, NULL) : "unknown") + "'");
273 if (X509_STORE_set_flags(store, crlflags) != 1)
275 throw ModuleException("Unable to set X509 CRL flags");
280 long GetDefaultContextOptions() const
285 long SetRawContextOptions(long setoptions, long clearoptions)
288 SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
290 // Set the default options and what is in the conf
291 SSL_CTX_set_options(ctx, ctx_options | setoptions);
292 return SSL_CTX_clear_options(ctx, clearoptions);
297 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
300 SSL* CreateServerSession()
302 SSL* sess = SSL_new(ctx);
303 SSL_set_accept_state(sess); // Act as server
307 SSL* CreateClientSession()
309 SSL* sess = SSL_new(ctx);
310 SSL_set_connect_state(sess); // Act as client
317 /** Name of this profile
319 const std::string name;
321 /** DH parameters in use
325 /** OpenSSL makes us have two contexts, one for servers and one for clients
330 /** Digest to use when generating fingerprints
332 const EVP_MD* digest;
334 /** Last error, set by error_callback()
338 /** True if renegotiations are allowed, false if not
340 const bool allowrenego;
342 /** Rough max size of records to send
344 const unsigned int outrecsize;
346 static int error_callback(const char* str, size_t len, void* u)
348 Profile* profile = reinterpret_cast<Profile*>(u);
349 profile->lasterr = std::string(str, len - 1);
353 /** Set raw OpenSSL context (SSL_CTX) options from a config tag
354 * @param ctxname Name of the context, client or server
355 * @param tag Config tag defining this profile
356 * @param context Context object to manipulate
358 void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context)
360 long setoptions = tag->getInt(ctxname + "setoptions", 0);
361 long clearoptions = tag->getInt(ctxname + "clearoptions", 0);
363 #ifdef SSL_OP_NO_COMPRESSION
364 // Disable compression by default
365 if (!tag->getBool("compression", false))
366 setoptions |= SSL_OP_NO_COMPRESSION;
369 // Disable TLSv1.0 by default.
370 if (!tag->getBool("tlsv1", false))
371 setoptions |= SSL_OP_NO_TLSv1;
373 #ifdef SSL_OP_NO_TLSv1_1
374 // Enable TLSv1.1 by default.
375 if (!tag->getBool("tlsv11", true))
376 setoptions |= SSL_OP_NO_TLSv1_1;
379 #ifdef SSL_OP_NO_TLSv1_2
380 // Enable TLSv1.2 by default.
381 if (!tag->getBool("tlsv12", true))
382 setoptions |= SSL_OP_NO_TLSv1_2;
385 if (!setoptions && !clearoptions)
386 return; // Nothing to do
388 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);
389 long final = context.SetRawContextOptions(setoptions, clearoptions);
390 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final);
394 Profile(const std::string& profilename, ConfigTag* tag)
396 , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dhparams.pem", 1)))
397 , ctx(SSL_CTX_new(SSLv23_server_method()))
398 , clictx(SSL_CTX_new(SSLv23_client_method()))
399 , allowrenego(tag->getBool("renegotiation")) // Disallow by default
400 , outrecsize(tag->getUInt("outrecsize", 2048, 512, 16384))
402 if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
403 throw Exception("Couldn't set DH parameters");
405 const std::string hash = tag->getString("hash", "md5", 1);
406 digest = EVP_get_digestbyname(hash.c_str());
408 throw Exception("Unknown hash type " + hash);
410 std::string ciphers = tag->getString("ciphers");
411 if (!ciphers.empty())
413 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
415 ERR_print_errors_cb(error_callback, this);
416 throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
420 #ifndef OPENSSL_NO_ECDH
421 const std::string curvename = tag->getString("ecdhcurve", "prime256v1", 1);
422 if (!curvename.empty())
423 ctx.SetECDH(curvename);
426 SetContextOptions("server", tag, ctx);
427 SetContextOptions("client", tag, clictx);
429 /* Load our keys and certificates
430 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
432 std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem", 1));
433 if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
435 ERR_print_errors_cb(error_callback, this);
436 throw Exception("Can't read certificate file: " + lasterr);
439 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem", 1));
440 if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
442 ERR_print_errors_cb(error_callback, this);
443 throw Exception("Can't read key file: " + lasterr);
446 // Load the CAs we trust
447 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem", 1));
448 if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
450 ERR_print_errors_cb(error_callback, this);
451 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());
455 const std::string crlfile = tag->getString("crlfile");
456 const std::string crlpath = tag->getString("crlpath");
457 const std::string crlmode = tag->getString("crlmode", "chain", 1);
458 ctx.SetCRL(crlfile, crlpath, crlmode);
460 clictx.SetVerifyCert();
461 if (tag->getBool("requestclientcert", true))
465 const std::string& GetName() const { return name; }
466 SSL* CreateServerSession() { return ctx.CreateServerSession(); }
467 SSL* CreateClientSession() { return clictx.CreateClientSession(); }
468 const EVP_MD* GetDigest() { return digest; }
469 bool AllowRenegotiation() const { return allowrenego; }
470 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
475 static int create(BIO* bio)
477 BIO_set_init(bio, 1);
481 static int destroy(BIO* bio)
483 // XXX: Dummy function to avoid a memory leak in OpenSSL.
484 // The memory leak happens in BIO_free() (bio_lib.c) when the destroy func of the BIO is NULL.
485 // This is fixed in OpenSSL but some distros still ship the unpatched version hence we provide this workaround.
489 static long ctrl(BIO* bio, int cmd, long num, void* ptr)
491 if (cmd == BIO_CTRL_FLUSH)
496 static int read(BIO* bio, char* buf, int len);
497 static int write(BIO* bio, const char* buf, int len);
499 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
500 static BIO_METHOD* alloc()
502 BIO_METHOD* meth = BIO_meth_new(100 | BIO_TYPE_SOURCE_SINK, "inspircd");
503 BIO_meth_set_write(meth, OpenSSL::BIOMethod::write);
504 BIO_meth_set_read(meth, OpenSSL::BIOMethod::read);
505 BIO_meth_set_ctrl(meth, OpenSSL::BIOMethod::ctrl);
506 BIO_meth_set_create(meth, OpenSSL::BIOMethod::create);
507 BIO_meth_set_destroy(meth, OpenSSL::BIOMethod::destroy);
514 // BIO_METHOD is opaque in OpenSSL 1.1 so we can't do this.
515 // See OpenSSL::BIOMethod::alloc for the new method.
516 #ifndef INSPIRCD_OPENSSL_OPAQUE_BIO
517 static BIO_METHOD biomethods =
519 (100 | BIO_TYPE_SOURCE_SINK),
521 OpenSSL::BIOMethod::write,
522 OpenSSL::BIOMethod::read,
525 OpenSSL::BIOMethod::ctrl,
526 OpenSSL::BIOMethod::create,
527 OpenSSL::BIOMethod::destroy, // destroy, does nothing, see function body for more info
528 NULL // callback_ctrl
531 static BIO_METHOD* biomethods;
534 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
536 /* XXX: This will allow self signed certificates.
537 * In the future if we want an option to not allow this,
538 * we can just return preverify_ok here, and openssl
539 * will boot off self-signed and invalid peer certs.
541 int ve = X509_STORE_CTX_get_error(ctx);
543 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
548 class OpenSSLIOHook : public SSLIOHook
555 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
556 int Handshake(StreamSocket* user)
559 int ret = SSL_do_handshake(sess);
562 int err = SSL_get_error(sess, ret);
564 if (err == SSL_ERROR_WANT_READ)
566 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
567 this->status = ISSL_HANDSHAKING;
570 else if (err == SSL_ERROR_WANT_WRITE)
572 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
573 this->status = ISSL_HANDSHAKING;
584 // Handshake complete.
589 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
612 void VerifyCertificate()
615 ssl_cert* certinfo = new ssl_cert;
616 this->certificate = certinfo;
618 unsigned char md[EVP_MAX_MD_SIZE];
620 cert = SSL_get_peer_certificate(sess);
624 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
628 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
632 certinfo->unknownsigner = false;
633 certinfo->trusted = true;
637 certinfo->unknownsigner = true;
638 certinfo->trusted = false;
642 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
644 // Make sure there are no chars in the string that we consider invalid
645 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
646 certinfo->dn.clear();
648 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
649 certinfo->issuer = buf;
650 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
651 certinfo->issuer.clear();
653 if (!X509_digest(cert, GetProfile().GetDigest(), md, &n))
655 certinfo->error = "Out of memory generating fingerprint";
659 certinfo->fingerprint = BinToHex(md, n);
662 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))
664 certinfo->error = "Not activated, or expired certificate";
670 void SSLInfoCallback(int where, int rc)
672 if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN))
674 if (GetProfile().AllowRenegotiation())
677 // The other side is trying to renegotiate, kill the connection and change status
678 // to ISSL_NONE so CheckRenego() closes the session
680 BIO* bio = SSL_get_rbio(sess);
681 EventHandler* eh = static_cast<StreamSocket*>(BIO_get_data(bio));
682 SocketEngine::Shutdown(eh, 2);
686 bool CheckRenego(StreamSocket* sock)
688 if (status != ISSL_NONE)
691 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess);
693 sock->SetError("Renegotiation is not allowed");
697 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
698 int PrepareIO(StreamSocket* sock)
700 if (status == ISSL_OPEN)
702 else if (status == ISSL_HANDSHAKING)
704 // The handshake isn't finished, try to finish it
705 return Handshake(sock);
712 // Calls our private SSLInfoCallback()
713 friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
716 OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, SSL* session)
717 : SSLIOHook(hookprov)
720 , data_to_write(false)
722 // Create BIO instance and store a pointer to the socket in it which will be used by the read and write functions
723 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
724 BIO* bio = BIO_new(biomethods);
726 BIO* bio = BIO_new(&biomethods);
728 BIO_set_data(bio, sock);
729 SSL_set_bio(sess, bio, bio);
731 SSL_set_ex_data(sess, exdataindex, this);
732 sock->AddIOHook(this);
736 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
741 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
743 // Finish handshake if needed
744 int prepret = PrepareIO(user);
748 // If we resumed the handshake then this->status will be ISSL_OPEN
751 char* buffer = ServerInstance->GetReadBuffer();
752 size_t bufsiz = ServerInstance->Config->NetBufferSize;
753 int ret = SSL_read(sess, buffer, bufsiz);
755 if (!CheckRenego(user))
760 recvq.append(buffer, ret);
762 // Schedule a read if there is still data in the OpenSSL buffer
763 if (SSL_pending(sess) > 0)
764 mask |= FD_ADD_TRIAL_READ;
766 mask |= FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE;
768 SocketEngine::ChangeEventMask(user, mask);
773 // Client closed connection.
775 user->SetError("Connection closed");
780 int err = SSL_get_error(sess, ret);
782 if (err == SSL_ERROR_WANT_READ)
784 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
787 else if (err == SSL_ERROR_WANT_WRITE)
789 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
801 int OnStreamSocketWrite(StreamSocket* user, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
803 // Finish handshake if needed
804 int prepret = PrepareIO(user);
808 data_to_write = true;
810 // Session is ready for transferring application data
811 while (!sendq.empty())
814 FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
815 const StreamSocket::SendQueue::Element& buffer = sendq.front();
816 int ret = SSL_write(sess, buffer.data(), buffer.size());
818 if (!CheckRenego(user))
821 if (ret == (int)buffer.length())
823 // Wrote entire record, continue sending
828 sendq.erase_front(ret);
829 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
839 int err = SSL_get_error(sess, ret);
841 if (err == SSL_ERROR_WANT_WRITE)
843 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
846 else if (err == SSL_ERROR_WANT_READ)
848 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
859 data_to_write = false;
860 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
864 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
866 if (!IsHandshakeDone())
868 out.append(SSL_get_version(sess)).push_back('-');
869 out.append(SSL_get_cipher(sess));
872 bool GetServerName(std::string& out) const CXX11_OVERRIDE
874 const char* name = SSL_get_servername(sess, TLSEXT_NAMETYPE_host_name);
882 bool IsHandshakeDone() const { return (status == ISSL_OPEN); }
883 OpenSSL::Profile& GetProfile();
886 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc)
888 OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex));
889 hook->SSLInfoCallback(where, rc);
892 static int OpenSSL::BIOMethod::write(BIO* bio, const char* buffer, int size)
894 BIO_clear_retry_flags(bio);
896 StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
897 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
899 // Writes blocked earlier, don't retry syscall
900 BIO_set_retry_write(bio);
904 int ret = SocketEngine::Send(sock, buffer, size, 0);
905 if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
907 // Blocked, set retry flag for OpenSSL
908 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
909 BIO_set_retry_write(bio);
915 static int OpenSSL::BIOMethod::read(BIO* bio, char* buffer, int size)
917 BIO_clear_retry_flags(bio);
919 StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
920 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
922 // Reads blocked earlier, don't retry syscall
923 BIO_set_retry_read(bio);
927 int ret = SocketEngine::Recv(sock, buffer, size, 0);
928 if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
930 // Blocked, set retry flag for OpenSSL
931 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
932 BIO_set_retry_read(bio);
938 class OpenSSLIOHookProvider : public IOHookProvider
940 OpenSSL::Profile profile;
943 OpenSSLIOHookProvider(Module* mod, const std::string& profilename, ConfigTag* tag)
944 : IOHookProvider(mod, "ssl/" + profilename, IOHookProvider::IOH_SSL)
945 , profile(profilename, tag)
947 ServerInstance->Modules->AddService(*this);
950 ~OpenSSLIOHookProvider()
952 ServerInstance->Modules->DelService(*this);
955 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
957 new OpenSSLIOHook(this, sock, profile.CreateServerSession());
960 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
962 new OpenSSLIOHook(this, sock, profile.CreateClientSession());
965 OpenSSL::Profile& GetProfile() { return profile; }
968 OpenSSL::Profile& OpenSSLIOHook::GetProfile()
970 IOHookProvider* hookprov = prov;
971 return static_cast<OpenSSLIOHookProvider*>(hookprov)->GetProfile();
974 class ModuleSSLOpenSSL : public Module
976 typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
978 ProfileList profiles;
982 ProfileList newprofiles;
983 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
984 if (tags.first == tags.second)
986 // Create a default profile named "openssl"
987 const std::string defname = "openssl";
988 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
989 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the deprecated <openssl> tag");
993 newprofiles.push_back(new OpenSSLIOHookProvider(this, defname, tag));
995 catch (OpenSSL::Exception& ex)
997 throw ModuleException("Error while initializing the default TLS (SSL) profile - " + ex.GetReason());
1002 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:ssl> or <link:ssl>");
1003 for (ConfigIter i = tags.first; i != tags.second; ++i)
1005 ConfigTag* tag = i->second;
1006 if (!stdalgo::string::equalsci(tag->getString("provider"), "openssl"))
1008 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring non-OpenSSL <sslprofile> tag at " + tag->getTagLocation());
1012 std::string name = tag->getString("name");
1015 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
1019 reference<OpenSSLIOHookProvider> prov;
1022 prov = new OpenSSLIOHookProvider(this, name, tag);
1024 catch (CoreException& ex)
1026 throw ModuleException("Error while initializing TLS (SSL) profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
1029 newprofiles.push_back(prov);
1033 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
1035 OpenSSLIOHookProvider& prov = **i;
1036 ServerInstance->Modules.DelService(prov);
1039 profiles.swap(newprofiles);
1045 // Initialize OpenSSL
1046 OPENSSL_init_ssl(0, NULL);
1047 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
1048 biomethods = OpenSSL::BIOMethod::alloc();
1053 BIO_meth_free(biomethods);
1057 void init() CXX11_OVERRIDE
1059 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "OpenSSL lib version \"%s\" module was compiled for \"" OPENSSL_VERSION_TEXT "\"", OpenSSL_version(OPENSSL_VERSION));
1061 // Register application specific data
1062 char exdatastr[] = "inspircd";
1063 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
1064 if (exdataindex < 0)
1065 throw ModuleException("Failed to register application specific data");
1070 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
1072 if (!irc::equals(param, "tls") && !irc::equals(param, "ssl"))
1078 ServerInstance->SNO->WriteToSnoMask('a', "OpenSSL TLS (SSL) profiles have been reloaded.");
1080 catch (ModuleException& ex)
1082 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
1086 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
1088 if (type == ExtensionItem::EXT_USER)
1090 LocalUser* user = IS_LOCAL((User*)item);
1092 if ((user) && (user->eh.GetModHook(this)))
1094 // User is using TLS (SSL), they're a local user, and they're using one of *our* TLS (SSL) ports.
1095 // Potentially there could be multiple TLS (SSL) modules loaded at once on different ports.
1096 ServerInstance->Users->QuitUser(user, "OpenSSL module unloading");
1101 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
1103 const OpenSSLIOHook* const iohook = static_cast<OpenSSLIOHook*>(user->eh.GetModHook(this));
1104 if ((iohook) && (!iohook->IsHandshakeDone()))
1105 return MOD_RES_DENY;
1106 return MOD_RES_PASSTHRU;
1109 Version GetVersion() CXX11_OVERRIDE
1111 return Version("Allows TLS (SSL) encrypted connections using the OpenSSL library.", VF_VENDOR);
1115 MODULE_INIT(ModuleSSLOpenSSL)