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