]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
c9dd6d37e0f72a190c5178851e3d71f3b2bedd00
[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: pkgconfincludes("gnutls","/gnutls/gnutls.h","") */
26 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") */
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         std::vector<std::string> listenports;
97
98         issl_session* sessions;
99
100         gnutls_certificate_credentials x509_cred;
101         gnutls_dh_params dh_params;
102
103         std::string keyfile;
104         std::string certfile;
105         std::string cafile;
106         std::string crlfile;
107         std::string sslports;
108         int dh_bits;
109
110         int clientactive;
111         bool cred_alloc;
112
113         CommandStartTLS* starttls;
114
115  public:
116
117         ModuleSSLGnuTLS(InspIRCd* Me)
118                 : Module(Me)
119         {
120                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
121
122                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
123
124                 gnutls_global_init(); // This must be called once in the program
125
126                 cred_alloc = false;
127                 // Needs the flag as it ignores a plain /rehash
128                 OnModuleRehash(NULL,"ssl");
129
130                 // Void return, guess we assume success
131                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
132                 Implementation eventlist[] = { I_On005Numeric, I_OnRawSocketConnect, I_OnRawSocketAccept,
133                         I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup,
134                         I_OnBufferFlushed, I_OnRequest, I_OnUnloadModule, I_OnRehash, I_OnModuleRehash,
135                         I_OnPostConnect, I_OnEvent, I_OnHookUserIO };
136                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
137
138                 starttls = new CommandStartTLS(ServerInstance, this);
139                 ServerInstance->AddCommand(starttls);
140         }
141
142         virtual void OnRehash(User* user)
143         {
144                 ConfigReader Conf(ServerInstance);
145
146                 listenports.clear();
147                 clientactive = 0;
148                 sslports.clear();
149
150                 for(int index = 0; index < Conf.Enumerate("bind"); index++)
151                 {
152                         // For each <bind> tag
153                         std::string x = Conf.ReadValue("bind", "type", index);
154                         if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "gnutls"))
155                         {
156                                 // Get the port we're meant to be listening on with SSL
157                                 std::string port = Conf.ReadValue("bind", "port", index);
158                                 std::string addr = Conf.ReadValue("bind", "address", index);
159
160                                 if (!addr.empty())
161                                 {
162                                         // normalize address, important for IPv6
163                                         int portint = 0;
164                                         irc::sockets::sockaddrs bin;
165                                         if (irc::sockets::aptosa(addr.c_str(), portint, &bin))
166                                                 irc::sockets::satoap(&bin, addr, portint);
167                                 }
168
169                                 irc::portparser portrange(port, false);
170                                 long portno = -1;
171                                 while ((portno = portrange.GetToken()))
172                                 {
173                                         clientactive++;
174                                         try
175                                         {
176                                                 listenports.push_back(addr + ":" + ConvToStr(portno));
177
178                                                 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
179                                                         if ((ServerInstance->ports[i]->GetPort() == portno) && (ServerInstance->ports[i]->GetIP() == addr))
180                                                                 ServerInstance->ports[i]->SetDescription("ssl");
181                                                 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %ld", portno);
182
183                                                 if (addr != "127.0.0.1")
184                                                         sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
185                                         }
186                                         catch (ModuleException &e)
187                                         {
188                                                 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());
189                                         }
190                                 }
191                         }
192                 }
193
194                 if (!sslports.empty())
195                         sslports.erase(sslports.end() - 1);
196         }
197
198         virtual void OnModuleRehash(User* user, const std::string &param)
199         {
200                 if(param != "ssl")
201                         return;
202
203                 OnRehash(user);
204
205                 ConfigReader Conf(ServerInstance);
206
207                 std::string confdir(ServerInstance->ConfigFileName);
208                 // +1 so we the path ends with a /
209                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
210
211                 cafile = Conf.ReadValue("gnutls", "cafile", 0);
212                 crlfile = Conf.ReadValue("gnutls", "crlfile", 0);
213                 certfile = Conf.ReadValue("gnutls", "certfile", 0);
214                 keyfile = Conf.ReadValue("gnutls", "keyfile", 0);
215                 dh_bits = Conf.ReadInteger("gnutls", "dhbits", 0, false);
216
217                 // Set all the default values needed.
218                 if (cafile.empty())
219                         cafile = "ca.pem";
220
221                 if (crlfile.empty())
222                         crlfile = "crl.pem";
223
224                 if (certfile.empty())
225                         certfile = "cert.pem";
226
227                 if (keyfile.empty())
228                         keyfile = "key.pem";
229
230                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
231                         dh_bits = 1024;
232
233                 // Prepend relative paths with the path to the config directory.
234                 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
235                         cafile = confdir + cafile;
236
237                 if ((crlfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(crlfile)))
238                         crlfile = confdir + crlfile;
239
240                 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
241                         certfile = confdir + certfile;
242
243                 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
244                         keyfile = confdir + keyfile;
245
246                 int ret;
247
248                 if (cred_alloc)
249                 {
250                         // Deallocate the old credentials
251                         gnutls_dh_params_deinit(dh_params);
252                         gnutls_certificate_free_credentials(x509_cred);
253                 }
254                 else
255                         cred_alloc = true;
256
257                 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
258                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
259
260                 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
261                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
262
263                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
264                         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));
265
266                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
267                         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));
268
269                 if((ret = gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
270                 {
271                         // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
272                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + ", key: " + keyfile + "): " + std::string(gnutls_strerror(ret)));
273                 }
274
275                 // This may be on a large (once a day or week) timer eventually.
276                 GenerateDHParams();
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"))
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->ports.size(); j++)
331                                         if (listenports[i] == (ServerInstance->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->ports[j]->GetPort())))
332                                                 ServerInstance->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                 else if (strcmp("GET_FP", request->GetId()) == 0)
407                 {
408                         if (ISR->Sock->GetFd() > -1)
409                         {
410                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
411                                 if (session->sess)
412                                 {
413                                         Extensible* ext = ISR->Sock;
414                                         ssl_cert* certinfo;
415                                         if (ext->GetExt("ssl_cert",certinfo))
416                                                 return certinfo->GetFingerprint().c_str();
417                                 }
418                         }
419                 }
420                 return NULL;
421         }
422
423
424         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
425         {
426                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
427                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
428                         return;
429
430                 issl_session* session = &sessions[fd];
431
432                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
433                 if (session->sess)
434                         return;
435
436                 gnutls_init(&session->sess, GNUTLS_SERVER);
437
438                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
439                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
440                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
441
442                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
443
444                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
445
446                 Handshake(session, fd);
447         }
448
449         virtual void OnRawSocketConnect(int fd)
450         {
451                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
452                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
453                         return;
454
455                 issl_session* session = &sessions[fd];
456
457                 gnutls_init(&session->sess, GNUTLS_CLIENT);
458
459                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
460                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
461                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
462                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
463
464                 Handshake(session, fd);
465         }
466
467         virtual void OnRawSocketClose(int fd)
468         {
469                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
470                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds()))
471                         return;
472
473                 CloseSession(&sessions[fd]);
474
475                 EventHandler* user = ServerInstance->SE->GetRef(fd);
476
477                 if ((user) && (user->GetExt("ssl_cert")))
478                 {
479                         ssl_cert* tofree;
480                         user->GetExt("ssl_cert", tofree);
481                         delete tofree;
482                         user->Shrink("ssl_cert");
483                 }
484         }
485
486         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
487         {
488                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
489                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
490                         return 0;
491
492                 issl_session* session = &sessions[fd];
493
494                 if (!session->sess)
495                 {
496                         readresult = 0;
497                         CloseSession(session);
498                         return 1;
499                 }
500
501                 if (session->status == ISSL_HANDSHAKING_READ)
502                 {
503                         // The handshake isn't finished, try to finish it.
504
505                         if(!Handshake(session, fd))
506                         {
507                                 errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
508                                 // Couldn't resume handshake.
509                                 return -1;
510                         }
511                 }
512                 else if (session->status == ISSL_HANDSHAKING_WRITE)
513                 {
514                         errno = EAGAIN;
515                         MakePollWrite(fd);
516                         return -1;
517                 }
518
519                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
520
521                 if (session->status == ISSL_HANDSHAKEN)
522                 {
523                         int ret = gnutls_record_recv(session->sess, buffer, count);
524
525                         if (ret > 0)
526                         {
527                                 readresult = ret;
528                         }
529                         else if (ret == 0)
530                         {
531                                 // Client closed connection.
532                                 readresult = 0;
533                                 CloseSession(session);
534                                 return 1;
535                         }
536                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
537                         {
538                                 errno = EAGAIN;
539                                 return -1;
540                         }
541                         else
542                         {
543                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
544                                                 "m_ssl_gnutls.so: Error while reading on fd %d: %s",
545                                                 fd, gnutls_strerror(ret));
546                                 readresult = 0;
547                                 CloseSession(session);
548                         }
549                 }
550                 else if(session->status == ISSL_CLOSING)
551                         readresult = 0;
552
553                 return 1;
554         }
555
556         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
557         {
558                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
559                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
560                         return 0;
561
562                 issl_session* session = &sessions[fd];
563                 const char* sendbuffer = buffer;
564
565                 if (!session->sess)
566                 {
567                         CloseSession(session);
568                         return 1;
569                 }
570
571                 session->outbuf.append(sendbuffer, count);
572                 sendbuffer = session->outbuf.c_str();
573                 count = session->outbuf.size();
574
575                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
576                 {
577                         // The handshake isn't finished, try to finish it.
578                         Handshake(session, fd);
579                         errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
580                         return -1;
581                 }
582
583                 int ret = 0;
584
585                 if (session->status == ISSL_HANDSHAKEN)
586                 {
587                         ret = gnutls_record_send(session->sess, sendbuffer, count);
588
589                         if (ret == 0)
590                         {
591                                 CloseSession(session);
592                         }
593                         else if (ret < 0)
594                         {
595                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
596                                 {
597                                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
598                                                         "m_ssl_gnutls.so: Error while writing to fd %d: %s",
599                                                         fd, gnutls_strerror(ret));
600                                         CloseSession(session);
601                                 }
602                                 else
603                                 {
604                                         errno = EAGAIN;
605                                 }
606                         }
607                         else
608                         {
609                                 session->outbuf = session->outbuf.substr(ret);
610                         }
611                 }
612
613                 MakePollWrite(fd);
614
615                 /* Who's smart idea was it to return 1 when we havent written anything?
616                  * This fucks the buffer up in BufferedSocket :p
617                  */
618                 return ret < 1 ? 0 : ret;
619         }
620
621         bool Handshake(issl_session* session, int fd)
622         {
623                 int ret = gnutls_handshake(session->sess);
624
625                 if (ret < 0)
626                 {
627                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
628                         {
629                                 // Handshake needs resuming later, read() or write() would have blocked.
630
631                                 if(gnutls_record_get_direction(session->sess) == 0)
632                                 {
633                                         // gnutls_handshake() wants to read() again.
634                                         session->status = ISSL_HANDSHAKING_READ;
635                                 }
636                                 else
637                                 {
638                                         // gnutls_handshake() wants to write() again.
639                                         session->status = ISSL_HANDSHAKING_WRITE;
640                                         MakePollWrite(fd);
641                                 }
642                         }
643                         else
644                         {
645                                 // Handshake failed.
646                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
647                                                 "m_ssl_gnutls.so: Handshake failed on fd %d: %s",
648                                                 fd, gnutls_strerror(ret));
649                                 CloseSession(session);
650                                 session->status = ISSL_CLOSING;
651                         }
652
653                         return false;
654                 }
655                 else
656                 {
657                         // Handshake complete.
658                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
659                         EventHandler *extendme = ServerInstance->SE->GetRef(fd);
660                         if (extendme)
661                         {
662                                 if (!extendme->GetExt("ssl"))
663                                         extendme->Extend("ssl", "ON");
664                         }
665
666                         // Change the seesion state
667                         session->status = ISSL_HANDSHAKEN;
668
669                         // Finish writing, if any left
670                         MakePollWrite(fd);
671
672                         return true;
673                 }
674         }
675
676         virtual void OnPostConnect(User* user)
677         {
678                 // This occurs AFTER OnUserConnect so we can be sure the
679                 // protocol module has propagated the NICK message.
680                 if (user->GetIOHook() == this && (IS_LOCAL(user)))
681                 {
682                         ssl_cert* certdata = VerifyCertificate(&sessions[user->GetFd()],user);
683                         if (sessions[user->GetFd()].sess)
684                         {
685                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
686                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
687                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
688                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
689                         }
690
691                         ServerInstance->PI->SendMetaData(user, TYPE_USER, "ssl", "ON");
692                         if (certdata)
693                                 ServerInstance->PI->SendMetaData(user, TYPE_USER, "ssl_cert", certdata->GetMetaLine().c_str());
694                 }
695         }
696
697         void MakePollWrite(int fd)
698         {
699                 //OnRawSocketWrite(fd, NULL, 0);
700                 EventHandler* eh = ServerInstance->SE->GetRef(fd);
701                 if (eh)
702                         ServerInstance->SE->WantWrite(eh);
703         }
704
705         virtual void OnBufferFlushed(User* user)
706         {
707                 if (user->GetIOHook() == this)
708                 {
709                         issl_session* session = &sessions[user->GetFd()];
710                         if (session && session->outbuf.size())
711                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
712                 }
713         }
714
715         void CloseSession(issl_session* session)
716         {
717                 if(session->sess)
718                 {
719                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
720                         gnutls_deinit(session->sess);
721                 }
722
723                 session->outbuf.clear();
724                 session->sess = NULL;
725                 session->status = ISSL_NONE;
726         }
727
728         ssl_cert* VerifyCertificate(issl_session* session, Extensible* user)
729         {
730                 if (!session->sess || !user)
731                         return NULL;
732
733                 unsigned int status;
734                 const gnutls_datum_t* cert_list;
735                 int ret;
736                 unsigned int cert_list_size;
737                 gnutls_x509_crt_t cert;
738                 char name[MAXBUF];
739                 unsigned char digest[MAXBUF];
740                 size_t digest_size = sizeof(digest);
741                 size_t name_size = sizeof(name);
742                 ssl_cert* certinfo = new ssl_cert;
743
744                 user->Extend("ssl_cert",certinfo);
745
746                 /* This verification function uses the trusted CAs in the credentials
747                  * structure. So you must have installed one or more CA certificates.
748                  */
749                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
750
751                 if (ret < 0)
752                 {
753                         certinfo->error = std::string(gnutls_strerror(ret));
754                         return certinfo;
755                 }
756
757                 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
758                 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
759                 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
760                 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
761
762                 /* Up to here the process is the same for X.509 certificates and
763                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
764                  * be easily extended to work with openpgp keys as well.
765                  */
766                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
767                 {
768                         certinfo->error = "No X509 keys sent";
769                         return certinfo;
770                 }
771
772                 ret = gnutls_x509_crt_init(&cert);
773                 if (ret < 0)
774                 {
775                         certinfo->error = gnutls_strerror(ret);
776                         return certinfo;
777                 }
778
779                 cert_list_size = 0;
780                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
781                 if (cert_list == NULL)
782                 {
783                         certinfo->error = "No certificate was found";
784                         return certinfo;
785                 }
786
787                 /* This is not a real world example, since we only check the first
788                  * certificate in the given chain.
789                  */
790
791                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
792                 if (ret < 0)
793                 {
794                         certinfo->error = gnutls_strerror(ret);
795                         return certinfo;
796                 }
797
798                 gnutls_x509_crt_get_dn(cert, name, &name_size);
799                 certinfo->dn = name;
800
801                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
802                 certinfo->issuer = name;
803
804                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
805                 {
806                         certinfo->error = gnutls_strerror(ret);
807                 }
808                 else
809                 {
810                         certinfo->fingerprint = irc::hex(digest, digest_size);
811                 }
812
813                 /* Beware here we do not check for errors.
814                  */
815                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
816                 {
817                         certinfo->error = "Not activated, or expired certificate";
818                 }
819
820                 gnutls_x509_crt_deinit(cert);
821
822                 return certinfo;
823         }
824
825         void OnEvent(Event* ev)
826         {
827                 GenericCapHandler(ev, "tls", "tls");
828         }
829
830         void Prioritize()
831         {
832                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
833                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
834         }
835 };
836
837 MODULE_INIT(ModuleSSLGnuTLS)