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, "libcrypto.lib")
21 # pragma comment(lib, "libssl.lib")
22 # pragma comment(lib, "user32.lib")
23 # pragma comment(lib, "advapi32.lib")
24 # pragma comment(lib, "libgcc.lib")
25 # pragma comment(lib, "libmingwex.lib")
26 # pragma comment(lib, "gdi32.lib")
27 # undef MAX_DESCRIPTORS
28 # define MAX_DESCRIPTORS 10000
31 /* $ModDesc: Provides SSL support for clients */
33 /* $LinkerFlags: if("USE_FREEBSD_BASE_SSL") -lssl -lcrypto */
34 /* $CompileFlags: if(!"USE_FREEBSD_BASE_SSL") pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
35 /* $LinkerFlags: if(!"USE_FREEBSD_BASE_SSL") rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
40 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
42 static bool SelfSigned = false;
46 return ERR_error_string(ERR_get_error(), NULL);
49 static int error_callback(const char *str, size_t len, void *u);
51 /** Represents an SSL user's extra data
58 reference<ssl_cert> cert;
67 data_to_write = false;
71 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
73 /* XXX: This will allow self signed certificates.
74 * In the future if we want an option to not allow this,
75 * we can just return preverify_ok here, and openssl
76 * will boot off self-signed and invalid peer certs.
78 int ve = X509_STORE_CTX_get_error(ctx);
80 SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
85 class ModuleSSLOpenSSL : public Module
88 issl_session* sessions;
98 ServiceProvider iohook;
101 ModuleSSLOpenSSL() : iohook(this, "ssl/openssl", SERVICE_IOHOOK)
103 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
105 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
106 inbufsize = ServerInstance->Config->NetBufferSize;
108 /* Global SSL library initialization*/
110 SSL_load_error_strings();
112 /* Build our SSL contexts:
113 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
115 ctx = SSL_CTX_new( SSLv23_server_method() );
116 clictx = SSL_CTX_new( SSLv23_client_method() );
118 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
119 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
121 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
122 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)
147 ConfigTag* Conf = ServerInstance->Config->ConfValue("openssl");
149 if (Conf->getBool("showports", true))
151 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
153 ListenSocket* port = ServerInstance->ports[i];
154 if (port->bind_tag->getString("ssl") != "openssl")
157 std::string portid = port->bind_desc;
158 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
159 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
160 sslports.append(portid).append(";");
163 if (!sslports.empty())
164 sslports.erase(sslports.end() - 1);
168 void OnModuleRehash(User* user, const std::string ¶m)
174 std::string certfile;
179 ConfigTag* conf = ServerInstance->Config->ConfValue("openssl");
181 cafile = conf->getString("cafile", "conf/ca.pem");
182 certfile = conf->getString("certfile", "conf/cert.pem");
183 keyfile = conf->getString("keyfile", "conf/key.pem");
184 dhfile = conf->getString("dhfile", "conf/dhparams.pem");
185 std::string hash = conf->getString("hash", "md5");
186 if (hash != "sha1" && hash != "md5")
187 throw ModuleException("Unknown hash type " + hash);
188 use_sha = (hash == "sha1");
191 /* Load our keys and certificates
192 * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
194 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
196 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
197 ERR_print_errors_cb(error_callback, this);
200 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)))
202 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
203 ERR_print_errors_cb(error_callback, this);
206 /* Load the CAs we trust*/
207 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
209 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
210 ERR_print_errors_cb(error_callback, this);
213 FILE* dhpfile = fopen(dhfile.c_str(), "r");
218 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
219 throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
223 ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
224 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
226 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
227 ERR_print_errors_cb(error_callback, this);
234 void On005Numeric(std::string &output)
236 if (!sslports.empty())
237 output.append(" SSL=" + sslports);
243 SSL_CTX_free(clictx);
247 void OnUserConnect(LocalUser* user)
249 if (user->eh.GetIOHook() == this)
251 if (sessions[user->eh.GetFd()].sess)
253 if (!sessions[user->eh.GetFd()].cert->fingerprint.empty())
254 user->WriteServ("NOTICE %s :*** You are connected using SSL fingerprint %s",
255 user->nick.c_str(), sessions[user->eh.GetFd()].cert->fingerprint.c_str());
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;
302 session->cert = NULL;
304 if (session->sess == NULL)
307 if (SSL_set_fd(session->sess, fd) == 0)
309 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
313 Handshake(user, session);
316 void OnStreamSocketConnect(StreamSocket* user)
318 int fd = user->GetFd();
319 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
320 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
323 issl_session* session = &sessions[fd];
326 session->sess = SSL_new(clictx);
327 session->status = ISSL_NONE;
328 session->outbound = true;
330 if (session->sess == NULL)
333 if (SSL_set_fd(session->sess, fd) == 0)
335 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
339 Handshake(user, session);
342 void OnStreamSocketClose(StreamSocket* user)
344 int fd = user->GetFd();
345 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
346 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
349 CloseSession(&sessions[fd]);
352 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
354 int fd = user->GetFd();
355 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
356 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
359 issl_session* session = &sessions[fd];
363 CloseSession(session);
367 if (session->status == ISSL_HANDSHAKING)
369 // The handshake isn't finished and it wants to read, try to finish it.
370 if (!Handshake(user, session))
372 // Couldn't resume handshake.
373 if (session->status == ISSL_NONE)
379 // If we resumed the handshake then session->status will be ISSL_OPEN
381 if (session->status == ISSL_OPEN)
383 char* buffer = ServerInstance->GetReadBuffer();
384 size_t bufsiz = ServerInstance->Config->NetBufferSize;
385 int ret = SSL_read(session->sess, buffer, bufsiz);
389 recvq.append(buffer, ret);
390 if (session->data_to_write)
391 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
396 // Client closed connection.
397 CloseSession(session);
402 int err = SSL_get_error(session->sess, ret);
404 if (err == SSL_ERROR_WANT_READ)
406 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
409 else if (err == SSL_ERROR_WANT_WRITE)
411 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
416 CloseSession(session);
425 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
427 int fd = user->GetFd();
429 issl_session* session = &sessions[fd];
433 CloseSession(session);
437 session->data_to_write = true;
439 if (session->status == ISSL_HANDSHAKING)
441 if (!Handshake(user, session))
443 // Couldn't resume handshake.
444 if (session->status == ISSL_NONE)
450 if (session->status == ISSL_OPEN)
452 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
453 if (ret == (int)buffer.length())
455 session->data_to_write = false;
456 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
461 buffer = buffer.substr(ret);
462 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
467 CloseSession(session);
472 int err = SSL_get_error(session->sess, ret);
474 if (err == SSL_ERROR_WANT_WRITE)
476 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
479 else if (err == SSL_ERROR_WANT_READ)
481 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
486 CloseSession(session);
494 bool Handshake(StreamSocket* user, issl_session* session)
498 if (session->outbound)
499 ret = SSL_connect(session->sess);
501 ret = SSL_accept(session->sess);
505 int err = SSL_get_error(session->sess, ret);
507 if (err == SSL_ERROR_WANT_READ)
509 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
510 session->status = ISSL_HANDSHAKING;
513 else if (err == SSL_ERROR_WANT_WRITE)
515 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
516 session->status = ISSL_HANDSHAKING;
521 CloseSession(session);
528 // Handshake complete.
529 VerifyCertificate(session, user);
531 session->status = ISSL_OPEN;
533 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
539 CloseSession(session);
546 void CloseSession(issl_session* session)
550 SSL_shutdown(session->sess);
551 SSL_free(session->sess);
554 session->sess = NULL;
555 session->status = ISSL_NONE;
559 void VerifyCertificate(issl_session* session, StreamSocket* user)
561 if (!session->sess || !user)
565 ssl_cert* certinfo = new ssl_cert;
566 session->cert = certinfo;
568 unsigned char md[EVP_MAX_MD_SIZE];
569 const EVP_MD *digest = use_sha ? EVP_sha1() : EVP_md5();
571 cert = SSL_get_peer_certificate((SSL*)session->sess);
575 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
579 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
583 certinfo->unknownsigner = false;
584 certinfo->trusted = true;
588 certinfo->unknownsigner = true;
589 certinfo->trusted = false;
592 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
593 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
595 if (!X509_digest(cert, digest, md, &n))
597 certinfo->error = "Out of memory generating fingerprint";
601 certinfo->fingerprint = irc::hex(md, n);
604 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))
606 certinfo->error = "Not activated, or expired certificate";
613 static int error_callback(const char *str, size_t len, void *u)
615 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
618 // XXX: Remove this line, it causes valgrind warnings...
620 // MD_update(&m, buf, j);
623 // ... ONLY JOKING! :-)
629 MODULE_INIT(ModuleSSLOpenSSL)