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