1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 #include <openssl/ssl.h>
17 #include <openssl/err.h>
20 #include <openssl/applink.c>
23 #include "configreader.h"
31 #include "transport.h"
34 #pragma comment(lib, "libeay32MTd")
35 #pragma comment(lib, "ssleay32MTd")
36 #undef MAX_DESCRIPTORS
37 #define MAX_DESCRIPTORS 10000
40 /* $ModDesc: Provides SSL support for clients */
41 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
42 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
43 /* $ModDep: transport.h */
45 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
46 enum issl_io_status { ISSL_WRITE, ISSL_READ };
48 static bool SelfSigned = false;
50 bool isin(int port, const std::vector<int> &portlist)
52 for(unsigned int i = 0; i < portlist.size(); i++)
53 if(portlist[i] == port)
61 return ERR_error_string(ERR_get_error(), NULL);
64 static int error_callback(const char *str, size_t len, void *u);
66 /** Represents an SSL user's extra data
68 class issl_session : public classbase
76 unsigned int inbufoffset;
77 char* inbuf; // Buffer OpenSSL reads into.
78 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
90 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
92 /* XXX: This will allow self signed certificates.
93 * In the future if we want an option to not allow this,
94 * we can just return preverify_ok here, and openssl
95 * will boot off self-signed and invalid peer certs.
97 int ve = X509_STORE_CTX_get_error(ctx);
99 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
104 class ModuleSSLOpenSSL : public Module
109 std::vector<int> listenports;
112 issl_session sessions[MAX_DESCRIPTORS];
121 std::string certfile;
123 // std::string crlfile;
130 InspIRCd* PublicInstance;
132 ModuleSSLOpenSSL(InspIRCd* Me)
133 : Module(Me), PublicInstance(Me)
135 ServerInstance->PublishInterface("InspSocketHook", this);
137 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
138 inbufsize = ServerInstance->Config->NetBufferSize;
140 /* Global SSL library initialization*/
142 SSL_load_error_strings();
144 /* Build our SSL contexts:
145 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
147 ctx = SSL_CTX_new( SSLv23_server_method() );
148 clictx = SSL_CTX_new( SSLv23_client_method() );
150 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
151 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
153 // Needs the flag as it ignores a plain /rehash
154 OnRehash(NULL,"ssl");
157 virtual void OnRehash(userrec* user, const std::string ¶m)
162 Conf = new ConfigReader(ServerInstance);
164 for (unsigned int i = 0; i < listenports.size(); i++)
166 ServerInstance->Config->DelIOHook(listenports[i]);
172 for (int i = 0; i < Conf->Enumerate("bind"); i++)
174 // For each <bind> tag
175 std::string x = Conf->ReadValue("bind", "type", i);
176 if (((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
178 // Get the port we're meant to be listening on with SSL
179 std::string port = Conf->ReadValue("bind", "port", i);
180 irc::portparser portrange(port, false);
182 while ((portno = portrange.GetToken()))
187 if (ServerInstance->Config->AddIOHook(portno, this))
189 listenports.push_back(portno);
190 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
191 if (ServerInstance->Config->ports[i]->GetPort() == portno)
192 ServerInstance->Config->ports[i]->SetDescription("ssl");
193 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
197 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
200 catch (ModuleException &e)
202 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d: %s. Maybe it's already hooked by the same port on a different IP, or you have another SSL or similar module loaded?", portno, e.GetReason());
208 std::string confdir(ServerInstance->ConfigFileName);
209 // +1 so we the path ends with a /
210 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
212 cafile = Conf->ReadValue("openssl", "cafile", 0);
213 certfile = Conf->ReadValue("openssl", "certfile", 0);
214 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
215 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
217 // Set all the default values needed.
221 if (certfile.empty())
222 certfile = "cert.pem";
228 dhfile = "dhparams.pem";
230 // Prepend relative paths with the path to the config directory.
231 if (cafile[0] != '/')
232 cafile = confdir + cafile;
234 if (certfile[0] != '/')
235 certfile = confdir + certfile;
237 if (keyfile[0] != '/')
238 keyfile = confdir + keyfile;
240 if (dhfile[0] != '/')
241 dhfile = confdir + dhfile;
243 /* Load our keys and certificates
244 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
246 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
248 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
249 ERR_print_errors_cb(error_callback, this);
252 if (((!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) || (!SSL_CTX_use_PrivateKey_file(clictx, keyfile.c_str(), SSL_FILETYPE_PEM)))
254 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
255 ERR_print_errors_cb(error_callback, this);
258 /* Load the CAs we trust*/
259 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
261 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
262 ERR_print_errors_cb(error_callback, this);
265 FILE* dhpfile = fopen(dhfile.c_str(), "r");
270 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
271 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
275 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
276 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
278 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
279 ERR_print_errors_cb(error_callback, this);
288 virtual ~ModuleSSLOpenSSL()
291 SSL_CTX_free(clictx);
294 virtual void OnCleanup(int target_type, void* item)
296 if (target_type == TYPE_USER)
298 userrec* user = (userrec*)item;
300 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
302 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
303 // Potentially there could be multiple SSL modules loaded at once on different ports.
304 ServerInstance->GlobalCulls.AddItem(user, "SSL module unloading");
306 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
309 user->GetExt("ssl_cert", tofree);
311 user->Shrink("ssl_cert");
316 virtual void OnUnloadModule(Module* mod, const std::string &name)
320 for(unsigned int i = 0; i < listenports.size(); i++)
322 ServerInstance->Config->DelIOHook(listenports[i]);
323 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
324 if (ServerInstance->Config->ports[j]->GetPort() == listenports[i])
325 ServerInstance->Config->ports[j]->SetDescription("plaintext");
330 virtual Version GetVersion()
332 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
335 void Implements(char* List)
337 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
338 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
341 virtual char* OnRequest(Request* request)
343 ISHRequest* ISR = (ISHRequest*)request;
344 if (strcmp("IS_NAME", request->GetId()) == 0)
348 else if (strcmp("IS_HOOK", request->GetId()) == 0)
353 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
355 catch (ModuleException &e)
362 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
364 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
366 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
368 if (ISR->Sock->GetFd() < 0)
371 issl_session* session = &sessions[ISR->Sock->GetFd()];
372 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
374 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
376 issl_session* session = &sessions[ISR->Sock->GetFd()];
379 VerifyCertificate(session, (InspSocket*)ISR->Sock);
387 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
389 issl_session* session = &sessions[fd];
392 session->inbuf = new char[inbufsize];
393 session->inbufoffset = 0;
394 session->sess = SSL_new(ctx);
395 session->status = ISSL_NONE;
396 session->outbound = false;
398 if (session->sess == NULL)
401 if (SSL_set_fd(session->sess, fd) == 0)
403 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
410 virtual void OnRawSocketConnect(int fd)
412 issl_session* session = &sessions[fd];
415 session->inbuf = new char[inbufsize];
416 session->inbufoffset = 0;
417 session->sess = SSL_new(clictx);
418 session->status = ISSL_NONE;
419 session->outbound = true;
421 if (session->sess == NULL)
424 if (SSL_set_fd(session->sess, fd) == 0)
426 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
433 virtual void OnRawSocketClose(int fd)
435 CloseSession(&sessions[fd]);
437 EventHandler* user = ServerInstance->SE->GetRef(fd);
439 if ((user) && (user->GetExt("ssl_cert", dummy)))
442 user->GetExt("ssl_cert", tofree);
444 user->Shrink("ssl_cert");
448 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
450 issl_session* session = &sessions[fd];
455 CloseSession(session);
459 if (session->status == ISSL_HANDSHAKING)
461 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
463 // The handshake isn't finished and it wants to read, try to finish it.
464 if (!Handshake(session))
466 // Couldn't resume handshake.
476 // If we resumed the handshake then session->status will be ISSL_OPEN
478 if (session->status == ISSL_OPEN)
480 if (session->wstat == ISSL_READ)
482 if(DoWrite(session) == 0)
486 if (session->rstat == ISSL_READ)
488 int ret = DoRead(session);
492 if (count <= session->inbufoffset)
494 memcpy(buffer, session->inbuf, count);
495 // Move the stuff left in inbuf to the beginning of it
496 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
497 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
498 session->inbufoffset -= count;
499 // Insp uses readresult as the count of how much data there is in buffer, so:
504 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
505 memcpy(buffer, session->inbuf, session->inbufoffset);
507 readresult = session->inbufoffset;
508 // Zero the offset, as there's nothing there..
509 session->inbufoffset = 0;
524 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
526 issl_session* session = &sessions[fd];
530 CloseSession(session);
534 session->outbuf.append(buffer, count);
536 if (session->status == ISSL_HANDSHAKING)
538 // The handshake isn't finished, try to finish it.
539 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
543 if (session->status == ISSL_OPEN)
545 if (session->rstat == ISSL_WRITE)
548 if (session->wstat == ISSL_WRITE)
549 return DoWrite(session);
555 int DoWrite(issl_session* session)
557 if (!session->outbuf.size())
560 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
564 CloseSession(session);
569 int err = SSL_get_error(session->sess, ret);
571 if (err == SSL_ERROR_WANT_WRITE)
573 session->wstat = ISSL_WRITE;
576 else if (err == SSL_ERROR_WANT_READ)
578 session->wstat = ISSL_READ;
583 CloseSession(session);
589 session->outbuf = session->outbuf.substr(ret);
594 int DoRead(issl_session* session)
596 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
597 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
599 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
603 // Client closed connection.
604 CloseSession(session);
609 int err = SSL_get_error(session->sess, ret);
611 if (err == SSL_ERROR_WANT_READ)
613 session->rstat = ISSL_READ;
616 else if (err == SSL_ERROR_WANT_WRITE)
618 session->rstat = ISSL_WRITE;
623 CloseSession(session);
629 // Read successfully 'ret' bytes into inbuf + inbufoffset
630 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
631 // 'buffer' is 'count' long
633 session->inbufoffset += ret;
639 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
640 virtual void OnWhois(userrec* source, userrec* dest)
645 // Bugfix, only send this numeric for *our* SSL users
646 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
648 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
652 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
654 // check if the linking module wants to know about OUR metadata
655 if (extname == "ssl")
657 // check if this user has an swhois field to send
658 if(user->GetExt(extname, dummy))
660 // call this function in the linking module, let it format the data how it
661 // sees fit, and send it on its way. We dont need or want to know how.
662 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
667 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
669 // check if its our metadata key, and its associated with a user
670 if ((target_type == TYPE_USER) && (extname == "ssl"))
672 userrec* dest = (userrec*)target;
673 // if they dont already have an ssl flag, accept the remote server's
674 if (!dest->GetExt(extname, dummy))
676 dest->Extend(extname, "ON");
681 bool Handshake(issl_session* session)
685 if (session->outbound)
686 ret = SSL_connect(session->sess);
688 ret = SSL_accept(session->sess);
692 int err = SSL_get_error(session->sess, ret);
694 if (err == SSL_ERROR_WANT_READ)
696 session->rstat = ISSL_READ;
697 session->status = ISSL_HANDSHAKING;
699 else if (err == SSL_ERROR_WANT_WRITE)
701 session->wstat = ISSL_WRITE;
702 session->status = ISSL_HANDSHAKING;
703 MakePollWrite(session);
707 CloseSession(session);
714 // Handshake complete.
715 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
716 userrec* u = ServerInstance->FindDescriptor(session->fd);
719 if (!u->GetExt("ssl", dummy))
720 u->Extend("ssl", "ON");
723 session->status = ISSL_OPEN;
725 MakePollWrite(session);
731 CloseSession(session);
738 virtual void OnPostConnect(userrec* user)
740 // This occurs AFTER OnUserConnect so we can be sure the
741 // protocol module has propogated the NICK message.
742 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
744 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
745 std::deque<std::string>* metadata = new std::deque<std::string>;
746 metadata->push_back(user->nick);
747 metadata->push_back("ssl"); // The metadata id
748 metadata->push_back("ON"); // The value to send
749 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
750 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
754 VerifyCertificate(&sessions[user->GetFd()], user);
755 if (sessions[user->GetFd()].sess)
756 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess));
760 void MakePollWrite(issl_session* session)
762 OnRawSocketWrite(session->fd, NULL, 0);
765 void CloseSession(issl_session* session)
769 SSL_shutdown(session->sess);
770 SSL_free(session->sess);
775 delete[] session->inbuf;
778 session->outbuf.clear();
779 session->inbuf = NULL;
780 session->sess = NULL;
781 session->status = ISSL_NONE;
784 void VerifyCertificate(issl_session* session, Extensible* user)
786 if (!session->sess || !user)
790 ssl_cert* certinfo = new ssl_cert;
792 unsigned char md[EVP_MAX_MD_SIZE];
793 const EVP_MD *digest = EVP_md5();
795 user->Extend("ssl_cert",certinfo);
797 cert = SSL_get_peer_certificate((SSL*)session->sess);
801 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
805 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
809 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
810 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
814 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
815 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
818 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
819 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
821 if (!X509_digest(cert, digest, md, &n))
823 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
827 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
830 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), time(NULL)) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), time(NULL)) == 0))
832 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
839 static int error_callback(const char *str, size_t len, void *u)
841 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
842 mssl->PublicInstance->Log(DEFAULT, "SSL error: " + std::string(str, len - 1));
846 class ModuleSSLOpenSSLFactory : public ModuleFactory
849 ModuleSSLOpenSSLFactory()
853 ~ModuleSSLOpenSSLFactory()
857 virtual Module * CreateModule(InspIRCd* Me)
859 return new ModuleSSLOpenSSL(Me);
864 extern "C" DllExport void * init_module( void )
866 return new ModuleSSLOpenSSLFactory;