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") */
35 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
37 static bool SelfSigned = false;
41 return ERR_error_string(ERR_get_error(), NULL);
44 static int error_callback(const char *str, size_t len, void *u);
46 /** Represents an SSL user's extra data
53 reference<ssl_cert> cert;
62 data_to_write = false;
66 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
68 /* XXX: This will allow self signed certificates.
69 * In the future if we want an option to not allow this,
70 * we can just return preverify_ok here, and openssl
71 * will boot off self-signed and invalid peer certs.
73 int ve = X509_STORE_CTX_get_error(ctx);
75 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
80 class ModuleSSLOpenSSL : public Module
83 issl_session* sessions;
93 ServiceProvider iohook;
96 ModuleSSLOpenSSL() : iohook(this, "ssl/openssl", SERVICE_IOHOOK)
98 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
100 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
101 inbufsize = ServerInstance->Config->NetBufferSize;
103 /* Global SSL library initialization*/
105 SSL_load_error_strings();
107 /* Build our SSL contexts:
108 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
110 ctx = SSL_CTX_new( SSLv23_server_method() );
111 clictx = SSL_CTX_new( SSLv23_client_method() );
113 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
114 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
116 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
117 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
122 // Needs the flag as it ignores a plain /rehash
123 OnModuleRehash(NULL,"ssl");
124 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO, I_OnUserConnect };
125 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
126 ServerInstance->Modules->AddService(iohook);
129 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
131 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
133 /* Hook the user with our module */
134 user->AddIOHook(this);
138 void OnRehash(User* user)
142 ConfigTag* Conf = ServerInstance->Config->ConfValue("openssl");
144 if (Conf->getBool("showports", true))
146 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
148 ListenSocket* port = ServerInstance->ports[i];
149 if (port->bind_tag->getString("ssl") != "openssl")
152 std::string portid = port->bind_desc;
153 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
154 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
155 sslports.append(portid).append(";");
158 if (!sslports.empty())
159 sslports.erase(sslports.end() - 1);
163 void OnModuleRehash(User* user, const std::string ¶m)
169 std::string certfile;
174 ConfigTag* conf = ServerInstance->Config->ConfValue("openssl");
176 cafile = conf->getString("cafile", "conf/ca.pem");
177 certfile = conf->getString("certfile", "conf/cert.pem");
178 keyfile = conf->getString("keyfile", "conf/key.pem");
179 dhfile = conf->getString("dhfile", "conf/dhparams.pem");
180 std::string hash = conf->getString("hash", "md5");
181 if (hash != "sha1" && hash != "md5")
182 throw ModuleException("Unknown hash type " + hash);
183 use_sha = (hash == "sha1");
186 /* Load our keys and certificates
187 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
189 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
191 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
192 ERR_print_errors_cb(error_callback, this);
195 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)))
197 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
198 ERR_print_errors_cb(error_callback, this);
201 /* Load the CAs we trust*/
202 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
204 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
205 ERR_print_errors_cb(error_callback, this);
208 FILE* dhpfile = fopen(dhfile.c_str(), "r");
213 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
214 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
218 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
219 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
221 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
222 ERR_print_errors_cb(error_callback, this);
229 void On005Numeric(std::string &output)
231 if (!sslports.empty())
232 output.append(" SSL=" + sslports);
238 SSL_CTX_free(clictx);
242 void OnUserConnect(LocalUser* user)
244 if (user->eh.GetIOHook() == this)
246 if (sessions[user->eh.GetFd()].sess)
248 if (!sessions[user->eh.GetFd()].cert->fingerprint.empty())
249 user->WriteServ("NOTICE %s :*** You are connected using SSL fingerprint %s",
250 user->nick.c_str(), sessions[user->eh.GetFd()].cert->fingerprint.c_str());
255 void OnCleanup(int target_type, void* item)
257 if (target_type == TYPE_USER)
259 LocalUser* user = IS_LOCAL((User*)item);
261 if (user && user->eh.GetIOHook() == this)
263 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
264 // Potentially there could be multiple SSL modules loaded at once on different ports.
265 ServerInstance->Users->QuitUser(user, "SSL module unloading");
272 return Version("Provides SSL support for clients", VF_VENDOR);
275 void OnRequest(Request& request)
277 if (strcmp("GET_SSL_CERT", request.id) == 0)
279 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
280 int fd = req.sock->GetFd();
281 issl_session* session = &sessions[fd];
283 req.cert = session->cert;
287 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
289 int fd = user->GetFd();
291 issl_session* session = &sessions[fd];
294 session->sess = SSL_new(ctx);
295 session->status = ISSL_NONE;
296 session->outbound = false;
298 if (session->sess == NULL)
301 if (SSL_set_fd(session->sess, fd) == 0)
303 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
307 Handshake(user, session);
310 void OnStreamSocketConnect(StreamSocket* user)
312 int fd = user->GetFd();
313 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
314 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
317 issl_session* session = &sessions[fd];
320 session->sess = SSL_new(clictx);
321 session->status = ISSL_NONE;
322 session->outbound = true;
324 if (session->sess == NULL)
327 if (SSL_set_fd(session->sess, fd) == 0)
329 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
333 Handshake(user, session);
336 void OnStreamSocketClose(StreamSocket* user)
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 CloseSession(&sessions[fd]);
346 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
348 int fd = user->GetFd();
349 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
350 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
353 issl_session* session = &sessions[fd];
357 CloseSession(session);
361 if (session->status == ISSL_HANDSHAKING)
363 // The handshake isn't finished and it wants to read, try to finish it.
364 if (!Handshake(user, session))
366 // Couldn't resume handshake.
367 if (session->status == ISSL_NONE)
373 // If we resumed the handshake then session->status will be ISSL_OPEN
375 if (session->status == ISSL_OPEN)
377 char* buffer = ServerInstance->GetReadBuffer();
378 size_t bufsiz = ServerInstance->Config->NetBufferSize;
379 int ret = SSL_read(session->sess, buffer, bufsiz);
383 recvq.append(buffer, ret);
388 // Client closed connection.
389 CloseSession(session);
394 int err = SSL_get_error(session->sess, ret);
396 if (err == SSL_ERROR_WANT_READ)
398 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
401 else if (err == SSL_ERROR_WANT_WRITE)
403 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
408 CloseSession(session);
417 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
419 int fd = user->GetFd();
421 issl_session* session = &sessions[fd];
425 CloseSession(session);
429 session->data_to_write = true;
431 if (session->status == ISSL_HANDSHAKING)
433 if (!Handshake(user, session))
435 // Couldn't resume handshake.
436 if (session->status == ISSL_NONE)
442 if (session->status == ISSL_OPEN)
444 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
445 if (ret == (int)buffer.length())
447 session->data_to_write = false;
448 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
453 buffer = buffer.substr(ret);
454 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
459 CloseSession(session);
464 int err = SSL_get_error(session->sess, ret);
466 if (err == SSL_ERROR_WANT_WRITE)
468 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
471 else if (err == SSL_ERROR_WANT_READ)
473 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
478 CloseSession(session);
486 bool Handshake(StreamSocket* user, issl_session* session)
490 if (session->outbound)
491 ret = SSL_connect(session->sess);
493 ret = SSL_accept(session->sess);
497 int err = SSL_get_error(session->sess, ret);
499 if (err == SSL_ERROR_WANT_READ)
501 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
502 session->status = ISSL_HANDSHAKING;
505 else if (err == SSL_ERROR_WANT_WRITE)
507 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
508 session->status = ISSL_HANDSHAKING;
513 CloseSession(session);
520 // Handshake complete.
521 VerifyCertificate(session, user);
523 session->status = ISSL_OPEN;
525 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
531 CloseSession(session);
538 void CloseSession(issl_session* session)
542 SSL_shutdown(session->sess);
543 SSL_free(session->sess);
546 session->sess = NULL;
547 session->status = ISSL_NONE;
551 void VerifyCertificate(issl_session* session, StreamSocket* user)
553 if (!session->sess || !user || session->cert)
557 ssl_cert* certinfo = new ssl_cert;
558 session->cert = certinfo;
560 unsigned char md[EVP_MAX_MD_SIZE];
561 const EVP_MD *digest = use_sha ? EVP_sha1() : EVP_md5();
563 cert = SSL_get_peer_certificate((SSL*)session->sess);
567 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
571 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
575 certinfo->unknownsigner = false;
576 certinfo->trusted = true;
580 certinfo->unknownsigner = true;
581 certinfo->trusted = false;
584 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
585 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
587 if (!X509_digest(cert, digest, md, &n))
589 certinfo->error = "Out of memory generating fingerprint";
593 certinfo->fingerprint = irc::hex(md, n);
596 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))
598 certinfo->error = "Not activated, or expired certificate";
605 static int error_callback(const char *str, size_t len, void *u)
607 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
610 // XXX: Remove this line, it causes valgrind warnings...
612 // MD_update(&m, buf, j);
615 // ... ONLY JOKING! :-)
621 MODULE_INIT(ModuleSSLOpenSSL)