4 #include <openssl/ssl.h>
5 #include <openssl/err.h>
7 #include "inspircd_config.h"
8 #include "configreader.h"
19 /* $ModDesc: Provides SSL support for clients */
20 /* $CompileFlags: -I/usr/include -I/usr/local/include */
21 /* $LinkerFlags: -L/usr/local/lib -Wl,--rpath -Wl,/usr/local/lib -L/usr/lib -Wl,--rpath -Wl,/usr/lib -lssl */
25 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
26 enum issl_io_status { ISSL_WRITE, ISSL_READ };
28 static bool SelfSigned = false;
30 bool isin(int port, const std::vector<int> &portlist)
32 for(unsigned int i = 0; i < portlist.size(); i++)
33 if(portlist[i] == port)
41 return ERR_error_string(ERR_get_error(), NULL);
44 /** Represents an SSL user's extra data
46 class issl_session : public classbase
54 unsigned int inbufoffset;
55 char* inbuf; // Buffer OpenSSL reads into.
56 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
66 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
68 /* XXX: This will allow self signed certificates.
69 * In the future if we want an option to not allow this,
70 * we can just return preverify_ok here, and openssl
71 * will boot off self-signed and invalid peer certs.
73 int ve = X509_STORE_CTX_get_error(ctx);
75 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
80 class ModuleSSLOpenSSL : public Module
87 std::vector<int> listenports;
90 issl_session sessions[MAX_DESCRIPTORS];
99 // std::string crlfile;
104 ModuleSSLOpenSSL(InspIRCd* Me)
107 culllist = new CullList(ServerInstance);
109 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
110 inbufsize = ServerInstance->Config->NetBufferSize;
112 /* Global SSL library initialization*/
114 SSL_load_error_strings();
116 /* Build our SSL context*/
117 ctx = SSL_CTX_new( SSLv23_server_method() );
119 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
121 // Needs the flag as it ignores a plain /rehash
125 virtual void OnRehash(const std::string ¶m)
130 Conf = new ConfigReader(ServerInstance);
132 for(unsigned int i = 0; i < listenports.size(); i++)
134 ServerInstance->Config->DelIOHook(listenports[i]);
139 for(int i = 0; i < Conf->Enumerate("bind"); i++)
141 // For each <bind> tag
142 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
144 // Get the port we're meant to be listening on with SSL
145 std::string port = Conf->ReadValue("bind", "port", i);
146 irc::commasepstream portrange(port);
147 std::string portno = "*";
148 while ((portno = portrange.GetToken()) != "")
150 std::string::size_type dash = portno.rfind('-');
151 if (dash != std::string::npos)
153 std::string sbegin = portno.substr(0, dash);
154 std::string send = portno.substr(dash+1, portno.length());
155 long begin = atoi(sbegin.c_str());
156 long end = atoi(send.c_str());
157 if ((begin < 0) || (end < 0) || (begin > 65535) || (end > 65535) || (begin >= end))
159 ServerInstance->Log(DEFAULT,"WARNING: Port range \"%d-%d\" discarded. begin >= end, or begin/end out of range.", begin, end);
163 for (int portval = begin; portval <= end; ++portval)
165 if (ServerInstance->Config->AddIOHook(portval, this))
167 listenports.push_back(portval);
168 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portval);
172 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?",
180 if (ServerInstance->Config->AddIOHook(atoi(portno.c_str()), this))
182 // We keep a record of which ports we're listening on with SSL
183 listenports.push_back(atoi(portno.c_str()));
185 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portno.c_str());
189 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %s, maybe you have another ssl or similar module loaded?", portno.c_str());
196 std::string confdir(CONFIG_FILE);
197 // +1 so we the path ends with a /
198 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
200 cafile = Conf->ReadValue("openssl", "cafile", 0);
201 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
202 certfile = Conf->ReadValue("openssl", "certfile", 0);
203 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
204 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
206 // Set all the default values needed.
211 // crlfile = "crl.pem";
214 certfile = "cert.pem";
220 dhfile = "dhparams.pem";
222 // Prepend relative paths with the path to the config directory.
224 cafile = confdir + cafile;
226 //if(crlfile[0] != '/')
227 // crlfile = confdir + crlfile;
229 if(certfile[0] != '/')
230 certfile = confdir + certfile;
232 if(keyfile[0] != '/')
233 keyfile = confdir + keyfile;
236 dhfile = confdir + dhfile;
238 /* Load our keys and certificates*/
239 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
241 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
244 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
246 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
249 /* Load the CAs we trust*/
250 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
252 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
255 FILE* dhpfile = fopen(dhfile.c_str(), "r");
260 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
261 throw ModuleException();
265 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
267 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
269 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
278 virtual ~ModuleSSLOpenSSL()
284 virtual void OnCleanup(int target_type, void* item)
286 if(target_type == TYPE_USER)
288 userrec* user = (userrec*)item;
290 if(user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
292 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
293 // Potentially there could be multiple SSL modules loaded at once on different ports.
294 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
295 culllist->AddItem(user, "SSL module unloading");
297 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
300 user->GetExt("ssl_cert", tofree);
302 user->Shrink("ssl_cert");
307 virtual void OnUnloadModule(Module* mod, const std::string &name)
311 // We're being unloaded, kill all the users added to the cull list in OnCleanup
312 int numusers = culllist->Apply();
313 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
315 for(unsigned int i = 0; i < listenports.size(); i++)
316 ServerInstance->Config->DelIOHook(listenports[i]);
320 virtual Version GetVersion()
322 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
325 void Implements(char* List)
327 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
328 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
331 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
333 issl_session* session = &sessions[fd];
336 session->inbuf = new char[inbufsize];
337 session->inbufoffset = 0;
338 session->sess = SSL_new(ctx);
339 session->status = ISSL_NONE;
341 if(session->sess == NULL)
343 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
347 if(SSL_set_fd(session->sess, fd) == 0)
349 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
356 virtual void OnRawSocketClose(int fd)
358 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
359 CloseSession(&sessions[fd]);
361 EventHandler* user = ServerInstance->SE->GetRef(fd);
363 if ((user) && (user->GetExt("ssl_cert", dummy)))
366 user->GetExt("ssl_cert", tofree);
368 user->Shrink("ssl_cert");
372 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
374 issl_session* session = &sessions[fd];
378 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
380 CloseSession(session);
384 if(session->status == ISSL_HANDSHAKING)
386 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
388 // The handshake isn't finished and it wants to read, try to finish it.
389 if(Handshake(session))
391 // Handshake successfully resumed.
392 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
396 // Couldn't resume handshake.
397 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
403 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
408 // If we resumed the handshake then session->status will be ISSL_OPEN
410 if(session->status == ISSL_OPEN)
412 if(session->wstat == ISSL_READ)
414 if(DoWrite(session) == 0)
418 if(session->rstat == ISSL_READ)
420 int ret = DoRead(session);
424 if(count <= session->inbufoffset)
426 memcpy(buffer, session->inbuf, count);
427 // Move the stuff left in inbuf to the beginning of it
428 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
429 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
430 session->inbufoffset -= count;
431 // Insp uses readresult as the count of how much data there is in buffer, so:
436 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
437 memcpy(buffer, session->inbuf, session->inbufoffset);
439 readresult = session->inbufoffset;
440 // Zero the offset, as there's nothing there..
441 session->inbufoffset = 0;
456 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
458 issl_session* session = &sessions[fd];
462 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
463 CloseSession(session);
467 session->outbuf.append(buffer, count);
469 if(session->status == ISSL_HANDSHAKING)
471 // The handshake isn't finished, try to finish it.
472 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
474 if(Handshake(session))
476 // Handshake successfully resumed.
477 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
481 // Couldn't resume handshake.
482 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
487 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
491 if(session->status == ISSL_OPEN)
493 if(session->rstat == ISSL_WRITE)
498 if(session->wstat == ISSL_WRITE)
500 return DoWrite(session);
507 int DoWrite(issl_session* session)
509 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
513 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
514 CloseSession(session);
519 int err = SSL_get_error(session->sess, ret);
521 if(err == SSL_ERROR_WANT_WRITE)
523 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
524 session->wstat = ISSL_WRITE;
527 else if(err == SSL_ERROR_WANT_READ)
529 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
530 session->wstat = ISSL_READ;
535 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
536 CloseSession(session);
542 session->outbuf = session->outbuf.substr(ret);
547 int DoRead(issl_session* session)
549 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
550 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
552 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
556 // Client closed connection.
557 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
558 CloseSession(session);
563 int err = SSL_get_error(session->sess, ret);
565 if(err == SSL_ERROR_WANT_READ)
567 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
568 session->rstat = ISSL_READ;
571 else if(err == SSL_ERROR_WANT_WRITE)
573 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
574 session->rstat = ISSL_WRITE;
579 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
580 CloseSession(session);
586 // Read successfully 'ret' bytes into inbuf + inbufoffset
587 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
588 // 'buffer' is 'count' long
590 session->inbufoffset += ret;
596 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
597 virtual void OnWhois(userrec* source, userrec* dest)
599 // Bugfix, only send this numeric for *our* SSL users
600 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
602 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
606 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
608 // check if the linking module wants to know about OUR metadata
611 // check if this user has an swhois field to send
612 if(user->GetExt(extname, dummy))
614 // call this function in the linking module, let it format the data how it
615 // sees fit, and send it on its way. We dont need or want to know how.
616 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
621 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
623 // check if its our metadata key, and its associated with a user
624 if ((target_type == TYPE_USER) && (extname == "ssl"))
626 userrec* dest = (userrec*)target;
627 // if they dont already have an ssl flag, accept the remote server's
628 if (!dest->GetExt(extname, dummy))
630 dest->Extend(extname, "ON");
635 bool Handshake(issl_session* session)
637 int ret = SSL_accept(session->sess);
641 int err = SSL_get_error(session->sess, ret);
643 if(err == SSL_ERROR_WANT_READ)
645 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
646 session->rstat = ISSL_READ;
647 session->status = ISSL_HANDSHAKING;
649 else if(err == SSL_ERROR_WANT_WRITE)
651 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
652 session->wstat = ISSL_WRITE;
653 session->status = ISSL_HANDSHAKING;
654 MakePollWrite(session);
658 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
659 CloseSession(session);
666 // Handshake complete.
667 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
669 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
670 userrec* u = ServerInstance->FindDescriptor(session->fd);
673 if (!u->GetExt("ssl", dummy))
674 u->Extend("ssl", "ON");
677 session->status = ISSL_OPEN;
679 MakePollWrite(session);
685 virtual void OnPostConnect(userrec* user)
687 // This occurs AFTER OnUserConnect so we can be sure the
688 // protocol module has propogated the NICK message.
689 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
691 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
692 std::deque<std::string>* metadata = new std::deque<std::string>;
693 metadata->push_back(user->nick);
694 metadata->push_back("ssl"); // The metadata id
695 metadata->push_back("ON"); // The value to send
696 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
697 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
701 VerifyCertificate(&sessions[user->GetFd()], user);
705 void MakePollWrite(issl_session* session)
707 OnRawSocketWrite(session->fd, NULL, 0);
710 void CloseSession(issl_session* session)
714 SSL_shutdown(session->sess);
715 SSL_free(session->sess);
720 delete[] session->inbuf;
723 session->outbuf.clear();
724 session->inbuf = NULL;
725 session->sess = NULL;
726 session->status = ISSL_NONE;
729 void VerifyCertificate(issl_session* session, userrec* user)
732 ssl_cert* certinfo = new ssl_cert;
734 unsigned char md[EVP_MAX_MD_SIZE];
735 const EVP_MD *digest = EVP_md5();
737 user->Extend("ssl_cert",certinfo);
739 cert = SSL_get_peer_certificate((SSL*)session->sess);
743 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
747 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
751 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
752 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
756 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
757 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
760 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
761 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
763 if (!X509_digest(cert, digest, md, &n))
765 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
769 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
772 user->WriteServ("NOTICE %s :*** Your SSL Certificate fingerprint is: %s", user->nick, irc::hex(md, n).c_str());
774 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))
776 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
783 class ModuleSSLOpenSSLFactory : public ModuleFactory
786 ModuleSSLOpenSSLFactory()
790 ~ModuleSSLOpenSSLFactory()
794 virtual Module * CreateModule(InspIRCd* Me)
796 return new ModuleSSLOpenSSL(Me);
801 extern "C" void * init_module( void )
803 return new ModuleSSLOpenSSLFactory;