4 #include <openssl/ssl.h>
5 #include <openssl/err.h>
7 #include "inspircd_config.h"
8 #include "configreader.h"
12 #include "helperfuncs.h"
16 /* $ModDesc: Provides SSL support for clients */
17 /* $CompileFlags: -I/usr/include -I/usr/local/include */
18 /* $LinkerFlags: -L/usr/local/lib -Wl,--rpath -Wl,/usr/local/lib -L/usr/lib -Wl,--rpath -Wl,/usr/lib -lssl */
20 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
21 enum issl_io_status { ISSL_WRITE, ISSL_READ };
23 bool isin(int port, const std::vector<int> &portlist)
25 for(unsigned int i = 0; i < portlist.size(); i++)
26 if(portlist[i] == port)
34 return ERR_error_string(ERR_get_error(), NULL);
37 class issl_session : public classbase
45 unsigned int inbufoffset;
46 char* inbuf; // Buffer OpenSSL reads into.
47 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
57 class ModuleSSLOpenSSL : public Module
60 ServerConfig* SrvConf;
65 std::vector<int> listenports;
68 issl_session sessions[MAX_DESCRIPTORS];
77 // std::string crlfile;
82 ModuleSSLOpenSSL(Server* Me)
86 SrvConf = Srv->GetConfig();
88 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
89 inbufsize = SrvConf->NetBufferSize;
91 /* Global SSL library initialization*/
93 SSL_load_error_strings();
95 /* Build our SSL context*/
96 ctx = SSL_CTX_new( SSLv23_server_method() );
98 // Needs the flag as it ignores a plain /rehash
102 virtual void OnRehash(const std::string ¶m)
107 Conf = new ConfigReader;
109 for(unsigned int i = 0; i < listenports.size(); i++)
111 SrvConf->DelIOHook(listenports[i]);
116 for(int i = 0; i < Conf->Enumerate("bind"); i++)
118 // For each <bind> tag
119 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
121 // Get the port we're meant to be listening on with SSL
122 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
123 if(SrvConf->AddIOHook(port, this))
125 // We keep a record of which ports we're listening on with SSL
126 listenports.push_back(port);
128 log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
132 log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
137 std::string confdir(CONFIG_FILE);
138 // +1 so we the path ends with a /
139 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
141 cafile = Conf->ReadValue("openssl", "cafile", 0);
142 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
143 certfile = Conf->ReadValue("openssl", "certfile", 0);
144 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
145 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
147 // Set all the default values needed.
152 // crlfile = "crl.pem";
155 certfile = "cert.pem";
161 dhfile = "dhparams.pem";
163 // Prepend relative paths with the path to the config directory.
165 cafile = confdir + cafile;
167 //if(crlfile[0] != '/')
168 // crlfile = confdir + crlfile;
170 if(certfile[0] != '/')
171 certfile = confdir + certfile;
173 if(keyfile[0] != '/')
174 keyfile = confdir + keyfile;
177 dhfile = confdir + dhfile;
179 /* Load our keys and certificates*/
180 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
182 log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
185 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
187 log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
190 /* Load the CAs we trust*/
191 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
193 log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
196 FILE* dhpfile = fopen(dhfile.c_str(), "r");
201 log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
202 throw ModuleException();
206 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
208 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
210 log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
219 virtual ~ModuleSSLOpenSSL()
224 virtual void OnCleanup(int target_type, void* item)
226 if(target_type == TYPE_USER)
228 userrec* user = (userrec*)item;
230 if(user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
232 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
233 // Potentially there could be multiple SSL modules loaded at once on different ports.
234 log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
235 culllist.AddItem(user, "SSL module unloading");
240 virtual void OnUnloadModule(Module* mod, const std::string &name)
244 // We're being unloaded, kill all the users added to the cull list in OnCleanup
245 int numusers = culllist.Apply();
246 log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
248 for(unsigned int i = 0; i < listenports.size(); i++)
249 SrvConf->DelIOHook(listenports[i]);
253 virtual Version GetVersion()
255 return Version(1, 0, 0, 0, VF_VENDOR);
258 void Implements(char* List)
260 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
261 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
264 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
266 issl_session* session = &sessions[fd];
269 session->inbuf = new char[inbufsize];
270 session->inbufoffset = 0;
271 session->sess = SSL_new(ctx);
272 session->status = ISSL_NONE;
274 if(session->sess == NULL)
276 log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
280 if(SSL_set_fd(session->sess, fd) == 0)
282 log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
289 virtual void OnRawSocketClose(int fd)
291 log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
292 CloseSession(&sessions[fd]);
295 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
297 issl_session* session = &sessions[fd];
301 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
303 CloseSession(session);
307 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
309 if(session->status == ISSL_HANDSHAKING)
311 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
313 // The handshake isn't finished and it wants to read, try to finish it.
314 if(Handshake(session))
316 // Handshake successfully resumed.
317 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
321 // Couldn't resume handshake.
322 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
328 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
333 // If we resumed the handshake then session->status will be ISSL_OPEN
335 if(session->status == ISSL_OPEN)
337 if(session->wstat == ISSL_READ)
339 if(DoWrite(session) == 0)
343 if(session->rstat == ISSL_READ)
345 int ret = DoRead(session);
349 if(count <= session->inbufoffset)
351 memcpy(buffer, session->inbuf, count);
352 // Move the stuff left in inbuf to the beginning of it
353 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
354 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
355 session->inbufoffset -= count;
356 // Insp uses readresult as the count of how much data there is in buffer, so:
361 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
362 memcpy(buffer, session->inbuf, session->inbufoffset);
364 readresult = session->inbufoffset;
365 // Zero the offset, as there's nothing there..
366 session->inbufoffset = 0;
369 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: Passing %d bytes up to insp:", count);
370 Srv->Log(DEBUG, std::string(buffer, readresult));
384 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
386 issl_session* session = &sessions[fd];
390 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
391 CloseSession(session);
395 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
396 session->outbuf.append(buffer, count);
398 if(session->status == ISSL_HANDSHAKING)
400 // The handshake isn't finished, try to finish it.
401 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
403 if(Handshake(session))
405 // Handshake successfully resumed.
406 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
410 // Couldn't resume handshake.
411 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
416 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
420 if(session->status == ISSL_OPEN)
422 if(session->rstat == ISSL_WRITE)
427 if(session->wstat == ISSL_WRITE)
429 return DoWrite(session);
436 int DoWrite(issl_session* session)
438 log(DEBUG, "m_ssl_openssl.so: DoWrite: Trying to write %d bytes:", session->outbuf.size());
439 Srv->Log(DEBUG, session->outbuf);
441 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
445 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 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 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 log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
468 CloseSession(session);
474 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 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 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 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 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 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 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 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 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 log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
595 CloseSession(session);
602 // Handshake complete.
603 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 = Srv->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 OnGlobalConnect(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(); // 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;
664 class ModuleSSLOpenSSLFactory : public ModuleFactory
667 ModuleSSLOpenSSLFactory()
671 ~ModuleSSLOpenSSLFactory()
675 virtual Module * CreateModule(Server* Me)
677 return new ModuleSSLOpenSSL(Me);
682 extern "C" void * init_module( void )
684 return new ModuleSSLOpenSSLFactory;