2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
23 /// $CompilerFlags: find_compiler_flags("gnutls")
24 /// $CompilerFlags: require_version("gnutls" "1.0" "2.12") execute("libgcrypt-config --cflags" "LIBGCRYPT_CXXFLAGS")
26 /// $LinkerFlags: find_linker_flags("gnutls" "-lgnutls")
27 /// $LinkerFlags: require_version("gnutls" "1.0" "2.12") execute("libgcrypt-config --libs" "LIBGCRYPT_LDFLAGS")
29 /// $PackageInfo: require_system("arch") gnutls pkgconf
30 /// $PackageInfo: require_system("centos") gnutls-devel pkgconfig
31 /// $PackageInfo: require_system("darwin") gnutls pkg-config
32 /// $PackageInfo: require_system("debian" "1.0" "7.99") libgcrypt11-dev
33 /// $PackageInfo: require_system("debian") gnutls-bin libgnutls28-dev pkg-config
34 /// $PackageInfo: require_system("ubuntu" "1.0" "13.10") libgcrypt11-dev
35 /// $PackageInfo: require_system("ubuntu") gnutls-bin libgnutls-dev pkg-config
38 #include "modules/ssl.h"
42 # pragma GCC diagnostic push
45 // Fix warnings about the use of commas at end of enumerator lists on C++03.
47 # pragma clang diagnostic ignored "-Wc++11-extensions"
48 #elif defined __GNUC__
49 # if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))
50 # pragma GCC diagnostic ignored "-Wpedantic"
52 # pragma GCC diagnostic ignored "-pedantic"
56 // Fix warnings about using std::auto_ptr on C++11 or newer.
57 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
59 #include <gnutls/gnutls.h>
60 #include <gnutls/x509.h>
63 # pragma GCC diagnostic pop
66 #ifndef GNUTLS_VERSION_NUMBER
67 #define GNUTLS_VERSION_NUMBER LIBGNUTLS_VERSION_NUMBER
68 #define GNUTLS_VERSION LIBGNUTLS_VERSION
71 // Check if the GnuTLS library is at least version major.minor.patch
72 #define INSPIRCD_GNUTLS_HAS_VERSION(major, minor, patch) (GNUTLS_VERSION_NUMBER >= ((major << 16) | (minor << 8) | patch))
74 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 9, 8)
75 #define GNUTLS_HAS_MAC_GET_ID
76 #include <gnutls/crypto.h>
79 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 12, 0)
80 # define GNUTLS_HAS_RND
86 # pragma comment(lib, "libgnutls-30.lib")
89 // These don't exist in older GnuTLS versions
90 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 1, 7)
91 #define GNUTLS_NEW_PRIO_API
94 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_HANDSHAKEN };
96 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 12, 0)
97 #define INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
98 #define GNUTLS_NEW_CERT_CALLBACK_API
99 typedef gnutls_retr2_st cert_cb_last_param_type;
101 typedef gnutls_retr_st cert_cb_last_param_type;
104 #if INSPIRCD_GNUTLS_HAS_VERSION(3, 3, 5)
105 #define INSPIRCD_GNUTLS_HAS_RECV_PACKET
108 #if INSPIRCD_GNUTLS_HAS_VERSION(2, 99, 0)
109 // The second parameter of gnutls_init() has changed in 2.99.0 from gnutls_connection_end_t to unsigned int
110 // (it became a general flags parameter) and the enum has been deprecated and generates a warning on use.
111 typedef unsigned int inspircd_gnutls_session_init_flags_t;
113 typedef gnutls_connection_end_t inspircd_gnutls_session_init_flags_t;
116 #if INSPIRCD_GNUTLS_HAS_VERSION(3, 1, 9)
117 #define INSPIRCD_GNUTLS_HAS_CORK
120 static Module* thismod;
125 static void Call(char* buffer, size_t len)
127 #ifdef GNUTLS_HAS_RND
128 gnutls_rnd(GNUTLS_RND_RANDOM, buffer, len);
130 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
140 Init() { gnutls_global_init(); }
141 ~Init() { gnutls_global_deinit(); }
144 class Exception : public ModuleException
147 Exception(const std::string& reason)
148 : ModuleException(reason) { }
151 void ThrowOnError(int errcode, const char* msg)
155 std::string reason = msg;
156 reason.append(" :").append(gnutls_strerror(errcode));
157 throw Exception(reason);
161 /** Used to create a gnutls_datum_t* from a std::string
165 gnutls_datum_t datum;
168 Datum(const std::string& dat)
170 datum.data = (unsigned char*)dat.data();
171 datum.size = static_cast<unsigned int>(dat.length());
174 const gnutls_datum_t* get() const { return &datum; }
179 gnutls_digest_algorithm_t hash;
182 // Nothing to deallocate, constructor may throw freely
183 Hash(const std::string& hashname)
185 // As older versions of gnutls can't do this, let's disable it where needed.
186 #ifdef GNUTLS_HAS_MAC_GET_ID
187 // As gnutls_digest_algorithm_t and gnutls_mac_algorithm_t are mapped 1:1, we can do this
188 // There is no gnutls_dig_get_id() at the moment, but it may come later
189 hash = (gnutls_digest_algorithm_t)gnutls_mac_get_id(hashname.c_str());
190 if (hash == GNUTLS_DIG_UNKNOWN)
191 throw Exception("Unknown hash type " + hashname);
193 // Check if the user is giving us something that is a valid MAC but not digest
194 gnutls_hash_hd_t is_digest;
195 if (gnutls_hash_init(&is_digest, hash) < 0)
196 throw Exception("Unknown hash type " + hashname);
197 gnutls_hash_deinit(is_digest, NULL);
199 if (stdalgo::string::equalsci(hashname, "md5"))
200 hash = GNUTLS_DIG_MD5;
201 else if (stdalgo::string::equalsci(hashname, "sha1"))
202 hash = GNUTLS_DIG_SHA1;
203 else if (stdalgo::string::equalsci(hashname, "sha256"))
204 hash = GNUTLS_DIG_SHA256;
206 throw Exception("Unknown hash type " + hashname);
210 gnutls_digest_algorithm_t get() const { return hash; }
215 gnutls_dh_params_t dh_params;
219 ThrowOnError(gnutls_dh_params_init(&dh_params), "gnutls_dh_params_init() failed");
224 static std::auto_ptr<DHParams> Import(const std::string& dhstr)
226 std::auto_ptr<DHParams> dh(new DHParams);
227 int ret = gnutls_dh_params_import_pkcs3(dh->dh_params, Datum(dhstr).get(), GNUTLS_X509_FMT_PEM);
228 ThrowOnError(ret, "Unable to import DH params");
234 gnutls_dh_params_deinit(dh_params);
237 const gnutls_dh_params_t& get() const { return dh_params; }
242 /** Ensure that the key is deinited in case the constructor of X509Key throws
247 gnutls_x509_privkey_t key;
251 ThrowOnError(gnutls_x509_privkey_init(&key), "gnutls_x509_privkey_init() failed");
256 gnutls_x509_privkey_deinit(key);
262 X509Key(const std::string& keystr)
264 int ret = gnutls_x509_privkey_import(key.key, Datum(keystr).get(), GNUTLS_X509_FMT_PEM);
265 ThrowOnError(ret, "Unable to import private key");
268 gnutls_x509_privkey_t& get() { return key.key; }
273 std::vector<gnutls_x509_crt_t> certs;
277 X509CertList(const std::string& certstr)
279 unsigned int certcount = 3;
280 certs.resize(certcount);
281 Datum datum(certstr);
283 int ret = gnutls_x509_crt_list_import(raw(), &certcount, datum.get(), GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
284 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
286 // the buffer wasn't big enough to hold all certs but gnutls changed certcount to the number of available certs,
287 // try again with a bigger buffer
288 certs.resize(certcount);
289 ret = gnutls_x509_crt_list_import(raw(), &certcount, datum.get(), GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
292 ThrowOnError(ret, "Unable to load certificates");
294 // Resize the vector to the actual number of certs because we rely on its size being correct
295 // when deallocating the certs
296 certs.resize(certcount);
301 for (std::vector<gnutls_x509_crt_t>::iterator i = certs.begin(); i != certs.end(); ++i)
302 gnutls_x509_crt_deinit(*i);
305 gnutls_x509_crt_t* raw() { return &certs[0]; }
306 unsigned int size() const { return certs.size(); }
309 class X509CRL : public refcountbase
314 gnutls_x509_crl_t crl;
318 ThrowOnError(gnutls_x509_crl_init(&crl), "gnutls_x509_crl_init() failed");
323 gnutls_x509_crl_deinit(crl);
329 X509CRL(const std::string& crlstr)
331 int ret = gnutls_x509_crl_import(get(), Datum(crlstr).get(), GNUTLS_X509_FMT_PEM);
332 ThrowOnError(ret, "Unable to load certificate revocation list");
335 gnutls_x509_crl_t& get() { return crl.crl; }
338 #ifdef GNUTLS_NEW_PRIO_API
341 gnutls_priority_t priority;
344 Priority(const std::string& priorities)
346 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
347 // If the user did not supply anything then the string is already set to "NORMAL"
348 const char* priocstr = priorities.c_str();
349 const char* prioerror;
351 int ret = gnutls_priority_init(&priority, priocstr, &prioerror);
354 // gnutls did not understand the user supplied string
355 throw Exception("Unable to initialize priorities to \"" + priorities + "\": " + gnutls_strerror(ret) + " Syntax error at position " + ConvToStr((unsigned int) (prioerror - priocstr)));
361 gnutls_priority_deinit(priority);
364 void SetupSession(gnutls_session_t sess)
366 gnutls_priority_set(sess, priority);
369 static const char* GetDefault()
371 return "NORMAL:%SERVER_PRECEDENCE:-VERS-SSL3.0";
374 static std::string RemoveUnknownTokens(const std::string& prio)
377 irc::sepstream ss(prio, ':');
378 for (std::string token; ss.GetToken(token); )
380 // Save current position so we can revert later if needed
381 const std::string::size_type prevpos = ret.length();
387 gnutls_priority_t test;
388 if (gnutls_priority_init(&test, ret.c_str(), NULL) < 0)
390 // The new token broke the priority string, revert to the previously working one
391 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Priority string token not recognized: \"%s\"", token.c_str());
397 gnutls_priority_deinit(test);
404 /** Dummy class, used when gnutls_priority_set() is not available
409 Priority(const std::string& priorities)
411 if (priorities != GetDefault())
412 throw Exception("You've set a non-default priority string, but GnuTLS lacks support for it");
415 static void SetupSession(gnutls_session_t sess)
417 // Always set the default priorities
418 gnutls_set_default_priority(sess);
421 static const char* GetDefault()
426 static std::string RemoveUnknownTokens(const std::string& prio)
428 // We don't do anything here because only NORMAL is accepted
434 class CertCredentials
436 /** DH parameters associated with these credentials
438 std::auto_ptr<DHParams> dh;
441 gnutls_certificate_credentials_t cred;
446 ThrowOnError(gnutls_certificate_allocate_credentials(&cred), "Cannot allocate certificate credentials");
451 gnutls_certificate_free_credentials(cred);
454 /** Associates these credentials with the session
456 void SetupSession(gnutls_session_t sess)
458 gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, cred);
461 /** Set the given DH parameters to be used with these credentials
463 void SetDH(std::auto_ptr<DHParams>& DH)
466 gnutls_certificate_set_dh_params(cred, dh->get());
470 class X509Credentials : public CertCredentials
476 /** Certificate list, presented to the peer
480 /** Trusted CA, may be NULL
482 std::auto_ptr<X509CertList> trustedca;
484 /** Certificate revocation list, may be NULL
486 std::auto_ptr<X509CRL> crl;
488 static int cert_callback(gnutls_session_t session, const gnutls_datum_t* req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t* sign_algos, int sign_algos_length, cert_cb_last_param_type* st);
491 X509Credentials(const std::string& certstr, const std::string& keystr)
495 // Throwing is ok here, the destructor of Credentials is called in that case
496 int ret = gnutls_certificate_set_x509_key(cred, certs.raw(), certs.size(), key.get());
497 ThrowOnError(ret, "Unable to set cert/key pair");
499 #ifdef GNUTLS_NEW_CERT_CALLBACK_API
500 gnutls_certificate_set_retrieve_function(cred, cert_callback);
502 gnutls_certificate_client_set_retrieve_function(cred, cert_callback);
506 /** Sets the trusted CA and the certificate revocation list
507 * to use when verifying certificates
509 void SetCA(std::auto_ptr<X509CertList>& certlist, std::auto_ptr<X509CRL>& CRL)
511 // Do nothing if certlist is NULL
514 int ret = gnutls_certificate_set_x509_trust(cred, certlist->raw(), certlist->size());
515 ThrowOnError(ret, "gnutls_certificate_set_x509_trust() failed");
519 ret = gnutls_certificate_set_x509_crl(cred, &CRL->get(), 1);
520 ThrowOnError(ret, "gnutls_certificate_set_x509_crl() failed");
523 trustedca = certlist;
532 #ifdef INSPIRCD_GNUTLS_HAS_RECV_PACKET
533 gnutls_packet_t packet;
536 DataReader(gnutls_session_t sess)
538 // Using the packet API avoids the final copy of the data which GnuTLS does if we supply
539 // our own buffer. Instead, we get the buffer containing the data from GnuTLS and copy it
540 // to the recvq directly from there in appendto().
541 retval = gnutls_record_recv_packet(sess, &packet);
544 void appendto(std::string& recvq)
546 // Copy data from GnuTLS buffers to recvq
547 gnutls_datum_t datum;
548 gnutls_packet_get(packet, &datum, NULL);
549 recvq.append(reinterpret_cast<const char*>(datum.data), datum.size);
551 gnutls_packet_deinit(packet);
557 DataReader(gnutls_session_t sess)
558 : buffer(ServerInstance->GetReadBuffer())
560 // Read data from GnuTLS buffers into ReadBuffer
561 retval = gnutls_record_recv(sess, buffer, ServerInstance->Config->NetBufferSize);
564 void appendto(std::string& recvq)
566 // Copy data from ReadBuffer to recvq
567 recvq.append(buffer, retval);
571 int ret() const { return retval; }
576 /** Name of this profile
578 const std::string name;
580 /** X509 certificate(s) and key
582 X509Credentials x509cred;
584 /** The minimum length in bits for the DH prime to be accepted as a client
586 unsigned int min_dh_bits;
588 /** Hashing algorithm to use when generating certificate fingerprints
592 /** Priorities for ciphers, compression methods, etc.
596 /** Rough max size of records to send
598 const unsigned int outrecsize;
600 /** True to request a client certificate as a server
602 const bool requestclientcert;
604 static std::string ReadFile(const std::string& filename)
606 FileReader reader(filename);
607 std::string ret = reader.GetString();
609 throw Exception("Cannot read file " + filename);
613 static std::string GetPrioStr(const std::string& profilename, ConfigTag* tag)
615 // Use default priority string if this tag does not specify one
616 std::string priostr = GnuTLS::Priority::GetDefault();
617 bool found = tag->readString("priority", priostr);
618 // If the prio string isn't set in the config don't be strict about the default one because it doesn't work on all versions of GnuTLS
619 if (!tag->getBool("strictpriority", found))
621 std::string stripped = GnuTLS::Priority::RemoveUnknownTokens(priostr);
622 if (stripped.empty())
624 // Stripping failed, act as if a prio string wasn't set
625 stripped = GnuTLS::Priority::RemoveUnknownTokens(GnuTLS::Priority::GetDefault());
626 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Priority string for profile \"%s\" contains unknown tokens and stripping it didn't yield a working one either, falling back to \"%s\"", profilename.c_str(), stripped.c_str());
628 else if ((found) && (stripped != priostr))
630 // Prio string was set in the config and we ended up with something that works but different
631 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Priority string for profile \"%s\" contains unknown tokens, stripped to \"%s\"", profilename.c_str(), stripped.c_str());
633 priostr.swap(stripped);
643 std::auto_ptr<X509CertList> ca;
644 std::auto_ptr<X509CRL> crl;
648 std::auto_ptr<DHParams> dh;
654 unsigned int outrecsize;
655 bool requestclientcert;
657 Config(const std::string& profilename, ConfigTag* tag)
659 , certstr(ReadFile(tag->getString("certfile", "cert.pem")))
660 , keystr(ReadFile(tag->getString("keyfile", "key.pem")))
661 , dh(DHParams::Import(ReadFile(tag->getString("dhfile", "dhparams.pem"))))
662 , priostr(GetPrioStr(profilename, tag))
663 , mindh(tag->getUInt("mindhbits", 1024))
664 , hashstr(tag->getString("hash", "md5"))
665 , requestclientcert(tag->getBool("requestclientcert", true))
667 // Load trusted CA and revocation list, if set
668 std::string filename = tag->getString("cafile");
669 if (!filename.empty())
671 ca.reset(new X509CertList(ReadFile(filename)));
673 filename = tag->getString("crlfile");
674 if (!filename.empty())
675 crl.reset(new X509CRL(ReadFile(filename)));
678 #ifdef INSPIRCD_GNUTLS_HAS_CORK
679 // If cork support is available outrecsize represents the (rough) max amount of data we give GnuTLS while corked
680 outrecsize = tag->getUInt("outrecsize", 2048, 512);
682 outrecsize = tag->getUInt("outrecsize", 2048, 512, 16384);
687 Profile(Config& config)
689 , x509cred(config.certstr, config.keystr)
690 , min_dh_bits(config.mindh)
691 , hash(config.hashstr)
692 , priority(config.priostr)
693 , outrecsize(config.outrecsize)
694 , requestclientcert(config.requestclientcert)
696 x509cred.SetDH(config.dh);
697 x509cred.SetCA(config.ca, config.crl);
699 /** Set up the given session with the settings in this profile
701 void SetupSession(gnutls_session_t sess)
703 priority.SetupSession(sess);
704 x509cred.SetupSession(sess);
705 gnutls_dh_set_prime_bits(sess, min_dh_bits);
707 // Request client certificate if enabled and we are a server, no-op if we're a client
708 if (requestclientcert)
709 gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
712 const std::string& GetName() const { return name; }
713 X509Credentials& GetX509Credentials() { return x509cred; }
714 gnutls_digest_algorithm_t GetHash() const { return hash.get(); }
715 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
719 class GnuTLSIOHook : public SSLIOHook
722 gnutls_session_t sess;
724 #ifdef INSPIRCD_GNUTLS_HAS_CORK
732 gnutls_bye(this->sess, GNUTLS_SHUT_WR);
733 gnutls_deinit(this->sess);
740 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
741 int Handshake(StreamSocket* user)
743 int ret = gnutls_handshake(this->sess);
747 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
749 // Handshake needs resuming later, read() or write() would have blocked.
750 this->status = ISSL_HANDSHAKING;
752 if (gnutls_record_get_direction(this->sess) == 0)
754 // gnutls_handshake() wants to read() again.
755 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
759 // gnutls_handshake() wants to write() again.
760 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
767 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
774 // Change the seesion state
775 this->status = ISSL_HANDSHAKEN;
779 // Finish writing, if any left
780 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
786 void VerifyCertificate()
788 unsigned int certstatus;
789 const gnutls_datum_t* cert_list;
791 unsigned int cert_list_size;
792 gnutls_x509_crt_t cert;
794 unsigned char digest[512];
795 size_t digest_size = sizeof(digest);
796 size_t name_size = sizeof(str);
797 ssl_cert* certinfo = new ssl_cert;
798 this->certificate = certinfo;
800 /* This verification function uses the trusted CAs in the credentials
801 * structure. So you must have installed one or more CA certificates.
803 ret = gnutls_certificate_verify_peers2(this->sess, &certstatus);
807 certinfo->error = std::string(gnutls_strerror(ret));
811 certinfo->invalid = (certstatus & GNUTLS_CERT_INVALID);
812 certinfo->unknownsigner = (certstatus & GNUTLS_CERT_SIGNER_NOT_FOUND);
813 certinfo->revoked = (certstatus & GNUTLS_CERT_REVOKED);
814 certinfo->trusted = !(certstatus & GNUTLS_CERT_SIGNER_NOT_CA);
816 /* Up to here the process is the same for X.509 certificates and
817 * OpenPGP keys. From now on X.509 certificates are assumed. This can
818 * be easily extended to work with openpgp keys as well.
820 if (gnutls_certificate_type_get(this->sess) != GNUTLS_CRT_X509)
822 certinfo->error = "No X509 keys sent";
826 ret = gnutls_x509_crt_init(&cert);
829 certinfo->error = gnutls_strerror(ret);
834 cert_list = gnutls_certificate_get_peers(this->sess, &cert_list_size);
835 if (cert_list == NULL)
837 certinfo->error = "No certificate was found";
838 goto info_done_dealloc;
841 /* This is not a real world example, since we only check the first
842 * certificate in the given chain.
845 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
848 certinfo->error = gnutls_strerror(ret);
849 goto info_done_dealloc;
852 if (gnutls_x509_crt_get_dn(cert, str, &name_size) == 0)
854 std::string& dn = certinfo->dn;
856 // Make sure there are no chars in the string that we consider invalid
857 if (dn.find_first_of("\r\n") != std::string::npos)
861 name_size = sizeof(str);
862 if (gnutls_x509_crt_get_issuer_dn(cert, str, &name_size) == 0)
864 std::string& issuer = certinfo->issuer;
866 if (issuer.find_first_of("\r\n") != std::string::npos)
870 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GetProfile().GetHash(), digest, &digest_size)) < 0)
872 certinfo->error = gnutls_strerror(ret);
876 certinfo->fingerprint = BinToHex(digest, digest_size);
879 /* Beware here we do not check for errors.
881 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
883 certinfo->error = "Not activated, or expired certificate";
887 gnutls_x509_crt_deinit(cert);
890 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
891 int PrepareIO(StreamSocket* sock)
893 if (status == ISSL_HANDSHAKEN)
895 else if (status == ISSL_HANDSHAKING)
897 // The handshake isn't finished, try to finish it
898 return Handshake(sock);
902 sock->SetError("No SSL session");
906 #ifdef INSPIRCD_GNUTLS_HAS_CORK
907 int FlushBuffer(StreamSocket* sock)
909 // If GnuTLS has some data buffered, write it
911 return HandleWriteRet(sock, gnutls_record_uncork(this->sess, 0));
916 int HandleWriteRet(StreamSocket* sock, int ret)
920 #ifdef INSPIRCD_GNUTLS_HAS_CORK
924 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
930 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
932 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
937 sock->SetError(gnutls_strerror(ret));
943 static const char* UnknownIfNULL(const char* str)
945 return str ? str : "UNKNOWN";
948 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
950 StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap);
952 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetModHook(thismod));
955 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
958 gnutls_transport_set_errno(session->sess, EAGAIN);
965 int rv = SocketEngine::Recv(sock, reinterpret_cast<char *>(buffer), size, 0);
970 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
971 * and then set errno appropriately.
972 * The gnutls library may also have a different errno variable than us, see
973 * gnutls_transport_set_errno(3).
975 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
980 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
984 #ifdef INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
985 static ssize_t VectorPush(gnutls_transport_ptr_t transportptr, const giovec_t* iov, int iovcnt)
987 StreamSocket* sock = reinterpret_cast<StreamSocket*>(transportptr);
989 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetModHook(thismod));
992 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
995 gnutls_transport_set_errno(session->sess, EAGAIN);
1002 // Cast the giovec_t to iovec not to IOVector so the correct function is called on Windows
1003 int ret = SocketEngine::WriteV(sock, reinterpret_cast<const iovec*>(iov), iovcnt);
1005 // See the function above for more info about the usage of gnutls_transport_set_errno() on Windows
1007 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
1011 for (int i = 0; i < iovcnt; i++)
1012 size += iov[i].iov_len;
1015 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
1019 #else // INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
1020 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
1022 StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap);
1024 GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetModHook(thismod));
1027 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
1030 gnutls_transport_set_errno(session->sess, EAGAIN);
1037 int rv = SocketEngine::Send(sock, reinterpret_cast<const char *>(buffer), size, 0);
1042 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
1043 * and then set errno appropriately.
1044 * The gnutls library may also have a different errno variable than us, see
1045 * gnutls_transport_set_errno(3).
1047 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
1052 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
1055 #endif // INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
1058 GnuTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, inspircd_gnutls_session_init_flags_t flags)
1059 : SSLIOHook(hookprov)
1062 #ifdef INSPIRCD_GNUTLS_HAS_CORK
1066 gnutls_init(&sess, flags);
1067 gnutls_transport_set_ptr(sess, reinterpret_cast<gnutls_transport_ptr_t>(sock));
1068 #ifdef INSPIRCD_GNUTLS_HAS_VECTOR_PUSH
1069 gnutls_transport_set_vec_push_function(sess, VectorPush);
1071 gnutls_transport_set_push_function(sess, gnutls_push_wrapper);
1073 gnutls_transport_set_pull_function(sess, gnutls_pull_wrapper);
1074 GetProfile().SetupSession(sess);
1076 sock->AddIOHook(this);
1080 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
1085 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
1087 // Finish handshake if needed
1088 int prepret = PrepareIO(user);
1092 // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN.
1094 GnuTLS::DataReader reader(sess);
1095 int ret = reader.ret();
1098 reader.appendto(recvq);
1099 // Schedule a read if there is still data in the GnuTLS buffer
1100 if (gnutls_record_check_pending(sess) > 0)
1101 SocketEngine::ChangeEventMask(user, FD_ADD_TRIAL_READ);
1104 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
1110 user->SetError("Connection closed");
1116 user->SetError(gnutls_strerror(ret));
1123 int OnStreamSocketWrite(StreamSocket* user, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
1125 // Finish handshake if needed
1126 int prepret = PrepareIO(user);
1130 // Session is ready for transferring application data
1132 #ifdef INSPIRCD_GNUTLS_HAS_CORK
1135 // If there is something in the GnuTLS buffer try to send() it
1136 int ret = FlushBuffer(user);
1138 return ret; // Couldn't flush entire buffer, retry later (or close on error)
1140 // GnuTLS buffer is empty, if the sendq is empty as well then break to set FD_WANT_NO_WRITE
1144 // GnuTLS buffer is empty but sendq is not, begin sending data from the sendq
1145 gnutls_record_cork(this->sess);
1146 while ((!sendq.empty()) && (gbuffersize < GetProfile().GetOutgoingRecordSize()))
1148 const StreamSocket::SendQueue::Element& elem = sendq.front();
1149 gbuffersize += elem.length();
1150 ret = gnutls_record_send(this->sess, elem.data(), elem.length());
1162 while (!sendq.empty())
1164 FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
1165 const StreamSocket::SendQueue::Element& buffer = sendq.front();
1166 ret = HandleWriteRet(user, gnutls_record_send(this->sess, buffer.data(), buffer.length()));
1170 else if (ret < (int)buffer.length())
1172 sendq.erase_front(ret);
1173 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
1177 // Wrote entire record, continue sending
1182 SocketEngine::ChangeEventMask(user, FD_WANT_NO_WRITE);
1186 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
1188 if (!IsHandshakeDone())
1190 out.append(UnknownIfNULL(gnutls_protocol_get_name(gnutls_protocol_get_version(sess)))).push_back('-');
1191 out.append(UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)))).push_back('-');
1192 out.append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).push_back('-');
1193 out.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
1196 bool GetServerName(std::string& out) const CXX11_OVERRIDE
1198 std::vector<char> nameBuffer;
1199 size_t nameLength = 0;
1200 unsigned int nameType = GNUTLS_NAME_DNS;
1202 // First, determine the size of the hostname.
1203 if (gnutls_server_name_get(sess, &nameBuffer[0], &nameLength, &nameType, 0) != GNUTLS_E_SHORT_MEMORY_BUFFER)
1206 // Then retrieve the hostname.
1207 nameBuffer.resize(nameLength);
1208 if (gnutls_server_name_get(sess, &nameBuffer[0], &nameLength, &nameType, 0) != GNUTLS_E_SUCCESS)
1211 out.append(&nameBuffer[0]);
1215 GnuTLS::Profile& GetProfile();
1216 bool IsHandshakeDone() const { return (status == ISSL_HANDSHAKEN); }
1219 int GnuTLS::X509Credentials::cert_callback(gnutls_session_t sess, const gnutls_datum_t* req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t* sign_algos, int sign_algos_length, cert_cb_last_param_type* st)
1221 #ifndef GNUTLS_NEW_CERT_CALLBACK_API
1222 st->type = GNUTLS_CRT_X509;
1224 st->cert_type = GNUTLS_CRT_X509;
1225 st->key_type = GNUTLS_PRIVKEY_X509;
1227 StreamSocket* sock = reinterpret_cast<StreamSocket*>(gnutls_transport_get_ptr(sess));
1228 GnuTLS::X509Credentials& cred = static_cast<GnuTLSIOHook*>(sock->GetModHook(thismod))->GetProfile().GetX509Credentials();
1230 st->ncerts = cred.certs.size();
1231 st->cert.x509 = cred.certs.raw();
1232 st->key.x509 = cred.key.get();
1238 class GnuTLSIOHookProvider : public IOHookProvider
1240 GnuTLS::Profile profile;
1243 GnuTLSIOHookProvider(Module* mod, GnuTLS::Profile::Config& config)
1244 : IOHookProvider(mod, "ssl/" + config.name, IOHookProvider::IOH_SSL)
1247 ServerInstance->Modules->AddService(*this);
1250 ~GnuTLSIOHookProvider()
1252 ServerInstance->Modules->DelService(*this);
1255 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
1257 new GnuTLSIOHook(this, sock, GNUTLS_SERVER);
1260 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
1262 new GnuTLSIOHook(this, sock, GNUTLS_CLIENT);
1265 GnuTLS::Profile& GetProfile() { return profile; }
1268 GnuTLS::Profile& GnuTLSIOHook::GetProfile()
1270 IOHookProvider* hookprov = prov;
1271 return static_cast<GnuTLSIOHookProvider*>(hookprov)->GetProfile();
1274 class ModuleSSLGnuTLS : public Module
1276 typedef std::vector<reference<GnuTLSIOHookProvider> > ProfileList;
1278 // First member of the class, gets constructed first and destructed last
1279 GnuTLS::Init libinit;
1280 ProfileList profiles;
1284 // First, store all profiles in a new, temporary container. If no problems occur, swap the two
1285 // containers; this way if something goes wrong we can go back and continue using the current profiles,
1286 // avoiding unpleasant situations where no new SSL connections are possible.
1287 ProfileList newprofiles;
1289 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
1290 if (tags.first == tags.second)
1292 // No <sslprofile> tags found, create a profile named "gnutls" from settings in the <gnutls> block
1293 const std::string defname = "gnutls";
1294 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
1295 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <gnutls> tag");
1299 GnuTLS::Profile::Config profileconfig(defname, tag);
1300 newprofiles.push_back(new GnuTLSIOHookProvider(this, profileconfig));
1302 catch (CoreException& ex)
1304 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
1308 for (ConfigIter i = tags.first; i != tags.second; ++i)
1310 ConfigTag* tag = i->second;
1311 if (!stdalgo::string::equalsci(tag->getString("provider"), "gnutls"))
1314 std::string name = tag->getString("name");
1317 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
1321 reference<GnuTLSIOHookProvider> prov;
1324 GnuTLS::Profile::Config profileconfig(name, tag);
1325 prov = new GnuTLSIOHookProvider(this, profileconfig);
1327 catch (CoreException& ex)
1329 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
1332 newprofiles.push_back(prov);
1335 // New profiles are ok, begin using them
1336 // Old profiles are deleted when their refcount drops to zero
1337 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
1339 GnuTLSIOHookProvider& prov = **i;
1340 ServerInstance->Modules.DelService(prov);
1343 profiles.swap(newprofiles);
1349 #ifndef GNUTLS_HAS_RND
1350 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
1355 void init() CXX11_OVERRIDE
1357 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "GnuTLS lib version %s module was compiled for " GNUTLS_VERSION, gnutls_check_version(NULL));
1359 ServerInstance->GenRandom = RandGen::Call;
1362 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
1371 catch (ModuleException& ex)
1373 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
1379 ServerInstance->GenRandom = &InspIRCd::DefaultGenRandom;
1382 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
1384 if (type == ExtensionItem::EXT_USER)
1386 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
1388 if ((user) && (user->eh.GetModHook(this)))
1390 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
1391 // Potentially there could be multiple SSL modules loaded at once on different ports.
1392 ServerInstance->Users->QuitUser(user, "SSL module unloading");
1397 Version GetVersion() CXX11_OVERRIDE
1399 return Version("Provides SSL support via GnuTLS", VF_VENDOR);
1402 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
1404 const GnuTLSIOHook* const iohook = static_cast<GnuTLSIOHook*>(user->eh.GetModHook(this));
1405 if ((iohook) && (!iohook->IsHandshakeDone()))
1406 return MOD_RES_DENY;
1407 return MOD_RES_PASSTHRU;
1411 MODULE_INIT(ModuleSSLGnuTLS)