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);
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];
75 // std::string crlfile;
80 ModuleSSLOpenSSL(Server* Me)
84 SrvConf = Srv->GetConfig();
86 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
87 inbufsize = SrvConf->NetBufferSize;
89 /* Global SSL library initialization*/
91 SSL_load_error_strings();
93 /* Build our SSL context*/
94 ctx = SSL_CTX_new( SSLv23_server_method() );
96 // Needs the flag as it ignores a plain /rehash
100 virtual void OnRehash(const std::string ¶m)
105 Conf = new ConfigReader;
107 for(unsigned int i = 0; i < listenports.size(); i++)
109 SrvConf->DelIOHook(listenports[i]);
114 for(int i = 0; i < Conf->Enumerate("bind"); i++)
116 // For each <bind> tag
117 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
119 // Get the port we're meant to be listening on with SSL
120 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
121 if(SrvConf->AddIOHook(port, this))
123 // We keep a record of which ports we're listening on with SSL
124 listenports.push_back(port);
126 log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
130 log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
135 std::string confdir(CONFIG_FILE);
136 // +1 so we the path ends with a /
137 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
139 cafile = Conf->ReadValue("openssl", "cafile", 0);
140 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
141 certfile = Conf->ReadValue("openssl", "certfile", 0);
142 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
143 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
145 // Set all the default values needed.
150 // crlfile = "crl.pem";
153 certfile = "cert.pem";
159 dhfile = "dhparams.pem";
161 // Prepend relative paths with the path to the config directory.
163 cafile = confdir + cafile;
165 //if(crlfile[0] != '/')
166 // crlfile = confdir + crlfile;
168 if(certfile[0] != '/')
169 certfile = confdir + certfile;
171 if(keyfile[0] != '/')
172 keyfile = confdir + keyfile;
175 dhfile = confdir + dhfile;
177 /* Load our keys and certificates*/
178 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
180 log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
183 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
185 log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
188 /* Load the CAs we trust*/
189 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
191 log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
194 FILE* dhpfile = fopen(dhfile.c_str(), "r");
199 log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
203 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");
216 virtual ~ModuleSSLOpenSSL()
221 virtual void OnCleanup(int target_type, void* item)
223 if(target_type == TYPE_USER)
225 userrec* user = (userrec*)item;
227 if(user->GetExt("ssl") && IS_LOCAL(user) && isin(user->port, listenports))
229 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
230 // Potentially there could be multiple SSL modules loaded at once on different ports.
231 log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
232 culllist.AddItem(user, "SSL module unloading");
237 virtual void OnUnloadModule(Module* mod, const std::string &name)
241 // We're being unloaded, kill all the users added to the cull list in OnCleanup
242 int numusers = culllist.Apply();
243 log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
245 for(unsigned int i = 0; i < listenports.size(); i++)
246 SrvConf->DelIOHook(listenports[i]);
250 virtual Version GetVersion()
252 return Version(1, 0, 0, 0, VF_VENDOR);
255 void Implements(char* List)
257 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
258 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
261 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
263 issl_session* session = &sessions[fd];
266 session->inbuf = new char[inbufsize];
267 session->inbufoffset = 0;
268 session->sess = SSL_new(ctx);
269 session->status = ISSL_NONE;
271 if(session->sess == NULL)
273 log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
277 if(SSL_set_fd(session->sess, fd) == 0)
279 log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
286 virtual void OnRawSocketClose(int fd)
288 log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
289 CloseSession(&sessions[fd]);
292 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
294 issl_session* session = &sessions[fd];
298 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
300 CloseSession(session);
304 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
306 if(session->status == ISSL_HANDSHAKING)
308 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
310 // The handshake isn't finished and it wants to read, try to finish it.
311 if(Handshake(session))
313 // Handshake successfully resumed.
314 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
318 // Couldn't resume handshake.
319 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
325 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
330 // If we resumed the handshake then session->status will be ISSL_OPEN
332 if(session->status == ISSL_OPEN)
334 if(session->wstat == ISSL_READ)
336 if(DoWrite(session) == 0)
340 if(session->rstat == ISSL_READ)
342 int ret = DoRead(session);
346 if(count <= session->inbufoffset)
348 memcpy(buffer, session->inbuf, count);
349 // Move the stuff left in inbuf to the beginning of it
350 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
351 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
352 session->inbufoffset -= count;
353 // Insp uses readresult as the count of how much data there is in buffer, so:
358 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
359 memcpy(buffer, session->inbuf, session->inbufoffset);
361 readresult = session->inbufoffset;
362 // Zero the offset, as there's nothing there..
363 session->inbufoffset = 0;
366 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: Passing %d bytes up to insp:", count);
367 Srv->Log(DEBUG, std::string(buffer, readresult));
381 virtual int OnRawSocketWrite(int fd, char* buffer, int count)
383 issl_session* session = &sessions[fd];
387 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
388 CloseSession(session);
392 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
393 session->outbuf.append(buffer, count);
395 if(session->status == ISSL_HANDSHAKING)
397 // The handshake isn't finished, try to finish it.
398 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
400 if(Handshake(session))
402 // Handshake successfully resumed.
403 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
407 // Couldn't resume handshake.
408 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
413 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
417 if(session->status == ISSL_OPEN)
419 if(session->rstat == ISSL_WRITE)
424 if(session->wstat == ISSL_WRITE)
426 return DoWrite(session);
433 int DoWrite(issl_session* session)
435 log(DEBUG, "m_ssl_openssl.so: DoWrite: Trying to write %d bytes:", session->outbuf.size());
436 Srv->Log(DEBUG, session->outbuf);
438 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
442 log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
443 CloseSession(session);
448 int err = SSL_get_error(session->sess, ret);
450 if(err == SSL_ERROR_WANT_WRITE)
452 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
453 session->wstat = ISSL_WRITE;
456 else if(err == SSL_ERROR_WANT_READ)
458 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
459 session->wstat = ISSL_READ;
464 log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
465 CloseSession(session);
471 log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
472 session->outbuf = session->outbuf.substr(ret);
477 int DoRead(issl_session* session)
479 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
480 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
481 log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
483 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
487 // Client closed connection.
488 log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
489 CloseSession(session);
494 int err = SSL_get_error(session->sess, ret);
496 if(err == SSL_ERROR_WANT_READ)
498 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
499 session->rstat = ISSL_READ;
502 else if(err == SSL_ERROR_WANT_WRITE)
504 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
505 session->rstat = ISSL_WRITE;
510 log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
511 CloseSession(session);
517 // Read successfully 'ret' bytes into inbuf + inbufoffset
518 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
519 // 'buffer' is 'count' long
521 log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);
523 session->inbufoffset += ret;
529 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
530 virtual void OnWhois(userrec* source, userrec* dest)
532 // Bugfix, only send this numeric for *our* SSL users
533 if(dest->GetExt("ssl") || (IS_LOCAL(dest) && isin(dest->port, listenports)))
535 WriteServ(source->fd, "320 %s %s :is using a secure connection", source->nick, dest->nick);
539 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
541 // check if the linking module wants to know about OUR metadata
544 // check if this user has an swhois field to send
545 if(user->GetExt(extname))
547 // call this function in the linking module, let it format the data how it
548 // sees fit, and send it on its way. We dont need or want to know how.
549 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
554 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
556 // check if its our metadata key, and its associated with a user
557 if ((target_type == TYPE_USER) && (extname == "ssl"))
559 userrec* dest = (userrec*)target;
560 // if they dont already have an ssl flag, accept the remote server's
561 if (!dest->GetExt(extname))
563 dest->Extend(extname, "ON");
568 bool Handshake(issl_session* session)
570 int ret = SSL_accept(session->sess);
574 int err = SSL_get_error(session->sess, ret);
576 if(err == SSL_ERROR_WANT_READ)
578 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
579 session->rstat = ISSL_READ;
580 session->status = ISSL_HANDSHAKING;
582 else if(err == SSL_ERROR_WANT_WRITE)
584 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
585 session->wstat = ISSL_WRITE;
586 session->status = ISSL_HANDSHAKING;
587 MakePollWrite(session);
591 log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
592 CloseSession(session);
599 // Handshake complete.
600 log(DEBUG, "m_ssl_openssl.so: Handshake completed");
602 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
603 userrec* u = Srv->FindDescriptor(session->fd);
606 if (!u->GetExt("ssl"))
607 u->Extend("ssl", "ON");
610 session->status = ISSL_OPEN;
612 MakePollWrite(session);
618 virtual void OnGlobalConnect(userrec* user)
620 // This occurs AFTER OnUserConnect so we can be sure the
621 // protocol module has propogated the NICK message.
622 if ((user->GetExt("ssl")) && (IS_LOCAL(user)))
624 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
625 std::deque<std::string>* metadata = new std::deque<std::string>;
626 metadata->push_back(user->nick);
627 metadata->push_back("ssl"); // The metadata id
628 metadata->push_back("ON"); // The value to send
629 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
630 event->Send(); // Trigger the event. We don't care what module picks it up.
636 void MakePollWrite(issl_session* session)
638 OnRawSocketWrite(session->fd, NULL, 0);
641 void CloseSession(issl_session* session)
645 SSL_shutdown(session->sess);
646 SSL_free(session->sess);
651 delete[] session->inbuf;
654 session->outbuf.clear();
655 session->inbuf = NULL;
656 session->sess = NULL;
657 session->status = ISSL_NONE;
661 class ModuleSSLOpenSSLFactory : public ModuleFactory
664 ModuleSSLOpenSSLFactory()
668 ~ModuleSSLOpenSSLFactory()
672 virtual Module * CreateModule(Server* Me)
674 return new ModuleSSLOpenSSL(Me);
679 extern "C" void * init_module( void )
681 return new ModuleSSLOpenSSLFactory;