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 // 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::portparser portrange(port, false);
148 while ((portno = portrange.GetToken()))
150 if (ServerInstance->Config->AddIOHook(portno, this))
152 listenports.push_back(portno);
153 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
157 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
163 std::string confdir(CONFIG_FILE);
164 // +1 so we the path ends with a /
165 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
167 cafile = Conf->ReadValue("openssl", "cafile", 0);
168 certfile = Conf->ReadValue("openssl", "certfile", 0);
169 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
170 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
172 // Set all the default values needed.
177 certfile = "cert.pem";
183 dhfile = "dhparams.pem";
185 // Prepend relative paths with the path to the config directory.
186 if (cafile[0] != '/')
187 cafile = confdir + cafile;
189 //if(crlfile[0] != '/')
190 // crlfile = confdir + crlfile;
192 if (certfile[0] != '/')
193 certfile = confdir + certfile;
195 if (keyfile[0] != '/')
196 keyfile = confdir + keyfile;
198 if (dhfile[0] != '/')
199 dhfile = confdir + dhfile;
201 /* Load our keys and certificates*/
202 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
204 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
207 if (!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
209 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
212 /* Load the CAs we trust*/
213 if (!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
215 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
218 FILE* dhpfile = fopen(dhfile.c_str(), "r");
223 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
224 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
228 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
230 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
232 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
241 virtual ~ModuleSSLOpenSSL()
247 virtual void OnCleanup(int target_type, void* item)
249 if (target_type == TYPE_USER)
251 userrec* user = (userrec*)item;
253 if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
255 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
256 // Potentially there could be multiple SSL modules loaded at once on different ports.
257 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
258 culllist->AddItem(user, "SSL module unloading");
260 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
263 user->GetExt("ssl_cert", tofree);
265 user->Shrink("ssl_cert");
270 virtual void OnUnloadModule(Module* mod, const std::string &name)
274 // We're being unloaded, kill all the users added to the cull list in OnCleanup
275 int numusers = culllist->Apply();
276 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
278 for(unsigned int i = 0; i < listenports.size(); i++)
279 ServerInstance->Config->DelIOHook(listenports[i]);
283 virtual Version GetVersion()
285 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
288 void Implements(char* List)
290 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
291 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
294 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
296 issl_session* session = &sessions[fd];
299 session->inbuf = new char[inbufsize];
300 session->inbufoffset = 0;
301 session->sess = SSL_new(ctx);
302 session->status = ISSL_NONE;
304 if (session->sess == NULL)
306 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
310 if (SSL_set_fd(session->sess, fd) == 0)
312 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
319 virtual void OnRawSocketConnect(int fd)
321 issl_session* session = &sessions[fd];
324 session->inbuf = new char[inbufsize];
325 session->inbufoffset = 0;
326 session->sess = SSL_new(ctx);
327 session->status = ISSL_NONE;
329 if (session->sess == NULL)
331 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
335 if (SSL_set_fd(session->sess, fd) == 0)
337 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
344 virtual void OnRawSocketClose(int fd)
346 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
347 CloseSession(&sessions[fd]);
349 EventHandler* user = ServerInstance->SE->GetRef(fd);
351 if ((user) && (user->GetExt("ssl_cert", dummy)))
354 user->GetExt("ssl_cert", tofree);
356 user->Shrink("ssl_cert");
360 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
362 issl_session* session = &sessions[fd];
366 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
368 CloseSession(session);
372 if (session->status == ISSL_HANDSHAKING)
374 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
376 // The handshake isn't finished and it wants to read, try to finish it.
377 if (Handshake(session))
379 // Handshake successfully resumed.
380 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
384 // Couldn't resume handshake.
385 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
391 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
396 // If we resumed the handshake then session->status will be ISSL_OPEN
398 if (session->status == ISSL_OPEN)
400 if (session->wstat == ISSL_READ)
402 if(DoWrite(session) == 0)
406 if (session->rstat == ISSL_READ)
408 int ret = DoRead(session);
412 if (count <= session->inbufoffset)
414 memcpy(buffer, session->inbuf, count);
415 // Move the stuff left in inbuf to the beginning of it
416 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
417 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
418 session->inbufoffset -= count;
419 // Insp uses readresult as the count of how much data there is in buffer, so:
424 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
425 memcpy(buffer, session->inbuf, session->inbufoffset);
427 readresult = session->inbufoffset;
428 // Zero the offset, as there's nothing there..
429 session->inbufoffset = 0;
444 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
446 issl_session* session = &sessions[fd];
450 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
451 CloseSession(session);
455 session->outbuf.append(buffer, count);
457 if (session->status == ISSL_HANDSHAKING)
459 // The handshake isn't finished, try to finish it.
460 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
462 if (Handshake(session))
464 // Handshake successfully resumed.
465 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
469 // Couldn't resume handshake.
470 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
475 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
479 if (session->status == ISSL_OPEN)
481 if (session->rstat == ISSL_WRITE)
486 if (session->wstat == ISSL_WRITE)
488 return DoWrite(session);
495 int DoWrite(issl_session* session)
497 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
501 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
502 CloseSession(session);
507 int err = SSL_get_error(session->sess, ret);
509 if (err == SSL_ERROR_WANT_WRITE)
511 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
512 session->wstat = ISSL_WRITE;
515 else if (err == SSL_ERROR_WANT_READ)
517 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
518 session->wstat = ISSL_READ;
523 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
524 CloseSession(session);
530 session->outbuf = session->outbuf.substr(ret);
535 int DoRead(issl_session* session)
537 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
538 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
540 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
544 // Client closed connection.
545 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
546 CloseSession(session);
551 int err = SSL_get_error(session->sess, ret);
553 if (err == SSL_ERROR_WANT_READ)
555 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
556 session->rstat = ISSL_READ;
559 else if (err == SSL_ERROR_WANT_WRITE)
561 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
562 session->rstat = ISSL_WRITE;
567 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
568 CloseSession(session);
574 // Read successfully 'ret' bytes into inbuf + inbufoffset
575 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
576 // 'buffer' is 'count' long
578 session->inbufoffset += ret;
584 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
585 virtual void OnWhois(userrec* source, userrec* dest)
587 // Bugfix, only send this numeric for *our* SSL users
588 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
590 ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
594 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
596 // check if the linking module wants to know about OUR metadata
597 if (extname == "ssl")
599 // check if this user has an swhois field to send
600 if(user->GetExt(extname, dummy))
602 // call this function in the linking module, let it format the data how it
603 // sees fit, and send it on its way. We dont need or want to know how.
604 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
609 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
611 // check if its our metadata key, and its associated with a user
612 if ((target_type == TYPE_USER) && (extname == "ssl"))
614 userrec* dest = (userrec*)target;
615 // if they dont already have an ssl flag, accept the remote server's
616 if (!dest->GetExt(extname, dummy))
618 dest->Extend(extname, "ON");
623 bool Handshake(issl_session* session)
625 int ret = SSL_accept(session->sess);
629 int err = SSL_get_error(session->sess, ret);
631 if (err == SSL_ERROR_WANT_READ)
633 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
634 session->rstat = ISSL_READ;
635 session->status = ISSL_HANDSHAKING;
637 else if (err == SSL_ERROR_WANT_WRITE)
639 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
640 session->wstat = ISSL_WRITE;
641 session->status = ISSL_HANDSHAKING;
642 MakePollWrite(session);
646 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
647 CloseSession(session);
654 // Handshake complete.
655 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
657 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
658 userrec* u = ServerInstance->FindDescriptor(session->fd);
661 if (!u->GetExt("ssl", dummy))
662 u->Extend("ssl", "ON");
665 session->status = ISSL_OPEN;
667 MakePollWrite(session);
673 virtual void OnPostConnect(userrec* user)
675 // This occurs AFTER OnUserConnect so we can be sure the
676 // protocol module has propogated the NICK message.
677 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
679 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
680 std::deque<std::string>* metadata = new std::deque<std::string>;
681 metadata->push_back(user->nick);
682 metadata->push_back("ssl"); // The metadata id
683 metadata->push_back("ON"); // The value to send
684 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
685 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
689 VerifyCertificate(&sessions[user->GetFd()], user);
693 void MakePollWrite(issl_session* session)
695 OnRawSocketWrite(session->fd, NULL, 0);
698 void CloseSession(issl_session* session)
702 SSL_shutdown(session->sess);
703 SSL_free(session->sess);
708 delete[] session->inbuf;
711 session->outbuf.clear();
712 session->inbuf = NULL;
713 session->sess = NULL;
714 session->status = ISSL_NONE;
717 void VerifyCertificate(issl_session* session, userrec* user)
720 ssl_cert* certinfo = new ssl_cert;
722 unsigned char md[EVP_MAX_MD_SIZE];
723 const EVP_MD *digest = EVP_md5();
725 user->Extend("ssl_cert",certinfo);
727 cert = SSL_get_peer_certificate((SSL*)session->sess);
731 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
735 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
739 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
740 certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
744 certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
745 certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
748 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
749 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
751 if (!X509_digest(cert, digest, md, &n))
753 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
757 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
760 user->WriteServ("NOTICE %s :*** Your SSL Certificate fingerprint is: %s", user->nick, irc::hex(md, n).c_str());
762 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))
764 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
771 class ModuleSSLOpenSSLFactory : public ModuleFactory
774 ModuleSSLOpenSSLFactory()
778 ~ModuleSSLOpenSSLFactory()
782 virtual Module * CreateModule(InspIRCd* Me)
784 return new ModuleSSLOpenSSL(Me);
789 extern "C" void * init_module( void )
791 return new ModuleSSLOpenSSLFactory;