]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Add <oper:autologin> to allow SSL fingerprint-based automatic oper login
[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-2010 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 <gcrypt.h>
18 #include "ssl.h"
19 #include "m_cap.h"
20
21 #ifdef WINDOWS
22 #pragma comment(lib, "libgnutls-13.lib")
23 #endif
24
25 /* $ModDesc: Provides SSL support for clients */
26 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") */
27 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") */
28
29 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
30
31 static gnutls_x509_crt_t x509_cert;
32 static gnutls_x509_privkey_t x509_key;
33 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
34         const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
35
36         st->type = GNUTLS_CRT_X509;
37         st->ncerts = 1;
38         st->cert.x509 = &x509_cert;
39         st->key.x509 = x509_key;
40         st->deinit_all = 0;
41
42         return 0;
43 }
44
45 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t user_wrap, void* buffer, size_t size)
46 {
47         StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
48         if (user->GetEventMask() & FD_READ_WILL_BLOCK)
49         {
50                 errno = EAGAIN;
51                 return -1;
52         }
53         int rv = recv(user->GetFd(), buffer, size, 0);
54         if (rv < (int)size)
55                 ServerInstance->SE->ChangeEventMask(user, FD_READ_WILL_BLOCK);
56         return rv;
57 }
58
59 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t user_wrap, const void* buffer, size_t size)
60 {
61         StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
62         if (user->GetEventMask() & FD_WRITE_WILL_BLOCK)
63         {
64                 errno = EAGAIN;
65                 return -1;
66         }
67         int rv = send(user->GetFd(), buffer, size, 0);
68         if (rv < (int)size)
69                 ServerInstance->SE->ChangeEventMask(user, FD_WRITE_WILL_BLOCK);
70         return rv;
71 }
72
73 class RandGen : public HandlerBase2<void, char*, size_t>
74 {
75  public:
76         RandGen() {}
77         void Call(char* buffer, size_t len)
78         {
79                 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
80         }
81 };
82
83 /** Represents an SSL user's extra data
84  */
85 class issl_session
86 {
87 public:
88         gnutls_session_t sess;
89         issl_status status;
90         reference<ssl_cert> cert;
91         issl_session() : sess(NULL) {}
92 };
93
94 class CommandStartTLS : public SplitCommand
95 {
96  public:
97         CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
98         {
99                 works_before_reg = true;
100         }
101
102         CmdResult HandleLocal(const std::vector<std::string> &parameters, LocalUser *user)
103         {
104                 /* changed from == REG_ALL to catch clients sending STARTTLS
105                  * after NICK and USER but before OnUserConnect completes and
106                  * give a proper error message (see bug #645) - dz
107                  */
108                 if (user->registered != REG_NONE)
109                 {
110                         user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration has started", user->nick.c_str());
111                 }
112                 else
113                 {
114                         if (!user->eh.GetIOHook())
115                         {
116                                 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
117                                 /* We need to flush the write buffer prior to adding the IOHook,
118                                  * otherwise we'll be sending this line inside the SSL session - which
119                                  * won't start its handshake until the client gets this line. Currently,
120                                  * we assume the write will not block here; this is usually safe, as
121                                  * STARTTLS is sent very early on in the registration phase, where the
122                                  * user hasn't built up much sendq. Handling a blocked write here would
123                                  * be very annoying.
124                                  */
125                                 user->eh.DoWrite();
126                                 user->eh.AddIOHook(creator);
127                                 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
128                         }
129                         else
130                                 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
131                 }
132
133                 return CMD_FAILURE;
134         }
135 };
136
137 class ModuleSSLGnuTLS : public Module
138 {
139         issl_session* sessions;
140
141         gnutls_certificate_credentials x509_cred;
142         gnutls_dh_params dh_params;
143         gnutls_digest_algorithm_t hash;
144
145         std::string sslports;
146         int dh_bits;
147
148         bool cred_alloc;
149
150         RandGen randhandler;
151         CommandStartTLS starttls;
152
153         GenericCap capHandler;
154         ServiceProvider iohook;
155  public:
156
157         ModuleSSLGnuTLS()
158                 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
159         {
160                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
161
162                 gnutls_global_init(); // This must be called once in the program
163                 gnutls_x509_crt_init(&x509_cert);
164                 gnutls_x509_privkey_init(&x509_key);
165
166                 cred_alloc = false;
167         }
168
169         void init()
170         {
171                 // Needs the flag as it ignores a plain /rehash
172                 OnModuleRehash(NULL,"ssl");
173
174                 ServerInstance->GenRandom = &randhandler;
175
176                 // Void return, guess we assume success
177                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
178                 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
179                         I_OnEvent, I_OnHookIO };
180                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
181
182                 ServerInstance->Modules->AddService(iohook);
183                 ServerInstance->AddCommand(&starttls);
184         }
185
186         void OnRehash(User* user)
187         {
188                 sslports.clear();
189
190                 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
191                 {
192                         ListenSocket* port = ServerInstance->ports[i];
193                         if (port->bind_tag->getString("ssl") != "gnutls")
194                                 continue;
195
196                         const std::string& portid = port->bind_desc;
197                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
198
199                         if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
200                                 sslports.append(portid).append(";");
201                 }
202
203                 if (!sslports.empty())
204                         sslports.erase(sslports.end() - 1);
205         }
206
207         void OnModuleRehash(User* user, const std::string &param)
208         {
209                 if(param != "ssl")
210                         return;
211
212                 std::string keyfile;
213                 std::string certfile;
214                 std::string cafile;
215                 std::string crlfile;
216                 OnRehash(user);
217
218                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
219
220                 cafile = Conf->getString("cafile", "conf/ca.pem");
221                 crlfile = Conf->getString("crlfile", "conf/crl.pem");
222                 certfile = Conf->getString("certfile", "conf/cert.pem");
223                 keyfile = Conf->getString("keyfile", "conf/key.pem");
224                 dh_bits = Conf->getInt("dhbits");
225                 std::string hashname = Conf->getString("hash", "md5");
226
227                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
228                         dh_bits = 1024;
229
230                 if (hashname == "md5")
231                         hash = GNUTLS_DIG_MD5;
232                 else if (hashname == "sha1")
233                         hash = GNUTLS_DIG_SHA1;
234                 else
235                         throw ModuleException("Unknown hash type " + hashname);
236
237
238                 int ret;
239
240                 if (cred_alloc)
241                 {
242                         // Deallocate the old credentials
243                         gnutls_dh_params_deinit(dh_params);
244                         gnutls_certificate_free_credentials(x509_cred);
245                 }
246                 else
247                         cred_alloc = true;
248
249                 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
250                         ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
251
252                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
253                         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));
254
255                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
256                         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));
257
258                 FileReader reader;
259
260                 reader.LoadFile(certfile);
261                 std::string cert_string = reader.Contents();
262                 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), cert_string.length() };
263
264                 reader.LoadFile(keyfile);
265                 std::string key_string = reader.Contents();
266                 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), key_string.length() };
267
268                 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
269                 if((ret = gnutls_x509_crt_import(x509_cert, &cert_datum, GNUTLS_X509_FMT_PEM)) < 0)
270                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + std::string(gnutls_strerror(ret)));
271
272                 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
273                         throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
274
275                 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_cert, 1, x509_key)) < 0)
276                         throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
277
278                 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
279
280                 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
281                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
282
283                 // This may be on a large (once a day or week) timer eventually.
284                 GenerateDHParams();
285         }
286
287         void GenerateDHParams()
288         {
289                 // Generate Diffie Hellman parameters - for use with DHE
290                 // kx algorithms. These should be discarded and regenerated
291                 // once a day, once a week or once a month. Depending on the
292                 // security requirements.
293
294                 int ret;
295
296                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
297                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
298         }
299
300         ~ModuleSSLGnuTLS()
301         {
302                 gnutls_x509_crt_deinit(x509_cert);
303                 gnutls_x509_privkey_deinit(x509_key);
304                 if (cred_alloc)
305                 {
306                         gnutls_dh_params_deinit(dh_params);
307                         gnutls_certificate_free_credentials(x509_cred);
308                 }
309                 gnutls_global_deinit();
310                 delete[] sessions;
311                 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
312         }
313
314         void OnCleanup(int target_type, void* item)
315         {
316                 if(target_type == TYPE_USER)
317                 {
318                         LocalUser* user = IS_LOCAL(static_cast<User*>(item));
319
320                         if (user && user->eh.GetIOHook() == this)
321                         {
322                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
323                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
324                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
325                         }
326                 }
327         }
328
329         Version GetVersion()
330         {
331                 return Version("Provides SSL support for clients", VF_VENDOR);
332         }
333
334
335         void On005Numeric(std::string &output)
336         {
337                 if (!sslports.empty())
338                         output.append(" SSL=" + sslports);
339                 output.append(" STARTTLS");
340         }
341
342         void OnHookIO(StreamSocket* user, ListenSocket* lsb)
343         {
344                 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
345                 {
346                         /* Hook the user with our module */
347                         user->AddIOHook(this);
348                 }
349         }
350
351         void OnRequest(Request& request)
352         {
353                 if (strcmp("GET_SSL_CERT", request.id) == 0)
354                 {
355                         SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
356                         int fd = req.sock->GetFd();
357                         issl_session* session = &sessions[fd];
358
359                         req.cert = session->cert;
360                 }
361         }
362
363         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
364         {
365                 int fd = user->GetFd();
366                 issl_session* session = &sessions[fd];
367
368                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
369                 if (session->sess)
370                         return;
371
372                 gnutls_init(&session->sess, GNUTLS_SERVER);
373
374                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
375                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
376                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
377
378                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
379                 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
380                 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
381
382                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
383
384                 Handshake(session, user);
385         }
386
387         void OnStreamSocketConnect(StreamSocket* user)
388         {
389                 issl_session* session = &sessions[user->GetFd()];
390
391                 gnutls_init(&session->sess, GNUTLS_CLIENT);
392
393                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
394                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
395                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
396                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
397                 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
398                 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
399
400                 Handshake(session, user);
401         }
402
403         void OnStreamSocketClose(StreamSocket* user)
404         {
405                 CloseSession(&sessions[user->GetFd()]);
406         }
407
408         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
409         {
410                 issl_session* session = &sessions[user->GetFd()];
411
412                 if (!session->sess)
413                 {
414                         CloseSession(session);
415                         user->SetError("No SSL session");
416                         return -1;
417                 }
418
419                 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
420                 {
421                         // The handshake isn't finished, try to finish it.
422
423                         if(!Handshake(session, user))
424                         {
425                                 if (session->status != ISSL_CLOSING)
426                                         return 0;
427                                 return -1;
428                         }
429                 }
430
431                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
432
433                 if (session->status == ISSL_HANDSHAKEN)
434                 {
435                         char* buffer = ServerInstance->GetReadBuffer();
436                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
437                         int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
438                         if (ret > 0)
439                         {
440                                 recvq.append(buffer, ret);
441                                 return 1;
442                         }
443                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
444                         {
445                                 return 0;
446                         }
447                         else if (ret == 0)
448                         {
449                                 user->SetError("SSL Connection closed");
450                                 CloseSession(session);
451                                 return -1;
452                         }
453                         else
454                         {
455                                 user->SetError(gnutls_strerror(ret));
456                                 CloseSession(session);
457                                 return -1;
458                         }
459                 }
460                 else if (session->status == ISSL_CLOSING)
461                         return -1;
462
463                 return 0;
464         }
465
466         int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
467         {
468                 issl_session* session = &sessions[user->GetFd()];
469
470                 if (!session->sess)
471                 {
472                         CloseSession(session);
473                         user->SetError("No SSL session");
474                         return -1;
475                 }
476
477                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
478                 {
479                         // The handshake isn't finished, try to finish it.
480                         Handshake(session, user);
481                         if (session->status != ISSL_CLOSING)
482                                 return 0;
483                         return -1;
484                 }
485
486                 int ret = 0;
487
488                 if (session->status == ISSL_HANDSHAKEN)
489                 {
490                         ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
491
492                         if (ret == (int)sendq.length())
493                         {
494                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
495                                 return 1;
496                         }
497                         else if (ret > 0)
498                         {
499                                 sendq = sendq.substr(ret);
500                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
501                                 return 0;
502                         }
503                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
504                         {
505                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
506                                 return 0;
507                         }
508                         else if (ret == 0)
509                         {
510                                 CloseSession(session);
511                                 user->SetError("SSL Connection closed");
512                                 return -1;
513                         }
514                         else // (ret < 0)
515                         {
516                                 user->SetError(gnutls_strerror(ret));
517                                 CloseSession(session);
518                                 return -1;
519                         }
520                 }
521
522                 return 0;
523         }
524
525         bool Handshake(issl_session* session, StreamSocket* user)
526         {
527                 int ret = gnutls_handshake(session->sess);
528
529                 if (ret < 0)
530                 {
531                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
532                         {
533                                 // Handshake needs resuming later, read() or write() would have blocked.
534
535                                 if(gnutls_record_get_direction(session->sess) == 0)
536                                 {
537                                         // gnutls_handshake() wants to read() again.
538                                         session->status = ISSL_HANDSHAKING_READ;
539                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
540                                 }
541                                 else
542                                 {
543                                         // gnutls_handshake() wants to write() again.
544                                         session->status = ISSL_HANDSHAKING_WRITE;
545                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
546                                 }
547                         }
548                         else
549                         {
550                                 user->SetError(std::string("Handshake Failed - ") + gnutls_strerror(ret));
551                                 CloseSession(session);
552                                 session->status = ISSL_CLOSING;
553                         }
554
555                         return false;
556                 }
557                 else
558                 {
559                         // Change the seesion state
560                         session->status = ISSL_HANDSHAKEN;
561
562                         VerifyCertificate(session,user);
563
564                         // Finish writing, if any left
565                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
566
567                         return true;
568                 }
569         }
570
571         void OnUserConnect(LocalUser* user)
572         {
573                 if (user->eh.GetIOHook() == this)
574                 {
575                         if (sessions[user->eh.GetFd()].sess)
576                         {
577                                 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
578                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->eh.GetFd()].sess));
579                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->eh.GetFd()].sess))).append("-");
580                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->eh.GetFd()].sess)));
581                                 if (cert->fingerprint.empty())
582                                         user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
583                                 else
584                                         user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
585                                                 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
586                         }
587                 }
588         }
589
590         void CloseSession(issl_session* session)
591         {
592                 if (session->sess)
593                 {
594                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
595                         gnutls_deinit(session->sess);
596                 }
597                 session->sess = NULL;
598                 session->cert = NULL;
599                 session->status = ISSL_NONE;
600         }
601
602         void VerifyCertificate(issl_session* session, StreamSocket* user)
603         {
604                 if (!session->sess || !user || session->cert)
605                         return;
606
607                 unsigned int status;
608                 const gnutls_datum_t* cert_list;
609                 int ret;
610                 unsigned int cert_list_size;
611                 gnutls_x509_crt_t cert;
612                 char name[MAXBUF];
613                 unsigned char digest[MAXBUF];
614                 size_t digest_size = sizeof(digest);
615                 size_t name_size = sizeof(name);
616                 ssl_cert* certinfo = new ssl_cert;
617                 session->cert = certinfo;
618
619                 /* This verification function uses the trusted CAs in the credentials
620                  * structure. So you must have installed one or more CA certificates.
621                  */
622                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
623
624                 if (ret < 0)
625                 {
626                         certinfo->error = std::string(gnutls_strerror(ret));
627                         return;
628                 }
629
630                 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
631                 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
632                 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
633                 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
634
635                 /* Up to here the process is the same for X.509 certificates and
636                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
637                  * be easily extended to work with openpgp keys as well.
638                  */
639                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
640                 {
641                         certinfo->error = "No X509 keys sent";
642                         return;
643                 }
644
645                 ret = gnutls_x509_crt_init(&cert);
646                 if (ret < 0)
647                 {
648                         certinfo->error = gnutls_strerror(ret);
649                         return;
650                 }
651
652                 cert_list_size = 0;
653                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
654                 if (cert_list == NULL)
655                 {
656                         certinfo->error = "No certificate was found";
657                         goto info_done_dealloc;
658                 }
659
660                 /* This is not a real world example, since we only check the first
661                  * certificate in the given chain.
662                  */
663
664                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
665                 if (ret < 0)
666                 {
667                         certinfo->error = gnutls_strerror(ret);
668                         goto info_done_dealloc;
669                 }
670
671                 gnutls_x509_crt_get_dn(cert, name, &name_size);
672                 certinfo->dn = name;
673
674                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
675                 certinfo->issuer = name;
676
677                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
678                 {
679                         certinfo->error = gnutls_strerror(ret);
680                 }
681                 else
682                 {
683                         certinfo->fingerprint = irc::hex(digest, digest_size);
684                 }
685
686                 /* Beware here we do not check for errors.
687                  */
688                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
689                 {
690                         certinfo->error = "Not activated, or expired certificate";
691                 }
692
693 info_done_dealloc:
694                 gnutls_x509_crt_deinit(cert);
695         }
696
697         void OnEvent(Event& ev)
698         {
699                 capHandler.HandleEvent(ev);
700         }
701 };
702
703 MODULE_INIT(ModuleSSLGnuTLS)