1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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>
19 #include "configreader.h"
27 #include "transport.h"
30 #pragma comment(lib, "libeay32MTd")
31 #pragma comment(lib, "ssleay32MTd")
32 #undef MAX_DESCRIPTORS
33 #define MAX_DESCRIPTORS 10000
36 /* $ModDesc: Provides SSL support for clients */
37 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
38 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
39 /* $ModDep: transport.h */
41 /* $CopyInstall: conf/key.pem $(CONPATH) */
42 /* $CopyInstall: conf/cert.pem $(CONPATH) */
44 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
45 enum issl_io_status { ISSL_WRITE, ISSL_READ };
47 static bool SelfSigned = false;
49 bool isin(const std::string &hostandport, const std::vector<std::string> &portlist)
51 return std::find(portlist.begin(), portlist.end(), hostandport) != portlist.end();
56 return ERR_error_string(ERR_get_error(), NULL);
59 static int error_callback(const char *str, size_t len, void *u);
61 /** Represents an SSL user's extra data
63 class issl_session : public classbase
71 unsigned int inbufoffset;
72 char* inbuf; // Buffer OpenSSL reads into.
73 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
85 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
87 /* XXX: This will allow self signed certificates.
88 * In the future if we want an option to not allow this,
89 * we can just return preverify_ok here, and openssl
90 * will boot off self-signed and invalid peer certs.
92 int ve = X509_STORE_CTX_get_error(ctx);
94 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
99 class ModuleSSLOpenSSL : public Module
101 std::vector<std::string> listenports;
104 issl_session sessions[MAX_DESCRIPTORS];
113 std::string certfile;
115 // std::string crlfile;
117 std::string sslports;
123 InspIRCd* PublicInstance;
125 ModuleSSLOpenSSL(InspIRCd* Me)
126 : Module(Me), PublicInstance(Me)
128 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
130 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
131 inbufsize = ServerInstance->Config->NetBufferSize;
133 /* Global SSL library initialization*/
135 SSL_load_error_strings();
137 /* Build our SSL contexts:
138 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
140 ctx = SSL_CTX_new( SSLv23_server_method() );
141 clictx = SSL_CTX_new( SSLv23_client_method() );
143 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
144 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
146 // Needs the flag as it ignores a plain /rehash
147 OnRehash(NULL,"ssl");
148 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup, I_On005Numeric,
149 I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect, I_OnHookUserIO };
150 ServerInstance->Modules->Attach(eventlist, this, 16);
153 virtual void OnHookUserIO(User* user, const std::string &targetip)
155 if (!user->io && isin(targetip + ":" + ConvToStr(user->GetPort()), listenports))
157 /* Hook the user with our module */
162 virtual void OnRehash(User* user, const std::string ¶m)
164 ConfigReader Conf(ServerInstance);
170 for(int index = 0; index < Conf.Enumerate("bind"); index++)
172 // For each <bind> tag
173 std::string x = Conf.ReadValue("bind", "type", index);
174 if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "openssl"))
176 // Get the port we're meant to be listening on with SSL
177 std::string port = Conf.ReadValue("bind", "port", index);
178 std::string addr = Conf.ReadValue("bind", "address", index);
180 irc::portparser portrange(port, false);
182 while ((portno = portrange.GetToken()))
187 listenports.push_back(addr + ":" + ConvToStr(portno));
189 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
190 if ((ServerInstance->Config->ports[i]->GetPort() == portno) && (ServerInstance->Config->ports[i]->GetIP() == addr))
191 ServerInstance->Config->ports[i]->SetDescription("ssl");
192 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", portno);
194 sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
196 catch (ModuleException &e)
198 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.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 an other SSL or similar module loaded?", portno, e.GetReason());
204 if (!sslports.empty())
205 sslports.erase(sslports.end() - 1);
212 std::string confdir(ServerInstance->ConfigFileName);
213 // +1 so we the path ends with a /
214 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
216 cafile = Conf.ReadValue("openssl", "cafile", 0);
217 certfile = Conf.ReadValue("openssl", "certfile", 0);
218 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
219 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
221 // Set all the default values needed.
225 if (certfile.empty())
226 certfile = "cert.pem";
232 dhfile = "dhparams.pem";
234 // Prepend relative paths with the path to the config directory.
235 if (cafile[0] != '/')
236 cafile = confdir + cafile;
238 if (certfile[0] != '/')
239 certfile = confdir + certfile;
241 if (keyfile[0] != '/')
242 keyfile = confdir + keyfile;
244 if (dhfile[0] != '/')
245 dhfile = confdir + dhfile;
247 /* Load our keys and certificates
248 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
250 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
252 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
253 ERR_print_errors_cb(error_callback, this);
256 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)))
258 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
259 ERR_print_errors_cb(error_callback, this);
262 /* Load the CAs we trust*/
263 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
265 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
266 ERR_print_errors_cb(error_callback, this);
269 FILE* dhpfile = fopen(dhfile.c_str(), "r");
274 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
275 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
279 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
280 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
282 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
283 ERR_print_errors_cb(error_callback, this);
290 virtual void On005Numeric(std::string &output)
292 output.append(" SSL=" + sslports);
295 virtual ~ModuleSSLOpenSSL()
298 SSL_CTX_free(clictx);
301 virtual void OnCleanup(int target_type, void* item)
303 if (target_type == TYPE_USER)
305 User* user = (User*)item;
307 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && user->io == this)
309 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
310 // Potentially there could be multiple SSL modules loaded at once on different ports.
311 User::QuitUser(ServerInstance, user, "SSL module unloading");
313 if (user->GetExt("ssl_cert", dummy))
316 user->GetExt("ssl_cert", tofree);
318 user->Shrink("ssl_cert");
325 virtual void OnUnloadModule(Module* mod, const std::string &name)
329 for(unsigned int i = 0; i < listenports.size(); i++)
331 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
332 if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
333 ServerInstance->Config->ports[j]->SetDescription("plaintext");
338 virtual Version GetVersion()
340 return Version(1, 2, 0, 0, VF_VENDOR, API_VERSION);
344 virtual const char* OnRequest(Request* request)
346 ISHRequest* ISR = (ISHRequest*)request;
347 if (strcmp("IS_NAME", request->GetId()) == 0)
351 else if (strcmp("IS_HOOK", request->GetId()) == 0)
353 const char* ret = "OK";
356 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? "OK" : NULL;
358 catch (ModuleException &e)
365 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
367 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? "OK" : NULL;
369 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
371 if (ISR->Sock->GetFd() < 0)
374 issl_session* session = &sessions[ISR->Sock->GetFd()];
375 return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
377 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
379 issl_session* session = &sessions[ISR->Sock->GetFd()];
382 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
390 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
392 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
393 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
396 issl_session* session = &sessions[fd];
399 session->inbuf = new char[inbufsize];
400 session->inbufoffset = 0;
401 session->sess = SSL_new(ctx);
402 session->status = ISSL_NONE;
403 session->outbound = false;
405 if (session->sess == NULL)
408 if (SSL_set_fd(session->sess, fd) == 0)
410 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
417 virtual void OnRawSocketConnect(int fd)
419 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
420 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
423 issl_session* session = &sessions[fd];
426 session->inbuf = new char[inbufsize];
427 session->inbufoffset = 0;
428 session->sess = SSL_new(clictx);
429 session->status = ISSL_NONE;
430 session->outbound = true;
432 if (session->sess == NULL)
435 if (SSL_set_fd(session->sess, fd) == 0)
437 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
444 virtual void OnRawSocketClose(int fd)
446 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
447 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
450 CloseSession(&sessions[fd]);
452 EventHandler* user = ServerInstance->SE->GetRef(fd);
454 if ((user) && (user->GetExt("ssl_cert", dummy)))
457 user->GetExt("ssl_cert", tofree);
459 user->Shrink("ssl_cert");
463 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
465 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
466 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
469 issl_session* session = &sessions[fd];
474 CloseSession(session);
478 if (session->status == ISSL_HANDSHAKING)
480 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
482 // The handshake isn't finished and it wants to read, try to finish it.
483 if (!Handshake(session))
485 // Couldn't resume handshake.
496 // If we resumed the handshake then session->status will be ISSL_OPEN
498 if (session->status == ISSL_OPEN)
500 if (session->wstat == ISSL_READ)
502 if(DoWrite(session) == 0)
506 if (session->rstat == ISSL_READ)
508 int ret = DoRead(session);
512 if (count <= session->inbufoffset)
514 memcpy(buffer, session->inbuf, count);
515 // Move the stuff left in inbuf to the beginning of it
516 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
517 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
518 session->inbufoffset -= count;
519 // Insp uses readresult as the count of how much data there is in buffer, so:
524 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
525 memcpy(buffer, session->inbuf, session->inbufoffset);
527 readresult = session->inbufoffset;
528 // Zero the offset, as there's nothing there..
529 session->inbufoffset = 0;
540 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
542 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
543 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
546 issl_session* session = &sessions[fd];
550 CloseSession(session);
554 session->outbuf.append(buffer, count);
555 MakePollWrite(session);
557 if (session->status == ISSL_HANDSHAKING)
559 // The handshake isn't finished, try to finish it.
560 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
566 if (session->status == ISSL_OPEN)
568 if (session->rstat == ISSL_WRITE)
573 if (session->wstat == ISSL_WRITE)
575 return DoWrite(session);
582 int DoWrite(issl_session* session)
584 if (!session->outbuf.size())
587 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
591 CloseSession(session);
596 int err = SSL_get_error(session->sess, ret);
598 if (err == SSL_ERROR_WANT_WRITE)
600 session->wstat = ISSL_WRITE;
603 else if (err == SSL_ERROR_WANT_READ)
605 session->wstat = ISSL_READ;
610 CloseSession(session);
616 session->outbuf = session->outbuf.substr(ret);
621 int DoRead(issl_session* session)
623 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
624 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
626 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
630 // Client closed connection.
631 CloseSession(session);
636 int err = SSL_get_error(session->sess, ret);
638 if (err == SSL_ERROR_WANT_READ)
640 session->rstat = ISSL_READ;
643 else if (err == SSL_ERROR_WANT_WRITE)
645 session->rstat = ISSL_WRITE;
646 MakePollWrite(session);
651 CloseSession(session);
657 // Read successfully 'ret' bytes into inbuf + inbufoffset
658 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
659 // 'buffer' is 'count' long
661 session->inbufoffset += ret;
667 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
668 virtual void OnWhois(User* source, User* dest)
673 // Bugfix, only send this numeric for *our* SSL users
674 if (dest->GetExt("ssl", dummy) || ((IS_LOCAL(dest) && dest->io == this)))
676 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
680 virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
682 // check if the linking module wants to know about OUR metadata
683 if (extname == "ssl")
685 // check if this user has an swhois field to send
686 if(user->GetExt(extname, dummy))
688 // call this function in the linking module, let it format the data how it
689 // sees fit, and send it on its way. We dont need or want to know how.
690 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
695 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
697 // check if its our metadata key, and its associated with a user
698 if ((target_type == TYPE_USER) && (extname == "ssl"))
700 User* dest = (User*)target;
701 // if they dont already have an ssl flag, accept the remote server's
702 if (!dest->GetExt(extname, dummy))
704 dest->Extend(extname, "ON");
709 bool Handshake(issl_session* session)
713 if (session->outbound)
714 ret = SSL_connect(session->sess);
716 ret = SSL_accept(session->sess);
720 int err = SSL_get_error(session->sess, ret);
722 if (err == SSL_ERROR_WANT_READ)
724 session->rstat = ISSL_READ;
725 session->status = ISSL_HANDSHAKING;
728 else if (err == SSL_ERROR_WANT_WRITE)
730 session->wstat = ISSL_WRITE;
731 session->status = ISSL_HANDSHAKING;
732 MakePollWrite(session);
737 CloseSession(session);
744 // Handshake complete.
745 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
746 User* u = ServerInstance->FindDescriptor(session->fd);
749 if (!u->GetExt("ssl", dummy))
750 u->Extend("ssl", "ON");
753 session->status = ISSL_OPEN;
755 MakePollWrite(session);
761 CloseSession(session);
768 virtual void OnPostConnect(User* user)
770 // This occurs AFTER OnUserConnect so we can be sure the
771 // protocol module has propagated the NICK message.
772 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
774 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
775 std::deque<std::string>* metadata = new std::deque<std::string>;
776 metadata->push_back(user->nick);
777 metadata->push_back("ssl"); // The metadata id
778 metadata->push_back("ON"); // The value to send
779 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
780 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
784 VerifyCertificate(&sessions[user->GetFd()], user);
785 if (sessions[user->GetFd()].sess)
786 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess));
790 void MakePollWrite(issl_session* session)
792 //OnRawSocketWrite(session->fd, NULL, 0);
793 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
796 ServerInstance->SE->WantWrite(eh);
800 virtual void OnBufferFlushed(User* user)
802 if (user->GetExt("ssl"))
804 issl_session* session = &sessions[user->GetFd()];
805 if (session && session->outbuf.size())
806 OnRawSocketWrite(user->GetFd(), NULL, 0);
810 void CloseSession(issl_session* session)
814 SSL_shutdown(session->sess);
815 SSL_free(session->sess);
820 delete[] session->inbuf;
823 session->outbuf.clear();
824 session->inbuf = NULL;
825 session->sess = NULL;
826 session->status = ISSL_NONE;
829 void VerifyCertificate(issl_session* session, Extensible* user)
831 if (!session->sess || !user)
835 ssl_cert* certinfo = new ssl_cert;
837 unsigned char md[EVP_MAX_MD_SIZE];
838 const EVP_MD *digest = EVP_md5();
840 user->Extend("ssl_cert",certinfo);
842 cert = SSL_get_peer_certificate((SSL*)session->sess);
846 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
850 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
854 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
855 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
859 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
860 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
863 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
864 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
866 if (!X509_digest(cert, digest, md, &n))
868 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
872 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
875 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))
877 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
884 static int error_callback(const char *str, size_t len, void *u)
886 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
887 mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
891 MODULE_INIT(ModuleSSLOpenSSL)