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)
105 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
107 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
108 inbufsize = ServerInstance->Config->NetBufferSize;
110 /* Global SSL library initialization*/
112 SSL_load_error_strings();
114 /* Build our SSL contexts:
115 * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
117 ctx = SSL_CTX_new( SSLv23_server_method() );
118 clictx = SSL_CTX_new( SSLv23_client_method() );
120 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
121 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
123 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
124 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
126 // Needs the flag as it ignores a plain /rehash
127 OnModuleRehash(NULL,"ssl");
128 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO, I_OnUserConnect };
129 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
130 ServerInstance->Modules->AddService(iohook);
133 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
135 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
137 /* Hook the user with our module */
138 user->AddIOHook(this);
142 void OnRehash(User* user)
148 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
150 ListenSocket* port = ServerInstance->ports[i];
151 if (port->bind_tag->getString("ssl") != "openssl")
154 std::string portid = port->bind_desc;
155 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
156 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
157 sslports.append(portid).append(";");
160 if (!sslports.empty())
161 sslports.erase(sslports.end() - 1);
164 void OnModuleRehash(User* user, const std::string ¶m)
173 cafile = Conf.ReadValue("openssl", "cafile", 0);
174 certfile = Conf.ReadValue("openssl", "certfile", 0);
175 keyfile = Conf.ReadValue("openssl", "keyfile", 0);
176 dhfile = Conf.ReadValue("openssl", "dhfile", 0);
178 // Set all the default values needed.
180 cafile = "conf/ca.pem";
182 if (certfile.empty())
183 certfile = "conf/cert.pem";
186 keyfile = "conf/key.pem";
189 dhfile = "conf/dhparams.pem";
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->GetFd()].sess)
253 SSLCertSubmission(user, this, ServerInstance->Modules->Find("m_sslinfo.so"), sessions[user->GetFd()].cert);
258 void OnCleanup(int target_type, void* item)
260 if (target_type == TYPE_USER)
262 LocalUser* user = IS_LOCAL((User*)item);
264 if (user && user->eh.GetIOHook() == this)
266 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
267 // Potentially there could be multiple SSL modules loaded at once on different ports.
268 ServerInstance->Users->QuitUser(user, "SSL module unloading");
275 return Version("Provides SSL support for clients", VF_VENDOR);
278 void OnRequest(Request& request)
280 if (strcmp("GET_SSL_CERT", request.id) == 0)
282 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
283 int fd = req.sock->GetFd();
284 issl_session* session = &sessions[fd];
286 req.cert = session->cert;
290 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
292 int fd = user->GetFd();
294 issl_session* session = &sessions[fd];
297 session->sess = SSL_new(ctx);
298 session->status = ISSL_NONE;
299 session->outbound = false;
301 if (session->sess == NULL)
304 if (SSL_set_fd(session->sess, fd) == 0)
306 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
310 Handshake(user, session);
313 void OnStreamSocketConnect(StreamSocket* user)
315 int fd = user->GetFd();
316 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
317 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
320 issl_session* session = &sessions[fd];
323 session->sess = SSL_new(clictx);
324 session->status = ISSL_NONE;
325 session->outbound = true;
327 if (session->sess == NULL)
330 if (SSL_set_fd(session->sess, fd) == 0)
332 ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
336 Handshake(user, session);
339 void OnStreamSocketClose(StreamSocket* user)
341 int fd = user->GetFd();
342 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
343 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
346 CloseSession(&sessions[fd]);
349 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
351 int fd = user->GetFd();
352 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
353 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
356 issl_session* session = &sessions[fd];
360 CloseSession(session);
364 if (session->status == ISSL_HANDSHAKING)
366 // The handshake isn't finished and it wants to read, try to finish it.
367 if (!Handshake(user, session))
369 // Couldn't resume handshake.
370 if (session->status == ISSL_NONE)
376 // If we resumed the handshake then session->status will be ISSL_OPEN
378 if (session->status == ISSL_OPEN)
380 char* buffer = ServerInstance->GetReadBuffer();
381 size_t bufsiz = ServerInstance->Config->NetBufferSize;
382 int ret = SSL_read(session->sess, buffer, bufsiz);
386 recvq.append(buffer, ret);
391 // Client closed connection.
392 CloseSession(session);
397 int err = SSL_get_error(session->sess, ret);
399 if (err == SSL_ERROR_WANT_READ)
401 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
404 else if (err == SSL_ERROR_WANT_WRITE)
406 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
411 CloseSession(session);
420 int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
422 int fd = user->GetFd();
424 issl_session* session = &sessions[fd];
428 CloseSession(session);
432 session->data_to_write = true;
434 if (session->status == ISSL_HANDSHAKING)
436 if (!Handshake(user, session))
438 // Couldn't resume handshake.
439 if (session->status == ISSL_NONE)
445 if (session->status == ISSL_OPEN)
447 int ret = SSL_write(session->sess, buffer.data(), buffer.size());
448 if (ret == (int)buffer.length())
450 session->data_to_write = false;
451 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
456 buffer = buffer.substr(ret);
457 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
462 CloseSession(session);
467 int err = SSL_get_error(session->sess, ret);
469 if (err == SSL_ERROR_WANT_WRITE)
471 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
474 else if (err == SSL_ERROR_WANT_READ)
476 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
481 CloseSession(session);
489 bool Handshake(StreamSocket* user, issl_session* session)
493 if (session->outbound)
494 ret = SSL_connect(session->sess);
496 ret = SSL_accept(session->sess);
500 int err = SSL_get_error(session->sess, ret);
502 if (err == SSL_ERROR_WANT_READ)
504 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
505 session->status = ISSL_HANDSHAKING;
508 else if (err == SSL_ERROR_WANT_WRITE)
510 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
511 session->status = ISSL_HANDSHAKING;
516 CloseSession(session);
523 // Handshake complete.
524 VerifyCertificate(session, user);
526 session->status = ISSL_OPEN;
528 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
534 CloseSession(session);
541 void CloseSession(issl_session* session)
545 SSL_shutdown(session->sess);
546 SSL_free(session->sess);
549 session->sess = NULL;
550 session->status = ISSL_NONE;
554 void VerifyCertificate(issl_session* session, StreamSocket* user)
556 if (!session->sess || !user || session->cert)
560 ssl_cert* certinfo = new ssl_cert;
561 session->cert = certinfo;
563 unsigned char md[EVP_MAX_MD_SIZE];
564 const EVP_MD *digest = EVP_md5();
566 cert = SSL_get_peer_certificate((SSL*)session->sess);
570 certinfo->error = "Could not get peer certificate: "+std::string(get_error());
574 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
578 certinfo->unknownsigner = false;
579 certinfo->trusted = true;
583 certinfo->unknownsigner = true;
584 certinfo->trusted = false;
587 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
588 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
590 if (!X509_digest(cert, digest, md, &n))
592 certinfo->error = "Out of memory generating fingerprint";
596 certinfo->fingerprint = irc::hex(md, n);
599 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))
601 certinfo->error = "Not activated, or expired certificate";
608 static int error_callback(const char *str, size_t len, void *u)
610 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
613 // XXX: Remove this line, it causes valgrind warnings...
615 // MD_update(&m, buf, j);
618 // ... ONLY JOKING! :-)
624 MODULE_INIT(ModuleSSLOpenSSL)