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 &host, int port, const std::vector<std::string> &portlist)
51 if (std::find(portlist.begin(), portlist.end(), "*:" + ConvToStr(port)) != portlist.end())
54 if (std::find(portlist.begin(), portlist.end(), ":" + ConvToStr(port)) != portlist.end())
57 return std::find(portlist.begin(), portlist.end(), host + ":" + ConvToStr(port)) != portlist.end();
62 return ERR_error_string(ERR_get_error(), NULL);
65 static int error_callback(const char *str, size_t len, void *u);
67 /** Represents an SSL user's extra data
69 class issl_session : public classbase
77 unsigned int inbufoffset;
78 char* inbuf; // Buffer OpenSSL reads into.
79 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
91 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
93 /* XXX: This will allow self signed certificates.
94 * In the future if we want an option to not allow this,
95 * we can just return preverify_ok here, and openssl
96 * will boot off self-signed and invalid peer certs.
98 int ve = X509_STORE_CTX_get_error(ctx);
100 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
105 class ModuleSSLOpenSSL : public Module
107 std::vector<std::string> listenports;
110 issl_session* sessions;
119 std::string certfile;
121 // std::string crlfile;
123 std::string sslports;
129 InspIRCd* PublicInstance;
131 ModuleSSLOpenSSL(InspIRCd* Me)
132 : Module(Me), PublicInstance(Me)
134 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
136 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
138 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
139 inbufsize = ServerInstance->Config->NetBufferSize;
141 /* Global SSL library initialization*/
143 SSL_load_error_strings();
145 /* Build our SSL contexts:
146 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
148 ctx = SSL_CTX_new( SSLv23_server_method() );
149 clictx = SSL_CTX_new( SSLv23_client_method() );
151 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
152 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
154 // Needs the flag as it ignores a plain /rehash
155 OnRehash(NULL,"ssl");
156 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup, I_On005Numeric,
157 I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect, I_OnHookUserIO };
158 ServerInstance->Modules->Attach(eventlist, this, 16);
161 virtual void OnHookUserIO(User* user, const std::string &targetip)
163 if (!user->io && isin(targetip,user->GetPort(), listenports))
165 /* Hook the user with our module */
170 virtual void OnRehash(User* user, const std::string ¶m)
172 ConfigReader Conf(ServerInstance);
178 for(int index = 0; index < Conf.Enumerate("bind"); index++)
180 // For each <bind> tag
181 std::string x = Conf.ReadValue("bind", "type", index);
182 if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "openssl"))
184 // Get the port we're meant to be listening on with SSL
185 std::string port = Conf.ReadValue("bind", "port", index);
186 std::string addr = Conf.ReadValue("bind", "address", index);
188 irc::portparser portrange(port, false);
190 while ((portno = portrange.GetToken()))
195 listenports.push_back(addr + ":" + ConvToStr(portno));
197 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
198 if ((ServerInstance->Config->ports[i]->GetPort() == portno) && (ServerInstance->Config->ports[i]->GetIP() == addr))
199 ServerInstance->Config->ports[i]->SetDescription("ssl");
200 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %ld", portno);
202 sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
204 catch (ModuleException &e)
206 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %ld: %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());
212 if (!sslports.empty())
213 sslports.erase(sslports.end() - 1);
220 std::string confdir(ServerInstance->ConfigFileName);
221 // +1 so we the path ends with a /
222 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
224 cafile = Conf.ReadValue("openssl", "cafile", 0);
225 certfile = Conf.ReadValue("openssl", "certfile", 0);
226 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
227 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
229 // Set all the default values needed.
233 if (certfile.empty())
234 certfile = "cert.pem";
240 dhfile = "dhparams.pem";
242 // Prepend relative paths with the path to the config directory.
243 if (cafile[0] != '/')
244 cafile = confdir + cafile;
246 if (certfile[0] != '/')
247 certfile = confdir + certfile;
249 if (keyfile[0] != '/')
250 keyfile = confdir + keyfile;
252 if (dhfile[0] != '/')
253 dhfile = confdir + dhfile;
255 /* Load our keys and certificates
256 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
258 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
260 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
261 ERR_print_errors_cb(error_callback, this);
264 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)))
266 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
267 ERR_print_errors_cb(error_callback, this);
270 /* Load the CAs we trust*/
271 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
273 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
274 ERR_print_errors_cb(error_callback, this);
277 FILE* dhpfile = fopen(dhfile.c_str(), "r");
282 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
283 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
287 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
288 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
290 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
291 ERR_print_errors_cb(error_callback, this);
298 virtual void On005Numeric(std::string &output)
300 output.append(" SSL=" + sslports);
303 virtual ~ModuleSSLOpenSSL()
306 SSL_CTX_free(clictx);
307 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
311 virtual void OnCleanup(int target_type, void* item)
313 if (target_type == TYPE_USER)
315 User* user = (User*)item;
317 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && user->io == this)
319 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
320 // Potentially there could be multiple SSL modules loaded at once on different ports.
321 User::QuitUser(ServerInstance, user, "SSL module unloading");
323 if (user->GetExt("ssl_cert", dummy))
326 user->GetExt("ssl_cert", tofree);
328 user->Shrink("ssl_cert");
335 virtual void OnUnloadModule(Module* mod, const std::string &name)
339 for(unsigned int i = 0; i < listenports.size(); i++)
341 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
342 if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
343 ServerInstance->Config->ports[j]->SetDescription("plaintext");
348 virtual Version GetVersion()
350 return Version(1, 2, 0, 0, VF_VENDOR, API_VERSION);
354 virtual const char* OnRequest(Request* request)
356 ISHRequest* ISR = (ISHRequest*)request;
357 if (strcmp("IS_NAME", request->GetId()) == 0)
361 else if (strcmp("IS_HOOK", request->GetId()) == 0)
363 const char* ret = "OK";
366 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? "OK" : NULL;
368 catch (ModuleException &e)
375 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
377 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? "OK" : NULL;
379 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
381 if (ISR->Sock->GetFd() < 0)
384 issl_session* session = &sessions[ISR->Sock->GetFd()];
385 return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
387 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
389 issl_session* session = &sessions[ISR->Sock->GetFd()];
392 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
400 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
402 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
403 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
406 issl_session* session = &sessions[fd];
409 session->inbuf = new char[inbufsize];
410 session->inbufoffset = 0;
411 session->sess = SSL_new(ctx);
412 session->status = ISSL_NONE;
413 session->outbound = false;
415 if (session->sess == NULL)
418 if (SSL_set_fd(session->sess, fd) == 0)
420 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
427 virtual void OnRawSocketConnect(int fd)
429 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
430 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
433 issl_session* session = &sessions[fd];
436 session->inbuf = new char[inbufsize];
437 session->inbufoffset = 0;
438 session->sess = SSL_new(clictx);
439 session->status = ISSL_NONE;
440 session->outbound = true;
442 if (session->sess == NULL)
445 if (SSL_set_fd(session->sess, fd) == 0)
447 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
454 virtual void OnRawSocketClose(int fd)
456 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
457 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
460 CloseSession(&sessions[fd]);
462 EventHandler* user = ServerInstance->SE->GetRef(fd);
464 if ((user) && (user->GetExt("ssl_cert", dummy)))
467 user->GetExt("ssl_cert", tofree);
469 user->Shrink("ssl_cert");
473 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
475 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
476 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
479 issl_session* session = &sessions[fd];
484 CloseSession(session);
488 if (session->status == ISSL_HANDSHAKING)
490 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
492 // The handshake isn't finished and it wants to read, try to finish it.
493 if (!Handshake(session))
495 // Couldn't resume handshake.
506 // If we resumed the handshake then session->status will be ISSL_OPEN
508 if (session->status == ISSL_OPEN)
510 if (session->wstat == ISSL_READ)
512 if(DoWrite(session) == 0)
516 if (session->rstat == ISSL_READ)
518 int ret = DoRead(session);
522 if (count <= session->inbufoffset)
524 memcpy(buffer, session->inbuf, count);
525 // Move the stuff left in inbuf to the beginning of it
526 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
527 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
528 session->inbufoffset -= count;
529 // Insp uses readresult as the count of how much data there is in buffer, so:
534 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
535 memcpy(buffer, session->inbuf, session->inbufoffset);
537 readresult = session->inbufoffset;
538 // Zero the offset, as there's nothing there..
539 session->inbufoffset = 0;
550 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
552 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
553 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
556 issl_session* session = &sessions[fd];
560 CloseSession(session);
564 session->outbuf.append(buffer, count);
565 MakePollWrite(session);
567 if (session->status == ISSL_HANDSHAKING)
569 // The handshake isn't finished, try to finish it.
570 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
576 if (session->status == ISSL_OPEN)
578 if (session->rstat == ISSL_WRITE)
583 if (session->wstat == ISSL_WRITE)
585 return DoWrite(session);
592 int DoWrite(issl_session* session)
594 if (!session->outbuf.size())
597 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
601 CloseSession(session);
606 int err = SSL_get_error(session->sess, ret);
608 if (err == SSL_ERROR_WANT_WRITE)
610 session->wstat = ISSL_WRITE;
613 else if (err == SSL_ERROR_WANT_READ)
615 session->wstat = ISSL_READ;
620 CloseSession(session);
626 session->outbuf = session->outbuf.substr(ret);
631 int DoRead(issl_session* session)
633 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
634 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
636 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
640 // Client closed connection.
641 CloseSession(session);
646 int err = SSL_get_error(session->sess, ret);
648 if (err == SSL_ERROR_WANT_READ)
650 session->rstat = ISSL_READ;
653 else if (err == SSL_ERROR_WANT_WRITE)
655 session->rstat = ISSL_WRITE;
656 MakePollWrite(session);
661 CloseSession(session);
667 // Read successfully 'ret' bytes into inbuf + inbufoffset
668 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
669 // 'buffer' is 'count' long
671 session->inbufoffset += ret;
677 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
678 virtual void OnWhois(User* source, User* dest)
683 // Bugfix, only send this numeric for *our* SSL users
684 if (dest->GetExt("ssl", dummy) || ((IS_LOCAL(dest) && dest->io == this)))
686 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
690 virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
692 // check if the linking module wants to know about OUR metadata
693 if (extname == "ssl")
695 // check if this user has an swhois field to send
696 if(user->GetExt(extname, dummy))
698 // call this function in the linking module, let it format the data how it
699 // sees fit, and send it on its way. We dont need or want to know how.
700 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
705 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
707 // check if its our metadata key, and its associated with a user
708 if ((target_type == TYPE_USER) && (extname == "ssl"))
710 User* dest = (User*)target;
711 // if they dont already have an ssl flag, accept the remote server's
712 if (!dest->GetExt(extname, dummy))
714 dest->Extend(extname, "ON");
719 bool Handshake(issl_session* session)
723 if (session->outbound)
724 ret = SSL_connect(session->sess);
726 ret = SSL_accept(session->sess);
730 int err = SSL_get_error(session->sess, ret);
732 if (err == SSL_ERROR_WANT_READ)
734 session->rstat = ISSL_READ;
735 session->status = ISSL_HANDSHAKING;
738 else if (err == SSL_ERROR_WANT_WRITE)
740 session->wstat = ISSL_WRITE;
741 session->status = ISSL_HANDSHAKING;
742 MakePollWrite(session);
747 CloseSession(session);
754 // Handshake complete.
755 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
756 User* u = ServerInstance->FindDescriptor(session->fd);
759 if (!u->GetExt("ssl", dummy))
760 u->Extend("ssl", "ON");
763 session->status = ISSL_OPEN;
765 MakePollWrite(session);
771 CloseSession(session);
778 virtual void OnPostConnect(User* user)
780 // This occurs AFTER OnUserConnect so we can be sure the
781 // protocol module has propagated the NICK message.
782 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
784 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
785 ServerInstance->PI->SendMetaData(user, TYPE_USER, "SSL", "on");
787 VerifyCertificate(&sessions[user->GetFd()], user);
788 if (sessions[user->GetFd()].sess)
789 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess));
793 void MakePollWrite(issl_session* session)
795 //OnRawSocketWrite(session->fd, NULL, 0);
796 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
799 ServerInstance->SE->WantWrite(eh);
803 virtual void OnBufferFlushed(User* user)
805 if (user->GetExt("ssl"))
807 issl_session* session = &sessions[user->GetFd()];
808 if (session && session->outbuf.size())
809 OnRawSocketWrite(user->GetFd(), NULL, 0);
813 void CloseSession(issl_session* session)
817 SSL_shutdown(session->sess);
818 SSL_free(session->sess);
823 delete[] session->inbuf;
826 session->outbuf.clear();
827 session->inbuf = NULL;
828 session->sess = NULL;
829 session->status = ISSL_NONE;
832 void VerifyCertificate(issl_session* session, Extensible* user)
834 if (!session->sess || !user)
838 ssl_cert* certinfo = new ssl_cert;
840 unsigned char md[EVP_MAX_MD_SIZE];
841 const EVP_MD *digest = EVP_md5();
843 user->Extend("ssl_cert",certinfo);
845 cert = SSL_get_peer_certificate((SSL*)session->sess);
849 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
853 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
857 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
858 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
862 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
863 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
866 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
867 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
869 if (!X509_digest(cert, digest, md, &n))
871 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
875 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
878 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))
880 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
888 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
889 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIO_AFTER, &server);
894 static int error_callback(const char *str, size_t len, void *u)
896 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
897 mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
901 MODULE_INIT(ModuleSSLOpenSSL)