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[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO };
129 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
132 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
134 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
136 /* Hook the user with our module */
137 user->AddIOHook(this);
141 void OnRehash(User* user)
147 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
149 ListenSocket* port = ServerInstance->ports[i];
150 if (port->bind_tag->getString("ssl") != "openssl")
153 std::string portid = port->bind_desc;
154 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
155 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
156 sslports.append(portid).append(";");
159 if (!sslports.empty())
160 sslports.erase(sslports.end() - 1);
163 void OnModuleRehash(User* user, const std::string ¶m)
172 cafile = Conf.ReadValue("openssl", "cafile", 0);
173 certfile = Conf.ReadValue("openssl", "certfile", 0);
174 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
175 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
177 // Set all the default values needed.
179 cafile = "conf/ca.pem";
181 if (certfile.empty())
182 certfile = "conf/cert.pem";
185 keyfile = "conf/key.pem";
188 dhfile = "conf/dhparams.pem";
190 /* Load our keys and certificates
191 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
193 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
195 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
196 ERR_print_errors_cb(error_callback, this);
199 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)))
201 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
202 ERR_print_errors_cb(error_callback, this);
205 /* Load the CAs we trust*/
206 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
208 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
209 ERR_print_errors_cb(error_callback, this);
212 FILE* dhpfile = fopen(dhfile.c_str(), "r");
217 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
218 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
222 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
223 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
225 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
226 ERR_print_errors_cb(error_callback, this);
233 void On005Numeric(std::string &output)
235 if (!sslports.empty())
236 output.append(" SSL=" + sslports);
242 SSL_CTX_free(clictx);
243 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
247 void OnCleanup(int target_type, void* item)
249 if (target_type == TYPE_USER)
251 LocalUser* user = IS_LOCAL((User*)item);
253 if (user && user->GetIOHook() == this)
255 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
256 // Potentially there could be multiple SSL modules loaded at once on different ports.
257 ServerInstance->Users->QuitUser(user, "SSL module unloading");
265 return Version("Provides SSL support for clients", VF_VENDOR);
269 void OnRequest(Request& request)
271 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
273 sslinfo->OnRequest(request);
277 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
279 int fd = user->GetFd();
281 issl_session* session = &sessions[fd];
284 session->sess = SSL_new(ctx);
285 session->status = ISSL_NONE;
286 session->outbound = false;
288 if (session->sess == NULL)
291 if (SSL_set_fd(session->sess, fd) == 0)
293 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
297 Handshake(user, session);
300 void OnStreamSocketConnect(StreamSocket* user)
302 int fd = user->GetFd();
303 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
304 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
307 issl_session* session = &sessions[fd];
310 session->sess = SSL_new(clictx);
311 session->status = ISSL_NONE;
312 session->outbound = true;
314 if (session->sess == NULL)
317 if (SSL_set_fd(session->sess, fd) == 0)
319 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
323 Handshake(user, session);
326 void OnStreamSocketClose(StreamSocket* user)
328 int fd = user->GetFd();
329 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
330 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
333 CloseSession(&sessions[fd]);
336 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
338 int fd = user->GetFd();
339 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
340 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
343 issl_session* session = &sessions[fd];
347 CloseSession(session);
351 if (session->status == ISSL_HANDSHAKING)
353 // The handshake isn't finished and it wants to read, try to finish it.
354 if (!Handshake(user, session))
356 // Couldn't resume handshake.
357 if (session->status == ISSL_NONE)
363 // If we resumed the handshake then session->status will be ISSL_OPEN
365 if (session->status == ISSL_OPEN)
367 char* buffer = ServerInstance->GetReadBuffer();
368 size_t bufsiz = ServerInstance->Config->NetBufferSize;
369 int ret = SSL_read(session->sess, buffer, bufsiz);
373 recvq.append(buffer, ret);
378 // Client closed connection.
379 CloseSession(session);
384 int err = SSL_get_error(session->sess, ret);
386 if (err == SSL_ERROR_WANT_READ)
388 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
391 else if (err == SSL_ERROR_WANT_WRITE)
393 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
398 CloseSession(session);
407 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
409 int fd = user->GetFd();
411 issl_session* session = &sessions[fd];
415 CloseSession(session);
419 session->data_to_write = true;
421 if (session->status == ISSL_HANDSHAKING)
423 if (!Handshake(user, session))
425 // Couldn't resume handshake.
426 if (session->status == ISSL_NONE)
432 if (session->status == ISSL_OPEN)
434 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
435 if (ret == (int)buffer.length())
437 session->data_to_write = false;
438 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
443 buffer = buffer.substr(ret);
444 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
449 CloseSession(session);
454 int err = SSL_get_error(session->sess, ret);
456 if (err == SSL_ERROR_WANT_WRITE)
458 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
461 else if (err == SSL_ERROR_WANT_READ)
463 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
468 CloseSession(session);
476 bool Handshake(EventHandler* user, issl_session* session)
480 if (session->outbound)
481 ret = SSL_connect(session->sess);
483 ret = SSL_accept(session->sess);
487 int err = SSL_get_error(session->sess, ret);
489 if (err == SSL_ERROR_WANT_READ)
491 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
492 session->status = ISSL_HANDSHAKING;
495 else if (err == SSL_ERROR_WANT_WRITE)
497 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
498 session->status = ISSL_HANDSHAKING;
503 CloseSession(session);
510 // Handshake complete.
511 VerifyCertificate(session, user);
513 session->status = ISSL_OPEN;
515 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
521 CloseSession(session);
528 void CloseSession(issl_session* session)
532 SSL_shutdown(session->sess);
533 SSL_free(session->sess);
536 session->sess = NULL;
537 session->status = ISSL_NONE;
541 void VerifyCertificate(issl_session* session, Extensible* user)
543 if (!session->sess || !user)
546 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
551 ssl_cert* certinfo = new ssl_cert;
553 unsigned char md[EVP_MAX_MD_SIZE];
554 const EVP_MD *digest = EVP_md5();
556 cert = SSL_get_peer_certificate((SSL*)session->sess);
560 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
561 SSLCertSubmission(user, this, sslinfo, certinfo);
565 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
569 certinfo->unknownsigner = false;
570 certinfo->trusted = true;
574 certinfo->unknownsigner = true;
575 certinfo->trusted = false;
578 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
579 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
581 if (!X509_digest(cert, digest, md, &n))
583 certinfo->error = "Out of memory generating fingerprint";
587 certinfo->fingerprint = irc::hex(md, n);
590 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))
592 certinfo->error = "Not activated, or expired certificate";
596 SSLCertSubmission(user, this, sslinfo, certinfo);
600 static int error_callback(const char *str, size_t len, void *u)
602 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
605 // XXX: Remove this line, it causes valgrind warnings...
607 // MD_update(&m, buf, j);
610 // ... ONLY JOKING! :-)
616 MODULE_INIT(ModuleSSLOpenSSL)