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