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