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