]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
m_ssl_gnutls Replace ISSL_HANDSHAKING_READ/WRITE with a single state
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_gnutls.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2008 John Brooks <john.brooks@dereferenced.net>
6  *   Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
8  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
9  *
10  * This file is part of InspIRCd.  InspIRCd is free software: you can
11  * redistribute it and/or modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation, version 2.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23
24 #include "inspircd.h"
25 #include "modules/ssl.h"
26 #include <memory>
27
28 // Fix warnings about the use of commas at end of enumerator lists on C++03.
29 #if defined __clang__
30 # pragma clang diagnostic ignored "-Wc++11-extensions"
31 #elif defined __GNUC__
32 # pragma GCC diagnostic ignored "-pedantic"
33 #endif
34
35 #include <gnutls/gnutls.h>
36 #include <gnutls/x509.h>
37
38 #ifndef GNUTLS_VERSION_NUMBER
39 #define GNUTLS_VERSION_NUMBER LIBGNUTLS_VERSION_NUMBER
40 #endif
41
42 // Check if the GnuTLS library is at least version major.minor.patch
43 #define INSPIRCD_GNUTLS_HAS_VERSION(major, minor, patch) (GNUTLS_VERSION_NUMBER >= ((major << 16) | (minor << 8) | patch))
44
45 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 9, 8)
46 #define GNUTLS_HAS_MAC_GET_ID
47 #include <gnutls/crypto.h>
48 #endif
49
50 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 12, 0)
51 # define GNUTLS_HAS_RND
52 #else
53 # include <gcrypt.h>
54 #endif
55
56 #ifdef _WIN32
57 # pragma comment(lib, "libgnutls-28.lib")
58 #endif
59
60 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") eval("print `libgcrypt-config --cflags | tr -d \r` if `pkg-config --modversion gnutls 2>/dev/null | tr -d \r` lt '2.12'") */
61 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") eval("print `libgcrypt-config --libs | tr -d \r` if `pkg-config --modversion gnutls 2>/dev/null | tr -d \r` lt '2.12'") */
62
63 // These don't exist in older GnuTLS versions
64 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 1, 7)
65 #define GNUTLS_NEW_PRIO_API
66 #endif
67
68 #if (!INSPIRCD_GNUTLS_HAS_VERSION(2, 0, 0))
69 typedef gnutls_certificate_credentials_t gnutls_certificate_credentials;
70 typedef gnutls_dh_params_t gnutls_dh_params;
71 #endif
72
73 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
74
75 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 12, 0)
76 #define GNUTLS_NEW_CERT_CALLBACK_API
77 typedef gnutls_retr2_st cert_cb_last_param_type;
78 #else
79 typedef gnutls_retr_st cert_cb_last_param_type;
80 #endif
81
82 #if INSPIRCD_GNUTLS_HAS_VERSION(3, 3, 5)
83 #define INSPIRCD_GNUTLS_HAS_RECV_PACKET
84 #endif
85
86 class RandGen : public HandlerBase2<void, char*, size_t>
87 {
88  public:
89         void Call(char* buffer, size_t len)
90         {
91 #ifdef GNUTLS_HAS_RND
92                 gnutls_rnd(GNUTLS_RND_RANDOM, buffer, len);
93 #else
94                 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
95 #endif
96         }
97 };
98
99 namespace GnuTLS
100 {
101         class Init
102         {
103          public:
104                 Init() { gnutls_global_init(); }
105                 ~Init() { gnutls_global_deinit(); }
106         };
107
108         class Exception : public ModuleException
109         {
110          public:
111                 Exception(const std::string& reason)
112                         : ModuleException(reason) { }
113         };
114
115         void ThrowOnError(int errcode, const char* msg)
116         {
117                 if (errcode < 0)
118                 {
119                         std::string reason = msg;
120                         reason.append(" :").append(gnutls_strerror(errcode));
121                         throw Exception(reason);
122                 }
123         }
124
125         /** Used to create a gnutls_datum_t* from a std::string
126          */
127         class Datum
128         {
129                 gnutls_datum_t datum;
130
131          public:
132                 Datum(const std::string& dat)
133                 {
134                         datum.data = (unsigned char*)dat.data();
135                         datum.size = static_cast<unsigned int>(dat.length());
136                 }
137
138                 const gnutls_datum_t* get() const { return &datum; }
139         };
140
141         class Hash
142         {
143                 gnutls_digest_algorithm_t hash;
144
145          public:
146                 // Nothing to deallocate, constructor may throw freely
147                 Hash(const std::string& hashname)
148                 {
149                         // As older versions of gnutls can't do this, let's disable it where needed.
150 #ifdef GNUTLS_HAS_MAC_GET_ID
151                         // As gnutls_digest_algorithm_t and gnutls_mac_algorithm_t are mapped 1:1, we can do this
152                         // There is no gnutls_dig_get_id() at the moment, but it may come later
153                         hash = (gnutls_digest_algorithm_t)gnutls_mac_get_id(hashname.c_str());
154                         if (hash == GNUTLS_DIG_UNKNOWN)
155                                 throw Exception("Unknown hash type " + hashname);
156
157                         // Check if the user is giving us something that is a valid MAC but not digest
158                         gnutls_hash_hd_t is_digest;
159                         if (gnutls_hash_init(&is_digest, hash) < 0)
160                                 throw Exception("Unknown hash type " + hashname);
161                         gnutls_hash_deinit(is_digest, NULL);
162 #else
163                         if (hashname == "md5")
164                                 hash = GNUTLS_DIG_MD5;
165                         else if (hashname == "sha1")
166                                 hash = GNUTLS_DIG_SHA1;
167 #ifdef INSPIRCD_GNUTLS_ENABLE_SHA256_FINGERPRINT
168                         else if (hashname == "sha256")
169                                 hash = GNUTLS_DIG_SHA256;
170 #endif
171                         else
172                                 throw Exception("Unknown hash type " + hashname);
173 #endif
174                 }
175
176                 gnutls_digest_algorithm_t get() const { return hash; }
177         };
178
179         class DHParams
180         {
181                 gnutls_dh_params_t dh_params;
182
183                 DHParams()
184                 {
185                         ThrowOnError(gnutls_dh_params_init(&dh_params), "gnutls_dh_params_init() failed");
186                 }
187
188          public:
189                 /** Import */
190                 static std::auto_ptr<DHParams> Import(const std::string& dhstr)
191                 {
192                         std::auto_ptr<DHParams> dh(new DHParams);
193                         int ret = gnutls_dh_params_import_pkcs3(dh->dh_params, Datum(dhstr).get(), GNUTLS_X509_FMT_PEM);
194                         ThrowOnError(ret, "Unable to import DH params");
195                         return dh;
196                 }
197
198                 /** Generate */
199                 static std::auto_ptr<DHParams> Generate(unsigned int bits)
200                 {
201                         std::auto_ptr<DHParams> dh(new DHParams);
202                         ThrowOnError(gnutls_dh_params_generate2(dh->dh_params, bits), "Unable to generate DH params");
203                         return dh;
204                 }
205
206                 ~DHParams()
207                 {
208                         gnutls_dh_params_deinit(dh_params);
209                 }
210
211                 const gnutls_dh_params_t& get() const { return dh_params; }
212         };
213
214         class X509Key
215         {
216                 /** Ensure that the key is deinited in case the constructor of X509Key throws
217                  */
218                 class RAIIKey
219                 {
220                  public:
221                         gnutls_x509_privkey_t key;
222
223                         RAIIKey()
224                         {
225                                 ThrowOnError(gnutls_x509_privkey_init(&key), "gnutls_x509_privkey_init() failed");
226                         }
227
228                         ~RAIIKey()
229                         {
230                                 gnutls_x509_privkey_deinit(key);
231                         }
232                 } key;
233
234          public:
235                 /** Import */
236                 X509Key(const std::string& keystr)
237                 {
238                         int ret = gnutls_x509_privkey_import(key.key, Datum(keystr).get(), GNUTLS_X509_FMT_PEM);
239                         ThrowOnError(ret, "Unable to import private key");
240                 }
241
242                 gnutls_x509_privkey_t& get() { return key.key; }
243         };
244
245         class X509CertList
246         {
247                 std::vector<gnutls_x509_crt_t> certs;
248
249          public:
250                 /** Import */
251                 X509CertList(const std::string& certstr)
252                 {
253                         unsigned int certcount = 3;
254                         certs.resize(certcount);
255                         Datum datum(certstr);
256
257                         int ret = gnutls_x509_crt_list_import(raw(), &certcount, datum.get(), GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
258                         if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
259                         {
260                                 // the buffer wasn't big enough to hold all certs but gnutls changed certcount to the number of available certs,
261                                 // try again with a bigger buffer
262                                 certs.resize(certcount);
263                                 ret = gnutls_x509_crt_list_import(raw(), &certcount, datum.get(), GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
264                         }
265
266                         ThrowOnError(ret, "Unable to load certificates");
267
268                         // Resize the vector to the actual number of certs because we rely on its size being correct
269                         // when deallocating the certs
270                         certs.resize(certcount);
271                 }
272
273                 ~X509CertList()
274                 {
275                         for (std::vector<gnutls_x509_crt_t>::iterator i = certs.begin(); i != certs.end(); ++i)
276                                 gnutls_x509_crt_deinit(*i);
277                 }
278
279                 gnutls_x509_crt_t* raw() { return &certs[0]; }
280                 unsigned int size() const { return certs.size(); }
281         };
282
283         class X509CRL : public refcountbase
284         {
285                 class RAIICRL
286                 {
287                  public:
288                         gnutls_x509_crl_t crl;
289
290                         RAIICRL()
291                         {
292                                 ThrowOnError(gnutls_x509_crl_init(&crl), "gnutls_x509_crl_init() failed");
293                         }
294
295                         ~RAIICRL()
296                         {
297                                 gnutls_x509_crl_deinit(crl);
298                         }
299                 } crl;
300
301          public:
302                 /** Import */
303                 X509CRL(const std::string& crlstr)
304                 {
305                         int ret = gnutls_x509_crl_import(get(), Datum(crlstr).get(), GNUTLS_X509_FMT_PEM);
306                         ThrowOnError(ret, "Unable to load certificate revocation list");
307                 }
308
309                 gnutls_x509_crl_t& get() { return crl.crl; }
310         };
311
312 #ifdef GNUTLS_NEW_PRIO_API
313         class Priority
314         {
315                 gnutls_priority_t priority;
316
317          public:
318                 Priority(const std::string& priorities)
319                 {
320                         // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
321                         // If the user did not supply anything then the string is already set to "NORMAL"
322                         const char* priocstr = priorities.c_str();
323                         const char* prioerror;
324
325                         int ret = gnutls_priority_init(&priority, priocstr, &prioerror);
326                         if (ret < 0)
327                         {
328                                 // gnutls did not understand the user supplied string
329                                 throw Exception("Unable to initialize priorities to \"" + priorities + "\": " + gnutls_strerror(ret) + " Syntax error at position " + ConvToStr((unsigned int) (prioerror - priocstr)));
330                         }
331                 }
332
333                 ~Priority()
334                 {
335                         gnutls_priority_deinit(priority);
336                 }
337
338                 void SetupSession(gnutls_session_t sess)
339                 {
340                         gnutls_priority_set(sess, priority);
341                 }
342         };
343 #else
344         /** Dummy class, used when gnutls_priority_set() is not available
345          */
346         class Priority
347         {
348          public:
349                 Priority(const std::string& priorities)
350                 {
351                         if (priorities != "NORMAL")
352                                 throw Exception("You've set a non-default priority string, but GnuTLS lacks support for it");
353                 }
354
355                 static void SetupSession(gnutls_session_t sess)
356                 {
357                         // Always set the default priorities
358                         gnutls_set_default_priority(sess);
359                 }
360         };
361 #endif
362
363         class CertCredentials
364         {
365                 /** DH parameters associated with these credentials
366                  */
367                 std::auto_ptr<DHParams> dh;
368
369          protected:
370                 gnutls_certificate_credentials_t cred;
371
372          public:
373                 CertCredentials()
374                 {
375                         ThrowOnError(gnutls_certificate_allocate_credentials(&cred), "Cannot allocate certificate credentials");
376                 }
377
378                 ~CertCredentials()
379                 {
380                         gnutls_certificate_free_credentials(cred);
381                 }
382
383                 /** Associates these credentials with the session
384                  */
385                 void SetupSession(gnutls_session_t sess)
386                 {
387                         gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, cred);
388                 }
389
390                 /** Set the given DH parameters to be used with these credentials
391                  */
392                 void SetDH(std::auto_ptr<DHParams>& DH)
393                 {
394                         dh = DH;
395                         gnutls_certificate_set_dh_params(cred, dh->get());
396                 }
397         };
398
399         class X509Credentials : public CertCredentials
400         {
401                 /** Private key
402                  */
403                 X509Key key;
404
405                 /** Certificate list, presented to the peer
406                  */
407                 X509CertList certs;
408
409                 /** Trusted CA, may be NULL
410                  */
411                 std::auto_ptr<X509CertList> trustedca;
412
413                 /** Certificate revocation list, may be NULL
414                  */
415                 std::auto_ptr<X509CRL> crl;
416
417                 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);
418
419          public:
420                 X509Credentials(const std::string& certstr, const std::string& keystr)
421                         : key(keystr)
422                         , certs(certstr)
423                 {
424                         // Throwing is ok here, the destructor of Credentials is called in that case
425                         int ret = gnutls_certificate_set_x509_key(cred, certs.raw(), certs.size(), key.get());
426                         ThrowOnError(ret, "Unable to set cert/key pair");
427
428 #ifdef GNUTLS_NEW_CERT_CALLBACK_API
429                         gnutls_certificate_set_retrieve_function(cred, cert_callback);
430 #else
431                         gnutls_certificate_client_set_retrieve_function(cred, cert_callback);
432 #endif
433                 }
434
435                 /** Sets the trusted CA and the certificate revocation list
436                  * to use when verifying certificates
437                  */
438                 void SetCA(std::auto_ptr<X509CertList>& certlist, std::auto_ptr<X509CRL>& CRL)
439                 {
440                         // Do nothing if certlist is NULL
441                         if (certlist.get())
442                         {
443                                 int ret = gnutls_certificate_set_x509_trust(cred, certlist->raw(), certlist->size());
444                                 ThrowOnError(ret, "gnutls_certificate_set_x509_trust() failed");
445
446                                 if (CRL.get())
447                                 {
448                                         ret = gnutls_certificate_set_x509_crl(cred, &CRL->get(), 1);
449                                         ThrowOnError(ret, "gnutls_certificate_set_x509_crl() failed");
450                                 }
451
452                                 trustedca = certlist;
453                                 crl = CRL;
454                         }
455                 }
456         };
457
458         class DataReader
459         {
460                 int retval;
461 #ifdef INSPIRCD_GNUTLS_HAS_RECV_PACKET
462                 gnutls_packet_t packet;
463
464          public:
465                 DataReader(gnutls_session_t sess)
466                 {
467                         // Using the packet API avoids the final copy of the data which GnuTLS does if we supply
468                         // our own buffer. Instead, we get the buffer containing the data from GnuTLS and copy it
469                         // to the recvq directly from there in appendto().
470                         retval = gnutls_record_recv_packet(sess, &packet);
471                 }
472
473                 void appendto(std::string& recvq)
474                 {
475                         // Copy data from GnuTLS buffers to recvq
476                         gnutls_datum_t datum;
477                         gnutls_packet_get(packet, &datum, NULL);
478                         recvq.append(reinterpret_cast<const char*>(datum.data), datum.size);
479
480                         gnutls_packet_deinit(packet);
481                 }
482 #else
483                 char* const buffer;
484
485          public:
486                 DataReader(gnutls_session_t sess)
487                         : buffer(ServerInstance->GetReadBuffer())
488                 {
489                         // Read data from GnuTLS buffers into ReadBuffer
490                         retval = gnutls_record_recv(sess, buffer, ServerInstance->Config->NetBufferSize);
491                 }
492
493                 void appendto(std::string& recvq)
494                 {
495                         // Copy data from ReadBuffer to recvq
496                         recvq.append(buffer, retval);
497                 }
498 #endif
499
500                 int ret() const { return retval; }
501         };
502
503         class Profile : public refcountbase
504         {
505                 /** Name of this profile
506                  */
507                 const std::string name;
508
509                 /** X509 certificate(s) and key
510                  */
511                 X509Credentials x509cred;
512
513                 /** The minimum length in bits for the DH prime to be accepted as a client
514                  */
515                 unsigned int min_dh_bits;
516
517                 /** Hashing algorithm to use when generating certificate fingerprints
518                  */
519                 Hash hash;
520
521                 /** Priorities for ciphers, compression methods, etc.
522                  */
523                 Priority priority;
524
525                 Profile(const std::string& profilename, const std::string& certstr, const std::string& keystr,
526                                 std::auto_ptr<DHParams>& DH, unsigned int mindh, const std::string& hashstr,
527                                 const std::string& priostr, std::auto_ptr<X509CertList>& CA, std::auto_ptr<X509CRL>& CRL)
528                         : name(profilename)
529                         , x509cred(certstr, keystr)
530                         , min_dh_bits(mindh)
531                         , hash(hashstr)
532                         , priority(priostr)
533                 {
534                         x509cred.SetDH(DH);
535                         x509cred.SetCA(CA, CRL);
536                 }
537
538                 static std::string ReadFile(const std::string& filename)
539                 {
540                         FileReader reader(filename);
541                         std::string ret = reader.GetString();
542                         if (ret.empty())
543                                 throw Exception("Cannot read file " + filename);
544                         return ret;
545                 }
546
547          public:
548                 static reference<Profile> Create(const std::string& profilename, ConfigTag* tag)
549                 {
550                         std::string certstr = ReadFile(tag->getString("certfile", "cert.pem"));
551                         std::string keystr = ReadFile(tag->getString("keyfile", "key.pem"));
552
553                         std::auto_ptr<DHParams> dh;
554                         int gendh = tag->getInt("gendh");
555                         if (gendh)
556                         {
557                                 gendh = (gendh < 1024 ? 1024 : gendh);
558                                 dh = DHParams::Generate(gendh);
559                         }
560                         else
561                                 dh = DHParams::Import(ReadFile(tag->getString("dhfile", "dhparams.pem")));
562
563                         // Use default priority string if this tag does not specify one
564                         std::string priostr = tag->getString("priority", "NORMAL");
565                         unsigned int mindh = tag->getInt("mindhbits", 1024);
566                         std::string hashstr = tag->getString("hash", "md5");
567
568                         // Load trusted CA and revocation list, if set
569                         std::auto_ptr<X509CertList> ca;
570                         std::auto_ptr<X509CRL> crl;
571                         std::string filename = tag->getString("cafile");
572                         if (!filename.empty())
573                         {
574                                 ca.reset(new X509CertList(ReadFile(filename)));
575
576                                 filename = tag->getString("crlfile");
577                                 if (!filename.empty())
578                                         crl.reset(new X509CRL(ReadFile(filename)));
579                         }
580
581                         return new Profile(profilename, certstr, keystr, dh, mindh, hashstr, priostr, ca, crl);
582                 }
583
584                 /** Set up the given session with the settings in this profile
585                  */
586                 void SetupSession(gnutls_session_t sess)
587                 {
588                         priority.SetupSession(sess);
589                         x509cred.SetupSession(sess);
590                         gnutls_dh_set_prime_bits(sess, min_dh_bits);
591                 }
592
593                 const std::string& GetName() const { return name; }
594                 X509Credentials& GetX509Credentials() { return x509cred; }
595                 gnutls_digest_algorithm_t GetHash() const { return hash.get(); }
596         };
597 }
598
599 class GnuTLSIOHook : public SSLIOHook
600 {
601  private:
602         gnutls_session_t sess;
603         issl_status status;
604         reference<GnuTLS::Profile> profile;
605
606         void InitSession(StreamSocket* user, bool me_server)
607         {
608                 gnutls_init(&sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
609
610                 profile->SetupSession(sess);
611                 gnutls_transport_set_ptr(sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
612                 gnutls_transport_set_push_function(sess, gnutls_push_wrapper);
613                 gnutls_transport_set_pull_function(sess, gnutls_pull_wrapper);
614
615                 if (me_server)
616                         gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
617         }
618
619         void CloseSession()
620         {
621                 if (this->sess)
622                 {
623                         gnutls_bye(this->sess, GNUTLS_SHUT_WR);
624                         gnutls_deinit(this->sess);
625                 }
626                 sess = NULL;
627                 certificate = NULL;
628                 status = ISSL_NONE;
629         }
630
631         bool Handshake(StreamSocket* user)
632         {
633                 int ret = gnutls_handshake(this->sess);
634
635                 if (ret < 0)
636                 {
637                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
638                         {
639                                 // Handshake needs resuming later, read() or write() would have blocked.
640                                 this->status = ISSL_HANDSHAKING;
641
642                                 if (gnutls_record_get_direction(this->sess) == 0)
643                                 {
644                                         // gnutls_handshake() wants to read() again.
645                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
646                                 }
647                                 else
648                                 {
649                                         // gnutls_handshake() wants to write() again.
650                                         SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
651                                 }
652                         }
653                         else
654                         {
655                                 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
656                                 CloseSession();
657                                 this->status = ISSL_CLOSING;
658                         }
659
660                         return false;
661                 }
662                 else
663                 {
664                         // Change the seesion state
665                         this->status = ISSL_HANDSHAKEN;
666
667                         VerifyCertificate();
668
669                         // Finish writing, if any left
670                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
671
672                         return true;
673                 }
674         }
675
676         void VerifyCertificate()
677         {
678                 unsigned int certstatus;
679                 const gnutls_datum_t* cert_list;
680                 int ret;
681                 unsigned int cert_list_size;
682                 gnutls_x509_crt_t cert;
683                 char str[512];
684                 unsigned char digest[512];
685                 size_t digest_size = sizeof(digest);
686                 size_t name_size = sizeof(str);
687                 ssl_cert* certinfo = new ssl_cert;
688                 this->certificate = certinfo;
689
690                 /* This verification function uses the trusted CAs in the credentials
691                  * structure. So you must have installed one or more CA certificates.
692                  */
693                 ret = gnutls_certificate_verify_peers2(this->sess, &certstatus);
694
695                 if (ret < 0)
696                 {
697                         certinfo->error = std::string(gnutls_strerror(ret));
698                         return;
699                 }
700
701                 certinfo->invalid = (certstatus & GNUTLS_CERT_INVALID);
702                 certinfo->unknownsigner = (certstatus & GNUTLS_CERT_SIGNER_NOT_FOUND);
703                 certinfo->revoked = (certstatus & GNUTLS_CERT_REVOKED);
704                 certinfo->trusted = !(certstatus & GNUTLS_CERT_SIGNER_NOT_CA);
705
706                 /* Up to here the process is the same for X.509 certificates and
707                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
708                  * be easily extended to work with openpgp keys as well.
709                  */
710                 if (gnutls_certificate_type_get(this->sess) != GNUTLS_CRT_X509)
711                 {
712                         certinfo->error = "No X509 keys sent";
713                         return;
714                 }
715
716                 ret = gnutls_x509_crt_init(&cert);
717                 if (ret < 0)
718                 {
719                         certinfo->error = gnutls_strerror(ret);
720                         return;
721                 }
722
723                 cert_list_size = 0;
724                 cert_list = gnutls_certificate_get_peers(this->sess, &cert_list_size);
725                 if (cert_list == NULL)
726                 {
727                         certinfo->error = "No certificate was found";
728                         goto info_done_dealloc;
729                 }
730
731                 /* This is not a real world example, since we only check the first
732                  * certificate in the given chain.
733                  */
734
735                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
736                 if (ret < 0)
737                 {
738                         certinfo->error = gnutls_strerror(ret);
739                         goto info_done_dealloc;
740                 }
741
742                 if (gnutls_x509_crt_get_dn(cert, str, &name_size) == 0)
743                 {
744                         std::string& dn = certinfo->dn;
745                         dn = str;
746                         // Make sure there are no chars in the string that we consider invalid
747                         if (dn.find_first_of("\r\n") != std::string::npos)
748                                 dn.clear();
749                 }
750
751                 name_size = sizeof(str);
752                 if (gnutls_x509_crt_get_issuer_dn(cert, str, &name_size) == 0)
753                 {
754                         std::string& issuer = certinfo->issuer;
755                         issuer = str;
756                         if (issuer.find_first_of("\r\n") != std::string::npos)
757                                 issuer.clear();
758                 }
759
760                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, profile->GetHash(), digest, &digest_size)) < 0)
761                 {
762                         certinfo->error = gnutls_strerror(ret);
763                 }
764                 else
765                 {
766                         certinfo->fingerprint = BinToHex(digest, digest_size);
767                 }
768
769                 /* Beware here we do not check for errors.
770                  */
771                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
772                 {
773                         certinfo->error = "Not activated, or expired certificate";
774                 }
775
776 info_done_dealloc:
777                 gnutls_x509_crt_deinit(cert);
778         }
779
780         static const char* UnknownIfNULL(const char* str)
781         {
782                 return str ? str : "UNKNOWN";
783         }
784
785         static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
786         {
787                 StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap);
788 #ifdef _WIN32
789                 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetIOHook());
790 #endif
791
792                 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
793                 {
794 #ifdef _WIN32
795                         gnutls_transport_set_errno(session->sess, EAGAIN);
796 #else
797                         errno = EAGAIN;
798 #endif
799                         return -1;
800                 }
801
802                 int rv = SocketEngine::Recv(sock, reinterpret_cast<char *>(buffer), size, 0);
803
804 #ifdef _WIN32
805                 if (rv < 0)
806                 {
807                         /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
808                          * and then set errno appropriately.
809                          * The gnutls library may also have a different errno variable than us, see
810                          * gnutls_transport_set_errno(3).
811                          */
812                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
813                 }
814 #endif
815
816                 if (rv < (int)size)
817                         SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
818                 return rv;
819         }
820
821         static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
822         {
823                 StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap);
824 #ifdef _WIN32
825                 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetIOHook());
826 #endif
827
828                 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
829                 {
830 #ifdef _WIN32
831                         gnutls_transport_set_errno(session->sess, EAGAIN);
832 #else
833                         errno = EAGAIN;
834 #endif
835                         return -1;
836                 }
837
838                 int rv = SocketEngine::Send(sock, reinterpret_cast<const char *>(buffer), size, 0);
839
840 #ifdef _WIN32
841                 if (rv < 0)
842                 {
843                         /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
844                          * and then set errno appropriately.
845                          * The gnutls library may also have a different errno variable than us, see
846                          * gnutls_transport_set_errno(3).
847                          */
848                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
849                 }
850 #endif
851
852                 if (rv < (int)size)
853                         SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
854                 return rv;
855         }
856
857  public:
858         GnuTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool outbound, const reference<GnuTLS::Profile>& sslprofile)
859                 : SSLIOHook(hookprov)
860                 , sess(NULL)
861                 , status(ISSL_NONE)
862                 , profile(sslprofile)
863         {
864                 InitSession(sock, outbound);
865                 sock->AddIOHook(this);
866                 Handshake(sock);
867         }
868
869         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
870         {
871                 CloseSession();
872         }
873
874         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
875         {
876                 if (!this->sess)
877                 {
878                         CloseSession();
879                         user->SetError("No SSL session");
880                         return -1;
881                 }
882
883                 if (this->status == ISSL_HANDSHAKING)
884                 {
885                         // The handshake isn't finished, try to finish it.
886
887                         if (!Handshake(user))
888                         {
889                                 if (this->status != ISSL_CLOSING)
890                                         return 0;
891                                 return -1;
892                         }
893                 }
894
895                 // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN.
896
897                 if (this->status == ISSL_HANDSHAKEN)
898                 {
899                         GnuTLS::DataReader reader(sess);
900                         int ret = reader.ret();
901                         if (ret > 0)
902                         {
903                                 reader.appendto(recvq);
904                                 return 1;
905                         }
906                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
907                         {
908                                 return 0;
909                         }
910                         else if (ret == 0)
911                         {
912                                 user->SetError("Connection closed");
913                                 CloseSession();
914                                 return -1;
915                         }
916                         else
917                         {
918                                 user->SetError(gnutls_strerror(ret));
919                                 CloseSession();
920                                 return -1;
921                         }
922                 }
923                 else if (this->status == ISSL_CLOSING)
924                         return -1;
925
926                 return 0;
927         }
928
929         int OnStreamSocketWrite(StreamSocket* user, std::string& sendq) CXX11_OVERRIDE
930         {
931                 if (!this->sess)
932                 {
933                         CloseSession();
934                         user->SetError("No SSL session");
935                         return -1;
936                 }
937
938                 if (this->status == ISSL_HANDSHAKING)
939                 {
940                         // The handshake isn't finished, try to finish it.
941                         Handshake(user);
942                         if (this->status != ISSL_CLOSING)
943                                 return 0;
944                         return -1;
945                 }
946
947                 int ret = 0;
948
949                 if (this->status == ISSL_HANDSHAKEN)
950                 {
951                         ret = gnutls_record_send(this->sess, sendq.data(), sendq.length());
952
953                         if (ret == (int)sendq.length())
954                         {
955                                 SocketEngine::ChangeEventMask(user, FD_WANT_NO_WRITE);
956                                 return 1;
957                         }
958                         else if (ret > 0)
959                         {
960                                 sendq.erase(0, ret);
961                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
962                                 return 0;
963                         }
964                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
965                         {
966                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
967                                 return 0;
968                         }
969                         else // (ret < 0)
970                         {
971                                 user->SetError(gnutls_strerror(ret));
972                                 CloseSession();
973                                 return -1;
974                         }
975                 }
976
977                 return 0;
978         }
979
980         void TellCiphersAndFingerprint(LocalUser* user)
981         {
982                 if (sess)
983                 {
984                         std::string text = "*** You are connected using SSL cipher '";
985                         GetCiphersuite(text);
986                         text += '\'';
987                         if (!certificate->fingerprint.empty())
988                                 text += " and your SSL certificate fingerprint is " + certificate->fingerprint;
989
990                         user->WriteNotice(text);
991                 }
992         }
993
994         void GetCiphersuite(std::string& out) const
995         {
996                 out.append(UnknownIfNULL(gnutls_protocol_get_name(gnutls_protocol_get_version(sess)))).push_back('-');
997                 out.append(UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)))).push_back('-');
998                 out.append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).push_back('-');
999                 out.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
1000         }
1001
1002         GnuTLS::Profile* GetProfile() { return profile; }
1003 };
1004
1005 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)
1006 {
1007 #ifndef GNUTLS_NEW_CERT_CALLBACK_API
1008         st->type = GNUTLS_CRT_X509;
1009 #else
1010         st->cert_type = GNUTLS_CRT_X509;
1011         st->key_type = GNUTLS_PRIVKEY_X509;
1012 #endif
1013         StreamSocket* sock = reinterpret_cast<StreamSocket*>(gnutls_transport_get_ptr(sess));
1014         GnuTLS::X509Credentials& cred = static_cast<GnuTLSIOHook*>(sock->GetIOHook())->GetProfile()->GetX509Credentials();
1015
1016         st->ncerts = cred.certs.size();
1017         st->cert.x509 = cred.certs.raw();
1018         st->key.x509 = cred.key.get();
1019         st->deinit_all = 0;
1020
1021         return 0;
1022 }
1023
1024 class GnuTLSIOHookProvider : public refcountbase, public IOHookProvider
1025 {
1026         reference<GnuTLS::Profile> profile;
1027
1028  public:
1029         GnuTLSIOHookProvider(Module* mod, reference<GnuTLS::Profile>& prof)
1030                 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
1031                 , profile(prof)
1032         {
1033                 ServerInstance->Modules->AddService(*this);
1034         }
1035
1036         ~GnuTLSIOHookProvider()
1037         {
1038                 ServerInstance->Modules->DelService(*this);
1039         }
1040
1041         void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
1042         {
1043                 new GnuTLSIOHook(this, sock, true, profile);
1044         }
1045
1046         void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
1047         {
1048                 new GnuTLSIOHook(this, sock, false, profile);
1049         }
1050 };
1051
1052 class ModuleSSLGnuTLS : public Module
1053 {
1054         typedef std::vector<reference<GnuTLSIOHookProvider> > ProfileList;
1055
1056         // First member of the class, gets constructed first and destructed last
1057         GnuTLS::Init libinit;
1058         RandGen randhandler;
1059         ProfileList profiles;
1060
1061         void ReadProfiles()
1062         {
1063                 // First, store all profiles in a new, temporary container. If no problems occur, swap the two
1064                 // containers; this way if something goes wrong we can go back and continue using the current profiles,
1065                 // avoiding unpleasant situations where no new SSL connections are possible.
1066                 ProfileList newprofiles;
1067
1068                 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
1069                 if (tags.first == tags.second)
1070                 {
1071                         // No <sslprofile> tags found, create a profile named "gnutls" from settings in the <gnutls> block
1072                         const std::string defname = "gnutls";
1073                         ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
1074                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <gnutls> tag");
1075
1076                         try
1077                         {
1078                                 reference<GnuTLS::Profile> profile(GnuTLS::Profile::Create(defname, tag));
1079                                 newprofiles.push_back(new GnuTLSIOHookProvider(this, profile));
1080                         }
1081                         catch (CoreException& ex)
1082                         {
1083                                 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
1084                         }
1085                 }
1086
1087                 for (ConfigIter i = tags.first; i != tags.second; ++i)
1088                 {
1089                         ConfigTag* tag = i->second;
1090                         if (tag->getString("provider") != "gnutls")
1091                                 continue;
1092
1093                         std::string name = tag->getString("name");
1094                         if (name.empty())
1095                         {
1096                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
1097                                 continue;
1098                         }
1099
1100                         reference<GnuTLS::Profile> profile;
1101                         try
1102                         {
1103                                 profile = GnuTLS::Profile::Create(name, tag);
1104                         }
1105                         catch (CoreException& ex)
1106                         {
1107                                 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
1108                         }
1109
1110                         newprofiles.push_back(new GnuTLSIOHookProvider(this, profile));
1111                 }
1112
1113                 // New profiles are ok, begin using them
1114                 // Old profiles are deleted when their refcount drops to zero
1115                 profiles.swap(newprofiles);
1116         }
1117
1118  public:
1119         ModuleSSLGnuTLS()
1120         {
1121 #ifndef GNUTLS_HAS_RND
1122                 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
1123 #endif
1124         }
1125
1126         void init() CXX11_OVERRIDE
1127         {
1128                 ReadProfiles();
1129                 ServerInstance->GenRandom = &randhandler;
1130         }
1131
1132         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
1133         {
1134                 if(param != "ssl")
1135                         return;
1136
1137                 try
1138                 {
1139                         ReadProfiles();
1140                 }
1141                 catch (ModuleException& ex)
1142                 {
1143                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
1144                 }
1145         }
1146
1147         ~ModuleSSLGnuTLS()
1148         {
1149                 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
1150         }
1151
1152         void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
1153         {
1154                 if(target_type == TYPE_USER)
1155                 {
1156                         LocalUser* user = IS_LOCAL(static_cast<User*>(item));
1157
1158                         if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this)
1159                         {
1160                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
1161                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
1162                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
1163                         }
1164                 }
1165         }
1166
1167         Version GetVersion() CXX11_OVERRIDE
1168         {
1169                 return Version("Provides SSL support for clients", VF_VENDOR);
1170         }
1171
1172         void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
1173         {
1174                 IOHook* hook = user->eh.GetIOHook();
1175                 if (hook && hook->prov->creator == this)
1176                         static_cast<GnuTLSIOHook*>(hook)->TellCiphersAndFingerprint(user);
1177         }
1178 };
1179
1180 MODULE_INIT(ModuleSSLGnuTLS)