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 * ---------------------------------------------------
17 #include <openssl/ssl.h>
18 #include <openssl/err.h>
20 #include "inspircd_config.h"
21 #include "configreader.h"
30 #include "transport.h"
32 /* $ModDesc: Provides SSL support for clients */
33 /* $CompileFlags: `perl extra/openssl_config.pl compile` */
34 /* $LinkerFlags: `perl extra/openssl_config.pl link` */
35 /* $ModDep: transport.h */
37 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
38 enum issl_io_status { ISSL_WRITE, ISSL_READ };
40 static bool SelfSigned = false;
42 bool isin(int port, const std::vector<int> &portlist)
44 for(unsigned int i = 0; i < portlist.size(); i++)
45 if(portlist[i] == port)
53 return ERR_error_string(ERR_get_error(), NULL);
56 /** Represents an SSL user's extra data
58 class issl_session : public classbase
66 unsigned int inbufoffset;
67 char* inbuf; // Buffer OpenSSL reads into.
68 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
78 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
80 /* XXX: This will allow self signed certificates.
81 * In the future if we want an option to not allow this,
82 * we can just return preverify_ok here, and openssl
83 * will boot off self-signed and invalid peer certs.
85 int ve = X509_STORE_CTX_get_error(ctx);
87 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
92 class ModuleSSLOpenSSL : public Module
99 std::vector<int> listenports;
102 issl_session sessions[MAX_DESCRIPTORS];
109 std::string certfile;
111 // std::string crlfile;
116 ModuleSSLOpenSSL(InspIRCd* Me)
119 culllist = new CullList(ServerInstance);
121 ServerInstance->PublishInterface("InspSocketHook", this);
123 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
124 inbufsize = ServerInstance->Config->NetBufferSize;
126 /* Global SSL library initialization*/
128 SSL_load_error_strings();
130 /* Build our SSL context*/
131 ctx = SSL_CTX_new( SSLv23_server_method() );
133 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
135 // Needs the flag as it ignores a plain /rehash
139 virtual void OnRehash(const std::string ¶m)
144 Conf = new ConfigReader(ServerInstance);
146 for (unsigned int i = 0; i < listenports.size(); i++)
148 ServerInstance->Config->DelIOHook(listenports[i]);
153 for (int i = 0; i < Conf->Enumerate("bind"); i++)
155 // For each <bind> tag
156 if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
158 // Get the port we're meant to be listening on with SSL
159 std::string port = Conf->ReadValue("bind", "port", i);
160 irc::portparser portrange(port, false);
162 while ((portno = portrange.GetToken()))
164 if (ServerInstance->Config->AddIOHook(portno, this))
166 listenports.push_back(portno);
167 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
171 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
177 std::string confdir(CONFIG_FILE);
178 // +1 so we the path ends with a /
179 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
181 cafile = Conf->ReadValue("openssl", "cafile", 0);
182 certfile = Conf->ReadValue("openssl", "certfile", 0);
183 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
184 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
186 // Set all the default values needed.
191 certfile = "cert.pem";
197 dhfile = "dhparams.pem";
199 // Prepend relative paths with the path to the config directory.
200 if (cafile[0] != '/')
201 cafile = confdir + cafile;
203 //if(crlfile[0] != '/')
204 // crlfile = confdir + crlfile;
206 if (certfile[0] != '/')
207 certfile = confdir + certfile;
209 if (keyfile[0] != '/')
210 keyfile = confdir + keyfile;
212 if (dhfile[0] != '/')
213 dhfile = confdir + dhfile;
215 /* Load our keys and certificates*/
216 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
218 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
221 if (!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
223 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
226 /* Load the CAs we trust*/
227 if (!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
229 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
232 FILE* dhpfile = fopen(dhfile.c_str(), "r");
237 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
238 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
242 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
244 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
246 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
255 virtual ~ModuleSSLOpenSSL()
261 virtual void OnCleanup(int target_type, void* item)
263 if (target_type == TYPE_USER)
265 userrec* user = (userrec*)item;
267 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
269 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
270 // Potentially there could be multiple SSL modules loaded at once on different ports.
271 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
272 culllist->AddItem(user, "SSL module unloading");
274 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
277 user->GetExt("ssl_cert", tofree);
279 user->Shrink("ssl_cert");
284 virtual void OnUnloadModule(Module* mod, const std::string &name)
288 // We're being unloaded, kill all the users added to the cull list in OnCleanup
289 int numusers = culllist->Apply();
290 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
292 for(unsigned int i = 0; i < listenports.size(); i++)
293 ServerInstance->Config->DelIOHook(listenports[i]);
297 virtual Version GetVersion()
299 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
302 void Implements(char* List)
304 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
305 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
308 virtual char* OnRequest(Request* request)
310 ISHRequest* ISR = (ISHRequest*)request;
311 ServerInstance->Log(DEBUG, "hook OnRequest");
312 if (strcmp("IS_NAME", request->GetId()) == 0)
316 else if (strcmp("IS_HOOK", request->GetId()) == 0)
321 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
323 catch (ModuleException &e)
330 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
332 ServerInstance->Log(DEBUG, "Unhooking socket %08x", ISR->Sock);
333 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
335 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
337 issl_session* session = &sessions[ISR->Sock->GetFd()];
338 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
340 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
342 issl_session* session = &sessions[ISR->Sock->GetFd()];
345 VerifyCertificate(session, (InspSocket*)ISR->Sock);
353 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
355 ServerInstance->Log(DEBUG, "Hook accept %d", fd);
356 issl_session* session = &sessions[fd];
359 session->inbuf = new char[inbufsize];
360 session->inbufoffset = 0;
361 session->sess = SSL_new(ctx);
362 session->status = ISSL_NONE;
364 if (session->sess == NULL)
366 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
370 if (SSL_set_fd(session->sess, fd) == 0)
372 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
379 virtual void OnRawSocketConnect(int fd)
381 issl_session* session = &sessions[fd];
384 session->inbuf = new char[inbufsize];
385 session->inbufoffset = 0;
386 session->sess = SSL_new(ctx);
387 session->status = ISSL_NONE;
389 if (session->sess == NULL)
391 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
395 if (SSL_set_fd(session->sess, fd) == 0)
397 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
404 virtual void OnRawSocketClose(int fd)
406 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
407 CloseSession(&sessions[fd]);
409 EventHandler* user = ServerInstance->SE->GetRef(fd);
411 if ((user) && (user->GetExt("ssl_cert", dummy)))
414 user->GetExt("ssl_cert", tofree);
416 user->Shrink("ssl_cert");
420 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
422 issl_session* session = &sessions[fd];
426 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
428 CloseSession(session);
432 if (session->status == ISSL_HANDSHAKING)
434 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
436 // The handshake isn't finished and it wants to read, try to finish it.
437 if (Handshake(session))
439 // Handshake successfully resumed.
440 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
444 // Couldn't resume handshake.
445 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
451 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
456 // If we resumed the handshake then session->status will be ISSL_OPEN
458 if (session->status == ISSL_OPEN)
460 if (session->wstat == ISSL_READ)
462 if(DoWrite(session) == 0)
466 if (session->rstat == ISSL_READ)
468 int ret = DoRead(session);
472 if (count <= session->inbufoffset)
474 memcpy(buffer, session->inbuf, count);
475 // Move the stuff left in inbuf to the beginning of it
476 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
477 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
478 session->inbufoffset -= count;
479 // Insp uses readresult as the count of how much data there is in buffer, so:
484 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
485 memcpy(buffer, session->inbuf, session->inbufoffset);
487 readresult = session->inbufoffset;
488 // Zero the offset, as there's nothing there..
489 session->inbufoffset = 0;
504 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
506 issl_session* session = &sessions[fd];
510 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
511 CloseSession(session);
515 session->outbuf.append(buffer, count);
517 if (session->status == ISSL_HANDSHAKING)
519 // The handshake isn't finished, try to finish it.
520 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
522 if (Handshake(session))
524 // Handshake successfully resumed.
525 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
529 // Couldn't resume handshake.
530 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
535 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
539 if (session->status == ISSL_OPEN)
541 if (session->rstat == ISSL_WRITE)
546 if (session->wstat == ISSL_WRITE)
548 return DoWrite(session);
555 int DoWrite(issl_session* session)
557 if (!session->outbuf.size())
560 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: To write: %d", session->outbuf.size());
561 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
565 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
566 CloseSession(session);
571 int err = SSL_get_error(session->sess, ret);
573 if (err == SSL_ERROR_WANT_WRITE)
575 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
576 session->wstat = ISSL_WRITE;
579 else if (err == SSL_ERROR_WANT_READ)
581 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
582 session->wstat = ISSL_READ;
587 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
588 CloseSession(session);
594 session->outbuf = session->outbuf.substr(ret);
599 int DoRead(issl_session* session)
601 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
602 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
604 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
608 // Client closed connection.
609 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
610 CloseSession(session);
615 int err = SSL_get_error(session->sess, ret);
617 if (err == SSL_ERROR_WANT_READ)
619 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
620 session->rstat = ISSL_READ;
623 else if (err == SSL_ERROR_WANT_WRITE)
625 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
626 session->rstat = ISSL_WRITE;
631 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
632 CloseSession(session);
638 // Read successfully 'ret' bytes into inbuf + inbufoffset
639 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
640 // 'buffer' is 'count' long
642 session->inbufoffset += ret;
648 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
649 virtual void OnWhois(userrec* source, userrec* dest)
651 // Bugfix, only send this numeric for *our* SSL users
652 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
654 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
658 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
660 // check if the linking module wants to know about OUR metadata
661 if (extname == "ssl")
663 // check if this user has an swhois field to send
664 if(user->GetExt(extname, dummy))
666 // call this function in the linking module, let it format the data how it
667 // sees fit, and send it on its way. We dont need or want to know how.
668 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
673 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
675 // check if its our metadata key, and its associated with a user
676 if ((target_type == TYPE_USER) && (extname == "ssl"))
678 userrec* dest = (userrec*)target;
679 // if they dont already have an ssl flag, accept the remote server's
680 if (!dest->GetExt(extname, dummy))
682 dest->Extend(extname, "ON");
687 bool Handshake(issl_session* session)
689 int ret = SSL_accept(session->sess);
693 int err = SSL_get_error(session->sess, ret);
695 if (err == SSL_ERROR_WANT_READ)
697 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
698 session->rstat = ISSL_READ;
699 session->status = ISSL_HANDSHAKING;
701 else if (err == SSL_ERROR_WANT_WRITE)
703 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
704 session->wstat = ISSL_WRITE;
705 session->status = ISSL_HANDSHAKING;
706 MakePollWrite(session);
710 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
711 CloseSession(session);
718 // Handshake complete.
719 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
721 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
722 userrec* u = ServerInstance->FindDescriptor(session->fd);
725 if (!u->GetExt("ssl", dummy))
726 u->Extend("ssl", "ON");
729 session->status = ISSL_OPEN;
731 MakePollWrite(session);
737 virtual void OnPostConnect(userrec* user)
739 // This occurs AFTER OnUserConnect so we can be sure the
740 // protocol module has propogated the NICK message.
741 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
743 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
744 std::deque<std::string>* metadata = new std::deque<std::string>;
745 metadata->push_back(user->nick);
746 metadata->push_back("ssl"); // The metadata id
747 metadata->push_back("ON"); // The value to send
748 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
749 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
753 VerifyCertificate(&sessions[user->GetFd()], user);
757 void MakePollWrite(issl_session* session)
759 OnRawSocketWrite(session->fd, NULL, 0);
762 void CloseSession(issl_session* session)
766 SSL_shutdown(session->sess);
767 SSL_free(session->sess);
772 delete[] session->inbuf;
775 session->outbuf.clear();
776 session->inbuf = NULL;
777 session->sess = NULL;
778 session->status = ISSL_NONE;
781 void VerifyCertificate(issl_session* session, Extensible* user)
784 ssl_cert* certinfo = new ssl_cert;
786 unsigned char md[EVP_MAX_MD_SIZE];
787 const EVP_MD *digest = EVP_md5();
789 user->Extend("ssl_cert",certinfo);
791 cert = SSL_get_peer_certificate((SSL*)session->sess);
795 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
799 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
803 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
804 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
808 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
809 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
812 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
813 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
815 if (!X509_digest(cert, digest, md, &n))
817 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
821 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
824 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))
826 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
833 class ModuleSSLOpenSSLFactory : public ModuleFactory
836 ModuleSSLOpenSSLFactory()
840 ~ModuleSSLOpenSSLFactory()
844 virtual Module * CreateModule(InspIRCd* Me)
846 return new ModuleSSLOpenSSL(Me);
851 extern "C" void * init_module( void )
853 return new ModuleSSLOpenSSLFactory;