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