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