]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Allow activation of TLS via STARTTLS even if CAP REQ tls isnt given, so that CAP...
[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 #undef MAX_DESCRIPTORS
32 #define MAX_DESCRIPTORS 10000
33 #endif
34
35 /* $ModDesc: Provides SSL support for clients */
36 /* $CompileFlags: exec("libgnutls-config --cflags") */
37 /* $LinkerFlags: rpath("libgnutls-config --libs") exec("libgnutls-config --libs") */
38 /* $ModDep: transport.h */
39 /* $CopyInstall: conf/key.pem $(CONPATH) */
40 /* $CopyInstall: conf/cert.pem $(CONPATH) */
41
42 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
43
44 bool isin(const std::string &host, int port, const std::vector<std::string> &portlist)
45 {
46         if (std::find(portlist.begin(), portlist.end(), "*:" + ConvToStr(port)) != portlist.end())
47                 return true;
48
49         if (std::find(portlist.begin(), portlist.end(), ":" + ConvToStr(port)) != portlist.end())
50                 return true;
51
52         return std::find(portlist.begin(), portlist.end(), host + ":" + ConvToStr(port)) != portlist.end();
53 }
54
55 /** Represents an SSL user's extra data
56  */
57 class issl_session : public classbase
58 {
59 public:
60         gnutls_session_t sess;
61         issl_status status;
62         std::string outbuf;
63         int inbufoffset;
64         char* inbuf;
65         int fd;
66 };
67
68 class CommandStartTLS : public Command
69 {
70         Module* Caller;
71  public:
72         /* Command 'dalinfo', takes no parameters and needs no special modes */
73         CommandStartTLS (InspIRCd* Instance, Module* mod) : Command(Instance,"STARTTLS", 0, 0, true), Caller(mod)
74         {
75                 this->source = "m_ssl_gnutls.so";
76         }
77
78         CmdResult Handle (const char* const* parameters, int pcnt, User *user)
79         {
80                 user->io = Caller;
81                 Caller->OnRawSocketAccept(user->GetFd(), user->GetIPString(), user->GetPort());
82
83                 return CMD_FAILURE;
84         }
85 };
86
87 class ModuleSSLGnuTLS : public Module
88 {
89
90         ConfigReader* Conf;
91
92         char* dummy;
93
94         std::vector<std::string> listenports;
95
96         int inbufsize;
97         issl_session sessions[MAX_DESCRIPTORS];
98
99         gnutls_certificate_credentials x509_cred;
100         gnutls_dh_params dh_params;
101
102         std::string keyfile;
103         std::string certfile;
104         std::string cafile;
105         std::string crlfile;
106         std::string sslports;
107         int dh_bits;
108
109         int clientactive;
110
111         CommandStartTLS* starttls;
112
113  public:
114
115         ModuleSSLGnuTLS(InspIRCd* Me)
116                 : Module(Me)
117         {
118                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
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 %d", 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 %d: %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] != '/')
224                         cafile = confdir + cafile;
225
226                 if(crlfile[0] != '/')
227                         crlfile = confdir + crlfile;
228
229                 if(certfile[0] != '/')
230                         certfile = confdir + certfile;
231
232                 if(keyfile[0] != '/')
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         }
274
275         virtual void OnCleanup(int target_type, void* item)
276         {
277                 if(target_type == TYPE_USER)
278                 {
279                         User* user = (User*)item;
280
281                         if(user->io)
282                         {
283                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
284                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
285                                 User::QuitUser(ServerInstance, user, "SSL module unloading");
286                         }
287                         if (user->GetExt("ssl_cert", dummy))
288                         {
289                                 ssl_cert* tofree;
290                                 user->GetExt("ssl_cert", tofree);
291                                 delete tofree;
292                                 user->Shrink("ssl_cert");
293                         }
294
295                         user->io = NULL;
296                 }
297         }
298
299         virtual void OnUnloadModule(Module* mod, const std::string &name)
300         {
301                 if(mod == this)
302                 {
303                         for(unsigned int i = 0; i < listenports.size(); i++)
304                         {
305                                 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
306                                         if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
307                                                 ServerInstance->Config->ports[j]->SetDescription("plaintext");
308                         }
309                 }
310         }
311
312         virtual Version GetVersion()
313         {
314                 return Version(1, 2, 0, 0, VF_VENDOR, API_VERSION);
315         }
316
317
318         virtual void On005Numeric(std::string &output)
319         {
320                 output.append(" SSL=" + sslports);
321         }
322
323         virtual void OnHookUserIO(User* user, const std::string &targetip)
324         {
325                 if (!user->io && isin(targetip,user->GetPort(),listenports))
326                 {
327                         /* Hook the user with our module */
328                         user->io = this;
329                 }
330         }
331
332         virtual const char* OnRequest(Request* request)
333         {
334                 ISHRequest* ISR = (ISHRequest*)request;
335                 if (strcmp("IS_NAME", request->GetId()) == 0)
336                 {
337                         return "gnutls";
338                 }
339                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
340                 {
341                         const char* ret = "OK";
342                         try
343                         {
344                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? "OK" : NULL;
345                         }
346                         catch (ModuleException &e)
347                         {
348                                 return NULL;
349                         }
350                         return ret;
351                 }
352                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
353                 {
354                         return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? "OK" : NULL;
355                 }
356                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
357                 {
358                         if (ISR->Sock->GetFd() < 0)
359                                 return "OK";
360
361                         issl_session* session = &sessions[ISR->Sock->GetFd()];
362                         return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : "OK";
363                 }
364                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
365                 {
366                         if (ISR->Sock->GetFd() > -1)
367                         {
368                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
369                                 if (session->sess)
370                                 {
371                                         if ((Extensible*)ServerInstance->FindDescriptor(ISR->Sock->GetFd()) == (Extensible*)(ISR->Sock))
372                                         {
373                                                 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
374                                                 return "OK";
375                                         }
376                                 }
377                         }
378                 }
379                 return NULL;
380         }
381
382
383         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
384         {
385                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
386                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
387                         return;
388
389                 issl_session* session = &sessions[fd];
390
391                 session->fd = fd;
392                 session->inbuf = new char[inbufsize];
393                 session->inbufoffset = 0;
394
395                 gnutls_init(&session->sess, GNUTLS_SERVER);
396
397                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
398                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
399                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
400
401                 /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes
402                  * This needs testing, but it's easy enough to rollback if need be
403                  * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
404                  * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket.
405                  *
406                  * With testing this seems to...not work :/
407                  */
408
409                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
410
411                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
412
413                 Handshake(session);
414         }
415
416         virtual void OnRawSocketConnect(int fd)
417         {
418                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
419                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
420                         return;
421
422                 issl_session* session = &sessions[fd];
423
424                 session->fd = fd;
425                 session->inbuf = new char[inbufsize];
426                 session->inbufoffset = 0;
427
428                 gnutls_init(&session->sess, GNUTLS_CLIENT);
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                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
434
435                 Handshake(session);
436         }
437
438         virtual void OnRawSocketClose(int fd)
439         {
440                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
441                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
442                         return;
443
444                 CloseSession(&sessions[fd]);
445
446                 EventHandler* user = ServerInstance->SE->GetRef(fd);
447
448                 if ((user) && (user->GetExt("ssl_cert", dummy)))
449                 {
450                         ssl_cert* tofree;
451                         user->GetExt("ssl_cert", tofree);
452                         delete tofree;
453                         user->Shrink("ssl_cert");
454                 }
455         }
456
457         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
458         {
459                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
460                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
461                         return 0;
462
463                 issl_session* session = &sessions[fd];
464
465                 if (!session->sess)
466                 {
467                         readresult = 0;
468                         CloseSession(session);
469                         return 1;
470                 }
471
472                 if (session->status == ISSL_HANDSHAKING_READ)
473                 {
474                         // The handshake isn't finished, try to finish it.
475
476                         if(!Handshake(session))
477                         {
478                                 // Couldn't resume handshake.
479                                 return -1;
480                         }
481                 }
482                 else if (session->status == ISSL_HANDSHAKING_WRITE)
483                 {
484                         errno = EAGAIN;
485                         MakePollWrite(session);
486                         return -1;
487                 }
488
489                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
490
491                 if (session->status == ISSL_HANDSHAKEN)
492                 {
493                         // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
494                         // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
495                         int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
496
497                         if (ret == 0)
498                         {
499                                 // Client closed connection.
500                                 readresult = 0;
501                                 CloseSession(session);
502                                 return 1;
503                         }
504                         else if (ret < 0)
505                         {
506                                 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
507                                 {
508                                         errno = EAGAIN;
509                                         return -1;
510                                 }
511                                 else
512                                 {
513                                         readresult = 0;
514                                         CloseSession(session);
515                                 }
516                         }
517                         else
518                         {
519                                 // Read successfully 'ret' bytes into inbuf + inbufoffset
520                                 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
521                                 // 'buffer' is 'count' long
522
523                                 unsigned int length = ret + session->inbufoffset;
524
525                                 if(count <= length)
526                                 {
527                                         memcpy(buffer, session->inbuf, count);
528                                         // Move the stuff left in inbuf to the beginning of it
529                                         memcpy(session->inbuf, session->inbuf + count, (length - count));
530                                         // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
531                                         session->inbufoffset = length - count;
532                                         // Insp uses readresult as the count of how much data there is in buffer, so:
533                                         readresult = count;
534                                 }
535                                 else
536                                 {
537                                         // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
538                                         memcpy(buffer, session->inbuf, length);
539                                         // Zero the offset, as there's nothing there..
540                                         session->inbufoffset = 0;
541                                         // As above
542                                         readresult = length;
543                                 }
544                         }
545                 }
546                 else if(session->status == ISSL_CLOSING)
547                         readresult = 0;
548
549                 return 1;
550         }
551
552         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
553         {
554                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
555                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
556                         return 0;
557
558                 issl_session* session = &sessions[fd];
559                 const char* sendbuffer = buffer;
560
561                 if (!session->sess)
562                 {
563                         CloseSession(session);
564                         return 1;
565                 }
566
567                 session->outbuf.append(sendbuffer, count);
568                 sendbuffer = session->outbuf.c_str();
569                 count = session->outbuf.size();
570
571                 if (session->status == ISSL_HANDSHAKING_WRITE)
572                 {
573                         // The handshake isn't finished, try to finish it.
574                         Handshake(session);
575                         errno = EAGAIN;
576                         return -1;
577                 }
578
579                 int ret = 0;
580
581                 if (session->status == ISSL_HANDSHAKEN)
582                 {
583                         ret = gnutls_record_send(session->sess, sendbuffer, count);
584
585                         if (ret == 0)
586                         {
587                                 CloseSession(session);
588                         }
589                         else if (ret < 0)
590                         {
591                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
592                                 {
593                                         CloseSession(session);
594                                 }
595                                 else
596                                 {
597                                         errno = EAGAIN;
598                                 }
599                         }
600                         else
601                         {
602                                 session->outbuf = session->outbuf.substr(ret);
603                         }
604                 }
605
606                 MakePollWrite(session);
607
608                 /* Who's smart idea was it to return 1 when we havent written anything?
609                  * This fucks the buffer up in BufferedSocket :p
610                  */
611                 return ret < 1 ? 0 : ret;
612         }
613
614         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
615         virtual void OnWhois(User* source, User* dest)
616         {
617                 if (!clientactive)
618                         return;
619
620                 // Bugfix, only send this numeric for *our* SSL users
621                 if (dest->GetExt("ssl", dummy) || ((IS_LOCAL(dest) && (dest->io == this))))
622                 {
623                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
624                 }
625         }
626
627         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
628         {
629                 // check if the linking module wants to know about OUR metadata
630                 if(extname == "ssl")
631                 {
632                         // check if this user has an swhois field to send
633                         if(user->GetExt(extname, dummy))
634                         {
635                                 // call this function in the linking module, let it format the data how it
636                                 // sees fit, and send it on its way. We dont need or want to know how.
637                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
638                         }
639                 }
640         }
641
642         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
643         {
644                 // check if its our metadata key, and its associated with a user
645                 if ((target_type == TYPE_USER) && (extname == "ssl"))
646                 {
647                         User* dest = (User*)target;
648                         // if they dont already have an ssl flag, accept the remote server's
649                         if (!dest->GetExt(extname, dummy))
650                         {
651                                 dest->Extend(extname, "ON");
652                         }
653                 }
654         }
655
656         bool Handshake(issl_session* session)
657         {
658                 int ret = gnutls_handshake(session->sess);
659
660                 if (ret < 0)
661                 {
662                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
663                         {
664                                 // Handshake needs resuming later, read() or write() would have blocked.
665
666                                 if(gnutls_record_get_direction(session->sess) == 0)
667                                 {
668                                         // gnutls_handshake() wants to read() again.
669                                         session->status = ISSL_HANDSHAKING_READ;
670                                 }
671                                 else
672                                 {
673                                         // gnutls_handshake() wants to write() again.
674                                         session->status = ISSL_HANDSHAKING_WRITE;
675                                         MakePollWrite(session);
676                                 }
677                         }
678                         else
679                         {
680                                 // Handshake failed.
681                                 CloseSession(session);
682                                 session->status = ISSL_CLOSING;
683                         }
684
685                         return false;
686                 }
687                 else
688                 {
689                         // Handshake complete.
690                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
691                         User* extendme = ServerInstance->FindDescriptor(session->fd);
692                         if (extendme)
693                         {
694                                 if (!extendme->GetExt("ssl", dummy))
695                                         extendme->Extend("ssl", "ON");
696                         }
697
698                         // Change the seesion state
699                         session->status = ISSL_HANDSHAKEN;
700
701                         // Finish writing, if any left
702                         MakePollWrite(session);
703
704                         return true;
705                 }
706         }
707
708         virtual void OnPostConnect(User* user)
709         {
710                 // This occurs AFTER OnUserConnect so we can be sure the
711                 // protocol module has propagated the NICK message.
712                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
713                 {
714                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
715                         std::deque<std::string>* metadata = new std::deque<std::string>;
716                         metadata->push_back(user->nick);
717                         metadata->push_back("ssl");             // The metadata id
718                         metadata->push_back("ON");              // The value to send
719                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
720                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
721                         delete event;
722                         delete metadata;
723
724                         VerifyCertificate(&sessions[user->GetFd()],user);
725                         if (sessions[user->GetFd()].sess)
726                         {
727                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
728                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
729                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
730                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, cipher.c_str());
731                         }
732                 }
733         }
734
735         void MakePollWrite(issl_session* session)
736         {
737                 //OnRawSocketWrite(session->fd, NULL, 0);
738                 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
739                 if (eh)
740                         ServerInstance->SE->WantWrite(eh);
741         }
742
743         virtual void OnBufferFlushed(User* user)
744         {
745                 if (user->GetExt("ssl"))
746                 {
747                         issl_session* session = &sessions[user->GetFd()];
748                         if (session && session->outbuf.size())
749                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
750                 }
751         }
752
753         void CloseSession(issl_session* session)
754         {
755                 if(session->sess)
756                 {
757                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
758                         gnutls_deinit(session->sess);
759                 }
760
761                 if(session->inbuf)
762                 {
763                         delete[] session->inbuf;
764                 }
765
766                 session->outbuf.clear();
767                 session->inbuf = NULL;
768                 session->sess = NULL;
769                 session->status = ISSL_NONE;
770         }
771
772         void VerifyCertificate(issl_session* session, Extensible* user)
773         {
774                 if (!session->sess || !user)
775                         return;
776
777                 unsigned int status;
778                 const gnutls_datum_t* cert_list;
779                 int ret;
780                 unsigned int cert_list_size;
781                 gnutls_x509_crt_t cert;
782                 char name[MAXBUF];
783                 unsigned char digest[MAXBUF];
784                 size_t digest_size = sizeof(digest);
785                 size_t name_size = sizeof(name);
786                 ssl_cert* certinfo = new ssl_cert;
787
788                 user->Extend("ssl_cert",certinfo);
789
790                 /* This verification function uses the trusted CAs in the credentials
791                  * structure. So you must have installed one or more CA certificates.
792                  */
793                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
794
795                 if (ret < 0)
796                 {
797                         certinfo->data.insert(std::make_pair("error",std::string(gnutls_strerror(ret))));
798                         return;
799                 }
800
801                 if (status & GNUTLS_CERT_INVALID)
802                 {
803                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(1)));
804                 }
805                 else
806                 {
807                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(0)));
808                 }
809                 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
810                 {
811                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
812                 }
813                 else
814                 {
815                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
816                 }
817                 if (status & GNUTLS_CERT_REVOKED)
818                 {
819                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(1)));
820                 }
821                 else
822                 {
823                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(0)));
824                 }
825                 if (status & GNUTLS_CERT_SIGNER_NOT_CA)
826                 {
827                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
828                 }
829                 else
830                 {
831                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
832                 }
833
834                 /* Up to here the process is the same for X.509 certificates and
835                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
836                  * be easily extended to work with openpgp keys as well.
837                  */
838                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
839                 {
840                         certinfo->data.insert(std::make_pair("error","No X509 keys sent"));
841                         return;
842                 }
843
844                 ret = gnutls_x509_crt_init(&cert);
845                 if (ret < 0)
846                 {
847                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
848                         return;
849                 }
850
851                 cert_list_size = 0;
852                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
853                 if (cert_list == NULL)
854                 {
855                         certinfo->data.insert(std::make_pair("error","No certificate was found"));
856                         return;
857                 }
858
859                 /* This is not a real world example, since we only check the first
860                  * certificate in the given chain.
861                  */
862
863                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
864                 if (ret < 0)
865                 {
866                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
867                         return;
868                 }
869
870                 gnutls_x509_crt_get_dn(cert, name, &name_size);
871
872                 certinfo->data.insert(std::make_pair("dn",name));
873
874                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
875
876                 certinfo->data.insert(std::make_pair("issuer",name));
877
878                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
879                 {
880                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
881                 }
882                 else
883                 {
884                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(digest, digest_size)));
885                 }
886
887                 /* Beware here we do not check for errors.
888                  */
889                 if ((gnutls_x509_crt_get_expiration_time(cert) < time(0)) || (gnutls_x509_crt_get_activation_time(cert) > time(0)))
890                 {
891                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
892                 }
893
894                 gnutls_x509_crt_deinit(cert);
895
896                 return;
897         }
898
899         void OnEvent(Event* ev)
900         {
901                 GenericCapHandler(ev, "tls", "tls");
902         }
903
904 };
905
906 MODULE_INIT(ModuleSSLGnuTLS)