4 #include <openssl/ssl.h>
5 #include <openssl/err.h>
7 #include "inspircd_config.h"
11 #include "helperfuncs.h"
15 /* $ModDesc: Provides SSL support for clients */
16 /* $CompileFlags: -I/usr/include -I/usr/local/include */
17 /* $LinkerFlags: -L/usr/local/lib -Wl,--rpath -Wl,/usr/local/lib -L/usr/lib -Wl,--rpath -Wl,/usr/lib -lssl -lcrypto */
19 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
20 enum issl_io_status { ISSL_WRITE, ISSL_READ };
22 bool isin(int port, std::vector<int> portlist)
24 for(unsigned int i = 0; i < portlist.size(); i++)
25 if(portlist[i] == port)
33 return ERR_error_string(ERR_get_error(), NULL);
44 unsigned int inbufoffset;
45 char* inbuf; // Buffer OpenSSL reads into.
46 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
56 class ModuleSSLOpenSSL : public Module
59 ServerConfig* SrvConf;
64 std::vector<int> listenports;
67 issl_session sessions[MAX_DESCRIPTORS];
74 // std::string crlfile;
79 ModuleSSLOpenSSL(Server* Me)
83 SrvConf = Srv->GetConfig();
85 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
86 inbufsize = SrvConf->NetBufferSize;
88 /* Global SSL library initialization*/
90 SSL_load_error_strings();
92 /* Build our SSL context*/
93 ctx = SSL_CTX_new( SSLv23_server_method() );
95 // Needs the flag as it ignores a plain /rehash
99 virtual void OnRehash(std::string param)
104 Conf = new ConfigReader;
106 for(unsigned int i = 0; i < listenports.size(); i++)
108 SrvConf->DelIOHook(listenports[i]);
113 for(int i = 0; i < Conf->Enumerate("bind"); i++)
115 // For each <bind> tag
116 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
118 // Get the port we're meant to be listening on with SSL
119 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
120 SrvConf->AddIOHook(port, this);
122 // We keep a record of which ports we're listening on with SSL
123 listenports.push_back(port);
125 log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
129 std::string confdir(CONFIG_FILE);
130 // +1 so we the path ends with a /
131 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
133 cafile = Conf->ReadValue("openssl", "cafile", 0);
134 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
135 certfile = Conf->ReadValue("openssl", "certfile", 0);
136 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
137 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
139 // Set all the default values needed.
144 // crlfile = "crl.pem";
147 certfile = "cert.pem";
153 dhfile = "dhparams.pem";
155 // Prepend relative paths with the path to the config directory.
157 cafile = confdir + cafile;
159 //if(crlfile[0] != '/')
160 // crlfile = confdir + crlfile;
162 if(certfile[0] != '/')
163 certfile = confdir + certfile;
165 if(keyfile[0] != '/')
166 keyfile = confdir + keyfile;
169 dhfile = confdir + dhfile;
171 /* Load our keys and certificates*/
172 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
174 log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
177 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
179 log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
182 /* Load the CAs we trust*/
183 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
185 log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
188 FILE* dhpfile = fopen(dhfile.c_str(), "r");
193 log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
197 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
202 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
204 log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
210 virtual ~ModuleSSLOpenSSL()
215 virtual void OnCleanup(int target_type, void* item)
217 if(target_type == TYPE_USER)
219 userrec* user = (userrec*)item;
221 if(user->GetExt("ssl") && IS_LOCAL(user) && isin(user->port, listenports))
223 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
224 // Potentially there could be multiple SSL modules loaded at once on different ports.
225 log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
226 culllist.AddItem(user, "SSL module unloading");
231 virtual void OnUnloadModule(Module* mod, std::string name)
235 // We're being unloaded, kill all the users added to the cull list in OnCleanup
236 int numusers = culllist.Apply();
237 log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
239 for(unsigned int i = 0; i < listenports.size(); i++)
240 SrvConf->DelIOHook(listenports[i]);
244 virtual Version GetVersion()
246 return Version(1, 0, 0, 0, VF_VENDOR);
249 void Implements(char* List)
251 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
252 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = 1;
255 virtual void OnRawSocketAccept(int fd, std::string ip, int localport)
257 issl_session* session = &sessions[fd];
260 session->inbuf = new char[inbufsize];
261 session->inbufoffset = 0;
262 session->sess = SSL_new(ctx);
263 session->status = ISSL_NONE;
265 if(session->sess == NULL)
267 log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
271 if(SSL_set_fd(session->sess, fd) == 0)
273 log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
280 virtual void OnRawSocketClose(int fd)
282 log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
283 CloseSession(&sessions[fd]);
286 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
288 issl_session* session = &sessions[fd];
292 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
294 CloseSession(session);
298 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
300 if(session->status == ISSL_HANDSHAKING)
302 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
304 // The handshake isn't finished and it wants to read, try to finish it.
305 if(Handshake(session))
307 // Handshake successfully resumed.
308 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
312 // Couldn't resume handshake.
313 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
319 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
324 // If we resumed the handshake then session->status will be ISSL_OPEN
326 if(session->status == ISSL_OPEN)
328 if(session->wstat == ISSL_READ)
330 if(DoWrite(session) == 0)
334 if(session->rstat == ISSL_READ)
336 int ret = DoRead(session);
340 if(count <= session->inbufoffset)
342 memcpy(buffer, session->inbuf, count);
343 // Move the stuff left in inbuf to the beginning of it
344 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
345 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
346 session->inbufoffset -= count;
347 // Insp uses readresult as the count of how much data there is in buffer, so:
352 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
353 memcpy(buffer, session->inbuf, session->inbufoffset);
355 readresult = session->inbufoffset;
356 // Zero the offset, as there's nothing there..
357 session->inbufoffset = 0;
360 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: Passing %d bytes up to insp:");
361 Srv->Log(DEBUG, std::string(buffer, readresult));
375 virtual int OnRawSocketWrite(int fd, char* buffer, int count)
377 issl_session* session = &sessions[fd];
381 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
382 CloseSession(session);
386 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
387 session->outbuf.append(buffer, count);
389 if(session->status == ISSL_HANDSHAKING)
391 // The handshake isn't finished, try to finish it.
392 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
394 if(Handshake(session))
396 // Handshake successfully resumed.
397 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
401 // Couldn't resume handshake.
402 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
407 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
411 if(session->status == ISSL_OPEN)
413 if(session->rstat == ISSL_WRITE)
418 if(session->wstat == ISSL_WRITE)
420 return DoWrite(session);
427 int DoWrite(issl_session* session)
429 log(DEBUG, "m_ssl_openssl.so: DoWrite: Trying to write %d bytes:", session->outbuf.size());
430 Srv->Log(DEBUG, session->outbuf);
432 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
436 log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
437 CloseSession(session);
442 int err = SSL_get_error(session->sess, ret);
444 if(err == SSL_ERROR_WANT_WRITE)
446 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
447 session->wstat = ISSL_WRITE;
450 else if(err == SSL_ERROR_WANT_READ)
452 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
453 session->wstat = ISSL_READ;
458 log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
459 CloseSession(session);
465 log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
466 session->outbuf = session->outbuf.substr(ret);
471 int DoRead(issl_session* session)
473 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
474 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
475 log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
477 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
481 // Client closed connection.
482 log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
483 CloseSession(session);
488 int err = SSL_get_error(session->sess, ret);
490 if(err == SSL_ERROR_WANT_READ)
492 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
493 session->rstat = ISSL_READ;
496 else if(err == SSL_ERROR_WANT_WRITE)
498 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
499 session->rstat = ISSL_WRITE;
504 log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
505 CloseSession(session);
511 // Read successfully 'ret' bytes into inbuf + inbufoffset
512 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
513 // 'buffer' is 'count' long
515 log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);
517 session->inbufoffset += ret;
523 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
524 virtual void OnWhois(userrec* source, userrec* dest)
526 if(dest->GetExt("ssl"))
528 WriteServ(source->fd, "320 %s %s :is a Secure Connection", source->nick, dest->nick);
532 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, std::string extname)
534 // check if the linking module wants to know about OUR metadata
537 // check if this user has an swhois field to send
538 if(user->GetExt(extname))
540 // call this function in the linking module, let it format the data how it
541 // sees fit, and send it on its way. We dont need or want to know how.
542 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
547 virtual void OnDecodeMetaData(int target_type, void* target, std::string extname, std::string extdata)
549 // check if its our metadata key, and its associated with a user
550 if ((target_type == TYPE_USER) && (extname == "ssl"))
552 userrec* dest = (userrec*)target;
553 // if they dont already have an ssl flag, accept the remote server's
554 if (!dest->GetExt(extname))
556 dest->Extend(extname, "ON");
561 bool Handshake(issl_session* session)
563 int ret = SSL_accept(session->sess);
567 int err = SSL_get_error(session->sess, ret);
569 if(err == SSL_ERROR_WANT_READ)
571 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
572 session->rstat = ISSL_READ;
573 session->status = ISSL_HANDSHAKING;
575 else if(err == SSL_ERROR_WANT_WRITE)
577 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
578 session->wstat = ISSL_WRITE;
579 session->status = ISSL_HANDSHAKING;
580 MakePollWrite(session);
584 log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
585 CloseSession(session);
592 // Handshake complete.
593 log(DEBUG, "m_ssl_openssl.so: Handshake completed");
595 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
596 Srv->FindDescriptor(session->fd)->Extend("ssl", "ON");
598 session->status = ISSL_OPEN;
600 MakePollWrite(session);
606 void MakePollWrite(issl_session* session)
608 OnRawSocketWrite(session->fd, NULL, 0);
611 void CloseSession(issl_session* session)
615 SSL_shutdown(session->sess);
616 SSL_free(session->sess);
621 delete[] session->inbuf;
624 session->outbuf.clear();
625 session->inbuf = NULL;
626 session->sess = NULL;
627 session->status = ISSL_NONE;
631 class ModuleSSLOpenSSLFactory : public ModuleFactory
634 ModuleSSLOpenSSLFactory()
638 ~ModuleSSLOpenSSLFactory()
642 virtual Module * CreateModule(Server* Me)
644 return new ModuleSSLOpenSSL(Me);
649 extern "C" void * init_module( void )
651 return new ModuleSSLOpenSSLFactory;