]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
m_ssl_gnutls, m_ssl_openssl Simplify status handling in IOHook read/write handlers
[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 };
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         // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
632         int Handshake(StreamSocket* user)
633         {
634                 int ret = gnutls_handshake(this->sess);
635
636                 if (ret < 0)
637                 {
638                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
639                         {
640                                 // Handshake needs resuming later, read() or write() would have blocked.
641                                 this->status = ISSL_HANDSHAKING;
642
643                                 if (gnutls_record_get_direction(this->sess) == 0)
644                                 {
645                                         // gnutls_handshake() wants to read() again.
646                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
647                                 }
648                                 else
649                                 {
650                                         // gnutls_handshake() wants to write() again.
651                                         SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
652                                 }
653
654                                 return 0;
655                         }
656                         else
657                         {
658                                 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
659                                 CloseSession();
660                                 return -1;
661                         }
662                 }
663                 else
664                 {
665                         // Change the seesion state
666                         this->status = ISSL_HANDSHAKEN;
667
668                         VerifyCertificate();
669
670                         // Finish writing, if any left
671                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
672
673                         return 1;
674                 }
675         }
676
677         void VerifyCertificate()
678         {
679                 unsigned int certstatus;
680                 const gnutls_datum_t* cert_list;
681                 int ret;
682                 unsigned int cert_list_size;
683                 gnutls_x509_crt_t cert;
684                 char str[512];
685                 unsigned char digest[512];
686                 size_t digest_size = sizeof(digest);
687                 size_t name_size = sizeof(str);
688                 ssl_cert* certinfo = new ssl_cert;
689                 this->certificate = certinfo;
690
691                 /* This verification function uses the trusted CAs in the credentials
692                  * structure. So you must have installed one or more CA certificates.
693                  */
694                 ret = gnutls_certificate_verify_peers2(this->sess, &certstatus);
695
696                 if (ret < 0)
697                 {
698                         certinfo->error = std::string(gnutls_strerror(ret));
699                         return;
700                 }
701
702                 certinfo->invalid = (certstatus & GNUTLS_CERT_INVALID);
703                 certinfo->unknownsigner = (certstatus & GNUTLS_CERT_SIGNER_NOT_FOUND);
704                 certinfo->revoked = (certstatus & GNUTLS_CERT_REVOKED);
705                 certinfo->trusted = !(certstatus & GNUTLS_CERT_SIGNER_NOT_CA);
706
707                 /* Up to here the process is the same for X.509 certificates and
708                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
709                  * be easily extended to work with openpgp keys as well.
710                  */
711                 if (gnutls_certificate_type_get(this->sess) != GNUTLS_CRT_X509)
712                 {
713                         certinfo->error = "No X509 keys sent";
714                         return;
715                 }
716
717                 ret = gnutls_x509_crt_init(&cert);
718                 if (ret < 0)
719                 {
720                         certinfo->error = gnutls_strerror(ret);
721                         return;
722                 }
723
724                 cert_list_size = 0;
725                 cert_list = gnutls_certificate_get_peers(this->sess, &cert_list_size);
726                 if (cert_list == NULL)
727                 {
728                         certinfo->error = "No certificate was found";
729                         goto info_done_dealloc;
730                 }
731
732                 /* This is not a real world example, since we only check the first
733                  * certificate in the given chain.
734                  */
735
736                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
737                 if (ret < 0)
738                 {
739                         certinfo->error = gnutls_strerror(ret);
740                         goto info_done_dealloc;
741                 }
742
743                 if (gnutls_x509_crt_get_dn(cert, str, &name_size) == 0)
744                 {
745                         std::string& dn = certinfo->dn;
746                         dn = str;
747                         // Make sure there are no chars in the string that we consider invalid
748                         if (dn.find_first_of("\r\n") != std::string::npos)
749                                 dn.clear();
750                 }
751
752                 name_size = sizeof(str);
753                 if (gnutls_x509_crt_get_issuer_dn(cert, str, &name_size) == 0)
754                 {
755                         std::string& issuer = certinfo->issuer;
756                         issuer = str;
757                         if (issuer.find_first_of("\r\n") != std::string::npos)
758                                 issuer.clear();
759                 }
760
761                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, profile->GetHash(), digest, &digest_size)) < 0)
762                 {
763                         certinfo->error = gnutls_strerror(ret);
764                 }
765                 else
766                 {
767                         certinfo->fingerprint = BinToHex(digest, digest_size);
768                 }
769
770                 /* Beware here we do not check for errors.
771                  */
772                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
773                 {
774                         certinfo->error = "Not activated, or expired certificate";
775                 }
776
777 info_done_dealloc:
778                 gnutls_x509_crt_deinit(cert);
779         }
780
781         static const char* UnknownIfNULL(const char* str)
782         {
783                 return str ? str : "UNKNOWN";
784         }
785
786         static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
787         {
788                 StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap);
789 #ifdef _WIN32
790                 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetIOHook());
791 #endif
792
793                 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
794                 {
795 #ifdef _WIN32
796                         gnutls_transport_set_errno(session->sess, EAGAIN);
797 #else
798                         errno = EAGAIN;
799 #endif
800                         return -1;
801                 }
802
803                 int rv = SocketEngine::Recv(sock, reinterpret_cast<char *>(buffer), size, 0);
804
805 #ifdef _WIN32
806                 if (rv < 0)
807                 {
808                         /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
809                          * and then set errno appropriately.
810                          * The gnutls library may also have a different errno variable than us, see
811                          * gnutls_transport_set_errno(3).
812                          */
813                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
814                 }
815 #endif
816
817                 if (rv < (int)size)
818                         SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
819                 return rv;
820         }
821
822         static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
823         {
824                 StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap);
825 #ifdef _WIN32
826                 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetIOHook());
827 #endif
828
829                 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
830                 {
831 #ifdef _WIN32
832                         gnutls_transport_set_errno(session->sess, EAGAIN);
833 #else
834                         errno = EAGAIN;
835 #endif
836                         return -1;
837                 }
838
839                 int rv = SocketEngine::Send(sock, reinterpret_cast<const char *>(buffer), size, 0);
840
841 #ifdef _WIN32
842                 if (rv < 0)
843                 {
844                         /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
845                          * and then set errno appropriately.
846                          * The gnutls library may also have a different errno variable than us, see
847                          * gnutls_transport_set_errno(3).
848                          */
849                         gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
850                 }
851 #endif
852
853                 if (rv < (int)size)
854                         SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
855                 return rv;
856         }
857
858  public:
859         GnuTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool outbound, const reference<GnuTLS::Profile>& sslprofile)
860                 : SSLIOHook(hookprov)
861                 , sess(NULL)
862                 , status(ISSL_NONE)
863                 , profile(sslprofile)
864         {
865                 InitSession(sock, outbound);
866                 sock->AddIOHook(this);
867                 Handshake(sock);
868         }
869
870         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
871         {
872                 CloseSession();
873         }
874
875         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
876         {
877                 if (!this->sess)
878                 {
879                         CloseSession();
880                         user->SetError("No SSL session");
881                         return -1;
882                 }
883
884                 if (this->status == ISSL_HANDSHAKING)
885                 {
886                         // The handshake isn't finished, try to finish it.
887                         int ret = Handshake(user);
888                         if (ret <= 0)
889                                 return ret;
890                 }
891
892                 // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN.
893                 {
894                         GnuTLS::DataReader reader(sess);
895                         int ret = reader.ret();
896                         if (ret > 0)
897                         {
898                                 reader.appendto(recvq);
899                                 return 1;
900                         }
901                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
902                         {
903                                 return 0;
904                         }
905                         else if (ret == 0)
906                         {
907                                 user->SetError("Connection closed");
908                                 CloseSession();
909                                 return -1;
910                         }
911                         else
912                         {
913                                 user->SetError(gnutls_strerror(ret));
914                                 CloseSession();
915                                 return -1;
916                         }
917                 }
918         }
919
920         int OnStreamSocketWrite(StreamSocket* user, std::string& sendq) CXX11_OVERRIDE
921         {
922                 if (!this->sess)
923                 {
924                         CloseSession();
925                         user->SetError("No SSL session");
926                         return -1;
927                 }
928
929                 if (this->status == ISSL_HANDSHAKING)
930                 {
931                         // The handshake isn't finished, try to finish it.
932                         int ret = Handshake(user);
933                         if (ret <= 0)
934                                 return ret;
935                 }
936
937                 // Session is ready for transferring application data
938                 int ret = 0;
939
940                 {
941                         ret = gnutls_record_send(this->sess, sendq.data(), sendq.length());
942
943                         if (ret == (int)sendq.length())
944                         {
945                                 SocketEngine::ChangeEventMask(user, FD_WANT_NO_WRITE);
946                                 return 1;
947                         }
948                         else if (ret > 0)
949                         {
950                                 sendq.erase(0, ret);
951                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
952                                 return 0;
953                         }
954                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
955                         {
956                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
957                                 return 0;
958                         }
959                         else // (ret < 0)
960                         {
961                                 user->SetError(gnutls_strerror(ret));
962                                 CloseSession();
963                                 return -1;
964                         }
965                 }
966         }
967
968         void TellCiphersAndFingerprint(LocalUser* user)
969         {
970                 if (sess)
971                 {
972                         std::string text = "*** You are connected using SSL cipher '";
973                         GetCiphersuite(text);
974                         text += '\'';
975                         if (!certificate->fingerprint.empty())
976                                 text += " and your SSL certificate fingerprint is " + certificate->fingerprint;
977
978                         user->WriteNotice(text);
979                 }
980         }
981
982         void GetCiphersuite(std::string& out) const
983         {
984                 out.append(UnknownIfNULL(gnutls_protocol_get_name(gnutls_protocol_get_version(sess)))).push_back('-');
985                 out.append(UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)))).push_back('-');
986                 out.append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).push_back('-');
987                 out.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
988         }
989
990         GnuTLS::Profile* GetProfile() { return profile; }
991 };
992
993 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)
994 {
995 #ifndef GNUTLS_NEW_CERT_CALLBACK_API
996         st->type = GNUTLS_CRT_X509;
997 #else
998         st->cert_type = GNUTLS_CRT_X509;
999         st->key_type = GNUTLS_PRIVKEY_X509;
1000 #endif
1001         StreamSocket* sock = reinterpret_cast<StreamSocket*>(gnutls_transport_get_ptr(sess));
1002         GnuTLS::X509Credentials& cred = static_cast<GnuTLSIOHook*>(sock->GetIOHook())->GetProfile()->GetX509Credentials();
1003
1004         st->ncerts = cred.certs.size();
1005         st->cert.x509 = cred.certs.raw();
1006         st->key.x509 = cred.key.get();
1007         st->deinit_all = 0;
1008
1009         return 0;
1010 }
1011
1012 class GnuTLSIOHookProvider : public refcountbase, public IOHookProvider
1013 {
1014         reference<GnuTLS::Profile> profile;
1015
1016  public:
1017         GnuTLSIOHookProvider(Module* mod, reference<GnuTLS::Profile>& prof)
1018                 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
1019                 , profile(prof)
1020         {
1021                 ServerInstance->Modules->AddService(*this);
1022         }
1023
1024         ~GnuTLSIOHookProvider()
1025         {
1026                 ServerInstance->Modules->DelService(*this);
1027         }
1028
1029         void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
1030         {
1031                 new GnuTLSIOHook(this, sock, true, profile);
1032         }
1033
1034         void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
1035         {
1036                 new GnuTLSIOHook(this, sock, false, profile);
1037         }
1038 };
1039
1040 class ModuleSSLGnuTLS : public Module
1041 {
1042         typedef std::vector<reference<GnuTLSIOHookProvider> > ProfileList;
1043
1044         // First member of the class, gets constructed first and destructed last
1045         GnuTLS::Init libinit;
1046         RandGen randhandler;
1047         ProfileList profiles;
1048
1049         void ReadProfiles()
1050         {
1051                 // First, store all profiles in a new, temporary container. If no problems occur, swap the two
1052                 // containers; this way if something goes wrong we can go back and continue using the current profiles,
1053                 // avoiding unpleasant situations where no new SSL connections are possible.
1054                 ProfileList newprofiles;
1055
1056                 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
1057                 if (tags.first == tags.second)
1058                 {
1059                         // No <sslprofile> tags found, create a profile named "gnutls" from settings in the <gnutls> block
1060                         const std::string defname = "gnutls";
1061                         ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
1062                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <gnutls> tag");
1063
1064                         try
1065                         {
1066                                 reference<GnuTLS::Profile> profile(GnuTLS::Profile::Create(defname, tag));
1067                                 newprofiles.push_back(new GnuTLSIOHookProvider(this, profile));
1068                         }
1069                         catch (CoreException& ex)
1070                         {
1071                                 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
1072                         }
1073                 }
1074
1075                 for (ConfigIter i = tags.first; i != tags.second; ++i)
1076                 {
1077                         ConfigTag* tag = i->second;
1078                         if (tag->getString("provider") != "gnutls")
1079                                 continue;
1080
1081                         std::string name = tag->getString("name");
1082                         if (name.empty())
1083                         {
1084                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
1085                                 continue;
1086                         }
1087
1088                         reference<GnuTLS::Profile> profile;
1089                         try
1090                         {
1091                                 profile = GnuTLS::Profile::Create(name, tag);
1092                         }
1093                         catch (CoreException& ex)
1094                         {
1095                                 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
1096                         }
1097
1098                         newprofiles.push_back(new GnuTLSIOHookProvider(this, profile));
1099                 }
1100
1101                 // New profiles are ok, begin using them
1102                 // Old profiles are deleted when their refcount drops to zero
1103                 profiles.swap(newprofiles);
1104         }
1105
1106  public:
1107         ModuleSSLGnuTLS()
1108         {
1109 #ifndef GNUTLS_HAS_RND
1110                 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
1111 #endif
1112         }
1113
1114         void init() CXX11_OVERRIDE
1115         {
1116                 ReadProfiles();
1117                 ServerInstance->GenRandom = &randhandler;
1118         }
1119
1120         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
1121         {
1122                 if(param != "ssl")
1123                         return;
1124
1125                 try
1126                 {
1127                         ReadProfiles();
1128                 }
1129                 catch (ModuleException& ex)
1130                 {
1131                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
1132                 }
1133         }
1134
1135         ~ModuleSSLGnuTLS()
1136         {
1137                 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
1138         }
1139
1140         void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
1141         {
1142                 if(target_type == TYPE_USER)
1143                 {
1144                         LocalUser* user = IS_LOCAL(static_cast<User*>(item));
1145
1146                         if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this)
1147                         {
1148                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
1149                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
1150                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
1151                         }
1152                 }
1153         }
1154
1155         Version GetVersion() CXX11_OVERRIDE
1156         {
1157                 return Version("Provides SSL support for clients", VF_VENDOR);
1158         }
1159
1160         void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
1161         {
1162                 IOHook* hook = user->eh.GetIOHook();
1163                 if (hook && hook->prov->creator == this)
1164                         static_cast<GnuTLSIOHook*>(hook)->TellCiphersAndFingerprint(user);
1165         }
1166 };
1167
1168 MODULE_INIT(ModuleSSLGnuTLS)