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