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, I_OnHookUserIO };
154 ServerInstance->Modules->Attach(eventlist, this, 16);
157 virtual void OnHookUserIO(User* user)
159 if (!user->io && isin(user->GetPort(), listenports))
161 /* Hook the user with our module */
166 virtual void OnRehash(User* user, const std::string ¶m)
168 ConfigReader Conf(ServerInstance);
170 for (unsigned int i = 0; i < listenports.size(); i++)
172 ServerInstance->Config->DelIOHook(listenports[i]);
179 for (int index = 0; index < Conf.Enumerate("bind"); index++)
181 // For each <bind> tag
182 std::string x = Conf.ReadValue("bind", "type", index);
183 if (((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "openssl"))
185 // Get the port we're meant to be listening on with SSL
186 std::string port = Conf.ReadValue("bind", "port", index);
187 irc::portparser portrange(port, false);
189 while ((portno = portrange.GetToken()))
194 if (ServerInstance->Config->AddIOHook(portno, this))
196 listenports.push_back(portno);
197 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
198 if (ServerInstance->Config->ports[i]->GetPort() == portno)
199 ServerInstance->Config->ports[i]->SetDescription("ssl");
200 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
201 sslports.append("*:").append(ConvToStr(portno)).append(";");
205 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
208 catch (ModuleException &e)
210 ServerInstance->Logs->Log("m_ssl_openssl",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());
216 if (!sslports.empty())
217 sslports.erase(sslports.end() - 1);
224 std::string confdir(ServerInstance->ConfigFileName);
225 // +1 so we the path ends with a /
226 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
228 cafile = Conf.ReadValue("openssl", "cafile", 0);
229 certfile = Conf.ReadValue("openssl", "certfile", 0);
230 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
231 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
233 // Set all the default values needed.
237 if (certfile.empty())
238 certfile = "cert.pem";
244 dhfile = "dhparams.pem";
246 // Prepend relative paths with the path to the config directory.
247 if (cafile[0] != '/')
248 cafile = confdir + cafile;
250 if (certfile[0] != '/')
251 certfile = confdir + certfile;
253 if (keyfile[0] != '/')
254 keyfile = confdir + keyfile;
256 if (dhfile[0] != '/')
257 dhfile = confdir + dhfile;
259 /* Load our keys and certificates
260 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
262 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
264 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
265 ERR_print_errors_cb(error_callback, this);
268 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)))
270 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
271 ERR_print_errors_cb(error_callback, this);
274 /* Load the CAs we trust*/
275 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
277 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
278 ERR_print_errors_cb(error_callback, this);
281 FILE* dhpfile = fopen(dhfile.c_str(), "r");
286 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
287 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
291 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
292 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
294 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
295 ERR_print_errors_cb(error_callback, this);
302 virtual void On005Numeric(std::string &output)
304 output.append(" SSL=" + sslports);
307 virtual ~ModuleSSLOpenSSL()
310 SSL_CTX_free(clictx);
313 virtual void OnCleanup(int target_type, void* item)
315 if (target_type == TYPE_USER)
317 User* user = (User*)item;
319 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
321 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
322 // Potentially there could be multiple SSL modules loaded at once on different ports.
323 User::QuitUser(ServerInstance, user, "SSL module unloading");
325 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
328 user->GetExt("ssl_cert", tofree);
330 user->Shrink("ssl_cert");
337 virtual void OnUnloadModule(Module* mod, const std::string &name)
341 for(unsigned int i = 0; i < listenports.size(); i++)
343 ServerInstance->Config->DelIOHook(listenports[i]);
344 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
345 if (ServerInstance->Config->ports[j]->GetPort() == listenports[i])
346 ServerInstance->Config->ports[j]->SetDescription("plaintext");
351 virtual Version GetVersion()
353 return Version(1, 2, 0, 0, VF_VENDOR, API_VERSION);
357 virtual const char* OnRequest(Request* request)
359 ISHRequest* ISR = (ISHRequest*)request;
360 if (strcmp("IS_NAME", request->GetId()) == 0)
364 else if (strcmp("IS_HOOK", request->GetId()) == 0)
366 const char* ret = "OK";
369 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? "OK" : NULL;
371 catch (ModuleException &e)
378 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
380 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? "OK" : NULL;
382 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
384 if (ISR->Sock->GetFd() < 0)
387 issl_session* session = &sessions[ISR->Sock->GetFd()];
388 return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
390 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
392 issl_session* session = &sessions[ISR->Sock->GetFd()];
395 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
403 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
405 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
406 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
409 issl_session* session = &sessions[fd];
412 session->inbuf = new char[inbufsize];
413 session->inbufoffset = 0;
414 session->sess = SSL_new(ctx);
415 session->status = ISSL_NONE;
416 session->outbound = false;
418 if (session->sess == NULL)
421 if (SSL_set_fd(session->sess, fd) == 0)
423 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
430 virtual void OnRawSocketConnect(int fd)
432 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
433 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
436 issl_session* session = &sessions[fd];
439 session->inbuf = new char[inbufsize];
440 session->inbufoffset = 0;
441 session->sess = SSL_new(clictx);
442 session->status = ISSL_NONE;
443 session->outbound = true;
445 if (session->sess == NULL)
448 if (SSL_set_fd(session->sess, fd) == 0)
450 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
457 virtual void OnRawSocketClose(int fd)
459 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
460 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
463 CloseSession(&sessions[fd]);
465 EventHandler* user = ServerInstance->SE->GetRef(fd);
467 if ((user) && (user->GetExt("ssl_cert", dummy)))
470 user->GetExt("ssl_cert", tofree);
472 user->Shrink("ssl_cert");
476 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
478 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
479 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
482 issl_session* session = &sessions[fd];
487 CloseSession(session);
491 if (session->status == ISSL_HANDSHAKING)
493 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
495 // The handshake isn't finished and it wants to read, try to finish it.
496 if (!Handshake(session))
498 // Couldn't resume handshake.
509 // If we resumed the handshake then session->status will be ISSL_OPEN
511 if (session->status == ISSL_OPEN)
513 if (session->wstat == ISSL_READ)
515 if(DoWrite(session) == 0)
519 if (session->rstat == ISSL_READ)
521 int ret = DoRead(session);
525 if (count <= session->inbufoffset)
527 memcpy(buffer, session->inbuf, count);
528 // Move the stuff left in inbuf to the beginning of it
529 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
530 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
531 session->inbufoffset -= count;
532 // Insp uses readresult as the count of how much data there is in buffer, so:
537 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
538 memcpy(buffer, session->inbuf, session->inbufoffset);
540 readresult = session->inbufoffset;
541 // Zero the offset, as there's nothing there..
542 session->inbufoffset = 0;
553 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
555 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
556 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
559 issl_session* session = &sessions[fd];
563 CloseSession(session);
567 session->outbuf.append(buffer, count);
568 MakePollWrite(session);
570 if (session->status == ISSL_HANDSHAKING)
572 // The handshake isn't finished, try to finish it.
573 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
579 if (session->status == ISSL_OPEN)
581 if (session->rstat == ISSL_WRITE)
586 if (session->wstat == ISSL_WRITE)
588 return DoWrite(session);
595 int DoWrite(issl_session* session)
597 if (!session->outbuf.size())
600 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
604 CloseSession(session);
609 int err = SSL_get_error(session->sess, ret);
611 if (err == SSL_ERROR_WANT_WRITE)
613 session->wstat = ISSL_WRITE;
616 else if (err == SSL_ERROR_WANT_READ)
618 session->wstat = ISSL_READ;
623 CloseSession(session);
629 session->outbuf = session->outbuf.substr(ret);
634 int DoRead(issl_session* session)
636 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
637 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
639 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
643 // Client closed connection.
644 CloseSession(session);
649 int err = SSL_get_error(session->sess, ret);
651 if (err == SSL_ERROR_WANT_READ)
653 session->rstat = ISSL_READ;
656 else if (err == SSL_ERROR_WANT_WRITE)
658 session->rstat = ISSL_WRITE;
659 MakePollWrite(session);
664 CloseSession(session);
670 // Read successfully 'ret' bytes into inbuf + inbufoffset
671 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
672 // 'buffer' is 'count' long
674 session->inbufoffset += ret;
680 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
681 virtual void OnWhois(User* source, User* dest)
686 // Bugfix, only send this numeric for *our* SSL users
687 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
689 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
693 virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
695 // check if the linking module wants to know about OUR metadata
696 if (extname == "ssl")
698 // check if this user has an swhois field to send
699 if(user->GetExt(extname, dummy))
701 // call this function in the linking module, let it format the data how it
702 // sees fit, and send it on its way. We dont need or want to know how.
703 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
708 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
710 // check if its our metadata key, and its associated with a user
711 if ((target_type == TYPE_USER) && (extname == "ssl"))
713 User* dest = (User*)target;
714 // if they dont already have an ssl flag, accept the remote server's
715 if (!dest->GetExt(extname, dummy))
717 dest->Extend(extname, "ON");
722 bool Handshake(issl_session* session)
726 if (session->outbound)
727 ret = SSL_connect(session->sess);
729 ret = SSL_accept(session->sess);
733 int err = SSL_get_error(session->sess, ret);
735 if (err == SSL_ERROR_WANT_READ)
737 session->rstat = ISSL_READ;
738 session->status = ISSL_HANDSHAKING;
741 else if (err == SSL_ERROR_WANT_WRITE)
743 session->wstat = ISSL_WRITE;
744 session->status = ISSL_HANDSHAKING;
745 MakePollWrite(session);
750 CloseSession(session);
757 // Handshake complete.
758 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
759 User* u = ServerInstance->FindDescriptor(session->fd);
762 if (!u->GetExt("ssl", dummy))
763 u->Extend("ssl", "ON");
766 session->status = ISSL_OPEN;
768 MakePollWrite(session);
774 CloseSession(session);
781 virtual void OnPostConnect(User* user)
783 // This occurs AFTER OnUserConnect so we can be sure the
784 // protocol module has propagated the NICK message.
785 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
787 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
788 std::deque<std::string>* metadata = new std::deque<std::string>;
789 metadata->push_back(user->nick);
790 metadata->push_back("ssl"); // The metadata id
791 metadata->push_back("ON"); // The value to send
792 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
793 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
797 VerifyCertificate(&sessions[user->GetFd()], user);
798 if (sessions[user->GetFd()].sess)
799 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess));
803 void MakePollWrite(issl_session* session)
805 //OnRawSocketWrite(session->fd, NULL, 0);
806 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
809 ServerInstance->SE->WantWrite(eh);
813 virtual void OnBufferFlushed(User* user)
815 if (user->GetExt("ssl"))
817 issl_session* session = &sessions[user->GetFd()];
818 if (session && session->outbuf.size())
819 OnRawSocketWrite(user->GetFd(), NULL, 0);
823 void CloseSession(issl_session* session)
827 SSL_shutdown(session->sess);
828 SSL_free(session->sess);
833 delete[] session->inbuf;
836 session->outbuf.clear();
837 session->inbuf = NULL;
838 session->sess = NULL;
839 session->status = ISSL_NONE;
842 void VerifyCertificate(issl_session* session, Extensible* user)
844 if (!session->sess || !user)
848 ssl_cert* certinfo = new ssl_cert;
850 unsigned char md[EVP_MAX_MD_SIZE];
851 const EVP_MD *digest = EVP_md5();
853 user->Extend("ssl_cert",certinfo);
855 cert = SSL_get_peer_certificate((SSL*)session->sess);
859 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
863 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
867 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
868 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
872 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
873 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
876 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
877 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
879 if (!X509_digest(cert, digest, md, &n))
881 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
885 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
888 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))
890 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
897 static int error_callback(const char *str, size_t len, void *u)
899 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
900 mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
904 MODULE_INIT(ModuleSSLOpenSSL)