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: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
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
101 std::vector<int> listenports;
104 issl_session sessions[MAX_DESCRIPTORS];
112 std::string certfile;
114 // std::string crlfile;
119 InspIRCd* PublicInstance;
121 ModuleSSLOpenSSL(InspIRCd* Me)
122 : Module::Module(Me), PublicInstance(Me)
124 ServerInstance->PublishInterface("InspSocketHook", this);
126 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
127 inbufsize = ServerInstance->Config->NetBufferSize;
129 /* Global SSL library initialization*/
131 SSL_load_error_strings();
133 /* Build our SSL contexts:
134 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
136 ctx = SSL_CTX_new( SSLv23_server_method() );
137 clictx = SSL_CTX_new( SSLv23_client_method() );
139 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
140 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
142 // Needs the flag as it ignores a plain /rehash
143 OnRehash(NULL,"ssl");
146 virtual void OnRehash(userrec* user, const std::string ¶m)
151 Conf = new ConfigReader(ServerInstance);
153 for (unsigned int i = 0; i < listenports.size(); i++)
155 ServerInstance->Config->DelIOHook(listenports[i]);
160 for (int i = 0; i < Conf->Enumerate("bind"); i++)
162 // For each <bind> tag
163 if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
165 // Get the port we're meant to be listening on with SSL
166 std::string port = Conf->ReadValue("bind", "port", i);
167 irc::portparser portrange(port, false);
169 while ((portno = portrange.GetToken()))
173 if (ServerInstance->Config->AddIOHook(portno, this))
175 listenports.push_back(portno);
176 for (unsigned int i = 0; i < ServerInstance->stats->BoundPortCount; i++)
177 if (ServerInstance->Config->ports[i] == portno)
178 ServerInstance->Config->openSockfd[i]->SetDescription("ssl");
179 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
183 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
186 catch (ModuleException &e)
188 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());
194 std::string confdir(CONFIG_FILE);
195 // +1 so we the path ends with a /
196 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
198 cafile = Conf->ReadValue("openssl", "cafile", 0);
199 certfile = Conf->ReadValue("openssl", "certfile", 0);
200 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
201 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
203 // Set all the default values needed.
208 certfile = "cert.pem";
214 dhfile = "dhparams.pem";
216 // Prepend relative paths with the path to the config directory.
217 if (cafile[0] != '/')
218 cafile = confdir + cafile;
220 //if(crlfile[0] != '/')
221 // crlfile = confdir + crlfile;
223 if (certfile[0] != '/')
224 certfile = confdir + certfile;
226 if (keyfile[0] != '/')
227 keyfile = confdir + keyfile;
229 if (dhfile[0] != '/')
230 dhfile = confdir + dhfile;
232 /* Load our keys and certificates
233 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
235 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
237 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
238 ERR_print_errors_cb(error_callback, this);
241 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)))
243 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
244 ERR_print_errors_cb(error_callback, this);
247 /* Load the CAs we trust*/
248 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
250 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
251 ERR_print_errors_cb(error_callback, this);
254 FILE* dhpfile = fopen(dhfile.c_str(), "r");
259 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
260 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
264 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
265 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
267 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
268 ERR_print_errors_cb(error_callback, this);
277 virtual ~ModuleSSLOpenSSL()
280 SSL_CTX_free(clictx);
283 virtual void OnCleanup(int target_type, void* item)
285 if (target_type == TYPE_USER)
287 userrec* user = (userrec*)item;
289 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
291 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
292 // Potentially there could be multiple SSL modules loaded at once on different ports.
293 ServerInstance->GlobalCulls.AddItem(user, "SSL module unloading");
295 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
298 user->GetExt("ssl_cert", tofree);
300 user->Shrink("ssl_cert");
305 virtual void OnUnloadModule(Module* mod, const std::string &name)
309 for(unsigned int i = 0; i < listenports.size(); i++)
311 ServerInstance->Config->DelIOHook(listenports[i]);
312 for (unsigned int j = 0; j < ServerInstance->stats->BoundPortCount; j++)
313 if (ServerInstance->Config->ports[j] == listenports[i])
314 if (ServerInstance->Config->openSockfd[j])
315 ServerInstance->Config->openSockfd[j]->SetDescription("plaintext");
320 virtual Version GetVersion()
322 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
325 void Implements(char* List)
327 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
328 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
331 virtual char* OnRequest(Request* request)
333 ISHRequest* ISR = (ISHRequest*)request;
334 if (strcmp("IS_NAME", request->GetId()) == 0)
338 else if (strcmp("IS_HOOK", request->GetId()) == 0)
343 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
345 catch (ModuleException &e)
352 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
354 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
356 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
358 issl_session* session = &sessions[ISR->Sock->GetFd()];
359 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
361 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
363 issl_session* session = &sessions[ISR->Sock->GetFd()];
366 VerifyCertificate(session, (InspSocket*)ISR->Sock);
374 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
376 issl_session* session = &sessions[fd];
379 session->inbuf = new char[inbufsize];
380 session->inbufoffset = 0;
381 session->sess = SSL_new(ctx);
382 session->status = ISSL_NONE;
383 session->outbound = false;
385 if (session->sess == NULL)
388 if (SSL_set_fd(session->sess, fd) == 0)
390 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
397 virtual void OnRawSocketConnect(int fd)
399 issl_session* session = &sessions[fd];
402 session->inbuf = new char[inbufsize];
403 session->inbufoffset = 0;
404 session->sess = SSL_new(clictx);
405 session->status = ISSL_NONE;
406 session->outbound = true;
408 if (session->sess == NULL)
411 if (SSL_set_fd(session->sess, fd) == 0)
413 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
420 virtual void OnRawSocketClose(int fd)
422 CloseSession(&sessions[fd]);
424 EventHandler* user = ServerInstance->SE->GetRef(fd);
426 if ((user) && (user->GetExt("ssl_cert", dummy)))
429 user->GetExt("ssl_cert", tofree);
431 user->Shrink("ssl_cert");
435 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
437 issl_session* session = &sessions[fd];
442 CloseSession(session);
446 if (session->status == ISSL_HANDSHAKING)
448 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
450 // The handshake isn't finished and it wants to read, try to finish it.
451 if (!Handshake(session))
453 // Couldn't resume handshake.
463 // If we resumed the handshake then session->status will be ISSL_OPEN
465 if (session->status == ISSL_OPEN)
467 if (session->wstat == ISSL_READ)
469 if(DoWrite(session) == 0)
473 if (session->rstat == ISSL_READ)
475 int ret = DoRead(session);
479 if (count <= session->inbufoffset)
481 memcpy(buffer, session->inbuf, count);
482 // Move the stuff left in inbuf to the beginning of it
483 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
484 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
485 session->inbufoffset -= count;
486 // Insp uses readresult as the count of how much data there is in buffer, so:
491 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
492 memcpy(buffer, session->inbuf, session->inbufoffset);
494 readresult = session->inbufoffset;
495 // Zero the offset, as there's nothing there..
496 session->inbufoffset = 0;
511 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
513 issl_session* session = &sessions[fd];
517 CloseSession(session);
521 session->outbuf.append(buffer, count);
523 if (session->status == ISSL_HANDSHAKING)
525 // The handshake isn't finished, try to finish it.
526 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
530 if (session->status == ISSL_OPEN)
532 if (session->rstat == ISSL_WRITE)
535 if (session->wstat == ISSL_WRITE)
536 return DoWrite(session);
542 int DoWrite(issl_session* session)
544 if (!session->outbuf.size())
547 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
551 CloseSession(session);
556 int err = SSL_get_error(session->sess, ret);
558 if (err == SSL_ERROR_WANT_WRITE)
560 session->wstat = ISSL_WRITE;
563 else if (err == SSL_ERROR_WANT_READ)
565 session->wstat = ISSL_READ;
570 CloseSession(session);
576 session->outbuf = session->outbuf.substr(ret);
581 int DoRead(issl_session* session)
583 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
584 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
586 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
590 // Client closed connection.
591 CloseSession(session);
596 int err = SSL_get_error(session->sess, ret);
598 if (err == SSL_ERROR_WANT_READ)
600 session->rstat = ISSL_READ;
603 else if (err == SSL_ERROR_WANT_WRITE)
605 session->rstat = ISSL_WRITE;
610 CloseSession(session);
616 // Read successfully 'ret' bytes into inbuf + inbufoffset
617 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
618 // 'buffer' is 'count' long
620 session->inbufoffset += ret;
626 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
627 virtual void OnWhois(userrec* source, userrec* dest)
629 // Bugfix, only send this numeric for *our* SSL users
630 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
632 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
636 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
638 // check if the linking module wants to know about OUR metadata
639 if (extname == "ssl")
641 // check if this user has an swhois field to send
642 if(user->GetExt(extname, dummy))
644 // call this function in the linking module, let it format the data how it
645 // sees fit, and send it on its way. We dont need or want to know how.
646 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
651 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
653 // check if its our metadata key, and its associated with a user
654 if ((target_type == TYPE_USER) && (extname == "ssl"))
656 userrec* dest = (userrec*)target;
657 // if they dont already have an ssl flag, accept the remote server's
658 if (!dest->GetExt(extname, dummy))
660 dest->Extend(extname, "ON");
665 bool Handshake(issl_session* session)
669 if (session->outbound)
670 ret = SSL_connect(session->sess);
672 ret = SSL_accept(session->sess);
676 int err = SSL_get_error(session->sess, ret);
678 if (err == SSL_ERROR_WANT_READ)
680 session->rstat = ISSL_READ;
681 session->status = ISSL_HANDSHAKING;
683 else if (err == SSL_ERROR_WANT_WRITE)
685 session->wstat = ISSL_WRITE;
686 session->status = ISSL_HANDSHAKING;
687 MakePollWrite(session);
691 CloseSession(session);
698 // Handshake complete.
699 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
700 userrec* u = ServerInstance->FindDescriptor(session->fd);
703 if (!u->GetExt("ssl", dummy))
704 u->Extend("ssl", "ON");
707 session->status = ISSL_OPEN;
709 MakePollWrite(session);
715 CloseSession(session);
722 virtual void OnPostConnect(userrec* user)
724 // This occurs AFTER OnUserConnect so we can be sure the
725 // protocol module has propogated the NICK message.
726 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
728 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
729 std::deque<std::string>* metadata = new std::deque<std::string>;
730 metadata->push_back(user->nick);
731 metadata->push_back("ssl"); // The metadata id
732 metadata->push_back("ON"); // The value to send
733 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
734 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
738 VerifyCertificate(&sessions[user->GetFd()], user);
742 void MakePollWrite(issl_session* session)
744 OnRawSocketWrite(session->fd, NULL, 0);
747 void CloseSession(issl_session* session)
751 SSL_shutdown(session->sess);
752 SSL_free(session->sess);
757 delete[] session->inbuf;
760 session->outbuf.clear();
761 session->inbuf = NULL;
762 session->sess = NULL;
763 session->status = ISSL_NONE;
766 void VerifyCertificate(issl_session* session, Extensible* user)
769 ssl_cert* certinfo = new ssl_cert;
771 unsigned char md[EVP_MAX_MD_SIZE];
772 const EVP_MD *digest = EVP_md5();
774 user->Extend("ssl_cert",certinfo);
776 cert = SSL_get_peer_certificate((SSL*)session->sess);
780 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
784 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
788 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
789 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
793 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
794 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
797 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
798 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
800 if (!X509_digest(cert, digest, md, &n))
802 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
806 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
809 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))
811 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
818 static int error_callback(const char *str, size_t len, void *u)
820 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
821 mssl->PublicInstance->Log(DEFAULT, "SSL error: " + std::string(str, len - 1));
825 class ModuleSSLOpenSSLFactory : public ModuleFactory
828 ModuleSSLOpenSSLFactory()
832 ~ModuleSSLOpenSSLFactory()
836 virtual Module * CreateModule(InspIRCd* Me)
838 return new ModuleSSLOpenSSL(Me);
843 extern "C" void * init_module( void )
845 return new ModuleSSLOpenSSLFactory;