4 #include <gnutls/gnutls.h>
6 #include "inspircd_config.h"
7 #include "configreader.h"
11 #include "helperfuncs.h"
16 /* $ModDesc: Provides SSL support for clients */
17 /* $CompileFlags: `libgnutls-config --cflags` */
18 /* $LinkerFlags: `libgnutls-config --libs` `perl ../gnutls_rpath.pl` */
22 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
24 bool isin(int port, const std::vector<int> &portlist)
26 for(unsigned int i = 0; i < portlist.size(); i++)
27 if(portlist[i] == port)
33 class issl_session : public classbase
36 gnutls_session_t sess;
44 class ModuleSSLGnuTLS : public Module
53 std::vector<int> listenports;
56 issl_session sessions[MAX_DESCRIPTORS];
58 gnutls_certificate_credentials x509_cred;
59 gnutls_dh_params dh_params;
69 ModuleSSLGnuTLS(InspIRCd* Me)
74 culllist = new CullList(ServerInstance);
76 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
77 inbufsize = ServerInstance->Config->NetBufferSize;
79 gnutls_global_init(); // This must be called once in the program
81 if(gnutls_certificate_allocate_credentials(&x509_cred) != 0)
82 log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials");
84 // Guessing return meaning
85 if(gnutls_dh_params_init(&dh_params) < 0)
86 log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters");
88 // Needs the flag as it ignores a plain /rehash
91 // Void return, guess we assume success
92 gnutls_certificate_set_dh_params(x509_cred, dh_params);
95 virtual void OnRehash(const std::string ¶m)
100 Conf = new ConfigReader(ServerInstance);
102 for(unsigned int i = 0; i < listenports.size(); i++)
104 ServerInstance->Config->DelIOHook(listenports[i]);
109 for(int i = 0; i < Conf->Enumerate("bind"); i++)
111 // For each <bind> tag
112 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
114 // Get the port we're meant to be listening on with SSL
115 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
116 if (ServerInstance->Config->AddIOHook(port, this))
118 // We keep a record of which ports we're listening on with SSL
119 listenports.push_back(port);
121 log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", port);
125 log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
130 std::string confdir(CONFIG_FILE);
131 // +1 so we the path ends with a /
132 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
134 cafile = Conf->ReadValue("gnutls", "cafile", 0);
135 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
136 certfile = Conf->ReadValue("gnutls", "certfile", 0);
137 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
138 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
140 // Set all the default values needed.
148 certfile = "cert.pem";
153 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
156 // Prepend relative paths with the path to the config directory.
158 cafile = confdir + cafile;
160 if(crlfile[0] != '/')
161 crlfile = confdir + crlfile;
163 if(certfile[0] != '/')
164 certfile = confdir + certfile;
166 if(keyfile[0] != '/')
167 keyfile = confdir + keyfile;
169 if(gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
170 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file: %s", cafile.c_str());
172 if(gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
173 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file: %s", crlfile.c_str());
175 // Guessing on the return value of this, manual doesn't say :|
176 if(gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
177 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 certificate and key files: %s and %s", certfile.c_str(), keyfile.c_str());
179 // This may be on a large (once a day or week) timer eventually.
185 void GenerateDHParams()
187 // Generate Diffie Hellman parameters - for use with DHE
188 // kx algorithms. These should be discarded and regenerated
189 // once a day, once a week or once a month. Depending on the
190 // security requirements.
192 if(gnutls_dh_params_generate2(dh_params, dh_bits) < 0)
193 log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits)", dh_bits);
196 virtual ~ModuleSSLGnuTLS()
198 gnutls_dh_params_deinit(dh_params);
199 gnutls_certificate_free_credentials(x509_cred);
200 gnutls_global_deinit();
204 virtual void OnCleanup(int target_type, void* item)
206 if(target_type == TYPE_USER)
208 userrec* user = (userrec*)item;
210 if(user->GetExt("ssl", dummy) && isin(user->GetPort(), listenports))
212 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
213 // Potentially there could be multiple SSL modules loaded at once on different ports.
214 log(DEBUG, "m_ssl_gnutls.so: Adding user %s to cull list", user->nick);
215 culllist->AddItem(user, "SSL module unloading");
220 virtual void OnUnloadModule(Module* mod, const std::string &name)
224 // We're being unloaded, kill all the users added to the cull list in OnCleanup
225 int numusers = culllist->Apply();
226 log(DEBUG, "m_ssl_gnutls.so: Killed %d users for unload of GnuTLS SSL module", numusers);
228 for(unsigned int i = 0; i < listenports.size(); i++)
229 ServerInstance->Config->DelIOHook(listenports[i]);
233 virtual Version GetVersion()
235 return Version(1, 0, 0, 0, VF_VENDOR);
238 void Implements(char* List)
240 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
241 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
244 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
246 issl_session* session = &sessions[fd];
249 session->inbuf = new char[inbufsize];
250 session->inbufoffset = 0;
252 gnutls_init(&session->sess, GNUTLS_SERVER);
254 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
255 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
256 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
257 gnutls_dh_set_prime_bits(session->sess, dh_bits);
259 /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes
260 * This needs testing, but it's easy enough to rollback if need be
261 * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
262 * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket.
264 * With testing this seems to...not work :/
267 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
272 virtual void OnRawSocketClose(int fd)
274 log(DEBUG, "OnRawSocketClose: %d", fd);
275 CloseSession(&sessions[fd]);
278 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
280 issl_session* session = &sessions[fd];
284 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: No session to read from");
286 CloseSession(session);
290 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
292 if(session->status == ISSL_HANDSHAKING_READ)
294 // The handshake isn't finished, try to finish it.
296 if(Handshake(session))
298 // Handshake successfully resumed.
299 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: successfully resumed handshake");
303 // Couldn't resume handshake.
304 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: failed to resume handshake");
308 else if(session->status == ISSL_HANDSHAKING_WRITE)
310 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
314 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
316 if(session->status == ISSL_HANDSHAKEN)
318 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
319 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
320 log(DEBUG, "m_ssl_gnutls.so: gnutls_record_recv(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
322 int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
326 // Client closed connection.
327 log(DEBUG, "m_ssl_gnutls.so: Client closed the connection");
329 CloseSession(session);
334 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
336 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Not all SSL data read: %s", gnutls_strerror(ret));
341 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Error reading SSL data: %s", gnutls_strerror(ret));
343 CloseSession(session);
348 // Read successfully 'ret' bytes into inbuf + inbufoffset
349 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
350 // 'buffer' is 'count' long
352 unsigned int length = ret + session->inbufoffset;
354 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Read %d bytes, now have %d waiting to be passed up", ret, length);
358 memcpy(buffer, session->inbuf, count);
359 // Move the stuff left in inbuf to the beginning of it
360 memcpy(session->inbuf, session->inbuf + count, (length - count));
361 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
362 session->inbufoffset = length - count;
363 // Insp uses readresult as the count of how much data there is in buffer, so:
368 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
369 memcpy(buffer, session->inbuf, length);
370 // Zero the offset, as there's nothing there..
371 session->inbufoffset = 0;
377 else if(session->status == ISSL_CLOSING)
379 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
386 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
388 issl_session* session = &sessions[fd];
389 const char* sendbuffer = buffer;
393 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
394 CloseSession(session);
398 if(session->status == ISSL_HANDSHAKING_WRITE)
400 // The handshake isn't finished, try to finish it.
402 if(Handshake(session))
404 // Handshake successfully resumed.
405 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
409 // Couldn't resume handshake.
410 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake");
413 else if(session->status == ISSL_HANDSHAKING_READ)
415 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
418 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
419 session->outbuf.append(sendbuffer, count);
420 sendbuffer = session->outbuf.c_str();
421 count = session->outbuf.size();
423 if(session->status == ISSL_HANDSHAKEN)
425 int ret = gnutls_record_send(session->sess, sendbuffer, count);
429 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Client closed the connection");
430 CloseSession(session);
434 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
436 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Not all SSL data written: %s", gnutls_strerror(ret));
440 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Error writing SSL data: %s", gnutls_strerror(ret));
441 CloseSession(session);
446 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Successfully wrote %d bytes", ret);
447 session->outbuf = session->outbuf.substr(ret);
450 else if(session->status == ISSL_CLOSING)
452 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: session closing...");
458 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
459 virtual void OnWhois(userrec* source, userrec* dest)
461 // Bugfix, only send this numeric for *our* SSL users
462 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
464 source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
468 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
470 // check if the linking module wants to know about OUR metadata
473 // check if this user has an swhois field to send
474 if(user->GetExt(extname, dummy))
476 // call this function in the linking module, let it format the data how it
477 // sees fit, and send it on its way. We dont need or want to know how.
478 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
483 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
485 // check if its our metadata key, and its associated with a user
486 if ((target_type == TYPE_USER) && (extname == "ssl"))
488 userrec* dest = (userrec*)target;
489 // if they dont already have an ssl flag, accept the remote server's
490 if (!dest->GetExt(extname, dummy))
492 dest->Extend(extname, "ON");
497 bool Handshake(issl_session* session)
499 int ret = gnutls_handshake(session->sess);
503 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
505 // Handshake needs resuming later, read() or write() would have blocked.
507 if(gnutls_record_get_direction(session->sess) == 0)
509 // gnutls_handshake() wants to read() again.
510 session->status = ISSL_HANDSHAKING_READ;
511 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (reading) later, error string: %s", gnutls_strerror(ret));
515 // gnutls_handshake() wants to write() again.
516 session->status = ISSL_HANDSHAKING_WRITE;
517 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (writing) later, error string: %s", gnutls_strerror(ret));
518 MakePollWrite(session);
524 CloseSession(session);
525 log(DEBUG, "m_ssl_gnutls.so: Handshake failed, error string: %s", gnutls_strerror(ret));
526 session->status = ISSL_CLOSING;
533 // Handshake complete.
534 log(DEBUG, "m_ssl_gnutls.so: Handshake completed");
536 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
537 userrec* extendme = ServerInstance->FindDescriptor(session->fd);
540 if (!extendme->GetExt("ssl", dummy))
541 extendme->Extend("ssl", "ON");
544 // Change the seesion state
545 session->status = ISSL_HANDSHAKEN;
547 // Finish writing, if any left
548 MakePollWrite(session);
554 virtual void OnGlobalConnect(userrec* user)
556 // This occurs AFTER OnUserConnect so we can be sure the
557 // protocol module has propogated the NICK message.
558 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
560 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
561 std::deque<std::string>* metadata = new std::deque<std::string>;
562 metadata->push_back(user->nick);
563 metadata->push_back("ssl"); // The metadata id
564 metadata->push_back("ON"); // The value to send
565 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
566 event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up.
572 void MakePollWrite(issl_session* session)
574 OnRawSocketWrite(session->fd, NULL, 0);
577 void CloseSession(issl_session* session)
581 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
582 gnutls_deinit(session->sess);
587 delete[] session->inbuf;
590 session->outbuf.clear();
591 session->inbuf = NULL;
592 session->sess = NULL;
593 session->status = ISSL_NONE;
597 class ModuleSSLGnuTLSFactory : public ModuleFactory
600 ModuleSSLGnuTLSFactory()
604 ~ModuleSSLGnuTLSFactory()
608 virtual Module * CreateModule(InspIRCd* Me)
610 return new ModuleSSLGnuTLS(Me);
615 extern "C" void * init_module( void )
617 return new ModuleSSLGnuTLSFactory;