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->eh.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");
264 return Version("Provides SSL support for clients", VF_VENDOR);
268 void OnRequest(Request& request)
270 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
272 sslinfo->OnRequest(request);
276 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
278 int fd = user->GetFd();
280 issl_session* session = &sessions[fd];
283 session->sess = SSL_new(ctx);
284 session->status = ISSL_NONE;
285 session->outbound = false;
287 if (session->sess == NULL)
290 if (SSL_set_fd(session->sess, fd) == 0)
292 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
296 Handshake(user, session);
299 void OnStreamSocketConnect(StreamSocket* user)
301 int fd = user->GetFd();
302 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
303 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
306 issl_session* session = &sessions[fd];
309 session->sess = SSL_new(clictx);
310 session->status = ISSL_NONE;
311 session->outbound = true;
313 if (session->sess == NULL)
316 if (SSL_set_fd(session->sess, fd) == 0)
318 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
322 Handshake(user, session);
325 void OnStreamSocketClose(StreamSocket* user)
327 int fd = user->GetFd();
328 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
329 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
332 CloseSession(&sessions[fd]);
335 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
337 int fd = user->GetFd();
338 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
339 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
342 issl_session* session = &sessions[fd];
346 CloseSession(session);
350 if (session->status == ISSL_HANDSHAKING)
352 // The handshake isn't finished and it wants to read, try to finish it.
353 if (!Handshake(user, session))
355 // Couldn't resume handshake.
356 if (session->status == ISSL_NONE)
362 // If we resumed the handshake then session->status will be ISSL_OPEN
364 if (session->status == ISSL_OPEN)
366 char* buffer = ServerInstance->GetReadBuffer();
367 size_t bufsiz = ServerInstance->Config->NetBufferSize;
368 int ret = SSL_read(session->sess, buffer, bufsiz);
372 recvq.append(buffer, ret);
377 // Client closed connection.
378 CloseSession(session);
383 int err = SSL_get_error(session->sess, ret);
385 if (err == SSL_ERROR_WANT_READ)
387 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
390 else if (err == SSL_ERROR_WANT_WRITE)
392 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
397 CloseSession(session);
406 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
408 int fd = user->GetFd();
410 issl_session* session = &sessions[fd];
414 CloseSession(session);
418 session->data_to_write = true;
420 if (session->status == ISSL_HANDSHAKING)
422 if (!Handshake(user, session))
424 // Couldn't resume handshake.
425 if (session->status == ISSL_NONE)
431 if (session->status == ISSL_OPEN)
433 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
434 if (ret == (int)buffer.length())
436 session->data_to_write = false;
437 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
442 buffer = buffer.substr(ret);
443 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
448 CloseSession(session);
453 int err = SSL_get_error(session->sess, ret);
455 if (err == SSL_ERROR_WANT_WRITE)
457 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
460 else if (err == SSL_ERROR_WANT_READ)
462 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
467 CloseSession(session);
475 bool Handshake(EventHandler* user, issl_session* session)
479 if (session->outbound)
480 ret = SSL_connect(session->sess);
482 ret = SSL_accept(session->sess);
486 int err = SSL_get_error(session->sess, ret);
488 if (err == SSL_ERROR_WANT_READ)
490 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
491 session->status = ISSL_HANDSHAKING;
494 else if (err == SSL_ERROR_WANT_WRITE)
496 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
497 session->status = ISSL_HANDSHAKING;
502 CloseSession(session);
509 // Handshake complete.
510 VerifyCertificate(session, user);
512 session->status = ISSL_OPEN;
514 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
520 CloseSession(session);
527 void CloseSession(issl_session* session)
531 SSL_shutdown(session->sess);
532 SSL_free(session->sess);
535 session->sess = NULL;
536 session->status = ISSL_NONE;
540 void VerifyCertificate(issl_session* session, Extensible* user)
542 if (!session->sess || !user)
545 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
550 ssl_cert* certinfo = new ssl_cert;
552 unsigned char md[EVP_MAX_MD_SIZE];
553 const EVP_MD *digest = EVP_md5();
555 cert = SSL_get_peer_certificate((SSL*)session->sess);
559 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
560 SSLCertSubmission(user, this, sslinfo, certinfo);
564 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
568 certinfo->unknownsigner = false;
569 certinfo->trusted = true;
573 certinfo->unknownsigner = true;
574 certinfo->trusted = false;
577 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
578 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
580 if (!X509_digest(cert, digest, md, &n))
582 certinfo->error = "Out of memory generating fingerprint";
586 certinfo->fingerprint = irc::hex(md, n);
589 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))
591 certinfo->error = "Not activated, or expired certificate";
595 SSLCertSubmission(user, this, sslinfo, certinfo);
599 static int error_callback(const char *str, size_t len, void *u)
601 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
604 // XXX: Remove this line, it causes valgrind warnings...
606 // MD_update(&m, buf, j);
609 // ... ONLY JOKING! :-)
615 MODULE_INIT(ModuleSSLOpenSSL)