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/>.
24 /* HACK: This prevents OpenSSL on OS X 10.7 and later from spewing deprecation
25 * warnings for every single function call. As far as I (SaberUK) know, Apple
26 * have no plans to remove OpenSSL so this warning just causes needless spam.
29 # define __AVAILABILITYMACROS__
30 # define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
35 #include <openssl/ssl.h>
36 #include <openssl/err.h>
37 #include "modules/ssl.h"
40 # pragma comment(lib, "libcrypto.lib")
41 # pragma comment(lib, "libssl.lib")
42 # pragma comment(lib, "user32.lib")
43 # pragma comment(lib, "advapi32.lib")
44 # pragma comment(lib, "libgcc.lib")
45 # pragma comment(lib, "libmingwex.lib")
46 # pragma comment(lib, "gdi32.lib")
49 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") -Wno-pedantic */
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;
58 return ERR_error_string(ERR_get_error(), NULL);
61 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
65 class Exception : public ModuleException
68 Exception(const std::string& reason)
69 : ModuleException(reason) { }
77 DHParams(const std::string& filename)
79 FILE* dhpfile = fopen(filename.c_str(), "r");
81 throw Exception("Couldn't open DH file " + filename + ": " + strerror(errno));
83 dh = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
86 throw Exception("Couldn't read DH params from file " + filename);
105 Context(SSL_CTX* context)
108 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
109 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
111 const unsigned char session_id[] = "inspircd";
112 SSL_CTX_set_session_id_context(ctx, session_id, sizeof(session_id) - 1);
120 bool SetDH(DHParams& dh)
122 return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
125 bool SetCiphers(const std::string& ciphers)
127 return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
130 bool SetCerts(const std::string& filename)
132 return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
135 bool SetPrivateKey(const std::string& filename)
137 return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
140 bool SetCA(const std::string& filename)
142 return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
151 class Profile : public refcountbase
153 /** Name of this profile
155 const std::string name;
157 /** DH parameters in use
161 /** OpenSSL makes us have two contexts, one for servers and one for clients
166 /** Digest to use when generating fingerprints
168 const EVP_MD* digest;
170 /** Last error, set by error_callback()
174 static int error_callback(const char* str, size_t len, void* u)
176 Profile* profile = reinterpret_cast<Profile*>(u);
177 profile->lasterr = std::string(str, len - 1);
182 Profile(const std::string& profilename, ConfigTag* tag)
184 , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem")))
185 , ctx(SSL_CTX_new(SSLv23_server_method()))
186 , clictx(SSL_CTX_new(SSLv23_client_method()))
188 if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
189 throw Exception("Couldn't set DH parameters");
191 std::string hash = tag->getString("hash", "md5");
192 digest = EVP_get_digestbyname(hash.c_str());
194 throw Exception("Unknown hash type " + hash);
196 std::string ciphers = tag->getString("ciphers");
197 if (!ciphers.empty())
199 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
201 ERR_print_errors_cb(error_callback, this);
202 throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
206 /* Load our keys and certificates
207 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
209 std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
210 if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
212 ERR_print_errors_cb(error_callback, this);
213 throw Exception("Can't read certificate file: " + lasterr);
216 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
217 if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
219 ERR_print_errors_cb(error_callback, this);
220 throw Exception("Can't read key file: " + lasterr);
223 // Load the CAs we trust
224 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
225 if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
227 ERR_print_errors_cb(error_callback, this);
228 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());
232 const std::string& GetName() const { return name; }
233 SSL* CreateServerSession() { return ctx.CreateSession(); }
234 SSL* CreateClientSession() { return clictx.CreateSession(); }
235 const EVP_MD* GetDigest() { return digest; }
239 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
241 /* XXX: This will allow self signed certificates.
242 * In the future if we want an option to not allow this,
243 * we can just return preverify_ok here, and openssl
244 * will boot off self-signed and invalid peer certs.
246 int ve = X509_STORE_CTX_get_error(ctx);
248 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
253 class OpenSSLIOHook : public SSLIOHook
260 reference<OpenSSL::Profile> profile;
262 bool Handshake(StreamSocket* user)
267 ret = SSL_connect(sess);
269 ret = SSL_accept(sess);
273 int err = SSL_get_error(sess, ret);
275 if (err == SSL_ERROR_WANT_READ)
277 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
278 this->status = ISSL_HANDSHAKING;
281 else if (err == SSL_ERROR_WANT_WRITE)
283 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
284 this->status = ISSL_HANDSHAKING;
296 // Handshake complete.
301 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
327 void VerifyCertificate()
330 ssl_cert* certinfo = new ssl_cert;
331 this->certificate = certinfo;
333 unsigned char md[EVP_MAX_MD_SIZE];
335 cert = SSL_get_peer_certificate(sess);
339 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
343 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
347 certinfo->unknownsigner = false;
348 certinfo->trusted = true;
352 certinfo->unknownsigner = true;
353 certinfo->trusted = false;
357 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
359 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
360 certinfo->issuer = buf;
362 if (!X509_digest(cert, profile->GetDigest(), md, &n))
364 certinfo->error = "Out of memory generating fingerprint";
368 certinfo->fingerprint = BinToHex(md, n);
371 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))
373 certinfo->error = "Not activated, or expired certificate";
380 OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool is_outbound, SSL* session, const reference<OpenSSL::Profile>& sslprofile)
381 : SSLIOHook(hookprov)
384 , outbound(is_outbound)
385 , data_to_write(false)
386 , profile(sslprofile)
390 if (SSL_set_fd(sess, sock->GetFd()) == 0)
391 throw ModuleException("Can't set fd with SSL_set_fd: " + ConvToStr(sock->GetFd()));
393 sock->AddIOHook(this);
397 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
402 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
410 if (status == ISSL_HANDSHAKING)
412 // The handshake isn't finished and it wants to read, try to finish it.
413 if (!Handshake(user))
415 // Couldn't resume handshake.
416 if (status == ISSL_NONE)
422 // If we resumed the handshake then this->status will be ISSL_OPEN
424 if (status == ISSL_OPEN)
426 char* buffer = ServerInstance->GetReadBuffer();
427 size_t bufsiz = ServerInstance->Config->NetBufferSize;
428 int ret = SSL_read(sess, buffer, bufsiz);
432 recvq.append(buffer, ret);
434 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
439 // Client closed connection.
441 user->SetError("Connection closed");
446 int err = SSL_get_error(sess, ret);
448 if (err == SSL_ERROR_WANT_READ)
450 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
453 else if (err == SSL_ERROR_WANT_WRITE)
455 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
469 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
477 data_to_write = true;
479 if (status == ISSL_HANDSHAKING)
481 if (!Handshake(user))
483 // Couldn't resume handshake.
484 if (status == ISSL_NONE)
490 if (status == ISSL_OPEN)
492 int ret = SSL_write(sess, buffer.data(), buffer.size());
493 if (ret == (int)buffer.length())
495 data_to_write = false;
496 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
501 buffer = buffer.substr(ret);
502 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
512 int err = SSL_get_error(sess, ret);
514 if (err == SSL_ERROR_WANT_WRITE)
516 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
519 else if (err == SSL_ERROR_WANT_READ)
521 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
534 void TellCiphersAndFingerprint(LocalUser* user)
538 std::string text = "*** You are connected using SSL cipher '" + std::string(SSL_get_cipher(sess)) + "'";
539 const std::string& fingerprint = certificate->fingerprint;
540 if (!fingerprint.empty())
541 text += " and your SSL fingerprint is " + fingerprint;
543 user->WriteNotice(text);
548 class OpenSSLIOHookProvider : public refcountbase, public IOHookProvider
550 reference<OpenSSL::Profile> profile;
553 OpenSSLIOHookProvider(Module* mod, reference<OpenSSL::Profile>& prof)
554 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
557 ServerInstance->Modules->AddService(*this);
560 ~OpenSSLIOHookProvider()
562 ServerInstance->Modules->DelService(*this);
565 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
567 new OpenSSLIOHook(this, sock, false, profile->CreateServerSession(), profile);
570 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
572 new OpenSSLIOHook(this, sock, true, profile->CreateClientSession(), profile);
576 class ModuleSSLOpenSSL : public Module
578 typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
580 ProfileList profiles;
584 ProfileList newprofiles;
585 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
586 if (tags.first == tags.second)
588 // Create a default profile named "openssl"
589 const std::string defname = "openssl";
590 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
591 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
595 reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag));
596 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
598 catch (OpenSSL::Exception& ex)
600 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
604 for (ConfigIter i = tags.first; i != tags.second; ++i)
606 ConfigTag* tag = i->second;
607 if (tag->getString("provider") != "openssl")
610 std::string name = tag->getString("name");
613 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
617 reference<OpenSSL::Profile> profile;
620 profile = new OpenSSL::Profile(name, tag);
622 catch (CoreException& ex)
624 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
627 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
630 profiles.swap(newprofiles);
636 // Initialize OpenSSL
638 SSL_load_error_strings();
641 void init() CXX11_OVERRIDE
646 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
655 catch (ModuleException& ex)
657 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
661 void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
663 IOHook* hook = user->eh.GetIOHook();
664 if (hook && hook->prov->creator == this)
665 static_cast<OpenSSLIOHook*>(hook)->TellCiphersAndFingerprint(user);
668 void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
670 if (target_type == TYPE_USER)
672 LocalUser* user = IS_LOCAL((User*)item);
674 if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this)
676 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
677 // Potentially there could be multiple SSL modules loaded at once on different ports.
678 ServerInstance->Users->QuitUser(user, "SSL module unloading");
683 Version GetVersion() CXX11_OVERRIDE
685 return Version("Provides SSL support for clients", VF_VENDOR);
689 MODULE_INIT(ModuleSSLOpenSSL)