]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Mass-tidyup of module global vars, theyre no longer global vars.
[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                 }
374                 else if(session->status == ISSL_CLOSING)
375                 {
376                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
377                         readresult = 0;
378                 }
379                 
380                 return 1;
381         }
382         
383         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
384         {               
385                 issl_session* session = &sessions[fd];
386                 const char* sendbuffer = buffer;
387
388                 if(!session->sess)
389                 {
390                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
391                         CloseSession(session);
392                         return 1;
393                 }
394                 
395                 if(session->status == ISSL_HANDSHAKING_WRITE)
396                 {
397                         // The handshake isn't finished, try to finish it.
398                         
399                         if(Handshake(session))
400                         {
401                                 // Handshake successfully resumed.
402                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
403                         }
404                         else
405                         {
406                                 // Couldn't resume handshake.   
407                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake"); 
408                         }
409                 }
410                 else if(session->status == ISSL_HANDSHAKING_READ)
411                 {
412                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
413                 }
414
415                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);         
416                 session->outbuf.append(sendbuffer, count);
417                 sendbuffer = session->outbuf.c_str();
418                 count = session->outbuf.size();
419
420                 if(session->status == ISSL_HANDSHAKEN)
421                 {       
422                         int ret = gnutls_record_send(session->sess, sendbuffer, count);
423                 
424                         if(ret == 0)
425                         {
426                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Client closed the connection");
427                                 CloseSession(session);
428                         }
429                         else if(ret < 0)
430                         {
431                                 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
432                                 {
433                                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Not all SSL data written: %s", gnutls_strerror(ret));
434                                 }
435                                 else
436                                 {
437                                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Error writing SSL data: %s", gnutls_strerror(ret));
438                                         CloseSession(session);                                  
439                                 }
440                         }
441                         else
442                         {
443                                 log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Successfully wrote %d bytes", ret);
444                                 session->outbuf = session->outbuf.substr(ret);
445                         }
446                 }
447                 else if(session->status == ISSL_CLOSING)
448                 {
449                         log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: session closing...");
450                 }
451                 
452                 return 1;
453         }
454         
455         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
456         virtual void OnWhois(userrec* source, userrec* dest)
457         {
458                 // Bugfix, only send this numeric for *our* SSL users
459                 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
460                 {
461                         source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
462                 }
463         }
464         
465         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
466         {
467                 // check if the linking module wants to know about OUR metadata
468                 if(extname == "ssl")
469                 {
470                         // check if this user has an swhois field to send
471                         if(user->GetExt(extname, dummy))
472                         {
473                                 // call this function in the linking module, let it format the data how it
474                                 // sees fit, and send it on its way. We dont need or want to know how.
475                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
476                         }
477                 }
478         }
479         
480         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
481         {
482                 // check if its our metadata key, and its associated with a user
483                 if ((target_type == TYPE_USER) && (extname == "ssl"))
484                 {
485                         userrec* dest = (userrec*)target;
486                         // if they dont already have an ssl flag, accept the remote server's
487                         if (!dest->GetExt(extname, dummy))
488                         {
489                                 dest->Extend(extname, "ON");
490                         }
491                 }
492         }
493         
494         bool Handshake(issl_session* session)
495         {               
496                 int ret = gnutls_handshake(session->sess);
497       
498       if(ret < 0)
499                 {
500                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
501                         {
502                                 // Handshake needs resuming later, read() or write() would have blocked.
503                                 
504                                 if(gnutls_record_get_direction(session->sess) == 0)
505                                 {
506                                         // gnutls_handshake() wants to read() again.
507                                         session->status = ISSL_HANDSHAKING_READ;
508                                         log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (reading) later, error string: %s", gnutls_strerror(ret));
509                                 }
510                                 else
511                                 {
512                                         // gnutls_handshake() wants to write() again.
513                                         session->status = ISSL_HANDSHAKING_WRITE;
514                                         log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (writing) later, error string: %s", gnutls_strerror(ret));
515                                         MakePollWrite(session); 
516                                 }
517                         }
518                         else
519                         {
520                                 // Handshake failed.
521                                 CloseSession(session);
522                            log(DEBUG, "m_ssl_gnutls.so: Handshake failed, error string: %s", gnutls_strerror(ret));
523                            session->status = ISSL_CLOSING;
524                         }
525                         
526                         return false;
527                 }
528                 else
529                 {
530                         // Handshake complete.
531                         log(DEBUG, "m_ssl_gnutls.so: Handshake completed");
532                         
533                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
534                         userrec* extendme = Srv->FindDescriptor(session->fd);
535                         if (extendme)
536                         {
537                                 if (!extendme->GetExt("ssl", dummy))
538                                         extendme->Extend("ssl", "ON");
539                         }
540
541                         // Change the seesion state
542                         session->status = ISSL_HANDSHAKEN;
543                         
544                         // Finish writing, if any left
545                         MakePollWrite(session);
546                         
547                         return true;
548                 }
549         }
550
551         virtual void OnGlobalConnect(userrec* user)
552         {
553                 // This occurs AFTER OnUserConnect so we can be sure the
554                 // protocol module has propogated the NICK message.
555                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
556                 {
557                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
558                         std::deque<std::string>* metadata = new std::deque<std::string>;
559                         metadata->push_back(user->nick);
560                         metadata->push_back("ssl");             // The metadata id
561                         metadata->push_back("ON");              // The value to send
562                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
563                         event->Send();                          // Trigger the event. We don't care what module picks it up.
564                         DELETE(event);
565                         DELETE(metadata);
566                 }
567         }
568         
569         void MakePollWrite(issl_session* session)
570         {
571                 OnRawSocketWrite(session->fd, NULL, 0);
572         }
573         
574         void CloseSession(issl_session* session)
575         {
576                 if(session->sess)
577                 {
578                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
579                         gnutls_deinit(session->sess);
580                 }
581                 
582                 if(session->inbuf)
583                 {
584                         delete[] session->inbuf;
585                 }
586                 
587                 session->outbuf.clear();
588                 session->inbuf = NULL;
589                 session->sess = NULL;
590                 session->status = ISSL_NONE;
591         }
592 };
593
594 class ModuleSSLGnuTLSFactory : public ModuleFactory
595 {
596  public:
597         ModuleSSLGnuTLSFactory()
598         {
599         }
600         
601         ~ModuleSSLGnuTLSFactory()
602         {
603         }
604         
605         virtual Module * CreateModule(Server* Me)
606         {
607                 return new ModuleSSLGnuTLS(Me);
608         }
609 };
610
611
612 extern "C" void * init_module( void )
613 {
614         return new ModuleSSLGnuTLSFactory;
615 }