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