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