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