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