2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5 * Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
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-2019 Sadie Powell <sadie@witchery.services>
10 * Copyright (C) 2012-2017 Attila Molnar <attilamolnar@hush.com>
11 * Copyright (C) 2012, 2019 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 // Fix warnings about the use of `long long` on C++03.
56 # pragma clang diagnostic ignored "-Wc++11-long-long"
57 #elif defined __GNUC__
58 # pragma GCC diagnostic ignored "-Wlong-long"
61 #include <openssl/ssl.h>
62 #include <openssl/err.h>
63 #include <openssl/dh.h>
66 # pragma GCC diagnostic pop
70 # pragma comment(lib, "ssleay32.lib")
71 # pragma comment(lib, "libeay32.lib")
74 // Compatibility layer to allow OpenSSL 1.0 to use the 1.1 API.
75 #if ((defined LIBRESSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x10100000L))
77 // BIO is opaque in OpenSSL 1.1 but the access API does not exist in 1.0.
78 # define BIO_get_data(BIO) BIO->ptr
79 # define BIO_set_data(BIO, VALUE) BIO->ptr = VALUE;
80 # define BIO_set_init(BIO, VALUE) BIO->init = VALUE;
82 // These functions have been renamed in OpenSSL 1.1.
83 # define OpenSSL_version SSLeay_version
84 # define X509_getm_notAfter X509_get_notAfter
85 # define X509_getm_notBefore X509_get_notBefore
86 # define OPENSSL_init_ssl(OPTIONS, SETTINGS) \
88 SSL_load_error_strings();
90 // These macros have been renamed in OpenSSL 1.1.
91 # define OPENSSL_VERSION SSLEAY_VERSION
94 # define INSPIRCD_OPENSSL_OPAQUE_BIO
97 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
99 static bool SelfSigned = false;
100 static int exdataindex;
104 return ERR_error_string(ERR_get_error(), NULL);
107 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
108 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
112 class Exception : public ModuleException
115 Exception(const std::string& reason)
116 : ModuleException(reason) { }
124 DHParams(const std::string& filename)
126 BIO* dhpfile = BIO_new_file(filename.c_str(), "r");
128 throw Exception("Couldn't open DH file " + filename);
130 dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
134 throw Exception("Couldn't read DH params from file " + filename);
154 Context(SSL_CTX* context)
157 // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
158 // and when choosing a cipher, use the server's preferences instead of the client preferences.
159 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;
160 // Only turn options on if they exist
161 #ifdef SSL_OP_SINGLE_ECDH_USE
162 opts |= SSL_OP_SINGLE_ECDH_USE;
164 #ifdef SSL_OP_NO_TICKET
165 opts |= SSL_OP_NO_TICKET;
168 ctx_options = SSL_CTX_set_options(ctx, opts);
170 long mode = SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
171 #ifdef SSL_MODE_RELEASE_BUFFERS
172 mode |= SSL_MODE_RELEASE_BUFFERS;
174 SSL_CTX_set_mode(ctx, mode);
175 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
176 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
177 SSL_CTX_set_info_callback(ctx, StaticSSLInfoCallback);
185 bool SetDH(DHParams& dh)
188 return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
191 #ifndef OPENSSL_NO_ECDH
192 void SetECDH(const std::string& curvename)
194 int nid = OBJ_sn2nid(curvename.c_str());
196 throw Exception("Unknown curve: " + curvename);
198 EC_KEY* eckey = EC_KEY_new_by_curve_name(nid);
200 throw Exception("Unable to create EC key object");
203 bool ret = (SSL_CTX_set_tmp_ecdh(ctx, eckey) >= 0);
206 throw Exception("Couldn't set ECDH parameters");
210 bool SetCiphers(const std::string& ciphers)
213 return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
216 bool SetCerts(const std::string& filename)
219 return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
222 bool SetPrivateKey(const std::string& filename)
225 return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
228 bool SetCA(const std::string& filename)
231 return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
234 void SetCRL(const std::string& crlfile, const std::string& crlpath, const std::string& crlmode)
236 if (crlfile.empty() && crlpath.empty())
240 unsigned long crlflags = X509_V_FLAG_CRL_CHECK;
241 if (stdalgo::string::equalsci(crlmode, "chain"))
243 crlflags |= X509_V_FLAG_CRL_CHECK_ALL;
245 else if (!stdalgo::string::equalsci(crlmode, "leaf"))
247 throw ModuleException("Unknown mode '" + crlmode + "'; expected either 'chain' (default) or 'leaf'");
251 X509_STORE* store = SSL_CTX_get_cert_store(ctx);
254 throw ModuleException("Unable to get X509_STORE from TLS (SSL) context; this should never happen");
257 if (!X509_STORE_load_locations(store,
258 crlfile.empty() ? NULL : crlfile.c_str(),
259 crlpath.empty() ? NULL : crlpath.c_str()))
261 int err = ERR_get_error();
262 throw ModuleException("Unable to load CRL file '" + crlfile + "' or CRL path '" + crlpath + "': '" + (err ? ERR_error_string(err, NULL) : "unknown") + "'");
266 if (X509_STORE_set_flags(store, crlflags) != 1)
268 throw ModuleException("Unable to set X509 CRL flags");
273 long GetDefaultContextOptions() const
278 long SetRawContextOptions(long setoptions, long clearoptions)
281 SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
283 // Set the default options and what is in the conf
284 SSL_CTX_set_options(ctx, ctx_options | setoptions);
285 return SSL_CTX_clear_options(ctx, clearoptions);
290 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
293 SSL* CreateServerSession()
295 SSL* sess = SSL_new(ctx);
296 SSL_set_accept_state(sess); // Act as server
300 SSL* CreateClientSession()
302 SSL* sess = SSL_new(ctx);
303 SSL_set_connect_state(sess); // Act as client
310 /** Name of this profile
312 const std::string name;
314 /** DH parameters in use
318 /** OpenSSL makes us have two contexts, one for servers and one for clients
323 /** Digest to use when generating fingerprints
325 const EVP_MD* digest;
327 /** Last error, set by error_callback()
331 /** True if renegotiations are allowed, false if not
333 const bool allowrenego;
335 /** Rough max size of records to send
337 const unsigned int outrecsize;
339 static int error_callback(const char* str, size_t len, void* u)
341 Profile* profile = reinterpret_cast<Profile*>(u);
342 profile->lasterr = std::string(str, len - 1);
346 /** Set raw OpenSSL context (SSL_CTX) options from a config tag
347 * @param ctxname Name of the context, client or server
348 * @param tag Config tag defining this profile
349 * @param context Context object to manipulate
351 void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context)
353 long setoptions = tag->getInt(ctxname + "setoptions", 0);
354 long clearoptions = tag->getInt(ctxname + "clearoptions", 0);
356 #ifdef SSL_OP_NO_COMPRESSION
357 // Disable compression by default
358 if (!tag->getBool("compression", false))
359 setoptions |= SSL_OP_NO_COMPRESSION;
362 // Disable TLSv1.0 by default.
363 if (!tag->getBool("tlsv1", false))
364 setoptions |= SSL_OP_NO_TLSv1;
366 #ifdef SSL_OP_NO_TLSv1_1
367 // Enable TLSv1.1 by default.
368 if (!tag->getBool("tlsv11", true))
369 setoptions |= SSL_OP_NO_TLSv1_1;
372 #ifdef SSL_OP_NO_TLSv1_2
373 // Enable TLSv1.2 by default.
374 if (!tag->getBool("tlsv12", true))
375 setoptions |= SSL_OP_NO_TLSv1_2;
378 if (!setoptions && !clearoptions)
379 return; // Nothing to do
381 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);
382 long final = context.SetRawContextOptions(setoptions, clearoptions);
383 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final);
387 Profile(const std::string& profilename, ConfigTag* tag)
389 , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dhparams.pem", 1)))
390 , ctx(SSL_CTX_new(SSLv23_server_method()))
391 , clictx(SSL_CTX_new(SSLv23_client_method()))
392 , allowrenego(tag->getBool("renegotiation")) // Disallow by default
393 , outrecsize(tag->getUInt("outrecsize", 2048, 512, 16384))
395 if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
396 throw Exception("Couldn't set DH parameters");
398 const std::string hash = tag->getString("hash", "md5", 1);
399 digest = EVP_get_digestbyname(hash.c_str());
401 throw Exception("Unknown hash type " + hash);
403 std::string ciphers = tag->getString("ciphers");
404 if (!ciphers.empty())
406 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
408 ERR_print_errors_cb(error_callback, this);
409 throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
413 #ifndef OPENSSL_NO_ECDH
414 const std::string curvename = tag->getString("ecdhcurve", "prime256v1", 1);
415 if (!curvename.empty())
416 ctx.SetECDH(curvename);
419 SetContextOptions("server", tag, ctx);
420 SetContextOptions("client", tag, clictx);
422 /* Load our keys and certificates
423 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
425 std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem", 1));
426 if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
428 ERR_print_errors_cb(error_callback, this);
429 throw Exception("Can't read certificate file: " + lasterr);
432 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem", 1));
433 if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
435 ERR_print_errors_cb(error_callback, this);
436 throw Exception("Can't read key file: " + lasterr);
439 // Load the CAs we trust
440 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem", 1));
441 if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
443 ERR_print_errors_cb(error_callback, this);
444 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());
448 const std::string crlfile = tag->getString("crlfile");
449 const std::string crlpath = tag->getString("crlpath");
450 const std::string crlmode = tag->getString("crlmode", "chain", 1);
451 ctx.SetCRL(crlfile, crlpath, crlmode);
453 clictx.SetVerifyCert();
454 if (tag->getBool("requestclientcert", true))
458 const std::string& GetName() const { return name; }
459 SSL* CreateServerSession() { return ctx.CreateServerSession(); }
460 SSL* CreateClientSession() { return clictx.CreateClientSession(); }
461 const EVP_MD* GetDigest() { return digest; }
462 bool AllowRenegotiation() const { return allowrenego; }
463 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
468 static int create(BIO* bio)
470 BIO_set_init(bio, 1);
474 static int destroy(BIO* bio)
476 // XXX: Dummy function to avoid a memory leak in OpenSSL.
477 // The memory leak happens in BIO_free() (bio_lib.c) when the destroy func of the BIO is NULL.
478 // This is fixed in OpenSSL but some distros still ship the unpatched version hence we provide this workaround.
482 static long ctrl(BIO* bio, int cmd, long num, void* ptr)
484 if (cmd == BIO_CTRL_FLUSH)
489 static int read(BIO* bio, char* buf, int len);
490 static int write(BIO* bio, const char* buf, int len);
492 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
493 static BIO_METHOD* alloc()
495 BIO_METHOD* meth = BIO_meth_new(100 | BIO_TYPE_SOURCE_SINK, "inspircd");
496 BIO_meth_set_write(meth, OpenSSL::BIOMethod::write);
497 BIO_meth_set_read(meth, OpenSSL::BIOMethod::read);
498 BIO_meth_set_ctrl(meth, OpenSSL::BIOMethod::ctrl);
499 BIO_meth_set_create(meth, OpenSSL::BIOMethod::create);
500 BIO_meth_set_destroy(meth, OpenSSL::BIOMethod::destroy);
507 // BIO_METHOD is opaque in OpenSSL 1.1 so we can't do this.
508 // See OpenSSL::BIOMethod::alloc for the new method.
509 #ifndef INSPIRCD_OPENSSL_OPAQUE_BIO
510 static BIO_METHOD biomethods =
512 (100 | BIO_TYPE_SOURCE_SINK),
514 OpenSSL::BIOMethod::write,
515 OpenSSL::BIOMethod::read,
518 OpenSSL::BIOMethod::ctrl,
519 OpenSSL::BIOMethod::create,
520 OpenSSL::BIOMethod::destroy, // destroy, does nothing, see function body for more info
521 NULL // callback_ctrl
524 static BIO_METHOD* biomethods;
527 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
529 /* XXX: This will allow self signed certificates.
530 * In the future if we want an option to not allow this,
531 * we can just return preverify_ok here, and openssl
532 * will boot off self-signed and invalid peer certs.
534 int ve = X509_STORE_CTX_get_error(ctx);
536 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
541 class OpenSSLIOHook : public SSLIOHook
548 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
549 int Handshake(StreamSocket* user)
552 int ret = SSL_do_handshake(sess);
555 int err = SSL_get_error(sess, ret);
557 if (err == SSL_ERROR_WANT_READ)
559 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
560 this->status = ISSL_HANDSHAKING;
563 else if (err == SSL_ERROR_WANT_WRITE)
565 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
566 this->status = ISSL_HANDSHAKING;
577 // Handshake complete.
582 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
605 void VerifyCertificate()
608 ssl_cert* certinfo = new ssl_cert;
609 this->certificate = certinfo;
611 unsigned char md[EVP_MAX_MD_SIZE];
613 cert = SSL_get_peer_certificate(sess);
617 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
621 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
625 certinfo->unknownsigner = false;
626 certinfo->trusted = true;
630 certinfo->unknownsigner = true;
631 certinfo->trusted = false;
635 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
637 // Make sure there are no chars in the string that we consider invalid
638 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
639 certinfo->dn.clear();
641 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
642 certinfo->issuer = buf;
643 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
644 certinfo->issuer.clear();
646 if (!X509_digest(cert, GetProfile().GetDigest(), md, &n))
648 certinfo->error = "Out of memory generating fingerprint";
652 certinfo->fingerprint = BinToHex(md, n);
655 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))
657 certinfo->error = "Not activated, or expired certificate";
663 void SSLInfoCallback(int where, int rc)
665 if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN))
667 if (GetProfile().AllowRenegotiation())
670 // The other side is trying to renegotiate, kill the connection and change status
671 // to ISSL_NONE so CheckRenego() closes the session
673 BIO* bio = SSL_get_rbio(sess);
674 EventHandler* eh = static_cast<StreamSocket*>(BIO_get_data(bio));
675 SocketEngine::Shutdown(eh, 2);
679 bool CheckRenego(StreamSocket* sock)
681 if (status != ISSL_NONE)
684 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess);
686 sock->SetError("Renegotiation is not allowed");
690 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
691 int PrepareIO(StreamSocket* sock)
693 if (status == ISSL_OPEN)
695 else if (status == ISSL_HANDSHAKING)
697 // The handshake isn't finished, try to finish it
698 return Handshake(sock);
705 // Calls our private SSLInfoCallback()
706 friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
709 OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, SSL* session)
710 : SSLIOHook(hookprov)
713 , data_to_write(false)
715 // Create BIO instance and store a pointer to the socket in it which will be used by the read and write functions
716 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
717 BIO* bio = BIO_new(biomethods);
719 BIO* bio = BIO_new(&biomethods);
721 BIO_set_data(bio, sock);
722 SSL_set_bio(sess, bio, bio);
724 SSL_set_ex_data(sess, exdataindex, this);
725 sock->AddIOHook(this);
729 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
734 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
736 // Finish handshake if needed
737 int prepret = PrepareIO(user);
741 // If we resumed the handshake then this->status will be ISSL_OPEN
744 char* buffer = ServerInstance->GetReadBuffer();
745 size_t bufsiz = ServerInstance->Config->NetBufferSize;
746 int ret = SSL_read(sess, buffer, bufsiz);
748 if (!CheckRenego(user))
753 recvq.append(buffer, ret);
755 // Schedule a read if there is still data in the OpenSSL buffer
756 if (SSL_pending(sess) > 0)
757 mask |= FD_ADD_TRIAL_READ;
759 mask |= FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE;
761 SocketEngine::ChangeEventMask(user, mask);
766 // Client closed connection.
768 user->SetError("Connection closed");
773 int err = SSL_get_error(sess, ret);
775 if (err == SSL_ERROR_WANT_READ)
777 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
780 else if (err == SSL_ERROR_WANT_WRITE)
782 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
794 int OnStreamSocketWrite(StreamSocket* user, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
796 // Finish handshake if needed
797 int prepret = PrepareIO(user);
801 data_to_write = true;
803 // Session is ready for transferring application data
804 while (!sendq.empty())
807 FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
808 const StreamSocket::SendQueue::Element& buffer = sendq.front();
809 int ret = SSL_write(sess, buffer.data(), buffer.size());
811 if (!CheckRenego(user))
814 if (ret == (int)buffer.length())
816 // Wrote entire record, continue sending
821 sendq.erase_front(ret);
822 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
832 int err = SSL_get_error(sess, ret);
834 if (err == SSL_ERROR_WANT_WRITE)
836 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
839 else if (err == SSL_ERROR_WANT_READ)
841 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
852 data_to_write = false;
853 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
857 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
859 if (!IsHandshakeDone())
861 out.append(SSL_get_version(sess)).push_back('-');
862 out.append(SSL_get_cipher(sess));
865 bool GetServerName(std::string& out) const CXX11_OVERRIDE
867 const char* name = SSL_get_servername(sess, TLSEXT_NAMETYPE_host_name);
875 bool IsHandshakeDone() const { return (status == ISSL_OPEN); }
876 OpenSSL::Profile& GetProfile();
879 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc)
881 OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex));
882 hook->SSLInfoCallback(where, rc);
885 static int OpenSSL::BIOMethod::write(BIO* bio, const char* buffer, int size)
887 BIO_clear_retry_flags(bio);
889 StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
890 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
892 // Writes blocked earlier, don't retry syscall
893 BIO_set_retry_write(bio);
897 int ret = SocketEngine::Send(sock, buffer, size, 0);
898 if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
900 // Blocked, set retry flag for OpenSSL
901 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
902 BIO_set_retry_write(bio);
908 static int OpenSSL::BIOMethod::read(BIO* bio, char* buffer, int size)
910 BIO_clear_retry_flags(bio);
912 StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
913 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
915 // Reads blocked earlier, don't retry syscall
916 BIO_set_retry_read(bio);
920 int ret = SocketEngine::Recv(sock, buffer, size, 0);
921 if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
923 // Blocked, set retry flag for OpenSSL
924 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
925 BIO_set_retry_read(bio);
931 class OpenSSLIOHookProvider : public IOHookProvider
933 OpenSSL::Profile profile;
936 OpenSSLIOHookProvider(Module* mod, const std::string& profilename, ConfigTag* tag)
937 : IOHookProvider(mod, "ssl/" + profilename, IOHookProvider::IOH_SSL)
938 , profile(profilename, tag)
940 ServerInstance->Modules->AddService(*this);
943 ~OpenSSLIOHookProvider()
945 ServerInstance->Modules->DelService(*this);
948 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
950 new OpenSSLIOHook(this, sock, profile.CreateServerSession());
953 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
955 new OpenSSLIOHook(this, sock, profile.CreateClientSession());
958 OpenSSL::Profile& GetProfile() { return profile; }
961 OpenSSL::Profile& OpenSSLIOHook::GetProfile()
963 IOHookProvider* hookprov = prov;
964 return static_cast<OpenSSLIOHookProvider*>(hookprov)->GetProfile();
967 class ModuleSSLOpenSSL : public Module
969 typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
971 ProfileList profiles;
975 ProfileList newprofiles;
976 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
977 if (tags.first == tags.second)
979 // Create a default profile named "openssl"
980 const std::string defname = "openssl";
981 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
982 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
986 newprofiles.push_back(new OpenSSLIOHookProvider(this, defname, tag));
988 catch (OpenSSL::Exception& ex)
990 throw ModuleException("Error while initializing the default TLS (SSL) profile - " + ex.GetReason());
994 for (ConfigIter i = tags.first; i != tags.second; ++i)
996 ConfigTag* tag = i->second;
997 if (!stdalgo::string::equalsci(tag->getString("provider"), "openssl"))
1000 std::string name = tag->getString("name");
1003 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
1007 reference<OpenSSLIOHookProvider> prov;
1010 prov = new OpenSSLIOHookProvider(this, name, tag);
1012 catch (CoreException& ex)
1014 throw ModuleException("Error while initializing TLS (SSL) profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
1017 newprofiles.push_back(prov);
1020 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
1022 OpenSSLIOHookProvider& prov = **i;
1023 ServerInstance->Modules.DelService(prov);
1026 profiles.swap(newprofiles);
1032 // Initialize OpenSSL
1033 OPENSSL_init_ssl(0, NULL);
1034 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
1035 biomethods = OpenSSL::BIOMethod::alloc();
1040 BIO_meth_free(biomethods);
1044 void init() CXX11_OVERRIDE
1046 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "OpenSSL lib version \"%s\" module was compiled for \"" OPENSSL_VERSION_TEXT "\"", OpenSSL_version(OPENSSL_VERSION));
1048 // Register application specific data
1049 char exdatastr[] = "inspircd";
1050 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
1051 if (exdataindex < 0)
1052 throw ModuleException("Failed to register application specific data");
1057 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
1059 if (!irc::equals(param, "ssl"))
1065 ServerInstance->SNO->WriteToSnoMask('a', "TLS (SSL) module OpenSSL rehashed.");
1067 catch (ModuleException& ex)
1069 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
1073 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
1075 if (type == ExtensionItem::EXT_USER)
1077 LocalUser* user = IS_LOCAL((User*)item);
1079 if ((user) && (user->eh.GetModHook(this)))
1081 // User is using TLS (SSL), they're a local user, and they're using one of *our* TLS (SSL) ports.
1082 // Potentially there could be multiple TLS (SSL) modules loaded at once on different ports.
1083 ServerInstance->Users->QuitUser(user, "OpenSSL module unloading");
1088 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
1090 const OpenSSLIOHook* const iohook = static_cast<OpenSSLIOHook*>(user->eh.GetModHook(this));
1091 if ((iohook) && (!iohook->IsHandshakeDone()))
1092 return MOD_RES_DENY;
1093 return MOD_RES_PASSTHRU;
1096 Version GetVersion() CXX11_OVERRIDE
1098 return Version("Allows TLS (SSL) encrypted connections using the OpenSSL library.", VF_VENDOR);
1102 MODULE_INIT(ModuleSSLOpenSSL)