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