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