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