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 * ---------------------------------------------------
17 #include <openssl/ssl.h>
18 #include <openssl/err.h>
20 #include "inspircd_config.h"
21 #include "configreader.h"
30 #include "transport.h"
32 /* $ModDesc: Provides SSL support for clients */
33 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
34 /* $LinkerFlags: pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */
35 /* $ModDep: transport.h */
37 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
38 enum issl_io_status { ISSL_WRITE, ISSL_READ };
40 static bool SelfSigned = false;
42 bool isin(int port, const std::vector<int> &portlist)
44 for(unsigned int i = 0; i < portlist.size(); i++)
45 if(portlist[i] == port)
53 return ERR_error_string(ERR_get_error(), NULL);
56 static int error_callback(const char *str, size_t len, void *u);
58 /** Represents an SSL user's extra data
60 class issl_session : public classbase
68 unsigned int inbufoffset;
69 char* inbuf; // Buffer OpenSSL reads into.
70 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
82 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
84 /* XXX: This will allow self signed certificates.
85 * In the future if we want an option to not allow this,
86 * we can just return preverify_ok here, and openssl
87 * will boot off self-signed and invalid peer certs.
89 int ve = X509_STORE_CTX_get_error(ctx);
91 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
96 class ModuleSSLOpenSSL : public Module
103 std::vector<int> listenports;
106 issl_session sessions[MAX_DESCRIPTORS];
114 std::string certfile;
116 // std::string crlfile;
121 InspIRCd* PublicInstance;
123 ModuleSSLOpenSSL(InspIRCd* Me)
124 : Module::Module(Me), PublicInstance(Me)
126 culllist = new CullList(ServerInstance);
128 ServerInstance->PublishInterface("InspSocketHook", 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");
150 virtual void OnRehash(userrec* user, const std::string ¶m)
155 Conf = new ConfigReader(ServerInstance);
157 for (unsigned int i = 0; i < listenports.size(); i++)
159 ServerInstance->Config->DelIOHook(listenports[i]);
164 for (int i = 0; i < Conf->Enumerate("bind"); i++)
166 // For each <bind> tag
167 if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
169 // Get the port we're meant to be listening on with SSL
170 std::string port = Conf->ReadValue("bind", "port", i);
171 irc::portparser portrange(port, false);
173 while ((portno = portrange.GetToken()))
175 if (ServerInstance->Config->AddIOHook(portno, this))
177 listenports.push_back(portno);
178 for (unsigned int i = 0; i < ServerInstance->stats->BoundPortCount; i++)
179 if (ServerInstance->Config->ports[i] == portno)
180 ServerInstance->Config->openSockfd[i]->SetDescription("ssl");
181 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
185 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
191 std::string confdir(CONFIG_FILE);
192 // +1 so we the path ends with a /
193 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
195 cafile = Conf->ReadValue("openssl", "cafile", 0);
196 certfile = Conf->ReadValue("openssl", "certfile", 0);
197 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
198 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
200 // Set all the default values needed.
205 certfile = "cert.pem";
211 dhfile = "dhparams.pem";
213 // Prepend relative paths with the path to the config directory.
214 if (cafile[0] != '/')
215 cafile = confdir + cafile;
217 //if(crlfile[0] != '/')
218 // crlfile = confdir + crlfile;
220 if (certfile[0] != '/')
221 certfile = confdir + certfile;
223 if (keyfile[0] != '/')
224 keyfile = confdir + keyfile;
226 if (dhfile[0] != '/')
227 dhfile = confdir + dhfile;
229 /* Load our keys and certificates
230 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
232 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
234 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
235 ERR_print_errors_cb(error_callback, this);
238 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)))
240 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
241 ERR_print_errors_cb(error_callback, this);
244 /* Load the CAs we trust*/
245 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
247 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
248 ERR_print_errors_cb(error_callback, this);
251 FILE* dhpfile = fopen(dhfile.c_str(), "r");
256 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
257 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
261 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
262 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
264 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
265 ERR_print_errors_cb(error_callback, this);
274 virtual ~ModuleSSLOpenSSL()
277 SSL_CTX_free(clictx);
281 virtual void OnCleanup(int target_type, void* item)
283 if (target_type == TYPE_USER)
285 userrec* user = (userrec*)item;
287 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
289 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
290 // Potentially there could be multiple SSL modules loaded at once on different ports.
291 culllist->AddItem(user, "SSL module unloading");
293 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
296 user->GetExt("ssl_cert", tofree);
298 user->Shrink("ssl_cert");
303 virtual void OnUnloadModule(Module* mod, const std::string &name)
307 // We're being unloaded, kill all the users added to the cull list in OnCleanup
310 for(unsigned int i = 0; i < listenports.size(); i++)
312 ServerInstance->Config->DelIOHook(listenports[i]);
313 for (unsigned int j = 0; j < ServerInstance->stats->BoundPortCount; j++)
314 if (ServerInstance->Config->ports[j] == listenports[i])
315 if (ServerInstance->Config->openSockfd[j])
316 ServerInstance->Config->openSockfd[j]->SetDescription("plaintext");
321 virtual Version GetVersion()
323 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
326 void Implements(char* List)
328 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
329 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
332 virtual char* OnRequest(Request* request)
334 ISHRequest* ISR = (ISHRequest*)request;
335 if (strcmp("IS_NAME", request->GetId()) == 0)
339 else if (strcmp("IS_HOOK", request->GetId()) == 0)
344 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
346 catch (ModuleException &e)
353 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
355 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
357 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
359 issl_session* session = &sessions[ISR->Sock->GetFd()];
360 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
362 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
364 issl_session* session = &sessions[ISR->Sock->GetFd()];
367 VerifyCertificate(session, (InspSocket*)ISR->Sock);
375 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
377 issl_session* session = &sessions[fd];
380 session->inbuf = new char[inbufsize];
381 session->inbufoffset = 0;
382 session->sess = SSL_new(ctx);
383 session->status = ISSL_NONE;
384 session->outbound = false;
386 if (session->sess == NULL)
389 if (SSL_set_fd(session->sess, fd) == 0)
391 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
398 virtual void OnRawSocketConnect(int fd)
400 issl_session* session = &sessions[fd];
403 session->inbuf = new char[inbufsize];
404 session->inbufoffset = 0;
405 session->sess = SSL_new(clictx);
406 session->status = ISSL_NONE;
407 session->outbound = true;
409 if (session->sess == NULL)
412 if (SSL_set_fd(session->sess, fd) == 0)
414 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
421 virtual void OnRawSocketClose(int fd)
423 CloseSession(&sessions[fd]);
425 EventHandler* user = ServerInstance->SE->GetRef(fd);
427 if ((user) && (user->GetExt("ssl_cert", dummy)))
430 user->GetExt("ssl_cert", tofree);
432 user->Shrink("ssl_cert");
436 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
438 issl_session* session = &sessions[fd];
443 CloseSession(session);
447 if (session->status == ISSL_HANDSHAKING)
449 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
451 // The handshake isn't finished and it wants to read, try to finish it.
452 if (!Handshake(session))
454 // Couldn't resume handshake.
464 // If we resumed the handshake then session->status will be ISSL_OPEN
466 if (session->status == ISSL_OPEN)
468 if (session->wstat == ISSL_READ)
470 if(DoWrite(session) == 0)
474 if (session->rstat == ISSL_READ)
476 int ret = DoRead(session);
480 if (count <= session->inbufoffset)
482 memcpy(buffer, session->inbuf, count);
483 // Move the stuff left in inbuf to the beginning of it
484 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
485 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
486 session->inbufoffset -= count;
487 // Insp uses readresult as the count of how much data there is in buffer, so:
492 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
493 memcpy(buffer, session->inbuf, session->inbufoffset);
495 readresult = session->inbufoffset;
496 // Zero the offset, as there's nothing there..
497 session->inbufoffset = 0;
512 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
514 issl_session* session = &sessions[fd];
518 CloseSession(session);
522 session->outbuf.append(buffer, count);
524 if (session->status == ISSL_HANDSHAKING)
526 // The handshake isn't finished, try to finish it.
527 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
531 if (session->status == ISSL_OPEN)
533 if (session->rstat == ISSL_WRITE)
536 if (session->wstat == ISSL_WRITE)
537 return DoWrite(session);
543 int DoWrite(issl_session* session)
545 if (!session->outbuf.size())
548 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
552 CloseSession(session);
557 int err = SSL_get_error(session->sess, ret);
559 if (err == SSL_ERROR_WANT_WRITE)
561 session->wstat = ISSL_WRITE;
564 else if (err == SSL_ERROR_WANT_READ)
566 session->wstat = ISSL_READ;
571 CloseSession(session);
577 session->outbuf = session->outbuf.substr(ret);
582 int DoRead(issl_session* session)
584 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
585 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
587 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
591 // Client closed connection.
592 CloseSession(session);
597 int err = SSL_get_error(session->sess, ret);
599 if (err == SSL_ERROR_WANT_READ)
601 session->rstat = ISSL_READ;
604 else if (err == SSL_ERROR_WANT_WRITE)
606 session->rstat = ISSL_WRITE;
611 CloseSession(session);
617 // Read successfully 'ret' bytes into inbuf + inbufoffset
618 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
619 // 'buffer' is 'count' long
621 session->inbufoffset += ret;
627 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
628 virtual void OnWhois(userrec* source, userrec* dest)
630 // Bugfix, only send this numeric for *our* SSL users
631 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
633 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
637 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
639 // check if the linking module wants to know about OUR metadata
640 if (extname == "ssl")
642 // check if this user has an swhois field to send
643 if(user->GetExt(extname, dummy))
645 // call this function in the linking module, let it format the data how it
646 // sees fit, and send it on its way. We dont need or want to know how.
647 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
652 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
654 // check if its our metadata key, and its associated with a user
655 if ((target_type == TYPE_USER) && (extname == "ssl"))
657 userrec* dest = (userrec*)target;
658 // if they dont already have an ssl flag, accept the remote server's
659 if (!dest->GetExt(extname, dummy))
661 dest->Extend(extname, "ON");
666 bool Handshake(issl_session* session)
670 if (session->outbound)
671 ret = SSL_connect(session->sess);
673 ret = SSL_accept(session->sess);
677 int err = SSL_get_error(session->sess, ret);
679 if (err == SSL_ERROR_WANT_READ)
681 session->rstat = ISSL_READ;
682 session->status = ISSL_HANDSHAKING;
684 else if (err == SSL_ERROR_WANT_WRITE)
686 session->wstat = ISSL_WRITE;
687 session->status = ISSL_HANDSHAKING;
688 MakePollWrite(session);
692 CloseSession(session);
699 // Handshake complete.
700 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
701 userrec* u = ServerInstance->FindDescriptor(session->fd);
704 if (!u->GetExt("ssl", dummy))
705 u->Extend("ssl", "ON");
708 session->status = ISSL_OPEN;
710 MakePollWrite(session);
716 CloseSession(session);
723 virtual void OnPostConnect(userrec* user)
725 // This occurs AFTER OnUserConnect so we can be sure the
726 // protocol module has propogated the NICK message.
727 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
729 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
730 std::deque<std::string>* metadata = new std::deque<std::string>;
731 metadata->push_back(user->nick);
732 metadata->push_back("ssl"); // The metadata id
733 metadata->push_back("ON"); // The value to send
734 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
735 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
739 VerifyCertificate(&sessions[user->GetFd()], user);
743 void MakePollWrite(issl_session* session)
745 OnRawSocketWrite(session->fd, NULL, 0);
748 void CloseSession(issl_session* session)
752 SSL_shutdown(session->sess);
753 SSL_free(session->sess);
758 delete[] session->inbuf;
761 session->outbuf.clear();
762 session->inbuf = NULL;
763 session->sess = NULL;
764 session->status = ISSL_NONE;
767 void VerifyCertificate(issl_session* session, Extensible* user)
770 ssl_cert* certinfo = new ssl_cert;
772 unsigned char md[EVP_MAX_MD_SIZE];
773 const EVP_MD *digest = EVP_md5();
775 user->Extend("ssl_cert",certinfo);
777 cert = SSL_get_peer_certificate((SSL*)session->sess);
781 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
785 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
789 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
790 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
794 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
795 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
798 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
799 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
801 if (!X509_digest(cert, digest, md, &n))
803 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
807 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
810 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))
812 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
819 static int error_callback(const char *str, size_t len, void *u)
821 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
822 mssl->PublicInstance->Log(DEFAULT, "SSL error: " + std::string(str, len - 1));
826 class ModuleSSLOpenSSLFactory : public ModuleFactory
829 ModuleSSLOpenSSLFactory()
833 ~ModuleSSLOpenSSLFactory()
837 virtual Module * CreateModule(InspIRCd* Me)
839 return new ModuleSSLOpenSSL(Me);
844 extern "C" void * init_module( void )
846 return new ModuleSSLOpenSSLFactory;