]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
f05a73227044d7f08e84389bc2b146408218ce90
[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                         user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration has started", user->nick.c_str());
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(), NULL, NULL);
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",DEBUG, "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",DEBUG, "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",DEBUG, "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",DEBUG, "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)
351         {
352                 if (!user->GetIOHook() && isin(user->GetServerIP(),user->GetServerPort(),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, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
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                         unsigned int len = 0;
524                         while (len < count)
525                         {
526                                 int ret = gnutls_record_recv(session->sess, buffer + len, count - len);
527                                 if (ret > 0)
528                                 {
529                                         len += ret;
530                                 }
531                                 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
532                                 {
533                                         break;
534                                 }
535                                 else
536                                 {
537                                         if (ret != 0)
538                                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
539                                                         "m_ssl_gnutls.so: Error while reading on fd %d: %s",
540                                                         fd, gnutls_strerror(ret));
541
542                                         // if ret == 0, client closed connection.
543                                         readresult = 0;
544                                         CloseSession(session);
545                                         return 1;
546                                 }
547                         }
548                         readresult = len;
549                         if (len)
550                         {
551                                 return 1;
552                         }
553                         else
554                         {
555                                 errno = EAGAIN;
556                                 return -1;
557                         }
558                 }
559                 else if (session->status == ISSL_CLOSING)
560                         readresult = 0;
561
562                 return 1;
563         }
564
565         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
566         {
567                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
568                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
569                         return 0;
570
571                 issl_session* session = &sessions[fd];
572                 const char* sendbuffer = buffer;
573
574                 if (!session->sess)
575                 {
576                         CloseSession(session);
577                         return 1;
578                 }
579
580                 session->outbuf.append(sendbuffer, count);
581                 sendbuffer = session->outbuf.c_str();
582                 count = session->outbuf.size();
583
584                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
585                 {
586                         // The handshake isn't finished, try to finish it.
587                         Handshake(session, fd);
588                         errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
589                         return -1;
590                 }
591
592                 int ret = 0;
593
594                 if (session->status == ISSL_HANDSHAKEN)
595                 {
596                         ret = gnutls_record_send(session->sess, sendbuffer, count);
597
598                         if (ret == 0)
599                         {
600                                 CloseSession(session);
601                         }
602                         else if (ret < 0)
603                         {
604                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
605                                 {
606                                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
607                                                         "m_ssl_gnutls.so: Error while writing to fd %d: %s",
608                                                         fd, gnutls_strerror(ret));
609                                         CloseSession(session);
610                                 }
611                                 else
612                                 {
613                                         errno = EAGAIN;
614                                 }
615                         }
616                         else
617                         {
618                                 session->outbuf = session->outbuf.substr(ret);
619                         }
620                 }
621
622                 if (!session->outbuf.empty())
623                         MakePollWrite(fd);
624
625                 /* Who's smart idea was it to return 1 when we havent written anything?
626                  * This fucks the buffer up in BufferedSocket :p
627                  */
628                 return ret < 1 ? 0 : ret;
629         }
630
631         bool Handshake(issl_session* session, int fd)
632         {
633                 int ret = gnutls_handshake(session->sess);
634
635                 if (ret < 0)
636                 {
637                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
638                         {
639                                 // Handshake needs resuming later, read() or write() would have blocked.
640
641                                 if(gnutls_record_get_direction(session->sess) == 0)
642                                 {
643                                         // gnutls_handshake() wants to read() again.
644                                         session->status = ISSL_HANDSHAKING_READ;
645                                 }
646                                 else
647                                 {
648                                         // gnutls_handshake() wants to write() again.
649                                         session->status = ISSL_HANDSHAKING_WRITE;
650                                         MakePollWrite(fd);
651                                 }
652                         }
653                         else
654                         {
655                                 // Handshake failed.
656                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
657                                                 "m_ssl_gnutls.so: Handshake failed on fd %d: %s",
658                                                 fd, gnutls_strerror(ret));
659                                 CloseSession(session);
660                                 session->status = ISSL_CLOSING;
661                         }
662
663                         return false;
664                 }
665                 else
666                 {
667                         // Handshake complete.
668                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
669                         EventHandler *extendme = ServerInstance->SE->GetRef(fd);
670                         if (extendme)
671                         {
672                                 if (!extendme->GetExt("ssl"))
673                                         extendme->Extend("ssl", "ON");
674                         }
675
676                         // Change the seesion state
677                         session->status = ISSL_HANDSHAKEN;
678
679                         // Finish writing, if any left
680                         MakePollWrite(fd);
681
682                         return true;
683                 }
684         }
685
686         virtual void OnPostConnect(User* user)
687         {
688                 // This occurs AFTER OnUserConnect so we can be sure the
689                 // protocol module has propagated the NICK message.
690                 if (user->GetIOHook() == this && (IS_LOCAL(user)))
691                 {
692                         ssl_cert* certdata = VerifyCertificate(&sessions[user->GetFd()],user);
693                         if (sessions[user->GetFd()].sess)
694                         {
695                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
696                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
697                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
698                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
699                         }
700
701                         ServerInstance->PI->SendMetaData(user, TYPE_USER, "ssl", "ON");
702                         if (certdata)
703                                 ServerInstance->PI->SendMetaData(user, TYPE_USER, "ssl_cert", certdata->GetMetaLine().c_str());
704                 }
705         }
706
707         void MakePollWrite(int fd)
708         {
709                 //OnRawSocketWrite(fd, NULL, 0);
710                 EventHandler* eh = ServerInstance->SE->GetRef(fd);
711                 if (eh)
712                         ServerInstance->SE->WantWrite(eh);
713         }
714
715         virtual void OnBufferFlushed(User* user)
716         {
717                 if (user->GetIOHook() == this)
718                 {
719                         issl_session* session = &sessions[user->GetFd()];
720                         if (session && session->outbuf.size())
721                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
722                 }
723         }
724
725         void CloseSession(issl_session* session)
726         {
727                 if(session->sess)
728                 {
729                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
730                         gnutls_deinit(session->sess);
731                 }
732
733                 session->outbuf.clear();
734                 session->sess = NULL;
735                 session->status = ISSL_NONE;
736         }
737
738         ssl_cert* VerifyCertificate(issl_session* session, Extensible* user)
739         {
740                 if (!session->sess || !user)
741                         return NULL;
742
743                 unsigned int status;
744                 const gnutls_datum_t* cert_list;
745                 int ret;
746                 unsigned int cert_list_size;
747                 gnutls_x509_crt_t cert;
748                 char name[MAXBUF];
749                 unsigned char digest[MAXBUF];
750                 size_t digest_size = sizeof(digest);
751                 size_t name_size = sizeof(name);
752                 ssl_cert* certinfo = new ssl_cert;
753
754                 user->Extend("ssl_cert",certinfo);
755
756                 /* This verification function uses the trusted CAs in the credentials
757                  * structure. So you must have installed one or more CA certificates.
758                  */
759                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
760
761                 if (ret < 0)
762                 {
763                         certinfo->error = std::string(gnutls_strerror(ret));
764                         return certinfo;
765                 }
766
767                 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
768                 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
769                 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
770                 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
771
772                 /* Up to here the process is the same for X.509 certificates and
773                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
774                  * be easily extended to work with openpgp keys as well.
775                  */
776                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
777                 {
778                         certinfo->error = "No X509 keys sent";
779                         return certinfo;
780                 }
781
782                 ret = gnutls_x509_crt_init(&cert);
783                 if (ret < 0)
784                 {
785                         certinfo->error = gnutls_strerror(ret);
786                         return certinfo;
787                 }
788
789                 cert_list_size = 0;
790                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
791                 if (cert_list == NULL)
792                 {
793                         certinfo->error = "No certificate was found";
794                         return certinfo;
795                 }
796
797                 /* This is not a real world example, since we only check the first
798                  * certificate in the given chain.
799                  */
800
801                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
802                 if (ret < 0)
803                 {
804                         certinfo->error = gnutls_strerror(ret);
805                         return certinfo;
806                 }
807
808                 gnutls_x509_crt_get_dn(cert, name, &name_size);
809                 certinfo->dn = name;
810
811                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
812                 certinfo->issuer = name;
813
814                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
815                 {
816                         certinfo->error = gnutls_strerror(ret);
817                 }
818                 else
819                 {
820                         certinfo->fingerprint = irc::hex(digest, digest_size);
821                 }
822
823                 /* Beware here we do not check for errors.
824                  */
825                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
826                 {
827                         certinfo->error = "Not activated, or expired certificate";
828                 }
829
830                 gnutls_x509_crt_deinit(cert);
831
832                 return certinfo;
833         }
834
835         void OnEvent(Event* ev)
836         {
837                 GenericCapHandler(ev, "tls", "tls");
838         }
839
840         void Prioritize()
841         {
842                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
843                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
844         }
845 };
846
847 MODULE_INIT(ModuleSSLGnuTLS)