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