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