1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
20 #include <openssl/ssl.h>
21 #include <openssl/err.h>
23 #include "inspircd_config.h"
24 #include "configreader.h"
33 #include "transport.h"
35 /* $ModDesc: Provides SSL support for clients */
36 /* $CompileFlags: `perl extra/openssl_config.pl compile` */
37 /* $LinkerFlags: `perl extra/openssl_config.pl link` */
38 /* $ModDep: transport.h */
40 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
41 enum issl_io_status { ISSL_WRITE, ISSL_READ };
43 static bool SelfSigned = false;
45 bool isin(int port, const std::vector<int> &portlist)
47 for(unsigned int i = 0; i < portlist.size(); i++)
48 if(portlist[i] == port)
56 return ERR_error_string(ERR_get_error(), NULL);
59 /** Represents an SSL user's extra data
61 class issl_session : public classbase
69 unsigned int inbufoffset;
70 char* inbuf; // Buffer OpenSSL reads into.
71 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
81 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
83 /* XXX: This will allow self signed certificates.
84 * In the future if we want an option to not allow this,
85 * we can just return preverify_ok here, and openssl
86 * will boot off self-signed and invalid peer certs.
88 int ve = X509_STORE_CTX_get_error(ctx);
90 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
95 class ModuleSSLOpenSSL : public Module
102 std::vector<int> listenports;
105 issl_session sessions[MAX_DESCRIPTORS];
112 std::string certfile;
114 // std::string crlfile;
119 ModuleSSLOpenSSL(InspIRCd* Me)
122 culllist = new CullList(ServerInstance);
124 ServerInstance->PublishInterface("InspSocketHook", this);
126 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
127 inbufsize = ServerInstance->Config->NetBufferSize;
129 /* Global SSL library initialization*/
131 SSL_load_error_strings();
133 /* Build our SSL context*/
134 ctx = SSL_CTX_new( SSLv23_server_method() );
136 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
138 // Needs the flag as it ignores a plain /rehash
142 virtual void OnRehash(const std::string ¶m)
147 Conf = new ConfigReader(ServerInstance);
149 for (unsigned int i = 0; i < listenports.size(); i++)
151 ServerInstance->Config->DelIOHook(listenports[i]);
156 for (int i = 0; i < Conf->Enumerate("bind"); i++)
158 // For each <bind> tag
159 if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
161 // Get the port we're meant to be listening on with SSL
162 std::string port = Conf->ReadValue("bind", "port", i);
163 irc::portparser portrange(port, false);
165 while ((portno = portrange.GetToken()))
167 if (ServerInstance->Config->AddIOHook(portno, this))
169 listenports.push_back(portno);
170 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
174 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
180 std::string confdir(CONFIG_FILE);
181 // +1 so we the path ends with a /
182 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
184 cafile = Conf->ReadValue("openssl", "cafile", 0);
185 certfile = Conf->ReadValue("openssl", "certfile", 0);
186 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
187 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
189 // Set all the default values needed.
194 certfile = "cert.pem";
200 dhfile = "dhparams.pem";
202 // Prepend relative paths with the path to the config directory.
203 if (cafile[0] != '/')
204 cafile = confdir + cafile;
206 //if(crlfile[0] != '/')
207 // crlfile = confdir + crlfile;
209 if (certfile[0] != '/')
210 certfile = confdir + certfile;
212 if (keyfile[0] != '/')
213 keyfile = confdir + keyfile;
215 if (dhfile[0] != '/')
216 dhfile = confdir + dhfile;
218 /* Load our keys and certificates*/
219 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
221 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
224 if (!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
226 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
229 /* Load the CAs we trust*/
230 if (!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
232 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
235 FILE* dhpfile = fopen(dhfile.c_str(), "r");
240 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
241 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
245 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
247 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
249 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
258 virtual ~ModuleSSLOpenSSL()
264 virtual void OnCleanup(int target_type, void* item)
266 if (target_type == TYPE_USER)
268 userrec* user = (userrec*)item;
270 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
272 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
273 // Potentially there could be multiple SSL modules loaded at once on different ports.
274 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
275 culllist->AddItem(user, "SSL module unloading");
277 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
280 user->GetExt("ssl_cert", tofree);
282 user->Shrink("ssl_cert");
287 virtual void OnUnloadModule(Module* mod, const std::string &name)
291 // We're being unloaded, kill all the users added to the cull list in OnCleanup
292 int numusers = culllist->Apply();
293 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
295 for(unsigned int i = 0; i < listenports.size(); i++)
296 ServerInstance->Config->DelIOHook(listenports[i]);
300 virtual Version GetVersion()
302 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
305 void Implements(char* List)
307 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
308 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
311 virtual char* OnRequest(Request* request)
313 ISHRequest* ISR = (ISHRequest*)request;
314 ServerInstance->Log(DEBUG, "hook OnRequest");
315 if (strcmp("IS_NAME", request->GetId()) == 0)
319 else if (strcmp("IS_HOOK", request->GetId()) == 0)
324 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
326 catch (ModuleException &e)
333 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
335 ServerInstance->Log(DEBUG, "Unhooking socket %08x", ISR->Sock);
336 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
338 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
340 issl_session* session = &sessions[ISR->Sock->GetFd()];
341 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
343 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
345 issl_session* session = &sessions[ISR->Sock->GetFd()];
348 VerifyCertificate(session, (InspSocket*)ISR->Sock);
356 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
358 ServerInstance->Log(DEBUG, "Hook accept %d", fd);
359 issl_session* session = &sessions[fd];
362 session->inbuf = new char[inbufsize];
363 session->inbufoffset = 0;
364 session->sess = SSL_new(ctx);
365 session->status = ISSL_NONE;
367 if (session->sess == NULL)
369 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
373 if (SSL_set_fd(session->sess, fd) == 0)
375 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
382 virtual void OnRawSocketConnect(int fd)
384 issl_session* session = &sessions[fd];
387 session->inbuf = new char[inbufsize];
388 session->inbufoffset = 0;
389 session->sess = SSL_new(ctx);
390 session->status = ISSL_NONE;
392 if (session->sess == NULL)
394 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
398 if (SSL_set_fd(session->sess, fd) == 0)
400 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
407 virtual void OnRawSocketClose(int fd)
409 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
410 CloseSession(&sessions[fd]);
412 EventHandler* user = ServerInstance->SE->GetRef(fd);
414 if ((user) && (user->GetExt("ssl_cert", dummy)))
417 user->GetExt("ssl_cert", tofree);
419 user->Shrink("ssl_cert");
423 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
425 issl_session* session = &sessions[fd];
429 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
431 CloseSession(session);
435 if (session->status == ISSL_HANDSHAKING)
437 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
439 // The handshake isn't finished and it wants to read, try to finish it.
440 if (Handshake(session))
442 // Handshake successfully resumed.
443 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
447 // Couldn't resume handshake.
448 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
454 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
459 // If we resumed the handshake then session->status will be ISSL_OPEN
461 if (session->status == ISSL_OPEN)
463 if (session->wstat == ISSL_READ)
465 if(DoWrite(session) == 0)
469 if (session->rstat == ISSL_READ)
471 int ret = DoRead(session);
475 if (count <= session->inbufoffset)
477 memcpy(buffer, session->inbuf, count);
478 // Move the stuff left in inbuf to the beginning of it
479 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
480 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
481 session->inbufoffset -= count;
482 // Insp uses readresult as the count of how much data there is in buffer, so:
487 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
488 memcpy(buffer, session->inbuf, session->inbufoffset);
490 readresult = session->inbufoffset;
491 // Zero the offset, as there's nothing there..
492 session->inbufoffset = 0;
507 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
509 issl_session* session = &sessions[fd];
513 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
514 CloseSession(session);
518 session->outbuf.append(buffer, count);
520 if (session->status == ISSL_HANDSHAKING)
522 // The handshake isn't finished, try to finish it.
523 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
525 if (Handshake(session))
527 // Handshake successfully resumed.
528 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
532 // Couldn't resume handshake.
533 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
538 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
542 if (session->status == ISSL_OPEN)
544 if (session->rstat == ISSL_WRITE)
549 if (session->wstat == ISSL_WRITE)
551 return DoWrite(session);
558 int DoWrite(issl_session* session)
560 if (!session->outbuf.size())
563 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: To write: %d", session->outbuf.size());
564 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
568 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
569 CloseSession(session);
574 int err = SSL_get_error(session->sess, ret);
576 if (err == SSL_ERROR_WANT_WRITE)
578 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
579 session->wstat = ISSL_WRITE;
582 else if (err == SSL_ERROR_WANT_READ)
584 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
585 session->wstat = ISSL_READ;
590 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
591 CloseSession(session);
597 session->outbuf = session->outbuf.substr(ret);
602 int DoRead(issl_session* session)
604 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
605 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
607 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
611 // Client closed connection.
612 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
613 CloseSession(session);
618 int err = SSL_get_error(session->sess, ret);
620 if (err == SSL_ERROR_WANT_READ)
622 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
623 session->rstat = ISSL_READ;
626 else if (err == SSL_ERROR_WANT_WRITE)
628 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
629 session->rstat = ISSL_WRITE;
634 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
635 CloseSession(session);
641 // Read successfully 'ret' bytes into inbuf + inbufoffset
642 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
643 // 'buffer' is 'count' long
645 session->inbufoffset += ret;
651 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
652 virtual void OnWhois(userrec* source, userrec* dest)
654 // Bugfix, only send this numeric for *our* SSL users
655 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
657 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
661 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
663 // check if the linking module wants to know about OUR metadata
664 if (extname == "ssl")
666 // check if this user has an swhois field to send
667 if(user->GetExt(extname, dummy))
669 // call this function in the linking module, let it format the data how it
670 // sees fit, and send it on its way. We dont need or want to know how.
671 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
676 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
678 // check if its our metadata key, and its associated with a user
679 if ((target_type == TYPE_USER) && (extname == "ssl"))
681 userrec* dest = (userrec*)target;
682 // if they dont already have an ssl flag, accept the remote server's
683 if (!dest->GetExt(extname, dummy))
685 dest->Extend(extname, "ON");
690 bool Handshake(issl_session* session)
692 int ret = SSL_accept(session->sess);
696 int err = SSL_get_error(session->sess, ret);
698 if (err == SSL_ERROR_WANT_READ)
700 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
701 session->rstat = ISSL_READ;
702 session->status = ISSL_HANDSHAKING;
704 else if (err == SSL_ERROR_WANT_WRITE)
706 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
707 session->wstat = ISSL_WRITE;
708 session->status = ISSL_HANDSHAKING;
709 MakePollWrite(session);
713 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
714 CloseSession(session);
721 // Handshake complete.
722 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
724 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
725 userrec* u = ServerInstance->FindDescriptor(session->fd);
728 if (!u->GetExt("ssl", dummy))
729 u->Extend("ssl", "ON");
732 session->status = ISSL_OPEN;
734 MakePollWrite(session);
740 virtual void OnPostConnect(userrec* user)
742 // This occurs AFTER OnUserConnect so we can be sure the
743 // protocol module has propogated the NICK message.
744 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
746 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
747 std::deque<std::string>* metadata = new std::deque<std::string>;
748 metadata->push_back(user->nick);
749 metadata->push_back("ssl"); // The metadata id
750 metadata->push_back("ON"); // The value to send
751 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
752 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
756 VerifyCertificate(&sessions[user->GetFd()], user);
760 void MakePollWrite(issl_session* session)
762 OnRawSocketWrite(session->fd, NULL, 0);
765 void CloseSession(issl_session* session)
769 SSL_shutdown(session->sess);
770 SSL_free(session->sess);
775 delete[] session->inbuf;
778 session->outbuf.clear();
779 session->inbuf = NULL;
780 session->sess = NULL;
781 session->status = ISSL_NONE;
784 void VerifyCertificate(issl_session* session, Extensible* user)
787 ssl_cert* certinfo = new ssl_cert;
789 unsigned char md[EVP_MAX_MD_SIZE];
790 const EVP_MD *digest = EVP_md5();
792 user->Extend("ssl_cert",certinfo);
794 cert = SSL_get_peer_certificate((SSL*)session->sess);
798 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
802 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
806 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
807 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
811 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
812 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
815 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
816 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
818 if (!X509_digest(cert, digest, md, &n))
820 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
824 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
827 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))
829 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
836 class ModuleSSLOpenSSLFactory : public ModuleFactory
839 ModuleSSLOpenSSLFactory()
843 ~ModuleSSLOpenSSLFactory()
847 virtual Module * CreateModule(InspIRCd* Me)
849 return new ModuleSSLOpenSSL(Me);
854 extern "C" void * init_module( void )
856 return new ModuleSSLOpenSSLFactory;