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/>.
26 #include <gnutls/gnutls.h>
27 #include <gnutls/x509.h>
28 #include "modules/ssl.h"
29 #include "modules/cap.h"
31 #if ((GNUTLS_VERSION_MAJOR > 2) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR > 9) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR == 9 && GNUTLS_VERSION_PATCH >= 8))
32 #define GNUTLS_HAS_MAC_GET_ID
33 #include <gnutls/crypto.h>
37 # pragma comment(lib, "libgnutls.lib")
38 # pragma comment(lib, "libgcrypt.lib")
39 # pragma comment(lib, "libgpg-error.lib")
40 # pragma comment(lib, "user32.lib")
41 # pragma comment(lib, "advapi32.lib")
42 # pragma comment(lib, "libgcc.lib")
43 # pragma comment(lib, "libmingwex.lib")
44 # pragma comment(lib, "gdi32.lib")
47 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") exec("libgcrypt-config --cflags") */
48 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") exec("libgcrypt-config --libs") */
51 // These don't exist in older GnuTLS versions
52 #if ((GNUTLS_VERSION_MAJOR > 2) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR > 1) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR == 1 && GNUTLS_VERSION_MICRO >= 7))
53 #define GNUTLS_NEW_PRIO_API
56 #if(GNUTLS_VERSION_MAJOR < 2)
57 typedef gnutls_certificate_credentials_t gnutls_certificate_credentials;
58 typedef gnutls_dh_params_t gnutls_dh_params;
61 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
63 static std::vector<gnutls_x509_crt_t> x509_certs;
64 static gnutls_x509_privkey_t x509_key;
65 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
66 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
67 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
69 st->type = GNUTLS_CRT_X509;
71 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
72 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr2_st * st) {
73 st->cert_type = GNUTLS_CRT_X509;
74 st->key_type = GNUTLS_PRIVKEY_X509;
76 st->ncerts = x509_certs.size();
77 st->cert.x509 = &x509_certs[0];
78 st->key.x509 = x509_key;
84 class RandGen : public HandlerBase2<void, char*, size_t>
88 void Call(char* buffer, size_t len)
90 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
94 /** Represents an SSL user's extra data
100 gnutls_session_t sess;
102 reference<ssl_cert> cert;
104 issl_session() : socket(NULL), sess(NULL) {}
107 class GnuTLSIOHook : public SSLIOHook
110 void InitSession(StreamSocket* user, bool me_server)
112 issl_session* session = &sessions[user->GetFd()];
114 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
115 session->socket = user;
117 #ifdef GNUTLS_NEW_PRIO_API
118 gnutls_priority_set(session->sess, priority);
120 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
121 gnutls_dh_set_prime_bits(session->sess, dh_bits);
122 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(session));
123 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
124 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
127 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
129 Handshake(session, user);
132 void CloseSession(issl_session* session)
136 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
137 gnutls_deinit(session->sess);
139 session->socket = NULL;
140 session->sess = NULL;
141 session->cert = NULL;
142 session->status = ISSL_NONE;
145 bool Handshake(issl_session* session, StreamSocket* user)
147 int ret = gnutls_handshake(session->sess);
151 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
153 // Handshake needs resuming later, read() or write() would have blocked.
155 if(gnutls_record_get_direction(session->sess) == 0)
157 // gnutls_handshake() wants to read() again.
158 session->status = ISSL_HANDSHAKING_READ;
159 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
163 // gnutls_handshake() wants to write() again.
164 session->status = ISSL_HANDSHAKING_WRITE;
165 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
170 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
171 CloseSession(session);
172 session->status = ISSL_CLOSING;
179 // Change the seesion state
180 session->status = ISSL_HANDSHAKEN;
182 VerifyCertificate(session,user);
184 // Finish writing, if any left
185 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
191 void VerifyCertificate(issl_session* session, StreamSocket* user)
193 if (!session->sess || !user)
197 const gnutls_datum_t* cert_list;
199 unsigned int cert_list_size;
200 gnutls_x509_crt_t cert;
202 unsigned char digest[512];
203 size_t digest_size = sizeof(digest);
204 size_t name_size = sizeof(str);
205 ssl_cert* certinfo = new ssl_cert;
206 session->cert = certinfo;
208 /* This verification function uses the trusted CAs in the credentials
209 * structure. So you must have installed one or more CA certificates.
211 ret = gnutls_certificate_verify_peers2(session->sess, &status);
215 certinfo->error = std::string(gnutls_strerror(ret));
219 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
220 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
221 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
222 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
224 /* Up to here the process is the same for X.509 certificates and
225 * OpenPGP keys. From now on X.509 certificates are assumed. This can
226 * be easily extended to work with openpgp keys as well.
228 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
230 certinfo->error = "No X509 keys sent";
234 ret = gnutls_x509_crt_init(&cert);
237 certinfo->error = gnutls_strerror(ret);
242 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
243 if (cert_list == NULL)
245 certinfo->error = "No certificate was found";
246 goto info_done_dealloc;
249 /* This is not a real world example, since we only check the first
250 * certificate in the given chain.
253 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
256 certinfo->error = gnutls_strerror(ret);
257 goto info_done_dealloc;
260 gnutls_x509_crt_get_dn(cert, str, &name_size);
263 gnutls_x509_crt_get_issuer_dn(cert, str, &name_size);
264 certinfo->issuer = str;
266 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
268 certinfo->error = gnutls_strerror(ret);
272 certinfo->fingerprint = BinToHex(digest, digest_size);
275 /* Beware here we do not check for errors.
277 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
279 certinfo->error = "Not activated, or expired certificate";
283 gnutls_x509_crt_deinit(cert);
286 static const char* UnknownIfNULL(const char* str)
288 return str ? str : "UNKNOWN";
291 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
293 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
294 if (session->socket->GetEventMask() & FD_READ_WILL_BLOCK)
297 gnutls_transport_set_errno(session->sess, EAGAIN);
304 int rv = ServerInstance->SE->Recv(session->socket, reinterpret_cast<char *>(buffer), size, 0);
309 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
310 * and then set errno appropriately.
311 * The gnutls library may also have a different errno variable than us, see
312 * gnutls_transport_set_errno(3).
314 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
319 ServerInstance->SE->ChangeEventMask(session->socket, FD_READ_WILL_BLOCK);
323 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
325 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
326 if (session->socket->GetEventMask() & FD_WRITE_WILL_BLOCK)
329 gnutls_transport_set_errno(session->sess, EAGAIN);
336 int rv = ServerInstance->SE->Send(session->socket, reinterpret_cast<const char *>(buffer), size, 0);
341 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
342 * and then set errno appropriately.
343 * The gnutls library may also have a different errno variable than us, see
344 * gnutls_transport_set_errno(3).
346 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
351 ServerInstance->SE->ChangeEventMask(session->socket, FD_WRITE_WILL_BLOCK);
356 issl_session* sessions;
357 gnutls_certificate_credentials_t x509_cred;
359 gnutls_digest_algorithm_t hash;
360 #ifdef GNUTLS_NEW_PRIO_API
361 gnutls_priority_t priority;
365 GnuTLSIOHook(Module* parent)
366 : SSLIOHook(parent, "ssl/gnutls")
368 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
376 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
378 issl_session* session = &sessions[user->GetFd()];
380 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
384 InitSession(user, true);
387 void OnStreamSocketConnect(StreamSocket* user) CXX11_OVERRIDE
389 InitSession(user, false);
392 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
394 CloseSession(&sessions[user->GetFd()]);
397 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
399 issl_session* session = &sessions[user->GetFd()];
403 CloseSession(session);
404 user->SetError("No SSL session");
408 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
410 // The handshake isn't finished, try to finish it.
412 if(!Handshake(session, user))
414 if (session->status != ISSL_CLOSING)
420 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
422 if (session->status == ISSL_HANDSHAKEN)
424 char* buffer = ServerInstance->GetReadBuffer();
425 size_t bufsiz = ServerInstance->Config->NetBufferSize;
426 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
429 recvq.append(buffer, ret);
432 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
438 user->SetError("Connection closed");
439 CloseSession(session);
444 user->SetError(gnutls_strerror(ret));
445 CloseSession(session);
449 else if (session->status == ISSL_CLOSING)
455 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq) CXX11_OVERRIDE
457 issl_session* session = &sessions[user->GetFd()];
461 CloseSession(session);
462 user->SetError("No SSL session");
466 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
468 // The handshake isn't finished, try to finish it.
469 Handshake(session, user);
470 if (session->status != ISSL_CLOSING)
477 if (session->status == ISSL_HANDSHAKEN)
479 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
481 if (ret == (int)sendq.length())
483 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
488 sendq = sendq.substr(ret);
489 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
492 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
494 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
499 user->SetError(gnutls_strerror(ret));
500 CloseSession(session);
508 ssl_cert* GetCertificate(StreamSocket* sock) CXX11_OVERRIDE
510 int fd = sock->GetFd();
511 issl_session* session = &sessions[fd];
512 return session->cert;
515 void TellCiphersAndFingerprint(LocalUser* user)
517 const gnutls_session_t& sess = sessions[user->eh.GetFd()].sess;
520 std::string text = "*** You are connected using SSL cipher '";
522 text += UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)));
523 text.append("-").append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).append("-");
524 text.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess)))).append("'");
526 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
527 if (!cert->fingerprint.empty())
528 text += " and your SSL fingerprint is " + cert->fingerprint;
530 user->WriteNotice(text);
535 class CommandStartTLS : public SplitCommand
541 CommandStartTLS(Module* mod, IOHook& Hook)
542 : SplitCommand(mod, "STARTTLS")
546 works_before_reg = true;
549 CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user)
553 user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
557 if (user->registered == REG_ALL)
559 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
563 if (!user->eh.GetIOHook())
565 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
566 /* We need to flush the write buffer prior to adding the IOHook,
567 * otherwise we'll be sending this line inside the SSL session - which
568 * won't start its handshake until the client gets this line. Currently,
569 * we assume the write will not block here; this is usually safe, as
570 * STARTTLS is sent very early on in the registration phase, where the
571 * user hasn't built up much sendq. Handling a blocked write here would
575 user->eh.AddIOHook(&hook);
576 hook.OnStreamSocketAccept(&user->eh, NULL, NULL);
579 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
586 class ModuleSSLGnuTLS : public Module
590 gnutls_dh_params_t dh_params;
592 std::string sslports;
598 CommandStartTLS starttls;
600 GenericCap capHandler;
604 : iohook(this), starttls(this, iohook), capHandler(this, "tls")
606 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
608 gnutls_global_init(); // This must be called once in the program
609 gnutls_x509_privkey_init(&x509_key);
611 #ifdef GNUTLS_NEW_PRIO_API
612 // Init this here so it's always initialized, avoids an extra boolean
613 gnutls_priority_init(&iohook.priority, "NORMAL", NULL);
620 void init() CXX11_OVERRIDE
622 // Needs the flag as it ignores a plain /rehash
623 OnModuleRehash(NULL,"ssl");
625 ServerInstance->GenRandom = &randhandler;
627 // Void return, guess we assume success
628 gnutls_certificate_set_dh_params(iohook.x509_cred, dh_params);
629 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
630 I_OnEvent, I_OnHookIO };
631 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
633 ServerInstance->Modules->AddService(iohook);
634 ServerInstance->Modules->AddService(starttls);
637 void OnRehash(User* user) CXX11_OVERRIDE
641 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
642 starttls.enabled = Conf->getBool("starttls", true);
644 if (Conf->getBool("showports", true))
646 sslports = Conf->getString("advertisedports");
647 if (!sslports.empty())
650 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
652 ListenSocket* port = ServerInstance->ports[i];
653 if (port->bind_tag->getString("ssl") != "gnutls")
656 const std::string& portid = port->bind_desc;
657 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
659 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
662 * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
663 * the IP:port in ISUPPORT.
665 * We used to advertise all ports seperated by a ';' char that matched the above criteria,
666 * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
667 * To solve this by default we now only display the first IP:port found and let the user
668 * configure the exact value for the 005 token, if necessary.
677 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
683 std::string certfile;
688 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
690 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
691 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
692 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
693 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
694 int dh_bits = Conf->getInt("dhbits");
695 std::string hashname = Conf->getString("hash", "md5");
697 // The GnuTLS manual states that the gnutls_set_default_priority()
698 // call we used previously when initializing the session is the same
699 // as setting the "NORMAL" priority string.
700 // Thus if the setting below is not in the config we will behave exactly
701 // the same as before, when the priority setting wasn't available.
702 std::string priorities = Conf->getString("priority", "NORMAL");
704 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
707 iohook.dh_bits = dh_bits;
709 // As older versions of gnutls can't do this, let's disable it where needed.
710 #ifdef GNUTLS_HAS_MAC_GET_ID
711 // As gnutls_digest_algorithm_t and gnutls_mac_algorithm_t are mapped 1:1, we can do this
712 // There is no gnutls_dig_get_id() at the moment, but it may come later
713 iohook.hash = (gnutls_digest_algorithm_t)gnutls_mac_get_id(hashname.c_str());
714 if (iohook.hash == GNUTLS_DIG_UNKNOWN)
715 throw ModuleException("Unknown hash type " + hashname);
717 // Check if the user is walking around with their head in the ass,
718 // giving us something that is a valid MAC but not digest
719 gnutls_hash_hd_t is_digest;
720 if (gnutls_hash_init(&is_digest, iohook.hash) < 0)
721 throw ModuleException("Unknown hash type " + hashname);
722 gnutls_hash_deinit(is_digest, NULL);
724 if (hashname == "md5")
725 iohook.hash = GNUTLS_DIG_MD5;
726 else if (hashname == "sha1")
727 iohook.hash = GNUTLS_DIG_SHA1;
729 throw ModuleException("Unknown hash type " + hashname);
736 gnutls_dh_params_deinit(dh_params);
743 // Deallocate the old credentials
744 gnutls_certificate_free_credentials(iohook.x509_cred);
746 for(unsigned int i=0; i < x509_certs.size(); i++)
747 gnutls_x509_crt_deinit(x509_certs[i]);
751 ret = gnutls_certificate_allocate_credentials(&iohook.x509_cred);
752 cred_alloc = (ret >= 0);
754 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
756 if((ret =gnutls_certificate_set_x509_trust_file(iohook.x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
757 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_ssl_gnutls.so: Failed to set X.509 trust file '%s': %s", cafile.c_str(), gnutls_strerror(ret));
759 if((ret = gnutls_certificate_set_x509_crl_file (iohook.x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
760 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret));
764 reader.Load(certfile);
765 std::string cert_string = reader.GetString();
766 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
768 reader.Load(keyfile);
769 std::string key_string = reader.GetString();
770 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
772 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
773 unsigned int certcount = 3;
774 x509_certs.resize(certcount);
775 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
776 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
778 // the buffer wasn't big enough to hold all certs but gnutls updated certcount to the number of available certs, try again with a bigger buffer
779 x509_certs.resize(certcount);
780 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
785 // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later
787 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read"));
789 x509_certs.resize(ret);
791 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
792 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
794 if((ret = gnutls_certificate_set_x509_key(iohook.x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
795 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
797 #ifdef GNUTLS_NEW_PRIO_API
798 // It's safe to call this every time as we cannot have this uninitialized, see constructor and below.
799 gnutls_priority_deinit(iohook.priority);
801 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
802 // If the user did not supply anything then the string is already set to "NORMAL"
803 const char* priocstr = priorities.c_str();
804 const char* prioerror;
806 if ((ret = gnutls_priority_init(&iohook.priority, priocstr, &prioerror)) < 0)
808 // gnutls did not understand the user supplied string, log and fall back to the default priorities
809 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "m_ssl_gnutls.so: Failed to set priorities to \"%s\": %s Syntax error at position %u, falling back to default (NORMAL)", priorities.c_str(), gnutls_strerror(ret), (unsigned int) (prioerror - priocstr));
810 gnutls_priority_init(&iohook.priority, "NORMAL", NULL);
814 if (priorities != "NORMAL")
815 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "m_ssl_gnutls.so: You've set <gnutls:priority> to a value other than the default, but this is only supported with GnuTLS v2.1.7 or newer. Your GnuTLS version is older than that so the option will have no effect.");
818 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
819 gnutls_certificate_client_set_retrieve_function (iohook.x509_cred, cert_callback);
821 gnutls_certificate_set_retrieve_function (iohook.x509_cred, cert_callback);
823 ret = gnutls_dh_params_init(&dh_params);
824 dh_alloc = (ret >= 0);
827 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
831 std::string dhfile = Conf->getString("dhfile");
834 // Try to load DH params from file
836 std::string dhstring = reader.GetString();
837 gnutls_datum_t dh_datum = { (unsigned char*)dhstring.data(), static_cast<unsigned int>(dhstring.length()) };
839 if ((ret = gnutls_dh_params_import_pkcs3(dh_params, &dh_datum, GNUTLS_X509_FMT_PEM)) < 0)
841 // File unreadable or GnuTLS was unhappy with the contents, generate the DH primes now
842 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "m_ssl_gnutls.so: Generating DH parameters because I failed to load them from file '%s': %s", dhfile.c_str(), gnutls_strerror(ret));
852 void GenerateDHParams()
854 // Generate Diffie Hellman parameters - for use with DHE
855 // kx algorithms. These should be discarded and regenerated
856 // once a day, once a week or once a month. Depending on the
857 // security requirements.
864 if((ret = gnutls_dh_params_generate2(dh_params, iohook.dh_bits)) < 0)
865 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", iohook.dh_bits, gnutls_strerror(ret));
870 for(unsigned int i=0; i < x509_certs.size(); i++)
871 gnutls_x509_crt_deinit(x509_certs[i]);
873 gnutls_x509_privkey_deinit(x509_key);
874 #ifdef GNUTLS_NEW_PRIO_API
875 gnutls_priority_deinit(iohook.priority);
879 gnutls_dh_params_deinit(dh_params);
881 gnutls_certificate_free_credentials(iohook.x509_cred);
883 gnutls_global_deinit();
884 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
887 void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
889 if(target_type == TYPE_USER)
891 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
893 if (user && user->eh.GetIOHook() == &iohook)
895 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
896 // Potentially there could be multiple SSL modules loaded at once on different ports.
897 ServerInstance->Users->QuitUser(user, "SSL module unloading");
902 Version GetVersion() CXX11_OVERRIDE
904 return Version("Provides SSL support for clients", VF_VENDOR);
907 void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
909 if (!sslports.empty())
910 tokens["SSL"] = sslports;
911 if (starttls.enabled)
915 void OnHookIO(StreamSocket* user, ListenSocket* lsb) CXX11_OVERRIDE
917 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
919 /* Hook the user with our module */
920 user->AddIOHook(&iohook);
924 void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
926 if (user->eh.GetIOHook() == &iohook)
927 iohook.TellCiphersAndFingerprint(user);
930 void OnEvent(Event& ev) CXX11_OVERRIDE
932 if (starttls.enabled)
933 capHandler.HandleEvent(ev);
937 MODULE_INIT(ModuleSSLGnuTLS)