2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2008 John Brooks <john.brooks@dereferenced.net>
6 * Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
8 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
10 * This file is part of InspIRCd. InspIRCd is free software: you can
11 * redistribute it and/or modify it under the terms of the GNU General Public
12 * License as published by the Free Software Foundation, version 2.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include <gnutls/gnutls.h>
26 #include <gnutls/x509.h>
31 /* $ModDesc: Provides SSL support for clients */
32 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") */
33 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") -lgcrypt */
35 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
37 static std::vector<gnutls_x509_crt_t> x509_certs;
38 static gnutls_x509_privkey_t x509_key;
39 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
40 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
42 st->type = GNUTLS_CRT_X509;
43 st->ncerts = x509_certs.size();
44 st->cert.x509 = &x509_certs[0];
45 st->key.x509 = x509_key;
51 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t user_wrap, void* buffer, size_t size)
53 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
54 if (user->GetEventMask() & FD_READ_WILL_BLOCK)
59 int rv = recv(user->GetFd(), reinterpret_cast<char *>(buffer), size, 0);
61 ServerInstance->SE->ChangeEventMask(user, FD_READ_WILL_BLOCK);
65 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t user_wrap, const void* buffer, size_t size)
67 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
68 if (user->GetEventMask() & FD_WRITE_WILL_BLOCK)
73 int rv = send(user->GetFd(), reinterpret_cast<const char *>(buffer), size, 0);
75 ServerInstance->SE->ChangeEventMask(user, FD_WRITE_WILL_BLOCK);
79 class RandGen : public HandlerBase2<void, char*, size_t>
83 void Call(char* buffer, size_t len)
85 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
89 /** Represents an SSL user's extra data
94 gnutls_session_t sess;
96 reference<ssl_cert> cert;
97 issl_session() : sess(NULL) {}
100 class CommandStartTLS : public SplitCommand
104 CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
107 works_before_reg = true;
110 CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user)
114 user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
118 if (user->registered == REG_ALL)
120 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
124 if (!user->eh.GetIOHook())
126 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
127 /* We need to flush the write buffer prior to adding the IOHook,
128 * otherwise we'll be sending this line inside the SSL session - which
129 * won't start its handshake until the client gets this line. Currently,
130 * we assume the write will not block here; this is usually safe, as
131 * STARTTLS is sent very early on in the registration phase, where the
132 * user hasn't built up much sendq. Handling a blocked write here would
136 user->eh.AddIOHook(creator);
137 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
140 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
147 class ModuleSSLGnuTLS : public Module
149 issl_session* sessions;
151 gnutls_certificate_credentials x509_cred;
152 gnutls_dh_params dh_params;
153 gnutls_digest_algorithm_t hash;
155 std::string sslports;
161 CommandStartTLS starttls;
163 GenericCap capHandler;
164 ServiceProvider iohook;
168 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
170 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
172 gnutls_global_init(); // This must be called once in the program
173 gnutls_x509_privkey_init(&x509_key);
180 // Needs the flag as it ignores a plain /rehash
181 OnModuleRehash(NULL,"ssl");
183 ServerInstance->GenRandom = &randhandler;
185 // Void return, guess we assume success
186 gnutls_certificate_set_dh_params(x509_cred, dh_params);
187 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
188 I_OnEvent, I_OnHookIO };
189 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
191 ServerInstance->Modules->AddService(iohook);
192 ServerInstance->AddCommand(&starttls);
195 void OnRehash(User* user)
199 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
200 starttls.enabled = Conf->getBool("starttls", true);
202 if (Conf->getBool("showports", true))
204 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
206 ListenSocket* port = ServerInstance->ports[i];
207 if (port->bind_tag->getString("ssl") != "gnutls")
210 const std::string& portid = port->bind_desc;
211 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
213 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
214 sslports.append(portid).append(";");
217 if (!sslports.empty())
218 sslports.erase(sslports.end() - 1);
222 void OnModuleRehash(User* user, const std::string ¶m)
228 std::string certfile;
233 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
235 cafile = Conf->getString("cafile", "conf/ca.pem");
236 crlfile = Conf->getString("crlfile", "conf/crl.pem");
237 certfile = Conf->getString("certfile", "conf/cert.pem");
238 keyfile = Conf->getString("keyfile", "conf/key.pem");
239 dh_bits = Conf->getInt("dhbits");
240 std::string hashname = Conf->getString("hash", "md5");
242 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
245 if (hashname == "md5")
246 hash = GNUTLS_DIG_MD5;
247 else if (hashname == "sha1")
248 hash = GNUTLS_DIG_SHA1;
250 throw ModuleException("Unknown hash type " + hashname);
257 // Deallocate the old credentials
258 gnutls_dh_params_deinit(dh_params);
259 gnutls_certificate_free_credentials(x509_cred);
261 for(unsigned int i=0; i < x509_certs.size(); i++)
262 gnutls_x509_crt_deinit(x509_certs[i]);
268 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
269 ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
271 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
272 ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to set X.509 trust file '%s': %s", cafile.c_str(), gnutls_strerror(ret));
274 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
275 ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret));
279 reader.LoadFile(certfile);
280 std::string cert_string = reader.Contents();
281 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), cert_string.length() };
283 reader.LoadFile(keyfile);
284 std::string key_string = reader.Contents();
285 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), key_string.length() };
287 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
288 unsigned int certcount = Conf->getInt("certcount", 3);
289 x509_certs.resize(certcount);
290 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
292 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + std::string(gnutls_strerror(ret)));
293 x509_certs.resize(certcount);
295 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
296 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
298 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
299 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
301 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
303 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
304 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
306 // This may be on a large (once a day or week) timer eventually.
310 void GenerateDHParams()
312 // Generate Diffie Hellman parameters - for use with DHE
313 // kx algorithms. These should be discarded and regenerated
314 // once a day, once a week or once a month. Depending on the
315 // security requirements.
319 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
320 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
325 for(unsigned int i=0; i < x509_certs.size(); i++)
326 gnutls_x509_crt_deinit(x509_certs[i]);
328 gnutls_x509_privkey_deinit(x509_key);
331 gnutls_dh_params_deinit(dh_params);
332 gnutls_certificate_free_credentials(x509_cred);
334 gnutls_global_deinit();
336 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
339 void OnCleanup(int target_type, void* item)
341 if(target_type == TYPE_USER)
343 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
345 if (user && user->eh.GetIOHook() == this)
347 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
348 // Potentially there could be multiple SSL modules loaded at once on different ports.
349 ServerInstance->Users->QuitUser(user, "SSL module unloading");
356 return Version("Provides SSL support for clients", VF_VENDOR);
360 void On005Numeric(std::string &output)
362 if (!sslports.empty())
363 output.append(" SSL=" + sslports);
364 if (starttls.enabled)
365 output.append(" STARTTLS");
368 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
370 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
372 /* Hook the user with our module */
373 user->AddIOHook(this);
377 void OnRequest(Request& request)
379 if (strcmp("GET_SSL_CERT", request.id) == 0)
381 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
382 int fd = req.sock->GetFd();
383 issl_session* session = &sessions[fd];
385 req.cert = session->cert;
389 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
391 int fd = user->GetFd();
392 issl_session* session = &sessions[fd];
394 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
398 gnutls_init(&session->sess, GNUTLS_SERVER);
400 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
401 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
402 gnutls_dh_set_prime_bits(session->sess, dh_bits);
404 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
405 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
406 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
408 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
410 Handshake(session, user);
413 void OnStreamSocketConnect(StreamSocket* user)
415 issl_session* session = &sessions[user->GetFd()];
417 gnutls_init(&session->sess, GNUTLS_CLIENT);
419 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
420 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
421 gnutls_dh_set_prime_bits(session->sess, dh_bits);
422 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
423 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
424 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
426 Handshake(session, user);
429 void OnStreamSocketClose(StreamSocket* user)
431 CloseSession(&sessions[user->GetFd()]);
434 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
436 issl_session* session = &sessions[user->GetFd()];
440 CloseSession(session);
441 user->SetError("No SSL session");
445 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
447 // The handshake isn't finished, try to finish it.
449 if(!Handshake(session, user))
451 if (session->status != ISSL_CLOSING)
457 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
459 if (session->status == ISSL_HANDSHAKEN)
461 char* buffer = ServerInstance->GetReadBuffer();
462 size_t bufsiz = ServerInstance->Config->NetBufferSize;
463 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
466 recvq.append(buffer, ret);
469 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
475 user->SetError("SSL Connection closed");
476 CloseSession(session);
481 user->SetError(gnutls_strerror(ret));
482 CloseSession(session);
486 else if (session->status == ISSL_CLOSING)
492 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
494 issl_session* session = &sessions[user->GetFd()];
498 CloseSession(session);
499 user->SetError("No SSL session");
503 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
505 // The handshake isn't finished, try to finish it.
506 Handshake(session, user);
507 if (session->status != ISSL_CLOSING)
514 if (session->status == ISSL_HANDSHAKEN)
516 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
518 if (ret == (int)sendq.length())
520 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
525 sendq = sendq.substr(ret);
526 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
529 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
531 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
536 user->SetError(gnutls_strerror(ret));
537 CloseSession(session);
545 bool Handshake(issl_session* session, StreamSocket* user)
547 int ret = gnutls_handshake(session->sess);
551 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
553 // Handshake needs resuming later, read() or write() would have blocked.
555 if(gnutls_record_get_direction(session->sess) == 0)
557 // gnutls_handshake() wants to read() again.
558 session->status = ISSL_HANDSHAKING_READ;
559 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
563 // gnutls_handshake() wants to write() again.
564 session->status = ISSL_HANDSHAKING_WRITE;
565 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
570 user->SetError(std::string("Handshake Failed - ") + gnutls_strerror(ret));
571 CloseSession(session);
572 session->status = ISSL_CLOSING;
579 // Change the seesion state
580 session->status = ISSL_HANDSHAKEN;
582 VerifyCertificate(session,user);
584 // Finish writing, if any left
585 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
591 void OnUserConnect(LocalUser* user)
593 if (user->eh.GetIOHook() == this)
595 if (sessions[user->eh.GetFd()].sess)
597 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
598 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->eh.GetFd()].sess));
599 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->eh.GetFd()].sess))).append("-");
600 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->eh.GetFd()].sess)));
601 if (cert->fingerprint.empty())
602 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
604 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
605 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
610 void CloseSession(issl_session* session)
614 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
615 gnutls_deinit(session->sess);
617 session->sess = NULL;
618 session->cert = NULL;
619 session->status = ISSL_NONE;
622 void VerifyCertificate(issl_session* session, StreamSocket* user)
624 if (!session->sess || !user)
628 const gnutls_datum_t* cert_list;
630 unsigned int cert_list_size;
631 gnutls_x509_crt_t cert;
633 unsigned char digest[MAXBUF];
634 size_t digest_size = sizeof(digest);
635 size_t name_size = sizeof(name);
636 ssl_cert* certinfo = new ssl_cert;
637 session->cert = certinfo;
639 /* This verification function uses the trusted CAs in the credentials
640 * structure. So you must have installed one or more CA certificates.
642 ret = gnutls_certificate_verify_peers2(session->sess, &status);
646 certinfo->error = std::string(gnutls_strerror(ret));
650 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
651 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
652 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
653 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
655 /* Up to here the process is the same for X.509 certificates and
656 * OpenPGP keys. From now on X.509 certificates are assumed. This can
657 * be easily extended to work with openpgp keys as well.
659 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
661 certinfo->error = "No X509 keys sent";
665 ret = gnutls_x509_crt_init(&cert);
668 certinfo->error = gnutls_strerror(ret);
673 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
674 if (cert_list == NULL)
676 certinfo->error = "No certificate was found";
677 goto info_done_dealloc;
680 /* This is not a real world example, since we only check the first
681 * certificate in the given chain.
684 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
687 certinfo->error = gnutls_strerror(ret);
688 goto info_done_dealloc;
691 gnutls_x509_crt_get_dn(cert, name, &name_size);
694 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
695 certinfo->issuer = name;
697 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
699 certinfo->error = gnutls_strerror(ret);
703 certinfo->fingerprint = irc::hex(digest, digest_size);
706 /* Beware here we do not check for errors.
708 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
710 certinfo->error = "Not activated, or expired certificate";
714 gnutls_x509_crt_deinit(cert);
717 void OnEvent(Event& ev)
719 if (starttls.enabled)
720 capHandler.HandleEvent(ev);
724 MODULE_INIT(ModuleSSLGnuTLS)