]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Fix two compile errors found by Shawn
[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(&bin, addr, portint);
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->SE->GetRef(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                                 errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
494                                 // Couldn't resume handshake.
495                                 return -1;
496                         }
497                 }
498                 else if (session->status == ISSL_HANDSHAKING_WRITE)
499                 {
500                         errno = EAGAIN;
501                         MakePollWrite(fd);
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                         int ret = gnutls_record_recv(session->sess, buffer, count);
510
511                         if (ret > 0)
512                         {
513                                 readresult = ret;
514                         }
515                         else if (ret == 0)
516                         {
517                                 // Client closed connection.
518                                 readresult = 0;
519                                 CloseSession(session);
520                                 return 1;
521                         }
522                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
523                         {
524                                 errno = EAGAIN;
525                                 return -1;
526                         }
527                         else
528                         {
529                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
530                                                 "m_ssl_gnutls.so: Error while reading on fd %d: %s",
531                                                 fd, gnutls_strerror(ret));
532                                 readresult = 0;
533                                 CloseSession(session);
534                         }
535                 }
536                 else if(session->status == ISSL_CLOSING)
537                         readresult = 0;
538
539                 return 1;
540         }
541
542         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
543         {
544                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
545                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
546                         return 0;
547
548                 issl_session* session = &sessions[fd];
549                 const char* sendbuffer = buffer;
550
551                 if (!session->sess)
552                 {
553                         CloseSession(session);
554                         return 1;
555                 }
556
557                 session->outbuf.append(sendbuffer, count);
558                 sendbuffer = session->outbuf.c_str();
559                 count = session->outbuf.size();
560
561                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
562                 {
563                         // The handshake isn't finished, try to finish it.
564                         Handshake(session, fd);
565                         errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
566                         return -1;
567                 }
568
569                 int ret = 0;
570
571                 if (session->status == ISSL_HANDSHAKEN)
572                 {
573                         ret = gnutls_record_send(session->sess, sendbuffer, count);
574
575                         if (ret == 0)
576                         {
577                                 CloseSession(session);
578                         }
579                         else if (ret < 0)
580                         {
581                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
582                                 {
583                                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
584                                                         "m_ssl_gnutls.so: Error while writing to fd %d: %s",
585                                                         fd, gnutls_strerror(ret));
586                                         CloseSession(session);
587                                 }
588                                 else
589                                 {
590                                         errno = EAGAIN;
591                                 }
592                         }
593                         else
594                         {
595                                 session->outbuf = session->outbuf.substr(ret);
596                         }
597                 }
598
599                 MakePollWrite(fd);
600
601                 /* Who's smart idea was it to return 1 when we havent written anything?
602                  * This fucks the buffer up in BufferedSocket :p
603                  */
604                 return ret < 1 ? 0 : ret;
605         }
606
607         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
608         virtual void OnWhois(User* source, User* dest)
609         {
610                 if (!clientactive)
611                         return;
612
613                 // Bugfix, only send this numeric for *our* SSL users
614                 if (dest->GetExt("ssl", dummy))
615                 {
616                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick.c_str(), dest->nick.c_str());
617                 }
618         }
619
620         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
621         {
622                 // check if the linking module wants to know about OUR metadata
623                 if(extname == "ssl")
624                 {
625                         // check if this user has an swhois field to send
626                         if(user->GetExt(extname, dummy))
627                         {
628                                 // call this function in the linking module, let it format the data how it
629                                 // sees fit, and send it on its way. We dont need or want to know how.
630                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
631                         }
632                 }
633         }
634
635         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
636         {
637                 // check if its our metadata key, and its associated with a user
638                 if ((target_type == TYPE_USER) && (extname == "ssl"))
639                 {
640                         User* dest = (User*)target;
641                         // if they dont already have an ssl flag, accept the remote server's
642                         if (!dest->GetExt(extname, dummy))
643                         {
644                                 dest->Extend(extname, "ON");
645                         }
646                 }
647         }
648
649         bool Handshake(issl_session* session, int fd)
650         {
651                 int ret = gnutls_handshake(session->sess);
652
653                 if (ret < 0)
654                 {
655                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
656                         {
657                                 // Handshake needs resuming later, read() or write() would have blocked.
658
659                                 if(gnutls_record_get_direction(session->sess) == 0)
660                                 {
661                                         // gnutls_handshake() wants to read() again.
662                                         session->status = ISSL_HANDSHAKING_READ;
663                                 }
664                                 else
665                                 {
666                                         // gnutls_handshake() wants to write() again.
667                                         session->status = ISSL_HANDSHAKING_WRITE;
668                                         MakePollWrite(fd);
669                                 }
670                         }
671                         else
672                         {
673                                 // Handshake failed.
674                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
675                                                 "m_ssl_gnutls.so: Handshake failed on fd %d: %s",
676                                                 fd, gnutls_strerror(ret));
677                                 CloseSession(session);
678                                 session->status = ISSL_CLOSING;
679                         }
680
681                         return false;
682                 }
683                 else
684                 {
685                         // Handshake complete.
686                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
687                         EventHandler *extendme = ServerInstance->SE->GetRef(fd);
688                         if (extendme)
689                         {
690                                 if (!extendme->GetExt("ssl", dummy))
691                                         extendme->Extend("ssl", "ON");
692                         }
693
694                         // Change the seesion state
695                         session->status = ISSL_HANDSHAKEN;
696
697                         // Finish writing, if any left
698                         MakePollWrite(fd);
699
700                         return true;
701                 }
702         }
703
704         virtual void OnPostConnect(User* user)
705         {
706                 // This occurs AFTER OnUserConnect so we can be sure the
707                 // protocol module has propagated the NICK message.
708                 if (user->GetIOHook() == this && (IS_LOCAL(user)))
709                 {
710                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
711                         ServerInstance->PI->SendMetaData(user, TYPE_USER, "ssl", "on");
712
713                         VerifyCertificate(&sessions[user->GetFd()],user);
714                         if (sessions[user->GetFd()].sess)
715                         {
716                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
717                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
718                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
719                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
720                         }
721                 }
722         }
723
724         void MakePollWrite(int fd)
725         {
726                 //OnRawSocketWrite(fd, NULL, 0);
727                 EventHandler* eh = ServerInstance->SE->GetRef(fd);
728                 if (eh)
729                         ServerInstance->SE->WantWrite(eh);
730         }
731
732         virtual void OnBufferFlushed(User* user)
733         {
734                 if (user->GetIOHook() == this)
735                 {
736                         issl_session* session = &sessions[user->GetFd()];
737                         if (session && session->outbuf.size())
738                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
739                 }
740         }
741
742         void CloseSession(issl_session* session)
743         {
744                 if(session->sess)
745                 {
746                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
747                         gnutls_deinit(session->sess);
748                 }
749
750                 session->outbuf.clear();
751                 session->sess = NULL;
752                 session->status = ISSL_NONE;
753         }
754
755         void VerifyCertificate(issl_session* session, Extensible* user)
756         {
757                 if (!session->sess || !user)
758                         return;
759
760                 unsigned int status;
761                 const gnutls_datum_t* cert_list;
762                 int ret;
763                 unsigned int cert_list_size;
764                 gnutls_x509_crt_t cert;
765                 char name[MAXBUF];
766                 unsigned char digest[MAXBUF];
767                 size_t digest_size = sizeof(digest);
768                 size_t name_size = sizeof(name);
769                 ssl_cert* certinfo = new ssl_cert;
770
771                 user->Extend("ssl_cert",certinfo);
772
773                 /* This verification function uses the trusted CAs in the credentials
774                  * structure. So you must have installed one or more CA certificates.
775                  */
776                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
777
778                 if (ret < 0)
779                 {
780                         certinfo->data.insert(std::make_pair("error",std::string(gnutls_strerror(ret))));
781                         return;
782                 }
783
784                 if (status & GNUTLS_CERT_INVALID)
785                 {
786                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(1)));
787                 }
788                 else
789                 {
790                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(0)));
791                 }
792                 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
793                 {
794                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
795                 }
796                 else
797                 {
798                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
799                 }
800                 if (status & GNUTLS_CERT_REVOKED)
801                 {
802                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(1)));
803                 }
804                 else
805                 {
806                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(0)));
807                 }
808                 if (status & GNUTLS_CERT_SIGNER_NOT_CA)
809                 {
810                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
811                 }
812                 else
813                 {
814                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
815                 }
816
817                 /* Up to here the process is the same for X.509 certificates and
818                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
819                  * be easily extended to work with openpgp keys as well.
820                  */
821                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
822                 {
823                         certinfo->data.insert(std::make_pair("error","No X509 keys sent"));
824                         return;
825                 }
826
827                 ret = gnutls_x509_crt_init(&cert);
828                 if (ret < 0)
829                 {
830                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
831                         return;
832                 }
833
834                 cert_list_size = 0;
835                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
836                 if (cert_list == NULL)
837                 {
838                         certinfo->data.insert(std::make_pair("error","No certificate was found"));
839                         return;
840                 }
841
842                 /* This is not a real world example, since we only check the first
843                  * certificate in the given chain.
844                  */
845
846                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
847                 if (ret < 0)
848                 {
849                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
850                         return;
851                 }
852
853                 gnutls_x509_crt_get_dn(cert, name, &name_size);
854
855                 certinfo->data.insert(std::make_pair("dn",name));
856
857                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
858
859                 certinfo->data.insert(std::make_pair("issuer",name));
860
861                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
862                 {
863                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
864                 }
865                 else
866                 {
867                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(digest, digest_size)));
868                 }
869
870                 /* Beware here we do not check for errors.
871                  */
872                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
873                 {
874                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
875                 }
876
877                 gnutls_x509_crt_deinit(cert);
878
879                 return;
880         }
881
882         void OnEvent(Event* ev)
883         {
884                 GenericCapHandler(ev, "tls", "tls");
885         }
886
887         void Prioritize()
888         {
889                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
890                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
891         }
892 };
893
894 MODULE_INIT(ModuleSSLGnuTLS)