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