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