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