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