]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Fix for when we hit PgSQL 9.x
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_gnutls.cpp
1 #include <string>
2 #include <vector>
3
4 #include <gnutls/gnutls.h>
5
6 #include "inspircd_config.h"
7 #include "configreader.h"
8 #include "users.h"
9 #include "channels.h"
10 #include "modules.h"
11 #include "helperfuncs.h"
12 #include "socket.h"
13 #include "hashcomp.h"
14 #include "inspircd.h"
15
16 /* $ModDesc: Provides SSL support for clients */
17 /* $CompileFlags: `libgnutls-config --cflags` */
18 /* $LinkerFlags: `libgnutls-config --libs` `perl ../gnutls_rpath.pl` */
19
20 extern InspIRCd* ServerInstance;
21
22 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
23
24 bool isin(int port, const std::vector<int> &portlist)
25 {
26         for(unsigned int i = 0; i < portlist.size(); i++)
27                 if(portlist[i] == port)
28                         return true;
29                         
30         return false;
31 }
32
33 class issl_session : public classbase
34 {
35 public:
36         gnutls_session_t sess;
37         issl_status status;
38         std::string outbuf;
39         int inbufoffset;
40         char* inbuf;
41         int fd;
42 };
43
44 class ModuleSSLGnuTLS : public Module
45 {
46         Server* Srv;
47         ConfigReader* Conf;
48
49         char* dummy;
50         
51         CullList culllist;
52         
53         std::vector<int> listenports;
54         
55         int inbufsize;
56         issl_session sessions[MAX_DESCRIPTORS];
57         
58         gnutls_certificate_credentials x509_cred;
59         gnutls_dh_params dh_params;
60         
61         std::string keyfile;
62         std::string certfile;
63         std::string cafile;
64         std::string crlfile;
65         int dh_bits;
66         
67  public:
68         
69         ModuleSSLGnuTLS(Server* Me)
70                 : Module::Module(Me)
71         {
72                 Srv = Me;
73                 
74                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
75                 inbufsize = ServerInstance->Config->NetBufferSize;
76                 
77                 gnutls_global_init(); // This must be called once in the program
78
79                 if(gnutls_certificate_allocate_credentials(&x509_cred) != 0)
80                         log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials");
81
82                 // Guessing return meaning
83                 if(gnutls_dh_params_init(&dh_params) < 0)
84                         log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters");
85
86                 // Needs the flag as it ignores a plain /rehash
87                 OnRehash("ssl");
88                 
89                 // Void return, guess we assume success
90                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
91         }
92         
93         virtual void OnRehash(const std::string &param)
94         {
95                 if(param != "ssl")
96                         return;
97         
98                 Conf = new ConfigReader;
99                 
100                 for(unsigned int i = 0; i < listenports.size(); i++)
101                 {
102                         ServerInstance->Config->DelIOHook(listenports[i]);
103                 }
104                 
105                 listenports.clear();
106                 
107                 for(int i = 0; i < Conf->Enumerate("bind"); i++)
108                 {
109                         // For each <bind> tag
110                         if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
111                         {
112                                 // Get the port we're meant to be listening on with SSL
113                                 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
114                                 if (ServerInstance->Config->AddIOHook(port, this))
115                                 {
116                                         // We keep a record of which ports we're listening on with SSL
117                                         listenports.push_back(port);
118                                 
119                                         log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", port);
120                                 }
121                                 else
122                                 {
123                                         log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
124                                 }
125                         }
126                 }
127                 
128                 std::string confdir(CONFIG_FILE);
129                 // +1 so we the path ends with a /
130                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
131                 
132                 cafile  = Conf->ReadValue("gnutls", "cafile", 0);
133                 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
134                 certfile        = Conf->ReadValue("gnutls", "certfile", 0);
135                 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
136                 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
137                 
138                 // Set all the default values needed.
139                 if(cafile == "")
140                         cafile = "ca.pem";
141                         
142                 if(crlfile == "")
143                         crlfile = "crl.pem";
144                         
145                 if(certfile == "")
146                         certfile = "cert.pem";
147                         
148                 if(keyfile == "")
149                         keyfile = "key.pem";
150                         
151                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
152                         dh_bits = 1024;
153                         
154                 // Prepend relative paths with the path to the config directory.        
155                 if(cafile[0] != '/')
156                         cafile = confdir + cafile;
157                 
158                 if(crlfile[0] != '/')
159                         crlfile = confdir + crlfile;
160                         
161                 if(certfile[0] != '/')
162                         certfile = confdir + certfile;
163                         
164                 if(keyfile[0] != '/')
165                         keyfile = confdir + keyfile;
166                 
167                 if(gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
168                         log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file: %s", cafile.c_str());
169                         
170                 if(gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
171                         log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file: %s", crlfile.c_str());
172                 
173                 // Guessing on the return value of this, manual doesn't say :|
174                 if(gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM) < 0)
175                         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                         
177                 // This may be on a large (once a day or week) timer eventually.
178                 GenerateDHParams();
179                 
180                 DELETE(Conf);
181         }
182         
183         void GenerateDHParams()
184         {
185                 // Generate Diffie Hellman parameters - for use with DHE
186                 // kx algorithms. These should be discarded and regenerated
187                 // once a day, once a week or once a month. Depending on the
188                 // security requirements.
189                 
190                 if(gnutls_dh_params_generate2(dh_params, dh_bits) < 0)
191                         log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits)", dh_bits);
192         }
193         
194         virtual ~ModuleSSLGnuTLS()
195         {
196                 gnutls_dh_params_deinit(dh_params);
197                 gnutls_certificate_free_credentials(x509_cred);
198                 gnutls_global_deinit();
199         }
200         
201         virtual void OnCleanup(int target_type, void* item)
202         {
203                 if(target_type == TYPE_USER)
204                 {
205                         userrec* user = (userrec*)item;
206                         
207                         if(user->GetExt("ssl", dummy) && isin(user->GetPort(), listenports))
208                         {
209                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
210                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
211                                 log(DEBUG, "m_ssl_gnutls.so: Adding user %s to cull list", user->nick);
212                                 culllist.AddItem(user, "SSL module unloading");
213                         }
214                 }
215         }
216         
217         virtual void OnUnloadModule(Module* mod, const std::string &name)
218         {
219                 if(mod == this)
220                 {
221                         // We're being unloaded, kill all the users added to the cull list in OnCleanup
222                         int numusers = culllist.Apply();
223                         log(DEBUG, "m_ssl_gnutls.so: Killed %d users for unload of GnuTLS SSL module", numusers);
224                         
225                         for(unsigned int i = 0; i < listenports.size(); i++)
226                                 ServerInstance->Config->DelIOHook(listenports[i]);
227                 }
228         }
229         
230         virtual Version GetVersion()
231         {
232                 return Version(1, 0, 0, 0, VF_VENDOR);
233         }
234
235         void Implements(char* List)
236         {
237                 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
238                 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
239         }
240
241         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
242         {
243                 issl_session* session = &sessions[fd];
244         
245                 session->fd = fd;
246                 session->inbuf = new char[inbufsize];
247                 session->inbufoffset = 0;
248         
249                 gnutls_init(&session->sess, GNUTLS_SERVER);
250
251                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
252                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
253                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
254                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
255                 
256                 /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes
257                  * This needs testing, but it's easy enough to rollback if need be
258                  * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
259                  * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket.
260                  *
261                  * With testing this seems to...not work :/
262                  */
263                 
264                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
265                 
266                 Handshake(session);
267         }
268
269         virtual void OnRawSocketClose(int fd)
270         {
271                 log(DEBUG, "OnRawSocketClose: %d", fd);
272                 CloseSession(&sessions[fd]);
273         }
274         
275         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
276         {
277                 issl_session* session = &sessions[fd];
278                 
279                 if(!session->sess)
280                 {
281                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: No session to read from");
282                         readresult = 0;
283                         CloseSession(session);
284                         return 1;
285                 }
286                 
287                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
288                 
289                 if(session->status == ISSL_HANDSHAKING_READ)
290                 {
291                         // The handshake isn't finished, try to finish it.
292                         
293                         if(Handshake(session))
294                         {
295                                 // Handshake successfully resumed.
296                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: successfully resumed handshake");
297                         }
298                         else
299                         {
300                                 // Couldn't resume handshake.   
301                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: failed to resume handshake");
302                                 return -1;
303                         }
304                 }
305                 else if(session->status == ISSL_HANDSHAKING_WRITE)
306                 {
307                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
308                         return -1;
309                 }
310                 
311                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
312                 
313                 if(session->status == ISSL_HANDSHAKEN)
314                 {
315                         // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
316                         // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
317                         log(DEBUG, "m_ssl_gnutls.so: gnutls_record_recv(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
318                         
319                         int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
320
321                         if(ret == 0)
322                         {
323                                 // Client closed connection.
324                                 log(DEBUG, "m_ssl_gnutls.so: Client closed the connection");
325                                 readresult = 0;
326                                 CloseSession(session);
327                                 return 1;
328                         }
329                         else if(ret < 0)
330                         {
331                                 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
332                                 {
333                                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Not all SSL data read: %s", gnutls_strerror(ret));
334                                         return -1;
335                                 }
336                                 else
337                                 {
338                                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Error reading SSL data: %s", gnutls_strerror(ret));
339                                         readresult = 0;
340                                         CloseSession(session);
341                                 }
342                         }
343                         else
344                         {
345                                 // Read successfully 'ret' bytes into inbuf + inbufoffset
346                                 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
347                                 // 'buffer' is 'count' long
348                                 
349                                 unsigned int length = ret + session->inbufoffset;
350                 
351                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Read %d bytes, now have %d waiting to be passed up", ret, length);
352                                                 
353                                 if(count <= length)
354                                 {
355                                         memcpy(buffer, session->inbuf, count);
356                                         // Move the stuff left in inbuf to the beginning of it
357                                         memcpy(session->inbuf, session->inbuf + count, (length - count));
358                                         // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
359                                         session->inbufoffset = length - count;
360                                         // Insp uses readresult as the count of how much data there is in buffer, so:
361                                         readresult = count;
362                                 }
363                                 else
364                                 {
365                                         // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
366                                         memcpy(buffer, session->inbuf, length);
367                                         // Zero the offset, as there's nothing there..
368                                         session->inbufoffset = 0;
369                                         // As above
370                                         readresult = length;
371                                 }
372                         
373                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Passing %d bytes up to insp:", length);
374                                 Srv->Log(DEBUG, std::string(buffer, readresult));
375                         }
376                 }
377                 else if(session->status == ISSL_CLOSING)
378                 {
379                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
380                         readresult = 0;
381                 }
382                 
383                 return 1;
384         }
385         
386         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
387         {               
388                 issl_session* session = &sessions[fd];
389                 const char* sendbuffer = buffer;
390
391                 if(!session->sess)
392                 {
393                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
394                         CloseSession(session);
395                         return 1;
396                 }
397                 
398                 if(session->status == ISSL_HANDSHAKING_WRITE)
399                 {
400                         // The handshake isn't finished, try to finish it.
401                         
402                         if(Handshake(session))
403                         {
404                                 // Handshake successfully resumed.
405                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
406                         }
407                         else
408                         {
409                                 // Couldn't resume handshake.   
410                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake"); 
411                         }
412                 }
413                 else if(session->status == ISSL_HANDSHAKING_READ)
414                 {
415                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
416                 }
417
418                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);         
419                 session->outbuf.append(sendbuffer, count);
420                 sendbuffer = session->outbuf.c_str();
421                 count = session->outbuf.size();
422
423                 if(session->status == ISSL_HANDSHAKEN)
424                 {
425                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Trying to write %d bytes:", count);
426                         Srv->Log(DEBUG, session->outbuf);
427                         
428                         int ret = gnutls_record_send(session->sess, sendbuffer, count);
429                 
430                         if(ret == 0)
431                         {
432                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Client closed the connection");
433                                 CloseSession(session);
434                         }
435                         else if(ret < 0)
436                         {
437                                 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
438                                 {
439                                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Not all SSL data written: %s", gnutls_strerror(ret));
440                                 }
441                                 else
442                                 {
443                                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Error writing SSL data: %s", gnutls_strerror(ret));
444                                         CloseSession(session);                                  
445                                 }
446                         }
447                         else
448                         {
449                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Successfully wrote %d bytes", ret);
450                                 session->outbuf = session->outbuf.substr(ret);
451                         }
452                 }
453                 else if(session->status == ISSL_CLOSING)
454                 {
455                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: session closing...");
456                 }
457                 
458                 return 1;
459         }
460         
461         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
462         virtual void OnWhois(userrec* source, userrec* dest)
463         {
464                 // Bugfix, only send this numeric for *our* SSL users
465                 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
466                 {
467                         source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
468                 }
469         }
470         
471         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
472         {
473                 // check if the linking module wants to know about OUR metadata
474                 if(extname == "ssl")
475                 {
476                         // check if this user has an swhois field to send
477                         if(user->GetExt(extname, dummy))
478                         {
479                                 // call this function in the linking module, let it format the data how it
480                                 // sees fit, and send it on its way. We dont need or want to know how.
481                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
482                         }
483                 }
484         }
485         
486         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
487         {
488                 // check if its our metadata key, and its associated with a user
489                 if ((target_type == TYPE_USER) && (extname == "ssl"))
490                 {
491                         userrec* dest = (userrec*)target;
492                         // if they dont already have an ssl flag, accept the remote server's
493                         if (!dest->GetExt(extname, dummy))
494                         {
495                                 dest->Extend(extname, "ON");
496                         }
497                 }
498         }
499         
500         bool Handshake(issl_session* session)
501         {               
502                 int ret = gnutls_handshake(session->sess);
503       
504       if(ret < 0)
505                 {
506                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
507                         {
508                                 // Handshake needs resuming later, read() or write() would have blocked.
509                                 
510                                 if(gnutls_record_get_direction(session->sess) == 0)
511                                 {
512                                         // gnutls_handshake() wants to read() again.
513                                         session->status = ISSL_HANDSHAKING_READ;
514                                         log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (reading) later, error string: %s", gnutls_strerror(ret));
515                                 }
516                                 else
517                                 {
518                                         // gnutls_handshake() wants to write() again.
519                                         session->status = ISSL_HANDSHAKING_WRITE;
520                                         log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (writing) later, error string: %s", gnutls_strerror(ret));
521                                         MakePollWrite(session); 
522                                 }
523                         }
524                         else
525                         {
526                                 // Handshake failed.
527                                 CloseSession(session);
528                            log(DEBUG, "m_ssl_gnutls.so: Handshake failed, error string: %s", gnutls_strerror(ret));
529                            session->status = ISSL_CLOSING;
530                         }
531                         
532                         return false;
533                 }
534                 else
535                 {
536                         // Handshake complete.
537                         log(DEBUG, "m_ssl_gnutls.so: Handshake completed");
538                         
539                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
540                         userrec* extendme = Srv->FindDescriptor(session->fd);
541                         if (extendme)
542                         {
543                                 if (!extendme->GetExt("ssl", dummy))
544                                         extendme->Extend("ssl", "ON");
545                         }
546
547                         // Change the seesion state
548                         session->status = ISSL_HANDSHAKEN;
549                         
550                         // Finish writing, if any left
551                         MakePollWrite(session);
552                         
553                         return true;
554                 }
555         }
556
557         virtual void OnGlobalConnect(userrec* user)
558         {
559                 // This occurs AFTER OnUserConnect so we can be sure the
560                 // protocol module has propogated the NICK message.
561                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
562                 {
563                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
564                         std::deque<std::string>* metadata = new std::deque<std::string>;
565                         metadata->push_back(user->nick);
566                         metadata->push_back("ssl");             // The metadata id
567                         metadata->push_back("ON");              // The value to send
568                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
569                         event->Send();                          // Trigger the event. We don't care what module picks it up.
570                         DELETE(event);
571                         DELETE(metadata);
572                 }
573         }
574         
575         void MakePollWrite(issl_session* session)
576         {
577                 OnRawSocketWrite(session->fd, NULL, 0);
578         }
579         
580         void CloseSession(issl_session* session)
581         {
582                 if(session->sess)
583                 {
584                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
585                         gnutls_deinit(session->sess);
586                 }
587                 
588                 if(session->inbuf)
589                 {
590                         delete[] session->inbuf;
591                 }
592                 
593                 session->outbuf.clear();
594                 session->inbuf = NULL;
595                 session->sess = NULL;
596                 session->status = ISSL_NONE;
597         }
598 };
599
600 class ModuleSSLGnuTLSFactory : public ModuleFactory
601 {
602  public:
603         ModuleSSLGnuTLSFactory()
604         {
605         }
606         
607         ~ModuleSSLGnuTLSFactory()
608         {
609         }
610         
611         virtual Module * CreateModule(Server* Me)
612         {
613                 return new ModuleSSLGnuTLS(Me);
614         }
615 };
616
617
618 extern "C" void * init_module( void )
619 {
620         return new ModuleSSLGnuTLSFactory;
621 }