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)
144 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
146 ListenSocket* port = ServerInstance->ports[i];
147 if (port->bind_tag->getString("ssl") != "openssl")
150 std::string portid = port->bind_desc;
151 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
152 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
153 sslports.append(portid).append(";");
156 if (!sslports.empty())
157 sslports.erase(sslports.end() - 1);
160 void OnModuleRehash(User* user, const std::string ¶m)
166 std::string certfile;
171 ConfigTag* conf = ServerInstance->Config->ConfValue("openssl");
173 cafile = conf->getString("cafile", "conf/ca.pem");
174 certfile = conf->getString("certfile", "conf/cert.pem");
175 keyfile = conf->getString("keyfile", "conf/key.pem");
176 dhfile = conf->getString("dhfile", "conf/dhparams.pem");
177 std::string hash = conf->getString("hash", "md5");
178 if (hash != "sha1" && hash != "md5")
179 throw ModuleException("Unknown hash type " + hash);
180 use_sha = (hash == "sha1");
183 /* Load our keys and certificates
184 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
186 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
188 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
189 ERR_print_errors_cb(error_callback, this);
192 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)))
194 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
195 ERR_print_errors_cb(error_callback, this);
198 /* Load the CAs we trust*/
199 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
201 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
202 ERR_print_errors_cb(error_callback, this);
205 FILE* dhpfile = fopen(dhfile.c_str(), "r");
210 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
211 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
215 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
216 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
218 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
219 ERR_print_errors_cb(error_callback, this);
226 void On005Numeric(std::string &output)
228 if (!sslports.empty())
229 output.append(" SSL=" + sslports);
235 SSL_CTX_free(clictx);
239 void OnUserConnect(LocalUser* user)
241 if (user->eh.GetIOHook() == this)
243 if (sessions[user->GetFd()].sess)
245 SSLCertSubmission(user, this, ServerInstance->Modules->Find("m_sslinfo.so"), sessions[user->GetFd()].cert);
247 if (!sessions[user->GetFd()].cert->fingerprint.empty())
248 user->WriteServ("NOTICE %s :*** You are connected using SSL fingerprint %s",
249 user->nick.c_str(), sessions[user->GetFd()].cert->fingerprint.c_str());
254 void OnCleanup(int target_type, void* item)
256 if (target_type == TYPE_USER)
258 LocalUser* user = IS_LOCAL((User*)item);
260 if (user && user->eh.GetIOHook() == this)
262 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
263 // Potentially there could be multiple SSL modules loaded at once on different ports.
264 ServerInstance->Users->QuitUser(user, "SSL module unloading");
271 return Version("Provides SSL support for clients", VF_VENDOR);
274 void OnRequest(Request& request)
276 if (strcmp("GET_SSL_CERT", request.id) == 0)
278 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
279 int fd = req.sock->GetFd();
280 issl_session* session = &sessions[fd];
282 req.cert = session->cert;
286 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
288 int fd = user->GetFd();
290 issl_session* session = &sessions[fd];
293 session->sess = SSL_new(ctx);
294 session->status = ISSL_NONE;
295 session->outbound = false;
297 if (session->sess == NULL)
300 if (SSL_set_fd(session->sess, fd) == 0)
302 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
306 Handshake(user, session);
309 void OnStreamSocketConnect(StreamSocket* user)
311 int fd = user->GetFd();
312 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
313 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
316 issl_session* session = &sessions[fd];
319 session->sess = SSL_new(clictx);
320 session->status = ISSL_NONE;
321 session->outbound = true;
323 if (session->sess == NULL)
326 if (SSL_set_fd(session->sess, fd) == 0)
328 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
332 Handshake(user, session);
335 void OnStreamSocketClose(StreamSocket* user)
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 CloseSession(&sessions[fd]);
345 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
347 int fd = user->GetFd();
348 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
349 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
352 issl_session* session = &sessions[fd];
356 CloseSession(session);
360 if (session->status == ISSL_HANDSHAKING)
362 // The handshake isn't finished and it wants to read, try to finish it.
363 if (!Handshake(user, session))
365 // Couldn't resume handshake.
366 if (session->status == ISSL_NONE)
372 // If we resumed the handshake then session->status will be ISSL_OPEN
374 if (session->status == ISSL_OPEN)
376 char* buffer = ServerInstance->GetReadBuffer();
377 size_t bufsiz = ServerInstance->Config->NetBufferSize;
378 int ret = SSL_read(session->sess, buffer, bufsiz);
382 recvq.append(buffer, ret);
387 // Client closed connection.
388 CloseSession(session);
393 int err = SSL_get_error(session->sess, ret);
395 if (err == SSL_ERROR_WANT_READ)
397 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
400 else if (err == SSL_ERROR_WANT_WRITE)
402 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
407 CloseSession(session);
416 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
418 int fd = user->GetFd();
420 issl_session* session = &sessions[fd];
424 CloseSession(session);
428 session->data_to_write = true;
430 if (session->status == ISSL_HANDSHAKING)
432 if (!Handshake(user, session))
434 // Couldn't resume handshake.
435 if (session->status == ISSL_NONE)
441 if (session->status == ISSL_OPEN)
443 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
444 if (ret == (int)buffer.length())
446 session->data_to_write = false;
447 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
452 buffer = buffer.substr(ret);
453 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
458 CloseSession(session);
463 int err = SSL_get_error(session->sess, ret);
465 if (err == SSL_ERROR_WANT_WRITE)
467 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
470 else if (err == SSL_ERROR_WANT_READ)
472 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
477 CloseSession(session);
485 bool Handshake(StreamSocket* user, issl_session* session)
489 if (session->outbound)
490 ret = SSL_connect(session->sess);
492 ret = SSL_accept(session->sess);
496 int err = SSL_get_error(session->sess, ret);
498 if (err == SSL_ERROR_WANT_READ)
500 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
501 session->status = ISSL_HANDSHAKING;
504 else if (err == SSL_ERROR_WANT_WRITE)
506 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
507 session->status = ISSL_HANDSHAKING;
512 CloseSession(session);
519 // Handshake complete.
520 VerifyCertificate(session, user);
522 session->status = ISSL_OPEN;
524 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
530 CloseSession(session);
537 void CloseSession(issl_session* session)
541 SSL_shutdown(session->sess);
542 SSL_free(session->sess);
545 session->sess = NULL;
546 session->status = ISSL_NONE;
550 void VerifyCertificate(issl_session* session, StreamSocket* user)
552 if (!session->sess || !user || session->cert)
556 ssl_cert* certinfo = new ssl_cert;
557 session->cert = certinfo;
559 unsigned char md[EVP_MAX_MD_SIZE];
560 const EVP_MD *digest = use_sha ? EVP_sha1() : EVP_md5();
562 cert = SSL_get_peer_certificate((SSL*)session->sess);
566 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
570 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
574 certinfo->unknownsigner = false;
575 certinfo->trusted = true;
579 certinfo->unknownsigner = true;
580 certinfo->trusted = false;
583 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
584 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
586 if (!X509_digest(cert, digest, md, &n))
588 certinfo->error = "Out of memory generating fingerprint";
592 certinfo->fingerprint = irc::hex(md, n);
595 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))
597 certinfo->error = "Not activated, or expired certificate";
604 static int error_callback(const char *str, size_t len, void *u)
606 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
609 // XXX: Remove this line, it causes valgrind warnings...
611 // MD_update(&m, buf, j);
614 // ... ONLY JOKING! :-)
620 MODULE_INIT(ModuleSSLOpenSSL)