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