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, const 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 if(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 log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
134 std::string confdir(CONFIG_FILE);
135 // +1 so we the path ends with a /
136 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
138 cafile = Conf->ReadValue("openssl", "cafile", 0);
139 // crlfile = Conf->ReadValue("openssl", "crlfile", 0);
140 certfile = Conf->ReadValue("openssl", "certfile", 0);
141 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
142 dhfile = Conf->ReadValue("openssl", "dhfile", 0);
144 // Set all the default values needed.
149 // crlfile = "crl.pem";
152 certfile = "cert.pem";
158 dhfile = "dhparams.pem";
160 // Prepend relative paths with the path to the config directory.
162 cafile = confdir + cafile;
164 //if(crlfile[0] != '/')
165 // crlfile = confdir + crlfile;
167 if(certfile[0] != '/')
168 certfile = confdir + certfile;
170 if(keyfile[0] != '/')
171 keyfile = confdir + keyfile;
174 dhfile = confdir + dhfile;
176 /* Load our keys and certificates*/
177 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
179 log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
182 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
184 log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
187 /* Load the CAs we trust*/
188 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
190 log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
193 FILE* dhpfile = fopen(dhfile.c_str(), "r");
198 log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
202 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
207 if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
209 log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
215 virtual ~ModuleSSLOpenSSL()
220 virtual void OnCleanup(int target_type, void* item)
222 if(target_type == TYPE_USER)
224 userrec* user = (userrec*)item;
226 if(user->GetExt("ssl") && IS_LOCAL(user) && isin(user->port, listenports))
228 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
229 // Potentially there could be multiple SSL modules loaded at once on different ports.
230 log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
231 culllist.AddItem(user, "SSL module unloading");
236 virtual void OnUnloadModule(Module* mod, std::string name)
240 // We're being unloaded, kill all the users added to the cull list in OnCleanup
241 int numusers = culllist.Apply();
242 log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
244 for(unsigned int i = 0; i < listenports.size(); i++)
245 SrvConf->DelIOHook(listenports[i]);
249 virtual Version GetVersion()
251 return Version(1, 0, 0, 0, VF_VENDOR);
254 void Implements(char* List)
256 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
257 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = 1;
260 virtual void OnRawSocketAccept(int fd, std::string ip, int localport)
262 issl_session* session = &sessions[fd];
265 session->inbuf = new char[inbufsize];
266 session->inbufoffset = 0;
267 session->sess = SSL_new(ctx);
268 session->status = ISSL_NONE;
270 if(session->sess == NULL)
272 log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
276 if(SSL_set_fd(session->sess, fd) == 0)
278 log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
285 virtual void OnRawSocketClose(int fd)
287 log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
288 CloseSession(&sessions[fd]);
291 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
293 issl_session* session = &sessions[fd];
297 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
299 CloseSession(session);
303 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
305 if(session->status == ISSL_HANDSHAKING)
307 if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
309 // The handshake isn't finished and it wants to read, try to finish it.
310 if(Handshake(session))
312 // Handshake successfully resumed.
313 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
317 // Couldn't resume handshake.
318 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
324 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
329 // If we resumed the handshake then session->status will be ISSL_OPEN
331 if(session->status == ISSL_OPEN)
333 if(session->wstat == ISSL_READ)
335 if(DoWrite(session) == 0)
339 if(session->rstat == ISSL_READ)
341 int ret = DoRead(session);
345 if(count <= session->inbufoffset)
347 memcpy(buffer, session->inbuf, count);
348 // Move the stuff left in inbuf to the beginning of it
349 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
350 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
351 session->inbufoffset -= count;
352 // Insp uses readresult as the count of how much data there is in buffer, so:
357 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
358 memcpy(buffer, session->inbuf, session->inbufoffset);
360 readresult = session->inbufoffset;
361 // Zero the offset, as there's nothing there..
362 session->inbufoffset = 0;
365 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: Passing %d bytes up to insp:");
366 Srv->Log(DEBUG, std::string(buffer, readresult));
380 virtual int OnRawSocketWrite(int fd, char* buffer, int count)
382 issl_session* session = &sessions[fd];
386 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
387 CloseSession(session);
391 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
392 session->outbuf.append(buffer, count);
394 if(session->status == ISSL_HANDSHAKING)
396 // The handshake isn't finished, try to finish it.
397 if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
399 if(Handshake(session))
401 // Handshake successfully resumed.
402 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
406 // Couldn't resume handshake.
407 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake");
412 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
416 if(session->status == ISSL_OPEN)
418 if(session->rstat == ISSL_WRITE)
423 if(session->wstat == ISSL_WRITE)
425 return DoWrite(session);
432 int DoWrite(issl_session* session)
434 log(DEBUG, "m_ssl_openssl.so: DoWrite: Trying to write %d bytes:", session->outbuf.size());
435 Srv->Log(DEBUG, session->outbuf);
437 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
441 log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
442 CloseSession(session);
447 int err = SSL_get_error(session->sess, ret);
449 if(err == SSL_ERROR_WANT_WRITE)
451 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
452 session->wstat = ISSL_WRITE;
455 else if(err == SSL_ERROR_WANT_READ)
457 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
458 session->wstat = ISSL_READ;
463 log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
464 CloseSession(session);
470 log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
471 session->outbuf = session->outbuf.substr(ret);
476 int DoRead(issl_session* session)
478 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
479 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
480 log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
482 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
486 // Client closed connection.
487 log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
488 CloseSession(session);
493 int err = SSL_get_error(session->sess, ret);
495 if(err == SSL_ERROR_WANT_READ)
497 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
498 session->rstat = ISSL_READ;
501 else if(err == SSL_ERROR_WANT_WRITE)
503 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
504 session->rstat = ISSL_WRITE;
509 log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
510 CloseSession(session);
516 // Read successfully 'ret' bytes into inbuf + inbufoffset
517 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
518 // 'buffer' is 'count' long
520 log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);
522 session->inbufoffset += ret;
528 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
529 virtual void OnWhois(userrec* source, userrec* dest)
531 if(dest->GetExt("ssl"))
533 WriteServ(source->fd, "320 %s %s :is a Secure Connection", source->nick, dest->nick);
537 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, std::string extname)
539 // check if the linking module wants to know about OUR metadata
542 // check if this user has an swhois field to send
543 if(user->GetExt(extname))
545 // call this function in the linking module, let it format the data how it
546 // sees fit, and send it on its way. We dont need or want to know how.
547 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
552 virtual void OnDecodeMetaData(int target_type, void* target, std::string extname, std::string extdata)
554 // check if its our metadata key, and its associated with a user
555 if ((target_type == TYPE_USER) && (extname == "ssl"))
557 userrec* dest = (userrec*)target;
558 // if they dont already have an ssl flag, accept the remote server's
559 if (!dest->GetExt(extname))
561 dest->Extend(extname, "ON");
566 bool Handshake(issl_session* session)
568 int ret = SSL_accept(session->sess);
572 int err = SSL_get_error(session->sess, ret);
574 if(err == SSL_ERROR_WANT_READ)
576 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
577 session->rstat = ISSL_READ;
578 session->status = ISSL_HANDSHAKING;
580 else if(err == SSL_ERROR_WANT_WRITE)
582 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
583 session->wstat = ISSL_WRITE;
584 session->status = ISSL_HANDSHAKING;
585 MakePollWrite(session);
589 log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
590 CloseSession(session);
597 // Handshake complete.
598 log(DEBUG, "m_ssl_openssl.so: Handshake completed");
600 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
601 Srv->FindDescriptor(session->fd)->Extend("ssl", "ON");
603 session->status = ISSL_OPEN;
605 MakePollWrite(session);
611 void MakePollWrite(issl_session* session)
613 OnRawSocketWrite(session->fd, NULL, 0);
616 void CloseSession(issl_session* session)
620 SSL_shutdown(session->sess);
621 SSL_free(session->sess);
626 delete[] session->inbuf;
629 session->outbuf.clear();
630 session->inbuf = NULL;
631 session->sess = NULL;
632 session->status = ISSL_NONE;
636 class ModuleSSLOpenSSLFactory : public ModuleFactory
639 ModuleSSLOpenSSLFactory()
643 ~ModuleSSLOpenSSLFactory()
647 virtual Module * CreateModule(Server* Me)
649 return new ModuleSSLOpenSSL(Me);
654 extern "C" void * init_module( void )
656 return new ModuleSSLOpenSSLFactory;