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