4 #include <openssl/ssl.h>
5 #include <openssl/err.h>
7 #include "inspircd_config.h"
8 #include "configreader.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 */
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(InspIRCd* Me)
89 culllist = new CullList(ServerInstance);
91 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
92 inbufsize = ServerInstance->Config->NetBufferSize;
94 /* Global SSL library initialization*/
96 SSL_load_error_strings();
98 /* Build our SSL context*/
99 ctx = SSL_CTX_new( SSLv23_server_method() );
101 // Needs the flag as it ignores a plain /rehash
105 virtual void OnRehash(const std::string ¶m)
110 Conf = new ConfigReader(ServerInstance);
112 for(unsigned int i = 0; i < listenports.size(); i++)
114 ServerInstance->Config->DelIOHook(listenports[i]);
119 for(int i = 0; i < Conf->Enumerate("bind"); i++)
121 // For each <bind> tag
122 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
124 // Get the port we're meant to be listening on with SSL
125 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
126 if (ServerInstance->Config->AddIOHook(port, this))
128 // We keep a record of which ports we're listening on with SSL
129 listenports.push_back(port);
131 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
135 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
140 std::string confdir(CONFIG_FILE);
141 // +1 so we the path ends with a /
142 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
144 cafile = Conf->ReadValue("openssl", "cafile", 0);
145 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
146 certfile = Conf->ReadValue("openssl", "certfile", 0);
147 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
148 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
150 // Set all the default values needed.
155 // crlfile = "crl.pem";
158 certfile = "cert.pem";
164 dhfile = "dhparams.pem";
166 // Prepend relative paths with the path to the config directory.
168 cafile = confdir + cafile;
170 //if(crlfile[0] != '/')
171 // crlfile = confdir + crlfile;
173 if(certfile[0] != '/')
174 certfile = confdir + certfile;
176 if(keyfile[0] != '/')
177 keyfile = confdir + keyfile;
180 dhfile = confdir + dhfile;
182 /* Load our keys and certificates*/
183 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
185 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
188 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
190 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
193 /* Load the CAs we trust*/
194 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
196 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
199 FILE* dhpfile = fopen(dhfile.c_str(), "r");
204 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
205 throw ModuleException();
209 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
211 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
213 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
222 virtual ~ModuleSSLOpenSSL()
228 virtual void OnCleanup(int target_type, void* item)
230 if(target_type == TYPE_USER)
232 userrec* user = (userrec*)item;
234 if(user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
236 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
237 // Potentially there could be multiple SSL modules loaded at once on different ports.
238 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
239 culllist->AddItem(user, "SSL module unloading");
244 virtual void OnUnloadModule(Module* mod, const std::string &name)
248 // We're being unloaded, kill all the users added to the cull list in OnCleanup
249 int numusers = culllist->Apply();
250 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
252 for(unsigned int i = 0; i < listenports.size(); i++)
253 ServerInstance->Config->DelIOHook(listenports[i]);
257 virtual Version GetVersion()
259 return Version(1, 0, 0, 0, VF_VENDOR);
262 void Implements(char* List)
264 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
265 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
268 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
270 issl_session* session = &sessions[fd];
273 session->inbuf = new char[inbufsize];
274 session->inbufoffset = 0;
275 session->sess = SSL_new(ctx);
276 session->status = ISSL_NONE;
278 if(session->sess == NULL)
280 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
284 if(SSL_set_fd(session->sess, fd) == 0)
286 ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
293 virtual void OnRawSocketClose(int fd)
295 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
296 CloseSession(&sessions[fd]);
299 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
301 issl_session* session = &sessions[fd];
305 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
307 CloseSession(session);
311 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
313 if(session->status == ISSL_HANDSHAKING)
315 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
317 // The handshake isn't finished and it wants to read, try to finish it.
318 if(Handshake(session))
320 // Handshake successfully resumed.
321 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
325 // Couldn't resume handshake.
326 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
332 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
337 // If we resumed the handshake then session->status will be ISSL_OPEN
339 if(session->status == ISSL_OPEN)
341 if(session->wstat == ISSL_READ)
343 if(DoWrite(session) == 0)
347 if(session->rstat == ISSL_READ)
349 int ret = DoRead(session);
353 if(count <= session->inbufoffset)
355 memcpy(buffer, session->inbuf, count);
356 // Move the stuff left in inbuf to the beginning of it
357 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
358 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
359 session->inbufoffset -= count;
360 // Insp uses readresult as the count of how much data there is in buffer, so:
365 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
366 memcpy(buffer, session->inbuf, session->inbufoffset);
368 readresult = session->inbufoffset;
369 // Zero the offset, as there's nothing there..
370 session->inbufoffset = 0;
385 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
387 issl_session* session = &sessions[fd];
391 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
392 CloseSession(session);
396 ServerInstance->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 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
411 // Couldn't resume handshake.
412 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
417 ServerInstance->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 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
443 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
444 CloseSession(session);
449 int err = SSL_get_error(session->sess, ret);
451 if(err == SSL_ERROR_WANT_WRITE)
453 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
454 session->wstat = ISSL_WRITE;
457 else if(err == SSL_ERROR_WANT_READ)
459 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
460 session->wstat = ISSL_READ;
465 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
466 CloseSession(session);
472 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
473 session->outbuf = session->outbuf.substr(ret);
478 int DoRead(issl_session* session)
480 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
481 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
482 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
484 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
488 // Client closed connection.
489 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
490 CloseSession(session);
495 int err = SSL_get_error(session->sess, ret);
497 if(err == SSL_ERROR_WANT_READ)
499 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
500 session->rstat = ISSL_READ;
503 else if(err == SSL_ERROR_WANT_WRITE)
505 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
506 session->rstat = ISSL_WRITE;
511 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
512 CloseSession(session);
518 // Read successfully 'ret' bytes into inbuf + inbufoffset
519 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
520 // 'buffer' is 'count' long
522 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);
524 session->inbufoffset += ret;
530 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
531 virtual void OnWhois(userrec* source, userrec* dest)
533 // Bugfix, only send this numeric for *our* SSL users
534 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
536 source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
540 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
542 // check if the linking module wants to know about OUR metadata
545 // check if this user has an swhois field to send
546 if(user->GetExt(extname, dummy))
548 // call this function in the linking module, let it format the data how it
549 // sees fit, and send it on its way. We dont need or want to know how.
550 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
555 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
557 // check if its our metadata key, and its associated with a user
558 if ((target_type == TYPE_USER) && (extname == "ssl"))
560 userrec* dest = (userrec*)target;
561 // if they dont already have an ssl flag, accept the remote server's
562 if (!dest->GetExt(extname, dummy))
564 dest->Extend(extname, "ON");
569 bool Handshake(issl_session* session)
571 int ret = SSL_accept(session->sess);
575 int err = SSL_get_error(session->sess, ret);
577 if(err == SSL_ERROR_WANT_READ)
579 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
580 session->rstat = ISSL_READ;
581 session->status = ISSL_HANDSHAKING;
583 else if(err == SSL_ERROR_WANT_WRITE)
585 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
586 session->wstat = ISSL_WRITE;
587 session->status = ISSL_HANDSHAKING;
588 MakePollWrite(session);
592 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
593 CloseSession(session);
600 // Handshake complete.
601 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
603 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
604 userrec* u = ServerInstance->FindDescriptor(session->fd);
607 if (!u->GetExt("ssl", dummy))
608 u->Extend("ssl", "ON");
611 session->status = ISSL_OPEN;
613 MakePollWrite(session);
619 virtual void OnPostConnect(userrec* user)
621 // This occurs AFTER OnUserConnect so we can be sure the
622 // protocol module has propogated the NICK message.
623 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
625 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
626 std::deque<std::string>* metadata = new std::deque<std::string>;
627 metadata->push_back(user->nick);
628 metadata->push_back("ssl"); // The metadata id
629 metadata->push_back("ON"); // The value to send
630 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
631 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
637 void MakePollWrite(issl_session* session)
639 OnRawSocketWrite(session->fd, NULL, 0);
642 void CloseSession(issl_session* session)
646 SSL_shutdown(session->sess);
647 SSL_free(session->sess);
652 delete[] session->inbuf;
655 session->outbuf.clear();
656 session->inbuf = NULL;
657 session->sess = NULL;
658 session->status = ISSL_NONE;
662 class ModuleSSLOpenSSLFactory : public ModuleFactory
665 ModuleSSLOpenSSLFactory()
669 ~ModuleSSLOpenSSLFactory()
673 virtual Module * CreateModule(InspIRCd* Me)
675 return new ModuleSSLOpenSSL(Me);
680 extern "C" void * init_module( void )
682 return new ModuleSSLOpenSSLFactory;