]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Merge pull request #1071 from SaberUK/insp20+fix-lusers
[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 "ssl.h"
28 #include "m_cap.h"
29
30 #ifdef _WIN32
31 # pragma comment(lib, "libgnutls-30.lib")
32 #endif
33
34 /* $ModDesc: Provides SSL support for clients */
35 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") iflt("pkg-config --modversion gnutls","2.12") exec("libgcrypt-config --cflags") */
36 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") iflt("pkg-config --modversion gnutls","2.12") exec("libgcrypt-config --libs") */
37 /* $NoPedantic */
38
39 #ifndef GNUTLS_VERSION_MAJOR
40 #define GNUTLS_VERSION_MAJOR LIBGNUTLS_VERSION_MAJOR
41 #define GNUTLS_VERSION_MINOR LIBGNUTLS_VERSION_MINOR
42 #define GNUTLS_VERSION_PATCH LIBGNUTLS_VERSION_PATCH
43 #endif
44
45 // These don't exist in older GnuTLS versions
46 #if ((GNUTLS_VERSION_MAJOR > 2) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR > 1) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR == 1 && GNUTLS_VERSION_PATCH >= 7))
47 #define GNUTLS_NEW_PRIO_API
48 #endif
49
50 #if(GNUTLS_VERSION_MAJOR < 2)
51 typedef gnutls_certificate_credentials_t gnutls_certificate_credentials;
52 typedef gnutls_dh_params_t gnutls_dh_params;
53 #endif
54
55 #if (GNUTLS_VERSION_MAJOR > 2 || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR >= 12))
56 # define GNUTLS_HAS_RND
57 # include <gnutls/crypto.h>
58 #else
59 # include <gcrypt.h>
60 #endif
61
62 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
63
64 struct SSLConfig : public refcountbase
65 {
66         gnutls_certificate_credentials_t x509_cred;
67         std::vector<gnutls_x509_crt_t> x509_certs;
68         gnutls_x509_privkey_t x509_key;
69         gnutls_dh_params_t dh_params;
70 #ifdef GNUTLS_NEW_PRIO_API
71         gnutls_priority_t priority;
72 #endif
73
74         SSLConfig()
75                 : x509_cred(NULL)
76                 , x509_key(NULL)
77                 , dh_params(NULL)
78 #ifdef GNUTLS_NEW_PRIO_API
79                 , priority(NULL)
80 #endif
81         {
82         }
83
84         ~SSLConfig()
85         {
86                 ServerInstance->Logs->Log("m_ssl_gnutls", DEBUG, "Destroying SSLConfig %p", (void*)this);
87
88                 if (x509_cred)
89                         gnutls_certificate_free_credentials(x509_cred);
90
91                 for (unsigned int i = 0; i < x509_certs.size(); i++)
92                         gnutls_x509_crt_deinit(x509_certs[i]);
93
94                 if (x509_key)
95                         gnutls_x509_privkey_deinit(x509_key);
96
97                 if (dh_params)
98                         gnutls_dh_params_deinit(dh_params);
99
100 #ifdef GNUTLS_NEW_PRIO_API
101                 if (priority)
102                         gnutls_priority_deinit(priority);
103 #endif
104         }
105 };
106
107 static reference<SSLConfig> currconf;
108
109 static SSLConfig* GetSessionConfig(gnutls_session_t session);
110
111 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
112 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
113         const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
114
115         st->type = GNUTLS_CRT_X509;
116 #else
117 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
118         const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr2_st * st) {
119         st->cert_type = GNUTLS_CRT_X509;
120         st->key_type = GNUTLS_PRIVKEY_X509;
121 #endif
122         SSLConfig* conf = GetSessionConfig(session);
123         std::vector<gnutls_x509_crt_t>& x509_certs = conf->x509_certs;
124         st->ncerts = x509_certs.size();
125         st->cert.x509 = &x509_certs[0];
126         st->key.x509 = conf->x509_key;
127         st->deinit_all = 0;
128
129         return 0;
130 }
131
132 class RandGen : public HandlerBase2<void, char*, size_t>
133 {
134  public:
135         RandGen() {}
136         void Call(char* buffer, size_t len)
137         {
138 #ifdef GNUTLS_HAS_RND
139                 gnutls_rnd(GNUTLS_RND_RANDOM, buffer, len);
140 #else
141                 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
142 #endif
143         }
144 };
145
146 /** Represents an SSL user's extra data
147  */
148 class issl_session
149 {
150 public:
151         StreamSocket* socket;
152         gnutls_session_t sess;
153         issl_status status;
154         reference<ssl_cert> cert;
155         reference<SSLConfig> config;
156
157         issl_session() : socket(NULL), sess(NULL), status(ISSL_NONE) {}
158 };
159
160 static SSLConfig* GetSessionConfig(gnutls_session_t sess)
161 {
162         issl_session* session = reinterpret_cast<issl_session*>(gnutls_transport_get_ptr(sess));
163         return session->config;
164 }
165
166 class CommandStartTLS : public SplitCommand
167 {
168  public:
169         bool enabled;
170         CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
171         {
172                 enabled = true;
173                 works_before_reg = true;
174         }
175
176         CmdResult HandleLocal(const std::vector<std::string> &parameters, LocalUser *user)
177         {
178                 if (!enabled)
179                 {
180                         user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
181                         return CMD_FAILURE;
182                 }
183
184                 if (user->registered == REG_ALL)
185                 {
186                         user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
187                 }
188                 else
189                 {
190                         if (!user->eh.GetIOHook())
191                         {
192                                 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
193                                 /* We need to flush the write buffer prior to adding the IOHook,
194                                  * otherwise we'll be sending this line inside the SSL session - which
195                                  * won't start its handshake until the client gets this line. Currently,
196                                  * we assume the write will not block here; this is usually safe, as
197                                  * STARTTLS is sent very early on in the registration phase, where the
198                                  * user hasn't built up much sendq. Handling a blocked write here would
199                                  * be very annoying.
200                                  */
201                                 user->eh.DoWrite();
202                                 user->eh.AddIOHook(creator);
203                                 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
204                         }
205                         else
206                                 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
207                 }
208
209                 return CMD_FAILURE;
210         }
211 };
212
213 class ModuleSSLGnuTLS : public Module
214 {
215         issl_session* sessions;
216
217         gnutls_digest_algorithm_t hash;
218
219         std::string sslports;
220         int dh_bits;
221
222         RandGen randhandler;
223         CommandStartTLS starttls;
224
225         GenericCap capHandler;
226         ServiceProvider iohook;
227
228         inline static const char* UnknownIfNULL(const char* str)
229         {
230                 return str ? str : "UNKNOWN";
231         }
232
233         static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
234         {
235                 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
236                 if (session->socket->GetEventMask() & FD_READ_WILL_BLOCK)
237                 {
238 #ifdef _WIN32
239                         gnutls_transport_set_errno(session->sess, EAGAIN);
240 #else
241                         errno = EAGAIN;
242 #endif
243                         return -1;
244                 }
245
246                 int rv = ServerInstance->SE->Recv(session->socket, reinterpret_cast<char *>(buffer), size, 0);
247
248 #ifdef _WIN32
249                 if (rv < 0)
250                 {
251                         /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
252                          * and then set errno appropriately.
253                          * The gnutls library may also have a different errno variable than us, see
254                          * gnutls_transport_set_errno(3).
255                          */
256                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
257                 }
258 #endif
259
260                 if (rv < (int)size)
261                         ServerInstance->SE->ChangeEventMask(session->socket, FD_READ_WILL_BLOCK);
262                 return rv;
263         }
264
265         static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
266         {
267                 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
268                 if (session->socket->GetEventMask() & FD_WRITE_WILL_BLOCK)
269                 {
270 #ifdef _WIN32
271                         gnutls_transport_set_errno(session->sess, EAGAIN);
272 #else
273                         errno = EAGAIN;
274 #endif
275                         return -1;
276                 }
277
278                 int rv = ServerInstance->SE->Send(session->socket, reinterpret_cast<const char *>(buffer), size, 0);
279
280 #ifdef _WIN32
281                 if (rv < 0)
282                 {
283                         /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
284                          * and then set errno appropriately.
285                          * The gnutls library may also have a different errno variable than us, see
286                          * gnutls_transport_set_errno(3).
287                          */
288                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
289                 }
290 #endif
291
292                 if (rv < (int)size)
293                         ServerInstance->SE->ChangeEventMask(session->socket, FD_WRITE_WILL_BLOCK);
294                 return rv;
295         }
296
297  public:
298
299         ModuleSSLGnuTLS()
300                 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
301         {
302 #ifndef GNUTLS_HAS_RND
303                 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
304 #endif
305
306                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
307
308                 gnutls_global_init(); // This must be called once in the program
309         }
310
311         void init()
312         {
313                 currconf = new SSLConfig;
314                 InitSSLConfig(currconf);
315
316                 ServerInstance->GenRandom = &randhandler;
317
318                 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
319                         I_OnEvent, I_OnHookIO, I_OnCheckReady };
320                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
321
322                 ServerInstance->Modules->AddService(iohook);
323                 ServerInstance->Modules->AddService(starttls);
324         }
325
326         void OnRehash(User* user)
327         {
328                 sslports.clear();
329
330                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
331                 starttls.enabled = Conf->getBool("starttls", true);
332
333                 if (Conf->getBool("showports", true))
334                 {
335                         sslports = Conf->getString("advertisedports");
336                         if (!sslports.empty())
337                                 return;
338
339                         for (size_t i = 0; i < ServerInstance->ports.size(); i++)
340                         {
341                                 ListenSocket* port = ServerInstance->ports[i];
342                                 if (port->bind_tag->getString("ssl") != "gnutls")
343                                         continue;
344
345                                 const std::string& portid = port->bind_desc;
346                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
347
348                                 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
349                                 {
350                                         /*
351                                          * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
352                                          * the IP:port in ISUPPORT.
353                                          *
354                                          * We used to advertise all ports seperated by a ';' char that matched the above criteria,
355                                          * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
356                                          * To solve this by default we now only display the first IP:port found and let the user
357                                          * configure the exact value for the 005 token, if necessary.
358                                          */
359                                         sslports = portid;
360                                         break;
361                                 }
362                         }
363                 }
364         }
365
366         void OnModuleRehash(User* user, const std::string &param)
367         {
368                 if(param != "ssl")
369                         return;
370
371                 reference<SSLConfig> newconf = new SSLConfig;
372                 try
373                 {
374                         InitSSLConfig(newconf);
375                 }
376                 catch (ModuleException& ex)
377                 {
378                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls: Not applying new config. %s", ex.GetReason());
379                         return;
380                 }
381
382                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls: Applying new config, old config is in use by %d connection(s)", currconf->GetReferenceCount()-1);
383                 currconf = newconf;
384         }
385
386         void InitSSLConfig(SSLConfig* config)
387         {
388                 ServerInstance->Logs->Log("m_ssl_gnutls", DEBUG, "Initializing new SSLConfig %p", (void*)config);
389
390                 std::string keyfile;
391                 std::string certfile;
392                 std::string cafile;
393                 std::string crlfile;
394                 OnRehash(NULL);
395
396                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
397
398                 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
399                 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
400                 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
401                 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
402                 dh_bits = Conf->getInt("dhbits");
403                 std::string hashname = Conf->getString("hash", "md5");
404
405                 // The GnuTLS manual states that the gnutls_set_default_priority()
406                 // call we used previously when initializing the session is the same
407                 // as setting the "NORMAL" priority string.
408                 // Thus if the setting below is not in the config we will behave exactly
409                 // the same as before, when the priority setting wasn't available.
410                 std::string priorities = Conf->getString("priority", "NORMAL");
411
412                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
413                         dh_bits = 1024;
414
415                 if (hashname == "md5")
416                         hash = GNUTLS_DIG_MD5;
417                 else if (hashname == "sha1")
418                         hash = GNUTLS_DIG_SHA1;
419 #ifdef INSPIRCD_GNUTLS_ENABLE_SHA256_FINGERPRINT
420                 else if (hashname == "sha256")
421                         hash = GNUTLS_DIG_SHA256;
422 #endif
423                 else
424                         throw ModuleException("Unknown hash type " + hashname);
425
426
427                 int ret;
428
429                 gnutls_certificate_credentials_t& x509_cred = config->x509_cred;
430
431                 ret = gnutls_certificate_allocate_credentials(&x509_cred);
432                 if (ret < 0)
433                 {
434                         // Set to NULL because we can't be sure what value is in it and we must not try to
435                         // deallocate it in case of an error
436                         x509_cred = NULL;
437                         throw ModuleException("Failed to allocate certificate credentials: " + std::string(gnutls_strerror(ret)));
438                 }
439
440                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
441                         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));
442
443                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
444                         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));
445
446                 FileReader reader;
447
448                 reader.LoadFile(certfile);
449                 std::string cert_string = reader.Contents();
450                 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
451
452                 reader.LoadFile(keyfile);
453                 std::string key_string = reader.Contents();
454                 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
455
456                 std::vector<gnutls_x509_crt_t>& x509_certs = config->x509_certs;
457
458                 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
459                 unsigned int certcount = 3;
460                 x509_certs.resize(certcount);
461                 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
462                 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
463                 {
464                         // the buffer wasn't big enough to hold all certs but gnutls updated certcount to the number of available certs, try again with a bigger buffer
465                         x509_certs.resize(certcount);
466                         ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
467                 }
468
469                 if (ret <= 0)
470                 {
471                         // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later
472                         x509_certs.clear();
473                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read"));
474                 }
475                 x509_certs.resize(ret);
476
477                 gnutls_x509_privkey_t& x509_key = config->x509_key;
478                 if (gnutls_x509_privkey_init(&x509_key) < 0)
479                 {
480                         // Make sure the destructor does not try to deallocate this, see above
481                         x509_key = NULL;
482                         throw ModuleException("Unable to initialize private key");
483                 }
484
485                 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
486                         throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
487
488                 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
489                         throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
490
491                 #ifdef GNUTLS_NEW_PRIO_API
492                 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
493                 // If the user did not supply anything then the string is already set to "NORMAL"
494                 const char* priocstr = priorities.c_str();
495                 const char* prioerror;
496
497                 gnutls_priority_t& priority = config->priority;
498                 if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0)
499                 {
500                         // gnutls did not understand the user supplied string, log and fall back to the default priorities
501                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set priorities to \"%s\": %s Syntax error at position %u, falling back to default (NORMAL)", priorities.c_str(), gnutls_strerror(ret), (unsigned int) (prioerror - priocstr));
502                         gnutls_priority_init(&priority, "NORMAL", NULL);
503                 }
504
505                 #else
506                 if (priorities != "NORMAL")
507                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: You've set <gnutls:priority> to a value other than the default, but this is only supported with GnuTLS v2.1.7 or newer. Your GnuTLS version is older than that so the option will have no effect.");
508                 #endif
509
510                 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
511                 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
512                 #else
513                 gnutls_certificate_set_retrieve_function (x509_cred, cert_callback);
514                 #endif
515
516                 gnutls_dh_params_t& dh_params = config->dh_params;
517                 ret = gnutls_dh_params_init(&dh_params);
518                 if (ret < 0)
519                 {
520                         // Make sure the destructor does not try to deallocate this, see above
521                         dh_params = NULL;
522                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
523                         return;
524                 }
525
526                 std::string dhfile = Conf->getString("dhfile");
527                 if (!dhfile.empty())
528                 {
529                         // Try to load DH params from file
530                         reader.LoadFile(dhfile);
531                         std::string dhstring = reader.Contents();
532                         gnutls_datum_t dh_datum = { (unsigned char*)dhstring.data(), static_cast<unsigned int>(dhstring.length()) };
533
534                         if ((ret = gnutls_dh_params_import_pkcs3(dh_params, &dh_datum, GNUTLS_X509_FMT_PEM)) < 0)
535                         {
536                                 // File unreadable or GnuTLS was unhappy with the contents, generate the DH primes now
537                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Generating DH parameters because I failed to load them from file '%s': %s", dhfile.c_str(), gnutls_strerror(ret));
538                                 GenerateDHParams(dh_params);
539                         }
540                 }
541                 else
542                 {
543                         GenerateDHParams(dh_params);
544                 }
545
546                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
547         }
548
549         void GenerateDHParams(gnutls_dh_params_t dh_params)
550         {
551                 // Generate Diffie Hellman parameters - for use with DHE
552                 // kx algorithms. These should be discarded and regenerated
553                 // once a day, once a week or once a month. Depending on the
554                 // security requirements.
555
556                 int ret;
557
558                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
559                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
560         }
561
562         ~ModuleSSLGnuTLS()
563         {
564                 currconf = NULL;
565
566                 gnutls_global_deinit();
567                 delete[] sessions;
568                 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
569         }
570
571         void OnCleanup(int target_type, void* item)
572         {
573                 if(target_type == TYPE_USER)
574                 {
575                         LocalUser* user = IS_LOCAL(static_cast<User*>(item));
576
577                         if (user && user->eh.GetIOHook() == this)
578                         {
579                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
580                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
581                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
582                         }
583                 }
584         }
585
586         Version GetVersion()
587         {
588                 return Version("Provides SSL support for clients", VF_VENDOR);
589         }
590
591
592         void On005Numeric(std::string &output)
593         {
594                 if (!sslports.empty())
595                         output.append(" SSL=" + sslports);
596                 if (starttls.enabled)
597                         output.append(" STARTTLS");
598         }
599
600         void OnHookIO(StreamSocket* user, ListenSocket* lsb)
601         {
602                 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
603                 {
604                         /* Hook the user with our module */
605                         user->AddIOHook(this);
606                 }
607         }
608
609         void OnRequest(Request& request)
610         {
611                 if (strcmp("GET_SSL_CERT", request.id) == 0)
612                 {
613                         SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
614                         int fd = req.sock->GetFd();
615                         issl_session* session = &sessions[fd];
616
617                         req.cert = session->cert;
618                 }
619                 else if (!strcmp("GET_RAW_SSL_SESSION", request.id))
620                 {
621                         SSLRawSessionRequest& req = static_cast<SSLRawSessionRequest&>(request);
622                         if ((req.fd >= 0) && (req.fd < ServerInstance->SE->GetMaxFds()))
623                                 req.data = reinterpret_cast<void*>(sessions[req.fd].sess);
624                 }
625         }
626
627         void InitSession(StreamSocket* user, bool me_server)
628         {
629                 issl_session* session = &sessions[user->GetFd()];
630
631                 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
632                 session->socket = user;
633                 session->config = currconf;
634
635                 #ifdef GNUTLS_NEW_PRIO_API
636                 gnutls_priority_set(session->sess, currconf->priority);
637                 #else
638                 gnutls_set_default_priority(session->sess);
639                 #endif
640                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, currconf->x509_cred);
641                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
642                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(session));
643                 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
644                 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
645
646                 if (me_server)
647                         gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
648
649                 Handshake(session, user);
650         }
651
652         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
653         {
654                 issl_session* session = &sessions[user->GetFd()];
655
656                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
657                 if (session->sess)
658                         return;
659
660                 InitSession(user, true);
661         }
662
663         void OnStreamSocketConnect(StreamSocket* user)
664         {
665                 InitSession(user, false);
666         }
667
668         void OnStreamSocketClose(StreamSocket* user)
669         {
670                 CloseSession(&sessions[user->GetFd()]);
671         }
672
673         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
674         {
675                 issl_session* session = &sessions[user->GetFd()];
676
677                 if (!session->sess)
678                 {
679                         CloseSession(session);
680                         user->SetError("No SSL session");
681                         return -1;
682                 }
683
684                 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
685                 {
686                         // The handshake isn't finished, try to finish it.
687
688                         if(!Handshake(session, user))
689                         {
690                                 if (session->status != ISSL_CLOSING)
691                                         return 0;
692                                 return -1;
693                         }
694                 }
695
696                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
697
698                 if (session->status == ISSL_HANDSHAKEN)
699                 {
700                         char* buffer = ServerInstance->GetReadBuffer();
701                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
702                         int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
703                         if (ret > 0)
704                         {
705                                 recvq.append(buffer, ret);
706                                 return 1;
707                         }
708                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
709                         {
710                                 return 0;
711                         }
712                         else if (ret == 0)
713                         {
714                                 user->SetError("Connection closed");
715                                 CloseSession(session);
716                                 return -1;
717                         }
718                         else
719                         {
720                                 user->SetError(gnutls_strerror(ret));
721                                 CloseSession(session);
722                                 return -1;
723                         }
724                 }
725                 else if (session->status == ISSL_CLOSING)
726                         return -1;
727
728                 return 0;
729         }
730
731         int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
732         {
733                 issl_session* session = &sessions[user->GetFd()];
734
735                 if (!session->sess)
736                 {
737                         CloseSession(session);
738                         user->SetError("No SSL session");
739                         return -1;
740                 }
741
742                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
743                 {
744                         // The handshake isn't finished, try to finish it.
745                         Handshake(session, user);
746                         if (session->status != ISSL_CLOSING)
747                                 return 0;
748                         return -1;
749                 }
750
751                 int ret = 0;
752
753                 if (session->status == ISSL_HANDSHAKEN)
754                 {
755                         ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
756
757                         if (ret == (int)sendq.length())
758                         {
759                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
760                                 return 1;
761                         }
762                         else if (ret > 0)
763                         {
764                                 sendq = sendq.substr(ret);
765                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
766                                 return 0;
767                         }
768                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
769                         {
770                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
771                                 return 0;
772                         }
773                         else // (ret < 0)
774                         {
775                                 user->SetError(gnutls_strerror(ret));
776                                 CloseSession(session);
777                                 return -1;
778                         }
779                 }
780
781                 return 0;
782         }
783
784         bool Handshake(issl_session* session, StreamSocket* user)
785         {
786                 int ret = gnutls_handshake(session->sess);
787
788                 if (ret < 0)
789                 {
790                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
791                         {
792                                 // Handshake needs resuming later, read() or write() would have blocked.
793
794                                 if(gnutls_record_get_direction(session->sess) == 0)
795                                 {
796                                         // gnutls_handshake() wants to read() again.
797                                         session->status = ISSL_HANDSHAKING_READ;
798                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
799                                 }
800                                 else
801                                 {
802                                         // gnutls_handshake() wants to write() again.
803                                         session->status = ISSL_HANDSHAKING_WRITE;
804                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
805                                 }
806                         }
807                         else
808                         {
809                                 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
810                                 CloseSession(session);
811                                 session->status = ISSL_CLOSING;
812                         }
813
814                         return false;
815                 }
816                 else
817                 {
818                         // Change the seesion state
819                         session->status = ISSL_HANDSHAKEN;
820
821                         VerifyCertificate(session,user);
822
823                         // Finish writing, if any left
824                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
825
826                         return true;
827                 }
828         }
829
830         void OnUserConnect(LocalUser* user)
831         {
832                 if (user->eh.GetIOHook() == this)
833                 {
834                         if (sessions[user->eh.GetFd()].sess)
835                         {
836                                 const gnutls_session_t& sess = sessions[user->eh.GetFd()].sess;
837                                 std::string cipher = UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)));
838                                 cipher.append("-").append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).append("-");
839                                 cipher.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
840
841                                 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
842                                 if (cert->fingerprint.empty())
843                                         user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
844                                 else
845                                         user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
846                                                 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
847                         }
848                 }
849         }
850
851         void CloseSession(issl_session* session)
852         {
853                 if (session->sess)
854                 {
855                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
856                         gnutls_deinit(session->sess);
857                 }
858                 session->socket = NULL;
859                 session->sess = NULL;
860                 session->cert = NULL;
861                 session->status = ISSL_NONE;
862                 session->config = NULL;
863         }
864
865         void VerifyCertificate(issl_session* session, StreamSocket* user)
866         {
867                 if (!session->sess || !user)
868                         return;
869
870                 unsigned int status;
871                 const gnutls_datum_t* cert_list;
872                 int ret;
873                 unsigned int cert_list_size;
874                 gnutls_x509_crt_t cert;
875                 char name[MAXBUF];
876                 unsigned char digest[MAXBUF];
877                 size_t digest_size = sizeof(digest);
878                 size_t name_size = sizeof(name);
879                 ssl_cert* certinfo = new ssl_cert;
880                 session->cert = certinfo;
881
882                 /* This verification function uses the trusted CAs in the credentials
883                  * structure. So you must have installed one or more CA certificates.
884                  */
885                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
886
887                 if (ret < 0)
888                 {
889                         certinfo->error = std::string(gnutls_strerror(ret));
890                         return;
891                 }
892
893                 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
894                 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
895                 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
896                 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
897
898                 /* Up to here the process is the same for X.509 certificates and
899                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
900                  * be easily extended to work with openpgp keys as well.
901                  */
902                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
903                 {
904                         certinfo->error = "No X509 keys sent";
905                         return;
906                 }
907
908                 ret = gnutls_x509_crt_init(&cert);
909                 if (ret < 0)
910                 {
911                         certinfo->error = gnutls_strerror(ret);
912                         return;
913                 }
914
915                 cert_list_size = 0;
916                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
917                 if (cert_list == NULL)
918                 {
919                         certinfo->error = "No certificate was found";
920                         goto info_done_dealloc;
921                 }
922
923                 /* This is not a real world example, since we only check the first
924                  * certificate in the given chain.
925                  */
926
927                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
928                 if (ret < 0)
929                 {
930                         certinfo->error = gnutls_strerror(ret);
931                         goto info_done_dealloc;
932                 }
933
934                 if (gnutls_x509_crt_get_dn(cert, name, &name_size) == 0)
935                 {
936                         std::string& dn = certinfo->dn;
937                         dn = name;
938                         // Make sure there are no chars in the string that we consider invalid
939                         if (dn.find_first_of("\r\n") != std::string::npos)
940                                 dn.clear();
941                 }
942
943                 name_size = sizeof(name);
944                 if (gnutls_x509_crt_get_issuer_dn(cert, name, &name_size) == 0)
945                 {
946                         std::string& issuer = certinfo->issuer;
947                         issuer = name;
948                         if (issuer.find_first_of("\r\n") != std::string::npos)
949                                 issuer.clear();
950                 }
951
952                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
953                 {
954                         certinfo->error = gnutls_strerror(ret);
955                 }
956                 else
957                 {
958                         certinfo->fingerprint = irc::hex(digest, digest_size);
959                 }
960
961                 /* Beware here we do not check for errors.
962                  */
963                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
964                 {
965                         certinfo->error = "Not activated, or expired certificate";
966                 }
967
968 info_done_dealloc:
969                 gnutls_x509_crt_deinit(cert);
970         }
971
972         void OnEvent(Event& ev)
973         {
974                 if (starttls.enabled)
975                         capHandler.HandleEvent(ev);
976         }
977
978         ModResult OnCheckReady(LocalUser* user)
979         {
980                 if ((user->eh.GetIOHook() == this) && (sessions[user->eh.GetFd()].status != ISSL_HANDSHAKEN))
981                         return MOD_RES_DENY;
982                 return MOD_RES_PASSTHRU;
983         }
984 };
985
986 MODULE_INIT(ModuleSSLGnuTLS)