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") */
33 /* $CopyInstall: conf/key.pem $(CONPATH) -m 0400 -o $(INSTUID) */
34 /* $CopyInstall: conf/cert.pem $(CONPATH) -m 0444 */
37 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
39 static bool SelfSigned = false;
43 return ERR_error_string(ERR_get_error(), NULL);
46 static int error_callback(const char *str, size_t len, void *u);
48 /** Represents an SSL user's extra data
55 reference<ssl_cert> cert;
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 ServiceProvider iohook;
98 ModuleSSLOpenSSL() : iohook(this, "ssl/openssl", SERVICE_IOHOOK)
100 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
102 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
103 inbufsize = ServerInstance->Config->NetBufferSize;
105 /* Global SSL library initialization*/
107 SSL_load_error_strings();
109 /* Build our SSL contexts:
110 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
112 ctx = SSL_CTX_new( SSLv23_server_method() );
113 clictx = SSL_CTX_new( SSLv23_client_method() );
115 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
116 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
118 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
119 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
124 // Needs the flag as it ignores a plain /rehash
125 OnModuleRehash(NULL,"ssl");
126 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO, I_OnUserConnect };
127 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
128 ServerInstance->Modules->AddService(iohook);
131 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
133 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
135 /* Hook the user with our module */
136 user->AddIOHook(this);
140 void OnRehash(User* user)
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);
162 void OnModuleRehash(User* user, const std::string ¶m)
168 std::string certfile;
173 ConfigTag* conf = ServerInstance->Config->ConfValue("openssl");
175 cafile = conf->getString("cafile", "conf/ca.pem");
176 certfile = conf->getString("certfile", "conf/cert.pem");
177 keyfile = conf->getString("keyfile", "conf/key.pem");
178 dhfile = conf->getString("dhfile", "conf/dhparams.pem");
179 std::string hash = conf->getString("hash", "md5");
180 if (hash != "sha1" && hash != "md5")
181 throw ModuleException("Unknown hash type " + hash);
182 use_sha = (hash == "sha1");
185 /* Load our keys and certificates
186 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
188 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
190 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
191 ERR_print_errors_cb(error_callback, this);
194 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)))
196 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
197 ERR_print_errors_cb(error_callback, this);
200 /* Load the CAs we trust*/
201 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
203 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
204 ERR_print_errors_cb(error_callback, this);
207 FILE* dhpfile = fopen(dhfile.c_str(), "r");
212 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
213 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
217 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
218 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
220 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
221 ERR_print_errors_cb(error_callback, this);
228 void On005Numeric(std::string &output)
230 if (!sslports.empty())
231 output.append(" SSL=" + sslports);
237 SSL_CTX_free(clictx);
241 void OnUserConnect(LocalUser* user)
243 if (user->eh.GetIOHook() == this)
245 if (sessions[user->GetFd()].sess)
247 SSLCertSubmission(user, this, ServerInstance->Modules->Find("m_sslinfo.so"), sessions[user->GetFd()].cert);
249 if (!sessions[user->GetFd()].cert->fingerprint.empty())
250 user->WriteServ("NOTICE %s :*** You are connected using SSL fingerprint %s",
251 user->nick.c_str(), sessions[user->GetFd()].cert->fingerprint.c_str());
256 void OnCleanup(int target_type, void* item)
258 if (target_type == TYPE_USER)
260 LocalUser* user = IS_LOCAL((User*)item);
262 if (user && user->eh.GetIOHook() == this)
264 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
265 // Potentially there could be multiple SSL modules loaded at once on different ports.
266 ServerInstance->Users->QuitUser(user, "SSL module unloading");
273 return Version("Provides SSL support for clients", VF_VENDOR);
276 void OnRequest(Request& request)
278 if (strcmp("GET_SSL_CERT", request.id) == 0)
280 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
281 int fd = req.sock->GetFd();
282 issl_session* session = &sessions[fd];
284 req.cert = session->cert;
288 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
290 int fd = user->GetFd();
292 issl_session* session = &sessions[fd];
295 session->sess = SSL_new(ctx);
296 session->status = ISSL_NONE;
297 session->outbound = false;
299 if (session->sess == NULL)
302 if (SSL_set_fd(session->sess, fd) == 0)
304 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
308 Handshake(user, session);
311 void OnStreamSocketConnect(StreamSocket* user)
313 int fd = user->GetFd();
314 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
315 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
318 issl_session* session = &sessions[fd];
321 session->sess = SSL_new(clictx);
322 session->status = ISSL_NONE;
323 session->outbound = true;
325 if (session->sess == NULL)
328 if (SSL_set_fd(session->sess, fd) == 0)
330 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
334 Handshake(user, session);
337 void OnStreamSocketClose(StreamSocket* user)
339 int fd = user->GetFd();
340 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
341 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
344 CloseSession(&sessions[fd]);
347 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
349 int fd = user->GetFd();
350 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
351 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
354 issl_session* session = &sessions[fd];
358 CloseSession(session);
362 if (session->status == ISSL_HANDSHAKING)
364 // The handshake isn't finished and it wants to read, try to finish it.
365 if (!Handshake(user, session))
367 // Couldn't resume handshake.
368 if (session->status == ISSL_NONE)
374 // If we resumed the handshake then session->status will be ISSL_OPEN
376 if (session->status == ISSL_OPEN)
378 char* buffer = ServerInstance->GetReadBuffer();
379 size_t bufsiz = ServerInstance->Config->NetBufferSize;
380 int ret = SSL_read(session->sess, buffer, bufsiz);
384 recvq.append(buffer, ret);
389 // Client closed connection.
390 CloseSession(session);
395 int err = SSL_get_error(session->sess, ret);
397 if (err == SSL_ERROR_WANT_READ)
399 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
402 else if (err == SSL_ERROR_WANT_WRITE)
404 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
409 CloseSession(session);
418 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
420 int fd = user->GetFd();
422 issl_session* session = &sessions[fd];
426 CloseSession(session);
430 session->data_to_write = true;
432 if (session->status == ISSL_HANDSHAKING)
434 if (!Handshake(user, session))
436 // Couldn't resume handshake.
437 if (session->status == ISSL_NONE)
443 if (session->status == ISSL_OPEN)
445 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
446 if (ret == (int)buffer.length())
448 session->data_to_write = false;
449 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
454 buffer = buffer.substr(ret);
455 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
460 CloseSession(session);
465 int err = SSL_get_error(session->sess, ret);
467 if (err == SSL_ERROR_WANT_WRITE)
469 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
472 else if (err == SSL_ERROR_WANT_READ)
474 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
479 CloseSession(session);
487 bool Handshake(StreamSocket* user, issl_session* session)
491 if (session->outbound)
492 ret = SSL_connect(session->sess);
494 ret = SSL_accept(session->sess);
498 int err = SSL_get_error(session->sess, ret);
500 if (err == SSL_ERROR_WANT_READ)
502 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
503 session->status = ISSL_HANDSHAKING;
506 else if (err == SSL_ERROR_WANT_WRITE)
508 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
509 session->status = ISSL_HANDSHAKING;
514 CloseSession(session);
521 // Handshake complete.
522 VerifyCertificate(session, user);
524 session->status = ISSL_OPEN;
526 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
532 CloseSession(session);
539 void CloseSession(issl_session* session)
543 SSL_shutdown(session->sess);
544 SSL_free(session->sess);
547 session->sess = NULL;
548 session->status = ISSL_NONE;
552 void VerifyCertificate(issl_session* session, StreamSocket* user)
554 if (!session->sess || !user || session->cert)
558 ssl_cert* certinfo = new ssl_cert;
559 session->cert = certinfo;
561 unsigned char md[EVP_MAX_MD_SIZE];
562 const EVP_MD *digest = use_sha ? EVP_sha1() : EVP_md5();
564 cert = SSL_get_peer_certificate((SSL*)session->sess);
568 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
572 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
576 certinfo->unknownsigner = false;
577 certinfo->trusted = true;
581 certinfo->unknownsigner = true;
582 certinfo->trusted = false;
585 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
586 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
588 if (!X509_digest(cert, digest, md, &n))
590 certinfo->error = "Out of memory generating fingerprint";
594 certinfo->fingerprint = irc::hex(md, n);
597 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))
599 certinfo->error = "Not activated, or expired certificate";
606 static int error_callback(const char *str, size_t len, void *u)
608 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
611 // XXX: Remove this line, it causes valgrind warnings...
613 // MD_update(&m, buf, j);
616 // ... ONLY JOKING! :-)
622 MODULE_INIT(ModuleSSLOpenSSL)