4 #include <openssl/ssl.h>
5 #include <openssl/err.h>
7 #include "inspircd_config.h"
8 #include "configreader.h"
17 #include "transport.h"
19 /* $ModDesc: Provides SSL support for clients */
20 /* $CompileFlags: `perl extra/openssl_config.pl compile` */
21 /* $LinkerFlags: `perl extra/openssl_config.pl link` */
22 /* $ModDep: transport.h */
24 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
25 enum issl_io_status { ISSL_WRITE, ISSL_READ };
27 static bool SelfSigned = false;
29 bool isin(int port, const std::vector<int> &portlist)
31 for(unsigned int i = 0; i < portlist.size(); i++)
32 if(portlist[i] == port)
40 return ERR_error_string(ERR_get_error(), NULL);
43 /** Represents an SSL user's extra data
45 class issl_session : public classbase
53 unsigned int inbufoffset;
54 char* inbuf; // Buffer OpenSSL reads into.
55 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
65 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
67 /* XXX: This will allow self signed certificates.
68 * In the future if we want an option to not allow this,
69 * we can just return preverify_ok here, and openssl
70 * will boot off self-signed and invalid peer certs.
72 int ve = X509_STORE_CTX_get_error(ctx);
74 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
79 class ModuleSSLOpenSSL : public Module
86 std::vector<int> listenports;
89 issl_session sessions[MAX_DESCRIPTORS];
98 // std::string crlfile;
103 ModuleSSLOpenSSL(InspIRCd* Me)
106 culllist = new CullList(ServerInstance);
108 ServerInstance->PublishInterface("InspSocketHook", this);
110 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
111 inbufsize = ServerInstance->Config->NetBufferSize;
113 /* Global SSL library initialization*/
115 SSL_load_error_strings();
117 /* Build our SSL context*/
118 ctx = SSL_CTX_new( SSLv23_server_method() );
120 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
122 // Needs the flag as it ignores a plain /rehash
126 virtual void OnRehash(const std::string ¶m)
131 Conf = new ConfigReader(ServerInstance);
133 for (unsigned int i = 0; i < listenports.size(); i++)
135 ServerInstance->Config->DelIOHook(listenports[i]);
140 for (int i = 0; i < Conf->Enumerate("bind"); i++)
142 // For each <bind> tag
143 if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
145 // Get the port we're meant to be listening on with SSL
146 std::string port = Conf->ReadValue("bind", "port", i);
147 irc::portparser portrange(port, false);
149 while ((portno = portrange.GetToken()))
151 if (ServerInstance->Config->AddIOHook(portno, this))
153 listenports.push_back(portno);
154 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
158 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
164 std::string confdir(CONFIG_FILE);
165 // +1 so we the path ends with a /
166 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
168 cafile = Conf->ReadValue("openssl", "cafile", 0);
169 certfile = Conf->ReadValue("openssl", "certfile", 0);
170 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
171 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
173 // Set all the default values needed.
178 certfile = "cert.pem";
184 dhfile = "dhparams.pem";
186 // Prepend relative paths with the path to the config directory.
187 if (cafile[0] != '/')
188 cafile = confdir + cafile;
190 //if(crlfile[0] != '/')
191 // crlfile = confdir + crlfile;
193 if (certfile[0] != '/')
194 certfile = confdir + certfile;
196 if (keyfile[0] != '/')
197 keyfile = confdir + keyfile;
199 if (dhfile[0] != '/')
200 dhfile = confdir + dhfile;
202 /* Load our keys and certificates*/
203 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
205 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
208 if (!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
210 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
213 /* Load the CAs we trust*/
214 if (!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
216 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
219 FILE* dhpfile = fopen(dhfile.c_str(), "r");
224 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
225 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
229 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
231 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
233 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
242 virtual ~ModuleSSLOpenSSL()
248 virtual void OnCleanup(int target_type, void* item)
250 if (target_type == TYPE_USER)
252 userrec* user = (userrec*)item;
254 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
256 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
257 // Potentially there could be multiple SSL modules loaded at once on different ports.
258 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
259 culllist->AddItem(user, "SSL module unloading");
261 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
264 user->GetExt("ssl_cert", tofree);
266 user->Shrink("ssl_cert");
271 virtual void OnUnloadModule(Module* mod, const std::string &name)
275 // We're being unloaded, kill all the users added to the cull list in OnCleanup
276 int numusers = culllist->Apply();
277 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
279 for(unsigned int i = 0; i < listenports.size(); i++)
280 ServerInstance->Config->DelIOHook(listenports[i]);
284 virtual Version GetVersion()
286 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
289 void Implements(char* List)
291 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
292 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
295 virtual char* OnRequest(Request* request)
297 ISHRequest* ISR = (ISHRequest*)request;
298 ServerInstance->Log(DEBUG, "hook OnRequest");
299 if (strcmp("IS_NAME", request->GetId()) == 0)
303 else if (strcmp("IS_HOOK", request->GetId()) == 0)
308 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
310 catch (ModuleException &e)
317 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
319 ServerInstance->Log(DEBUG, "Unhooking socket %08x", ISR->Sock);
320 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
322 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
324 issl_session* session = &sessions[ISR->Sock->GetFd()];
325 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
327 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
329 issl_session* session = &sessions[ISR->Sock->GetFd()];
332 VerifyCertificate(session, (InspSocket*)ISR->Sock);
340 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
342 ServerInstance->Log(DEBUG, "Hook accept %d", fd);
343 issl_session* session = &sessions[fd];
346 session->inbuf = new char[inbufsize];
347 session->inbufoffset = 0;
348 session->sess = SSL_new(ctx);
349 session->status = ISSL_NONE;
351 if (session->sess == NULL)
353 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
357 if (SSL_set_fd(session->sess, fd) == 0)
359 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
366 virtual void OnRawSocketConnect(int fd)
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;
376 if (session->sess == NULL)
378 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
382 if (SSL_set_fd(session->sess, fd) == 0)
384 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
391 virtual void OnRawSocketClose(int fd)
393 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
394 CloseSession(&sessions[fd]);
396 EventHandler* user = ServerInstance->SE->GetRef(fd);
398 if ((user) && (user->GetExt("ssl_cert", dummy)))
401 user->GetExt("ssl_cert", tofree);
403 user->Shrink("ssl_cert");
407 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
409 issl_session* session = &sessions[fd];
413 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
415 CloseSession(session);
419 if (session->status == ISSL_HANDSHAKING)
421 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
423 // The handshake isn't finished and it wants to read, try to finish it.
424 if (Handshake(session))
426 // Handshake successfully resumed.
427 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
431 // Couldn't resume handshake.
432 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
438 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
443 // If we resumed the handshake then session->status will be ISSL_OPEN
445 if (session->status == ISSL_OPEN)
447 if (session->wstat == ISSL_READ)
449 if(DoWrite(session) == 0)
453 if (session->rstat == ISSL_READ)
455 int ret = DoRead(session);
459 if (count <= session->inbufoffset)
461 memcpy(buffer, session->inbuf, count);
462 // Move the stuff left in inbuf to the beginning of it
463 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
464 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
465 session->inbufoffset -= count;
466 // Insp uses readresult as the count of how much data there is in buffer, so:
471 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
472 memcpy(buffer, session->inbuf, session->inbufoffset);
474 readresult = session->inbufoffset;
475 // Zero the offset, as there's nothing there..
476 session->inbufoffset = 0;
491 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
493 issl_session* session = &sessions[fd];
497 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
498 CloseSession(session);
502 session->outbuf.append(buffer, count);
504 if (session->status == ISSL_HANDSHAKING)
506 // The handshake isn't finished, try to finish it.
507 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
509 if (Handshake(session))
511 // Handshake successfully resumed.
512 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
516 // Couldn't resume handshake.
517 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
522 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
526 if (session->status == ISSL_OPEN)
528 if (session->rstat == ISSL_WRITE)
533 if (session->wstat == ISSL_WRITE)
535 return DoWrite(session);
542 int DoWrite(issl_session* session)
544 if (!session->outbuf.size())
547 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: To write: %d", session->outbuf.size());
548 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
552 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
553 CloseSession(session);
558 int err = SSL_get_error(session->sess, ret);
560 if (err == SSL_ERROR_WANT_WRITE)
562 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
563 session->wstat = ISSL_WRITE;
566 else if (err == SSL_ERROR_WANT_READ)
568 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
569 session->wstat = ISSL_READ;
574 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
575 CloseSession(session);
581 session->outbuf = session->outbuf.substr(ret);
586 int DoRead(issl_session* session)
588 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
589 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
591 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
595 // Client closed connection.
596 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
597 CloseSession(session);
602 int err = SSL_get_error(session->sess, ret);
604 if (err == SSL_ERROR_WANT_READ)
606 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
607 session->rstat = ISSL_READ;
610 else if (err == SSL_ERROR_WANT_WRITE)
612 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
613 session->rstat = ISSL_WRITE;
618 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
619 CloseSession(session);
625 // Read successfully 'ret' bytes into inbuf + inbufoffset
626 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
627 // 'buffer' is 'count' long
629 session->inbufoffset += ret;
635 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
636 virtual void OnWhois(userrec* source, userrec* dest)
638 // Bugfix, only send this numeric for *our* SSL users
639 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
641 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
645 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
647 // check if the linking module wants to know about OUR metadata
648 if (extname == "ssl")
650 // check if this user has an swhois field to send
651 if(user->GetExt(extname, dummy))
653 // call this function in the linking module, let it format the data how it
654 // sees fit, and send it on its way. We dont need or want to know how.
655 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
660 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
662 // check if its our metadata key, and its associated with a user
663 if ((target_type == TYPE_USER) && (extname == "ssl"))
665 userrec* dest = (userrec*)target;
666 // if they dont already have an ssl flag, accept the remote server's
667 if (!dest->GetExt(extname, dummy))
669 dest->Extend(extname, "ON");
674 bool Handshake(issl_session* session)
676 int ret = SSL_accept(session->sess);
680 int err = SSL_get_error(session->sess, ret);
682 if (err == SSL_ERROR_WANT_READ)
684 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
685 session->rstat = ISSL_READ;
686 session->status = ISSL_HANDSHAKING;
688 else if (err == SSL_ERROR_WANT_WRITE)
690 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
691 session->wstat = ISSL_WRITE;
692 session->status = ISSL_HANDSHAKING;
693 MakePollWrite(session);
697 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
698 CloseSession(session);
705 // Handshake complete.
706 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
708 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
709 userrec* u = ServerInstance->FindDescriptor(session->fd);
712 if (!u->GetExt("ssl", dummy))
713 u->Extend("ssl", "ON");
716 session->status = ISSL_OPEN;
718 MakePollWrite(session);
724 virtual void OnPostConnect(userrec* user)
726 // This occurs AFTER OnUserConnect so we can be sure the
727 // protocol module has propogated the NICK message.
728 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
730 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
731 std::deque<std::string>* metadata = new std::deque<std::string>;
732 metadata->push_back(user->nick);
733 metadata->push_back("ssl"); // The metadata id
734 metadata->push_back("ON"); // The value to send
735 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
736 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
740 VerifyCertificate(&sessions[user->GetFd()], user);
744 void MakePollWrite(issl_session* session)
746 OnRawSocketWrite(session->fd, NULL, 0);
749 void CloseSession(issl_session* session)
753 SSL_shutdown(session->sess);
754 SSL_free(session->sess);
759 delete[] session->inbuf;
762 session->outbuf.clear();
763 session->inbuf = NULL;
764 session->sess = NULL;
765 session->status = ISSL_NONE;
768 void VerifyCertificate(issl_session* session, Extensible* user)
771 ssl_cert* certinfo = new ssl_cert;
773 unsigned char md[EVP_MAX_MD_SIZE];
774 const EVP_MD *digest = EVP_md5();
776 user->Extend("ssl_cert",certinfo);
778 cert = SSL_get_peer_certificate((SSL*)session->sess);
782 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
786 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
790 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
791 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
795 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
796 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
799 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
800 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
802 if (!X509_digest(cert, digest, md, &n))
804 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
808 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
811 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))
813 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
820 class ModuleSSLOpenSSLFactory : public ModuleFactory
823 ModuleSSLOpenSSLFactory()
827 ~ModuleSSLOpenSSLFactory()
831 virtual Module * CreateModule(InspIRCd* Me)
833 return new ModuleSSLOpenSSL(Me);
838 extern "C" void * init_module( void )
840 return new ModuleSSLOpenSSLFactory;