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>
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
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
85 issl_session* sessions;
95 // std::string crlfile;
103 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
105 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
107 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
108 inbufsize = ServerInstance->Config->NetBufferSize;
110 /* Global SSL library initialization*/
112 SSL_load_error_strings();
114 /* Build our SSL contexts:
115 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
117 ctx = SSL_CTX_new( SSLv23_server_method() );
118 clictx = SSL_CTX_new( SSLv23_client_method() );
120 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
121 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
123 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
124 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
126 // Needs the flag as it ignores a plain /rehash
127 OnModuleRehash(NULL,"ssl");
128 Implementation eventlist[] = {
129 I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnPostConnect,
131 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
134 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
136 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
138 /* Hook the user with our module */
139 user->AddIOHook(this);
143 void OnRehash(User* user)
149 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
151 ListenSocket* port = ServerInstance->ports[i];
152 if (port->bind_tag->getString("ssl") != "openssl")
155 std::string portid = port->bind_desc;
156 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
157 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
158 sslports.append(portid).append(";");
161 if (!sslports.empty())
162 sslports.erase(sslports.end() - 1);
165 void OnModuleRehash(User* user, const std::string ¶m)
174 cafile = Conf.ReadValue("openssl", "cafile", 0);
175 certfile = Conf.ReadValue("openssl", "certfile", 0);
176 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
177 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
179 // Set all the default values needed.
181 cafile = "conf/ca.pem";
183 if (certfile.empty())
184 certfile = "conf/cert.pem";
187 keyfile = "conf/key.pem";
190 dhfile = "conf/dhparams.pem";
192 /* Load our keys and certificates
193 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
195 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
197 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
198 ERR_print_errors_cb(error_callback, this);
201 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)))
203 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
204 ERR_print_errors_cb(error_callback, this);
207 /* Load the CAs we trust*/
208 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
210 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
211 ERR_print_errors_cb(error_callback, this);
214 FILE* dhpfile = fopen(dhfile.c_str(), "r");
219 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
220 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
224 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
225 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
227 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
228 ERR_print_errors_cb(error_callback, this);
235 void On005Numeric(std::string &output)
237 if (!sslports.empty())
238 output.append(" SSL=" + sslports);
244 SSL_CTX_free(clictx);
245 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
249 void OnCleanup(int target_type, void* item)
251 if (target_type == TYPE_USER)
253 User* user = (User*)item;
255 if (user->GetIOHook() == this)
257 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
258 // Potentially there could be multiple SSL modules loaded at once on different ports.
259 ServerInstance->Users->QuitUser(user, "SSL module unloading");
267 return Version("Provides SSL support for clients", VF_VENDOR);
271 void OnRequest(Request& request)
273 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
275 sslinfo->OnRequest(request);
279 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
281 int fd = user->GetFd();
283 issl_session* session = &sessions[fd];
286 session->sess = SSL_new(ctx);
287 session->status = ISSL_NONE;
288 session->outbound = false;
290 if (session->sess == NULL)
293 if (SSL_set_fd(session->sess, fd) == 0)
295 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
299 Handshake(user, session);
302 void OnStreamSocketConnect(StreamSocket* user)
304 int fd = user->GetFd();
305 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
306 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
309 issl_session* session = &sessions[fd];
312 session->sess = SSL_new(clictx);
313 session->status = ISSL_NONE;
314 session->outbound = true;
316 if (session->sess == NULL)
319 if (SSL_set_fd(session->sess, fd) == 0)
321 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
325 Handshake(user, session);
328 void OnStreamSocketClose(StreamSocket* user)
330 int fd = user->GetFd();
331 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
332 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
335 CloseSession(&sessions[fd]);
338 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
340 int fd = user->GetFd();
341 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
342 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
345 issl_session* session = &sessions[fd];
349 CloseSession(session);
353 if (session->status == ISSL_HANDSHAKING)
355 // The handshake isn't finished and it wants to read, try to finish it.
356 if (!Handshake(user, session))
358 // Couldn't resume handshake.
359 if (session->status == ISSL_NONE)
365 // If we resumed the handshake then session->status will be ISSL_OPEN
367 if (session->status == ISSL_OPEN)
369 char* buffer = ServerInstance->GetReadBuffer();
370 size_t bufsiz = ServerInstance->Config->NetBufferSize;
371 int ret = SSL_read(session->sess, buffer, bufsiz);
375 recvq.append(buffer, ret);
380 // Client closed connection.
381 CloseSession(session);
386 int err = SSL_get_error(session->sess, ret);
388 if (err == SSL_ERROR_WANT_READ)
390 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
393 else if (err == SSL_ERROR_WANT_WRITE)
395 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
400 CloseSession(session);
409 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
411 int fd = user->GetFd();
413 issl_session* session = &sessions[fd];
417 CloseSession(session);
421 session->data_to_write = true;
423 if (session->status == ISSL_HANDSHAKING)
425 if (!Handshake(user, session))
427 // Couldn't resume handshake.
428 if (session->status == ISSL_NONE)
434 if (session->status == ISSL_OPEN)
436 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
437 if (ret == (int)buffer.length())
439 session->data_to_write = false;
440 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
445 buffer = buffer.substr(ret);
446 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
451 CloseSession(session);
456 int err = SSL_get_error(session->sess, ret);
458 if (err == SSL_ERROR_WANT_WRITE)
460 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
463 else if (err == SSL_ERROR_WANT_READ)
465 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
470 CloseSession(session);
478 bool Handshake(EventHandler* user, issl_session* session)
482 if (session->outbound)
483 ret = SSL_connect(session->sess);
485 ret = SSL_accept(session->sess);
489 int err = SSL_get_error(session->sess, ret);
491 if (err == SSL_ERROR_WANT_READ)
493 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
494 session->status = ISSL_HANDSHAKING;
497 else if (err == SSL_ERROR_WANT_WRITE)
499 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
500 session->status = ISSL_HANDSHAKING;
505 CloseSession(session);
512 // Handshake complete.
513 VerifyCertificate(session, user);
515 session->status = ISSL_OPEN;
517 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
523 CloseSession(session);
530 void CloseSession(issl_session* session)
534 SSL_shutdown(session->sess);
535 SSL_free(session->sess);
538 session->sess = NULL;
539 session->status = ISSL_NONE;
543 void VerifyCertificate(issl_session* session, Extensible* user)
545 if (!session->sess || !user)
548 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
553 ssl_cert* certinfo = new ssl_cert;
555 unsigned char md[EVP_MAX_MD_SIZE];
556 const EVP_MD *digest = EVP_md5();
558 cert = SSL_get_peer_certificate((SSL*)session->sess);
562 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
563 SSLCertSubmission(user, this, sslinfo, certinfo);
567 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
571 certinfo->unknownsigner = false;
572 certinfo->trusted = true;
576 certinfo->unknownsigner = true;
577 certinfo->trusted = false;
580 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
581 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
583 if (!X509_digest(cert, digest, md, &n))
585 certinfo->error = "Out of memory generating fingerprint";
589 certinfo->fingerprint = irc::hex(md, n);
592 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))
594 certinfo->error = "Not activated, or expired certificate";
598 SSLCertSubmission(user, this, sslinfo, certinfo);
603 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
604 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
609 static int error_callback(const char *str, size_t len, void *u)
611 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
614 // XXX: Remove this line, it causes valgrind warnings...
616 // MD_update(&m, buf, j);
619 // ... ONLY JOKING! :-)
625 MODULE_INIT(ModuleSSLOpenSSL)