]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Fix for bug #601
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_gnutls.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15
16 #include <gnutls/gnutls.h>
17 #include <gnutls/x509.h>
18
19 #include "inspircd_config.h"
20 #include "configreader.h"
21 #include "users.h"
22 #include "channels.h"
23 #include "modules.h"
24 #include "socket.h"
25 #include "hashcomp.h"
26 #include "transport.h"
27 #include "m_cap.h"
28
29 #ifdef WINDOWS
30 #pragma comment(lib, "libgnutls-13.lib")
31 #endif
32
33 /* $ModDesc: Provides SSL support for clients */
34 /* $CompileFlags: exec("libgnutls-config --cflags") */
35 /* $LinkerFlags: rpath("libgnutls-config --libs") exec("libgnutls-config --libs") */
36 /* $ModDep: transport.h */
37 /* $CopyInstall: conf/key.pem $(CONPATH) */
38 /* $CopyInstall: conf/cert.pem $(CONPATH) */
39
40 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
41
42 bool isin(const std::string &host, int port, const std::vector<std::string> &portlist)
43 {
44         if (std::find(portlist.begin(), portlist.end(), "*:" + ConvToStr(port)) != portlist.end())
45                 return true;
46
47         if (std::find(portlist.begin(), portlist.end(), ":" + ConvToStr(port)) != portlist.end())
48                 return true;
49
50         return std::find(portlist.begin(), portlist.end(), host + ":" + ConvToStr(port)) != portlist.end();
51 }
52
53 /** Represents an SSL user's extra data
54  */
55 class issl_session : public classbase
56 {
57 public:
58         issl_session()
59         {
60                 sess = NULL;
61         }
62
63         gnutls_session_t sess;
64         issl_status status;
65         std::string outbuf;
66         int inbufoffset;
67         char* inbuf;
68         int fd;
69 };
70
71 class CommandStartTLS : public Command
72 {
73         Module* Caller;
74  public:
75         /* Command 'dalinfo', takes no parameters and needs no special modes */
76         CommandStartTLS (InspIRCd* Instance, Module* mod) : Command(Instance,"STARTTLS", 0, 0, true), Caller(mod)
77         {
78                 this->source = "m_ssl_gnutls.so";
79         }
80
81         CmdResult Handle (const std::vector<std::string> &parameters, User *user)
82         {
83                 if (user->registered == REG_ALL)
84                 {
85                         ServerInstance->Users->QuitUser(user, "STARTTLS not allowed after client registration");
86                 }
87                 else
88                 {
89                         if (!user->GetIOHook())
90                         {
91                                 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
92                                 user->AddIOHook(Caller);
93                                 Caller->OnRawSocketAccept(user->GetFd(), user->GetIPString(), user->GetPort());
94                         }
95                         else
96                                 user->WriteNumeric(671, "%s :STARTTLS failure", user->nick.c_str());
97                 }
98
99                 return CMD_FAILURE;
100         }
101 };
102
103 class ModuleSSLGnuTLS : public Module
104 {
105
106         ConfigReader* Conf;
107
108         char* dummy;
109
110         std::vector<std::string> listenports;
111
112         int inbufsize;
113         issl_session* sessions;
114
115         gnutls_certificate_credentials x509_cred;
116         gnutls_dh_params dh_params;
117
118         std::string keyfile;
119         std::string certfile;
120         std::string cafile;
121         std::string crlfile;
122         std::string sslports;
123         int dh_bits;
124
125         int clientactive;
126         bool cred_alloc;
127
128         CommandStartTLS* starttls;
129
130  public:
131
132         ModuleSSLGnuTLS(InspIRCd* Me)
133                 : Module(Me)
134         {
135                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
136
137                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
138
139                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
140                 inbufsize = ServerInstance->Config->NetBufferSize;
141
142                 gnutls_global_init(); // This must be called once in the program
143
144                 cred_alloc = false;
145                 // Needs the flag as it ignores a plain /rehash
146                 OnRehash(NULL,"ssl");
147
148                 // Void return, guess we assume success
149                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
150                 Implementation eventlist[] = { I_On005Numeric, I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup,
151                         I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect, I_OnEvent, I_OnHookUserIO };
152                 ServerInstance->Modules->Attach(eventlist, this, 17);
153
154                 starttls = new CommandStartTLS(ServerInstance, this);
155                 ServerInstance->AddCommand(starttls);
156         }
157
158         virtual void OnRehash(User* user, const std::string &param)
159         {
160                 Conf = new ConfigReader(ServerInstance);
161
162                 listenports.clear();
163                 clientactive = 0;
164                 sslports.clear();
165
166                 for(int index = 0; index < Conf->Enumerate("bind"); index++)
167                 {
168                         // For each <bind> tag
169                         std::string x = Conf->ReadValue("bind", "type", index);
170                         if(((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", index) == "gnutls"))
171                         {
172                                 // Get the port we're meant to be listening on with SSL
173                                 std::string port = Conf->ReadValue("bind", "port", index);
174                                 std::string addr = Conf->ReadValue("bind", "address", index);
175
176                                 irc::portparser portrange(port, false);
177                                 long portno = -1;
178                                 while ((portno = portrange.GetToken()))
179                                 {
180                                         clientactive++;
181                                         try
182                                         {
183                                                 listenports.push_back(addr + ":" + ConvToStr(portno));
184
185                                                 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
186                                                         if ((ServerInstance->Config->ports[i]->GetPort() == portno) && (ServerInstance->Config->ports[i]->GetIP() == addr))
187                                                                 ServerInstance->Config->ports[i]->SetDescription("ssl");
188                                                 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %ld", portno);
189
190                                                 sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
191                                         }
192                                         catch (ModuleException &e)
193                                         {
194                                                 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %ld: %s. Maybe it's already hooked by the same port on a different IP, or you have an other SSL or similar module loaded?", portno, e.GetReason());
195                                         }
196                                 }
197                         }
198                 }
199
200                 if (!sslports.empty())
201                         sslports.erase(sslports.end() - 1);
202
203                 if(param != "ssl")
204                 {
205                         delete Conf;
206                         return;
207                 }
208
209                 std::string confdir(ServerInstance->ConfigFileName);
210                 // +1 so we the path ends with a /
211                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
212
213                 cafile  = Conf->ReadValue("gnutls", "cafile", 0);
214                 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
215                 certfile        = Conf->ReadValue("gnutls", "certfile", 0);
216                 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
217                 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
218
219                 // Set all the default values needed.
220                 if (cafile.empty())
221                         cafile = "ca.pem";
222
223                 if (crlfile.empty())
224                         crlfile = "crl.pem";
225
226                 if (certfile.empty())
227                         certfile = "cert.pem";
228
229                 if (keyfile.empty())
230                         keyfile = "key.pem";
231
232                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
233                         dh_bits = 1024;
234
235                 // Prepend relative paths with the path to the config directory.
236                 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
237                         cafile = confdir + cafile;
238
239                 if ((crlfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(crlfile)))
240                         crlfile = confdir + crlfile;
241
242                 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
243                         certfile = confdir + certfile;
244
245                 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
246                         keyfile = confdir + keyfile;
247
248                 int ret;
249                 
250                 if (cred_alloc)
251                 {
252                         // Deallocate the old credentials
253                         gnutls_dh_params_deinit(dh_params);
254                         gnutls_certificate_free_credentials(x509_cred);
255                 }
256                 else
257                         cred_alloc = true;
258                 
259                 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
260                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
261                 
262                 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
263                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
264                 
265                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
266                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file '%s': %s", cafile.c_str(), gnutls_strerror(ret));
267
268                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
269                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret));
270
271                 if((ret = gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
272                 {
273                         // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
274                         throw ModuleException("Unable to load GnuTLS server certificate: " + std::string(gnutls_strerror(ret)));
275                 }
276
277                 // This may be on a large (once a day or week) timer eventually.
278                 GenerateDHParams();
279
280                 delete Conf;
281         }
282
283         void GenerateDHParams()
284         {
285                 // Generate Diffie Hellman parameters - for use with DHE
286                 // kx algorithms. These should be discarded and regenerated
287                 // once a day, once a week or once a month. Depending on the
288                 // security requirements.
289
290                 int ret;
291
292                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
293                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
294         }
295
296         virtual ~ModuleSSLGnuTLS()
297         {
298                 gnutls_dh_params_deinit(dh_params);
299                 gnutls_certificate_free_credentials(x509_cred);
300                 gnutls_global_deinit();
301                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
302                 delete[] sessions;
303         }
304
305         virtual void OnCleanup(int target_type, void* item)
306         {
307                 if(target_type == TYPE_USER)
308                 {
309                         User* user = (User*)item;
310
311                         if (user->GetIOHook() == this)
312                         {
313                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
314                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
315                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
316                                 user->DelIOHook();
317                         }
318                         if (user->GetExt("ssl_cert", dummy))
319                         {
320                                 ssl_cert* tofree;
321                                 user->GetExt("ssl_cert", tofree);
322                                 delete tofree;
323                                 user->Shrink("ssl_cert");
324                         }
325                 }
326         }
327
328         virtual void OnUnloadModule(Module* mod, const std::string &name)
329         {
330                 if(mod == this)
331                 {
332                         for(unsigned int i = 0; i < listenports.size(); i++)
333                         {
334                                 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
335                                         if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
336                                                 ServerInstance->Config->ports[j]->SetDescription("plaintext");
337                         }
338                 }
339         }
340
341         virtual Version GetVersion()
342         {
343                 return Version("$Id$", VF_VENDOR, API_VERSION);
344         }
345
346
347         virtual void On005Numeric(std::string &output)
348         {
349                 output.append(" SSL=" + sslports);
350         }
351
352         virtual void OnHookUserIO(User* user, const std::string &targetip)
353         {
354                 if (!user->GetIOHook() && isin(targetip,user->GetPort(),listenports))
355                 {
356                         /* Hook the user with our module */
357                         user->AddIOHook(this);
358                 }
359         }
360
361         virtual const char* OnRequest(Request* request)
362         {
363                 ISHRequest* ISR = (ISHRequest*)request;
364                 if (strcmp("IS_NAME", request->GetId()) == 0)
365                 {
366                         return "gnutls";
367                 }
368                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
369                 {
370                         const char* ret = "OK";
371                         try
372                         {
373                                 ret = ISR->Sock->AddIOHook((Module*)this) ? "OK" : NULL;
374                         }
375                         catch (ModuleException &e)
376                         {
377                                 return NULL;
378                         }
379                         return ret;
380                 }
381                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
382                 {
383                         return ISR->Sock->DelIOHook() ? "OK" : NULL;
384                 }
385                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
386                 {
387                         if (ISR->Sock->GetFd() < 0)
388                                 return "OK";
389
390                         issl_session* session = &sessions[ISR->Sock->GetFd()];
391                         return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : "OK";
392                 }
393                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
394                 {
395                         if (ISR->Sock->GetFd() > -1)
396                         {
397                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
398                                 if (session->sess)
399                                 {
400                                         if ((Extensible*)ServerInstance->FindDescriptor(ISR->Sock->GetFd()) == (Extensible*)(ISR->Sock))
401                                         {
402                                                 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
403                                                 return "OK";
404                                         }
405                                 }
406                         }
407                 }
408                 return NULL;
409         }
410
411
412         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
413         {
414                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
415                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
416                         return;
417
418                 issl_session* session = &sessions[fd];
419
420                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
421                 if (session->sess)
422                         return;
423
424                 session->fd = fd;
425                 session->inbuf = new char[inbufsize];
426                 session->inbufoffset = 0;
427
428                 gnutls_init(&session->sess, GNUTLS_SERVER);
429
430                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
431                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
432                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
433
434                 /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes
435                  * This needs testing, but it's easy enough to rollback if need be
436                  * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
437                  * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket.
438                  *
439                  * With testing this seems to...not work :/
440                  */
441
442                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
443
444                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
445
446                 Handshake(session);
447         }
448
449         virtual void OnRawSocketConnect(int fd)
450         {
451                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
452                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
453                         return;
454
455                 issl_session* session = &sessions[fd];
456
457                 session->fd = fd;
458                 session->inbuf = new char[inbufsize];
459                 session->inbufoffset = 0;
460
461                 gnutls_init(&session->sess, GNUTLS_CLIENT);
462
463                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
464                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
465                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
466                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
467
468                 Handshake(session);
469         }
470
471         virtual void OnRawSocketClose(int fd)
472         {
473                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
474                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds()))
475                         return;
476
477                 CloseSession(&sessions[fd]);
478
479                 EventHandler* user = ServerInstance->SE->GetRef(fd);
480
481                 if ((user) && (user->GetExt("ssl_cert", dummy)))
482                 {
483                         ssl_cert* tofree;
484                         user->GetExt("ssl_cert", tofree);
485                         delete tofree;
486                         user->Shrink("ssl_cert");
487                 }
488         }
489
490         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
491         {
492                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
493                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
494                         return 0;
495
496                 issl_session* session = &sessions[fd];
497
498                 if (!session->sess)
499                 {
500                         readresult = 0;
501                         CloseSession(session);
502                         return 1;
503                 }
504
505                 if (session->status == ISSL_HANDSHAKING_READ)
506                 {
507                         // The handshake isn't finished, try to finish it.
508
509                         if(!Handshake(session))
510                         {
511                                 // Couldn't resume handshake.
512                                 return -1;
513                         }
514                 }
515                 else if (session->status == ISSL_HANDSHAKING_WRITE)
516                 {
517                         errno = EAGAIN;
518                         MakePollWrite(session);
519                         return -1;
520                 }
521
522                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
523
524                 if (session->status == ISSL_HANDSHAKEN)
525                 {
526                         // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
527                         // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
528                         int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
529
530                         if (ret == 0)
531                         {
532                                 // Client closed connection.
533                                 readresult = 0;
534                                 CloseSession(session);
535                                 return 1;
536                         }
537                         else if (ret < 0)
538                         {
539                                 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
540                                 {
541                                         errno = EAGAIN;
542                                         return -1;
543                                 }
544                                 else
545                                 {
546                                         readresult = 0;
547                                         CloseSession(session);
548                                 }
549                         }
550                         else
551                         {
552                                 // Read successfully 'ret' bytes into inbuf + inbufoffset
553                                 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
554                                 // 'buffer' is 'count' long
555
556                                 unsigned int length = ret + session->inbufoffset;
557
558                                 if(count <= length)
559                                 {
560                                         memcpy(buffer, session->inbuf, count);
561                                         // Move the stuff left in inbuf to the beginning of it
562                                         memmove(session->inbuf, session->inbuf + count, (length - count));
563                                         // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
564                                         session->inbufoffset = length - count;
565                                         // Insp uses readresult as the count of how much data there is in buffer, so:
566                                         readresult = count;
567                                 }
568                                 else
569                                 {
570                                         // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
571                                         memcpy(buffer, session->inbuf, length);
572                                         // Zero the offset, as there's nothing there..
573                                         session->inbufoffset = 0;
574                                         // As above
575                                         readresult = length;
576                                 }
577                         }
578                 }
579                 else if(session->status == ISSL_CLOSING)
580                         readresult = 0;
581
582                 return 1;
583         }
584
585         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
586         {
587                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
588                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
589                         return 0;
590
591                 issl_session* session = &sessions[fd];
592                 const char* sendbuffer = buffer;
593
594                 if (!session->sess)
595                 {
596                         CloseSession(session);
597                         return 1;
598                 }
599
600                 session->outbuf.append(sendbuffer, count);
601                 sendbuffer = session->outbuf.c_str();
602                 count = session->outbuf.size();
603
604                 if (session->status == ISSL_HANDSHAKING_WRITE)
605                 {
606                         // The handshake isn't finished, try to finish it.
607                         Handshake(session);
608                         errno = EAGAIN;
609                         return -1;
610                 }
611
612                 int ret = 0;
613
614                 if (session->status == ISSL_HANDSHAKEN)
615                 {
616                         ret = gnutls_record_send(session->sess, sendbuffer, count);
617
618                         if (ret == 0)
619                         {
620                                 CloseSession(session);
621                         }
622                         else if (ret < 0)
623                         {
624                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
625                                 {
626                                         CloseSession(session);
627                                 }
628                                 else
629                                 {
630                                         errno = EAGAIN;
631                                 }
632                         }
633                         else
634                         {
635                                 session->outbuf = session->outbuf.substr(ret);
636                         }
637                 }
638
639                 MakePollWrite(session);
640
641                 /* Who's smart idea was it to return 1 when we havent written anything?
642                  * This fucks the buffer up in BufferedSocket :p
643                  */
644                 return ret < 1 ? 0 : ret;
645         }
646
647         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
648         virtual void OnWhois(User* source, User* dest)
649         {
650                 if (!clientactive)
651                         return;
652
653                 // Bugfix, only send this numeric for *our* SSL users
654                 if (dest->GetExt("ssl", dummy) || ((IS_LOCAL(dest) && (dest->GetIOHook() == this))))
655                 {
656                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick.c_str(), dest->nick.c_str());
657                 }
658         }
659
660         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
661         {
662                 // check if the linking module wants to know about OUR metadata
663                 if(extname == "ssl")
664                 {
665                         // check if this user has an swhois field to send
666                         if(user->GetExt(extname, dummy))
667                         {
668                                 // call this function in the linking module, let it format the data how it
669                                 // sees fit, and send it on its way. We dont need or want to know how.
670                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
671                         }
672                 }
673         }
674
675         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
676         {
677                 // check if its our metadata key, and its associated with a user
678                 if ((target_type == TYPE_USER) && (extname == "ssl"))
679                 {
680                         User* dest = (User*)target;
681                         // if they dont already have an ssl flag, accept the remote server's
682                         if (!dest->GetExt(extname, dummy))
683                         {
684                                 dest->Extend(extname, "ON");
685                         }
686                 }
687         }
688
689         bool Handshake(issl_session* session)
690         {
691                 int ret = gnutls_handshake(session->sess);
692
693                 if (ret < 0)
694                 {
695                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
696                         {
697                                 // Handshake needs resuming later, read() or write() would have blocked.
698
699                                 if(gnutls_record_get_direction(session->sess) == 0)
700                                 {
701                                         // gnutls_handshake() wants to read() again.
702                                         session->status = ISSL_HANDSHAKING_READ;
703                                 }
704                                 else
705                                 {
706                                         // gnutls_handshake() wants to write() again.
707                                         session->status = ISSL_HANDSHAKING_WRITE;
708                                         MakePollWrite(session);
709                                 }
710                         }
711                         else
712                         {
713                                 // Handshake failed.
714                                 CloseSession(session);
715                                 session->status = ISSL_CLOSING;
716                         }
717
718                         return false;
719                 }
720                 else
721                 {
722                         // Handshake complete.
723                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
724                         User* extendme = ServerInstance->FindDescriptor(session->fd);
725                         if (extendme)
726                         {
727                                 if (!extendme->GetExt("ssl", dummy))
728                                         extendme->Extend("ssl", "ON");
729                         }
730
731                         // Change the seesion state
732                         session->status = ISSL_HANDSHAKEN;
733
734                         // Finish writing, if any left
735                         MakePollWrite(session);
736
737                         return true;
738                 }
739         }
740
741         virtual void OnPostConnect(User* user)
742         {
743                 // This occurs AFTER OnUserConnect so we can be sure the
744                 // protocol module has propagated the NICK message.
745                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
746                 {
747                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
748                         ServerInstance->PI->SendMetaData(user, TYPE_USER, "SSL", "on");
749
750                         VerifyCertificate(&sessions[user->GetFd()],user);
751                         if (sessions[user->GetFd()].sess)
752                         {
753                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
754                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
755                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
756                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
757                         }
758                 }
759         }
760
761         void MakePollWrite(issl_session* session)
762         {
763                 //OnRawSocketWrite(session->fd, NULL, 0);
764                 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
765                 if (eh)
766                         ServerInstance->SE->WantWrite(eh);
767         }
768
769         virtual void OnBufferFlushed(User* user)
770         {
771                 if (user->GetExt("ssl"))
772                 {
773                         issl_session* session = &sessions[user->GetFd()];
774                         if (session && session->outbuf.size())
775                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
776                 }
777         }
778
779         void CloseSession(issl_session* session)
780         {
781                 if(session->sess)
782                 {
783                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
784                         gnutls_deinit(session->sess);
785                 }
786
787                 if(session->inbuf)
788                 {
789                         delete[] session->inbuf;
790                 }
791
792                 session->outbuf.clear();
793                 session->inbuf = NULL;
794                 session->sess = NULL;
795                 session->status = ISSL_NONE;
796         }
797
798         void VerifyCertificate(issl_session* session, Extensible* user)
799         {
800                 if (!session->sess || !user)
801                         return;
802
803                 unsigned int status;
804                 const gnutls_datum_t* cert_list;
805                 int ret;
806                 unsigned int cert_list_size;
807                 gnutls_x509_crt_t cert;
808                 char name[MAXBUF];
809                 unsigned char digest[MAXBUF];
810                 size_t digest_size = sizeof(digest);
811                 size_t name_size = sizeof(name);
812                 ssl_cert* certinfo = new ssl_cert;
813
814                 user->Extend("ssl_cert",certinfo);
815
816                 /* This verification function uses the trusted CAs in the credentials
817                  * structure. So you must have installed one or more CA certificates.
818                  */
819                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
820
821                 if (ret < 0)
822                 {
823                         certinfo->data.insert(std::make_pair("error",std::string(gnutls_strerror(ret))));
824                         return;
825                 }
826
827                 if (status & GNUTLS_CERT_INVALID)
828                 {
829                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(1)));
830                 }
831                 else
832                 {
833                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(0)));
834                 }
835                 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
836                 {
837                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
838                 }
839                 else
840                 {
841                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
842                 }
843                 if (status & GNUTLS_CERT_REVOKED)
844                 {
845                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(1)));
846                 }
847                 else
848                 {
849                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(0)));
850                 }
851                 if (status & GNUTLS_CERT_SIGNER_NOT_CA)
852                 {
853                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
854                 }
855                 else
856                 {
857                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
858                 }
859
860                 /* Up to here the process is the same for X.509 certificates and
861                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
862                  * be easily extended to work with openpgp keys as well.
863                  */
864                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
865                 {
866                         certinfo->data.insert(std::make_pair("error","No X509 keys sent"));
867                         return;
868                 }
869
870                 ret = gnutls_x509_crt_init(&cert);
871                 if (ret < 0)
872                 {
873                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
874                         return;
875                 }
876
877                 cert_list_size = 0;
878                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
879                 if (cert_list == NULL)
880                 {
881                         certinfo->data.insert(std::make_pair("error","No certificate was found"));
882                         return;
883                 }
884
885                 /* This is not a real world example, since we only check the first
886                  * certificate in the given chain.
887                  */
888
889                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
890                 if (ret < 0)
891                 {
892                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
893                         return;
894                 }
895
896                 gnutls_x509_crt_get_dn(cert, name, &name_size);
897
898                 certinfo->data.insert(std::make_pair("dn",name));
899
900                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
901
902                 certinfo->data.insert(std::make_pair("issuer",name));
903
904                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
905                 {
906                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
907                 }
908                 else
909                 {
910                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(digest, digest_size)));
911                 }
912
913                 /* Beware here we do not check for errors.
914                  */
915                 if ((gnutls_x509_crt_get_expiration_time(cert) < time(0)) || (gnutls_x509_crt_get_activation_time(cert) > time(0)))
916                 {
917                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
918                 }
919
920                 gnutls_x509_crt_deinit(cert);
921
922                 return;
923         }
924
925         void OnEvent(Event* ev)
926         {
927                 GenericCapHandler(ev, "tls", "tls");
928         }
929
930         void Prioritize()
931         {
932                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
933                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIO_AFTER, &server);
934         }
935 };
936
937 MODULE_INIT(ModuleSSLGnuTLS)