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: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
34 /* $LinkerFlags: pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */
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.
80 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
82 /* XXX: This will allow self signed certificates.
83 * In the future if we want an option to not allow this,
84 * we can just return preverify_ok here, and openssl
85 * will boot off self-signed and invalid peer certs.
87 int ve = X509_STORE_CTX_get_error(ctx);
89 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
94 class ModuleSSLOpenSSL : public Module
101 std::vector<int> listenports;
104 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 contexts:
134 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
136 ctx = SSL_CTX_new( SSLv23_server_method() );
137 clictx = SSL_CTX_new( SSLv23_client_method() );
139 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
140 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
142 // Needs the flag as it ignores a plain /rehash
143 OnRehash(NULL,"ssl");
146 virtual void OnRehash(userrec* user, const std::string ¶m)
151 Conf = new ConfigReader(ServerInstance);
153 for (unsigned int i = 0; i < listenports.size(); i++)
155 ServerInstance->Config->DelIOHook(listenports[i]);
160 for (int i = 0; i < Conf->Enumerate("bind"); i++)
162 // For each <bind> tag
163 if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
165 // Get the port we're meant to be listening on with SSL
166 std::string port = Conf->ReadValue("bind", "port", i);
167 irc::portparser portrange(port, false);
169 while ((portno = portrange.GetToken()))
171 if (ServerInstance->Config->AddIOHook(portno, this))
173 listenports.push_back(portno);
174 for (unsigned int i = 0; i < ServerInstance->stats->BoundPortCount; i++)
175 if (ServerInstance->Config->ports[i] == portno)
176 ServerInstance->Config->openSockfd[i]->SetDescription("ssl");
177 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
181 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
187 std::string confdir(CONFIG_FILE);
188 // +1 so we the path ends with a /
189 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
191 cafile = Conf->ReadValue("openssl", "cafile", 0);
192 certfile = Conf->ReadValue("openssl", "certfile", 0);
193 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
194 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
196 // Set all the default values needed.
201 certfile = "cert.pem";
207 dhfile = "dhparams.pem";
209 // Prepend relative paths with the path to the config directory.
210 if (cafile[0] != '/')
211 cafile = confdir + cafile;
213 //if(crlfile[0] != '/')
214 // crlfile = confdir + crlfile;
216 if (certfile[0] != '/')
217 certfile = confdir + certfile;
219 if (keyfile[0] != '/')
220 keyfile = confdir + keyfile;
222 if (dhfile[0] != '/')
223 dhfile = confdir + dhfile;
225 /* Load our keys and certificates*/
226 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
228 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
231 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)))
233 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
236 /* Load the CAs we trust*/
237 if ((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0)) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
239 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
242 FILE* dhpfile = fopen(dhfile.c_str(), "r");
247 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
248 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
252 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
254 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
256 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
265 virtual ~ModuleSSLOpenSSL()
268 SSL_CTX_free(clictx);
272 virtual void OnCleanup(int target_type, void* item)
274 if (target_type == TYPE_USER)
276 userrec* user = (userrec*)item;
278 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
280 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
281 // Potentially there could be multiple SSL modules loaded at once on different ports.
282 culllist->AddItem(user, "SSL module unloading");
284 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
287 user->GetExt("ssl_cert", tofree);
289 user->Shrink("ssl_cert");
294 virtual void OnUnloadModule(Module* mod, const std::string &name)
298 // We're being unloaded, kill all the users added to the cull list in OnCleanup
301 for(unsigned int i = 0; i < listenports.size(); i++)
303 ServerInstance->Config->DelIOHook(listenports[i]);
304 for (unsigned int j = 0; j < ServerInstance->stats->BoundPortCount; j++)
305 if (ServerInstance->Config->ports[j] == listenports[i])
306 if (ServerInstance->Config->openSockfd[j])
307 ServerInstance->Config->openSockfd[j]->SetDescription("plaintext");
312 virtual Version GetVersion()
314 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
317 void Implements(char* List)
319 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
320 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
323 virtual char* OnRequest(Request* request)
325 ISHRequest* ISR = (ISHRequest*)request;
326 if (strcmp("IS_NAME", request->GetId()) == 0)
330 else if (strcmp("IS_HOOK", request->GetId()) == 0)
335 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
337 catch (ModuleException &e)
344 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
346 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
348 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
350 issl_session* session = &sessions[ISR->Sock->GetFd()];
351 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
353 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
355 issl_session* session = &sessions[ISR->Sock->GetFd()];
358 VerifyCertificate(session, (InspSocket*)ISR->Sock);
366 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
368 issl_session* session = &sessions[fd];
371 session->inbuf = new char[inbufsize];
372 session->inbufoffset = 0;
373 session->sess = SSL_new(ctx);
374 session->status = ISSL_NONE;
375 session->outbound = false;
377 if (session->sess == NULL)
380 if (SSL_set_fd(session->sess, fd) == 0)
382 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
389 virtual void OnRawSocketConnect(int fd)
391 issl_session* session = &sessions[fd];
394 session->inbuf = new char[inbufsize];
395 session->inbufoffset = 0;
396 session->sess = SSL_new(clictx);
397 session->status = ISSL_NONE;
398 session->outbound = true;
400 if (session->sess == NULL)
403 if (SSL_set_fd(session->sess, fd) == 0)
405 ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
412 virtual void OnRawSocketClose(int fd)
414 CloseSession(&sessions[fd]);
416 EventHandler* user = ServerInstance->SE->GetRef(fd);
418 if ((user) && (user->GetExt("ssl_cert", dummy)))
421 user->GetExt("ssl_cert", tofree);
423 user->Shrink("ssl_cert");
427 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
429 issl_session* session = &sessions[fd];
434 CloseSession(session);
438 if (session->status == ISSL_HANDSHAKING)
440 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
442 // The handshake isn't finished and it wants to read, try to finish it.
443 if (!Handshake(session))
445 // Couldn't resume handshake.
455 // If we resumed the handshake then session->status will be ISSL_OPEN
457 if (session->status == ISSL_OPEN)
459 if (session->wstat == ISSL_READ)
461 if(DoWrite(session) == 0)
465 if (session->rstat == ISSL_READ)
467 int ret = DoRead(session);
471 if (count <= session->inbufoffset)
473 memcpy(buffer, session->inbuf, count);
474 // Move the stuff left in inbuf to the beginning of it
475 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
476 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
477 session->inbufoffset -= count;
478 // Insp uses readresult as the count of how much data there is in buffer, so:
483 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
484 memcpy(buffer, session->inbuf, session->inbufoffset);
486 readresult = session->inbufoffset;
487 // Zero the offset, as there's nothing there..
488 session->inbufoffset = 0;
503 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
505 issl_session* session = &sessions[fd];
509 CloseSession(session);
513 session->outbuf.append(buffer, count);
515 if (session->status == ISSL_HANDSHAKING)
517 // The handshake isn't finished, try to finish it.
518 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
522 if (session->status == ISSL_OPEN)
524 if (session->rstat == ISSL_WRITE)
527 if (session->wstat == ISSL_WRITE)
528 return DoWrite(session);
534 int DoWrite(issl_session* session)
536 if (!session->outbuf.size())
539 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
543 CloseSession(session);
548 int err = SSL_get_error(session->sess, ret);
550 if (err == SSL_ERROR_WANT_WRITE)
552 session->wstat = ISSL_WRITE;
555 else if (err == SSL_ERROR_WANT_READ)
557 session->wstat = ISSL_READ;
562 CloseSession(session);
568 session->outbuf = session->outbuf.substr(ret);
573 int DoRead(issl_session* session)
575 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
576 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
578 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
582 // Client closed connection.
583 CloseSession(session);
588 int err = SSL_get_error(session->sess, ret);
590 if (err == SSL_ERROR_WANT_READ)
592 session->rstat = ISSL_READ;
595 else if (err == SSL_ERROR_WANT_WRITE)
597 session->rstat = ISSL_WRITE;
602 CloseSession(session);
608 // Read successfully 'ret' bytes into inbuf + inbufoffset
609 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
610 // 'buffer' is 'count' long
612 session->inbufoffset += ret;
618 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
619 virtual void OnWhois(userrec* source, userrec* dest)
621 // Bugfix, only send this numeric for *our* SSL users
622 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
624 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
628 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
630 // check if the linking module wants to know about OUR metadata
631 if (extname == "ssl")
633 // check if this user has an swhois field to send
634 if(user->GetExt(extname, dummy))
636 // call this function in the linking module, let it format the data how it
637 // sees fit, and send it on its way. We dont need or want to know how.
638 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
643 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
645 // check if its our metadata key, and its associated with a user
646 if ((target_type == TYPE_USER) && (extname == "ssl"))
648 userrec* dest = (userrec*)target;
649 // if they dont already have an ssl flag, accept the remote server's
650 if (!dest->GetExt(extname, dummy))
652 dest->Extend(extname, "ON");
657 bool Handshake(issl_session* session)
661 if (session->outbound)
662 ret = SSL_connect(session->sess);
664 ret = SSL_accept(session->sess);
668 int err = SSL_get_error(session->sess, ret);
670 if (err == SSL_ERROR_WANT_READ)
672 session->rstat = ISSL_READ;
673 session->status = ISSL_HANDSHAKING;
675 else if (err == SSL_ERROR_WANT_WRITE)
677 session->wstat = ISSL_WRITE;
678 session->status = ISSL_HANDSHAKING;
679 MakePollWrite(session);
683 CloseSession(session);
690 // Handshake complete.
691 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
692 userrec* u = ServerInstance->FindDescriptor(session->fd);
695 if (!u->GetExt("ssl", dummy))
696 u->Extend("ssl", "ON");
699 session->status = ISSL_OPEN;
701 MakePollWrite(session);
707 CloseSession(session);
714 virtual void OnPostConnect(userrec* user)
716 // This occurs AFTER OnUserConnect so we can be sure the
717 // protocol module has propogated the NICK message.
718 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
720 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
721 std::deque<std::string>* metadata = new std::deque<std::string>;
722 metadata->push_back(user->nick);
723 metadata->push_back("ssl"); // The metadata id
724 metadata->push_back("ON"); // The value to send
725 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
726 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
730 VerifyCertificate(&sessions[user->GetFd()], user);
734 void MakePollWrite(issl_session* session)
736 OnRawSocketWrite(session->fd, NULL, 0);
739 void CloseSession(issl_session* session)
743 SSL_shutdown(session->sess);
744 SSL_free(session->sess);
749 delete[] session->inbuf;
752 session->outbuf.clear();
753 session->inbuf = NULL;
754 session->sess = NULL;
755 session->status = ISSL_NONE;
758 void VerifyCertificate(issl_session* session, Extensible* user)
761 ssl_cert* certinfo = new ssl_cert;
763 unsigned char md[EVP_MAX_MD_SIZE];
764 const EVP_MD *digest = EVP_md5();
766 user->Extend("ssl_cert",certinfo);
768 cert = SSL_get_peer_certificate((SSL*)session->sess);
772 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
776 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
780 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
781 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
785 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
786 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
789 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
790 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
792 if (!X509_digest(cert, digest, md, &n))
794 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
798 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
801 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))
803 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
810 class ModuleSSLOpenSSLFactory : public ModuleFactory
813 ModuleSSLOpenSSLFactory()
817 ~ModuleSSLOpenSSLFactory()
821 virtual Module * CreateModule(InspIRCd* Me)
823 return new ModuleSSLOpenSSL(Me);
828 extern "C" void * init_module( void )
830 return new ModuleSSLOpenSSLFactory;