4 #include <openssl/ssl.h>
5 #include <openssl/err.h>
7 #include "inspircd_config.h"
8 #include "configreader.h"
12 #include "helperfuncs.h"
17 /* $ModDesc: Provides SSL support for clients */
18 /* $CompileFlags: -I/usr/include -I/usr/local/include */
19 /* $LinkerFlags: -L/usr/local/lib -Wl,--rpath -Wl,/usr/local/lib -L/usr/lib -Wl,--rpath -Wl,/usr/lib -lssl */
21 extern InspIRCd* ServerInstance;
23 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
24 enum issl_io_status { ISSL_WRITE, ISSL_READ };
26 bool isin(int port, const std::vector<int> &portlist)
28 for(unsigned int i = 0; i < portlist.size(); i++)
29 if(portlist[i] == port)
37 return ERR_error_string(ERR_get_error(), NULL);
40 class issl_session : public classbase
48 unsigned int inbufoffset;
49 char* inbuf; // Buffer OpenSSL reads into.
50 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
60 class ModuleSSLOpenSSL : public Module
67 std::vector<int> listenports;
70 issl_session sessions[MAX_DESCRIPTORS];
79 // std::string crlfile;
84 ModuleSSLOpenSSL(Server* Me)
89 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
90 inbufsize = ServerInstance->Config->NetBufferSize;
92 /* Global SSL library initialization*/
94 SSL_load_error_strings();
96 /* Build our SSL context*/
97 ctx = SSL_CTX_new( SSLv23_server_method() );
99 // Needs the flag as it ignores a plain /rehash
103 virtual void OnRehash(const std::string ¶m)
108 Conf = new ConfigReader;
110 for(unsigned int i = 0; i < listenports.size(); i++)
112 ServerInstance->Config->DelIOHook(listenports[i]);
117 for(int i = 0; i < Conf->Enumerate("bind"); i++)
119 // For each <bind> tag
120 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
122 // Get the port we're meant to be listening on with SSL
123 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
124 if (ServerInstance->Config->AddIOHook(port, this))
126 // We keep a record of which ports we're listening on with SSL
127 listenports.push_back(port);
129 log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
133 log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
138 std::string confdir(CONFIG_FILE);
139 // +1 so we the path ends with a /
140 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
142 cafile = Conf->ReadValue("openssl", "cafile", 0);
143 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
144 certfile = Conf->ReadValue("openssl", "certfile", 0);
145 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
146 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
148 // Set all the default values needed.
153 // crlfile = "crl.pem";
156 certfile = "cert.pem";
162 dhfile = "dhparams.pem";
164 // Prepend relative paths with the path to the config directory.
166 cafile = confdir + cafile;
168 //if(crlfile[0] != '/')
169 // crlfile = confdir + crlfile;
171 if(certfile[0] != '/')
172 certfile = confdir + certfile;
174 if(keyfile[0] != '/')
175 keyfile = confdir + keyfile;
178 dhfile = confdir + dhfile;
180 /* Load our keys and certificates*/
181 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
183 log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
186 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
188 log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
191 /* Load the CAs we trust*/
192 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
194 log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
197 FILE* dhpfile = fopen(dhfile.c_str(), "r");
202 log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
203 throw ModuleException();
207 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
209 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
211 log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
220 virtual ~ModuleSSLOpenSSL()
225 virtual void OnCleanup(int target_type, void* item)
227 if(target_type == TYPE_USER)
229 userrec* user = (userrec*)item;
231 if(user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
233 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
234 // Potentially there could be multiple SSL modules loaded at once on different ports.
235 log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
236 culllist.AddItem(user, "SSL module unloading");
241 virtual void OnUnloadModule(Module* mod, const std::string &name)
245 // We're being unloaded, kill all the users added to the cull list in OnCleanup
246 int numusers = culllist.Apply();
247 log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
249 for(unsigned int i = 0; i < listenports.size(); i++)
250 ServerInstance->Config->DelIOHook(listenports[i]);
254 virtual Version GetVersion()
256 return Version(1, 0, 0, 0, VF_VENDOR);
259 void Implements(char* List)
261 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
262 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
265 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
267 issl_session* session = &sessions[fd];
270 session->inbuf = new char[inbufsize];
271 session->inbufoffset = 0;
272 session->sess = SSL_new(ctx);
273 session->status = ISSL_NONE;
275 if(session->sess == NULL)
277 log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
281 if(SSL_set_fd(session->sess, fd) == 0)
283 log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
290 virtual void OnRawSocketClose(int fd)
292 log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
293 CloseSession(&sessions[fd]);
296 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
298 issl_session* session = &sessions[fd];
302 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
304 CloseSession(session);
308 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
310 if(session->status == ISSL_HANDSHAKING)
312 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
314 // The handshake isn't finished and it wants to read, try to finish it.
315 if(Handshake(session))
317 // Handshake successfully resumed.
318 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
322 // Couldn't resume handshake.
323 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
329 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
334 // If we resumed the handshake then session->status will be ISSL_OPEN
336 if(session->status == ISSL_OPEN)
338 if(session->wstat == ISSL_READ)
340 if(DoWrite(session) == 0)
344 if(session->rstat == ISSL_READ)
346 int ret = DoRead(session);
350 if(count <= session->inbufoffset)
352 memcpy(buffer, session->inbuf, count);
353 // Move the stuff left in inbuf to the beginning of it
354 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
355 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
356 session->inbufoffset -= count;
357 // Insp uses readresult as the count of how much data there is in buffer, so:
362 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
363 memcpy(buffer, session->inbuf, session->inbufoffset);
365 readresult = session->inbufoffset;
366 // Zero the offset, as there's nothing there..
367 session->inbufoffset = 0;
370 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: Passing %d bytes up to insp:", count);
371 Srv->Log(DEBUG, std::string(buffer, readresult));
385 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
387 issl_session* session = &sessions[fd];
391 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
392 CloseSession(session);
396 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
397 session->outbuf.append(buffer, count);
399 if(session->status == ISSL_HANDSHAKING)
401 // The handshake isn't finished, try to finish it.
402 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
404 if(Handshake(session))
406 // Handshake successfully resumed.
407 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
411 // Couldn't resume handshake.
412 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
417 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
421 if(session->status == ISSL_OPEN)
423 if(session->rstat == ISSL_WRITE)
428 if(session->wstat == ISSL_WRITE)
430 return DoWrite(session);
437 int DoWrite(issl_session* session)
439 log(DEBUG, "m_ssl_openssl.so: DoWrite: Trying to write %d bytes:", session->outbuf.size());
440 Srv->Log(DEBUG, session->outbuf);
442 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
446 log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
447 CloseSession(session);
452 int err = SSL_get_error(session->sess, ret);
454 if(err == SSL_ERROR_WANT_WRITE)
456 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
457 session->wstat = ISSL_WRITE;
460 else if(err == SSL_ERROR_WANT_READ)
462 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
463 session->wstat = ISSL_READ;
468 log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
469 CloseSession(session);
475 log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
476 session->outbuf = session->outbuf.substr(ret);
481 int DoRead(issl_session* session)
483 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
484 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
485 log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
487 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
491 // Client closed connection.
492 log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
493 CloseSession(session);
498 int err = SSL_get_error(session->sess, ret);
500 if(err == SSL_ERROR_WANT_READ)
502 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
503 session->rstat = ISSL_READ;
506 else if(err == SSL_ERROR_WANT_WRITE)
508 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
509 session->rstat = ISSL_WRITE;
514 log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
515 CloseSession(session);
521 // Read successfully 'ret' bytes into inbuf + inbufoffset
522 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
523 // 'buffer' is 'count' long
525 log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);
527 session->inbufoffset += ret;
533 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
534 virtual void OnWhois(userrec* source, userrec* dest)
536 // Bugfix, only send this numeric for *our* SSL users
537 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
539 source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
543 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
545 // check if the linking module wants to know about OUR metadata
548 // check if this user has an swhois field to send
549 if(user->GetExt(extname, dummy))
551 // call this function in the linking module, let it format the data how it
552 // sees fit, and send it on its way. We dont need or want to know how.
553 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
558 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
560 // check if its our metadata key, and its associated with a user
561 if ((target_type == TYPE_USER) && (extname == "ssl"))
563 userrec* dest = (userrec*)target;
564 // if they dont already have an ssl flag, accept the remote server's
565 if (!dest->GetExt(extname, dummy))
567 dest->Extend(extname, "ON");
572 bool Handshake(issl_session* session)
574 int ret = SSL_accept(session->sess);
578 int err = SSL_get_error(session->sess, ret);
580 if(err == SSL_ERROR_WANT_READ)
582 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
583 session->rstat = ISSL_READ;
584 session->status = ISSL_HANDSHAKING;
586 else if(err == SSL_ERROR_WANT_WRITE)
588 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
589 session->wstat = ISSL_WRITE;
590 session->status = ISSL_HANDSHAKING;
591 MakePollWrite(session);
595 log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
596 CloseSession(session);
603 // Handshake complete.
604 log(DEBUG, "m_ssl_openssl.so: Handshake completed");
606 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
607 userrec* u = Srv->FindDescriptor(session->fd);
610 if (!u->GetExt("ssl", dummy))
611 u->Extend("ssl", "ON");
614 session->status = ISSL_OPEN;
616 MakePollWrite(session);
622 virtual void OnGlobalConnect(userrec* user)
624 // This occurs AFTER OnUserConnect so we can be sure the
625 // protocol module has propogated the NICK message.
626 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
628 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
629 std::deque<std::string>* metadata = new std::deque<std::string>;
630 metadata->push_back(user->nick);
631 metadata->push_back("ssl"); // The metadata id
632 metadata->push_back("ON"); // The value to send
633 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
634 event->Send(); // Trigger the event. We don't care what module picks it up.
640 void MakePollWrite(issl_session* session)
642 OnRawSocketWrite(session->fd, NULL, 0);
645 void CloseSession(issl_session* session)
649 SSL_shutdown(session->sess);
650 SSL_free(session->sess);
655 delete[] session->inbuf;
658 session->outbuf.clear();
659 session->inbuf = NULL;
660 session->sess = NULL;
661 session->status = ISSL_NONE;
665 class ModuleSSLOpenSSLFactory : public ModuleFactory
668 ModuleSSLOpenSSLFactory()
672 ~ModuleSSLOpenSSLFactory()
676 virtual Module * CreateModule(Server* Me)
678 return new ModuleSSLOpenSSL(Me);
683 extern "C" void * init_module( void )
685 return new ModuleSSLOpenSSLFactory;