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