2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
6 * Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "modules/ssl.h"
29 // Ignore OpenSSL deprecation warnings on OS X Lion and newer.
31 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
34 // Fix warnings about the use of `long long` on C++03.
36 # pragma clang diagnostic ignored "-Wc++11-long-long"
37 #elif defined __GNUC__
38 # pragma GCC diagnostic ignored "-Wlong-long"
41 #include <openssl/ssl.h>
42 #include <openssl/err.h>
45 # pragma comment(lib, "ssleay32.lib")
46 # pragma comment(lib, "libeay32.lib")
49 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
50 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */
52 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
54 static bool SelfSigned = false;
55 static int exdataindex;
59 return ERR_error_string(ERR_get_error(), NULL);
62 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
63 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
67 class Exception : public ModuleException
70 Exception(const std::string& reason)
71 : ModuleException(reason) { }
79 DHParams(const std::string& filename)
81 BIO* dhpfile = BIO_new_file(filename.c_str(), "r");
83 throw Exception("Couldn't open DH file " + filename);
85 dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
89 throw Exception("Couldn't read DH params from file " + filename);
109 Context(SSL_CTX* context)
112 // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
113 // and when choosing a cipher, use the server's preferences instead of the client preferences.
114 long opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE;
115 // Only turn options on if they exist
116 #ifdef SSL_OP_SINGLE_ECDH_USE
117 opts |= SSL_OP_SINGLE_ECDH_USE;
119 #ifdef SSL_OP_NO_TICKET
120 opts |= SSL_OP_NO_TICKET;
123 ctx_options = SSL_CTX_set_options(ctx, opts);
124 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
125 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
126 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
127 SSL_CTX_set_info_callback(ctx, StaticSSLInfoCallback);
135 bool SetDH(DHParams& dh)
138 return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
141 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
142 void SetECDH(const std::string& curvename)
144 int nid = OBJ_sn2nid(curvename.c_str());
146 throw Exception("Unknown curve: " + curvename);
148 EC_KEY* eckey = EC_KEY_new_by_curve_name(nid);
150 throw Exception("Unable to create EC key object");
153 bool ret = (SSL_CTX_set_tmp_ecdh(ctx, eckey) >= 0);
156 throw Exception("Couldn't set ECDH parameters");
160 bool SetCiphers(const std::string& ciphers)
163 return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
166 bool SetCerts(const std::string& filename)
169 return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
172 bool SetPrivateKey(const std::string& filename)
175 return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
178 bool SetCA(const std::string& filename)
181 return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
184 long GetDefaultContextOptions() const
189 long SetRawContextOptions(long setoptions, long clearoptions)
192 SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
194 // Set the default options and what is in the conf
195 SSL_CTX_set_options(ctx, ctx_options | setoptions);
196 return SSL_CTX_clear_options(ctx, clearoptions);
205 class Profile : public refcountbase
207 /** Name of this profile
209 const std::string name;
211 /** DH parameters in use
215 /** OpenSSL makes us have two contexts, one for servers and one for clients
220 /** Digest to use when generating fingerprints
222 const EVP_MD* digest;
224 /** Last error, set by error_callback()
228 /** True if renegotiations are allowed, false if not
230 const bool allowrenego;
232 static int error_callback(const char* str, size_t len, void* u)
234 Profile* profile = reinterpret_cast<Profile*>(u);
235 profile->lasterr = std::string(str, len - 1);
239 /** Set raw OpenSSL context (SSL_CTX) options from a config tag
240 * @param ctxname Name of the context, client or server
241 * @param tag Config tag defining this profile
242 * @param context Context object to manipulate
244 void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context)
246 long setoptions = tag->getInt(ctxname + "setoptions");
247 long clearoptions = tag->getInt(ctxname + "clearoptions");
248 #ifdef SSL_OP_NO_COMPRESSION
249 if (!tag->getBool("compression", true))
250 setoptions |= SSL_OP_NO_COMPRESSION;
252 if (!tag->getBool("sslv3", true))
253 setoptions |= SSL_OP_NO_SSLv3;
254 if (!tag->getBool("tlsv1", true))
255 setoptions |= SSL_OP_NO_TLSv1;
257 if (!setoptions && !clearoptions)
258 return; // Nothing to do
260 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Setting %s %s context options, default: %ld set: %ld clear: %ld", name.c_str(), ctxname.c_str(), ctx.GetDefaultContextOptions(), setoptions, clearoptions);
261 long final = context.SetRawContextOptions(setoptions, clearoptions);
262 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final);
266 Profile(const std::string& profilename, ConfigTag* tag)
268 , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem")))
269 , ctx(SSL_CTX_new(SSLv23_server_method()))
270 , clictx(SSL_CTX_new(SSLv23_client_method()))
271 , allowrenego(tag->getBool("renegotiation", true))
273 if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
274 throw Exception("Couldn't set DH parameters");
276 std::string hash = tag->getString("hash", "md5");
277 digest = EVP_get_digestbyname(hash.c_str());
279 throw Exception("Unknown hash type " + hash);
281 std::string ciphers = tag->getString("ciphers");
282 if (!ciphers.empty())
284 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
286 ERR_print_errors_cb(error_callback, this);
287 throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
291 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
292 std::string curvename = tag->getString("ecdhcurve", "prime256v1");
293 if (!curvename.empty())
294 ctx.SetECDH(curvename);
297 SetContextOptions("server", tag, ctx);
298 SetContextOptions("client", tag, clictx);
300 /* Load our keys and certificates
301 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
303 std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
304 if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
306 ERR_print_errors_cb(error_callback, this);
307 throw Exception("Can't read certificate file: " + lasterr);
310 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
311 if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
313 ERR_print_errors_cb(error_callback, this);
314 throw Exception("Can't read key file: " + lasterr);
317 // Load the CAs we trust
318 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
319 if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
321 ERR_print_errors_cb(error_callback, this);
322 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Can't read CA list from %s. This is only a problem if you want to verify client certificates, otherwise it's safe to ignore this message. Error: %s", filename.c_str(), lasterr.c_str());
326 const std::string& GetName() const { return name; }
327 SSL* CreateServerSession() { return ctx.CreateSession(); }
328 SSL* CreateClientSession() { return clictx.CreateSession(); }
329 const EVP_MD* GetDigest() { return digest; }
330 bool AllowRenegotiation() const { return allowrenego; }
334 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
336 /* XXX: This will allow self signed certificates.
337 * In the future if we want an option to not allow this,
338 * we can just return preverify_ok here, and openssl
339 * will boot off self-signed and invalid peer certs.
341 int ve = X509_STORE_CTX_get_error(ctx);
343 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
348 class OpenSSLIOHook : public SSLIOHook
355 reference<OpenSSL::Profile> profile;
357 bool Handshake(StreamSocket* user)
363 ret = SSL_connect(sess);
365 ret = SSL_accept(sess);
369 int err = SSL_get_error(sess, ret);
371 if (err == SSL_ERROR_WANT_READ)
373 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
374 this->status = ISSL_HANDSHAKING;
377 else if (err == SSL_ERROR_WANT_WRITE)
379 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
380 this->status = ISSL_HANDSHAKING;
392 // Handshake complete.
397 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
420 void VerifyCertificate()
423 ssl_cert* certinfo = new ssl_cert;
424 this->certificate = certinfo;
426 unsigned char md[EVP_MAX_MD_SIZE];
428 cert = SSL_get_peer_certificate(sess);
432 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
436 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
440 certinfo->unknownsigner = false;
441 certinfo->trusted = true;
445 certinfo->unknownsigner = true;
446 certinfo->trusted = false;
450 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
452 // Make sure there are no chars in the string that we consider invalid
453 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
454 certinfo->dn.clear();
456 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
457 certinfo->issuer = buf;
458 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
459 certinfo->issuer.clear();
461 if (!X509_digest(cert, profile->GetDigest(), md, &n))
463 certinfo->error = "Out of memory generating fingerprint";
467 certinfo->fingerprint = BinToHex(md, n);
470 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), ServerInstance->Time()) == 0))
472 certinfo->error = "Not activated, or expired certificate";
478 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
479 void SSLInfoCallback(int where, int rc)
481 if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN))
483 if (profile->AllowRenegotiation())
486 // The other side is trying to renegotiate, kill the connection and change status
487 // to ISSL_NONE so CheckRenego() closes the session
489 SocketEngine::Shutdown(SSL_get_fd(sess), 2);
493 bool CheckRenego(StreamSocket* sock)
495 if (status != ISSL_NONE)
498 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess);
500 sock->SetError("Renegotiation is not allowed");
505 // Calls our private SSLInfoCallback()
506 friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
509 OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool is_outbound, SSL* session, const reference<OpenSSL::Profile>& sslprofile)
510 : SSLIOHook(hookprov)
513 , outbound(is_outbound)
514 , data_to_write(false)
515 , profile(sslprofile)
519 if (SSL_set_fd(sess, sock->GetFd()) == 0)
520 throw ModuleException("Can't set fd with SSL_set_fd: " + ConvToStr(sock->GetFd()));
522 SSL_set_ex_data(sess, exdataindex, this);
523 sock->AddIOHook(this);
527 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
532 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
540 if (status == ISSL_HANDSHAKING)
542 // The handshake isn't finished and it wants to read, try to finish it.
543 if (!Handshake(user))
545 // Couldn't resume handshake.
546 if (status == ISSL_NONE)
552 // If we resumed the handshake then this->status will be ISSL_OPEN
554 if (status == ISSL_OPEN)
557 char* buffer = ServerInstance->GetReadBuffer();
558 size_t bufsiz = ServerInstance->Config->NetBufferSize;
559 int ret = SSL_read(sess, buffer, bufsiz);
561 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
562 if (!CheckRenego(user))
568 recvq.append(buffer, ret);
570 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
575 // Client closed connection.
577 user->SetError("Connection closed");
582 int err = SSL_get_error(sess, ret);
584 if (err == SSL_ERROR_WANT_READ)
586 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
589 else if (err == SSL_ERROR_WANT_WRITE)
591 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
605 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
613 data_to_write = true;
615 if (status == ISSL_HANDSHAKING)
617 if (!Handshake(user))
619 // Couldn't resume handshake.
620 if (status == ISSL_NONE)
626 if (status == ISSL_OPEN)
629 int ret = SSL_write(sess, buffer.data(), buffer.size());
631 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
632 if (!CheckRenego(user))
636 if (ret == (int)buffer.length())
638 data_to_write = false;
639 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
644 buffer = buffer.substr(ret);
645 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
655 int err = SSL_get_error(sess, ret);
657 if (err == SSL_ERROR_WANT_WRITE)
659 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
662 else if (err == SSL_ERROR_WANT_READ)
664 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
677 void TellCiphersAndFingerprint(LocalUser* user)
681 std::string text = "*** You are connected using SSL cipher '" + std::string(SSL_get_cipher(sess)) + "'";
682 const std::string& fingerprint = certificate->fingerprint;
683 if (!fingerprint.empty())
684 text += " and your SSL certificate fingerprint is " + fingerprint;
686 user->WriteNotice(text);
691 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc)
693 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
694 OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex));
695 hook->SSLInfoCallback(where, rc);
699 class OpenSSLIOHookProvider : public refcountbase, public IOHookProvider
701 reference<OpenSSL::Profile> profile;
704 OpenSSLIOHookProvider(Module* mod, reference<OpenSSL::Profile>& prof)
705 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
708 ServerInstance->Modules->AddService(*this);
711 ~OpenSSLIOHookProvider()
713 ServerInstance->Modules->DelService(*this);
716 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
718 new OpenSSLIOHook(this, sock, false, profile->CreateServerSession(), profile);
721 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
723 new OpenSSLIOHook(this, sock, true, profile->CreateClientSession(), profile);
727 class ModuleSSLOpenSSL : public Module
729 typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
731 ProfileList profiles;
735 ProfileList newprofiles;
736 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
737 if (tags.first == tags.second)
739 // Create a default profile named "openssl"
740 const std::string defname = "openssl";
741 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
742 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
746 reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag));
747 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
749 catch (OpenSSL::Exception& ex)
751 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
755 for (ConfigIter i = tags.first; i != tags.second; ++i)
757 ConfigTag* tag = i->second;
758 if (tag->getString("provider") != "openssl")
761 std::string name = tag->getString("name");
764 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
768 reference<OpenSSL::Profile> profile;
771 profile = new OpenSSL::Profile(name, tag);
773 catch (CoreException& ex)
775 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
778 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
781 profiles.swap(newprofiles);
787 // Initialize OpenSSL
789 SSL_load_error_strings();
792 void init() CXX11_OVERRIDE
794 // Register application specific data
795 char exdatastr[] = "inspircd";
796 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
798 throw ModuleException("Failed to register application specific data");
803 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
812 catch (ModuleException& ex)
814 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
818 void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
820 IOHook* hook = user->eh.GetIOHook();
821 if (hook && hook->prov->creator == this)
822 static_cast<OpenSSLIOHook*>(hook)->TellCiphersAndFingerprint(user);
825 void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
827 if (target_type == TYPE_USER)
829 LocalUser* user = IS_LOCAL((User*)item);
831 if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this)
833 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
834 // Potentially there could be multiple SSL modules loaded at once on different ports.
835 ServerInstance->Users->QuitUser(user, "SSL module unloading");
840 Version GetVersion() CXX11_OVERRIDE
842 return Version("Provides SSL support for clients", VF_VENDOR);
846 MODULE_INIT(ModuleSSLOpenSSL)