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: `perl extra/openssl_config.pl compile` */
21 /* $LinkerFlags: `perl extra/openssl_config.pl link` */
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 ServerInstance->PublishInterface("InspSocketHook", this);
111 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
112 inbufsize = ServerInstance->Config->NetBufferSize;
114 /* Global SSL library initialization*/
116 SSL_load_error_strings();
118 /* Build our SSL context*/
119 ctx = SSL_CTX_new( SSLv23_server_method() );
121 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
123 // Needs the flag as it ignores a plain /rehash
127 virtual void OnRehash(const std::string ¶m)
132 Conf = new ConfigReader(ServerInstance);
134 for (unsigned int i = 0; i < listenports.size(); i++)
136 ServerInstance->Config->DelIOHook(listenports[i]);
141 for (int i = 0; i < Conf->Enumerate("bind"); i++)
143 // For each <bind> tag
144 if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
146 // Get the port we're meant to be listening on with SSL
147 std::string port = Conf->ReadValue("bind", "port", i);
148 irc::portparser portrange(port, false);
150 while ((portno = portrange.GetToken()))
152 if (ServerInstance->Config->AddIOHook(portno, this))
154 listenports.push_back(portno);
155 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
159 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
165 std::string confdir(CONFIG_FILE);
166 // +1 so we the path ends with a /
167 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
169 cafile = Conf->ReadValue("openssl", "cafile", 0);
170 certfile = Conf->ReadValue("openssl", "certfile", 0);
171 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
172 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
174 // Set all the default values needed.
179 certfile = "cert.pem";
185 dhfile = "dhparams.pem";
187 // Prepend relative paths with the path to the config directory.
188 if (cafile[0] != '/')
189 cafile = confdir + cafile;
191 //if(crlfile[0] != '/')
192 // crlfile = confdir + crlfile;
194 if (certfile[0] != '/')
195 certfile = confdir + certfile;
197 if (keyfile[0] != '/')
198 keyfile = confdir + keyfile;
200 if (dhfile[0] != '/')
201 dhfile = confdir + dhfile;
203 /* Load our keys and certificates*/
204 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
206 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
209 if (!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
211 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
214 /* Load the CAs we trust*/
215 if (!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
217 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
220 FILE* dhpfile = fopen(dhfile.c_str(), "r");
225 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
226 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
230 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
232 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
234 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
243 virtual ~ModuleSSLOpenSSL()
249 virtual void OnCleanup(int target_type, void* item)
251 if (target_type == TYPE_USER)
253 userrec* user = (userrec*)item;
255 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
257 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
258 // Potentially there could be multiple SSL modules loaded at once on different ports.
259 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
260 culllist->AddItem(user, "SSL module unloading");
262 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
265 user->GetExt("ssl_cert", tofree);
267 user->Shrink("ssl_cert");
272 virtual void OnUnloadModule(Module* mod, const std::string &name)
276 // We're being unloaded, kill all the users added to the cull list in OnCleanup
277 int numusers = culllist->Apply();
278 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
280 for(unsigned int i = 0; i < listenports.size(); i++)
281 ServerInstance->Config->DelIOHook(listenports[i]);
285 virtual Version GetVersion()
287 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
290 void Implements(char* List)
292 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
293 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
296 virtual char* OnRequest(Request* request)
298 ISHRequest* ISR = (ISHRequest*)request;
299 ServerInstance->Log(DEBUG, "hook OnRequest");
300 if (strcmp("IS_NAME", request->GetId()) == 0)
304 else if (strcmp("IS_HOOK", request->GetId()) == 0)
306 ServerInstance->Log(DEBUG, "Hooking socket %08x", ISR->Sock);
307 return ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
309 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
311 ServerInstance->Log(DEBUG, "Unhooking socket %08x", ISR->Sock);
312 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
314 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
316 issl_session* session = &sessions[ISR->Sock->GetFd()];
317 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
319 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
321 issl_session* session = &sessions[ISR->Sock->GetFd()];
324 VerifyCertificate(session, (InspSocket*)ISR->Sock);
332 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
334 ServerInstance->Log(DEBUG, "Hook accept %d", fd);
335 issl_session* session = &sessions[fd];
338 session->inbuf = new char[inbufsize];
339 session->inbufoffset = 0;
340 session->sess = SSL_new(ctx);
341 session->status = ISSL_NONE;
343 if (session->sess == NULL)
345 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
349 if (SSL_set_fd(session->sess, fd) == 0)
351 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
358 virtual void OnRawSocketConnect(int fd)
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)
370 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
374 if (SSL_set_fd(session->sess, fd) == 0)
376 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
383 virtual void OnRawSocketClose(int fd)
385 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
386 CloseSession(&sessions[fd]);
388 EventHandler* user = ServerInstance->SE->GetRef(fd);
390 if ((user) && (user->GetExt("ssl_cert", dummy)))
393 user->GetExt("ssl_cert", tofree);
395 user->Shrink("ssl_cert");
399 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
401 issl_session* session = &sessions[fd];
405 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
407 CloseSession(session);
411 if (session->status == ISSL_HANDSHAKING)
413 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
415 // The handshake isn't finished and it wants to read, try to finish it.
416 if (Handshake(session))
418 // Handshake successfully resumed.
419 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
423 // Couldn't resume handshake.
424 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
430 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
435 // If we resumed the handshake then session->status will be ISSL_OPEN
437 if (session->status == ISSL_OPEN)
439 if (session->wstat == ISSL_READ)
441 if(DoWrite(session) == 0)
445 if (session->rstat == ISSL_READ)
447 int ret = DoRead(session);
451 if (count <= session->inbufoffset)
453 memcpy(buffer, session->inbuf, count);
454 // Move the stuff left in inbuf to the beginning of it
455 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
456 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
457 session->inbufoffset -= count;
458 // Insp uses readresult as the count of how much data there is in buffer, so:
463 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
464 memcpy(buffer, session->inbuf, session->inbufoffset);
466 readresult = session->inbufoffset;
467 // Zero the offset, as there's nothing there..
468 session->inbufoffset = 0;
483 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
485 issl_session* session = &sessions[fd];
489 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
490 CloseSession(session);
494 session->outbuf.append(buffer, count);
496 if (session->status == ISSL_HANDSHAKING)
498 // The handshake isn't finished, try to finish it.
499 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
501 if (Handshake(session))
503 // Handshake successfully resumed.
504 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
508 // Couldn't resume handshake.
509 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
514 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
518 if (session->status == ISSL_OPEN)
520 if (session->rstat == ISSL_WRITE)
525 if (session->wstat == ISSL_WRITE)
527 return DoWrite(session);
534 int DoWrite(issl_session* session)
536 if (!session->outbuf.size())
539 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: To write: %d", session->outbuf.size());
540 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
544 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
545 CloseSession(session);
550 int err = SSL_get_error(session->sess, ret);
552 if (err == SSL_ERROR_WANT_WRITE)
554 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
555 session->wstat = ISSL_WRITE;
558 else if (err == SSL_ERROR_WANT_READ)
560 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
561 session->wstat = ISSL_READ;
566 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
567 CloseSession(session);
573 session->outbuf = session->outbuf.substr(ret);
578 int DoRead(issl_session* session)
580 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
581 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
583 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
587 // Client closed connection.
588 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
589 CloseSession(session);
594 int err = SSL_get_error(session->sess, ret);
596 if (err == SSL_ERROR_WANT_READ)
598 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
599 session->rstat = ISSL_READ;
602 else if (err == SSL_ERROR_WANT_WRITE)
604 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
605 session->rstat = ISSL_WRITE;
610 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
611 CloseSession(session);
617 // Read successfully 'ret' bytes into inbuf + inbufoffset
618 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
619 // 'buffer' is 'count' long
621 session->inbufoffset += ret;
627 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
628 virtual void OnWhois(userrec* source, userrec* dest)
630 // Bugfix, only send this numeric for *our* SSL users
631 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
633 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
637 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
639 // check if the linking module wants to know about OUR metadata
640 if (extname == "ssl")
642 // check if this user has an swhois field to send
643 if(user->GetExt(extname, dummy))
645 // call this function in the linking module, let it format the data how it
646 // sees fit, and send it on its way. We dont need or want to know how.
647 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
652 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
654 // check if its our metadata key, and its associated with a user
655 if ((target_type == TYPE_USER) && (extname == "ssl"))
657 userrec* dest = (userrec*)target;
658 // if they dont already have an ssl flag, accept the remote server's
659 if (!dest->GetExt(extname, dummy))
661 dest->Extend(extname, "ON");
666 bool Handshake(issl_session* session)
668 int ret = SSL_accept(session->sess);
672 int err = SSL_get_error(session->sess, ret);
674 if (err == SSL_ERROR_WANT_READ)
676 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
677 session->rstat = ISSL_READ;
678 session->status = ISSL_HANDSHAKING;
680 else if (err == SSL_ERROR_WANT_WRITE)
682 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
683 session->wstat = ISSL_WRITE;
684 session->status = ISSL_HANDSHAKING;
685 MakePollWrite(session);
689 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
690 CloseSession(session);
697 // Handshake complete.
698 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
700 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
701 userrec* u = ServerInstance->FindDescriptor(session->fd);
704 if (!u->GetExt("ssl", dummy))
705 u->Extend("ssl", "ON");
708 session->status = ISSL_OPEN;
710 MakePollWrite(session);
716 virtual void OnPostConnect(userrec* user)
718 // This occurs AFTER OnUserConnect so we can be sure the
719 // protocol module has propogated the NICK message.
720 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
722 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
723 std::deque<std::string>* metadata = new std::deque<std::string>;
724 metadata->push_back(user->nick);
725 metadata->push_back("ssl"); // The metadata id
726 metadata->push_back("ON"); // The value to send
727 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
728 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
732 VerifyCertificate(&sessions[user->GetFd()], user);
736 void MakePollWrite(issl_session* session)
738 OnRawSocketWrite(session->fd, NULL, 0);
741 void CloseSession(issl_session* session)
745 SSL_shutdown(session->sess);
746 SSL_free(session->sess);
751 delete[] session->inbuf;
754 session->outbuf.clear();
755 session->inbuf = NULL;
756 session->sess = NULL;
757 session->status = ISSL_NONE;
760 void VerifyCertificate(issl_session* session, Extensible* user)
763 ssl_cert* certinfo = new ssl_cert;
765 unsigned char md[EVP_MAX_MD_SIZE];
766 const EVP_MD *digest = EVP_md5();
768 user->Extend("ssl_cert",certinfo);
770 cert = SSL_get_peer_certificate((SSL*)session->sess);
774 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
778 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
782 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
783 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
787 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
788 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
791 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
792 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
794 if (!X509_digest(cert, digest, md, &n))
796 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
800 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
803 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))
805 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
812 class ModuleSSLOpenSSLFactory : public ModuleFactory
815 ModuleSSLOpenSSLFactory()
819 ~ModuleSSLOpenSSLFactory()
823 virtual Module * CreateModule(InspIRCd* Me)
825 return new ModuleSSLOpenSSL(Me);
830 extern "C" void * init_module( void )
832 return new ModuleSSLOpenSSLFactory;