1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 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
56 reference<ssl_cert> cert;
65 data_to_write = false;
69 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
71 /* XXX: This will allow self signed certificates.
72 * In the future if we want an option to not allow this,
73 * we can just return preverify_ok here, and openssl
74 * will boot off self-signed and invalid peer certs.
76 int ve = X509_STORE_CTX_get_error(ctx);
78 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
83 class ModuleSSLOpenSSL : public Module
86 issl_session* sessions;
96 // std::string crlfile;
100 ServiceProvider iohook;
103 ModuleSSLOpenSSL() : iohook(this, "ssl/openssl", SERVICE_IOHOOK)
106 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
108 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
109 inbufsize = ServerInstance->Config->NetBufferSize;
111 /* Global SSL library initialization*/
113 SSL_load_error_strings();
115 /* Build our SSL contexts:
116 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
118 ctx = SSL_CTX_new( SSLv23_server_method() );
119 clictx = SSL_CTX_new( SSLv23_client_method() );
121 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
122 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
124 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
125 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
127 // Needs the flag as it ignores a plain /rehash
128 OnModuleRehash(NULL,"ssl");
129 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO, I_OnUserConnect };
130 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
131 ServerInstance->Modules->AddService(iohook);
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);
248 void OnUserConnect(LocalUser* user)
250 if (user->eh.GetIOHook() == this)
252 if (sessions[user->GetFd()].sess)
254 SSLCertSubmission(user, this, ServerInstance->Modules->Find("m_sslinfo.so"), sessions[user->GetFd()].cert);
259 void OnCleanup(int target_type, void* item)
261 if (target_type == TYPE_USER)
263 LocalUser* user = IS_LOCAL((User*)item);
265 if (user && user->eh.GetIOHook() == this)
267 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
268 // Potentially there could be multiple SSL modules loaded at once on different ports.
269 ServerInstance->Users->QuitUser(user, "SSL module unloading");
276 return Version("Provides SSL support for clients", VF_VENDOR);
279 void OnRequest(Request& request)
281 if (strcmp("GET_SSL_CERT", request.id) == 0)
283 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
284 int fd = req.sock->GetFd();
285 issl_session* session = &sessions[fd];
287 req.cert = session->cert;
291 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
293 int fd = user->GetFd();
295 issl_session* session = &sessions[fd];
298 session->sess = SSL_new(ctx);
299 session->status = ISSL_NONE;
300 session->outbound = false;
302 if (session->sess == NULL)
305 if (SSL_set_fd(session->sess, fd) == 0)
307 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
311 Handshake(user, session);
314 void OnStreamSocketConnect(StreamSocket* user)
316 int fd = user->GetFd();
317 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
318 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
321 issl_session* session = &sessions[fd];
324 session->sess = SSL_new(clictx);
325 session->status = ISSL_NONE;
326 session->outbound = true;
328 if (session->sess == NULL)
331 if (SSL_set_fd(session->sess, fd) == 0)
333 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
337 Handshake(user, session);
340 void OnStreamSocketClose(StreamSocket* user)
342 int fd = user->GetFd();
343 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
344 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
347 CloseSession(&sessions[fd]);
350 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
352 int fd = user->GetFd();
353 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
354 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
357 issl_session* session = &sessions[fd];
361 CloseSession(session);
365 if (session->status == ISSL_HANDSHAKING)
367 // The handshake isn't finished and it wants to read, try to finish it.
368 if (!Handshake(user, session))
370 // Couldn't resume handshake.
371 if (session->status == ISSL_NONE)
377 // If we resumed the handshake then session->status will be ISSL_OPEN
379 if (session->status == ISSL_OPEN)
381 char* buffer = ServerInstance->GetReadBuffer();
382 size_t bufsiz = ServerInstance->Config->NetBufferSize;
383 int ret = SSL_read(session->sess, buffer, bufsiz);
387 recvq.append(buffer, ret);
392 // Client closed connection.
393 CloseSession(session);
398 int err = SSL_get_error(session->sess, ret);
400 if (err == SSL_ERROR_WANT_READ)
402 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
405 else if (err == SSL_ERROR_WANT_WRITE)
407 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
412 CloseSession(session);
421 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
423 int fd = user->GetFd();
425 issl_session* session = &sessions[fd];
429 CloseSession(session);
433 session->data_to_write = true;
435 if (session->status == ISSL_HANDSHAKING)
437 if (!Handshake(user, session))
439 // Couldn't resume handshake.
440 if (session->status == ISSL_NONE)
446 if (session->status == ISSL_OPEN)
448 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
449 if (ret == (int)buffer.length())
451 session->data_to_write = false;
452 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
457 buffer = buffer.substr(ret);
458 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
463 CloseSession(session);
468 int err = SSL_get_error(session->sess, ret);
470 if (err == SSL_ERROR_WANT_WRITE)
472 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
475 else if (err == SSL_ERROR_WANT_READ)
477 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
482 CloseSession(session);
490 bool Handshake(StreamSocket* user, issl_session* session)
494 if (session->outbound)
495 ret = SSL_connect(session->sess);
497 ret = SSL_accept(session->sess);
501 int err = SSL_get_error(session->sess, ret);
503 if (err == SSL_ERROR_WANT_READ)
505 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
506 session->status = ISSL_HANDSHAKING;
509 else if (err == SSL_ERROR_WANT_WRITE)
511 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
512 session->status = ISSL_HANDSHAKING;
517 CloseSession(session);
524 // Handshake complete.
525 VerifyCertificate(session, user);
527 session->status = ISSL_OPEN;
529 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
535 CloseSession(session);
542 void CloseSession(issl_session* session)
546 SSL_shutdown(session->sess);
547 SSL_free(session->sess);
550 session->sess = NULL;
551 session->status = ISSL_NONE;
555 void VerifyCertificate(issl_session* session, StreamSocket* user)
557 if (!session->sess || !user || session->cert)
561 ssl_cert* certinfo = new ssl_cert;
562 session->cert = certinfo;
564 unsigned char md[EVP_MAX_MD_SIZE];
565 const EVP_MD *digest = EVP_md5();
567 cert = SSL_get_peer_certificate((SSL*)session->sess);
571 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
575 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
579 certinfo->unknownsigner = false;
580 certinfo->trusted = true;
584 certinfo->unknownsigner = true;
585 certinfo->trusted = false;
588 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
589 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
591 if (!X509_digest(cert, digest, md, &n))
593 certinfo->error = "Out of memory generating fingerprint";
597 certinfo->fingerprint = irc::hex(md, n);
600 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))
602 certinfo->error = "Not activated, or expired certificate";
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)