]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
26c24ac7080a3f5deebf88df4550957ddbeec7ae
[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 /// $CompilerFlags: find_compiler_flags("gnutls")
24 /// $CompilerFlags: require_version("gnutls" "1.0" "2.12") execute("libgcrypt-config --cflags" "LIBGCRYPT_CXXFLAGS")
25
26 /// $LinkerFlags: find_linker_flags("gnutls" "-lgnutls")
27 /// $LinkerFlags: require_version("gnutls" "1.0" "2.12") execute("libgcrypt-config --libs" "LIBGCRYPT_LDFLAGS")
28
29 /// $PackageInfo: require_system("arch") gnutls pkgconf
30 /// $PackageInfo: require_system("centos") gnutls-devel pkgconfig
31 /// $PackageInfo: require_system("darwin") gnutls pkg-config
32 /// $PackageInfo: require_system("debian" "1.0" "7.99") libgcrypt11-dev
33 /// $PackageInfo: require_system("debian") gnutls-bin libgnutls28-dev pkg-config
34 /// $PackageInfo: require_system("ubuntu" "1.0" "13.10") libgcrypt11-dev
35 /// $PackageInfo: require_system("ubuntu") gnutls-bin libgnutls-dev pkg-config
36
37 #include "inspircd.h"
38 #include "modules/ssl.h"
39 #include <memory>
40
41 #ifdef __GNUC__
42 # pragma GCC diagnostic push
43 #endif
44
45 // Fix warnings about the use of commas at end of enumerator lists on C++03.
46 #if defined __clang__
47 # pragma clang diagnostic ignored "-Wc++11-extensions"
48 #elif defined __GNUC__
49 # if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))
50 #  pragma GCC diagnostic ignored "-Wpedantic"
51 # else
52 #  pragma GCC diagnostic ignored "-pedantic"
53 # endif
54 #endif
55
56 // Fix warnings about using std::auto_ptr on C++11 or newer.
57 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
58
59 #include <gnutls/gnutls.h>
60 #include <gnutls/x509.h>
61
62 #ifdef __GNUC__
63 # pragma GCC diagnostic pop
64 #endif
65
66 #ifndef GNUTLS_VERSION_NUMBER
67 #define GNUTLS_VERSION_NUMBER LIBGNUTLS_VERSION_NUMBER
68 #define GNUTLS_VERSION LIBGNUTLS_VERSION
69 #endif
70
71 // Check if the GnuTLS library is at least version major.minor.patch
72 #define INSPIRCD_GNUTLS_HAS_VERSION(major, minor, patch) (GNUTLS_VERSION_NUMBER >= ((major << 16) | (minor << 8) | patch))
73
74 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 9, 8)
75 #define GNUTLS_HAS_MAC_GET_ID
76 #include <gnutls/crypto.h>
77 #endif
78
79 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 12, 0)
80 # define GNUTLS_HAS_RND
81 #else
82 # include <gcrypt.h>
83 #endif
84
85 #ifdef _WIN32
86 # pragma comment(lib, "libgnutls-30.lib")
87 #endif
88
89 // These don't exist in older GnuTLS versions
90 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 1, 7)
91 #define GNUTLS_NEW_PRIO_API
92 #endif
93
94 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_HANDSHAKEN };
95
96 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 12, 0)
97 #define INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
98 #define GNUTLS_NEW_CERT_CALLBACK_API
99 typedef gnutls_retr2_st cert_cb_last_param_type;
100 #else
101 typedef gnutls_retr_st cert_cb_last_param_type;
102 #endif
103
104 #if INSPIRCD_GNUTLS_HAS_VERSION(3, 3, 5)
105 #define INSPIRCD_GNUTLS_HAS_RECV_PACKET
106 #endif
107
108 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 99, 0)
109 // The second parameter of gnutls_init() has changed in 2.99.0 from gnutls_connection_end_t to unsigned int
110 // (it became a general flags parameter) and the enum has been deprecated and generates a warning on use.
111 typedef unsigned int inspircd_gnutls_session_init_flags_t;
112 #else
113 typedef gnutls_connection_end_t inspircd_gnutls_session_init_flags_t;
114 #endif
115
116 #if INSPIRCD_GNUTLS_HAS_VERSION(3, 1, 9)
117 #define INSPIRCD_GNUTLS_HAS_CORK
118 #endif
119
120 static Module* thismod;
121
122 class RandGen
123 {
124  public:
125         static void Call(char* buffer, size_t len)
126         {
127 #ifdef GNUTLS_HAS_RND
128                 gnutls_rnd(GNUTLS_RND_RANDOM, buffer, len);
129 #else
130                 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
131 #endif
132         }
133 };
134
135 namespace GnuTLS
136 {
137         class Init
138         {
139          public:
140                 Init() { gnutls_global_init(); }
141                 ~Init() { gnutls_global_deinit(); }
142         };
143
144         class Exception : public ModuleException
145         {
146          public:
147                 Exception(const std::string& reason)
148                         : ModuleException(reason) { }
149         };
150
151         void ThrowOnError(int errcode, const char* msg)
152         {
153                 if (errcode < 0)
154                 {
155                         std::string reason = msg;
156                         reason.append(" :").append(gnutls_strerror(errcode));
157                         throw Exception(reason);
158                 }
159         }
160
161         /** Used to create a gnutls_datum_t* from a std::string
162          */
163         class Datum
164         {
165                 gnutls_datum_t datum;
166
167          public:
168                 Datum(const std::string& dat)
169                 {
170                         datum.data = (unsigned char*)dat.data();
171                         datum.size = static_cast<unsigned int>(dat.length());
172                 }
173
174                 const gnutls_datum_t* get() const { return &datum; }
175         };
176
177         class Hash
178         {
179                 gnutls_digest_algorithm_t hash;
180
181          public:
182                 // Nothing to deallocate, constructor may throw freely
183                 Hash(const std::string& hashname)
184                 {
185                         // As older versions of gnutls can't do this, let's disable it where needed.
186 #ifdef GNUTLS_HAS_MAC_GET_ID
187                         // As gnutls_digest_algorithm_t and gnutls_mac_algorithm_t are mapped 1:1, we can do this
188                         // There is no gnutls_dig_get_id() at the moment, but it may come later
189                         hash = (gnutls_digest_algorithm_t)gnutls_mac_get_id(hashname.c_str());
190                         if (hash == GNUTLS_DIG_UNKNOWN)
191                                 throw Exception("Unknown hash type " + hashname);
192
193                         // Check if the user is giving us something that is a valid MAC but not digest
194                         gnutls_hash_hd_t is_digest;
195                         if (gnutls_hash_init(&is_digest, hash) < 0)
196                                 throw Exception("Unknown hash type " + hashname);
197                         gnutls_hash_deinit(is_digest, NULL);
198 #else
199                         if (stdalgo::string::equalsci(hashname, "md5"))
200                                 hash = GNUTLS_DIG_MD5;
201                         else if (stdalgo::string::equalsci(hashname, "sha1"))
202                                 hash = GNUTLS_DIG_SHA1;
203                         else if (stdalgo::string::equalsci(hashname, "sha256"))
204                                 hash = GNUTLS_DIG_SHA256;
205                         else
206                                 throw Exception("Unknown hash type " + hashname);
207 #endif
208                 }
209
210                 gnutls_digest_algorithm_t get() const { return hash; }
211         };
212
213         class DHParams
214         {
215                 gnutls_dh_params_t dh_params;
216
217                 DHParams()
218                 {
219                         ThrowOnError(gnutls_dh_params_init(&dh_params), "gnutls_dh_params_init() failed");
220                 }
221
222          public:
223                 /** Import */
224                 static std::auto_ptr<DHParams> Import(const std::string& dhstr)
225                 {
226                         std::auto_ptr<DHParams> dh(new DHParams);
227                         int ret = gnutls_dh_params_import_pkcs3(dh->dh_params, Datum(dhstr).get(), GNUTLS_X509_FMT_PEM);
228                         ThrowOnError(ret, "Unable to import DH params");
229                         return dh;
230                 }
231
232                 ~DHParams()
233                 {
234                         gnutls_dh_params_deinit(dh_params);
235                 }
236
237                 const gnutls_dh_params_t& get() const { return dh_params; }
238         };
239
240         class X509Key
241         {
242                 /** Ensure that the key is deinited in case the constructor of X509Key throws
243                  */
244                 class RAIIKey
245                 {
246                  public:
247                         gnutls_x509_privkey_t key;
248
249                         RAIIKey()
250                         {
251                                 ThrowOnError(gnutls_x509_privkey_init(&key), "gnutls_x509_privkey_init() failed");
252                         }
253
254                         ~RAIIKey()
255                         {
256                                 gnutls_x509_privkey_deinit(key);
257                         }
258                 } key;
259
260          public:
261                 /** Import */
262                 X509Key(const std::string& keystr)
263                 {
264                         int ret = gnutls_x509_privkey_import(key.key, Datum(keystr).get(), GNUTLS_X509_FMT_PEM);
265                         ThrowOnError(ret, "Unable to import private key");
266                 }
267
268                 gnutls_x509_privkey_t& get() { return key.key; }
269         };
270
271         class X509CertList
272         {
273                 std::vector<gnutls_x509_crt_t> certs;
274
275          public:
276                 /** Import */
277                 X509CertList(const std::string& certstr)
278                 {
279                         unsigned int certcount = 3;
280                         certs.resize(certcount);
281                         Datum datum(certstr);
282
283                         int ret = gnutls_x509_crt_list_import(raw(), &certcount, datum.get(), GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
284                         if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
285                         {
286                                 // the buffer wasn't big enough to hold all certs but gnutls changed certcount to the number of available certs,
287                                 // try again with a bigger buffer
288                                 certs.resize(certcount);
289                                 ret = gnutls_x509_crt_list_import(raw(), &certcount, datum.get(), GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
290                         }
291
292                         ThrowOnError(ret, "Unable to load certificates");
293
294                         // Resize the vector to the actual number of certs because we rely on its size being correct
295                         // when deallocating the certs
296                         certs.resize(certcount);
297                 }
298
299                 ~X509CertList()
300                 {
301                         for (std::vector<gnutls_x509_crt_t>::iterator i = certs.begin(); i != certs.end(); ++i)
302                                 gnutls_x509_crt_deinit(*i);
303                 }
304
305                 gnutls_x509_crt_t* raw() { return &certs[0]; }
306                 unsigned int size() const { return certs.size(); }
307         };
308
309         class X509CRL : public refcountbase
310         {
311                 class RAIICRL
312                 {
313                  public:
314                         gnutls_x509_crl_t crl;
315
316                         RAIICRL()
317                         {
318                                 ThrowOnError(gnutls_x509_crl_init(&crl), "gnutls_x509_crl_init() failed");
319                         }
320
321                         ~RAIICRL()
322                         {
323                                 gnutls_x509_crl_deinit(crl);
324                         }
325                 } crl;
326
327          public:
328                 /** Import */
329                 X509CRL(const std::string& crlstr)
330                 {
331                         int ret = gnutls_x509_crl_import(get(), Datum(crlstr).get(), GNUTLS_X509_FMT_PEM);
332                         ThrowOnError(ret, "Unable to load certificate revocation list");
333                 }
334
335                 gnutls_x509_crl_t& get() { return crl.crl; }
336         };
337
338 #ifdef GNUTLS_NEW_PRIO_API
339         class Priority
340         {
341                 gnutls_priority_t priority;
342
343          public:
344                 Priority(const std::string& priorities)
345                 {
346                         // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
347                         // If the user did not supply anything then the string is already set to "NORMAL"
348                         const char* priocstr = priorities.c_str();
349                         const char* prioerror;
350
351                         int ret = gnutls_priority_init(&priority, priocstr, &prioerror);
352                         if (ret < 0)
353                         {
354                                 // gnutls did not understand the user supplied string
355                                 throw Exception("Unable to initialize priorities to \"" + priorities + "\": " + gnutls_strerror(ret) + " Syntax error at position " + ConvToStr((unsigned int) (prioerror - priocstr)));
356                         }
357                 }
358
359                 ~Priority()
360                 {
361                         gnutls_priority_deinit(priority);
362                 }
363
364                 void SetupSession(gnutls_session_t sess)
365                 {
366                         gnutls_priority_set(sess, priority);
367                 }
368
369                 static const char* GetDefault()
370                 {
371                         return "NORMAL:%SERVER_PRECEDENCE:-VERS-SSL3.0";
372                 }
373
374                 static std::string RemoveUnknownTokens(const std::string& prio)
375                 {
376                         std::string ret;
377                         irc::sepstream ss(prio, ':');
378                         for (std::string token; ss.GetToken(token); )
379                         {
380                                 // Save current position so we can revert later if needed
381                                 const std::string::size_type prevpos = ret.length();
382                                 // Append next token
383                                 if (!ret.empty())
384                                         ret.push_back(':');
385                                 ret.append(token);
386
387                                 gnutls_priority_t test;
388                                 if (gnutls_priority_init(&test, ret.c_str(), NULL) < 0)
389                                 {
390                                         // The new token broke the priority string, revert to the previously working one
391                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Priority string token not recognized: \"%s\"", token.c_str());
392                                         ret.erase(prevpos);
393                                 }
394                                 else
395                                 {
396                                         // Worked
397                                         gnutls_priority_deinit(test);
398                                 }
399                         }
400                         return ret;
401                 }
402         };
403 #else
404         /** Dummy class, used when gnutls_priority_set() is not available
405          */
406         class Priority
407         {
408          public:
409                 Priority(const std::string& priorities)
410                 {
411                         if (priorities != GetDefault())
412                                 throw Exception("You've set a non-default priority string, but GnuTLS lacks support for it");
413                 }
414
415                 static void SetupSession(gnutls_session_t sess)
416                 {
417                         // Always set the default priorities
418                         gnutls_set_default_priority(sess);
419                 }
420
421                 static const char* GetDefault()
422                 {
423                         return "NORMAL";
424                 }
425
426                 static std::string RemoveUnknownTokens(const std::string& prio)
427                 {
428                         // We don't do anything here because only NORMAL is accepted
429                         return prio;
430                 }
431         };
432 #endif
433
434         class CertCredentials
435         {
436                 /** DH parameters associated with these credentials
437                  */
438                 std::auto_ptr<DHParams> dh;
439
440          protected:
441                 gnutls_certificate_credentials_t cred;
442
443          public:
444                 CertCredentials()
445                 {
446                         ThrowOnError(gnutls_certificate_allocate_credentials(&cred), "Cannot allocate certificate credentials");
447                 }
448
449                 ~CertCredentials()
450                 {
451                         gnutls_certificate_free_credentials(cred);
452                 }
453
454                 /** Associates these credentials with the session
455                  */
456                 void SetupSession(gnutls_session_t sess)
457                 {
458                         gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, cred);
459                 }
460
461                 /** Set the given DH parameters to be used with these credentials
462                  */
463                 void SetDH(std::auto_ptr<DHParams>& DH)
464                 {
465                         dh = DH;
466                         gnutls_certificate_set_dh_params(cred, dh->get());
467                 }
468         };
469
470         class X509Credentials : public CertCredentials
471         {
472                 /** Private key
473                  */
474                 X509Key key;
475
476                 /** Certificate list, presented to the peer
477                  */
478                 X509CertList certs;
479
480                 /** Trusted CA, may be NULL
481                  */
482                 std::auto_ptr<X509CertList> trustedca;
483
484                 /** Certificate revocation list, may be NULL
485                  */
486                 std::auto_ptr<X509CRL> crl;
487
488                 static int cert_callback(gnutls_session_t session, const gnutls_datum_t* req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t* sign_algos, int sign_algos_length, cert_cb_last_param_type* st);
489
490          public:
491                 X509Credentials(const std::string& certstr, const std::string& keystr)
492                         : key(keystr)
493                         , certs(certstr)
494                 {
495                         // Throwing is ok here, the destructor of Credentials is called in that case
496                         int ret = gnutls_certificate_set_x509_key(cred, certs.raw(), certs.size(), key.get());
497                         ThrowOnError(ret, "Unable to set cert/key pair");
498
499 #ifdef GNUTLS_NEW_CERT_CALLBACK_API
500                         gnutls_certificate_set_retrieve_function(cred, cert_callback);
501 #else
502                         gnutls_certificate_client_set_retrieve_function(cred, cert_callback);
503 #endif
504                 }
505
506                 /** Sets the trusted CA and the certificate revocation list
507                  * to use when verifying certificates
508                  */
509                 void SetCA(std::auto_ptr<X509CertList>& certlist, std::auto_ptr<X509CRL>& CRL)
510                 {
511                         // Do nothing if certlist is NULL
512                         if (certlist.get())
513                         {
514                                 int ret = gnutls_certificate_set_x509_trust(cred, certlist->raw(), certlist->size());
515                                 ThrowOnError(ret, "gnutls_certificate_set_x509_trust() failed");
516
517                                 if (CRL.get())
518                                 {
519                                         ret = gnutls_certificate_set_x509_crl(cred, &CRL->get(), 1);
520                                         ThrowOnError(ret, "gnutls_certificate_set_x509_crl() failed");
521                                 }
522
523                                 trustedca = certlist;
524                                 crl = CRL;
525                         }
526                 }
527         };
528
529         class DataReader
530         {
531                 int retval;
532 #ifdef INSPIRCD_GNUTLS_HAS_RECV_PACKET
533                 gnutls_packet_t packet;
534
535          public:
536                 DataReader(gnutls_session_t sess)
537                 {
538                         // Using the packet API avoids the final copy of the data which GnuTLS does if we supply
539                         // our own buffer. Instead, we get the buffer containing the data from GnuTLS and copy it
540                         // to the recvq directly from there in appendto().
541                         retval = gnutls_record_recv_packet(sess, &packet);
542                 }
543
544                 void appendto(std::string& recvq)
545                 {
546                         // Copy data from GnuTLS buffers to recvq
547                         gnutls_datum_t datum;
548                         gnutls_packet_get(packet, &datum, NULL);
549                         recvq.append(reinterpret_cast<const char*>(datum.data), datum.size);
550
551                         gnutls_packet_deinit(packet);
552                 }
553 #else
554                 char* const buffer;
555
556          public:
557                 DataReader(gnutls_session_t sess)
558                         : buffer(ServerInstance->GetReadBuffer())
559                 {
560                         // Read data from GnuTLS buffers into ReadBuffer
561                         retval = gnutls_record_recv(sess, buffer, ServerInstance->Config->NetBufferSize);
562                 }
563
564                 void appendto(std::string& recvq)
565                 {
566                         // Copy data from ReadBuffer to recvq
567                         recvq.append(buffer, retval);
568                 }
569 #endif
570
571                 int ret() const { return retval; }
572         };
573
574         class Profile
575         {
576                 /** Name of this profile
577                  */
578                 const std::string name;
579
580                 /** X509 certificate(s) and key
581                  */
582                 X509Credentials x509cred;
583
584                 /** The minimum length in bits for the DH prime to be accepted as a client
585                  */
586                 unsigned int min_dh_bits;
587
588                 /** Hashing algorithm to use when generating certificate fingerprints
589                  */
590                 Hash hash;
591
592                 /** Priorities for ciphers, compression methods, etc.
593                  */
594                 Priority priority;
595
596                 /** Rough max size of records to send
597                  */
598                 const unsigned int outrecsize;
599
600                 /** True to request a client certificate as a server
601                  */
602                 const bool requestclientcert;
603
604                 static std::string ReadFile(const std::string& filename)
605                 {
606                         FileReader reader(filename);
607                         std::string ret = reader.GetString();
608                         if (ret.empty())
609                                 throw Exception("Cannot read file " + filename);
610                         return ret;
611                 }
612
613                 static std::string GetPrioStr(const std::string& profilename, ConfigTag* tag)
614                 {
615                         // Use default priority string if this tag does not specify one
616                         std::string priostr = GnuTLS::Priority::GetDefault();
617                         bool found = tag->readString("priority", priostr);
618                         // If the prio string isn't set in the config don't be strict about the default one because it doesn't work on all versions of GnuTLS
619                         if (!tag->getBool("strictpriority", found))
620                         {
621                                 std::string stripped = GnuTLS::Priority::RemoveUnknownTokens(priostr);
622                                 if (stripped.empty())
623                                 {
624                                         // Stripping failed, act as if a prio string wasn't set
625                                         stripped = GnuTLS::Priority::RemoveUnknownTokens(GnuTLS::Priority::GetDefault());
626                                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Priority string for profile \"%s\" contains unknown tokens and stripping it didn't yield a working one either, falling back to \"%s\"", profilename.c_str(), stripped.c_str());
627                                 }
628                                 else if ((found) && (stripped != priostr))
629                                 {
630                                         // Prio string was set in the config and we ended up with something that works but different
631                                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Priority string for profile \"%s\" contains unknown tokens, stripped to \"%s\"", profilename.c_str(), stripped.c_str());
632                                 }
633                                 priostr.swap(stripped);
634                         }
635                         return priostr;
636                 }
637
638          public:
639                 struct Config
640                 {
641                         std::string name;
642
643                         std::auto_ptr<X509CertList> ca;
644                         std::auto_ptr<X509CRL> crl;
645
646                         std::string certstr;
647                         std::string keystr;
648                         std::auto_ptr<DHParams> dh;
649
650                         std::string priostr;
651                         unsigned int mindh;
652                         std::string hashstr;
653
654                         unsigned int outrecsize;
655                         bool requestclientcert;
656
657                         Config(const std::string& profilename, ConfigTag* tag)
658                                 : name(profilename)
659                                 , certstr(ReadFile(tag->getString("certfile", "cert.pem")))
660                                 , keystr(ReadFile(tag->getString("keyfile", "key.pem")))
661                                 , dh(DHParams::Import(ReadFile(tag->getString("dhfile", "dhparams.pem"))))
662                                 , priostr(GetPrioStr(profilename, tag))
663                                 , mindh(tag->getUInt("mindhbits", 1024))
664                                 , hashstr(tag->getString("hash", "md5"))
665                                 , requestclientcert(tag->getBool("requestclientcert", true))
666                         {
667                                 // Load trusted CA and revocation list, if set
668                                 std::string filename = tag->getString("cafile");
669                                 if (!filename.empty())
670                                 {
671                                         ca.reset(new X509CertList(ReadFile(filename)));
672
673                                         filename = tag->getString("crlfile");
674                                         if (!filename.empty())
675                                                 crl.reset(new X509CRL(ReadFile(filename)));
676                                 }
677
678 #ifdef INSPIRCD_GNUTLS_HAS_CORK
679                                 // If cork support is available outrecsize represents the (rough) max amount of data we give GnuTLS while corked
680                                 outrecsize = tag->getUInt("outrecsize", 2048, 512);
681 #else
682                                 outrecsize = tag->getUInt("outrecsize", 2048, 512, 16384);
683 #endif
684                         }
685                 };
686
687                 Profile(Config& config)
688                         : name(config.name)
689                         , x509cred(config.certstr, config.keystr)
690                         , min_dh_bits(config.mindh)
691                         , hash(config.hashstr)
692                         , priority(config.priostr)
693                         , outrecsize(config.outrecsize)
694                         , requestclientcert(config.requestclientcert)
695                 {
696                         x509cred.SetDH(config.dh);
697                         x509cred.SetCA(config.ca, config.crl);
698                 }
699                 /** Set up the given session with the settings in this profile
700                  */
701                 void SetupSession(gnutls_session_t sess)
702                 {
703                         priority.SetupSession(sess);
704                         x509cred.SetupSession(sess);
705                         gnutls_dh_set_prime_bits(sess, min_dh_bits);
706
707                         // Request client certificate if enabled and we are a server, no-op if we're a client
708                         if (requestclientcert)
709                                 gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
710                 }
711
712                 const std::string& GetName() const { return name; }
713                 X509Credentials& GetX509Credentials() { return x509cred; }
714                 gnutls_digest_algorithm_t GetHash() const { return hash.get(); }
715                 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
716         };
717 }
718
719 class GnuTLSIOHook : public SSLIOHook
720 {
721  private:
722         gnutls_session_t sess;
723         issl_status status;
724 #ifdef INSPIRCD_GNUTLS_HAS_CORK
725         size_t gbuffersize;
726 #endif
727
728         void CloseSession()
729         {
730                 if (this->sess)
731                 {
732                         gnutls_bye(this->sess, GNUTLS_SHUT_WR);
733                         gnutls_deinit(this->sess);
734                 }
735                 sess = NULL;
736                 certificate = NULL;
737                 status = ISSL_NONE;
738         }
739
740         // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
741         int Handshake(StreamSocket* user)
742         {
743                 int ret = gnutls_handshake(this->sess);
744
745                 if (ret < 0)
746                 {
747                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
748                         {
749                                 // Handshake needs resuming later, read() or write() would have blocked.
750                                 this->status = ISSL_HANDSHAKING;
751
752                                 if (gnutls_record_get_direction(this->sess) == 0)
753                                 {
754                                         // gnutls_handshake() wants to read() again.
755                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
756                                 }
757                                 else
758                                 {
759                                         // gnutls_handshake() wants to write() again.
760                                         SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
761                                 }
762
763                                 return 0;
764                         }
765                         else
766                         {
767                                 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
768                                 CloseSession();
769                                 return -1;
770                         }
771                 }
772                 else
773                 {
774                         // Change the seesion state
775                         this->status = ISSL_HANDSHAKEN;
776
777                         VerifyCertificate();
778
779                         // Finish writing, if any left
780                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
781
782                         return 1;
783                 }
784         }
785
786         void VerifyCertificate()
787         {
788                 unsigned int certstatus;
789                 const gnutls_datum_t* cert_list;
790                 int ret;
791                 unsigned int cert_list_size;
792                 gnutls_x509_crt_t cert;
793                 char str[512];
794                 unsigned char digest[512];
795                 size_t digest_size = sizeof(digest);
796                 size_t name_size = sizeof(str);
797                 ssl_cert* certinfo = new ssl_cert;
798                 this->certificate = certinfo;
799
800                 /* This verification function uses the trusted CAs in the credentials
801                  * structure. So you must have installed one or more CA certificates.
802                  */
803                 ret = gnutls_certificate_verify_peers2(this->sess, &certstatus);
804
805                 if (ret < 0)
806                 {
807                         certinfo->error = std::string(gnutls_strerror(ret));
808                         return;
809                 }
810
811                 certinfo->invalid = (certstatus & GNUTLS_CERT_INVALID);
812                 certinfo->unknownsigner = (certstatus & GNUTLS_CERT_SIGNER_NOT_FOUND);
813                 certinfo->revoked = (certstatus & GNUTLS_CERT_REVOKED);
814                 certinfo->trusted = !(certstatus & GNUTLS_CERT_SIGNER_NOT_CA);
815
816                 /* Up to here the process is the same for X.509 certificates and
817                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
818                  * be easily extended to work with openpgp keys as well.
819                  */
820                 if (gnutls_certificate_type_get(this->sess) != GNUTLS_CRT_X509)
821                 {
822                         certinfo->error = "No X509 keys sent";
823                         return;
824                 }
825
826                 ret = gnutls_x509_crt_init(&cert);
827                 if (ret < 0)
828                 {
829                         certinfo->error = gnutls_strerror(ret);
830                         return;
831                 }
832
833                 cert_list_size = 0;
834                 cert_list = gnutls_certificate_get_peers(this->sess, &cert_list_size);
835                 if (cert_list == NULL)
836                 {
837                         certinfo->error = "No certificate was found";
838                         goto info_done_dealloc;
839                 }
840
841                 /* This is not a real world example, since we only check the first
842                  * certificate in the given chain.
843                  */
844
845                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
846                 if (ret < 0)
847                 {
848                         certinfo->error = gnutls_strerror(ret);
849                         goto info_done_dealloc;
850                 }
851
852                 if (gnutls_x509_crt_get_dn(cert, str, &name_size) == 0)
853                 {
854                         std::string& dn = certinfo->dn;
855                         dn = str;
856                         // Make sure there are no chars in the string that we consider invalid
857                         if (dn.find_first_of("\r\n") != std::string::npos)
858                                 dn.clear();
859                 }
860
861                 name_size = sizeof(str);
862                 if (gnutls_x509_crt_get_issuer_dn(cert, str, &name_size) == 0)
863                 {
864                         std::string& issuer = certinfo->issuer;
865                         issuer = str;
866                         if (issuer.find_first_of("\r\n") != std::string::npos)
867                                 issuer.clear();
868                 }
869
870                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GetProfile().GetHash(), digest, &digest_size)) < 0)
871                 {
872                         certinfo->error = gnutls_strerror(ret);
873                 }
874                 else
875                 {
876                         certinfo->fingerprint = BinToHex(digest, digest_size);
877                 }
878
879                 /* Beware here we do not check for errors.
880                  */
881                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
882                 {
883                         certinfo->error = "Not activated, or expired certificate";
884                 }
885
886 info_done_dealloc:
887                 gnutls_x509_crt_deinit(cert);
888         }
889
890         // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
891         int PrepareIO(StreamSocket* sock)
892         {
893                 if (status == ISSL_HANDSHAKEN)
894                         return 1;
895                 else if (status == ISSL_HANDSHAKING)
896                 {
897                         // The handshake isn't finished, try to finish it
898                         return Handshake(sock);
899                 }
900
901                 CloseSession();
902                 sock->SetError("No SSL session");
903                 return -1;
904         }
905
906 #ifdef INSPIRCD_GNUTLS_HAS_CORK
907         int FlushBuffer(StreamSocket* sock)
908         {
909                 // If GnuTLS has some data buffered, write it
910                 if (gbuffersize)
911                         return HandleWriteRet(sock, gnutls_record_uncork(this->sess, 0));
912                 return 1;
913         }
914 #endif
915
916         int HandleWriteRet(StreamSocket* sock, int ret)
917         {
918                 if (ret > 0)
919                 {
920 #ifdef INSPIRCD_GNUTLS_HAS_CORK
921                         gbuffersize -= ret;
922                         if (gbuffersize)
923                         {
924                                 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
925                                 return 0;
926                         }
927 #endif
928                         return ret;
929                 }
930                 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
931                 {
932                         SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
933                         return 0;
934                 }
935                 else // (ret < 0)
936                 {
937                         sock->SetError(gnutls_strerror(ret));
938                         CloseSession();
939                         return -1;
940                 }
941         }
942
943         static const char* UnknownIfNULL(const char* str)
944         {
945                 return str ? str : "UNKNOWN";
946         }
947
948         static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
949         {
950                 StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap);
951 #ifdef _WIN32
952                 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetModHook(thismod));
953 #endif
954
955                 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
956                 {
957 #ifdef _WIN32
958                         gnutls_transport_set_errno(session->sess, EAGAIN);
959 #else
960                         errno = EAGAIN;
961 #endif
962                         return -1;
963                 }
964
965                 int rv = SocketEngine::Recv(sock, reinterpret_cast<char *>(buffer), size, 0);
966
967 #ifdef _WIN32
968                 if (rv < 0)
969                 {
970                         /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
971                          * and then set errno appropriately.
972                          * The gnutls library may also have a different errno variable than us, see
973                          * gnutls_transport_set_errno(3).
974                          */
975                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
976                 }
977 #endif
978
979                 if (rv < (int)size)
980                         SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
981                 return rv;
982         }
983
984 #ifdef INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
985         static ssize_t VectorPush(gnutls_transport_ptr_t transportptr, const giovec_t* iov, int iovcnt)
986         {
987                 StreamSocket* sock = reinterpret_cast<StreamSocket*>(transportptr);
988 #ifdef _WIN32
989                 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetModHook(thismod));
990 #endif
991
992                 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
993                 {
994 #ifdef _WIN32
995                         gnutls_transport_set_errno(session->sess, EAGAIN);
996 #else
997                         errno = EAGAIN;
998 #endif
999                         return -1;
1000                 }
1001
1002                 // Cast the giovec_t to iovec not to IOVector so the correct function is called on Windows
1003                 int ret = SocketEngine::WriteV(sock, reinterpret_cast<const iovec*>(iov), iovcnt);
1004 #ifdef _WIN32
1005                 // See the function above for more info about the usage of gnutls_transport_set_errno() on Windows
1006                 if (ret < 0)
1007                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
1008 #endif
1009
1010                 int size = 0;
1011                 for (int i = 0; i < iovcnt; i++)
1012                         size += iov[i].iov_len;
1013
1014                 if (ret < size)
1015                         SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
1016                 return ret;
1017         }
1018
1019 #else // INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
1020         static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
1021         {
1022                 StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap);
1023 #ifdef _WIN32
1024                 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetModHook(thismod));
1025 #endif
1026
1027                 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
1028                 {
1029 #ifdef _WIN32
1030                         gnutls_transport_set_errno(session->sess, EAGAIN);
1031 #else
1032                         errno = EAGAIN;
1033 #endif
1034                         return -1;
1035                 }
1036
1037                 int rv = SocketEngine::Send(sock, reinterpret_cast<const char *>(buffer), size, 0);
1038
1039 #ifdef _WIN32
1040                 if (rv < 0)
1041                 {
1042                         /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
1043                          * and then set errno appropriately.
1044                          * The gnutls library may also have a different errno variable than us, see
1045                          * gnutls_transport_set_errno(3).
1046                          */
1047                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
1048                 }
1049 #endif
1050
1051                 if (rv < (int)size)
1052                         SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
1053                 return rv;
1054         }
1055 #endif // INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
1056
1057  public:
1058         GnuTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, inspircd_gnutls_session_init_flags_t flags)
1059                 : SSLIOHook(hookprov)
1060                 , sess(NULL)
1061                 , status(ISSL_NONE)
1062 #ifdef INSPIRCD_GNUTLS_HAS_CORK
1063                 , gbuffersize(0)
1064 #endif
1065         {
1066                 gnutls_init(&sess, flags);
1067                 gnutls_transport_set_ptr(sess, reinterpret_cast<gnutls_transport_ptr_t>(sock));
1068 #ifdef INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
1069                 gnutls_transport_set_vec_push_function(sess, VectorPush);
1070 #else
1071                 gnutls_transport_set_push_function(sess, gnutls_push_wrapper);
1072 #endif
1073                 gnutls_transport_set_pull_function(sess, gnutls_pull_wrapper);
1074                 GetProfile().SetupSession(sess);
1075
1076                 sock->AddIOHook(this);
1077                 Handshake(sock);
1078         }
1079
1080         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
1081         {
1082                 CloseSession();
1083         }
1084
1085         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
1086         {
1087                 // Finish handshake if needed
1088                 int prepret = PrepareIO(user);
1089                 if (prepret <= 0)
1090                         return prepret;
1091
1092                 // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN.
1093                 {
1094                         GnuTLS::DataReader reader(sess);
1095                         int ret = reader.ret();
1096                         if (ret > 0)
1097                         {
1098                                 reader.appendto(recvq);
1099                                 // Schedule a read if there is still data in the GnuTLS buffer
1100                                 if (gnutls_record_check_pending(sess) > 0)
1101                                         SocketEngine::ChangeEventMask(user, FD_ADD_TRIAL_READ);
1102                                 return 1;
1103                         }
1104                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
1105                         {
1106                                 return 0;
1107                         }
1108                         else if (ret == 0)
1109                         {
1110                                 user->SetError("Connection closed");
1111                                 CloseSession();
1112                                 return -1;
1113                         }
1114                         else
1115                         {
1116                                 user->SetError(gnutls_strerror(ret));
1117                                 CloseSession();
1118                                 return -1;
1119                         }
1120                 }
1121         }
1122
1123         int OnStreamSocketWrite(StreamSocket* user, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
1124         {
1125                 // Finish handshake if needed
1126                 int prepret = PrepareIO(user);
1127                 if (prepret <= 0)
1128                         return prepret;
1129
1130                 // Session is ready for transferring application data
1131
1132 #ifdef INSPIRCD_GNUTLS_HAS_CORK
1133                 while (true)
1134                 {
1135                         // If there is something in the GnuTLS buffer try to send() it
1136                         int ret = FlushBuffer(user);
1137                         if (ret <= 0)
1138                                 return ret; // Couldn't flush entire buffer, retry later (or close on error)
1139
1140                         // GnuTLS buffer is empty, if the sendq is empty as well then break to set FD_WANT_NO_WRITE
1141                         if (sendq.empty())
1142                                 break;
1143
1144                         // GnuTLS buffer is empty but sendq is not, begin sending data from the sendq
1145                         gnutls_record_cork(this->sess);
1146                         while ((!sendq.empty()) && (gbuffersize < GetProfile().GetOutgoingRecordSize()))
1147                         {
1148                                 const StreamSocket::SendQueue::Element& elem = sendq.front();
1149                                 gbuffersize += elem.length();
1150                                 ret = gnutls_record_send(this->sess, elem.data(), elem.length());
1151                                 if (ret < 0)
1152                                 {
1153                                         CloseSession();
1154                                         return -1;
1155                                 }
1156                                 sendq.pop_front();
1157                         }
1158                 }
1159 #else
1160                 int ret = 0;
1161
1162                 while (!sendq.empty())
1163                 {
1164                         FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
1165                         const StreamSocket::SendQueue::Element& buffer = sendq.front();
1166                         ret = HandleWriteRet(user, gnutls_record_send(this->sess, buffer.data(), buffer.length()));
1167
1168                         if (ret <= 0)
1169                                 return ret;
1170                         else if (ret < (int)buffer.length())
1171                         {
1172                                 sendq.erase_front(ret);
1173                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
1174                                 return 0;
1175                         }
1176
1177                         // Wrote entire record, continue sending
1178                         sendq.pop_front();
1179                 }
1180 #endif
1181
1182                 SocketEngine::ChangeEventMask(user, FD_WANT_NO_WRITE);
1183                 return 1;
1184         }
1185
1186         void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
1187         {
1188                 if (!IsHandshakeDone())
1189                         return;
1190                 out.append(UnknownIfNULL(gnutls_protocol_get_name(gnutls_protocol_get_version(sess)))).push_back('-');
1191                 out.append(UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)))).push_back('-');
1192                 out.append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).push_back('-');
1193                 out.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
1194         }
1195
1196         bool GetServerName(std::string& out) const CXX11_OVERRIDE
1197         {
1198                 std::vector<char> nameBuffer;
1199                 size_t nameLength = 0;
1200                 unsigned int nameType = GNUTLS_NAME_DNS;
1201
1202                 // First, determine the size of the hostname.
1203                 if (gnutls_server_name_get(sess, &nameBuffer[0], &nameLength, &nameType, 0) != GNUTLS_E_SHORT_MEMORY_BUFFER)
1204                         return false;
1205
1206                 // Then retrieve the hostname.
1207                 nameBuffer.resize(nameLength);
1208                 if (gnutls_server_name_get(sess, &nameBuffer[0], &nameLength, &nameType, 0) != GNUTLS_E_SUCCESS)
1209                         return false;
1210
1211                 out.append(&nameBuffer[0]);
1212                 return true;
1213         }
1214
1215         GnuTLS::Profile& GetProfile();
1216         bool IsHandshakeDone() const { return (status == ISSL_HANDSHAKEN); }
1217 };
1218
1219 int GnuTLS::X509Credentials::cert_callback(gnutls_session_t sess, const gnutls_datum_t* req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t* sign_algos, int sign_algos_length, cert_cb_last_param_type* st)
1220 {
1221 #ifndef GNUTLS_NEW_CERT_CALLBACK_API
1222         st->type = GNUTLS_CRT_X509;
1223 #else
1224         st->cert_type = GNUTLS_CRT_X509;
1225         st->key_type = GNUTLS_PRIVKEY_X509;
1226 #endif
1227         StreamSocket* sock = reinterpret_cast<StreamSocket*>(gnutls_transport_get_ptr(sess));
1228         GnuTLS::X509Credentials& cred = static_cast<GnuTLSIOHook*>(sock->GetModHook(thismod))->GetProfile().GetX509Credentials();
1229
1230         st->ncerts = cred.certs.size();
1231         st->cert.x509 = cred.certs.raw();
1232         st->key.x509 = cred.key.get();
1233         st->deinit_all = 0;
1234
1235         return 0;
1236 }
1237
1238 class GnuTLSIOHookProvider : public IOHookProvider
1239 {
1240         GnuTLS::Profile profile;
1241
1242  public:
1243         GnuTLSIOHookProvider(Module* mod, GnuTLS::Profile::Config& config)
1244                 : IOHookProvider(mod, "ssl/" + config.name, IOHookProvider::IOH_SSL)
1245                 , profile(config)
1246         {
1247                 ServerInstance->Modules->AddService(*this);
1248         }
1249
1250         ~GnuTLSIOHookProvider()
1251         {
1252                 ServerInstance->Modules->DelService(*this);
1253         }
1254
1255         void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
1256         {
1257                 new GnuTLSIOHook(this, sock, GNUTLS_SERVER);
1258         }
1259
1260         void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
1261         {
1262                 new GnuTLSIOHook(this, sock, GNUTLS_CLIENT);
1263         }
1264
1265         GnuTLS::Profile& GetProfile() { return profile; }
1266 };
1267
1268 GnuTLS::Profile& GnuTLSIOHook::GetProfile()
1269 {
1270         IOHookProvider* hookprov = prov;
1271         return static_cast<GnuTLSIOHookProvider*>(hookprov)->GetProfile();
1272 }
1273
1274 class ModuleSSLGnuTLS : public Module
1275 {
1276         typedef std::vector<reference<GnuTLSIOHookProvider> > ProfileList;
1277
1278         // First member of the class, gets constructed first and destructed last
1279         GnuTLS::Init libinit;
1280         ProfileList profiles;
1281
1282         void ReadProfiles()
1283         {
1284                 // First, store all profiles in a new, temporary container. If no problems occur, swap the two
1285                 // containers; this way if something goes wrong we can go back and continue using the current profiles,
1286                 // avoiding unpleasant situations where no new SSL connections are possible.
1287                 ProfileList newprofiles;
1288
1289                 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
1290                 if (tags.first == tags.second)
1291                 {
1292                         // No <sslprofile> tags found, create a profile named "gnutls" from settings in the <gnutls> block
1293                         const std::string defname = "gnutls";
1294                         ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
1295                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <gnutls> tag");
1296
1297                         try
1298                         {
1299                                 GnuTLS::Profile::Config profileconfig(defname, tag);
1300                                 newprofiles.push_back(new GnuTLSIOHookProvider(this, profileconfig));
1301                         }
1302                         catch (CoreException& ex)
1303                         {
1304                                 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
1305                         }
1306                 }
1307
1308                 for (ConfigIter i = tags.first; i != tags.second; ++i)
1309                 {
1310                         ConfigTag* tag = i->second;
1311                         if (!stdalgo::string::equalsci(tag->getString("provider"), "gnutls"))
1312                                 continue;
1313
1314                         std::string name = tag->getString("name");
1315                         if (name.empty())
1316                         {
1317                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
1318                                 continue;
1319                         }
1320
1321                         reference<GnuTLSIOHookProvider> prov;
1322                         try
1323                         {
1324                                 GnuTLS::Profile::Config profileconfig(name, tag);
1325                                 prov = new GnuTLSIOHookProvider(this, profileconfig);
1326                         }
1327                         catch (CoreException& ex)
1328                         {
1329                                 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
1330                         }
1331
1332                         newprofiles.push_back(prov);
1333                 }
1334
1335                 // New profiles are ok, begin using them
1336                 // Old profiles are deleted when their refcount drops to zero
1337                 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
1338                 {
1339                         GnuTLSIOHookProvider& prov = **i;
1340                         ServerInstance->Modules.DelService(prov);
1341                 }
1342
1343                 profiles.swap(newprofiles);
1344         }
1345
1346  public:
1347         ModuleSSLGnuTLS()
1348         {
1349 #ifndef GNUTLS_HAS_RND
1350                 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
1351 #endif
1352                 thismod = this;
1353         }
1354
1355         void init() CXX11_OVERRIDE
1356         {
1357                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "GnuTLS lib version %s module was compiled for " GNUTLS_VERSION, gnutls_check_version(NULL));
1358                 ReadProfiles();
1359                 ServerInstance->GenRandom = RandGen::Call;
1360         }
1361
1362         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
1363         {
1364                 if(param != "ssl")
1365                         return;
1366
1367                 try
1368                 {
1369                         ReadProfiles();
1370                 }
1371                 catch (ModuleException& ex)
1372                 {
1373                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
1374                 }
1375         }
1376
1377         ~ModuleSSLGnuTLS()
1378         {
1379                 ServerInstance->GenRandom = &InspIRCd::DefaultGenRandom;
1380         }
1381
1382         void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
1383         {
1384                 if (type == ExtensionItem::EXT_USER)
1385                 {
1386                         LocalUser* user = IS_LOCAL(static_cast<User*>(item));
1387
1388                         if ((user) && (user->eh.GetModHook(this)))
1389                         {
1390                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
1391                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
1392                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
1393                         }
1394                 }
1395         }
1396
1397         Version GetVersion() CXX11_OVERRIDE
1398         {
1399                 return Version("Provides SSL support via GnuTLS", VF_VENDOR);
1400         }
1401
1402         ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
1403         {
1404                 const GnuTLSIOHook* const iohook = static_cast<GnuTLSIOHook*>(user->eh.GetModHook(this));
1405                 if ((iohook) && (!iohook->IsHandshakeDone()))
1406                         return MOD_RES_DENY;
1407                 return MOD_RES_PASSTHRU;
1408         }
1409 };
1410
1411 MODULE_INIT(ModuleSSLGnuTLS)