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.
62 std::string outbuf; // Buffer for outgoing data that OpenSSL will not take.
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;
102 std::string certfile;
104 // std::string crlfile;
106 std::string sslports;
110 InspIRCd* PublicInstance;
112 ModuleSSLOpenSSL(InspIRCd* Me)
113 : Module(Me), PublicInstance(Me)
115 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
117 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
119 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
120 inbufsize = ServerInstance->Config->NetBufferSize;
122 /* Global SSL library initialization*/
124 SSL_load_error_strings();
126 /* Build our SSL contexts:
127 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
129 ctx = SSL_CTX_new( SSLv23_server_method() );
130 clictx = SSL_CTX_new( SSLv23_client_method() );
132 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
133 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
135 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
136 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
138 // Needs the flag as it ignores a plain /rehash
139 OnModuleRehash(NULL,"ssl");
140 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept,
141 I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup, I_On005Numeric,
142 I_OnBufferFlushed, I_OnRequest, I_OnRehash, I_OnModuleRehash, I_OnPostConnect,
144 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
147 virtual void OnHookIO(EventHandler* user, ListenSocketBase* lsb)
149 if (!user->GetIOHook() && listenports.find(lsb) != listenports.end())
151 /* Hook the user with our module */
152 user->AddIOHook(this);
156 virtual void OnRehash(User* user)
158 ConfigReader Conf(ServerInstance);
163 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
165 ListenSocketBase* port = ServerInstance->ports[i];
166 std::string desc = port->GetDescription();
167 if (desc != "openssl")
170 listenports.insert(port);
171 std::string portid = port->GetBindDesc();
173 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
174 if (port->GetIP() != "127.0.0.1")
175 sslports.append(portid).append(";");
178 if (!sslports.empty())
179 sslports.erase(sslports.end() - 1);
182 virtual void OnModuleRehash(User* user, const std::string ¶m)
189 ConfigReader Conf(ServerInstance);
191 std::string confdir(ServerInstance->ConfigFileName);
192 // +1 so we the path ends with a /
193 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
195 cafile = Conf.ReadValue("openssl", "cafile", 0);
196 certfile = Conf.ReadValue("openssl", "certfile", 0);
197 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
198 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
200 // Set all the default values needed.
204 if (certfile.empty())
205 certfile = "cert.pem";
211 dhfile = "dhparams.pem";
213 // Prepend relative paths with the path to the config directory.
214 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
215 cafile = confdir + cafile;
217 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
218 certfile = confdir + certfile;
220 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
221 keyfile = confdir + keyfile;
223 if ((dhfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(dhfile)))
224 dhfile = confdir + dhfile;
226 /* Load our keys and certificates
227 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
229 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
231 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
232 ERR_print_errors_cb(error_callback, this);
235 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)))
237 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
238 ERR_print_errors_cb(error_callback, this);
241 /* Load the CAs we trust*/
242 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
244 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
245 ERR_print_errors_cb(error_callback, this);
248 FILE* dhpfile = fopen(dhfile.c_str(), "r");
253 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
254 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
258 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
259 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
261 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
262 ERR_print_errors_cb(error_callback, this);
269 virtual void On005Numeric(std::string &output)
271 if (!sslports.empty())
272 output.append(" SSL=" + sslports);
275 virtual ~ModuleSSLOpenSSL()
278 SSL_CTX_free(clictx);
279 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
283 virtual void OnCleanup(int target_type, void* item)
285 if (target_type == TYPE_USER)
287 User* user = (User*)item;
289 if (user->GetIOHook() == this)
291 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
292 // Potentially there could be multiple SSL modules loaded at once on different ports.
293 ServerInstance->Users->QuitUser(user, "SSL module unloading");
299 virtual Version GetVersion()
301 return Version("$Id$", VF_VENDOR, API_VERSION);
305 virtual const char* OnRequest(Request* request)
307 ISHRequest* ISR = (ISHRequest*)request;
308 if (strcmp("IS_NAME", request->GetId()) == 0)
312 else if (strcmp("IS_HOOK", request->GetId()) == 0)
314 const char* ret = "OK";
317 ret = ISR->Sock->AddIOHook((Module*)this) ? "OK" : NULL;
319 catch (ModuleException &e)
326 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
328 return ISR->Sock->DelIOHook() ? "OK" : NULL;
330 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
332 if (ISR->Sock->GetFd() < 0)
335 issl_session* session = &sessions[ISR->Sock->GetFd()];
336 return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
338 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
340 issl_session* session = &sessions[ISR->Sock->GetFd()];
346 else if (strcmp("GET_CERT", request->GetId()) == 0)
348 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
350 return sslinfo->OnRequest(request);
356 virtual void OnRawSocketAccept(int fd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
358 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
359 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
362 issl_session* session = &sessions[fd];
365 session->inbuf = new char[inbufsize];
366 session->inbufoffset = 0;
367 session->sess = SSL_new(ctx);
368 session->status = ISSL_NONE;
369 session->outbound = false;
371 if (session->sess == NULL)
374 if (SSL_set_fd(session->sess, fd) == 0)
376 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
383 virtual void OnRawSocketConnect(int fd)
385 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
386 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
389 issl_session* session = &sessions[fd];
392 session->inbuf = new char[inbufsize];
393 session->inbufoffset = 0;
394 session->sess = SSL_new(clictx);
395 session->status = ISSL_NONE;
396 session->outbound = true;
398 if (session->sess == NULL)
401 if (SSL_set_fd(session->sess, fd) == 0)
403 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
410 virtual void OnRawSocketClose(int fd)
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 CloseSession(&sessions[fd]);
419 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
421 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
422 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
425 issl_session* session = &sessions[fd];
430 CloseSession(session);
434 if (session->status == ISSL_HANDSHAKING)
436 if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
438 // The handshake isn't finished and it wants to read, try to finish it.
439 if (!Handshake(session))
441 // Couldn't resume handshake.
442 errno = session->status == ISSL_NONE ? EIO : EAGAIN;
453 // If we resumed the handshake then session->status will be ISSL_OPEN
455 if (session->status == ISSL_OPEN)
457 if (session->wstat == ISSL_READ)
459 if(DoWrite(session) == 0)
463 if (session->rstat == ISSL_READ)
465 int ret = DoRead(session);
469 if (count <= session->inbufoffset)
471 memcpy(buffer, session->inbuf, count);
472 // Move the stuff left in inbuf to the beginning of it
473 memmove(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
474 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
475 session->inbufoffset -= count;
476 // Insp uses readresult as the count of how much data there is in buffer, so:
481 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
482 memcpy(buffer, session->inbuf, session->inbufoffset);
484 readresult = session->inbufoffset;
485 // Zero the offset, as there's nothing there..
486 session->inbufoffset = 0;
497 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
499 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
500 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
504 issl_session* session = &sessions[fd];
508 CloseSession(session);
512 session->outbuf.append(buffer, count);
513 MakePollWrite(session);
515 if (session->status == ISSL_HANDSHAKING)
517 // The handshake isn't finished, try to finish it.
518 if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
520 if (!Handshake(session))
522 // Couldn't resume handshake.
523 errno = session->status == ISSL_NONE ? EIO : EAGAIN;
529 if (session->status == ISSL_OPEN)
531 if (session->rstat == ISSL_WRITE)
536 if (session->wstat == ISSL_WRITE)
538 return DoWrite(session);
545 int DoWrite(issl_session* session)
547 if (!session->outbuf.size())
550 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
554 CloseSession(session);
559 int err = SSL_get_error(session->sess, ret);
561 if (err == SSL_ERROR_WANT_WRITE)
563 session->wstat = ISSL_WRITE;
566 else if (err == SSL_ERROR_WANT_READ)
568 session->wstat = ISSL_READ;
573 CloseSession(session);
579 session->outbuf = session->outbuf.substr(ret);
584 int DoRead(issl_session* session)
586 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
587 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
589 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
593 // Client closed connection.
594 CloseSession(session);
599 int err = SSL_get_error(session->sess, ret);
601 if (err == SSL_ERROR_WANT_READ)
603 session->rstat = ISSL_READ;
606 else if (err == SSL_ERROR_WANT_WRITE)
608 session->rstat = ISSL_WRITE;
609 MakePollWrite(session);
614 CloseSession(session);
620 // Read successfully 'ret' bytes into inbuf + inbufoffset
621 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
622 // 'buffer' is 'count' long
624 session->inbufoffset += ret;
630 bool Handshake(issl_session* session)
634 if (session->outbound)
635 ret = SSL_connect(session->sess);
637 ret = SSL_accept(session->sess);
641 int err = SSL_get_error(session->sess, ret);
643 if (err == SSL_ERROR_WANT_READ)
645 session->rstat = ISSL_READ;
646 session->status = ISSL_HANDSHAKING;
649 else if (err == SSL_ERROR_WANT_WRITE)
651 session->wstat = ISSL_WRITE;
652 session->status = ISSL_HANDSHAKING;
653 MakePollWrite(session);
658 CloseSession(session);
665 // Handshake complete.
666 // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
667 EventHandler *u = ServerInstance->SE->GetRef(session->fd);
668 VerifyCertificate(session, u);
670 session->status = ISSL_OPEN;
672 MakePollWrite(session);
678 CloseSession(session);
685 virtual void OnPostConnect(User* user)
687 // This occurs AFTER OnUserConnect so we can be sure the
688 // protocol module has propagated the NICK message.
689 if ((user->GetIOHook() == this) && (IS_LOCAL(user)))
691 if (sessions[user->GetFd()].sess)
692 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), SSL_get_cipher(sessions[user->GetFd()].sess));
696 void MakePollWrite(issl_session* session)
698 //OnRawSocketWrite(session->fd, NULL, 0);
699 EventHandler* eh = ServerInstance->SE->GetRef(session->fd);
702 ServerInstance->SE->WantWrite(eh);
706 virtual void OnBufferFlushed(User* user)
708 if (user->GetIOHook() == this)
710 issl_session* session = &sessions[user->GetFd()];
711 if (session && session->outbuf.size())
712 OnRawSocketWrite(user->GetFd(), NULL, 0);
716 void CloseSession(issl_session* session)
720 SSL_shutdown(session->sess);
721 SSL_free(session->sess);
726 delete[] session->inbuf;
729 session->outbuf.clear();
730 session->inbuf = NULL;
731 session->sess = NULL;
732 session->status = ISSL_NONE;
736 void VerifyCertificate(issl_session* session, Extensible* user)
738 if (!session->sess || !user)
741 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
746 ssl_cert* certinfo = new ssl_cert;
748 unsigned char md[EVP_MAX_MD_SIZE];
749 const EVP_MD *digest = EVP_md5();
751 cert = SSL_get_peer_certificate((SSL*)session->sess);
755 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
756 BufferedSocketFingerprintSubmission(user, this, sslinfo, certinfo).Send();
760 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
764 certinfo->unknownsigner = false;
765 certinfo->trusted = true;
769 certinfo->unknownsigner = true;
770 certinfo->trusted = false;
773 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
774 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
776 if (!X509_digest(cert, digest, md, &n))
778 certinfo->error = "Out of memory generating fingerprint";
782 certinfo->fingerprint = irc::hex(md, n);
785 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))
787 certinfo->error = "Not activated, or expired certificate";
791 BufferedSocketFingerprintSubmission(user, this, sslinfo, certinfo).Send();
796 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
797 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
802 static int error_callback(const char *str, size_t len, void *u)
804 ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
805 mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
808 // XXX: Remove this line, it causes valgrind warnings...
810 // MD_update(&m, buf, j);
813 // ... ONLY JOKING! :-)
819 MODULE_INIT(ModuleSSLOpenSSL)