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)
30 class issl_session : public classbase
33 gnutls_session_t sess;
41 class ModuleSSLGnuTLS : public Module
44 ServerConfig* SrvConf;
51 std::vector<int> listenports;
54 issl_session sessions[MAX_DESCRIPTORS];
56 gnutls_certificate_credentials x509_cred;
57 gnutls_dh_params dh_params;
67 ModuleSSLGnuTLS(Server* Me)
71 SrvConf = Srv->GetConfig();
73 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
74 inbufsize = SrvConf->NetBufferSize;
76 gnutls_global_init(); // This must be called once in the program
78 if(gnutls_certificate_allocate_credentials(&x509_cred) != 0)
79 log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials");
81 // Guessing return meaning
82 if(gnutls_dh_params_init(&dh_params) < 0)
83 log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters");
85 // Needs the flag as it ignores a plain /rehash
88 // Void return, guess we assume success
89 gnutls_certificate_set_dh_params(x509_cred, dh_params);
92 virtual void OnRehash(const std::string ¶m)
97 Conf = new ConfigReader;
99 for(unsigned int i = 0; i < listenports.size(); i++)
101 SrvConf->DelIOHook(listenports[i]);
106 for(int i = 0; i < Conf->Enumerate("bind"); i++)
108 // For each <bind> tag
109 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
111 // Get the port we're meant to be listening on with SSL
112 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
113 if(SrvConf->AddIOHook(port, this))
115 // We keep a record of which ports we're listening on with SSL
116 listenports.push_back(port);
118 log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", port);
122 log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
127 std::string confdir(CONFIG_FILE);
128 // +1 so we the path ends with a /
129 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
131 cafile = Conf->ReadValue("gnutls", "cafile", 0);
132 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
133 certfile = Conf->ReadValue("gnutls", "certfile", 0);
134 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
135 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
137 // Set all the default values needed.
145 certfile = "cert.pem";
150 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
153 // Prepend relative paths with the path to the config directory.
155 cafile = confdir + cafile;
157 if(crlfile[0] != '/')
158 crlfile = confdir + crlfile;
160 if(certfile[0] != '/')
161 certfile = confdir + certfile;
163 if(keyfile[0] != '/')
164 keyfile = confdir + keyfile;
166 if(gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
167 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file: %s", cafile.c_str());
169 if(gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
170 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file: %s", crlfile.c_str());
172 // Guessing on the return value of this, manual doesn't say :|
173 if(gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
174 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 certificate and key files: %s and %s", certfile.c_str(), keyfile.c_str());
176 // This may be on a large (once a day or week) timer eventually.
182 void GenerateDHParams()
184 // Generate Diffie Hellman parameters - for use with DHE
185 // kx algorithms. These should be discarded and regenerated
186 // once a day, once a week or once a month. Depending on the
187 // security requirements.
189 if(gnutls_dh_params_generate2(dh_params, dh_bits) < 0)
190 log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits)", dh_bits);
193 virtual ~ModuleSSLGnuTLS()
195 gnutls_dh_params_deinit(dh_params);
196 gnutls_certificate_free_credentials(x509_cred);
197 gnutls_global_deinit();
200 virtual void OnCleanup(int target_type, void* item)
202 if(target_type == TYPE_USER)
204 userrec* user = (userrec*)item;
206 if(user->GetExt("ssl", dummy) && isin(user->GetPort(), listenports))
208 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
209 // Potentially there could be multiple SSL modules loaded at once on different ports.
210 log(DEBUG, "m_ssl_gnutls.so: Adding user %s to cull list", user->nick);
211 culllist.AddItem(user, "SSL module unloading");
216 virtual void OnUnloadModule(Module* mod, const std::string &name)
220 // We're being unloaded, kill all the users added to the cull list in OnCleanup
221 int numusers = culllist.Apply();
222 log(DEBUG, "m_ssl_gnutls.so: Killed %d users for unload of GnuTLS SSL module", numusers);
224 for(unsigned int i = 0; i < listenports.size(); i++)
225 SrvConf->DelIOHook(listenports[i]);
229 virtual Version GetVersion()
231 return Version(1, 0, 0, 0, VF_VENDOR);
234 void Implements(char* List)
236 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
237 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
240 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
242 issl_session* session = &sessions[fd];
245 session->inbuf = new char[inbufsize];
246 session->inbufoffset = 0;
248 gnutls_init(&session->sess, GNUTLS_SERVER);
250 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
251 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
252 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
253 gnutls_dh_set_prime_bits(session->sess, dh_bits);
255 /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes
256 * This needs testing, but it's easy enough to rollback if need be
257 * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
258 * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket.
260 * With testing this seems to...not work :/
263 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
268 virtual void OnRawSocketClose(int fd)
270 log(DEBUG, "OnRawSocketClose: %d", fd);
271 CloseSession(&sessions[fd]);
274 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
276 issl_session* session = &sessions[fd];
280 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: No session to read from");
282 CloseSession(session);
286 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
288 if(session->status == ISSL_HANDSHAKING_READ)
290 // The handshake isn't finished, try to finish it.
292 if(Handshake(session))
294 // Handshake successfully resumed.
295 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: successfully resumed handshake");
299 // Couldn't resume handshake.
300 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: failed to resume handshake");
304 else if(session->status == ISSL_HANDSHAKING_WRITE)
306 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
310 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
312 if(session->status == ISSL_HANDSHAKEN)
314 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
315 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
316 log(DEBUG, "m_ssl_gnutls.so: gnutls_record_recv(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
318 int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
322 // Client closed connection.
323 log(DEBUG, "m_ssl_gnutls.so: Client closed the connection");
325 CloseSession(session);
330 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
332 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Not all SSL data read: %s", gnutls_strerror(ret));
337 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Error reading SSL data: %s", gnutls_strerror(ret));
339 CloseSession(session);
344 // Read successfully 'ret' bytes into inbuf + inbufoffset
345 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
346 // 'buffer' is 'count' long
348 unsigned int length = ret + session->inbufoffset;
350 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Read %d bytes, now have %d waiting to be passed up", ret, length);
354 memcpy(buffer, session->inbuf, count);
355 // Move the stuff left in inbuf to the beginning of it
356 memcpy(session->inbuf, session->inbuf + count, (length - count));
357 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
358 session->inbufoffset = length - count;
359 // Insp uses readresult as the count of how much data there is in buffer, so:
364 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
365 memcpy(buffer, session->inbuf, length);
366 // Zero the offset, as there's nothing there..
367 session->inbufoffset = 0;
372 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Passing %d bytes up to insp:", length);
373 Srv->Log(DEBUG, std::string(buffer, readresult));
376 else if(session->status == ISSL_CLOSING)
378 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
385 virtual int OnRawSocketWrite(int fd, char* buffer, int count)
387 issl_session* session = &sessions[fd];
388 const char* sendbuffer = buffer;
392 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
393 CloseSession(session);
397 if(session->status == ISSL_HANDSHAKING_WRITE)
399 // The handshake isn't finished, try to finish it.
401 if(Handshake(session))
403 // Handshake successfully resumed.
404 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
408 // Couldn't resume handshake.
409 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake");
412 else if(session->status == ISSL_HANDSHAKING_READ)
414 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
417 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
418 session->outbuf.append(sendbuffer, count);
419 sendbuffer = session->outbuf.c_str();
420 count = session->outbuf.size();
422 if(session->status == ISSL_HANDSHAKEN)
424 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Trying to write %d bytes:", count);
425 Srv->Log(DEBUG, session->outbuf);
427 int ret = gnutls_record_send(session->sess, sendbuffer, count);
431 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Client closed the connection");
432 CloseSession(session);
436 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
438 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Not all SSL data written: %s", gnutls_strerror(ret));
442 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Error writing SSL data: %s", gnutls_strerror(ret));
443 CloseSession(session);
448 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Successfully wrote %d bytes", ret);
449 session->outbuf = session->outbuf.substr(ret);
452 else if(session->status == ISSL_CLOSING)
454 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: session closing...");
460 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
461 virtual void OnWhois(userrec* source, userrec* dest)
463 // Bugfix, only send this numeric for *our* SSL users
464 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports)))
466 WriteServ(source->fd, "320 %s %s :is using a secure connection", source->nick, dest->nick);
470 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
472 // check if the linking module wants to know about OUR metadata
475 // check if this user has an swhois field to send
476 if(user->GetExt(extname, dummy))
478 // call this function in the linking module, let it format the data how it
479 // sees fit, and send it on its way. We dont need or want to know how.
480 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
485 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
487 // check if its our metadata key, and its associated with a user
488 if ((target_type == TYPE_USER) && (extname == "ssl"))
490 userrec* dest = (userrec*)target;
491 // if they dont already have an ssl flag, accept the remote server's
492 if (!dest->GetExt(extname, dummy))
494 dest->Extend(extname, "ON");
499 bool Handshake(issl_session* session)
501 int ret = gnutls_handshake(session->sess);
505 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
507 // Handshake needs resuming later, read() or write() would have blocked.
509 if(gnutls_record_get_direction(session->sess) == 0)
511 // gnutls_handshake() wants to read() again.
512 session->status = ISSL_HANDSHAKING_READ;
513 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (reading) later, error string: %s", gnutls_strerror(ret));
517 // gnutls_handshake() wants to write() again.
518 session->status = ISSL_HANDSHAKING_WRITE;
519 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (writing) later, error string: %s", gnutls_strerror(ret));
520 MakePollWrite(session);
526 CloseSession(session);
527 log(DEBUG, "m_ssl_gnutls.so: Handshake failed, error string: %s", gnutls_strerror(ret));
528 session->status = ISSL_CLOSING;
535 // Handshake complete.
536 log(DEBUG, "m_ssl_gnutls.so: Handshake completed");
538 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
539 userrec* extendme = Srv->FindDescriptor(session->fd);
542 if (!extendme->GetExt("ssl", dummy))
543 extendme->Extend("ssl", "ON");
546 // Change the seesion state
547 session->status = ISSL_HANDSHAKEN;
549 // Finish writing, if any left
550 MakePollWrite(session);
556 virtual void OnGlobalConnect(userrec* user)
558 // This occurs AFTER OnUserConnect so we can be sure the
559 // protocol module has propogated the NICK message.
560 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
562 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
563 std::deque<std::string>* metadata = new std::deque<std::string>;
564 metadata->push_back(user->nick);
565 metadata->push_back("ssl"); // The metadata id
566 metadata->push_back("ON"); // The value to send
567 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
568 event->Send(); // Trigger the event. We don't care what module picks it up.
574 void MakePollWrite(issl_session* session)
576 OnRawSocketWrite(session->fd, NULL, 0);
579 void CloseSession(issl_session* session)
583 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
584 gnutls_deinit(session->sess);
589 delete[] session->inbuf;
592 session->outbuf.clear();
593 session->inbuf = NULL;
594 session->sess = NULL;
595 session->status = ISSL_NONE;
599 class ModuleSSLGnuTLSFactory : public ModuleFactory
602 ModuleSSLGnuTLSFactory()
606 ~ModuleSSLGnuTLSFactory()
610 virtual Module * CreateModule(Server* Me)
612 return new ModuleSSLGnuTLS(Me);
617 extern "C" void * init_module( void )
619 return new ModuleSSLGnuTLSFactory;