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(int port, const std::vector<int> &portlist)
51 for(unsigned int i = 0; i < portlist.size(); i++)
52 if(portlist[i] == port)
60 return ERR_error_string(ERR_get_error(), NULL);
63 static int error_callback(const char *str, size_t len, void *u);
65 /** Represents an SSL user's extra data
67 class issl_session : public classbase
75 unsigned int inbufoffset;
76 char* inbuf; // Buffer OpenSSL reads into.
77 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
89 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
91 /* XXX: This will allow self signed certificates.
92 * In the future if we want an option to not allow this,
93 * we can just return preverify_ok here, and openssl
94 * will boot off self-signed and invalid peer certs.
96 int ve = X509_STORE_CTX_get_error(ctx);
98 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
103 class ModuleSSLOpenSSL : public Module
105 std::vector<int> listenports;
108 issl_session sessions[MAX_DESCRIPTORS];
117 std::string certfile;
119 // std::string crlfile;
121 std::string sslports;
127 InspIRCd* PublicInstance;
129 ModuleSSLOpenSSL(InspIRCd* Me)
130 : Module(Me), PublicInstance(Me)
132 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
134 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
135 inbufsize = ServerInstance->Config->NetBufferSize;
137 /* Global SSL library initialization*/
139 SSL_load_error_strings();
141 /* Build our SSL contexts:
142 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
144 ctx = SSL_CTX_new( SSLv23_server_method() );
145 clictx = SSL_CTX_new( SSLv23_client_method() );
147 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
148 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
150 // Needs the flag as it ignores a plain /rehash
151 OnRehash(NULL,"ssl");
152 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup, I_On005Numeric,
153 I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect };
154 ServerInstance->Modules->Attach(eventlist, this, 15);
157 virtual void OnRehash(User* user, const std::string ¶m)
162 ConfigReader Conf(ServerInstance);
164 for (unsigned int i = 0; i < listenports.size(); i++)
166 ServerInstance->Config->DelIOHook(listenports[i]);
173 for (int i = 0; i < Conf.Enumerate("bind"); i++)
175 // For each <bind> tag
176 std::string x = Conf.ReadValue("bind", "type", i);
177 if (((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", i) == "openssl"))
179 // Get the port we're meant to be listening on with SSL
180 std::string port = Conf.ReadValue("bind", "port", i);
181 irc::portparser portrange(port, false);
183 while ((portno = portrange.GetToken()))
188 if (ServerInstance->Config->AddIOHook(portno, this))
190 listenports.push_back(portno);
191 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
192 if (ServerInstance->Config->ports[i]->GetPort() == portno)
193 ServerInstance->Config->ports[i]->SetDescription("ssl");
194 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
195 sslports.append("*:").append(ConvToStr(portno)).append(";");
199 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
202 catch (ModuleException &e)
204 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());
210 if (!sslports.empty())
211 sslports.erase(sslports.end() - 1);
213 std::string confdir(ServerInstance->ConfigFileName);
214 // +1 so we the path ends with a /
215 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
217 cafile = Conf.ReadValue("openssl", "cafile", 0);
218 certfile = Conf.ReadValue("openssl", "certfile", 0);
219 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
220 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
222 // Set all the default values needed.
226 if (certfile.empty())
227 certfile = "cert.pem";
233 dhfile = "dhparams.pem";
235 // Prepend relative paths with the path to the config directory.
236 if (cafile[0] != '/')
237 cafile = confdir + cafile;
239 if (certfile[0] != '/')
240 certfile = confdir + certfile;
242 if (keyfile[0] != '/')
243 keyfile = confdir + keyfile;
245 if (dhfile[0] != '/')
246 dhfile = confdir + dhfile;
248 /* Load our keys and certificates
249 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
251 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
253 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
254 ERR_print_errors_cb(error_callback, this);
257 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)))
259 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
260 ERR_print_errors_cb(error_callback, this);
263 /* Load the CAs we trust*/
264 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
266 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
267 ERR_print_errors_cb(error_callback, this);
270 FILE* dhpfile = fopen(dhfile.c_str(), "r");
275 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
276 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
280 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
281 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
283 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
284 ERR_print_errors_cb(error_callback, this);
291 virtual void On005Numeric(std::string &output)
293 output.append(" SSL=" + sslports);
296 virtual ~ModuleSSLOpenSSL()
299 SSL_CTX_free(clictx);
302 virtual void OnCleanup(int target_type, void* item)
304 if (target_type == TYPE_USER)
306 User* user = (User*)item;
308 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
310 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
311 // Potentially there could be multiple SSL modules loaded at once on different ports.
312 User::QuitUser(ServerInstance, user, "SSL module unloading");
314 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
317 user->GetExt("ssl_cert", tofree);
319 user->Shrink("ssl_cert");
324 virtual void OnUnloadModule(Module* mod, const std::string &name)
328 for(unsigned int i = 0; i < listenports.size(); i++)
330 ServerInstance->Config->DelIOHook(listenports[i]);
331 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
332 if (ServerInstance->Config->ports[j]->GetPort() == listenports[i])
333 ServerInstance->Config->ports[j]->SetDescription("plaintext");
338 virtual Version GetVersion()
340 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
344 virtual 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)
356 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
358 catch (ModuleException &e)
365 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
367 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? (char*)"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 : (char*)"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->Log(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->Log(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) && isin(dest->GetPort(), listenports)))
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->Log(DEFAULT, "SSL error: " + std::string(str, len - 1));
891 MODULE_INIT(ModuleSSLOpenSSL)