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