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