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 #include <openssl/ssl.h>
35 #include <openssl/err.h>
38 # pragma comment(lib, "libcrypto.lib")
39 # pragma comment(lib, "libssl.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: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
48 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */
50 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
52 static bool SelfSigned = false;
56 return ERR_error_string(ERR_get_error(), NULL);
59 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
63 class Exception : public ModuleException
66 Exception(const std::string& reason)
67 : ModuleException(reason) { }
75 DHParams(const std::string& filename)
77 FILE* dhpfile = fopen(filename.c_str(), "r");
79 throw Exception("Couldn't open DH file " + filename + ": " + strerror(errno));
81 dh = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
84 throw Exception("Couldn't read DH params from file " + filename);
103 Context(SSL_CTX* context)
106 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
107 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
109 const unsigned char session_id[] = "inspircd";
110 SSL_CTX_set_session_id_context(ctx, session_id, sizeof(session_id) - 1);
118 bool SetDH(DHParams& dh)
120 return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
123 bool SetCiphers(const std::string& ciphers)
125 return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
128 bool SetCerts(const std::string& filename)
130 return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
133 bool SetPrivateKey(const std::string& filename)
135 return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
138 bool SetCA(const std::string& filename)
140 return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
149 class Profile : public refcountbase
151 /** Name of this profile
153 const std::string name;
155 /** DH parameters in use
159 /** OpenSSL makes us have two contexts, one for servers and one for clients
164 /** Digest to use when generating fingerprints
166 const EVP_MD* digest;
168 /** Last error, set by error_callback()
172 static int error_callback(const char* str, size_t len, void* u)
174 Profile* profile = reinterpret_cast<Profile*>(u);
175 profile->lasterr = std::string(str, len - 1);
180 Profile(const std::string& profilename, ConfigTag* tag)
182 , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem")))
183 , ctx(SSL_CTX_new(SSLv23_server_method()))
184 , clictx(SSL_CTX_new(SSLv23_client_method()))
186 if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
187 throw Exception("Couldn't set DH parameters");
189 std::string hash = tag->getString("hash", "md5");
190 digest = EVP_get_digestbyname(hash.c_str());
192 throw Exception("Unknown hash type " + hash);
194 std::string ciphers = tag->getString("ciphers");
195 if (!ciphers.empty())
197 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
199 ERR_print_errors_cb(error_callback, this);
200 throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
204 /* Load our keys and certificates
205 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
207 std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
208 if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
210 ERR_print_errors_cb(error_callback, this);
211 throw Exception("Can't read certificate file: " + lasterr);
214 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
215 if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
217 ERR_print_errors_cb(error_callback, this);
218 throw Exception("Can't read key file: " + lasterr);
221 // Load the CAs we trust
222 filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
223 if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
225 ERR_print_errors_cb(error_callback, this);
226 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());
230 const std::string& GetName() const { return name; }
231 SSL* CreateServerSession() { return ctx.CreateSession(); }
232 SSL* CreateClientSession() { return clictx.CreateSession(); }
233 const EVP_MD* GetDigest() { return digest; }
237 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
239 /* XXX: This will allow self signed certificates.
240 * In the future if we want an option to not allow this,
241 * we can just return preverify_ok here, and openssl
242 * will boot off self-signed and invalid peer certs.
244 int ve = X509_STORE_CTX_get_error(ctx);
246 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
251 class OpenSSLIOHook : public SSLIOHook
258 reference<OpenSSL::Profile> profile;
260 bool Handshake(StreamSocket* user)
265 ret = SSL_connect(sess);
267 ret = SSL_accept(sess);
271 int err = SSL_get_error(sess, ret);
273 if (err == SSL_ERROR_WANT_READ)
275 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
276 this->status = ISSL_HANDSHAKING;
279 else if (err == SSL_ERROR_WANT_WRITE)
281 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
282 this->status = ISSL_HANDSHAKING;
294 // Handshake complete.
299 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
325 void VerifyCertificate()
328 ssl_cert* certinfo = new ssl_cert;
329 this->certificate = certinfo;
331 unsigned char md[EVP_MAX_MD_SIZE];
333 cert = SSL_get_peer_certificate(sess);
337 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
341 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
345 certinfo->unknownsigner = false;
346 certinfo->trusted = true;
350 certinfo->unknownsigner = true;
351 certinfo->trusted = false;
355 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
357 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
358 certinfo->issuer = buf;
360 if (!X509_digest(cert, profile->GetDigest(), md, &n))
362 certinfo->error = "Out of memory generating fingerprint";
366 certinfo->fingerprint = BinToHex(md, n);
369 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))
371 certinfo->error = "Not activated, or expired certificate";
378 OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool is_outbound, SSL* session, const reference<OpenSSL::Profile>& sslprofile)
379 : SSLIOHook(hookprov)
382 , outbound(is_outbound)
383 , data_to_write(false)
384 , profile(sslprofile)
388 if (SSL_set_fd(sess, sock->GetFd()) == 0)
389 throw ModuleException("Can't set fd with SSL_set_fd: " + ConvToStr(sock->GetFd()));
391 sock->AddIOHook(this);
395 void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
400 int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
408 if (status == ISSL_HANDSHAKING)
410 // The handshake isn't finished and it wants to read, try to finish it.
411 if (!Handshake(user))
413 // Couldn't resume handshake.
414 if (status == ISSL_NONE)
420 // If we resumed the handshake then this->status will be ISSL_OPEN
422 if (status == ISSL_OPEN)
424 char* buffer = ServerInstance->GetReadBuffer();
425 size_t bufsiz = ServerInstance->Config->NetBufferSize;
426 int ret = SSL_read(sess, buffer, bufsiz);
430 recvq.append(buffer, ret);
432 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
437 // Client closed connection.
439 user->SetError("Connection closed");
444 int err = SSL_get_error(sess, ret);
446 if (err == SSL_ERROR_WANT_READ)
448 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
451 else if (err == SSL_ERROR_WANT_WRITE)
453 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
467 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
475 data_to_write = true;
477 if (status == ISSL_HANDSHAKING)
479 if (!Handshake(user))
481 // Couldn't resume handshake.
482 if (status == ISSL_NONE)
488 if (status == ISSL_OPEN)
490 int ret = SSL_write(sess, buffer.data(), buffer.size());
491 if (ret == (int)buffer.length())
493 data_to_write = false;
494 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
499 buffer = buffer.substr(ret);
500 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
510 int err = SSL_get_error(sess, ret);
512 if (err == SSL_ERROR_WANT_WRITE)
514 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
517 else if (err == SSL_ERROR_WANT_READ)
519 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
532 void TellCiphersAndFingerprint(LocalUser* user)
536 std::string text = "*** You are connected using SSL cipher '" + std::string(SSL_get_cipher(sess)) + "'";
537 const std::string& fingerprint = certificate->fingerprint;
538 if (!fingerprint.empty())
539 text += " and your SSL fingerprint is " + fingerprint;
541 user->WriteNotice(text);
546 class OpenSSLIOHookProvider : public refcountbase, public IOHookProvider
548 reference<OpenSSL::Profile> profile;
551 OpenSSLIOHookProvider(Module* mod, reference<OpenSSL::Profile>& prof)
552 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
555 ServerInstance->Modules->AddService(*this);
558 ~OpenSSLIOHookProvider()
560 ServerInstance->Modules->DelService(*this);
563 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
565 new OpenSSLIOHook(this, sock, false, profile->CreateServerSession(), profile);
568 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
570 new OpenSSLIOHook(this, sock, true, profile->CreateClientSession(), profile);
574 class ModuleSSLOpenSSL : public Module
576 typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
578 ProfileList profiles;
582 ProfileList newprofiles;
583 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
584 if (tags.first == tags.second)
586 // Create a default profile named "openssl"
587 const std::string defname = "openssl";
588 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
589 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
593 reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag));
594 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
596 catch (OpenSSL::Exception& ex)
598 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
602 for (ConfigIter i = tags.first; i != tags.second; ++i)
604 ConfigTag* tag = i->second;
605 if (tag->getString("provider") != "openssl")
608 std::string name = tag->getString("name");
611 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
615 reference<OpenSSL::Profile> profile;
618 profile = new OpenSSL::Profile(name, tag);
620 catch (CoreException& ex)
622 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
625 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
628 profiles.swap(newprofiles);
634 // Initialize OpenSSL
636 SSL_load_error_strings();
639 void init() CXX11_OVERRIDE
644 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
653 catch (ModuleException& ex)
655 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
659 void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
661 IOHook* hook = user->eh.GetIOHook();
662 if (hook && hook->prov->creator == this)
663 static_cast<OpenSSLIOHook*>(hook)->TellCiphersAndFingerprint(user);
666 void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
668 if (target_type == TYPE_USER)
670 LocalUser* user = IS_LOCAL((User*)item);
672 if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this)
674 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
675 // Potentially there could be multiple SSL modules loaded at once on different ports.
676 ServerInstance->Users->QuitUser(user, "SSL module unloading");
681 Version GetVersion() CXX11_OVERRIDE
683 return Version("Provides SSL support for clients", VF_VENDOR);
687 MODULE_INIT(ModuleSSLOpenSSL)