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 };
33 gnutls_session_t sess;
41 class ModuleSSL : public Module
44 ServerConfig* SrvConf;
47 std::vector<int> listenports;
50 issl_session sessions[MAX_DESCRIPTORS];
52 gnutls_certificate_credentials x509_cred;
53 gnutls_dh_params dh_params;
67 SrvConf = Srv->GetConfig();
68 Conf = new ConfigReader;
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");
84 // Void return, guess we assume success
85 gnutls_certificate_set_dh_params(x509_cred, dh_params);
88 virtual void OnRehash(std::string param)
91 Conf = new ConfigReader;
93 for(unsigned int i = 0; i < listenports.size(); i++)
95 SrvConf->DelIOHook(listenports[i]);
100 for(int i = 0; i < Conf->Enumerate("bind"); i++)
102 // For each <bind> tag
103 if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
105 // Get the port we're meant to be listening on with SSL
106 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
107 SrvConf->AddIOHook(port, this);
109 // We keep a record of which ports we're listening on with SSL
110 listenports.push_back(port);
112 log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", port);
116 std::string confdir(CONFIG_FILE);
117 // +1 so we the path ends with a /
118 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
120 cafile = Conf->ReadValue("gnutls", "cafile", 0);
121 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
122 certfile = Conf->ReadValue("gnutls", "certfile", 0);
123 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
124 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
126 // Set all the default values needed.
134 certfile = "cert.pem";
139 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
142 // Prepend relative paths with the path to the config directory.
144 cafile = confdir + cafile;
146 if(crlfile[0] != '/')
147 crlfile = confdir + crlfile;
149 if(certfile[0] != '/')
150 certfile = confdir + certfile;
152 if(keyfile[0] != '/')
153 keyfile = confdir + keyfile;
155 if(gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
156 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file: %s", cafile.c_str());
158 if(gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
159 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file: %s", crlfile.c_str());
161 // Guessing on the return value of this, manual doesn't say :|
162 if(gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
163 log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 certificate and key files: %s and %s", certfile.c_str(), keyfile.c_str());
165 // Generate Diffie Hellman parameters - for use with DHE
166 // kx algorithms. These should be discarded and regenerated
167 // once a day, once a week or once a month. Depending on the
168 // security requirements.
170 if(gnutls_dh_params_generate2(dh_params, dh_bits) < 0)
171 log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits)", dh_bits);
177 gnutls_dh_params_deinit(dh_params);
178 gnutls_certificate_free_credentials(x509_cred);
179 gnutls_global_deinit();
182 virtual Version GetVersion()
184 return Version(1, 0, 0, 0, VF_STATIC | VF_VENDOR);
187 void Implements(char* List)
189 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
190 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUserQuit] = List[I_OnRehash] = List[I_OnWhois] = 1;
193 virtual void OnRawSocketAccept(int fd, std::string ip, int localport)
195 issl_session* session = &sessions[fd];
198 session->inbuf = new char[inbufsize];
199 session->inbufoffset = 0;
201 gnutls_init(&session->sess, GNUTLS_SERVER);
203 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
204 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
205 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
206 gnutls_dh_set_prime_bits(session->sess, dh_bits);
207 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
212 virtual void OnRawSocketClose(int fd)
214 CloseSession(&sessions[fd]);
217 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
219 issl_session* session = &sessions[fd];
223 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: No session to read from");
225 CloseSession(session);
229 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
231 if(session->status == ISSL_HANDSHAKING_READ)
233 // The handshake isn't finished, try to finish it.
235 if(Handshake(session))
237 // Handshake successfully resumed.
238 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: successfully resumed handshake");
242 // Couldn't resume handshake.
243 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: failed to resume handshake");
247 else if(session->status == ISSL_HANDSHAKING_WRITE)
249 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
253 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
255 if(session->status == ISSL_HANDSHAKEN)
257 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
258 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
259 log(DEBUG, "m_ssl_gnutls.so: gnutls_record_recv(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
261 int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
265 // Client closed connection.
266 log(DEBUG, "m_ssl_gnutls.so: Client closed the connection");
268 CloseSession(session);
273 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
275 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Not all SSL data read: %s", gnutls_strerror(ret));
280 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Error reading SSL data: %s", gnutls_strerror(ret));
282 CloseSession(session);
287 // Read successfully 'ret' bytes into inbuf + inbufoffset
288 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
289 // 'buffer' is 'count' long
291 unsigned int length = ret + session->inbufoffset;
293 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Read %d bytes, now have %d waiting to be passed up", ret, length);
297 memcpy(buffer, session->inbuf, count);
298 // Move the stuff left in inbuf to the beginning of it
299 memcpy(session->inbuf, session->inbuf + count, (length - count));
300 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
301 session->inbufoffset = length - count;
302 // Insp uses readresult as the count of how much data there is in buffer, so:
307 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
308 memcpy(buffer, session->inbuf, length);
309 // Zero the offset, as there's nothing there..
310 session->inbufoffset = 0;
315 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Passing %d bytes up to insp:");
316 Srv->Log(DEBUG, std::string(buffer, readresult));
319 else if(session->status == ISSL_CLOSING)
321 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
328 virtual int OnRawSocketWrite(int fd, char* buffer, int count)
330 issl_session* session = &sessions[fd];
331 const char* sendbuffer = buffer;
335 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
336 CloseSession(session);
340 if(session->status == ISSL_HANDSHAKING_WRITE)
342 // The handshake isn't finished, try to finish it.
344 if(Handshake(session))
346 // Handshake successfully resumed.
347 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
351 // Couldn't resume handshake.
352 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake");
355 else if(session->status == ISSL_HANDSHAKING_READ)
357 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
360 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);
361 session->outbuf.append(sendbuffer, count);
362 sendbuffer = session->outbuf.c_str();
363 count = session->outbuf.size();
365 if(session->status == ISSL_HANDSHAKEN)
367 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Trying to write %d bytes:", count);
368 Srv->Log(DEBUG, session->outbuf);
370 int ret = gnutls_record_send(session->sess, sendbuffer, count);
374 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Client closed the connection");
375 CloseSession(session);
379 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
381 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Not all SSL data written: %s", gnutls_strerror(ret));
385 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Error writing SSL data: %s", gnutls_strerror(ret));
386 CloseSession(session);
391 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Successfully wrote %d bytes", ret);
392 session->outbuf = session->outbuf.substr(ret);
395 else if(session->status == ISSL_CLOSING)
397 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: session closing...");
403 virtual void OnUserQuit(userrec* user, std::string reason)
405 CloseSession(&sessions[user->fd]);
408 // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
409 virtual void OnWhois(userrec* source, userrec* dest)
411 if(dest->GetExt("ssl"))
413 WriteServ(source->fd, "320 %s %s :is a Secure Connection", source->nick, dest->nick);
417 virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, std::string extname)
419 // check if the linking module wants to know about OUR metadata
422 // check if this user has an swhois field to send
423 if(user->GetExt(extname))
425 // call this function in the linking module, let it format the data how it
426 // sees fit, and send it on its way. We dont need or want to know how.
427 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
432 virtual void OnDecodeMetaData(int target_type, void* target, std::string extname, std::string extdata)
434 // check if its our metadata key, and its associated with a user
435 if ((target_type == TYPE_USER) && (extname == "ssl"))
437 userrec* dest = (userrec*)target;
438 // if they dont already have an ssl flag, accept the remote server's
439 if (!dest->GetExt(extname))
441 dest->Extend(extname, "ON");
446 bool Handshake(issl_session* session)
448 int ret = gnutls_handshake(session->sess);
452 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
454 // Handshake needs resuming later, read() or write() would have blocked.
456 if(gnutls_record_get_direction(session->sess) == 0)
458 // gnutls_handshake() wants to read() again.
459 session->status = ISSL_HANDSHAKING_READ;
460 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (reading) later, error string: %s", gnutls_strerror(ret));
464 // gnutls_handshake() wants to write() again.
465 session->status = ISSL_HANDSHAKING_WRITE;
466 log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (writing) later, error string: %s", gnutls_strerror(ret));
467 MakePollWrite(session);
473 CloseSession(session);
474 log(DEBUG, "m_ssl_gnutls.so: Handshake failed, error string: %s", gnutls_strerror(ret));
475 session->status = ISSL_CLOSING;
482 // Handshake complete.
483 log(DEBUG, "m_ssl_gnutls.so: Handshake completed");
485 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
486 Srv->FindDescriptor(session->fd)->Extend("ssl", "ON");
488 session->status = ISSL_HANDSHAKEN;
490 MakePollWrite(session);
496 void MakePollWrite(issl_session* session)
498 OnRawSocketWrite(session->fd, NULL, 0);
501 void CloseSession(issl_session* session)
505 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
506 gnutls_deinit(session->sess);
511 delete[] session->inbuf;
514 session->outbuf.clear();
515 session->inbuf = NULL;
516 session->sess = NULL;
517 session->status = ISSL_NONE;
521 class ModuleSSLFactory : public ModuleFactory
532 virtual Module * CreateModule(Server* Me)
534 return new ModuleSSL(Me);
539 extern "C" void * init_module( void )
541 return new ModuleSSLFactory;