1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include <openssl/ssl.h>
16 #include <openssl/err.h>
17 #include "transport.h"
20 #pragma comment(lib, "libeay32MTd")
21 #pragma comment(lib, "ssleay32MTd")
22 #undef MAX_DESCRIPTORS
23 #define MAX_DESCRIPTORS 10000
26 /* $ModDesc: Provides SSL support for clients */
28 /* $LinkerFlags: if("USE_FREEBSD_BASE_SSL") -lssl -lcrypto */
29 /* $CompileFlags: if(!"USE_FREEBSD_BASE_SSL") pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
30 /* $LinkerFlags: if(!"USE_FREEBSD_BASE_SSL") rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
32 /* $ModDep: transport.h */
34 /* $CopyInstall: conf/key.pem $(CONPATH) */
35 /* $CopyInstall: conf/cert.pem $(CONPATH) */
38 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
40 static bool SelfSigned = false;
44 return ERR_error_string(ERR_get_error(), NULL);
47 static int error_callback(const char *str, size_t len, void *u);
49 /** Represents an SSL user's extra data
51 class issl_session : public classbase
64 data_to_write = false;
68 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
70 /* XXX: This will allow self signed certificates.
71 * In the future if we want an option to not allow this,
72 * we can just return preverify_ok here, and openssl
73 * will boot off self-signed and invalid peer certs.
75 int ve = X509_STORE_CTX_get_error(ctx);
77 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
82 class ModuleSSLOpenSSL : public Module
84 std::set<ListenSocketBase*> listenports;
87 issl_session* sessions;
97 // std::string crlfile;
105 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
107 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
109 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
110 inbufsize = ServerInstance->Config->NetBufferSize;
112 /* Global SSL library initialization*/
114 SSL_load_error_strings();
116 /* Build our SSL contexts:
117 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
119 ctx = SSL_CTX_new( SSLv23_server_method() );
120 clictx = SSL_CTX_new( SSLv23_client_method() );
122 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
123 SSL_CTX_set_mode(clictx, 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_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
128 // Needs the flag as it ignores a plain /rehash
129 OnModuleRehash(NULL,"ssl");
130 Implementation eventlist[] = {
131 I_On005Numeric, I_OnRequest, I_OnRehash, I_OnModuleRehash, I_OnPostConnect,
133 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
136 void OnHookIO(StreamSocket* user, ListenSocketBase* lsb)
138 if (!user->GetIOHook() && listenports.find(lsb) != listenports.end())
140 /* Hook the user with our module */
141 user->AddIOHook(this);
145 void OnRehash(User* user)
152 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
154 ListenSocketBase* port = ServerInstance->ports[i];
155 std::string desc = port->GetDescription();
156 if (desc != "openssl")
159 listenports.insert(port);
160 std::string portid = port->GetBindDesc();
162 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
163 if (port->GetIP() != "127.0.0.1")
164 sslports.append(portid).append(";");
167 if (!sslports.empty())
168 sslports.erase(sslports.end() - 1);
171 void OnModuleRehash(User* user, const std::string ¶m)
180 std::string confdir(ServerInstance->ConfigFileName);
181 // +1 so we the path ends with a /
182 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
184 cafile = Conf.ReadValue("openssl", "cafile", 0);
185 certfile = Conf.ReadValue("openssl", "certfile", 0);
186 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
187 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
189 // Set all the default values needed.
193 if (certfile.empty())
194 certfile = "cert.pem";
200 dhfile = "dhparams.pem";
202 // Prepend relative paths with the path to the config directory.
203 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
204 cafile = confdir + cafile;
206 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
207 certfile = confdir + certfile;
209 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
210 keyfile = confdir + keyfile;
212 if ((dhfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(dhfile)))
213 dhfile = confdir + dhfile;
215 /* Load our keys and certificates
216 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
218 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
220 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
221 ERR_print_errors_cb(error_callback, this);
224 if (((!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) || (!SSL_CTX_use_PrivateKey_file(clictx, keyfile.c_str(), SSL_FILETYPE_PEM)))
226 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
227 ERR_print_errors_cb(error_callback, this);
230 /* Load the CAs we trust*/
231 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
233 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
234 ERR_print_errors_cb(error_callback, this);
237 FILE* dhpfile = fopen(dhfile.c_str(), "r");
242 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
243 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
247 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
248 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
250 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
251 ERR_print_errors_cb(error_callback, this);
258 void On005Numeric(std::string &output)
260 if (!sslports.empty())
261 output.append(" SSL=" + sslports);
267 SSL_CTX_free(clictx);
268 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
272 void OnCleanup(int target_type, void* item)
274 if (target_type == TYPE_USER)
276 User* user = (User*)item;
278 if (user->GetIOHook() == this)
280 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
281 // Potentially there could be multiple SSL modules loaded at once on different ports.
282 ServerInstance->Users->QuitUser(user, "SSL module unloading");
290 return Version("Provides SSL support for clients", VF_VENDOR, API_VERSION);
294 const char* OnRequest(Request* request)
296 ISHRequest* ISR = (ISHRequest*)request;
297 if (strcmp("IS_NAME", request->GetId()) == 0)
301 else if (strcmp("IS_HOOK", request->GetId()) == 0)
303 ISR->Sock->AddIOHook(this);
306 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
308 ISR->Sock->DelIOHook();
311 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
313 if (ISR->Sock->GetFd() < 0)
316 issl_session* session = &sessions[ISR->Sock->GetFd()];
317 return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
319 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
321 issl_session* session = &sessions[ISR->Sock->GetFd()];
327 else if (strcmp("GET_CERT", request->GetId()) == 0)
329 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
331 return sslinfo->OnRequest(request);
337 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
339 int fd = user->GetFd();
341 issl_session* session = &sessions[fd];
344 session->sess = SSL_new(ctx);
345 session->status = ISSL_NONE;
346 session->outbound = false;
348 if (session->sess == NULL)
351 if (SSL_set_fd(session->sess, fd) == 0)
353 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
357 Handshake(user, session);
360 void OnStreamSocketConnect(StreamSocket* user)
362 int fd = user->GetFd();
363 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
364 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
367 issl_session* session = &sessions[fd];
370 session->sess = SSL_new(clictx);
371 session->status = ISSL_NONE;
372 session->outbound = true;
374 if (session->sess == NULL)
377 if (SSL_set_fd(session->sess, fd) == 0)
379 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
383 Handshake(user, session);
386 void OnStreamSocketClose(StreamSocket* user)
388 int fd = user->GetFd();
389 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
390 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
393 CloseSession(&sessions[fd]);
396 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
398 int fd = user->GetFd();
399 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
400 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
403 issl_session* session = &sessions[fd];
407 CloseSession(session);
411 if (session->status == ISSL_HANDSHAKING)
413 // The handshake isn't finished and it wants to read, try to finish it.
414 if (!Handshake(user, session))
416 // Couldn't resume handshake.
417 if (session->status == ISSL_NONE)
423 // If we resumed the handshake then session->status will be ISSL_OPEN
425 if (session->status == ISSL_OPEN)
427 char* buffer = ServerInstance->GetReadBuffer();
428 size_t bufsiz = ServerInstance->Config->NetBufferSize;
429 int ret = SSL_read(session->sess, buffer, bufsiz);
433 recvq.append(buffer, ret);
438 // Client closed connection.
439 CloseSession(session);
444 int err = SSL_get_error(session->sess, ret);
446 if (err == SSL_ERROR_WANT_READ)
448 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
451 else if (err == SSL_ERROR_WANT_WRITE)
453 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
458 CloseSession(session);
467 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
469 int fd = user->GetFd();
471 issl_session* session = &sessions[fd];
475 CloseSession(session);
479 session->data_to_write = true;
481 if (session->status == ISSL_HANDSHAKING)
483 if (!Handshake(user, session))
485 // Couldn't resume handshake.
486 if (session->status == ISSL_NONE)
492 if (session->status == ISSL_OPEN)
494 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
495 if (ret == (int)buffer.length())
497 session->data_to_write = false;
498 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
503 buffer = buffer.substr(ret);
504 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
509 CloseSession(session);
514 int err = SSL_get_error(session->sess, ret);
516 if (err == SSL_ERROR_WANT_WRITE)
518 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
521 else if (err == SSL_ERROR_WANT_READ)
523 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
528 CloseSession(session);
536 bool Handshake(EventHandler* user, issl_session* session)
540 if (session->outbound)
541 ret = SSL_connect(session->sess);
543 ret = SSL_accept(session->sess);
547 int err = SSL_get_error(session->sess, ret);
549 if (err == SSL_ERROR_WANT_READ)
551 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
552 session->status = ISSL_HANDSHAKING;
555 else if (err == SSL_ERROR_WANT_WRITE)
557 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
558 session->status = ISSL_HANDSHAKING;
563 CloseSession(session);
570 // Handshake complete.
571 VerifyCertificate(session, user);
573 session->status = ISSL_OPEN;
575 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
581 CloseSession(session);
588 void CloseSession(issl_session* session)
592 SSL_shutdown(session->sess);
593 SSL_free(session->sess);
596 session->sess = NULL;
597 session->status = ISSL_NONE;
601 void VerifyCertificate(issl_session* session, Extensible* user)
603 if (!session->sess || !user)
606 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
611 ssl_cert* certinfo = new ssl_cert;
613 unsigned char md[EVP_MAX_MD_SIZE];
614 const EVP_MD *digest = EVP_md5();
616 cert = SSL_get_peer_certificate((SSL*)session->sess);
620 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
621 BufferedSocketFingerprintSubmission(user, this, sslinfo, certinfo).Send();
625 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
629 certinfo->unknownsigner = false;
630 certinfo->trusted = true;
634 certinfo->unknownsigner = true;
635 certinfo->trusted = false;
638 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
639 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
641 if (!X509_digest(cert, digest, md, &n))
643 certinfo->error = "Out of memory generating fingerprint";
647 certinfo->fingerprint = irc::hex(md, n);
650 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))
652 certinfo->error = "Not activated, or expired certificate";
656 BufferedSocketFingerprintSubmission(user, this, sslinfo, certinfo).Send();
661 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
662 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
667 static int error_callback(const char *str, size_t len, void *u)
669 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
672 // XXX: Remove this line, it causes valgrind warnings...
674 // MD_update(&m, buf, j);
677 // ... ONLY JOKING! :-)
683 MODULE_INIT(ModuleSSLOpenSSL)