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 bool isin(int port, const std::vector<int> &portlist)
30 for(unsigned int i = 0; i < portlist.size(); i++)
31 if(portlist[i] == port)
39 return ERR_error_string(ERR_get_error(), NULL);
42 class issl_session : public classbase
50 unsigned int inbufoffset;
51 char* inbuf; // Buffer OpenSSL reads into.
52 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
62 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
64 /* XXX: This will allow self signed certificates.
65 * In the future if we want an option to not allow this,
66 * we can just return preverify_ok here, and openssl
67 * will boot off self-signed and invalid peer certs.
72 class ModuleSSLOpenSSL : public Module
79 std::vector<int> listenports;
82 issl_session sessions[MAX_DESCRIPTORS];
91 // std::string crlfile;
96 ModuleSSLOpenSSL(InspIRCd* Me)
99 culllist = new CullList(ServerInstance);
101 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
102 inbufsize = ServerInstance->Config->NetBufferSize;
104 /* Global SSL library initialization*/
106 SSL_load_error_strings();
108 /* Build our SSL context*/
109 ctx = SSL_CTX_new( SSLv23_server_method() );
111 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
113 // Needs the flag as it ignores a plain /rehash
117 virtual void OnRehash(const std::string ¶m)
122 Conf = new ConfigReader(ServerInstance);
124 for(unsigned int i = 0; i < listenports.size(); i++)
126 ServerInstance->Config->DelIOHook(listenports[i]);
131 for(int i = 0; i < Conf->Enumerate("bind"); i++)
133 // For each <bind> tag
134 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
136 // Get the port we're meant to be listening on with SSL
137 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
138 if (ServerInstance->Config->AddIOHook(port, this))
140 // We keep a record of which ports we're listening on with SSL
141 listenports.push_back(port);
143 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
147 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
152 std::string confdir(CONFIG_FILE);
153 // +1 so we the path ends with a /
154 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
156 cafile = Conf->ReadValue("openssl", "cafile", 0);
157 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
158 certfile = Conf->ReadValue("openssl", "certfile", 0);
159 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
160 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
162 // Set all the default values needed.
167 // crlfile = "crl.pem";
170 certfile = "cert.pem";
176 dhfile = "dhparams.pem";
178 // Prepend relative paths with the path to the config directory.
180 cafile = confdir + cafile;
182 //if(crlfile[0] != '/')
183 // crlfile = confdir + crlfile;
185 if(certfile[0] != '/')
186 certfile = confdir + certfile;
188 if(keyfile[0] != '/')
189 keyfile = confdir + keyfile;
192 dhfile = confdir + dhfile;
194 /* Load our keys and certificates*/
195 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
197 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
200 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
202 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
205 /* Load the CAs we trust*/
206 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
208 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
211 FILE* dhpfile = fopen(dhfile.c_str(), "r");
216 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
217 throw ModuleException();
221 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
223 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
225 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
234 virtual ~ModuleSSLOpenSSL()
240 virtual void OnCleanup(int target_type, void* item)
242 if(target_type == TYPE_USER)
244 userrec* user = (userrec*)item;
246 if(user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
248 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
249 // Potentially there could be multiple SSL modules loaded at once on different ports.
250 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
251 culllist->AddItem(user, "SSL module unloading");
253 if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
256 user->GetExt("ssl_cert", tofree);
258 user->Shrink("ssl_cert");
263 virtual void OnUnloadModule(Module* mod, const std::string &name)
267 // We're being unloaded, kill all the users added to the cull list in OnCleanup
268 int numusers = culllist->Apply();
269 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
271 for(unsigned int i = 0; i < listenports.size(); i++)
272 ServerInstance->Config->DelIOHook(listenports[i]);
276 virtual Version GetVersion()
278 return Version(1, 0, 0, 0, VF_VENDOR);
281 void Implements(char* List)
283 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
284 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
287 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
289 issl_session* session = &sessions[fd];
292 session->inbuf = new char[inbufsize];
293 session->inbufoffset = 0;
294 session->sess = SSL_new(ctx);
295 session->status = ISSL_NONE;
297 if(session->sess == NULL)
299 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
303 if(SSL_set_fd(session->sess, fd) == 0)
305 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
312 virtual void OnRawSocketClose(int fd)
314 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
315 CloseSession(&sessions[fd]);
318 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
320 issl_session* session = &sessions[fd];
324 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
326 CloseSession(session);
330 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
332 if(session->status == ISSL_HANDSHAKING)
334 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
336 // The handshake isn't finished and it wants to read, try to finish it.
337 if(Handshake(session))
339 // Handshake successfully resumed.
340 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
344 // Couldn't resume handshake.
345 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
351 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
356 // If we resumed the handshake then session->status will be ISSL_OPEN
358 if(session->status == ISSL_OPEN)
360 if(session->wstat == ISSL_READ)
362 if(DoWrite(session) == 0)
366 if(session->rstat == ISSL_READ)
368 int ret = DoRead(session);
372 if(count <= session->inbufoffset)
374 memcpy(buffer, session->inbuf, count);
375 // Move the stuff left in inbuf to the beginning of it
376 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
377 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
378 session->inbufoffset -= count;
379 // Insp uses readresult as the count of how much data there is in buffer, so:
384 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
385 memcpy(buffer, session->inbuf, session->inbufoffset);
387 readresult = session->inbufoffset;
388 // Zero the offset, as there's nothing there..
389 session->inbufoffset = 0;
404 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
406 issl_session* session = &sessions[fd];
410 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
411 CloseSession(session);
415 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
416 session->outbuf.append(buffer, count);
418 if(session->status == ISSL_HANDSHAKING)
420 // The handshake isn't finished, try to finish it.
421 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
423 if(Handshake(session))
425 // Handshake successfully resumed.
426 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
430 // Couldn't resume handshake.
431 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
436 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
440 if(session->status == ISSL_OPEN)
442 if(session->rstat == ISSL_WRITE)
447 if(session->wstat == ISSL_WRITE)
449 return DoWrite(session);
456 int DoWrite(issl_session* session)
458 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
462 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
463 CloseSession(session);
468 int err = SSL_get_error(session->sess, ret);
470 if(err == SSL_ERROR_WANT_WRITE)
472 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
473 session->wstat = ISSL_WRITE;
476 else if(err == SSL_ERROR_WANT_READ)
478 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
479 session->wstat = ISSL_READ;
484 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
485 CloseSession(session);
491 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
492 session->outbuf = session->outbuf.substr(ret);
497 int DoRead(issl_session* session)
499 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
500 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
501 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
503 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
507 // Client closed connection.
508 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
509 CloseSession(session);
514 int err = SSL_get_error(session->sess, ret);
516 if(err == SSL_ERROR_WANT_READ)
518 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
519 session->rstat = ISSL_READ;
522 else if(err == SSL_ERROR_WANT_WRITE)
524 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
525 session->rstat = ISSL_WRITE;
530 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
531 CloseSession(session);
537 // Read successfully 'ret' bytes into inbuf + inbufoffset
538 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
539 // 'buffer' is 'count' long
541 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);
543 session->inbufoffset += ret;
549 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
550 virtual void OnWhois(userrec* source, userrec* dest)
552 // Bugfix, only send this numeric for *our* SSL users
553 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
555 source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
559 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
561 // check if the linking module wants to know about OUR metadata
564 // check if this user has an swhois field to send
565 if(user->GetExt(extname, dummy))
567 // call this function in the linking module, let it format the data how it
568 // sees fit, and send it on its way. We dont need or want to know how.
569 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
574 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
576 // check if its our metadata key, and its associated with a user
577 if ((target_type == TYPE_USER) && (extname == "ssl"))
579 userrec* dest = (userrec*)target;
580 // if they dont already have an ssl flag, accept the remote server's
581 if (!dest->GetExt(extname, dummy))
583 dest->Extend(extname, "ON");
588 bool Handshake(issl_session* session)
590 int ret = SSL_accept(session->sess);
594 int err = SSL_get_error(session->sess, ret);
596 if(err == SSL_ERROR_WANT_READ)
598 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
599 session->rstat = ISSL_READ;
600 session->status = ISSL_HANDSHAKING;
602 else if(err == SSL_ERROR_WANT_WRITE)
604 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
605 session->wstat = ISSL_WRITE;
606 session->status = ISSL_HANDSHAKING;
607 MakePollWrite(session);
611 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
612 CloseSession(session);
619 // Handshake complete.
620 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
622 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
623 userrec* u = ServerInstance->FindDescriptor(session->fd);
626 if (!u->GetExt("ssl", dummy))
627 u->Extend("ssl", "ON");
630 session->status = ISSL_OPEN;
632 MakePollWrite(session);
638 virtual void OnPostConnect(userrec* user)
640 // This occurs AFTER OnUserConnect so we can be sure the
641 // protocol module has propogated the NICK message.
642 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
644 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
645 std::deque<std::string>* metadata = new std::deque<std::string>;
646 metadata->push_back(user->nick);
647 metadata->push_back("ssl"); // The metadata id
648 metadata->push_back("ON"); // The value to send
649 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
650 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
654 VerifyCertificate(&sessions[user->GetFd()], user);
658 void MakePollWrite(issl_session* session)
660 OnRawSocketWrite(session->fd, NULL, 0);
663 void CloseSession(issl_session* session)
667 SSL_shutdown(session->sess);
668 SSL_free(session->sess);
673 delete[] session->inbuf;
676 session->outbuf.clear();
677 session->inbuf = NULL;
678 session->sess = NULL;
679 session->status = ISSL_NONE;
682 void VerifyCertificate(issl_session* session, userrec* user)
685 ssl_cert* certinfo = new ssl_cert;
687 unsigned char md[EVP_MAX_MD_SIZE];
688 const EVP_MD *digest = EVP_md5();
691 user->Extend("ssl_cert",certinfo);
693 cert = SSL_get_peer_certificate((SSL*)session->sess);
697 certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
701 /*if (!X509_verify_cert(cert))
703 certinfo->data.insert(std::make_pair("invalid",ConvToStr(1)));
707 certinfo->data.insert(std::make_pair("invalid",ConvToStr(0)));
710 //X509_NAME_oneline(nm, 0, 0);
711 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
712 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
714 if (!X509_digest(cert, digest, md, &n))
716 certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
720 certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
723 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))
725 certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
730 class ModuleSSLOpenSSLFactory : public ModuleFactory
733 ModuleSSLOpenSSLFactory()
737 ~ModuleSSLOpenSSLFactory()
741 virtual Module * CreateModule(InspIRCd* Me)
743 return new ModuleSSLOpenSSL(Me);
748 extern "C" void * init_module( void )
750 return new ModuleSSLOpenSSLFactory;