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