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