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>
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 /* $CopyInstall: conf/key.pem $(CONPATH) */
46 /* $CopyInstall: conf/cert.pem $(CONPATH) */
48 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
49 enum issl_io_status { ISSL_WRITE, ISSL_READ };
51 static bool SelfSigned = false;
53 bool isin(int port, const std::vector<int> &portlist)
55 for(unsigned int i = 0; i < portlist.size(); i++)
56 if(portlist[i] == port)
64 return ERR_error_string(ERR_get_error(), NULL);
67 static int error_callback(const char *str, size_t len, void *u);
69 /** Represents an SSL user's extra data
71 class issl_session : public classbase
79 unsigned int inbufoffset;
80 char* inbuf; // Buffer OpenSSL reads into.
81 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
93 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
95 /* XXX: This will allow self signed certificates.
96 * In the future if we want an option to not allow this,
97 * we can just return preverify_ok here, and openssl
98 * will boot off self-signed and invalid peer certs.
100 int ve = X509_STORE_CTX_get_error(ctx);
102 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
107 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->Modules->PublishInterface("BufferedSocketHook", 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");
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 };
158 ServerInstance->Modules->Attach(eventlist, this, 15);
161 virtual void OnRehash(User* user, const std::string ¶m)
166 ConfigReader Conf(ServerInstance);
168 for (unsigned int i = 0; i < listenports.size(); i++)
170 ServerInstance->Config->DelIOHook(listenports[i]);
177 for (int i = 0; i < Conf.Enumerate("bind"); i++)
179 // For each <bind> tag
180 std::string x = Conf.ReadValue("bind", "type", i);
181 if (((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", i) == "openssl"))
183 // Get the port we're meant to be listening on with SSL
184 std::string port = Conf.ReadValue("bind", "port", i);
185 irc::portparser portrange(port, false);
187 while ((portno = portrange.GetToken()))
192 if (ServerInstance->Config->AddIOHook(portno, this))
194 listenports.push_back(portno);
195 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
196 if (ServerInstance->Config->ports[i]->GetPort() == portno)
197 ServerInstance->Config->ports[i]->SetDescription("ssl");
198 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
199 sslports.append("*:").append(ConvToStr(portno)).append(";");
203 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
206 catch (ModuleException &e)
208 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());
214 if (!sslports.empty())
215 sslports.erase(sslports.end() - 1);
217 std::string confdir(ServerInstance->ConfigFileName);
218 // +1 so we the path ends with a /
219 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
221 cafile = Conf.ReadValue("openssl", "cafile", 0);
222 certfile = Conf.ReadValue("openssl", "certfile", 0);
223 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
224 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
226 // Set all the default values needed.
230 if (certfile.empty())
231 certfile = "cert.pem";
237 dhfile = "dhparams.pem";
239 // Prepend relative paths with the path to the config directory.
240 if (cafile[0] != '/')
241 cafile = confdir + cafile;
243 if (certfile[0] != '/')
244 certfile = confdir + certfile;
246 if (keyfile[0] != '/')
247 keyfile = confdir + keyfile;
249 if (dhfile[0] != '/')
250 dhfile = confdir + dhfile;
252 /* Load our keys and certificates
253 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
255 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
257 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
258 ERR_print_errors_cb(error_callback, this);
261 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)))
263 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
264 ERR_print_errors_cb(error_callback, this);
267 /* Load the CAs we trust*/
268 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
270 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
271 ERR_print_errors_cb(error_callback, this);
274 FILE* dhpfile = fopen(dhfile.c_str(), "r");
279 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
280 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
284 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
285 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
287 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
288 ERR_print_errors_cb(error_callback, this);
295 virtual void On005Numeric(std::string &output)
297 output.append(" SSL=" + sslports);
300 virtual ~ModuleSSLOpenSSL()
303 SSL_CTX_free(clictx);
306 virtual void OnCleanup(int target_type, void* item)
308 if (target_type == TYPE_USER)
310 User* user = (User*)item;
312 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
314 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
315 // Potentially there could be multiple SSL modules loaded at once on different ports.
316 User::QuitUser(ServerInstance, user, "SSL module unloading");
318 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
321 user->GetExt("ssl_cert", tofree);
323 user->Shrink("ssl_cert");
328 virtual void OnUnloadModule(Module* mod, const std::string &name)
332 for(unsigned int i = 0; i < listenports.size(); i++)
334 ServerInstance->Config->DelIOHook(listenports[i]);
335 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
336 if (ServerInstance->Config->ports[j]->GetPort() == listenports[i])
337 ServerInstance->Config->ports[j]->SetDescription("plaintext");
342 virtual Version GetVersion()
344 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
348 virtual char* OnRequest(Request* request)
350 ISHRequest* ISR = (ISHRequest*)request;
351 if (strcmp("IS_NAME", request->GetId()) == 0)
355 else if (strcmp("IS_HOOK", request->GetId()) == 0)
360 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
362 catch (ModuleException &e)
369 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
371 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
373 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
375 if (ISR->Sock->GetFd() < 0)
378 issl_session* session = &sessions[ISR->Sock->GetFd()];
379 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
381 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
383 issl_session* session = &sessions[ISR->Sock->GetFd()];
386 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
394 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
396 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
397 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
400 issl_session* session = &sessions[fd];
403 session->inbuf = new char[inbufsize];
404 session->inbufoffset = 0;
405 session->sess = SSL_new(ctx);
406 session->status = ISSL_NONE;
407 session->outbound = false;
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 OnRawSocketConnect(int fd)
423 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
424 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
427 issl_session* session = &sessions[fd];
430 session->inbuf = new char[inbufsize];
431 session->inbufoffset = 0;
432 session->sess = SSL_new(clictx);
433 session->status = ISSL_NONE;
434 session->outbound = true;
436 if (session->sess == NULL)
439 if (SSL_set_fd(session->sess, fd) == 0)
441 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
448 virtual void OnRawSocketClose(int fd)
450 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
451 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
454 CloseSession(&sessions[fd]);
456 EventHandler* user = ServerInstance->SE->GetRef(fd);
458 if ((user) && (user->GetExt("ssl_cert", dummy)))
461 user->GetExt("ssl_cert", tofree);
463 user->Shrink("ssl_cert");
467 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
469 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
470 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
473 issl_session* session = &sessions[fd];
478 CloseSession(session);
482 if (session->status == ISSL_HANDSHAKING)
484 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
486 // The handshake isn't finished and it wants to read, try to finish it.
487 if (!Handshake(session))
489 // Couldn't resume handshake.
500 // If we resumed the handshake then session->status will be ISSL_OPEN
502 if (session->status == ISSL_OPEN)
504 if (session->wstat == ISSL_READ)
506 if(DoWrite(session) == 0)
510 if (session->rstat == ISSL_READ)
512 int ret = DoRead(session);
516 if (count <= session->inbufoffset)
518 memcpy(buffer, session->inbuf, count);
519 // Move the stuff left in inbuf to the beginning of it
520 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
521 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
522 session->inbufoffset -= count;
523 // Insp uses readresult as the count of how much data there is in buffer, so:
528 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
529 memcpy(buffer, session->inbuf, session->inbufoffset);
531 readresult = session->inbufoffset;
532 // Zero the offset, as there's nothing there..
533 session->inbufoffset = 0;
544 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
546 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
547 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
550 issl_session* session = &sessions[fd];
554 CloseSession(session);
558 session->outbuf.append(buffer, count);
559 MakePollWrite(session);
561 if (session->status == ISSL_HANDSHAKING)
563 // The handshake isn't finished, try to finish it.
564 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
570 if (session->status == ISSL_OPEN)
572 if (session->rstat == ISSL_WRITE)
577 if (session->wstat == ISSL_WRITE)
579 return DoWrite(session);
586 int DoWrite(issl_session* session)
588 if (!session->outbuf.size())
591 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
595 CloseSession(session);
600 int err = SSL_get_error(session->sess, ret);
602 if (err == SSL_ERROR_WANT_WRITE)
604 session->wstat = ISSL_WRITE;
607 else if (err == SSL_ERROR_WANT_READ)
609 session->wstat = ISSL_READ;
614 CloseSession(session);
620 session->outbuf = session->outbuf.substr(ret);
625 int DoRead(issl_session* session)
627 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
628 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
630 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
634 // Client closed connection.
635 CloseSession(session);
640 int err = SSL_get_error(session->sess, ret);
642 if (err == SSL_ERROR_WANT_READ)
644 session->rstat = ISSL_READ;
647 else if (err == SSL_ERROR_WANT_WRITE)
649 session->rstat = ISSL_WRITE;
650 MakePollWrite(session);
655 CloseSession(session);
661 // Read successfully 'ret' bytes into inbuf + inbufoffset
662 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
663 // 'buffer' is 'count' long
665 session->inbufoffset += ret;
671 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
672 virtual void OnWhois(User* source, User* dest)
677 // Bugfix, only send this numeric for *our* SSL users
678 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
680 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
684 virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
686 // check if the linking module wants to know about OUR metadata
687 if (extname == "ssl")
689 // check if this user has an swhois field to send
690 if(user->GetExt(extname, dummy))
692 // call this function in the linking module, let it format the data how it
693 // sees fit, and send it on its way. We dont need or want to know how.
694 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
699 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
701 // check if its our metadata key, and its associated with a user
702 if ((target_type == TYPE_USER) && (extname == "ssl"))
704 User* dest = (User*)target;
705 // if they dont already have an ssl flag, accept the remote server's
706 if (!dest->GetExt(extname, dummy))
708 dest->Extend(extname, "ON");
713 bool Handshake(issl_session* session)
717 if (session->outbound)
718 ret = SSL_connect(session->sess);
720 ret = SSL_accept(session->sess);
724 int err = SSL_get_error(session->sess, ret);
726 if (err == SSL_ERROR_WANT_READ)
728 session->rstat = ISSL_READ;
729 session->status = ISSL_HANDSHAKING;
732 else if (err == SSL_ERROR_WANT_WRITE)
734 session->wstat = ISSL_WRITE;
735 session->status = ISSL_HANDSHAKING;
736 MakePollWrite(session);
741 CloseSession(session);
748 // Handshake complete.
749 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
750 User* u = ServerInstance->FindDescriptor(session->fd);
753 if (!u->GetExt("ssl", dummy))
754 u->Extend("ssl", "ON");
757 session->status = ISSL_OPEN;
759 MakePollWrite(session);
765 CloseSession(session);
772 virtual void OnPostConnect(User* user)
774 // This occurs AFTER OnUserConnect so we can be sure the
775 // protocol module has propagated the NICK message.
776 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
778 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
779 std::deque<std::string>* metadata = new std::deque<std::string>;
780 metadata->push_back(user->nick);
781 metadata->push_back("ssl"); // The metadata id
782 metadata->push_back("ON"); // The value to send
783 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
784 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
788 VerifyCertificate(&sessions[user->GetFd()], user);
789 if (sessions[user->GetFd()].sess)
790 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess));
794 void MakePollWrite(issl_session* session)
796 //OnRawSocketWrite(session->fd, NULL, 0);
797 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
800 ServerInstance->SE->WantWrite(eh);
804 virtual void OnBufferFlushed(User* user)
806 if (user->GetExt("ssl"))
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)