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