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[MAX_DESCRIPTORS];
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 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
137 inbufsize = ServerInstance->Config->NetBufferSize;
139 /* Global SSL library initialization*/
141 SSL_load_error_strings();
143 /* Build our SSL contexts:
144 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
146 ctx = SSL_CTX_new( SSLv23_server_method() );
147 clictx = SSL_CTX_new( SSLv23_client_method() );
149 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
150 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
152 // Needs the flag as it ignores a plain /rehash
153 OnRehash(NULL,"ssl");
154 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup, I_On005Numeric,
155 I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect, I_OnHookUserIO };
156 ServerInstance->Modules->Attach(eventlist, this, 16);
159 virtual void OnHookUserIO(User* user, const std::string &targetip)
161 if (!user->io && isin(targetip,user->GetPort(), listenports))
163 /* Hook the user with our module */
168 virtual void OnRehash(User* user, const std::string ¶m)
170 ConfigReader Conf(ServerInstance);
176 for(int index = 0; index < Conf.Enumerate("bind"); index++)
178 // For each <bind> tag
179 std::string x = Conf.ReadValue("bind", "type", index);
180 if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "openssl"))
182 // Get the port we're meant to be listening on with SSL
183 std::string port = Conf.ReadValue("bind", "port", index);
184 std::string addr = Conf.ReadValue("bind", "address", index);
186 irc::portparser portrange(port, false);
188 while ((portno = portrange.GetToken()))
193 listenports.push_back(addr + ":" + ConvToStr(portno));
195 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
196 if ((ServerInstance->Config->ports[i]->GetPort() == portno) && (ServerInstance->Config->ports[i]->GetIP() == addr))
197 ServerInstance->Config->ports[i]->SetDescription("ssl");
198 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", portno);
200 sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
202 catch (ModuleException &e)
204 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.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 an other SSL or similar module loaded?", portno, e.GetReason());
210 if (!sslports.empty())
211 sslports.erase(sslports.end() - 1);
218 std::string confdir(ServerInstance->ConfigFileName);
219 // +1 so we the path ends with a /
220 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
222 cafile = Conf.ReadValue("openssl", "cafile", 0);
223 certfile = Conf.ReadValue("openssl", "certfile", 0);
224 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
225 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
227 // Set all the default values needed.
231 if (certfile.empty())
232 certfile = "cert.pem";
238 dhfile = "dhparams.pem";
240 // Prepend relative paths with the path to the config directory.
241 if (cafile[0] != '/')
242 cafile = confdir + cafile;
244 if (certfile[0] != '/')
245 certfile = confdir + certfile;
247 if (keyfile[0] != '/')
248 keyfile = confdir + keyfile;
250 if (dhfile[0] != '/')
251 dhfile = confdir + dhfile;
253 /* Load our keys and certificates
254 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
256 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
258 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
259 ERR_print_errors_cb(error_callback, this);
262 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)))
264 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
265 ERR_print_errors_cb(error_callback, this);
268 /* Load the CAs we trust*/
269 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
271 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
272 ERR_print_errors_cb(error_callback, this);
275 FILE* dhpfile = fopen(dhfile.c_str(), "r");
280 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
281 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
285 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
286 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
288 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
289 ERR_print_errors_cb(error_callback, this);
296 virtual void On005Numeric(std::string &output)
298 output.append(" SSL=" + sslports);
301 virtual ~ModuleSSLOpenSSL()
304 SSL_CTX_free(clictx);
307 virtual void OnCleanup(int target_type, void* item)
309 if (target_type == TYPE_USER)
311 User* user = (User*)item;
313 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && user->io == this)
315 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
316 // Potentially there could be multiple SSL modules loaded at once on different ports.
317 User::QuitUser(ServerInstance, user, "SSL module unloading");
319 if (user->GetExt("ssl_cert", dummy))
322 user->GetExt("ssl_cert", tofree);
324 user->Shrink("ssl_cert");
331 virtual void OnUnloadModule(Module* mod, const std::string &name)
335 for(unsigned int i = 0; i < listenports.size(); i++)
337 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
338 if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
339 ServerInstance->Config->ports[j]->SetDescription("plaintext");
344 virtual Version GetVersion()
346 return Version(1, 2, 0, 0, VF_VENDOR, API_VERSION);
350 virtual const char* OnRequest(Request* request)
352 ISHRequest* ISR = (ISHRequest*)request;
353 if (strcmp("IS_NAME", request->GetId()) == 0)
357 else if (strcmp("IS_HOOK", request->GetId()) == 0)
359 const char* ret = "OK";
362 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? "OK" : NULL;
364 catch (ModuleException &e)
371 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
373 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? "OK" : NULL;
375 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
377 if (ISR->Sock->GetFd() < 0)
380 issl_session* session = &sessions[ISR->Sock->GetFd()];
381 return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
383 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
385 issl_session* session = &sessions[ISR->Sock->GetFd()];
388 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
396 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
398 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
399 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
402 issl_session* session = &sessions[fd];
405 session->inbuf = new char[inbufsize];
406 session->inbufoffset = 0;
407 session->sess = SSL_new(ctx);
408 session->status = ISSL_NONE;
409 session->outbound = false;
411 if (session->sess == NULL)
414 if (SSL_set_fd(session->sess, fd) == 0)
416 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
423 virtual void OnRawSocketConnect(int fd)
425 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
426 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
429 issl_session* session = &sessions[fd];
432 session->inbuf = new char[inbufsize];
433 session->inbufoffset = 0;
434 session->sess = SSL_new(clictx);
435 session->status = ISSL_NONE;
436 session->outbound = true;
438 if (session->sess == NULL)
441 if (SSL_set_fd(session->sess, fd) == 0)
443 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
450 virtual void OnRawSocketClose(int fd)
452 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
453 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
456 CloseSession(&sessions[fd]);
458 EventHandler* user = ServerInstance->SE->GetRef(fd);
460 if ((user) && (user->GetExt("ssl_cert", dummy)))
463 user->GetExt("ssl_cert", tofree);
465 user->Shrink("ssl_cert");
469 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
471 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
472 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
475 issl_session* session = &sessions[fd];
480 CloseSession(session);
484 if (session->status == ISSL_HANDSHAKING)
486 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
488 // The handshake isn't finished and it wants to read, try to finish it.
489 if (!Handshake(session))
491 // Couldn't resume handshake.
502 // If we resumed the handshake then session->status will be ISSL_OPEN
504 if (session->status == ISSL_OPEN)
506 if (session->wstat == ISSL_READ)
508 if(DoWrite(session) == 0)
512 if (session->rstat == ISSL_READ)
514 int ret = DoRead(session);
518 if (count <= session->inbufoffset)
520 memcpy(buffer, session->inbuf, count);
521 // Move the stuff left in inbuf to the beginning of it
522 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
523 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
524 session->inbufoffset -= count;
525 // Insp uses readresult as the count of how much data there is in buffer, so:
530 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
531 memcpy(buffer, session->inbuf, session->inbufoffset);
533 readresult = session->inbufoffset;
534 // Zero the offset, as there's nothing there..
535 session->inbufoffset = 0;
546 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
548 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
549 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
552 issl_session* session = &sessions[fd];
556 CloseSession(session);
560 session->outbuf.append(buffer, count);
561 MakePollWrite(session);
563 if (session->status == ISSL_HANDSHAKING)
565 // The handshake isn't finished, try to finish it.
566 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
572 if (session->status == ISSL_OPEN)
574 if (session->rstat == ISSL_WRITE)
579 if (session->wstat == ISSL_WRITE)
581 return DoWrite(session);
588 int DoWrite(issl_session* session)
590 if (!session->outbuf.size())
593 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
597 CloseSession(session);
602 int err = SSL_get_error(session->sess, ret);
604 if (err == SSL_ERROR_WANT_WRITE)
606 session->wstat = ISSL_WRITE;
609 else if (err == SSL_ERROR_WANT_READ)
611 session->wstat = ISSL_READ;
616 CloseSession(session);
622 session->outbuf = session->outbuf.substr(ret);
627 int DoRead(issl_session* session)
629 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
630 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
632 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
636 // Client closed connection.
637 CloseSession(session);
642 int err = SSL_get_error(session->sess, ret);
644 if (err == SSL_ERROR_WANT_READ)
646 session->rstat = ISSL_READ;
649 else if (err == SSL_ERROR_WANT_WRITE)
651 session->rstat = ISSL_WRITE;
652 MakePollWrite(session);
657 CloseSession(session);
663 // Read successfully 'ret' bytes into inbuf + inbufoffset
664 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
665 // 'buffer' is 'count' long
667 session->inbufoffset += ret;
673 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
674 virtual void OnWhois(User* source, User* dest)
679 // Bugfix, only send this numeric for *our* SSL users
680 if (dest->GetExt("ssl", dummy) || ((IS_LOCAL(dest) && dest->io == this)))
682 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
686 virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
688 // check if the linking module wants to know about OUR metadata
689 if (extname == "ssl")
691 // check if this user has an swhois field to send
692 if(user->GetExt(extname, dummy))
694 // call this function in the linking module, let it format the data how it
695 // sees fit, and send it on its way. We dont need or want to know how.
696 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
701 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
703 // check if its our metadata key, and its associated with a user
704 if ((target_type == TYPE_USER) && (extname == "ssl"))
706 User* dest = (User*)target;
707 // if they dont already have an ssl flag, accept the remote server's
708 if (!dest->GetExt(extname, dummy))
710 dest->Extend(extname, "ON");
715 bool Handshake(issl_session* session)
719 if (session->outbound)
720 ret = SSL_connect(session->sess);
722 ret = SSL_accept(session->sess);
726 int err = SSL_get_error(session->sess, ret);
728 if (err == SSL_ERROR_WANT_READ)
730 session->rstat = ISSL_READ;
731 session->status = ISSL_HANDSHAKING;
734 else if (err == SSL_ERROR_WANT_WRITE)
736 session->wstat = ISSL_WRITE;
737 session->status = ISSL_HANDSHAKING;
738 MakePollWrite(session);
743 CloseSession(session);
750 // Handshake complete.
751 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
752 User* u = ServerInstance->FindDescriptor(session->fd);
755 if (!u->GetExt("ssl", dummy))
756 u->Extend("ssl", "ON");
759 session->status = ISSL_OPEN;
761 MakePollWrite(session);
767 CloseSession(session);
774 virtual void OnPostConnect(User* user)
776 // This occurs AFTER OnUserConnect so we can be sure the
777 // protocol module has propagated the NICK message.
778 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
780 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
781 std::deque<std::string>* metadata = new std::deque<std::string>;
782 metadata->push_back(user->nick);
783 metadata->push_back("ssl"); // The metadata id
784 metadata->push_back("ON"); // The value to send
785 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
786 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
790 VerifyCertificate(&sessions[user->GetFd()], user);
791 if (sessions[user->GetFd()].sess)
792 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess));
796 void MakePollWrite(issl_session* session)
798 //OnRawSocketWrite(session->fd, NULL, 0);
799 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
802 ServerInstance->SE->WantWrite(eh);
806 virtual void OnBufferFlushed(User* user)
808 if (user->GetExt("ssl"))
810 issl_session* session = &sessions[user->GetFd()];
811 if (session && session->outbuf.size())
812 OnRawSocketWrite(user->GetFd(), NULL, 0);
816 void CloseSession(issl_session* session)
820 SSL_shutdown(session->sess);
821 SSL_free(session->sess);
826 delete[] session->inbuf;
829 session->outbuf.clear();
830 session->inbuf = NULL;
831 session->sess = NULL;
832 session->status = ISSL_NONE;
835 void VerifyCertificate(issl_session* session, Extensible* user)
837 if (!session->sess || !user)
841 ssl_cert* certinfo = new ssl_cert;
843 unsigned char md[EVP_MAX_MD_SIZE];
844 const EVP_MD *digest = EVP_md5();
846 user->Extend("ssl_cert",certinfo);
848 cert = SSL_get_peer_certificate((SSL*)session->sess);
852 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
856 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
860 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
861 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
865 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
866 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
869 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
870 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
872 if (!X509_digest(cert, digest, md, &n))
874 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
878 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
881 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))
883 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
890 static int error_callback(const char *str, size_t len, void *u)
892 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
893 mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
897 MODULE_INIT(ModuleSSLOpenSSL)