8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
14 #include <gnutls/gnutls.h>
16 #include "inspircd_config.h"
20 #include "helperfuncs.h"
24 /* $ModDesc: Provides SSL support for clients */
25 /* $CompileFlags: `libgnutls-config --cflags` */
26 /* $LinkerFlags: -L/usr/local/lib -Wl,--rpath -Wl,/usr/local/lib -L/usr/lib -Wl,--rpath -Wl,/usr/lib -lgnutls */
28 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
30 bool isin(int port, std::vector<int> portlist)
32 for(unsigned int i = 0; i < portlist.size(); i++)
33 if(portlist[i] == port)
42 gnutls_session_t sess;
50 class ModuleSSL : public Module
53 ServerConfig* SrvConf;
58 std::vector<int> listenports;
61 issl_session sessions[MAX_DESCRIPTORS];
63 gnutls_certificate_credentials x509_cred;
64 gnutls_dh_params dh_params;
78 SrvConf = Srv->GetConfig();
79 Conf = new ConfigReader;
81 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
82 inbufsize = SrvConf->NetBufferSize;
84 gnutls_global_init(); // This must be called once in the program
86 if(gnutls_certificate_allocate_credentials(&x509_cred) != 0)
87 log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials");
89 // Guessing return meaning
90 if(gnutls_dh_params_init(&dh_params) < 0)
91 log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters");
95 // Void return, guess we assume success
96 gnutls_certificate_set_dh_params(x509_cred, dh_params);
99 virtual void OnRehash(std::string param)
102 Conf = new ConfigReader;
104 for(unsigned int i = 0; i < listenports.size(); i++)
106 SrvConf->DelIOHook(listenports[i]);
111 for(int i = 0; i < Conf->Enumerate("bind"); i++)
113 // For each <bind> tag
114 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
116 // Get the port we're meant to be listening on with SSL
117 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
118 SrvConf->AddIOHook(port, this);
120 // We keep a record of which ports we're listening on with SSL
121 listenports.push_back(port);
123 log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", 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 // Generate Diffie Hellman parameters - for use with DHE
177 // kx algorithms. These should be discarded and regenerated
178 // once a day, once a week or once a month. Depending on the
179 // security requirements.
181 if(gnutls_dh_params_generate2(dh_params, dh_bits) < 0)
182 log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits)", dh_bits);
188 gnutls_dh_params_deinit(dh_params);
189 gnutls_certificate_free_credentials(x509_cred);
190 gnutls_global_deinit();
193 virtual void OnCleanup(int target_type, void* item)
195 if(target_type == TYPE_USER)
197 userrec* user = (userrec*)item;
199 if(user->GetExt("ssl") && isin(user->port, listenports))
201 // User is using SSL, and they're using one of *our* SSL ports.
202 // Potentially there could be multiple SSL modules loaded at once on different ports.
203 culllist.AddItem(user, "SSL module unloading");
208 virtual void OnUnloadModule(Module* mod, std::string name)
212 // We're being unloaded, kill all the users added to the cull list in OnCleanup
213 int numusers = culllist.Apply();
214 log(DEBUG, "m_ssl_gnutls.so: Killed %d users for unload of GnuTLS SSL module", numusers);
218 virtual Version GetVersion()
220 return Version(1, 0, 0, 0, VF_VENDOR);
223 void Implements(char* List)
225 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
226 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = 1;
229 virtual void OnRawSocketAccept(int fd, std::string ip, int localport)
231 issl_session* session = &sessions[fd];
234 session->inbuf = new char[inbufsize];
235 session->inbufoffset = 0;
237 gnutls_init(&session->sess, GNUTLS_SERVER);
239 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
240 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
241 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
242 gnutls_dh_set_prime_bits(session->sess, dh_bits);
243 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
248 virtual void OnRawSocketClose(int fd)
250 CloseSession(&sessions[fd]);
253 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
255 issl_session* session = &sessions[fd];
259 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: No session to read from");
261 CloseSession(session);
265 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
267 if(session->status == ISSL_HANDSHAKING_READ)
269 // The handshake isn't finished, try to finish it.
271 if(Handshake(session))
273 // Handshake successfully resumed.
274 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: successfully resumed handshake");
278 // Couldn't resume handshake.
279 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: failed to resume handshake");
283 else if(session->status == ISSL_HANDSHAKING_WRITE)
285 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
289 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
291 if(session->status == ISSL_HANDSHAKEN)
293 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
294 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
295 log(DEBUG, "m_ssl_gnutls.so: gnutls_record_recv(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
297 int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
301 // Client closed connection.
302 log(DEBUG, "m_ssl_gnutls.so: Client closed the connection");
304 CloseSession(session);
309 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
311 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Not all SSL data read: %s", gnutls_strerror(ret));
316 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Error reading SSL data: %s", gnutls_strerror(ret));
318 CloseSession(session);
323 // Read successfully 'ret' bytes into inbuf + inbufoffset
324 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
325 // 'buffer' is 'count' long
327 unsigned int length = ret + session->inbufoffset;
329 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Read %d bytes, now have %d waiting to be passed up", ret, length);
333 memcpy(buffer, session->inbuf, count);
334 // Move the stuff left in inbuf to the beginning of it
335 memcpy(session->inbuf, session->inbuf + count, (length - count));
336 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
337 session->inbufoffset = length - count;
338 // Insp uses readresult as the count of how much data there is in buffer, so:
343 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
344 memcpy(buffer, session->inbuf, length);
345 // Zero the offset, as there's nothing there..
346 session->inbufoffset = 0;
351 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Passing %d bytes up to insp:");
352 Srv->Log(DEBUG, std::string(buffer, readresult));
355 else if(session->status == ISSL_CLOSING)
357 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
364 virtual int OnRawSocketWrite(int fd, char* buffer, int count)
366 issl_session* session = &sessions[fd];
367 const char* sendbuffer = buffer;
371 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
372 CloseSession(session);
376 if(session->status == ISSL_HANDSHAKING_WRITE)
378 // The handshake isn't finished, try to finish it.
380 if(Handshake(session))
382 // Handshake successfully resumed.
383 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
387 // Couldn't resume handshake.
388 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake");
391 else if(session->status == ISSL_HANDSHAKING_READ)
393 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
396 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
397 session->outbuf.append(sendbuffer, count);
398 sendbuffer = session->outbuf.c_str();
399 count = session->outbuf.size();
401 if(session->status == ISSL_HANDSHAKEN)
403 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Trying to write %d bytes:", count);
404 Srv->Log(DEBUG, session->outbuf);
406 int ret = gnutls_record_send(session->sess, sendbuffer, count);
410 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Client closed the connection");
411 CloseSession(session);
415 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
417 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Not all SSL data written: %s", gnutls_strerror(ret));
421 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Error writing SSL data: %s", gnutls_strerror(ret));
422 CloseSession(session);
427 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Successfully wrote %d bytes", ret);
428 session->outbuf = session->outbuf.substr(ret);
431 else if(session->status == ISSL_CLOSING)
433 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: session closing...");
439 virtual void OnUserQuit(userrec* user, std::string reason)
442 CloseSession(&sessions[user->fd]);
445 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
446 virtual void OnWhois(userrec* source, userrec* dest)
448 if(dest->GetExt("ssl"))
450 WriteServ(source->fd, "320 %s %s :is a Secure Connection", source->nick, dest->nick);
454 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, std::string extname)
456 // check if the linking module wants to know about OUR metadata
459 // check if this user has an swhois field to send
460 if(user->GetExt(extname))
462 // call this function in the linking module, let it format the data how it
463 // sees fit, and send it on its way. We dont need or want to know how.
464 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
469 virtual void OnDecodeMetaData(int target_type, void* target, std::string extname, std::string extdata)
471 // check if its our metadata key, and its associated with a user
472 if ((target_type == TYPE_USER) && (extname == "ssl"))
474 userrec* dest = (userrec*)target;
475 // if they dont already have an ssl flag, accept the remote server's
476 if (!dest->GetExt(extname))
478 dest->Extend(extname, "ON");
483 bool Handshake(issl_session* session)
485 int ret = gnutls_handshake(session->sess);
489 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
491 // Handshake needs resuming later, read() or write() would have blocked.
493 if(gnutls_record_get_direction(session->sess) == 0)
495 // gnutls_handshake() wants to read() again.
496 session->status = ISSL_HANDSHAKING_READ;
497 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (reading) later, error string: %s", gnutls_strerror(ret));
501 // gnutls_handshake() wants to write() again.
502 session->status = ISSL_HANDSHAKING_WRITE;
503 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (writing) later, error string: %s", gnutls_strerror(ret));
504 MakePollWrite(session);
510 CloseSession(session);
511 log(DEBUG, "m_ssl_gnutls.so: Handshake failed, error string: %s", gnutls_strerror(ret));
512 session->status = ISSL_CLOSING;
519 // Handshake complete.
520 log(DEBUG, "m_ssl_gnutls.so: Handshake completed");
522 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
523 Srv->FindDescriptor(session->fd)->Extend("ssl", "ON");
525 session->status = ISSL_HANDSHAKEN;
527 MakePollWrite(session);
533 void MakePollWrite(issl_session* session)
535 OnRawSocketWrite(session->fd, NULL, 0);
538 void CloseSession(issl_session* session)
542 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
543 gnutls_deinit(session->sess);
548 delete[] session->inbuf;
551 session->outbuf.clear();
552 session->inbuf = NULL;
553 session->sess = NULL;
554 session->status = ISSL_NONE;
558 class ModuleSSLFactory : public ModuleFactory
569 virtual Module * CreateModule(Server* Me)
571 return new ModuleSSL(Me);
576 extern "C" void * init_module( void )
578 return new ModuleSSLFactory;