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)
305 ServerInstance->Log(DEBUG, "Hooking socket %08x", ISR->Sock);
306 return ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
308 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
310 ServerInstance->Log(DEBUG, "Unhooking socket %08x", ISR->Sock);
311 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
313 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
315 issl_session* session = &sessions[ISR->Sock->GetFd()];
316 return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
318 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
320 issl_session* session = &sessions[ISR->Sock->GetFd()];
323 VerifyCertificate(session, (InspSocket*)ISR->Sock);
331 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
333 ServerInstance->Log(DEBUG, "Hook accept %d", fd);
334 issl_session* session = &sessions[fd];
337 session->inbuf = new char[inbufsize];
338 session->inbufoffset = 0;
339 session->sess = SSL_new(ctx);
340 session->status = ISSL_NONE;
342 if (session->sess == NULL)
344 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
348 if (SSL_set_fd(session->sess, fd) == 0)
350 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
357 virtual void OnRawSocketConnect(int fd)
359 issl_session* session = &sessions[fd];
362 session->inbuf = new char[inbufsize];
363 session->inbufoffset = 0;
364 session->sess = SSL_new(ctx);
365 session->status = ISSL_NONE;
367 if (session->sess == NULL)
369 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
373 if (SSL_set_fd(session->sess, fd) == 0)
375 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
382 virtual void OnRawSocketClose(int fd)
384 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
385 CloseSession(&sessions[fd]);
387 EventHandler* user = ServerInstance->SE->GetRef(fd);
389 if ((user) && (user->GetExt("ssl_cert", dummy)))
392 user->GetExt("ssl_cert", tofree);
394 user->Shrink("ssl_cert");
398 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
400 issl_session* session = &sessions[fd];
404 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
406 CloseSession(session);
410 if (session->status == ISSL_HANDSHAKING)
412 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
414 // The handshake isn't finished and it wants to read, try to finish it.
415 if (Handshake(session))
417 // Handshake successfully resumed.
418 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
422 // Couldn't resume handshake.
423 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
429 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
434 // If we resumed the handshake then session->status will be ISSL_OPEN
436 if (session->status == ISSL_OPEN)
438 if (session->wstat == ISSL_READ)
440 if(DoWrite(session) == 0)
444 if (session->rstat == ISSL_READ)
446 int ret = DoRead(session);
450 if (count <= session->inbufoffset)
452 memcpy(buffer, session->inbuf, count);
453 // Move the stuff left in inbuf to the beginning of it
454 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
455 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
456 session->inbufoffset -= count;
457 // Insp uses readresult as the count of how much data there is in buffer, so:
462 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
463 memcpy(buffer, session->inbuf, session->inbufoffset);
465 readresult = session->inbufoffset;
466 // Zero the offset, as there's nothing there..
467 session->inbufoffset = 0;
482 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
484 issl_session* session = &sessions[fd];
488 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
489 CloseSession(session);
493 session->outbuf.append(buffer, count);
495 if (session->status == ISSL_HANDSHAKING)
497 // The handshake isn't finished, try to finish it.
498 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
500 if (Handshake(session))
502 // Handshake successfully resumed.
503 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
507 // Couldn't resume handshake.
508 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
513 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
517 if (session->status == ISSL_OPEN)
519 if (session->rstat == ISSL_WRITE)
524 if (session->wstat == ISSL_WRITE)
526 return DoWrite(session);
533 int DoWrite(issl_session* session)
535 if (!session->outbuf.size())
538 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: To write: %d", session->outbuf.size());
539 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
543 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
544 CloseSession(session);
549 int err = SSL_get_error(session->sess, ret);
551 if (err == SSL_ERROR_WANT_WRITE)
553 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
554 session->wstat = ISSL_WRITE;
557 else if (err == SSL_ERROR_WANT_READ)
559 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
560 session->wstat = ISSL_READ;
565 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
566 CloseSession(session);
572 session->outbuf = session->outbuf.substr(ret);
577 int DoRead(issl_session* session)
579 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
580 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
582 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
586 // Client closed connection.
587 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
588 CloseSession(session);
593 int err = SSL_get_error(session->sess, ret);
595 if (err == SSL_ERROR_WANT_READ)
597 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
598 session->rstat = ISSL_READ;
601 else if (err == SSL_ERROR_WANT_WRITE)
603 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
604 session->rstat = ISSL_WRITE;
609 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
610 CloseSession(session);
616 // Read successfully 'ret' bytes into inbuf + inbufoffset
617 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
618 // 'buffer' is 'count' long
620 session->inbufoffset += ret;
626 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
627 virtual void OnWhois(userrec* source, userrec* dest)
629 // Bugfix, only send this numeric for *our* SSL users
630 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
632 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
636 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
638 // check if the linking module wants to know about OUR metadata
639 if (extname == "ssl")
641 // check if this user has an swhois field to send
642 if(user->GetExt(extname, dummy))
644 // call this function in the linking module, let it format the data how it
645 // sees fit, and send it on its way. We dont need or want to know how.
646 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
651 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
653 // check if its our metadata key, and its associated with a user
654 if ((target_type == TYPE_USER) && (extname == "ssl"))
656 userrec* dest = (userrec*)target;
657 // if they dont already have an ssl flag, accept the remote server's
658 if (!dest->GetExt(extname, dummy))
660 dest->Extend(extname, "ON");
665 bool Handshake(issl_session* session)
667 int ret = SSL_accept(session->sess);
671 int err = SSL_get_error(session->sess, ret);
673 if (err == SSL_ERROR_WANT_READ)
675 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
676 session->rstat = ISSL_READ;
677 session->status = ISSL_HANDSHAKING;
679 else if (err == SSL_ERROR_WANT_WRITE)
681 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
682 session->wstat = ISSL_WRITE;
683 session->status = ISSL_HANDSHAKING;
684 MakePollWrite(session);
688 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
689 CloseSession(session);
696 // Handshake complete.
697 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
699 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
700 userrec* u = ServerInstance->FindDescriptor(session->fd);
703 if (!u->GetExt("ssl", dummy))
704 u->Extend("ssl", "ON");
707 session->status = ISSL_OPEN;
709 MakePollWrite(session);
715 virtual void OnPostConnect(userrec* user)
717 // This occurs AFTER OnUserConnect so we can be sure the
718 // protocol module has propogated the NICK message.
719 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
721 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
722 std::deque<std::string>* metadata = new std::deque<std::string>;
723 metadata->push_back(user->nick);
724 metadata->push_back("ssl"); // The metadata id
725 metadata->push_back("ON"); // The value to send
726 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
727 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
731 VerifyCertificate(&sessions[user->GetFd()], user);
735 void MakePollWrite(issl_session* session)
737 OnRawSocketWrite(session->fd, NULL, 0);
740 void CloseSession(issl_session* session)
744 SSL_shutdown(session->sess);
745 SSL_free(session->sess);
750 delete[] session->inbuf;
753 session->outbuf.clear();
754 session->inbuf = NULL;
755 session->sess = NULL;
756 session->status = ISSL_NONE;
759 void VerifyCertificate(issl_session* session, Extensible* user)
762 ssl_cert* certinfo = new ssl_cert;
764 unsigned char md[EVP_MAX_MD_SIZE];
765 const EVP_MD *digest = EVP_md5();
767 user->Extend("ssl_cert",certinfo);
769 cert = SSL_get_peer_certificate((SSL*)session->sess);
773 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
777 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
781 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
782 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
786 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
787 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
790 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
791 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
793 if (!X509_digest(cert, digest, md, &n))
795 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
799 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
802 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))
804 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
811 class ModuleSSLOpenSSLFactory : public ModuleFactory
814 ModuleSSLOpenSSLFactory()
818 ~ModuleSSLOpenSSLFactory()
822 virtual Module * CreateModule(InspIRCd* Me)
824 return new ModuleSSLOpenSSL(Me);
829 extern "C" void * init_module( void )
831 return new ModuleSSLOpenSSLFactory;