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 class issl_session : public classbase
52 unsigned int inbufoffset;
53 char* inbuf; // Buffer OpenSSL reads into.
54 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
64 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
66 /* XXX: This will allow self signed certificates.
67 * In the future if we want an option to not allow this,
68 * we can just return preverify_ok here, and openssl
69 * will boot off self-signed and invalid peer certs.
71 int ve = X509_STORE_CTX_get_error(ctx);
73 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
78 class ModuleSSLOpenSSL : public Module
85 std::vector<int> listenports;
88 issl_session sessions[MAX_DESCRIPTORS];
97 // std::string crlfile;
102 ModuleSSLOpenSSL(InspIRCd* Me)
105 culllist = new CullList(ServerInstance);
107 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
108 inbufsize = ServerInstance->Config->NetBufferSize;
110 /* Global SSL library initialization*/
112 SSL_load_error_strings();
114 /* Build our SSL context*/
115 ctx = SSL_CTX_new( SSLv23_server_method() );
117 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
119 // Needs the flag as it ignores a plain /rehash
123 virtual void OnRehash(const std::string ¶m)
128 Conf = new ConfigReader(ServerInstance);
130 for(unsigned int i = 0; i < listenports.size(); i++)
132 ServerInstance->Config->DelIOHook(listenports[i]);
137 for(int i = 0; i < Conf->Enumerate("bind"); i++)
139 // For each <bind> tag
140 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
142 // Get the port we're meant to be listening on with SSL
143 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
144 if (ServerInstance->Config->AddIOHook(port, this))
146 // We keep a record of which ports we're listening on with SSL
147 listenports.push_back(port);
149 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
153 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
158 std::string confdir(CONFIG_FILE);
159 // +1 so we the path ends with a /
160 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
162 cafile = Conf->ReadValue("openssl", "cafile", 0);
163 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
164 certfile = Conf->ReadValue("openssl", "certfile", 0);
165 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
166 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
168 // Set all the default values needed.
173 // crlfile = "crl.pem";
176 certfile = "cert.pem";
182 dhfile = "dhparams.pem";
184 // Prepend relative paths with the path to the config directory.
186 cafile = confdir + cafile;
188 //if(crlfile[0] != '/')
189 // crlfile = confdir + crlfile;
191 if(certfile[0] != '/')
192 certfile = confdir + certfile;
194 if(keyfile[0] != '/')
195 keyfile = confdir + keyfile;
198 dhfile = confdir + dhfile;
200 /* Load our keys and certificates*/
201 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
203 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
206 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
208 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
211 /* Load the CAs we trust*/
212 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
214 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
217 FILE* dhpfile = fopen(dhfile.c_str(), "r");
222 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
223 throw ModuleException();
227 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
229 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
231 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
240 virtual ~ModuleSSLOpenSSL()
246 virtual void OnCleanup(int target_type, void* item)
248 if(target_type == TYPE_USER)
250 userrec* user = (userrec*)item;
252 if(user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
254 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
255 // Potentially there could be multiple SSL modules loaded at once on different ports.
256 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
257 culllist->AddItem(user, "SSL module unloading");
259 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
262 user->GetExt("ssl_cert", tofree);
264 user->Shrink("ssl_cert");
269 virtual void OnUnloadModule(Module* mod, const std::string &name)
273 // We're being unloaded, kill all the users added to the cull list in OnCleanup
274 int numusers = culllist->Apply();
275 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
277 for(unsigned int i = 0; i < listenports.size(); i++)
278 ServerInstance->Config->DelIOHook(listenports[i]);
282 virtual Version GetVersion()
284 return Version(1, 0, 0, 0, VF_VENDOR);
287 void Implements(char* List)
289 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
290 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
293 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
295 issl_session* session = &sessions[fd];
298 session->inbuf = new char[inbufsize];
299 session->inbufoffset = 0;
300 session->sess = SSL_new(ctx);
301 session->status = ISSL_NONE;
303 if(session->sess == NULL)
305 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
309 if(SSL_set_fd(session->sess, fd) == 0)
311 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
318 virtual void OnRawSocketClose(int fd)
320 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
321 CloseSession(&sessions[fd]);
323 EventHandler* user = ServerInstance->SE->GetRef(fd);
325 if ((user) && (user->GetExt("ssl_cert", dummy)))
328 user->GetExt("ssl_cert", tofree);
330 user->Shrink("ssl_cert");
334 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
336 issl_session* session = &sessions[fd];
340 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
342 CloseSession(session);
346 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
348 if(session->status == ISSL_HANDSHAKING)
350 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
352 // The handshake isn't finished and it wants to read, try to finish it.
353 if(Handshake(session))
355 // Handshake successfully resumed.
356 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
360 // Couldn't resume handshake.
361 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
367 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
372 // If we resumed the handshake then session->status will be ISSL_OPEN
374 if(session->status == ISSL_OPEN)
376 if(session->wstat == ISSL_READ)
378 if(DoWrite(session) == 0)
382 if(session->rstat == ISSL_READ)
384 int ret = DoRead(session);
388 if(count <= session->inbufoffset)
390 memcpy(buffer, session->inbuf, count);
391 // Move the stuff left in inbuf to the beginning of it
392 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
393 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
394 session->inbufoffset -= count;
395 // Insp uses readresult as the count of how much data there is in buffer, so:
400 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
401 memcpy(buffer, session->inbuf, session->inbufoffset);
403 readresult = session->inbufoffset;
404 // Zero the offset, as there's nothing there..
405 session->inbufoffset = 0;
420 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
422 issl_session* session = &sessions[fd];
426 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
427 CloseSession(session);
431 session->outbuf.append(buffer, count);
433 if(session->status == ISSL_HANDSHAKING)
435 // The handshake isn't finished, try to finish it.
436 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
438 if(Handshake(session))
440 // Handshake successfully resumed.
441 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
445 // Couldn't resume handshake.
446 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
451 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
455 if(session->status == ISSL_OPEN)
457 if(session->rstat == ISSL_WRITE)
462 if(session->wstat == ISSL_WRITE)
464 return DoWrite(session);
471 int DoWrite(issl_session* session)
473 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
477 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
478 CloseSession(session);
483 int err = SSL_get_error(session->sess, ret);
485 if(err == SSL_ERROR_WANT_WRITE)
487 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
488 session->wstat = ISSL_WRITE;
491 else if(err == SSL_ERROR_WANT_READ)
493 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
494 session->wstat = ISSL_READ;
499 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
500 CloseSession(session);
506 session->outbuf = session->outbuf.substr(ret);
511 int DoRead(issl_session* session)
513 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
514 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
516 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
520 // Client closed connection.
521 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
522 CloseSession(session);
527 int err = SSL_get_error(session->sess, ret);
529 if(err == SSL_ERROR_WANT_READ)
531 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
532 session->rstat = ISSL_READ;
535 else if(err == SSL_ERROR_WANT_WRITE)
537 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
538 session->rstat = ISSL_WRITE;
543 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
544 CloseSession(session);
550 // Read successfully 'ret' bytes into inbuf + inbufoffset
551 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
552 // 'buffer' is 'count' long
554 session->inbufoffset += ret;
560 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
561 virtual void OnWhois(userrec* source, userrec* dest)
563 // Bugfix, only send this numeric for *our* SSL users
564 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
566 source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
570 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
572 // check if the linking module wants to know about OUR metadata
575 // check if this user has an swhois field to send
576 if(user->GetExt(extname, dummy))
578 // call this function in the linking module, let it format the data how it
579 // sees fit, and send it on its way. We dont need or want to know how.
580 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
585 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
587 // check if its our metadata key, and its associated with a user
588 if ((target_type == TYPE_USER) && (extname == "ssl"))
590 userrec* dest = (userrec*)target;
591 // if they dont already have an ssl flag, accept the remote server's
592 if (!dest->GetExt(extname, dummy))
594 dest->Extend(extname, "ON");
599 bool Handshake(issl_session* session)
601 int ret = SSL_accept(session->sess);
605 int err = SSL_get_error(session->sess, ret);
607 if(err == SSL_ERROR_WANT_READ)
609 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
610 session->rstat = ISSL_READ;
611 session->status = ISSL_HANDSHAKING;
613 else if(err == SSL_ERROR_WANT_WRITE)
615 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
616 session->wstat = ISSL_WRITE;
617 session->status = ISSL_HANDSHAKING;
618 MakePollWrite(session);
622 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
623 CloseSession(session);
630 // Handshake complete.
631 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
633 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
634 userrec* u = ServerInstance->FindDescriptor(session->fd);
637 if (!u->GetExt("ssl", dummy))
638 u->Extend("ssl", "ON");
641 session->status = ISSL_OPEN;
643 MakePollWrite(session);
649 virtual void OnPostConnect(userrec* user)
651 // This occurs AFTER OnUserConnect so we can be sure the
652 // protocol module has propogated the NICK message.
653 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
655 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
656 std::deque<std::string>* metadata = new std::deque<std::string>;
657 metadata->push_back(user->nick);
658 metadata->push_back("ssl"); // The metadata id
659 metadata->push_back("ON"); // The value to send
660 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
661 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
665 VerifyCertificate(&sessions[user->GetFd()], user);
669 void MakePollWrite(issl_session* session)
671 OnRawSocketWrite(session->fd, NULL, 0);
674 void CloseSession(issl_session* session)
678 SSL_shutdown(session->sess);
679 SSL_free(session->sess);
684 delete[] session->inbuf;
687 session->outbuf.clear();
688 session->inbuf = NULL;
689 session->sess = NULL;
690 session->status = ISSL_NONE;
693 void VerifyCertificate(issl_session* session, userrec* user)
696 ssl_cert* certinfo = new ssl_cert;
698 unsigned char md[EVP_MAX_MD_SIZE];
699 const EVP_MD *digest = EVP_md5();
702 user->Extend("ssl_cert",certinfo);
704 cert = SSL_get_peer_certificate((SSL*)session->sess);
708 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
712 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
716 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
717 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
721 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
722 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
725 /*if (!X509_verify_cert(cert))
727 certinfo->data.insert(std::make_pair("invalid",ConvToStr(1)));
731 certinfo->data.insert(std::make_pair("invalid",ConvToStr(0)));
734 //X509_NAME_oneline(nm, 0, 0);
735 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
736 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
738 if (!X509_digest(cert, digest, md, &n))
740 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
744 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
747 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))
749 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
754 class ModuleSSLOpenSSLFactory : public ModuleFactory
757 ModuleSSLOpenSSLFactory()
761 ~ModuleSSLOpenSSLFactory()
765 virtual Module * CreateModule(InspIRCd* Me)
767 return new ModuleSSLOpenSSL(Me);
772 extern "C" void * init_module( void )
774 return new ModuleSSLOpenSSLFactory;