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 };
39 enum issl_io_status { ISSL_WRITE, ISSL_READ };
41 static bool SelfSigned = false;
45 return ERR_error_string(ERR_get_error(), NULL);
48 static int error_callback(const char *str, size_t len, void *u);
50 /** Represents an SSL user's extra data
52 class issl_session : public classbase
60 unsigned int inbufoffset;
61 char* inbuf; // Buffer OpenSSL reads into.
74 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
76 /* XXX: This will allow self signed certificates.
77 * In the future if we want an option to not allow this,
78 * we can just return preverify_ok here, and openssl
79 * will boot off self-signed and invalid peer certs.
81 int ve = X509_STORE_CTX_get_error(ctx);
83 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
88 class ModuleSSLOpenSSL : public Module
90 std::set<ListenSocketBase*> listenports;
93 issl_session* sessions;
101 std::string certfile;
103 // std::string crlfile;
105 std::string sslports;
109 InspIRCd* PublicInstance;
111 ModuleSSLOpenSSL(InspIRCd* Me)
112 : Module(Me), PublicInstance(Me)
114 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
116 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
118 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
119 inbufsize = ServerInstance->Config->NetBufferSize;
121 /* Global SSL library initialization*/
123 SSL_load_error_strings();
125 /* Build our SSL contexts:
126 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
128 ctx = SSL_CTX_new( SSLv23_server_method() );
129 clictx = SSL_CTX_new( SSLv23_client_method() );
131 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
132 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
134 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
135 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
137 // Needs the flag as it ignores a plain /rehash
138 OnModuleRehash(NULL,"ssl");
139 Implementation eventlist[] = {
140 I_On005Numeric, I_OnBufferFlushed, I_OnRequest, I_OnRehash, I_OnModuleRehash, I_OnPostConnect,
142 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
145 void OnHookIO(StreamSocket* user, ListenSocketBase* lsb)
147 if (!user->GetIOHook() && listenports.find(lsb) != listenports.end())
149 /* Hook the user with our module */
150 user->AddIOHook(this);
154 void OnRehash(User* user)
156 ConfigReader Conf(ServerInstance);
161 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
163 ListenSocketBase* port = ServerInstance->ports[i];
164 std::string desc = port->GetDescription();
165 if (desc != "openssl")
168 listenports.insert(port);
169 std::string portid = port->GetBindDesc();
171 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
172 if (port->GetIP() != "127.0.0.1")
173 sslports.append(portid).append(";");
176 if (!sslports.empty())
177 sslports.erase(sslports.end() - 1);
180 void OnModuleRehash(User* user, const std::string ¶m)
187 ConfigReader Conf(ServerInstance);
189 std::string confdir(ServerInstance->ConfigFileName);
190 // +1 so we the path ends with a /
191 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
193 cafile = Conf.ReadValue("openssl", "cafile", 0);
194 certfile = Conf.ReadValue("openssl", "certfile", 0);
195 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
196 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
198 // Set all the default values needed.
202 if (certfile.empty())
203 certfile = "cert.pem";
209 dhfile = "dhparams.pem";
211 // Prepend relative paths with the path to the config directory.
212 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
213 cafile = confdir + cafile;
215 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
216 certfile = confdir + certfile;
218 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
219 keyfile = confdir + keyfile;
221 if ((dhfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(dhfile)))
222 dhfile = confdir + dhfile;
224 /* Load our keys and certificates
225 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
227 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
229 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
230 ERR_print_errors_cb(error_callback, this);
233 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)))
235 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
236 ERR_print_errors_cb(error_callback, this);
239 /* Load the CAs we trust*/
240 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
242 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
243 ERR_print_errors_cb(error_callback, this);
246 FILE* dhpfile = fopen(dhfile.c_str(), "r");
251 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
252 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
256 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
257 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
259 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
260 ERR_print_errors_cb(error_callback, this);
267 void On005Numeric(std::string &output)
269 if (!sslports.empty())
270 output.append(" SSL=" + sslports);
276 SSL_CTX_free(clictx);
277 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
281 void OnCleanup(int target_type, void* item)
283 if (target_type == TYPE_USER)
285 User* user = (User*)item;
287 if (user->GetIOHook() == this)
289 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
290 // Potentially there could be multiple SSL modules loaded at once on different ports.
291 ServerInstance->Users->QuitUser(user, "SSL module unloading");
299 return Version("$Id$", VF_VENDOR, API_VERSION);
303 const char* OnRequest(Request* request)
305 ISHRequest* ISR = (ISHRequest*)request;
306 if (strcmp("IS_NAME", request->GetId()) == 0)
310 else if (strcmp("IS_HOOK", request->GetId()) == 0)
312 ISR->Sock->AddIOHook(this);
315 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
317 ISR->Sock->DelIOHook();
320 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
322 if (ISR->Sock->GetFd() < 0)
325 issl_session* session = &sessions[ISR->Sock->GetFd()];
326 return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
328 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
330 issl_session* session = &sessions[ISR->Sock->GetFd()];
336 else if (strcmp("GET_CERT", request->GetId()) == 0)
338 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
340 return sslinfo->OnRequest(request);
346 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
348 int fd = user->GetFd();
350 issl_session* session = &sessions[fd];
353 session->inbuf = new char[inbufsize];
354 session->inbufoffset = 0;
355 session->sess = SSL_new(ctx);
356 session->status = ISSL_NONE;
357 session->outbound = false;
359 if (session->sess == NULL)
362 if (SSL_set_fd(session->sess, fd) == 0)
364 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
368 Handshake(user, session);
371 void OnStreamSocketConnect(StreamSocket* user)
373 int fd = user->GetFd();
374 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
375 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
378 issl_session* session = &sessions[fd];
381 session->inbuf = new char[inbufsize];
382 session->inbufoffset = 0;
383 session->sess = SSL_new(clictx);
384 session->status = ISSL_NONE;
385 session->outbound = true;
387 if (session->sess == NULL)
390 if (SSL_set_fd(session->sess, fd) == 0)
392 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
396 Handshake(user, session);
399 void OnStreamSocketClose(StreamSocket* user)
401 int fd = user->GetFd();
402 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
403 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
406 CloseSession(&sessions[fd]);
409 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
411 int fd = user->GetFd();
412 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
413 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
416 issl_session* session = &sessions[fd];
420 CloseSession(session);
424 if (session->status == ISSL_HANDSHAKING)
426 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
428 // The handshake isn't finished and it wants to read, try to finish it.
429 if (!Handshake(user, session))
431 // Couldn't resume handshake.
432 if (session->status == ISSL_NONE)
443 // If we resumed the handshake then session->status will be ISSL_OPEN
445 if (session->status == ISSL_OPEN)
447 if (session->wstat == ISSL_READ)
449 if(DoWrite(user, session) == 0)
453 if (session->rstat == ISSL_READ)
455 int ret = DoRead(user, session);
459 recvq.append(session->inbuf, session->inbufoffset);
460 session->inbufoffset = 0;
463 else if (errno == EAGAIN || errno == EINTR)
473 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
475 int fd = user->GetFd();
476 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
477 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
480 issl_session* session = &sessions[fd];
484 CloseSession(session);
488 if (session->status == ISSL_HANDSHAKING)
490 // The handshake isn't finished, try to finish it.
491 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
493 if (!Handshake(user, session))
495 // Couldn't resume handshake.
496 if (session->status == ISSL_NONE)
505 // don't pull items into the output buffer until they are
506 // unlikely to block; this allows sendq exceeded to continue
507 // to work for SSL users.
508 // TODO better signaling for I/O requests so this isn't needed
509 if (session->outbuf.empty())
511 session->outbuf = buffer;
515 if (session->status == ISSL_OPEN)
517 if (session->rstat == ISSL_WRITE)
519 DoRead(user, session);
522 if (session->wstat == ISSL_WRITE)
524 DoWrite(user, session);
528 if (rv == 0 || !session->outbuf.empty())
529 ServerInstance->SE->WantWrite(user);
534 int DoWrite(StreamSocket* user, issl_session* session)
536 if (!session->outbuf.size())
539 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
543 CloseSession(session);
548 int err = SSL_get_error(session->sess, ret);
550 if (err == SSL_ERROR_WANT_WRITE)
552 session->wstat = ISSL_WRITE;
553 ServerInstance->SE->WantWrite(user);
556 else if (err == SSL_ERROR_WANT_READ)
558 session->wstat = ISSL_READ;
563 CloseSession(session);
569 session->outbuf = session->outbuf.substr(ret);
574 int DoRead(StreamSocket* user, issl_session* session)
576 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
577 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
579 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
583 // Client closed connection.
584 CloseSession(session);
589 int err = SSL_get_error(session->sess, ret);
591 if (err == SSL_ERROR_WANT_READ)
593 session->rstat = ISSL_READ;
596 else if (err == SSL_ERROR_WANT_WRITE)
598 session->rstat = ISSL_WRITE;
599 ServerInstance->SE->WantWrite(user);
604 CloseSession(session);
610 // Read successfully 'ret' bytes into inbuf + inbufoffset
611 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
612 // 'buffer' is 'count' long
614 session->inbufoffset += ret;
620 bool Handshake(EventHandler* user, issl_session* session)
624 if (session->outbound)
625 ret = SSL_connect(session->sess);
627 ret = SSL_accept(session->sess);
631 int err = SSL_get_error(session->sess, ret);
633 if (err == SSL_ERROR_WANT_READ)
635 session->rstat = ISSL_READ;
636 session->status = ISSL_HANDSHAKING;
639 else if (err == SSL_ERROR_WANT_WRITE)
641 session->wstat = ISSL_WRITE;
642 session->status = ISSL_HANDSHAKING;
643 ServerInstance->SE->WantWrite(user);
648 CloseSession(session);
655 // Handshake complete.
656 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
657 EventHandler *u = ServerInstance->SE->GetRef(session->fd);
658 VerifyCertificate(session, u);
660 session->status = ISSL_OPEN;
662 ServerInstance->SE->WantWrite(user);
668 CloseSession(session);
675 void OnBufferFlushed(User* user)
677 if (user->GetIOHook() == this)
680 issl_session* session = &sessions[user->GetFd()];
681 if (session && session->outbuf.size())
682 OnStreamSocketWrite(user, dummy);
686 void CloseSession(issl_session* session)
690 SSL_shutdown(session->sess);
691 SSL_free(session->sess);
696 delete[] session->inbuf;
699 session->outbuf.clear();
700 session->inbuf = NULL;
701 session->sess = NULL;
702 session->status = ISSL_NONE;
706 void VerifyCertificate(issl_session* session, Extensible* user)
708 if (!session->sess || !user)
711 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
716 ssl_cert* certinfo = new ssl_cert;
718 unsigned char md[EVP_MAX_MD_SIZE];
719 const EVP_MD *digest = EVP_md5();
721 cert = SSL_get_peer_certificate((SSL*)session->sess);
725 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
726 BufferedSocketFingerprintSubmission(user, this, sslinfo, certinfo).Send();
730 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
734 certinfo->unknownsigner = false;
735 certinfo->trusted = true;
739 certinfo->unknownsigner = true;
740 certinfo->trusted = false;
743 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
744 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
746 if (!X509_digest(cert, digest, md, &n))
748 certinfo->error = "Out of memory generating fingerprint";
752 certinfo->fingerprint = irc::hex(md, n);
755 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))
757 certinfo->error = "Not activated, or expired certificate";
761 BufferedSocketFingerprintSubmission(user, this, sslinfo, certinfo).Send();
766 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
767 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
772 static int error_callback(const char *str, size_t len, void *u)
774 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
775 mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
778 // XXX: Remove this line, it causes valgrind warnings...
780 // MD_update(&m, buf, j);
783 // ... ONLY JOKING! :-)
789 MODULE_INIT(ModuleSSLOpenSSL)