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: 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.
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
136 OnRehash(NULL,"ssl");
139 virtual void OnRehash(userrec* user, 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 for (unsigned int i = 0; i < ServerInstance->stats->BoundPortCount; i++)
168 if (ServerInstance->Config->ports[i] == portno)
169 ServerInstance->Config->openSockfd[i]->SetDescription("ssl");
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 culllist->AddItem(user, "SSL module unloading");
276 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
279 user->GetExt("ssl_cert", tofree);
281 user->Shrink("ssl_cert");
286 virtual void OnUnloadModule(Module* mod, const std::string &name)
290 // We're being unloaded, kill all the users added to the cull list in OnCleanup
293 for(unsigned int i = 0; i < listenports.size(); i++)
295 ServerInstance->Config->DelIOHook(listenports[i]);
296 for (unsigned int j = 0; j < ServerInstance->stats->BoundPortCount; j++)
297 if (ServerInstance->Config->ports[j] == listenports[i])
298 if (ServerInstance->Config->openSockfd[j])
299 ServerInstance->Config->openSockfd[j]->SetDescription("plaintext");
304 virtual Version GetVersion()
306 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
309 void Implements(char* List)
311 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
312 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
315 virtual char* OnRequest(Request* request)
317 ISHRequest* ISR = (ISHRequest*)request;
318 if (strcmp("IS_NAME", request->GetId()) == 0)
322 else if (strcmp("IS_HOOK", request->GetId()) == 0)
327 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
329 catch (ModuleException &e)
336 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
338 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
340 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
342 issl_session* session = &sessions[ISR->Sock->GetFd()];
343 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
345 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
347 issl_session* session = &sessions[ISR->Sock->GetFd()];
350 VerifyCertificate(session, (InspSocket*)ISR->Sock);
358 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
360 issl_session* session = &sessions[fd];
363 session->inbuf = new char[inbufsize];
364 session->inbufoffset = 0;
365 session->sess = SSL_new(ctx);
366 session->status = ISSL_NONE;
368 if (session->sess == NULL)
371 if (SSL_set_fd(session->sess, fd) == 0)
377 virtual void OnRawSocketConnect(int fd)
379 issl_session* session = &sessions[fd];
382 session->inbuf = new char[inbufsize];
383 session->inbufoffset = 0;
384 session->sess = SSL_new(ctx);
385 session->status = ISSL_NONE;
387 if (session->sess == NULL)
390 if (SSL_set_fd(session->sess, fd) == 0)
396 virtual void OnRawSocketClose(int fd)
398 CloseSession(&sessions[fd]);
400 EventHandler* user = ServerInstance->SE->GetRef(fd);
402 if ((user) && (user->GetExt("ssl_cert", dummy)))
405 user->GetExt("ssl_cert", tofree);
407 user->Shrink("ssl_cert");
411 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
413 issl_session* session = &sessions[fd];
418 CloseSession(session);
422 if (session->status == ISSL_HANDSHAKING)
424 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
426 // The handshake isn't finished and it wants to read, try to finish it.
427 if (!Handshake(session))
429 // Couldn't resume handshake.
439 // If we resumed the handshake then session->status will be ISSL_OPEN
441 if (session->status == ISSL_OPEN)
443 if (session->wstat == ISSL_READ)
445 if(DoWrite(session) == 0)
449 if (session->rstat == ISSL_READ)
451 int ret = DoRead(session);
455 if (count <= session->inbufoffset)
457 memcpy(buffer, session->inbuf, count);
458 // Move the stuff left in inbuf to the beginning of it
459 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
460 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
461 session->inbufoffset -= count;
462 // Insp uses readresult as the count of how much data there is in buffer, so:
467 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
468 memcpy(buffer, session->inbuf, session->inbufoffset);
470 readresult = session->inbufoffset;
471 // Zero the offset, as there's nothing there..
472 session->inbufoffset = 0;
487 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
489 issl_session* session = &sessions[fd];
493 CloseSession(session);
497 session->outbuf.append(buffer, count);
499 if (session->status == ISSL_HANDSHAKING)
501 // The handshake isn't finished, try to finish it.
502 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
506 if (session->status == ISSL_OPEN)
508 if (session->rstat == ISSL_WRITE)
511 if (session->wstat == ISSL_WRITE)
512 return DoWrite(session);
518 int DoWrite(issl_session* session)
520 if (!session->outbuf.size())
523 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
527 CloseSession(session);
532 int err = SSL_get_error(session->sess, ret);
534 if (err == SSL_ERROR_WANT_WRITE)
536 session->wstat = ISSL_WRITE;
539 else if (err == SSL_ERROR_WANT_READ)
541 session->wstat = ISSL_READ;
546 CloseSession(session);
552 session->outbuf = session->outbuf.substr(ret);
557 int DoRead(issl_session* session)
559 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
560 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
562 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
566 // Client closed connection.
567 CloseSession(session);
572 int err = SSL_get_error(session->sess, ret);
574 if (err == SSL_ERROR_WANT_READ)
576 session->rstat = ISSL_READ;
579 else if (err == SSL_ERROR_WANT_WRITE)
581 session->rstat = ISSL_WRITE;
586 CloseSession(session);
592 // Read successfully 'ret' bytes into inbuf + inbufoffset
593 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
594 // 'buffer' is 'count' long
596 session->inbufoffset += ret;
602 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
603 virtual void OnWhois(userrec* source, userrec* dest)
605 // Bugfix, only send this numeric for *our* SSL users
606 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
608 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
612 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
614 // check if the linking module wants to know about OUR metadata
615 if (extname == "ssl")
617 // check if this user has an swhois field to send
618 if(user->GetExt(extname, dummy))
620 // call this function in the linking module, let it format the data how it
621 // sees fit, and send it on its way. We dont need or want to know how.
622 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
627 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
629 // check if its our metadata key, and its associated with a user
630 if ((target_type == TYPE_USER) && (extname == "ssl"))
632 userrec* dest = (userrec*)target;
633 // if they dont already have an ssl flag, accept the remote server's
634 if (!dest->GetExt(extname, dummy))
636 dest->Extend(extname, "ON");
641 bool Handshake(issl_session* session)
643 int ret = SSL_accept(session->sess);
647 int err = SSL_get_error(session->sess, ret);
649 if (err == SSL_ERROR_WANT_READ)
651 session->rstat = ISSL_READ;
652 session->status = ISSL_HANDSHAKING;
654 else if (err == SSL_ERROR_WANT_WRITE)
656 session->wstat = ISSL_WRITE;
657 session->status = ISSL_HANDSHAKING;
658 MakePollWrite(session);
661 CloseSession(session);
667 // Handshake complete.
668 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
669 userrec* u = ServerInstance->FindDescriptor(session->fd);
672 if (!u->GetExt("ssl", dummy))
673 u->Extend("ssl", "ON");
676 session->status = ISSL_OPEN;
678 MakePollWrite(session);
684 virtual void OnPostConnect(userrec* user)
686 // This occurs AFTER OnUserConnect so we can be sure the
687 // protocol module has propogated the NICK message.
688 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
690 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
691 std::deque<std::string>* metadata = new std::deque<std::string>;
692 metadata->push_back(user->nick);
693 metadata->push_back("ssl"); // The metadata id
694 metadata->push_back("ON"); // The value to send
695 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
696 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
700 VerifyCertificate(&sessions[user->GetFd()], user);
704 void MakePollWrite(issl_session* session)
706 OnRawSocketWrite(session->fd, NULL, 0);
709 void CloseSession(issl_session* session)
713 SSL_shutdown(session->sess);
714 SSL_free(session->sess);
719 delete[] session->inbuf;
722 session->outbuf.clear();
723 session->inbuf = NULL;
724 session->sess = NULL;
725 session->status = ISSL_NONE;
728 void VerifyCertificate(issl_session* session, Extensible* user)
731 ssl_cert* certinfo = new ssl_cert;
733 unsigned char md[EVP_MAX_MD_SIZE];
734 const EVP_MD *digest = EVP_md5();
736 user->Extend("ssl_cert",certinfo);
738 cert = SSL_get_peer_certificate((SSL*)session->sess);
742 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
746 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
750 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
751 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
755 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
756 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
759 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
760 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
762 if (!X509_digest(cert, digest, md, &n))
764 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
768 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
771 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))
773 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
780 class ModuleSSLOpenSSLFactory : public ModuleFactory
783 ModuleSSLOpenSSLFactory()
787 ~ModuleSSLOpenSSLFactory()
791 virtual Module * CreateModule(InspIRCd* Me)
793 return new ModuleSSLOpenSSL(Me);
798 extern "C" void * init_module( void )
800 return new ModuleSSLOpenSSLFactory;