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 /* HACK: This prevents OpenSSL on OS X 10.7 and later from spewing deprecation
25 * warnings for every single function call. As far as I (SaberUK) know, Apple
26 * have no plans to remove OpenSSL so this warning just causes needless spam.
29 # define __AVAILABILITYMACROS__
30 # define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
35 #include <openssl/ssl.h>
36 #include <openssl/err.h>
37 #include "modules/ssl.h"
40 # pragma comment(lib, "libcrypto.lib")
41 # pragma comment(lib, "libssl.lib")
42 # pragma comment(lib, "user32.lib")
43 # pragma comment(lib, "advapi32.lib")
44 # pragma comment(lib, "libgcc.lib")
45 # pragma comment(lib, "libmingwex.lib")
46 # pragma comment(lib, "gdi32.lib")
47 # undef MAX_DESCRIPTORS
48 # define MAX_DESCRIPTORS 10000
51 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") -Wno-pedantic */
52 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */
54 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
56 static bool SelfSigned = false;
60 return ERR_error_string(ERR_get_error(), NULL);
63 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
67 class Exception : public ModuleException
70 Exception(const std::string& reason)
71 : ModuleException(reason) { }
79 DHParams(const std::string& filename)
81 FILE* dhpfile = fopen(filename.c_str(), "r");
83 throw Exception("Couldn't open DH file " + filename + ": " + strerror(errno));
85 dh = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
88 throw Exception("Couldn't read DH params from file " + filename);
107 Context(SSL_CTX* context)
110 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
111 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
119 bool SetDH(DHParams& dh)
121 return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
124 bool SetCiphers(const std::string& ciphers)
126 return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
129 bool SetCerts(const std::string& filename)
131 return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
134 bool SetPrivateKey(const std::string& filename)
136 return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
139 bool SetCA(const std::string& filename)
141 return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
150 class Profile : public refcountbase
152 /** Name of this profile
154 const std::string name;
156 /** DH parameters in use
160 /** OpenSSL makes us have two contexts, one for servers and one for clients
165 /** Digest to use when generating fingerprints
167 const EVP_MD* digest;
169 /** Last error, set by error_callback()
173 static int error_callback(const char* str, size_t len, void* u)
175 Profile* profile = reinterpret_cast<Profile*>(u);
176 profile->lasterr = std::string(str, len - 1);
181 Profile(const std::string& profilename, ConfigTag* tag)
183 , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem")))
184 , ctx(SSL_CTX_new(SSLv23_server_method()))
185 , clictx(SSL_CTX_new(SSLv23_client_method()))
187 if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
188 throw Exception("Couldn't set DH parameters");
190 std::string hash = tag->getString("hash", "md5");
191 digest = EVP_get_digestbyname(hash.c_str());
193 throw Exception("Unknown hash type " + hash);
195 std::string ciphers = tag->getString("ciphers");
196 if (!ciphers.empty())
198 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
200 ERR_print_errors_cb(error_callback, this);
201 throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
205 /* Load our keys and certificates
206 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
208 std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
209 if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
211 ERR_print_errors_cb(error_callback, this);
212 throw Exception("Can't read certificate file: " + lasterr);
215 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
216 if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
218 ERR_print_errors_cb(error_callback, this);
219 throw Exception("Can't read key file: " + lasterr);
222 // Load the CAs we trust
223 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
224 if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
226 ERR_print_errors_cb(error_callback, this);
227 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());
231 const std::string& GetName() const { return name; }
232 SSL* CreateServerSession() { return ctx.CreateSession(); }
233 SSL* CreateClientSession() { return clictx.CreateSession(); }
234 const EVP_MD* GetDigest() { return digest; }
238 /** Represents an SSL user's extra data
245 reference<ssl_cert> cert;
246 reference<OpenSSL::Profile> profile;
254 data_to_write = false;
258 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
260 /* XXX: This will allow self signed certificates.
261 * In the future if we want an option to not allow this,
262 * we can just return preverify_ok here, and openssl
263 * will boot off self-signed and invalid peer certs.
265 int ve = X509_STORE_CTX_get_error(ctx);
267 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
272 class OpenSSLIOHook : public SSLIOHook
275 bool Handshake(StreamSocket* user, issl_session* session)
279 if (session->outbound)
280 ret = SSL_connect(session->sess);
282 ret = SSL_accept(session->sess);
286 int err = SSL_get_error(session->sess, ret);
288 if (err == SSL_ERROR_WANT_READ)
290 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
291 session->status = ISSL_HANDSHAKING;
294 else if (err == SSL_ERROR_WANT_WRITE)
296 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
297 session->status = ISSL_HANDSHAKING;
302 CloseSession(session);
309 // Handshake complete.
310 VerifyCertificate(session, user);
312 session->status = ISSL_OPEN;
314 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
320 CloseSession(session);
327 void CloseSession(issl_session* session)
331 SSL_shutdown(session->sess);
332 SSL_free(session->sess);
335 session->sess = NULL;
336 session->status = ISSL_NONE;
340 void VerifyCertificate(issl_session* session, StreamSocket* user)
342 if (!session->sess || !user)
346 ssl_cert* certinfo = new ssl_cert;
347 session->cert = certinfo;
349 unsigned char md[EVP_MAX_MD_SIZE];
351 cert = SSL_get_peer_certificate((SSL*)session->sess);
355 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
359 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
363 certinfo->unknownsigner = false;
364 certinfo->trusted = true;
368 certinfo->unknownsigner = true;
369 certinfo->trusted = false;
372 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
373 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
375 if (!X509_digest(cert, session->profile->GetDigest(), md, &n))
377 certinfo->error = "Out of memory generating fingerprint";
381 certinfo->fingerprint = BinToHex(md, n);
384 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))
386 certinfo->error = "Not activated, or expired certificate";
393 issl_session* sessions;
395 OpenSSLIOHook(Module* mod)
396 : SSLIOHook(mod, "ssl/openssl")
398 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
406 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
408 int fd = user->GetFd();
410 issl_session* session = &sessions[fd];
412 session->sess = session->profile->CreateServerSession();
413 session->status = ISSL_NONE;
414 session->outbound = false;
415 session->cert = NULL;
417 if (session->sess == NULL)
420 if (SSL_set_fd(session->sess, fd) == 0)
422 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Can't set fd with SSL_set_fd: %d", fd);
426 Handshake(user, session);
429 void OnStreamSocketConnect(StreamSocket* user) CXX11_OVERRIDE
431 int fd = user->GetFd();
432 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
433 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
436 issl_session* session = &sessions[fd];
438 session->sess = session->profile->CreateClientSession();
439 session->status = ISSL_NONE;
440 session->outbound = true;
442 if (session->sess == NULL)
445 if (SSL_set_fd(session->sess, fd) == 0)
447 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Can't set fd with SSL_set_fd: %d", fd);
451 Handshake(user, session);
454 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
456 int fd = user->GetFd();
457 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
458 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
461 CloseSession(&sessions[fd]);
464 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
466 int fd = user->GetFd();
467 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
468 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
471 issl_session* session = &sessions[fd];
475 CloseSession(session);
479 if (session->status == ISSL_HANDSHAKING)
481 // The handshake isn't finished and it wants to read, try to finish it.
482 if (!Handshake(user, session))
484 // Couldn't resume handshake.
485 if (session->status == ISSL_NONE)
491 // If we resumed the handshake then session->status will be ISSL_OPEN
493 if (session->status == ISSL_OPEN)
495 char* buffer = ServerInstance->GetReadBuffer();
496 size_t bufsiz = ServerInstance->Config->NetBufferSize;
497 int ret = SSL_read(session->sess, buffer, bufsiz);
501 recvq.append(buffer, ret);
502 if (session->data_to_write)
503 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
508 // Client closed connection.
509 CloseSession(session);
510 user->SetError("Connection closed");
515 int err = SSL_get_error(session->sess, ret);
517 if (err == SSL_ERROR_WANT_READ)
519 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
522 else if (err == SSL_ERROR_WANT_WRITE)
524 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
529 CloseSession(session);
538 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
540 int fd = user->GetFd();
542 issl_session* session = &sessions[fd];
546 CloseSession(session);
550 session->data_to_write = true;
552 if (session->status == ISSL_HANDSHAKING)
554 if (!Handshake(user, session))
556 // Couldn't resume handshake.
557 if (session->status == ISSL_NONE)
563 if (session->status == ISSL_OPEN)
565 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
566 if (ret == (int)buffer.length())
568 session->data_to_write = false;
569 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
574 buffer = buffer.substr(ret);
575 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
580 CloseSession(session);
585 int err = SSL_get_error(session->sess, ret);
587 if (err == SSL_ERROR_WANT_WRITE)
589 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
592 else if (err == SSL_ERROR_WANT_READ)
594 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
599 CloseSession(session);
607 ssl_cert* GetCertificate(StreamSocket* sock) CXX11_OVERRIDE
609 int fd = sock->GetFd();
610 issl_session* session = &sessions[fd];
611 return session->cert;
614 void TellCiphersAndFingerprint(LocalUser* user)
616 issl_session& s = sessions[user->eh.GetFd()];
619 std::string text = "*** You are connected using SSL cipher '" + std::string(SSL_get_cipher(s.sess)) + "'";
620 const std::string& fingerprint = s.cert->fingerprint;
621 if (!fingerprint.empty())
622 text += " and your SSL fingerprint is " + fingerprint;
624 user->WriteNotice(text);
629 class ModuleSSLOpenSSL : public Module
631 typedef std::vector<reference<OpenSSL::Profile> > ProfileList;
633 std::string sslports;
634 OpenSSLIOHook iohook;
635 ProfileList profiles;
639 ProfileList newprofiles;
640 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
641 if (tags.first == tags.second)
643 // Create a default profile named "openssl"
644 const std::string defname = "openssl";
645 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
646 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
650 reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag));
651 newprofiles.push_back(profile);
653 catch (OpenSSL::Exception& ex)
655 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
659 for (ConfigIter i = tags.first; i != tags.second; ++i)
661 ConfigTag* tag = i->second;
662 if (tag->getString("provider") != "openssl")
665 std::string name = tag->getString("name");
668 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
672 reference<OpenSSL::Profile> profile;
675 profile = new OpenSSL::Profile(name, tag);
677 catch (CoreException& ex)
679 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
682 newprofiles.push_back(profile);
685 profiles.swap(newprofiles);
689 ModuleSSLOpenSSL() : iohook(this)
691 // Initialize OpenSSL
693 SSL_load_error_strings();
696 void init() CXX11_OVERRIDE
701 void OnHookIO(StreamSocket* user, ListenSocket* lsb) CXX11_OVERRIDE
703 if (user->GetIOHook())
706 ConfigTag* tag = lsb->bind_tag;
707 std::string profilename = tag->getString("ssl");
708 for (ProfileList::const_iterator i = profiles.begin(); i != profiles.end(); ++i)
710 if ((*i)->GetName() == profilename)
712 iohook.sessions[user->GetFd()].profile = *i;
713 user->AddIOHook(&iohook);
719 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
723 ConfigTag* Conf = ServerInstance->Config->ConfValue("openssl");
725 if (Conf->getBool("showports", true))
727 sslports = Conf->getString("advertisedports");
728 if (!sslports.empty())
731 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
733 ListenSocket* port = ServerInstance->ports[i];
734 if (port->bind_tag->getString("ssl") != "openssl")
737 const std::string& portid = port->bind_desc;
738 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Enabling SSL for port %s", portid.c_str());
740 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
743 * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
744 * the IP:port in ISUPPORT.
746 * We used to advertise all ports seperated by a ';' char that matched the above criteria,
747 * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
748 * To solve this by default we now only display the first IP:port found and let the user
749 * configure the exact value for the 005 token, if necessary.
758 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
767 catch (ModuleException& ex)
769 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
773 void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
775 if (!sslports.empty())
776 tokens["SSL"] = sslports;
779 void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
781 if (user->eh.GetIOHook() == &iohook)
782 iohook.TellCiphersAndFingerprint(user);
785 void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
787 if (target_type == TYPE_USER)
789 LocalUser* user = IS_LOCAL((User*)item);
791 if (user && user->eh.GetIOHook() == &iohook)
793 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
794 // Potentially there could be multiple SSL modules loaded at once on different ports.
795 ServerInstance->Users->QuitUser(user, "SSL module unloading");
800 Version GetVersion() CXX11_OVERRIDE
802 return Version("Provides SSL support for clients", VF_VENDOR);
806 MODULE_INIT(ModuleSSLOpenSSL)