4 #include <gnutls/gnutls.h>
6 #include "inspircd_config.h"
10 #include "helperfuncs.h"
14 /* $ModDesc: Provides SSL support for clients */
15 /* $CompileFlags: `libgnutls-config --cflags` */
16 /* $LinkerFlags: `libgnutls-config --libs` */
18 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
20 bool isin(int port, const std::vector<int> &portlist)
22 for(unsigned int i = 0; i < portlist.size(); i++)
23 if(portlist[i] == port)
32 gnutls_session_t sess;
40 class ModuleSSLGnuTLS : public Module
43 ServerConfig* SrvConf;
48 std::vector<int> listenports;
51 issl_session sessions[MAX_DESCRIPTORS];
53 gnutls_certificate_credentials x509_cred;
54 gnutls_dh_params dh_params;
64 ModuleSSLGnuTLS(Server* Me)
68 SrvConf = Srv->GetConfig();
70 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
71 inbufsize = SrvConf->NetBufferSize;
73 gnutls_global_init(); // This must be called once in the program
75 if(gnutls_certificate_allocate_credentials(&x509_cred) != 0)
76 log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials");
78 // Guessing return meaning
79 if(gnutls_dh_params_init(&dh_params) < 0)
80 log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters");
82 // Needs the flag as it ignores a plain /rehash
85 // Void return, guess we assume success
86 gnutls_certificate_set_dh_params(x509_cred, dh_params);
89 virtual void OnRehash(std::string param)
94 Conf = new ConfigReader;
96 for(unsigned int i = 0; i < listenports.size(); i++)
98 SrvConf->DelIOHook(listenports[i]);
103 for(int i = 0; i < Conf->Enumerate("bind"); i++)
105 // For each <bind> tag
106 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
108 // Get the port we're meant to be listening on with SSL
109 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
110 if(SrvConf->AddIOHook(port, this))
112 // We keep a record of which ports we're listening on with SSL
113 listenports.push_back(port);
115 log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", port);
119 log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
124 std::string confdir(CONFIG_FILE);
125 // +1 so we the path ends with a /
126 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
128 cafile = Conf->ReadValue("gnutls", "cafile", 0);
129 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
130 certfile = Conf->ReadValue("gnutls", "certfile", 0);
131 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
132 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
134 // Set all the default values needed.
142 certfile = "cert.pem";
147 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
150 // Prepend relative paths with the path to the config directory.
152 cafile = confdir + cafile;
154 if(crlfile[0] != '/')
155 crlfile = confdir + crlfile;
157 if(certfile[0] != '/')
158 certfile = confdir + certfile;
160 if(keyfile[0] != '/')
161 keyfile = confdir + keyfile;
163 if(gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
164 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file: %s", cafile.c_str());
166 if(gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
167 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file: %s", crlfile.c_str());
169 // Guessing on the return value of this, manual doesn't say :|
170 if(gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
171 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 certificate and key files: %s and %s", certfile.c_str(), keyfile.c_str());
173 // This may be on a large (once a day or week) timer eventually.
179 void GenerateDHParams()
181 // Generate Diffie Hellman parameters - for use with DHE
182 // kx algorithms. These should be discarded and regenerated
183 // once a day, once a week or once a month. Depending on the
184 // security requirements.
186 if(gnutls_dh_params_generate2(dh_params, dh_bits) < 0)
187 log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits)", dh_bits);
190 virtual ~ModuleSSLGnuTLS()
192 gnutls_dh_params_deinit(dh_params);
193 gnutls_certificate_free_credentials(x509_cred);
194 gnutls_global_deinit();
197 virtual void OnCleanup(int target_type, void* item)
199 if(target_type == TYPE_USER)
201 userrec* user = (userrec*)item;
203 if(user->GetExt("ssl") && IS_LOCAL(user) && isin(user->port, listenports))
205 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
206 // Potentially there could be multiple SSL modules loaded at once on different ports.
207 log(DEBUG, "m_ssl_gnutls.so: Adding user %s to cull list", user->nick);
208 culllist.AddItem(user, "SSL module unloading");
213 virtual void OnUnloadModule(Module* mod, std::string name)
217 // We're being unloaded, kill all the users added to the cull list in OnCleanup
218 int numusers = culllist.Apply();
219 log(DEBUG, "m_ssl_gnutls.so: Killed %d users for unload of GnuTLS SSL module", numusers);
221 for(unsigned int i = 0; i < listenports.size(); i++)
222 SrvConf->DelIOHook(listenports[i]);
226 virtual Version GetVersion()
228 return Version(1, 0, 0, 0, VF_VENDOR);
231 void Implements(char* List)
233 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
234 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
237 virtual void OnRawSocketAccept(int fd, std::string ip, int localport)
239 issl_session* session = &sessions[fd];
242 session->inbuf = new char[inbufsize];
243 session->inbufoffset = 0;
245 gnutls_init(&session->sess, GNUTLS_SERVER);
247 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
248 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
249 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
250 gnutls_dh_set_prime_bits(session->sess, dh_bits);
251 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
256 virtual void OnRawSocketClose(int fd)
258 log(DEBUG, "OnRawSocketClose: %d", fd);
259 CloseSession(&sessions[fd]);
262 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
264 issl_session* session = &sessions[fd];
268 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: No session to read from");
270 CloseSession(session);
274 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
276 if(session->status == ISSL_HANDSHAKING_READ)
278 // The handshake isn't finished, try to finish it.
280 if(Handshake(session))
282 // Handshake successfully resumed.
283 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: successfully resumed handshake");
287 // Couldn't resume handshake.
288 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: failed to resume handshake");
292 else if(session->status == ISSL_HANDSHAKING_WRITE)
294 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
298 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
300 if(session->status == ISSL_HANDSHAKEN)
302 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
303 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
304 log(DEBUG, "m_ssl_gnutls.so: gnutls_record_recv(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
306 int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
310 // Client closed connection.
311 log(DEBUG, "m_ssl_gnutls.so: Client closed the connection");
313 CloseSession(session);
318 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
320 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Not all SSL data read: %s", gnutls_strerror(ret));
325 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Error reading SSL data: %s", gnutls_strerror(ret));
327 CloseSession(session);
332 // Read successfully 'ret' bytes into inbuf + inbufoffset
333 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
334 // 'buffer' is 'count' long
336 unsigned int length = ret + session->inbufoffset;
338 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Read %d bytes, now have %d waiting to be passed up", ret, length);
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, (length - count));
345 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
346 session->inbufoffset = length - 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, length);
354 // Zero the offset, as there's nothing there..
355 session->inbufoffset = 0;
360 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Passing %d bytes up to insp:");
361 Srv->Log(DEBUG, std::string(buffer, readresult));
364 else if(session->status == ISSL_CLOSING)
366 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
373 virtual int OnRawSocketWrite(int fd, char* buffer, int count)
375 issl_session* session = &sessions[fd];
376 const char* sendbuffer = buffer;
380 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
381 CloseSession(session);
385 if(session->status == ISSL_HANDSHAKING_WRITE)
387 // The handshake isn't finished, try to finish it.
389 if(Handshake(session))
391 // Handshake successfully resumed.
392 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
396 // Couldn't resume handshake.
397 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake");
400 else if(session->status == ISSL_HANDSHAKING_READ)
402 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
405 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
406 session->outbuf.append(sendbuffer, count);
407 sendbuffer = session->outbuf.c_str();
408 count = session->outbuf.size();
410 if(session->status == ISSL_HANDSHAKEN)
412 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Trying to write %d bytes:", count);
413 Srv->Log(DEBUG, session->outbuf);
415 int ret = gnutls_record_send(session->sess, sendbuffer, count);
419 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Client closed the connection");
420 CloseSession(session);
424 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
426 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Not all SSL data written: %s", gnutls_strerror(ret));
430 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Error writing SSL data: %s", gnutls_strerror(ret));
431 CloseSession(session);
436 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Successfully wrote %d bytes", ret);
437 session->outbuf = session->outbuf.substr(ret);
440 else if(session->status == ISSL_CLOSING)
442 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: session closing...");
448 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
449 virtual void OnWhois(userrec* source, userrec* dest)
451 // Bugfix, only send this numeric for *our* SSL users
452 if(dest->GetExt("ssl") && isin(dest->port, listenports))
454 WriteServ(source->fd, "320 %s %s :is using a secure connection", source->nick, dest->nick);
458 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, std::string extname)
460 // check if the linking module wants to know about OUR metadata
463 // check if this user has an swhois field to send
464 if(user->GetExt(extname))
466 // call this function in the linking module, let it format the data how it
467 // sees fit, and send it on its way. We dont need or want to know how.
468 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
473 virtual void OnDecodeMetaData(int target_type, void* target, std::string extname, std::string extdata)
475 // check if its our metadata key, and its associated with a user
476 if ((target_type == TYPE_USER) && (extname == "ssl"))
478 userrec* dest = (userrec*)target;
479 // if they dont already have an ssl flag, accept the remote server's
480 if (!dest->GetExt(extname))
482 dest->Extend(extname, "ON");
487 bool Handshake(issl_session* session)
489 int ret = gnutls_handshake(session->sess);
493 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
495 // Handshake needs resuming later, read() or write() would have blocked.
497 if(gnutls_record_get_direction(session->sess) == 0)
499 // gnutls_handshake() wants to read() again.
500 session->status = ISSL_HANDSHAKING_READ;
501 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (reading) later, error string: %s", gnutls_strerror(ret));
505 // gnutls_handshake() wants to write() again.
506 session->status = ISSL_HANDSHAKING_WRITE;
507 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (writing) later, error string: %s", gnutls_strerror(ret));
508 MakePollWrite(session);
514 CloseSession(session);
515 log(DEBUG, "m_ssl_gnutls.so: Handshake failed, error string: %s", gnutls_strerror(ret));
516 session->status = ISSL_CLOSING;
523 // Handshake complete.
524 log(DEBUG, "m_ssl_gnutls.so: Handshake completed");
526 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
527 userrec* extendme = Srv->FindDescriptor(session->fd);
528 extendme->Extend("ssl", "ON");
530 // Change the seesion state
531 session->status = ISSL_HANDSHAKEN;
533 // Finish writing, if any left
534 MakePollWrite(session);
540 virtual void OnGlobalConnect(userrec* user)
542 // This occurs AFTER OnUserConnect so we can be sure the
543 // protocol module has propogated the NICK message.
544 if ((user->GetExt("ssl")) && (IS_LOCAL(user)))
546 // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
547 std::deque<std::string>* metadata = new std::deque<std::string>;
548 metadata->push_back(user->nick);
549 metadata->push_back("ssl"); // The metadata id
550 metadata->push_back("ON"); // The value to send
551 Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
552 event->Send(); // Trigger the event. We don't care what module picks it up.
558 void MakePollWrite(issl_session* session)
560 OnRawSocketWrite(session->fd, NULL, 0);
563 void CloseSession(issl_session* session)
567 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
568 gnutls_deinit(session->sess);
573 delete[] session->inbuf;
576 session->outbuf.clear();
577 session->inbuf = NULL;
578 session->sess = NULL;
579 session->status = ISSL_NONE;
583 class ModuleSSLGnuTLSFactory : public ModuleFactory
586 ModuleSSLGnuTLSFactory()
590 ~ModuleSSLGnuTLSFactory()
594 virtual Module * CreateModule(Server* Me)
596 return new ModuleSSLGnuTLS(Me);
601 extern "C" void * init_module( void )
603 return new ModuleSSLGnuTLSFactory;