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 class ModuleSSLOpenSSL : public Module
69 std::vector<int> listenports;
72 issl_session sessions[MAX_DESCRIPTORS];
81 // std::string crlfile;
86 ModuleSSLOpenSSL(InspIRCd* Me)
91 culllist = new CullList(ServerInstance);
93 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
94 inbufsize = ServerInstance->Config->NetBufferSize;
96 /* Global SSL library initialization*/
98 SSL_load_error_strings();
100 /* Build our SSL context*/
101 ctx = SSL_CTX_new( SSLv23_server_method() );
103 // Needs the flag as it ignores a plain /rehash
107 virtual void OnRehash(const std::string ¶m)
112 Conf = new ConfigReader(ServerInstance);
114 for(unsigned int i = 0; i < listenports.size(); i++)
116 ServerInstance->Config->DelIOHook(listenports[i]);
121 for(int i = 0; i < Conf->Enumerate("bind"); i++)
123 // For each <bind> tag
124 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
126 // Get the port we're meant to be listening on with SSL
127 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
128 if (ServerInstance->Config->AddIOHook(port, this))
130 // We keep a record of which ports we're listening on with SSL
131 listenports.push_back(port);
133 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
137 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
142 std::string confdir(CONFIG_FILE);
143 // +1 so we the path ends with a /
144 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
146 cafile = Conf->ReadValue("openssl", "cafile", 0);
147 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
148 certfile = Conf->ReadValue("openssl", "certfile", 0);
149 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
150 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
152 // Set all the default values needed.
157 // crlfile = "crl.pem";
160 certfile = "cert.pem";
166 dhfile = "dhparams.pem";
168 // Prepend relative paths with the path to the config directory.
170 cafile = confdir + cafile;
172 //if(crlfile[0] != '/')
173 // crlfile = confdir + crlfile;
175 if(certfile[0] != '/')
176 certfile = confdir + certfile;
178 if(keyfile[0] != '/')
179 keyfile = confdir + keyfile;
182 dhfile = confdir + dhfile;
184 /* Load our keys and certificates*/
185 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
187 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
190 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
192 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
195 /* Load the CAs we trust*/
196 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
198 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
201 FILE* dhpfile = fopen(dhfile.c_str(), "r");
206 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
207 throw ModuleException();
211 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
213 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
215 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
224 virtual ~ModuleSSLOpenSSL()
230 virtual void OnCleanup(int target_type, void* item)
232 if(target_type == TYPE_USER)
234 userrec* user = (userrec*)item;
236 if(user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
238 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
239 // Potentially there could be multiple SSL modules loaded at once on different ports.
240 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
241 culllist->AddItem(user, "SSL module unloading");
246 virtual void OnUnloadModule(Module* mod, const std::string &name)
250 // We're being unloaded, kill all the users added to the cull list in OnCleanup
251 int numusers = culllist->Apply();
252 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
254 for(unsigned int i = 0; i < listenports.size(); i++)
255 ServerInstance->Config->DelIOHook(listenports[i]);
259 virtual Version GetVersion()
261 return Version(1, 0, 0, 0, VF_VENDOR);
264 void Implements(char* List)
266 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
267 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
270 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
272 issl_session* session = &sessions[fd];
275 session->inbuf = new char[inbufsize];
276 session->inbufoffset = 0;
277 session->sess = SSL_new(ctx);
278 session->status = ISSL_NONE;
280 if(session->sess == NULL)
282 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
286 if(SSL_set_fd(session->sess, fd) == 0)
288 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
295 virtual void OnRawSocketClose(int fd)
297 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
298 CloseSession(&sessions[fd]);
301 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
303 issl_session* session = &sessions[fd];
307 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
309 CloseSession(session);
313 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
315 if(session->status == ISSL_HANDSHAKING)
317 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
319 // The handshake isn't finished and it wants to read, try to finish it.
320 if(Handshake(session))
322 // Handshake successfully resumed.
323 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
327 // Couldn't resume handshake.
328 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
334 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
339 // If we resumed the handshake then session->status will be ISSL_OPEN
341 if(session->status == ISSL_OPEN)
343 if(session->wstat == ISSL_READ)
345 if(DoWrite(session) == 0)
349 if(session->rstat == ISSL_READ)
351 int ret = DoRead(session);
355 if(count <= session->inbufoffset)
357 memcpy(buffer, session->inbuf, count);
358 // Move the stuff left in inbuf to the beginning of it
359 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
360 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
361 session->inbufoffset -= count;
362 // Insp uses readresult as the count of how much data there is in buffer, so:
367 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
368 memcpy(buffer, session->inbuf, session->inbufoffset);
370 readresult = session->inbufoffset;
371 // Zero the offset, as there's nothing there..
372 session->inbufoffset = 0;
387 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
389 issl_session* session = &sessions[fd];
393 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
394 CloseSession(session);
398 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
399 session->outbuf.append(buffer, count);
401 if(session->status == ISSL_HANDSHAKING)
403 // The handshake isn't finished, try to finish it.
404 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
406 if(Handshake(session))
408 // Handshake successfully resumed.
409 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
413 // Couldn't resume handshake.
414 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
419 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
423 if(session->status == ISSL_OPEN)
425 if(session->rstat == ISSL_WRITE)
430 if(session->wstat == ISSL_WRITE)
432 return DoWrite(session);
439 int DoWrite(issl_session* session)
441 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
445 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
446 CloseSession(session);
451 int err = SSL_get_error(session->sess, ret);
453 if(err == SSL_ERROR_WANT_WRITE)
455 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
456 session->wstat = ISSL_WRITE;
459 else if(err == SSL_ERROR_WANT_READ)
461 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
462 session->wstat = ISSL_READ;
467 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
468 CloseSession(session);
474 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
475 session->outbuf = session->outbuf.substr(ret);
480 int DoRead(issl_session* session)
482 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
483 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
484 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
486 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
490 // Client closed connection.
491 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
492 CloseSession(session);
497 int err = SSL_get_error(session->sess, ret);
499 if(err == SSL_ERROR_WANT_READ)
501 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
502 session->rstat = ISSL_READ;
505 else if(err == SSL_ERROR_WANT_WRITE)
507 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
508 session->rstat = ISSL_WRITE;
513 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
514 CloseSession(session);
520 // Read successfully 'ret' bytes into inbuf + inbufoffset
521 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
522 // 'buffer' is 'count' long
524 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);
526 session->inbufoffset += ret;
532 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
533 virtual void OnWhois(userrec* source, userrec* dest)
535 // Bugfix, only send this numeric for *our* SSL users
536 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
538 source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
542 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
544 // check if the linking module wants to know about OUR metadata
547 // check if this user has an swhois field to send
548 if(user->GetExt(extname, dummy))
550 // call this function in the linking module, let it format the data how it
551 // sees fit, and send it on its way. We dont need or want to know how.
552 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
557 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
559 // check if its our metadata key, and its associated with a user
560 if ((target_type == TYPE_USER) && (extname == "ssl"))
562 userrec* dest = (userrec*)target;
563 // if they dont already have an ssl flag, accept the remote server's
564 if (!dest->GetExt(extname, dummy))
566 dest->Extend(extname, "ON");
571 bool Handshake(issl_session* session)
573 int ret = SSL_accept(session->sess);
577 int err = SSL_get_error(session->sess, ret);
579 if(err == SSL_ERROR_WANT_READ)
581 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
582 session->rstat = ISSL_READ;
583 session->status = ISSL_HANDSHAKING;
585 else if(err == SSL_ERROR_WANT_WRITE)
587 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
588 session->wstat = ISSL_WRITE;
589 session->status = ISSL_HANDSHAKING;
590 MakePollWrite(session);
594 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
595 CloseSession(session);
602 // Handshake complete.
603 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
605 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
606 userrec* u = ServerInstance->FindDescriptor(session->fd);
609 if (!u->GetExt("ssl", dummy))
610 u->Extend("ssl", "ON");
613 session->status = ISSL_OPEN;
615 MakePollWrite(session);
621 virtual void OnPostConnect(userrec* user)
623 // This occurs AFTER OnUserConnect so we can be sure the
624 // protocol module has propogated the NICK message.
625 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
627 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
628 std::deque<std::string>* metadata = new std::deque<std::string>;
629 metadata->push_back(user->nick);
630 metadata->push_back("ssl"); // The metadata id
631 metadata->push_back("ON"); // The value to send
632 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
633 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
639 void MakePollWrite(issl_session* session)
641 OnRawSocketWrite(session->fd, NULL, 0);
644 void CloseSession(issl_session* session)
648 SSL_shutdown(session->sess);
649 SSL_free(session->sess);
654 delete[] session->inbuf;
657 session->outbuf.clear();
658 session->inbuf = NULL;
659 session->sess = NULL;
660 session->status = ISSL_NONE;
663 void VerifyCertificate(issl_session* session, userrec* user)
672 class ModuleSSLOpenSSLFactory : public ModuleFactory
675 ModuleSSLOpenSSLFactory()
679 ~ModuleSSLOpenSSLFactory()
683 virtual Module * CreateModule(InspIRCd* Me)
685 return new ModuleSSLOpenSSL(Me);
690 extern "C" void * init_module( void )
692 return new ModuleSSLOpenSSLFactory;