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