4 #include <gnutls/gnutls.h>
6 #include "inspircd_config.h"
7 #include "configreader.h"
11 #include "helperfuncs.h"
15 /* $ModDesc: Provides SSL support for clients */
16 /* $CompileFlags: `libgnutls-config --cflags` */
17 /* $LinkerFlags: `libgnutls-config --libs` `perl ../gnutls_rpath.pl` */
19 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
21 bool isin(int port, const std::vector<int> &portlist)
23 for(unsigned int i = 0; i < portlist.size(); i++)
24 if(portlist[i] == port)
33 gnutls_session_t sess;
41 class ModuleSSLGnuTLS : public Module
44 ServerConfig* SrvConf;
49 std::vector<int> listenports;
52 issl_session sessions[MAX_DESCRIPTORS];
54 gnutls_certificate_credentials x509_cred;
55 gnutls_dh_params dh_params;
65 ModuleSSLGnuTLS(Server* Me)
69 SrvConf = Srv->GetConfig();
71 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
72 inbufsize = SrvConf->NetBufferSize;
74 gnutls_global_init(); // This must be called once in the program
76 if(gnutls_certificate_allocate_credentials(&x509_cred) != 0)
77 log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials");
79 // Guessing return meaning
80 if(gnutls_dh_params_init(&dh_params) < 0)
81 log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters");
83 // Needs the flag as it ignores a plain /rehash
86 // Void return, guess we assume success
87 gnutls_certificate_set_dh_params(x509_cred, dh_params);
90 virtual void OnRehash(const std::string ¶m)
95 Conf = new ConfigReader;
97 for(unsigned int i = 0; i < listenports.size(); i++)
99 SrvConf->DelIOHook(listenports[i]);
104 for(int i = 0; i < Conf->Enumerate("bind"); i++)
106 // For each <bind> tag
107 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
109 // Get the port we're meant to be listening on with SSL
110 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
111 if(SrvConf->AddIOHook(port, this))
113 // We keep a record of which ports we're listening on with SSL
114 listenports.push_back(port);
116 log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", port);
120 log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
125 std::string confdir(CONFIG_FILE);
126 // +1 so we the path ends with a /
127 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
129 cafile = Conf->ReadValue("gnutls", "cafile", 0);
130 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
131 certfile = Conf->ReadValue("gnutls", "certfile", 0);
132 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
133 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
135 // Set all the default values needed.
143 certfile = "cert.pem";
148 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
151 // Prepend relative paths with the path to the config directory.
153 cafile = confdir + cafile;
155 if(crlfile[0] != '/')
156 crlfile = confdir + crlfile;
158 if(certfile[0] != '/')
159 certfile = confdir + certfile;
161 if(keyfile[0] != '/')
162 keyfile = confdir + keyfile;
164 if(gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
165 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file: %s", cafile.c_str());
167 if(gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
168 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file: %s", crlfile.c_str());
170 // Guessing on the return value of this, manual doesn't say :|
171 if(gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
172 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 certificate and key files: %s and %s", certfile.c_str(), keyfile.c_str());
174 // This may be on a large (once a day or week) timer eventually.
180 void GenerateDHParams()
182 // Generate Diffie Hellman parameters - for use with DHE
183 // kx algorithms. These should be discarded and regenerated
184 // once a day, once a week or once a month. Depending on the
185 // security requirements.
187 if(gnutls_dh_params_generate2(dh_params, dh_bits) < 0)
188 log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits)", dh_bits);
191 virtual ~ModuleSSLGnuTLS()
193 gnutls_dh_params_deinit(dh_params);
194 gnutls_certificate_free_credentials(x509_cred);
195 gnutls_global_deinit();
198 virtual void OnCleanup(int target_type, void* item)
200 if(target_type == TYPE_USER)
202 userrec* user = (userrec*)item;
204 if(user->GetExt("ssl") && IS_LOCAL(user) && isin(user->port, listenports))
206 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
207 // Potentially there could be multiple SSL modules loaded at once on different ports.
208 log(DEBUG, "m_ssl_gnutls.so: Adding user %s to cull list", user->nick);
209 culllist.AddItem(user, "SSL module unloading");
214 virtual void OnUnloadModule(Module* mod, const std::string &name)
218 // We're being unloaded, kill all the users added to the cull list in OnCleanup
219 int numusers = culllist.Apply();
220 log(DEBUG, "m_ssl_gnutls.so: Killed %d users for unload of GnuTLS SSL module", numusers);
222 for(unsigned int i = 0; i < listenports.size(); i++)
223 SrvConf->DelIOHook(listenports[i]);
227 virtual Version GetVersion()
229 return Version(1, 0, 0, 0, VF_VENDOR);
232 void Implements(char* List)
234 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
235 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
238 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
240 issl_session* session = &sessions[fd];
243 session->inbuf = new char[inbufsize];
244 session->inbufoffset = 0;
246 gnutls_init(&session->sess, GNUTLS_SERVER);
248 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
249 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
250 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
251 gnutls_dh_set_prime_bits(session->sess, dh_bits);
253 /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes
254 * This needs testing, but it's easy enough to rollback if need be
255 * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
256 * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket.
258 * With testing this seems to...not work :/
261 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
266 virtual void OnRawSocketClose(int fd)
268 log(DEBUG, "OnRawSocketClose: %d", fd);
269 CloseSession(&sessions[fd]);
272 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
274 issl_session* session = &sessions[fd];
278 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: No session to read from");
280 CloseSession(session);
284 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
286 if(session->status == ISSL_HANDSHAKING_READ)
288 // The handshake isn't finished, try to finish it.
290 if(Handshake(session))
292 // Handshake successfully resumed.
293 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: successfully resumed handshake");
297 // Couldn't resume handshake.
298 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: failed to resume handshake");
302 else if(session->status == ISSL_HANDSHAKING_WRITE)
304 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
308 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
310 if(session->status == ISSL_HANDSHAKEN)
312 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
313 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
314 log(DEBUG, "m_ssl_gnutls.so: gnutls_record_recv(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
316 int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
320 // Client closed connection.
321 log(DEBUG, "m_ssl_gnutls.so: Client closed the connection");
323 CloseSession(session);
328 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
330 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Not all SSL data read: %s", gnutls_strerror(ret));
335 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Error reading SSL data: %s", gnutls_strerror(ret));
337 CloseSession(session);
342 // Read successfully 'ret' bytes into inbuf + inbufoffset
343 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
344 // 'buffer' is 'count' long
346 unsigned int length = ret + session->inbufoffset;
348 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Read %d bytes, now have %d waiting to be passed up", ret, length);
352 memcpy(buffer, session->inbuf, count);
353 // Move the stuff left in inbuf to the beginning of it
354 memcpy(session->inbuf, session->inbuf + count, (length - count));
355 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
356 session->inbufoffset = length - count;
357 // Insp uses readresult as the count of how much data there is in buffer, so:
362 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
363 memcpy(buffer, session->inbuf, length);
364 // Zero the offset, as there's nothing there..
365 session->inbufoffset = 0;
370 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Passing %d bytes up to insp:", length);
371 Srv->Log(DEBUG, std::string(buffer, readresult));
374 else if(session->status == ISSL_CLOSING)
376 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
383 virtual int OnRawSocketWrite(int fd, char* buffer, int count)
385 issl_session* session = &sessions[fd];
386 const char* sendbuffer = buffer;
390 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
391 CloseSession(session);
395 if(session->status == ISSL_HANDSHAKING_WRITE)
397 // The handshake isn't finished, try to finish it.
399 if(Handshake(session))
401 // Handshake successfully resumed.
402 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
406 // Couldn't resume handshake.
407 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake");
410 else if(session->status == ISSL_HANDSHAKING_READ)
412 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
415 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
416 session->outbuf.append(sendbuffer, count);
417 sendbuffer = session->outbuf.c_str();
418 count = session->outbuf.size();
420 if(session->status == ISSL_HANDSHAKEN)
422 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Trying to write %d bytes:", count);
423 Srv->Log(DEBUG, session->outbuf);
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") && isin(dest->port, listenports))
464 WriteServ(source->fd, "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))
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))
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 = Srv->FindDescriptor(session->fd);
540 if (!extendme->GetExt("ssl"))
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")) && (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(); // 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(Server* Me)
610 return new ModuleSSLGnuTLS(Me);
615 extern "C" void * init_module( void )
617 return new ModuleSSLGnuTLSFactory;