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