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 * ---------------------------------------------------
16 #include <openssl/ssl.h>
17 #include <openssl/err.h>
20 #include <openssl/applink.c>
23 #include "configreader.h"
31 #include "transport.h"
34 #pragma comment(lib, "libeay32MTd")
35 #pragma comment(lib, "ssleay32MTd")
36 #undef MAX_DESCRIPTORS
37 #define MAX_DESCRIPTORS 10000
40 /* $ModDesc: Provides SSL support for clients */
41 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
42 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
43 /* $ModDep: transport.h */
45 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
46 enum issl_io_status { ISSL_WRITE, ISSL_READ };
48 static bool SelfSigned = false;
50 bool isin(int port, const std::vector<int> &portlist)
52 for(unsigned int i = 0; i < portlist.size(); i++)
53 if(portlist[i] == port)
61 return ERR_error_string(ERR_get_error(), NULL);
64 static int error_callback(const char *str, size_t len, void *u);
66 /** Represents an SSL user's extra data
68 class issl_session : public classbase
76 unsigned int inbufoffset;
77 char* inbuf; // Buffer OpenSSL reads into.
78 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
90 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
92 /* XXX: This will allow self signed certificates.
93 * In the future if we want an option to not allow this,
94 * we can just return preverify_ok here, and openssl
95 * will boot off self-signed and invalid peer certs.
97 int ve = X509_STORE_CTX_get_error(ctx);
99 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
104 class ModuleSSLOpenSSL : public Module
109 std::vector<int> listenports;
112 issl_session sessions[MAX_DESCRIPTORS];
121 std::string certfile;
123 // std::string crlfile;
125 std::string sslports;
131 InspIRCd* PublicInstance;
133 ModuleSSLOpenSSL(InspIRCd* Me)
134 : Module(Me), PublicInstance(Me)
136 ServerInstance->PublishInterface("InspSocketHook", this);
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");
158 virtual void OnRehash(userrec* user, const std::string ¶m)
163 Conf = new ConfigReader(ServerInstance);
165 for (unsigned int i = 0; i < listenports.size(); i++)
167 ServerInstance->Config->DelIOHook(listenports[i]);
174 for (int i = 0; i < Conf->Enumerate("bind"); i++)
176 // For each <bind> tag
177 std::string x = Conf->ReadValue("bind", "type", i);
178 if (((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
180 // Get the port we're meant to be listening on with SSL
181 std::string port = Conf->ReadValue("bind", "port", i);
182 irc::portparser portrange(port, false);
184 while ((portno = portrange.GetToken()))
189 if (ServerInstance->Config->AddIOHook(portno, this))
191 listenports.push_back(portno);
192 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
193 if (ServerInstance->Config->ports[i]->GetPort() == portno)
194 ServerInstance->Config->ports[i]->SetDescription("ssl");
195 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
196 sslports.append("*:").append(ConvToStr(portno)).append(";");
200 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
203 catch (ModuleException &e)
205 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());
211 if (!sslports.empty())
212 sslports.erase(sslports.end() - 1);
214 std::string confdir(ServerInstance->ConfigFileName);
215 // +1 so we the path ends with a /
216 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
218 cafile = Conf->ReadValue("openssl", "cafile", 0);
219 certfile = Conf->ReadValue("openssl", "certfile", 0);
220 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
221 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
223 // Set all the default values needed.
227 if (certfile.empty())
228 certfile = "cert.pem";
234 dhfile = "dhparams.pem";
236 // Prepend relative paths with the path to the config directory.
237 if (cafile[0] != '/')
238 cafile = confdir + cafile;
240 if (certfile[0] != '/')
241 certfile = confdir + certfile;
243 if (keyfile[0] != '/')
244 keyfile = confdir + keyfile;
246 if (dhfile[0] != '/')
247 dhfile = confdir + dhfile;
249 /* Load our keys and certificates
250 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
252 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
254 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
255 ERR_print_errors_cb(error_callback, this);
258 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)))
260 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
261 ERR_print_errors_cb(error_callback, this);
264 /* Load the CAs we trust*/
265 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
267 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
268 ERR_print_errors_cb(error_callback, this);
271 FILE* dhpfile = fopen(dhfile.c_str(), "r");
276 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
277 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
281 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
282 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
284 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
285 ERR_print_errors_cb(error_callback, this);
294 virtual void On005Numeric(std::string &output)
296 output.append(" SSL=" + sslports);
299 virtual ~ModuleSSLOpenSSL()
302 SSL_CTX_free(clictx);
305 virtual void OnCleanup(int target_type, void* item)
307 if (target_type == TYPE_USER)
309 userrec* user = (userrec*)item;
311 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
313 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
314 // Potentially there could be multiple SSL modules loaded at once on different ports.
315 userrec::QuitUser(ServerInstance, user, "SSL module unloading");
317 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
320 user->GetExt("ssl_cert", tofree);
322 user->Shrink("ssl_cert");
327 virtual void OnUnloadModule(Module* mod, const std::string &name)
331 for(unsigned int i = 0; i < listenports.size(); i++)
333 ServerInstance->Config->DelIOHook(listenports[i]);
334 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
335 if (ServerInstance->Config->ports[j]->GetPort() == listenports[i])
336 ServerInstance->Config->ports[j]->SetDescription("plaintext");
341 virtual Version GetVersion()
343 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
346 void Implements(char* List)
348 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = List[I_On005Numeric] = 1;
349 List[I_OnBufferFlushed] = List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
352 virtual char* OnRequest(Request* request)
354 ISHRequest* ISR = (ISHRequest*)request;
355 if (strcmp("IS_NAME", request->GetId()) == 0)
359 else if (strcmp("IS_HOOK", request->GetId()) == 0)
364 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
366 catch (ModuleException &e)
373 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
375 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
377 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
379 ServerInstance->Log(DEBUG,"Module checking if handshake is done");
380 if (ISR->Sock->GetFd() < 0)
383 issl_session* session = &sessions[ISR->Sock->GetFd()];
384 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
386 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
388 issl_session* session = &sessions[ISR->Sock->GetFd()];
391 VerifyCertificate(session, (InspSocket*)ISR->Sock);
399 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
401 issl_session* session = &sessions[fd];
404 session->inbuf = new char[inbufsize];
405 session->inbufoffset = 0;
406 session->sess = SSL_new(ctx);
407 session->status = ISSL_NONE;
408 session->outbound = false;
410 if (session->sess == NULL)
413 if (SSL_set_fd(session->sess, fd) == 0)
415 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
422 virtual void OnRawSocketConnect(int fd)
424 issl_session* session = &sessions[fd];
427 session->inbuf = new char[inbufsize];
428 session->inbufoffset = 0;
429 session->sess = SSL_new(clictx);
430 session->status = ISSL_NONE;
431 session->outbound = true;
433 if (session->sess == NULL)
436 if (SSL_set_fd(session->sess, fd) == 0)
438 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
445 virtual void OnRawSocketClose(int fd)
447 CloseSession(&sessions[fd]);
449 EventHandler* user = ServerInstance->SE->GetRef(fd);
451 if ((user) && (user->GetExt("ssl_cert", dummy)))
454 user->GetExt("ssl_cert", tofree);
456 user->Shrink("ssl_cert");
460 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
462 issl_session* session = &sessions[fd];
467 CloseSession(session);
471 if (session->status == ISSL_HANDSHAKING)
473 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
475 // The handshake isn't finished and it wants to read, try to finish it.
476 if (!Handshake(session))
478 // Couldn't resume handshake.
489 // If we resumed the handshake then session->status will be ISSL_OPEN
491 if (session->status == ISSL_OPEN)
493 if (session->wstat == ISSL_READ)
495 if(DoWrite(session) == 0)
499 if (session->rstat == ISSL_READ)
501 int ret = DoRead(session);
503 ServerInstance->Log(DEBUG, "<***> DoRead count: " + ConvToStr(count));
504 ServerInstance->Log(DEBUG, "<***> DoRead ret: " + ConvToStr(ret));
505 ServerInstance->Log(DEBUG, "<***> DoRead session->inbufoffset: " + ConvToStr(session->inbufoffset));
509 if (count <= session->inbufoffset)
511 memcpy(buffer, session->inbuf, count);
512 // Move the stuff left in inbuf to the beginning of it
513 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
514 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
515 session->inbufoffset -= count;
516 // Insp uses readresult as the count of how much data there is in buffer, so:
521 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
522 memcpy(buffer, session->inbuf, session->inbufoffset);
524 readresult = session->inbufoffset;
525 // Zero the offset, as there's nothing there..
526 session->inbufoffset = 0;
541 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
543 issl_session* session = &sessions[fd];
547 CloseSession(session);
551 session->outbuf.append(buffer, count);
553 if (session->status == ISSL_HANDSHAKING)
555 // The handshake isn't finished, try to finish it.
556 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
562 if (session->status == ISSL_OPEN)
564 if (session->rstat == ISSL_WRITE)
569 if (session->wstat == ISSL_WRITE)
571 return DoWrite(session);
578 int DoWrite(issl_session* session)
580 if (!session->outbuf.size())
583 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
587 CloseSession(session);
592 MakePollWrite(session);
594 int err = SSL_get_error(session->sess, ret);
596 if (err == SSL_ERROR_WANT_WRITE)
598 session->wstat = ISSL_WRITE;
601 else if (err == SSL_ERROR_WANT_READ)
603 session->wstat = ISSL_READ;
608 CloseSession(session);
614 session->outbuf = session->outbuf.substr(ret);
615 MakePollWrite(session);
620 int DoRead(issl_session* session)
622 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
623 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
625 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
629 // Client closed connection.
630 CloseSession(session);
635 int err = SSL_get_error(session->sess, ret);
637 if (err == SSL_ERROR_WANT_READ)
639 session->rstat = ISSL_READ;
642 else if (err == SSL_ERROR_WANT_WRITE)
644 session->rstat = ISSL_WRITE;
645 MakePollWrite(session);
650 CloseSession(session);
656 // Read successfully 'ret' bytes into inbuf + inbufoffset
657 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
658 // 'buffer' is 'count' long
660 session->inbufoffset += ret;
666 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
667 virtual void OnWhois(userrec* source, userrec* dest)
672 // Bugfix, only send this numeric for *our* SSL users
673 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
675 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
679 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
681 // check if the linking module wants to know about OUR metadata
682 if (extname == "ssl")
684 // check if this user has an swhois field to send
685 if(user->GetExt(extname, dummy))
687 // call this function in the linking module, let it format the data how it
688 // sees fit, and send it on its way. We dont need or want to know how.
689 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
694 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
696 // check if its our metadata key, and its associated with a user
697 if ((target_type == TYPE_USER) && (extname == "ssl"))
699 userrec* dest = (userrec*)target;
700 // if they dont already have an ssl flag, accept the remote server's
701 if (!dest->GetExt(extname, dummy))
703 dest->Extend(extname, "ON");
708 bool Handshake(issl_session* session)
712 if (session->outbound)
714 ret = SSL_connect(session->sess);
717 ret = SSL_accept(session->sess);
721 int err = SSL_get_error(session->sess, ret);
723 if (err == SSL_ERROR_WANT_READ)
725 session->rstat = ISSL_READ;
726 session->status = ISSL_HANDSHAKING;
729 else if (err == SSL_ERROR_WANT_WRITE)
731 session->wstat = ISSL_WRITE;
732 session->status = ISSL_HANDSHAKING;
733 MakePollWrite(session);
738 CloseSession(session);
745 // Handshake complete.
746 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
747 userrec* u = ServerInstance->FindDescriptor(session->fd);
750 if (!u->GetExt("ssl", dummy))
751 u->Extend("ssl", "ON");
754 session->status = ISSL_OPEN;
756 MakePollWrite(session);
762 int ssl_err = SSL_get_error(session->sess, ret);
764 ERR_print_errors_fp(stderr);
765 ServerInstance->Log(DEBUG,"Handshake fail 2: %d: %s", ssl_err, ERR_error_string(ssl_err,buf));
766 CloseSession(session);
773 virtual void OnPostConnect(userrec* user)
775 // This occurs AFTER OnUserConnect so we can be sure the
776 // protocol module has propogated the NICK message.
777 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
779 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
780 std::deque<std::string>* metadata = new std::deque<std::string>;
781 metadata->push_back(user->nick);
782 metadata->push_back("ssl"); // The metadata id
783 metadata->push_back("ON"); // The value to send
784 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
785 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
789 VerifyCertificate(&sessions[user->GetFd()], user);
790 if (sessions[user->GetFd()].sess)
791 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess));
795 void MakePollWrite(issl_session* session)
797 //OnRawSocketWrite(session->fd, NULL, 0);
798 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
800 ServerInstance->SE->WantWrite(eh);
803 virtual void OnBufferFlushed(userrec* user)
805 if (user->GetExt("ssl"))
807 ServerInstance->Log(DEBUG,"OnBufferFlushed for ssl user");
808 issl_session* session = &sessions[user->GetFd()];
809 if (session && session->outbuf.size())
810 OnRawSocketWrite(user->GetFd(), NULL, 0);
814 void CloseSession(issl_session* session)
818 SSL_shutdown(session->sess);
819 SSL_free(session->sess);
824 delete[] session->inbuf;
827 session->outbuf.clear();
828 session->inbuf = NULL;
829 session->sess = NULL;
830 session->status = ISSL_NONE;
833 void VerifyCertificate(issl_session* session, Extensible* user)
835 if (!session->sess || !user)
839 ssl_cert* certinfo = new ssl_cert;
841 unsigned char md[EVP_MAX_MD_SIZE];
842 const EVP_MD *digest = EVP_md5();
844 user->Extend("ssl_cert",certinfo);
846 cert = SSL_get_peer_certificate((SSL*)session->sess);
850 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
854 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
858 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
859 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
863 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
864 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
867 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
868 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
870 if (!X509_digest(cert, digest, md, &n))
872 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
876 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
879 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))
881 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
888 static int error_callback(const char *str, size_t len, void *u)
890 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
891 mssl->PublicInstance->Log(DEFAULT, "SSL error: " + std::string(str, len - 1));
895 MODULE_INIT(ModuleSSLOpenSSL);