2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
6 * Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 /// $CompilerFlags: find_compiler_flags("openssl")
25 /// $LinkerFlags: find_linker_flags("openssl" "-lssl -lcrypto")
27 /// $PackageInfo: require_system("centos") openssl-devel pkgconfig
28 /// $PackageInfo: require_system("darwin") openssl pkg-config
29 /// $PackageInfo: require_system("debian") libssl-dev openssl pkg-config
30 /// $PackageInfo: require_system("ubuntu") libssl-dev openssl pkg-config
35 #include "modules/ssl.h"
37 // Ignore OpenSSL deprecation warnings on OS X Lion and newer.
39 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
42 // Fix warnings about the use of `long long` on C++03.
44 # pragma clang diagnostic ignored "-Wc++11-long-long"
45 #elif defined __GNUC__
46 # pragma GCC diagnostic ignored "-Wlong-long"
49 #include <openssl/ssl.h>
50 #include <openssl/err.h>
53 # pragma comment(lib, "ssleay32.lib")
54 # pragma comment(lib, "libeay32.lib")
57 #if ((OPENSSL_VERSION_NUMBER >= 0x10000000L) && (!(defined(OPENSSL_NO_ECDH))))
58 // OpenSSL 0.9.8 includes some ECC support, but it's unfinished. Enable only for 1.0.0 and later.
59 #define INSPIRCD_OPENSSL_ENABLE_ECDH
62 // BIO is opaque in OpenSSL 1.1 but the access API does not exist in 1.0 and older.
63 #if ((defined LIBRESSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x10100000L))
64 # define BIO_get_data(BIO) BIO->ptr
65 # define BIO_set_data(BIO, VALUE) BIO->ptr = VALUE;
66 # define BIO_set_init(BIO, VALUE) BIO->init = VALUE;
68 # define INSPIRCD_OPENSSL_OPAQUE_BIO
71 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
73 static bool SelfSigned = false;
74 static int exdataindex;
78 return ERR_error_string(ERR_get_error(), NULL);
81 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
82 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
86 class Exception : public ModuleException
89 Exception(const std::string& reason)
90 : ModuleException(reason) { }
98 DHParams(const std::string& filename)
100 BIO* dhpfile = BIO_new_file(filename.c_str(), "r");
102 throw Exception("Couldn't open DH file " + filename);
104 dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
108 throw Exception("Couldn't read DH params from file " + filename);
128 Context(SSL_CTX* context)
131 // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
132 // and when choosing a cipher, use the server's preferences instead of the client preferences.
133 long opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE;
134 // Only turn options on if they exist
135 #ifdef SSL_OP_SINGLE_ECDH_USE
136 opts |= SSL_OP_SINGLE_ECDH_USE;
138 #ifdef SSL_OP_NO_TICKET
139 opts |= SSL_OP_NO_TICKET;
142 ctx_options = SSL_CTX_set_options(ctx, opts);
144 long mode = SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
145 #ifdef SSL_MODE_RELEASE_BUFFERS
146 mode |= SSL_MODE_RELEASE_BUFFERS;
148 SSL_CTX_set_mode(ctx, mode);
149 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
150 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
151 SSL_CTX_set_info_callback(ctx, StaticSSLInfoCallback);
159 bool SetDH(DHParams& dh)
162 return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
165 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
166 void SetECDH(const std::string& curvename)
168 int nid = OBJ_sn2nid(curvename.c_str());
170 throw Exception("Unknown curve: " + curvename);
172 EC_KEY* eckey = EC_KEY_new_by_curve_name(nid);
174 throw Exception("Unable to create EC key object");
177 bool ret = (SSL_CTX_set_tmp_ecdh(ctx, eckey) >= 0);
180 throw Exception("Couldn't set ECDH parameters");
184 bool SetCiphers(const std::string& ciphers)
187 return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
190 bool SetCerts(const std::string& filename)
193 return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
196 bool SetPrivateKey(const std::string& filename)
199 return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
202 bool SetCA(const std::string& filename)
205 return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
208 long GetDefaultContextOptions() const
213 long SetRawContextOptions(long setoptions, long clearoptions)
216 SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
218 // Set the default options and what is in the conf
219 SSL_CTX_set_options(ctx, ctx_options | setoptions);
220 return SSL_CTX_clear_options(ctx, clearoptions);
225 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
228 SSL* CreateServerSession()
230 SSL* sess = SSL_new(ctx);
231 SSL_set_accept_state(sess); // Act as server
235 SSL* CreateClientSession()
237 SSL* sess = SSL_new(ctx);
238 SSL_set_connect_state(sess); // Act as client
245 /** Name of this profile
247 const std::string name;
249 /** DH parameters in use
253 /** OpenSSL makes us have two contexts, one for servers and one for clients
258 /** Digest to use when generating fingerprints
260 const EVP_MD* digest;
262 /** Last error, set by error_callback()
266 /** True if renegotiations are allowed, false if not
268 const bool allowrenego;
270 /** Rough max size of records to send
272 const unsigned int outrecsize;
274 static int error_callback(const char* str, size_t len, void* u)
276 Profile* profile = reinterpret_cast<Profile*>(u);
277 profile->lasterr = std::string(str, len - 1);
281 /** Set raw OpenSSL context (SSL_CTX) options from a config tag
282 * @param ctxname Name of the context, client or server
283 * @param tag Config tag defining this profile
284 * @param context Context object to manipulate
286 void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context)
288 long setoptions = tag->getInt(ctxname + "setoptions");
289 long clearoptions = tag->getInt(ctxname + "clearoptions");
290 #ifdef SSL_OP_NO_COMPRESSION
291 if (!tag->getBool("compression", false)) // Disable compression by default
292 setoptions |= SSL_OP_NO_COMPRESSION;
294 if (!tag->getBool("sslv3", false)) // Disable SSLv3 by default
295 setoptions |= SSL_OP_NO_SSLv3;
296 if (!tag->getBool("tlsv1", true))
297 setoptions |= SSL_OP_NO_TLSv1;
299 if (!setoptions && !clearoptions)
300 return; // Nothing to do
302 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);
303 long final = context.SetRawContextOptions(setoptions, clearoptions);
304 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final);
308 Profile(const std::string& profilename, ConfigTag* tag)
310 , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dhparams.pem")))
311 , ctx(SSL_CTX_new(SSLv23_server_method()))
312 , clictx(SSL_CTX_new(SSLv23_client_method()))
313 , allowrenego(tag->getBool("renegotiation")) // Disallow by default
314 , outrecsize(tag->getInt("outrecsize", 2048, 512, 16384))
316 if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
317 throw Exception("Couldn't set DH parameters");
319 std::string hash = tag->getString("hash", "md5");
320 digest = EVP_get_digestbyname(hash.c_str());
322 throw Exception("Unknown hash type " + hash);
324 std::string ciphers = tag->getString("ciphers");
325 if (!ciphers.empty())
327 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
329 ERR_print_errors_cb(error_callback, this);
330 throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
334 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
335 std::string curvename = tag->getString("ecdhcurve", "prime256v1");
336 if (!curvename.empty())
337 ctx.SetECDH(curvename);
340 SetContextOptions("server", tag, ctx);
341 SetContextOptions("client", tag, clictx);
343 /* Load our keys and certificates
344 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
346 std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
347 if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
349 ERR_print_errors_cb(error_callback, this);
350 throw Exception("Can't read certificate file: " + lasterr);
353 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
354 if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
356 ERR_print_errors_cb(error_callback, this);
357 throw Exception("Can't read key file: " + lasterr);
360 // Load the CAs we trust
361 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
362 if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
364 ERR_print_errors_cb(error_callback, this);
365 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());
368 clictx.SetVerifyCert();
369 if (tag->getBool("requestclientcert", true))
373 const std::string& GetName() const { return name; }
374 SSL* CreateServerSession() { return ctx.CreateServerSession(); }
375 SSL* CreateClientSession() { return clictx.CreateClientSession(); }
376 const EVP_MD* GetDigest() { return digest; }
377 bool AllowRenegotiation() const { return allowrenego; }
378 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
383 static int create(BIO* bio)
385 BIO_set_init(bio, 1);
389 static int destroy(BIO* bio)
391 // XXX: Dummy function to avoid a memory leak in OpenSSL.
392 // The memory leak happens in BIO_free() (bio_lib.c) when the destroy func of the BIO is NULL.
393 // This is fixed in OpenSSL but some distros still ship the unpatched version hence we provide this workaround.
397 static long ctrl(BIO* bio, int cmd, long num, void* ptr)
399 if (cmd == BIO_CTRL_FLUSH)
404 static int read(BIO* bio, char* buf, int len);
405 static int write(BIO* bio, const char* buf, int len);
407 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
408 static BIO_METHOD* alloc()
410 BIO_METHOD* meth = BIO_meth_new(100 | BIO_TYPE_SOURCE_SINK, "inspircd");
411 BIO_meth_set_write(meth, OpenSSL::BIOMethod::write);
412 BIO_meth_set_read(meth, OpenSSL::BIOMethod::read);
413 BIO_meth_set_ctrl(meth, OpenSSL::BIOMethod::ctrl);
414 BIO_meth_set_create(meth, OpenSSL::BIOMethod::create);
415 BIO_meth_set_destroy(meth, OpenSSL::BIOMethod::destroy);
422 // BIO_METHOD is opaque in OpenSSL 1.1 so we can't do this.
423 // See OpenSSL::BIOMethod::alloc for the new method.
424 #ifndef INSPIRCD_OPENSSL_OPAQUE_BIO
425 static BIO_METHOD biomethods =
427 (100 | BIO_TYPE_SOURCE_SINK),
429 OpenSSL::BIOMethod::write,
430 OpenSSL::BIOMethod::read,
433 OpenSSL::BIOMethod::ctrl,
434 OpenSSL::BIOMethod::create,
435 OpenSSL::BIOMethod::destroy, // destroy, does nothing, see function body for more info
436 NULL // callback_ctrl
439 static BIO_METHOD* biomethods;
442 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
444 /* XXX: This will allow self signed certificates.
445 * In the future if we want an option to not allow this,
446 * we can just return preverify_ok here, and openssl
447 * will boot off self-signed and invalid peer certs.
449 int ve = X509_STORE_CTX_get_error(ctx);
451 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
456 class OpenSSLIOHook : public SSLIOHook
463 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
464 int Handshake(StreamSocket* user)
467 int ret = SSL_do_handshake(sess);
470 int err = SSL_get_error(sess, ret);
472 if (err == SSL_ERROR_WANT_READ)
474 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
475 this->status = ISSL_HANDSHAKING;
478 else if (err == SSL_ERROR_WANT_WRITE)
480 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
481 this->status = ISSL_HANDSHAKING;
492 // Handshake complete.
497 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
520 void VerifyCertificate()
523 ssl_cert* certinfo = new ssl_cert;
524 this->certificate = certinfo;
526 unsigned char md[EVP_MAX_MD_SIZE];
528 cert = SSL_get_peer_certificate(sess);
532 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
536 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
540 certinfo->unknownsigner = false;
541 certinfo->trusted = true;
545 certinfo->unknownsigner = true;
546 certinfo->trusted = false;
550 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
552 // Make sure there are no chars in the string that we consider invalid
553 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
554 certinfo->dn.clear();
556 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
557 certinfo->issuer = buf;
558 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
559 certinfo->issuer.clear();
561 if (!X509_digest(cert, GetProfile().GetDigest(), md, &n))
563 certinfo->error = "Out of memory generating fingerprint";
567 certinfo->fingerprint = BinToHex(md, n);
570 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), ServerInstance->Time()) == 0))
572 certinfo->error = "Not activated, or expired certificate";
578 void SSLInfoCallback(int where, int rc)
580 if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN))
582 if (GetProfile().AllowRenegotiation())
585 // The other side is trying to renegotiate, kill the connection and change status
586 // to ISSL_NONE so CheckRenego() closes the session
588 BIO* bio = SSL_get_rbio(sess);
589 EventHandler* eh = static_cast<StreamSocket*>(BIO_get_data(bio));
590 SocketEngine::Shutdown(eh, 2);
594 bool CheckRenego(StreamSocket* sock)
596 if (status != ISSL_NONE)
599 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess);
601 sock->SetError("Renegotiation is not allowed");
605 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
606 int PrepareIO(StreamSocket* sock)
608 if (status == ISSL_OPEN)
610 else if (status == ISSL_HANDSHAKING)
612 // The handshake isn't finished, try to finish it
613 return Handshake(sock);
620 // Calls our private SSLInfoCallback()
621 friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
624 OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, SSL* session)
625 : SSLIOHook(hookprov)
628 , data_to_write(false)
630 // Create BIO instance and store a pointer to the socket in it which will be used by the read and write functions
631 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
632 BIO* bio = BIO_new(biomethods);
634 BIO* bio = BIO_new(&biomethods);
636 BIO_set_data(bio, sock);
637 SSL_set_bio(sess, bio, bio);
639 SSL_set_ex_data(sess, exdataindex, this);
640 sock->AddIOHook(this);
644 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
649 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
651 // Finish handshake if needed
652 int prepret = PrepareIO(user);
656 // If we resumed the handshake then this->status will be ISSL_OPEN
659 char* buffer = ServerInstance->GetReadBuffer();
660 size_t bufsiz = ServerInstance->Config->NetBufferSize;
661 int ret = SSL_read(sess, buffer, bufsiz);
663 if (!CheckRenego(user))
668 recvq.append(buffer, ret);
670 // Schedule a read if there is still data in the OpenSSL buffer
671 if (SSL_pending(sess) > 0)
672 mask |= FD_ADD_TRIAL_READ;
674 mask |= FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE;
676 SocketEngine::ChangeEventMask(user, mask);
681 // Client closed connection.
683 user->SetError("Connection closed");
688 int err = SSL_get_error(sess, ret);
690 if (err == SSL_ERROR_WANT_READ)
692 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
695 else if (err == SSL_ERROR_WANT_WRITE)
697 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
709 int OnStreamSocketWrite(StreamSocket* user, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
711 // Finish handshake if needed
712 int prepret = PrepareIO(user);
716 data_to_write = true;
718 // Session is ready for transferring application data
719 while (!sendq.empty())
722 FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
723 const StreamSocket::SendQueue::Element& buffer = sendq.front();
724 int ret = SSL_write(sess, buffer.data(), buffer.size());
726 if (!CheckRenego(user))
729 if (ret == (int)buffer.length())
731 // Wrote entire record, continue sending
736 sendq.erase_front(ret);
737 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
747 int err = SSL_get_error(sess, ret);
749 if (err == SSL_ERROR_WANT_WRITE)
751 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
754 else if (err == SSL_ERROR_WANT_READ)
756 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
767 data_to_write = false;
768 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
772 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
774 if (!IsHandshakeDone())
776 out.append(SSL_get_version(sess)).push_back('-');
777 out.append(SSL_get_cipher(sess));
780 bool GetServerName(std::string& out) const CXX11_OVERRIDE
782 const char* name = SSL_get_servername(sess, TLSEXT_NAMETYPE_host_name);
790 bool IsHandshakeDone() const { return (status == ISSL_OPEN); }
791 OpenSSL::Profile& GetProfile();
794 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc)
796 OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex));
797 hook->SSLInfoCallback(where, rc);
800 static int OpenSSL::BIOMethod::write(BIO* bio, const char* buffer, int size)
802 BIO_clear_retry_flags(bio);
804 StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
805 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
807 // Writes blocked earlier, don't retry syscall
808 BIO_set_retry_write(bio);
812 int ret = SocketEngine::Send(sock, buffer, size, 0);
813 if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
815 // Blocked, set retry flag for OpenSSL
816 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
817 BIO_set_retry_write(bio);
823 static int OpenSSL::BIOMethod::read(BIO* bio, char* buffer, int size)
825 BIO_clear_retry_flags(bio);
827 StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
828 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
830 // Reads blocked earlier, don't retry syscall
831 BIO_set_retry_read(bio);
835 int ret = SocketEngine::Recv(sock, buffer, size, 0);
836 if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
838 // Blocked, set retry flag for OpenSSL
839 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
840 BIO_set_retry_read(bio);
846 class OpenSSLIOHookProvider : public IOHookProvider
848 OpenSSL::Profile profile;
851 OpenSSLIOHookProvider(Module* mod, const std::string& profilename, ConfigTag* tag)
852 : IOHookProvider(mod, "ssl/" + profilename, IOHookProvider::IOH_SSL)
853 , profile(profilename, tag)
855 ServerInstance->Modules->AddService(*this);
858 ~OpenSSLIOHookProvider()
860 ServerInstance->Modules->DelService(*this);
863 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
865 new OpenSSLIOHook(this, sock, profile.CreateServerSession());
868 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
870 new OpenSSLIOHook(this, sock, profile.CreateClientSession());
873 OpenSSL::Profile& GetProfile() { return profile; }
876 OpenSSL::Profile& OpenSSLIOHook::GetProfile()
878 IOHookProvider* hookprov = prov;
879 return static_cast<OpenSSLIOHookProvider*>(hookprov)->GetProfile();
882 class ModuleSSLOpenSSL : public Module
884 typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
886 ProfileList profiles;
890 ProfileList newprofiles;
891 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
892 if (tags.first == tags.second)
894 // Create a default profile named "openssl"
895 const std::string defname = "openssl";
896 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
897 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
901 newprofiles.push_back(new OpenSSLIOHookProvider(this, defname, tag));
903 catch (OpenSSL::Exception& ex)
905 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
909 for (ConfigIter i = tags.first; i != tags.second; ++i)
911 ConfigTag* tag = i->second;
912 if (tag->getString("provider") != "openssl")
915 std::string name = tag->getString("name");
918 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
922 reference<OpenSSLIOHookProvider> prov;
925 prov = new OpenSSLIOHookProvider(this, name, tag);
927 catch (CoreException& ex)
929 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
932 newprofiles.push_back(prov);
935 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
937 OpenSSLIOHookProvider& prov = **i;
938 ServerInstance->Modules.DelService(prov);
941 profiles.swap(newprofiles);
947 // Initialize OpenSSL
949 SSL_load_error_strings();
950 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
951 biomethods = OpenSSL::BIOMethod::alloc();
956 BIO_meth_free(biomethods);
960 void init() CXX11_OVERRIDE
962 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "OpenSSL lib version \"%s\" module was compiled for \"" OPENSSL_VERSION_TEXT "\"", SSLeay_version(SSLEAY_VERSION));
964 // Register application specific data
965 char exdatastr[] = "inspircd";
966 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
968 throw ModuleException("Failed to register application specific data");
973 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
982 catch (ModuleException& ex)
984 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
988 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
990 if (type == ExtensionItem::EXT_USER)
992 LocalUser* user = IS_LOCAL((User*)item);
994 if ((user) && (user->eh.GetModHook(this)))
996 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
997 // Potentially there could be multiple SSL modules loaded at once on different ports.
998 ServerInstance->Users->QuitUser(user, "SSL module unloading");
1003 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
1005 const OpenSSLIOHook* const iohook = static_cast<OpenSSLIOHook*>(user->eh.GetModHook(this));
1006 if ((iohook) && (!iohook->IsHandshakeDone()))
1007 return MOD_RES_DENY;
1008 return MOD_RES_PASSTHRU;
1011 Version GetVersion() CXX11_OVERRIDE
1013 return Version("Provides SSL support for clients", VF_VENDOR);
1017 MODULE_INIT(ModuleSSLOpenSSL)