]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
a769bd12bfae55aadb200b1b2ce5775974e7c3ab
[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), starttls(Me, this)
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                 ServerInstance->AddCommand(&starttls);
139         }
140
141         virtual void OnRehash(User* user)
142         {
143                 ConfigReader Conf(ServerInstance);
144
145                 listenports.clear();
146                 clientactive = 0;
147                 sslports.clear();
148
149                 for(int index = 0; index < Conf.Enumerate("bind"); index++)
150                 {
151                         // For each <bind> tag
152                         std::string x = Conf.ReadValue("bind", "type", index);
153                         if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "gnutls"))
154                         {
155                                 // Get the port we're meant to be listening on with SSL
156                                 std::string port = Conf.ReadValue("bind", "port", index);
157                                 std::string addr = Conf.ReadValue("bind", "address", index);
158
159                                 if (!addr.empty())
160                                 {
161                                         // normalize address, important for IPv6
162                                         int portint = 0;
163                                         irc::sockets::sockaddrs bin;
164                                         if (irc::sockets::aptosa(addr.c_str(), portint, &bin))
165                                                 irc::sockets::satoap(&bin, addr, portint);
166                                 }
167
168                                 irc::portparser portrange(port, false);
169                                 long portno = -1;
170                                 while ((portno = portrange.GetToken()))
171                                 {
172                                         clientactive++;
173                                         try
174                                         {
175                                                 listenports.push_back(addr + ":" + ConvToStr(portno));
176
177                                                 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
178                                                         if ((ServerInstance->ports[i]->GetPort() == portno) && (ServerInstance->ports[i]->GetIP() == addr))
179                                                                 ServerInstance->ports[i]->SetDescription("ssl");
180                                                 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %ld", portno);
181
182                                                 if (addr != "127.0.0.1")
183                                                         sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
184                                         }
185                                         catch (ModuleException &e)
186                                         {
187                                                 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());
188                                         }
189                                 }
190                         }
191                 }
192
193                 if (!sslports.empty())
194                         sslports.erase(sslports.end() - 1);
195         }
196
197         virtual void OnModuleRehash(User* user, const std::string &param)
198         {
199                 if(param != "ssl")
200                         return;
201
202                 OnRehash(user);
203
204                 ConfigReader Conf(ServerInstance);
205
206                 std::string confdir(ServerInstance->ConfigFileName);
207                 // +1 so we the path ends with a /
208                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
209
210                 cafile = Conf.ReadValue("gnutls", "cafile", 0);
211                 crlfile = Conf.ReadValue("gnutls", "crlfile", 0);
212                 certfile = Conf.ReadValue("gnutls", "certfile", 0);
213                 keyfile = Conf.ReadValue("gnutls", "keyfile", 0);
214                 dh_bits = Conf.ReadInteger("gnutls", "dhbits", 0, false);
215
216                 // Set all the default values needed.
217                 if (cafile.empty())
218                         cafile = "ca.pem";
219
220                 if (crlfile.empty())
221                         crlfile = "crl.pem";
222
223                 if (certfile.empty())
224                         certfile = "cert.pem";
225
226                 if (keyfile.empty())
227                         keyfile = "key.pem";
228
229                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
230                         dh_bits = 1024;
231
232                 // Prepend relative paths with the path to the config directory.
233                 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
234                         cafile = confdir + cafile;
235
236                 if ((crlfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(crlfile)))
237                         crlfile = confdir + crlfile;
238
239                 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
240                         certfile = confdir + certfile;
241
242                 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
243                         keyfile = confdir + keyfile;
244
245                 int ret;
246
247                 if (cred_alloc)
248                 {
249                         // Deallocate the old credentials
250                         gnutls_dh_params_deinit(dh_params);
251                         gnutls_certificate_free_credentials(x509_cred);
252                 }
253                 else
254                         cred_alloc = true;
255
256                 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
257                         ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
258
259                 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
260                         ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
261
262                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
263                         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));
264
265                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
266                         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));
267
268                 if((ret = gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
269                 {
270                         // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
271                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + ", key: " + keyfile + "): " + std::string(gnutls_strerror(ret)));
272                 }
273
274                 // This may be on a large (once a day or week) timer eventually.
275                 GenerateDHParams();
276         }
277
278         void GenerateDHParams()
279         {
280                 // Generate Diffie Hellman parameters - for use with DHE
281                 // kx algorithms. These should be discarded and regenerated
282                 // once a day, once a week or once a month. Depending on the
283                 // security requirements.
284
285                 int ret;
286
287                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
288                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
289         }
290
291         virtual ~ModuleSSLGnuTLS()
292         {
293                 gnutls_dh_params_deinit(dh_params);
294                 gnutls_certificate_free_credentials(x509_cred);
295                 gnutls_global_deinit();
296                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
297                 delete[] sessions;
298         }
299
300         virtual void OnCleanup(int target_type, void* item)
301         {
302                 if(target_type == TYPE_USER)
303                 {
304                         User* user = static_cast<User*>(item);
305
306                         if (user->GetIOHook() == this)
307                         {
308                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
309                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
310                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
311                                 user->DelIOHook();
312                         }
313                         if (user->GetExt("ssl_cert"))
314                         {
315                                 ssl_cert* tofree;
316                                 user->GetExt("ssl_cert", tofree);
317                                 delete tofree;
318                                 user->Shrink("ssl_cert");
319                         }
320                 }
321         }
322
323         virtual void OnUnloadModule(Module* mod, const std::string &name)
324         {
325                 if(mod == this)
326                 {
327                         for(unsigned int i = 0; i < listenports.size(); i++)
328                         {
329                                 for (size_t j = 0; j < ServerInstance->ports.size(); j++)
330                                         if (listenports[i] == (ServerInstance->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->ports[j]->GetPort())))
331                                                 ServerInstance->ports[j]->SetDescription("plaintext");
332                         }
333                 }
334         }
335
336         virtual Version GetVersion()
337         {
338                 return Version("$Id$", VF_VENDOR, API_VERSION);
339         }
340
341
342         virtual void On005Numeric(std::string &output)
343         {
344                 if (!sslports.empty())
345                         output.append(" SSL=" + sslports);
346                 output.append(" STARTTLS");
347         }
348
349         virtual void OnHookUserIO(User* user)
350         {
351                 if (!user->GetIOHook() && isin(user->GetServerIP(),user->GetServerPort(),listenports))
352                 {
353                         /* Hook the user with our module */
354                         user->AddIOHook(this);
355                 }
356         }
357
358         virtual const char* OnRequest(Request* request)
359         {
360                 ISHRequest* ISR = static_cast<ISHRequest*>(request);
361                 if (strcmp("IS_NAME", request->GetId()) == 0)
362                 {
363                         return "gnutls";
364                 }
365                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
366                 {
367                         const char* ret = "OK";
368                         try
369                         {
370                                 ret = ISR->Sock->AddIOHook(this) ? "OK" : NULL;
371                         }
372                         catch (ModuleException &e)
373                         {
374                                 return NULL;
375                         }
376                         return ret;
377                 }
378                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
379                 {
380                         return ISR->Sock->DelIOHook() ? "OK" : NULL;
381                 }
382                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
383                 {
384                         if (ISR->Sock->GetFd() < 0)
385                                 return "OK";
386
387                         issl_session* session = &sessions[ISR->Sock->GetFd()];
388                         return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : "OK";
389                 }
390                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
391                 {
392                         if (ISR->Sock->GetFd() > -1)
393                         {
394                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
395                                 if (session->sess)
396                                 {
397                                         if (static_cast<Extensible*>(ServerInstance->SE->GetRef(ISR->Sock->GetFd())) == static_cast<Extensible*>(ISR->Sock))
398                                         {
399                                                 VerifyCertificate(session, ISR->Sock);
400                                                 return "OK";
401                                         }
402                                 }
403                         }
404                 }
405                 else if (strcmp("GET_FP", request->GetId()) == 0)
406                 {
407                         if (ISR->Sock->GetFd() > -1)
408                         {
409                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
410                                 if (session->sess)
411                                 {
412                                         Extensible* ext = ISR->Sock;
413                                         ssl_cert* certinfo;
414                                         if (ext->GetExt("ssl_cert",certinfo))
415                                                 return certinfo->GetFingerprint().c_str();
416                                 }
417                         }
418                 }
419                 return NULL;
420         }
421
422
423         virtual void OnRawSocketAccept(int fd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
424         {
425                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
426                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
427                         return;
428
429                 issl_session* session = &sessions[fd];
430
431                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
432                 if (session->sess)
433                         return;
434
435                 gnutls_init(&session->sess, GNUTLS_SERVER);
436
437                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
438                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
439                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
440
441                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(fd)); // Give gnutls the fd for the socket.
442
443                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
444
445                 Handshake(session, fd);
446         }
447
448         virtual void OnRawSocketConnect(int fd)
449         {
450                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
451                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
452                         return;
453
454                 issl_session* session = &sessions[fd];
455
456                 gnutls_init(&session->sess, GNUTLS_CLIENT);
457
458                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
459                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
460                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
461                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(fd)); // Give gnutls the fd for the socket.
462
463                 Handshake(session, fd);
464         }
465
466         virtual void OnRawSocketClose(int fd)
467         {
468                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
469                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds()))
470                         return;
471
472                 CloseSession(&sessions[fd]);
473
474                 EventHandler* user = ServerInstance->SE->GetRef(fd);
475
476                 if ((user) && (user->GetExt("ssl_cert")))
477                 {
478                         ssl_cert* tofree;
479                         user->GetExt("ssl_cert", tofree);
480                         delete tofree;
481                         user->Shrink("ssl_cert");
482                 }
483         }
484
485         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
486         {
487                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
488                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
489                         return 0;
490
491                 issl_session* session = &sessions[fd];
492
493                 if (!session->sess)
494                 {
495                         readresult = 0;
496                         CloseSession(session);
497                         return 1;
498                 }
499
500                 if (session->status == ISSL_HANDSHAKING_READ)
501                 {
502                         // The handshake isn't finished, try to finish it.
503
504                         if(!Handshake(session, fd))
505                         {
506                                 errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
507                                 // Couldn't resume handshake.
508                                 return -1;
509                         }
510                 }
511                 else if (session->status == ISSL_HANDSHAKING_WRITE)
512                 {
513                         errno = EAGAIN;
514                         MakePollWrite(fd);
515                         return -1;
516                 }
517
518                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
519
520                 if (session->status == ISSL_HANDSHAKEN)
521                 {
522                         unsigned int len = 0;
523                         while (len < count)
524                         {
525                                 int ret = gnutls_record_recv(session->sess, buffer + len, count - len);
526                                 if (ret > 0)
527                                 {
528                                         len += ret;
529                                 }
530                                 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
531                                 {
532                                         break;
533                                 }
534                                 else
535                                 {
536                                         if (ret != 0)
537                                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
538                                                         "m_ssl_gnutls.so: Error while reading on fd %d: %s",
539                                                         fd, gnutls_strerror(ret));
540
541                                         // if ret == 0, client closed connection.
542                                         readresult = 0;
543                                         CloseSession(session);
544                                         return 1;
545                                 }
546                         }
547                         readresult = len;
548                         if (len)
549                         {
550                                 return 1;
551                         }
552                         else
553                         {
554                                 errno = EAGAIN;
555                                 return -1;
556                         }
557                 }
558                 else if (session->status == ISSL_CLOSING)
559                         readresult = 0;
560
561                 return 1;
562         }
563
564         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
565         {
566                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
567                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
568                         return 0;
569
570                 issl_session* session = &sessions[fd];
571                 const char* sendbuffer = buffer;
572
573                 if (!session->sess)
574                 {
575                         CloseSession(session);
576                         return 1;
577                 }
578
579                 session->outbuf.append(sendbuffer, count);
580                 sendbuffer = session->outbuf.c_str();
581                 count = session->outbuf.size();
582
583                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
584                 {
585                         // The handshake isn't finished, try to finish it.
586                         Handshake(session, fd);
587                         errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
588                         return -1;
589                 }
590
591                 int ret = 0;
592
593                 if (session->status == ISSL_HANDSHAKEN)
594                 {
595                         ret = gnutls_record_send(session->sess, sendbuffer, count);
596
597                         if (ret == 0)
598                         {
599                                 CloseSession(session);
600                         }
601                         else if (ret < 0)
602                         {
603                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
604                                 {
605                                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
606                                                         "m_ssl_gnutls.so: Error while writing to fd %d: %s",
607                                                         fd, gnutls_strerror(ret));
608                                         CloseSession(session);
609                                 }
610                                 else
611                                 {
612                                         errno = EAGAIN;
613                                 }
614                         }
615                         else
616                         {
617                                 session->outbuf = session->outbuf.substr(ret);
618                         }
619                 }
620
621                 if (!session->outbuf.empty())
622                         MakePollWrite(fd);
623
624                 /* Who's smart idea was it to return 1 when we havent written anything?
625                  * This fucks the buffer up in BufferedSocket :p
626                  */
627                 return ret < 1 ? 0 : ret;
628         }
629
630         bool Handshake(issl_session* session, int fd)
631         {
632                 int ret = gnutls_handshake(session->sess);
633
634                 if (ret < 0)
635                 {
636                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
637                         {
638                                 // Handshake needs resuming later, read() or write() would have blocked.
639
640                                 if(gnutls_record_get_direction(session->sess) == 0)
641                                 {
642                                         // gnutls_handshake() wants to read() again.
643                                         session->status = ISSL_HANDSHAKING_READ;
644                                 }
645                                 else
646                                 {
647                                         // gnutls_handshake() wants to write() again.
648                                         session->status = ISSL_HANDSHAKING_WRITE;
649                                         MakePollWrite(fd);
650                                 }
651                         }
652                         else
653                         {
654                                 // Handshake failed.
655                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
656                                                 "m_ssl_gnutls.so: Handshake failed on fd %d: %s",
657                                                 fd, gnutls_strerror(ret));
658                                 CloseSession(session);
659                                 session->status = ISSL_CLOSING;
660                         }
661
662                         return false;
663                 }
664                 else
665                 {
666                         // Handshake complete.
667                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
668                         EventHandler *extendme = ServerInstance->SE->GetRef(fd);
669                         if (extendme)
670                         {
671                                 if (!extendme->GetExt("ssl"))
672                                         extendme->Extend("ssl", "ON");
673                         }
674
675                         // Change the seesion state
676                         session->status = ISSL_HANDSHAKEN;
677
678                         // Finish writing, if any left
679                         MakePollWrite(fd);
680
681                         return true;
682                 }
683         }
684
685         virtual void OnPostConnect(User* user)
686         {
687                 // This occurs AFTER OnUserConnect so we can be sure the
688                 // protocol module has propagated the NICK message.
689                 if (user->GetIOHook() == this && (IS_LOCAL(user)))
690                 {
691                         ssl_cert* certdata = VerifyCertificate(&sessions[user->GetFd()],user);
692                         if (sessions[user->GetFd()].sess)
693                         {
694                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
695                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
696                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
697                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
698                         }
699
700                         ServerInstance->PI->SendMetaData(user, "ssl", "ON");
701                         if (certdata)
702                                 ServerInstance->PI->SendMetaData(user, "ssl_cert", certdata->GetMetaLine().c_str());
703                 }
704         }
705
706         void MakePollWrite(int fd)
707         {
708                 //OnRawSocketWrite(fd, NULL, 0);
709                 EventHandler* eh = ServerInstance->SE->GetRef(fd);
710                 if (eh)
711                         ServerInstance->SE->WantWrite(eh);
712         }
713
714         virtual void OnBufferFlushed(User* user)
715         {
716                 if (user->GetIOHook() == this)
717                 {
718                         issl_session* session = &sessions[user->GetFd()];
719                         if (session && session->outbuf.size())
720                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
721                 }
722         }
723
724         void CloseSession(issl_session* session)
725         {
726                 if(session->sess)
727                 {
728                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
729                         gnutls_deinit(session->sess);
730                 }
731
732                 session->outbuf.clear();
733                 session->sess = NULL;
734                 session->status = ISSL_NONE;
735         }
736
737         ssl_cert* VerifyCertificate(issl_session* session, Extensible* user)
738         {
739                 if (!session->sess || !user)
740                         return NULL;
741
742                 unsigned int status;
743                 const gnutls_datum_t* cert_list;
744                 int ret;
745                 unsigned int cert_list_size;
746                 gnutls_x509_crt_t cert;
747                 char name[MAXBUF];
748                 unsigned char digest[MAXBUF];
749                 size_t digest_size = sizeof(digest);
750                 size_t name_size = sizeof(name);
751                 ssl_cert* certinfo = new ssl_cert;
752
753                 user->Extend("ssl_cert",certinfo);
754
755                 /* This verification function uses the trusted CAs in the credentials
756                  * structure. So you must have installed one or more CA certificates.
757                  */
758                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
759
760                 if (ret < 0)
761                 {
762                         certinfo->error = std::string(gnutls_strerror(ret));
763                         return certinfo;
764                 }
765
766                 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
767                 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
768                 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
769                 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
770
771                 /* Up to here the process is the same for X.509 certificates and
772                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
773                  * be easily extended to work with openpgp keys as well.
774                  */
775                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
776                 {
777                         certinfo->error = "No X509 keys sent";
778                         return certinfo;
779                 }
780
781                 ret = gnutls_x509_crt_init(&cert);
782                 if (ret < 0)
783                 {
784                         certinfo->error = gnutls_strerror(ret);
785                         return certinfo;
786                 }
787
788                 cert_list_size = 0;
789                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
790                 if (cert_list == NULL)
791                 {
792                         certinfo->error = "No certificate was found";
793                         return certinfo;
794                 }
795
796                 /* This is not a real world example, since we only check the first
797                  * certificate in the given chain.
798                  */
799
800                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
801                 if (ret < 0)
802                 {
803                         certinfo->error = gnutls_strerror(ret);
804                         return certinfo;
805                 }
806
807                 gnutls_x509_crt_get_dn(cert, name, &name_size);
808                 certinfo->dn = name;
809
810                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
811                 certinfo->issuer = name;
812
813                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
814                 {
815                         certinfo->error = gnutls_strerror(ret);
816                 }
817                 else
818                 {
819                         certinfo->fingerprint = irc::hex(digest, digest_size);
820                 }
821
822                 /* Beware here we do not check for errors.
823                  */
824                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
825                 {
826                         certinfo->error = "Not activated, or expired certificate";
827                 }
828
829                 gnutls_x509_crt_deinit(cert);
830
831                 return certinfo;
832         }
833
834         void OnEvent(Event* ev)
835         {
836                 GenericCapHandler(ev, "tls", "tls");
837         }
838
839         void Prioritize()
840         {
841                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
842                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
843         }
844 };
845
846 MODULE_INIT(ModuleSSLGnuTLS)