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