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 // std::string crlfile;
99 ServiceProvider iohook;
102 ModuleSSLOpenSSL() : iohook(this, "ssl/openssl", SERVICE_IOHOOK)
104 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
106 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
107 inbufsize = ServerInstance->Config->NetBufferSize;
109 /* Global SSL library initialization*/
111 SSL_load_error_strings();
113 /* Build our SSL contexts:
114 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
116 ctx = SSL_CTX_new( SSLv23_server_method() );
117 clictx = SSL_CTX_new( SSLv23_client_method() );
119 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
120 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
122 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
123 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
128 // Needs the flag as it ignores a plain /rehash
129 OnModuleRehash(NULL,"ssl");
130 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO, I_OnUserConnect };
131 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
132 ServerInstance->Modules->AddService(iohook);
135 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
137 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
139 /* Hook the user with our module */
140 user->AddIOHook(this);
144 void OnRehash(User* user)
150 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
152 ListenSocket* port = ServerInstance->ports[i];
153 if (port->bind_tag->getString("ssl") != "openssl")
156 std::string portid = port->bind_desc;
157 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
158 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
159 sslports.append(portid).append(";");
162 if (!sslports.empty())
163 sslports.erase(sslports.end() - 1);
166 void OnModuleRehash(User* user, const std::string ¶m)
175 cafile = Conf.ReadValue("openssl", "cafile", 0);
176 certfile = Conf.ReadValue("openssl", "certfile", 0);
177 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
178 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
180 // Set all the default values needed.
182 cafile = "conf/ca.pem";
184 if (certfile.empty())
185 certfile = "conf/cert.pem";
188 keyfile = "conf/key.pem";
191 dhfile = "conf/dhparams.pem";
193 /* Load our keys and certificates
194 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
196 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
198 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
199 ERR_print_errors_cb(error_callback, this);
202 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)))
204 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
205 ERR_print_errors_cb(error_callback, this);
208 /* Load the CAs we trust*/
209 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
211 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
212 ERR_print_errors_cb(error_callback, this);
215 FILE* dhpfile = fopen(dhfile.c_str(), "r");
220 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
221 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
225 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
226 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
228 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
229 ERR_print_errors_cb(error_callback, this);
236 void On005Numeric(std::string &output)
238 if (!sslports.empty())
239 output.append(" SSL=" + sslports);
245 SSL_CTX_free(clictx);
249 void OnUserConnect(LocalUser* user)
251 if (user->eh.GetIOHook() == this)
253 if (sessions[user->GetFd()].sess)
255 SSLCertSubmission(user, this, ServerInstance->Modules->Find("m_sslinfo.so"), sessions[user->GetFd()].cert);
260 void OnCleanup(int target_type, void* item)
262 if (target_type == TYPE_USER)
264 LocalUser* user = IS_LOCAL((User*)item);
266 if (user && user->eh.GetIOHook() == this)
268 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
269 // Potentially there could be multiple SSL modules loaded at once on different ports.
270 ServerInstance->Users->QuitUser(user, "SSL module unloading");
277 return Version("Provides SSL support for clients", VF_VENDOR);
280 void OnRequest(Request& request)
282 if (strcmp("GET_SSL_CERT", request.id) == 0)
284 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
285 int fd = req.sock->GetFd();
286 issl_session* session = &sessions[fd];
288 req.cert = session->cert;
292 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
294 int fd = user->GetFd();
296 issl_session* session = &sessions[fd];
299 session->sess = SSL_new(ctx);
300 session->status = ISSL_NONE;
301 session->outbound = false;
303 if (session->sess == NULL)
306 if (SSL_set_fd(session->sess, fd) == 0)
308 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
312 Handshake(user, session);
315 void OnStreamSocketConnect(StreamSocket* user)
317 int fd = user->GetFd();
318 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
319 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
322 issl_session* session = &sessions[fd];
325 session->sess = SSL_new(clictx);
326 session->status = ISSL_NONE;
327 session->outbound = true;
329 if (session->sess == NULL)
332 if (SSL_set_fd(session->sess, fd) == 0)
334 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
338 Handshake(user, session);
341 void OnStreamSocketClose(StreamSocket* user)
343 int fd = user->GetFd();
344 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
345 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
348 CloseSession(&sessions[fd]);
351 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
353 int fd = user->GetFd();
354 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
355 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
358 issl_session* session = &sessions[fd];
362 CloseSession(session);
366 if (session->status == ISSL_HANDSHAKING)
368 // The handshake isn't finished and it wants to read, try to finish it.
369 if (!Handshake(user, session))
371 // Couldn't resume handshake.
372 if (session->status == ISSL_NONE)
378 // If we resumed the handshake then session->status will be ISSL_OPEN
380 if (session->status == ISSL_OPEN)
382 char* buffer = ServerInstance->GetReadBuffer();
383 size_t bufsiz = ServerInstance->Config->NetBufferSize;
384 int ret = SSL_read(session->sess, buffer, bufsiz);
388 recvq.append(buffer, ret);
393 // Client closed connection.
394 CloseSession(session);
399 int err = SSL_get_error(session->sess, ret);
401 if (err == SSL_ERROR_WANT_READ)
403 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
406 else if (err == SSL_ERROR_WANT_WRITE)
408 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
413 CloseSession(session);
422 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
424 int fd = user->GetFd();
426 issl_session* session = &sessions[fd];
430 CloseSession(session);
434 session->data_to_write = true;
436 if (session->status == ISSL_HANDSHAKING)
438 if (!Handshake(user, session))
440 // Couldn't resume handshake.
441 if (session->status == ISSL_NONE)
447 if (session->status == ISSL_OPEN)
449 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
450 if (ret == (int)buffer.length())
452 session->data_to_write = false;
453 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
458 buffer = buffer.substr(ret);
459 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
464 CloseSession(session);
469 int err = SSL_get_error(session->sess, ret);
471 if (err == SSL_ERROR_WANT_WRITE)
473 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
476 else if (err == SSL_ERROR_WANT_READ)
478 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
483 CloseSession(session);
491 bool Handshake(StreamSocket* user, issl_session* session)
495 if (session->outbound)
496 ret = SSL_connect(session->sess);
498 ret = SSL_accept(session->sess);
502 int err = SSL_get_error(session->sess, ret);
504 if (err == SSL_ERROR_WANT_READ)
506 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
507 session->status = ISSL_HANDSHAKING;
510 else if (err == SSL_ERROR_WANT_WRITE)
512 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
513 session->status = ISSL_HANDSHAKING;
518 CloseSession(session);
525 // Handshake complete.
526 VerifyCertificate(session, user);
528 session->status = ISSL_OPEN;
530 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
536 CloseSession(session);
543 void CloseSession(issl_session* session)
547 SSL_shutdown(session->sess);
548 SSL_free(session->sess);
551 session->sess = NULL;
552 session->status = ISSL_NONE;
556 void VerifyCertificate(issl_session* session, StreamSocket* user)
558 if (!session->sess || !user || session->cert)
562 ssl_cert* certinfo = new ssl_cert;
563 session->cert = certinfo;
565 unsigned char md[EVP_MAX_MD_SIZE];
566 const EVP_MD *digest = EVP_md5();
568 cert = SSL_get_peer_certificate((SSL*)session->sess);
572 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
576 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
580 certinfo->unknownsigner = false;
581 certinfo->trusted = true;
585 certinfo->unknownsigner = true;
586 certinfo->trusted = false;
589 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
590 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
592 if (!X509_digest(cert, digest, md, &n))
594 certinfo->error = "Out of memory generating fingerprint";
598 certinfo->fingerprint = irc::hex(md, n);
601 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))
603 certinfo->error = "Not activated, or expired certificate";
610 static int error_callback(const char *str, size_t len, void *u)
612 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
615 // XXX: Remove this line, it causes valgrind warnings...
617 // MD_update(&m, buf, j);
620 // ... ONLY JOKING! :-)
626 MODULE_INIT(ModuleSSLOpenSSL)