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>
32 # pragma comment(lib, "libgnutls.lib")
33 # pragma comment(lib, "libgcrypt.lib")
34 # pragma comment(lib, "libgpg-error.lib")
35 # pragma comment(lib, "user32.lib")
36 # pragma comment(lib, "advapi32.lib")
37 # pragma comment(lib, "libgcc.lib")
38 # pragma comment(lib, "libmingwex.lib")
39 # pragma comment(lib, "gdi32.lib")
42 /* $ModDesc: Provides SSL support for clients */
43 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") -Wno-deprecated-declarations */
44 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") -lgcrypt */
46 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
48 static std::vector<gnutls_x509_crt_t> x509_certs;
49 static gnutls_x509_privkey_t x509_key;
50 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
51 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
53 st->type = GNUTLS_CRT_X509;
54 st->ncerts = x509_certs.size();
55 st->cert.x509 = &x509_certs[0];
56 st->key.x509 = x509_key;
62 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t user_wrap, void* buffer, size_t size)
64 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
65 if (user->GetEventMask() & FD_READ_WILL_BLOCK)
70 int rv = ServerInstance->SE->Recv(user, reinterpret_cast<char *>(buffer), size, 0);
72 ServerInstance->SE->ChangeEventMask(user, FD_READ_WILL_BLOCK);
76 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t user_wrap, const void* buffer, size_t size)
78 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
79 if (user->GetEventMask() & FD_WRITE_WILL_BLOCK)
84 int rv = ServerInstance->SE->Send(user, reinterpret_cast<const char *>(buffer), size, 0);
86 ServerInstance->SE->ChangeEventMask(user, FD_WRITE_WILL_BLOCK);
90 class RandGen : public HandlerBase2<void, char*, size_t>
94 void Call(char* buffer, size_t len)
96 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
100 /** Represents an SSL user's extra data
105 gnutls_session_t sess;
107 reference<ssl_cert> cert;
108 issl_session() : sess(NULL) {}
111 class CommandStartTLS : public SplitCommand
115 CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
118 works_before_reg = true;
121 CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user)
125 user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
129 if (user->registered == REG_ALL)
131 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
135 if (!user->eh.GetIOHook())
137 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
138 /* We need to flush the write buffer prior to adding the IOHook,
139 * otherwise we'll be sending this line inside the SSL session - which
140 * won't start its handshake until the client gets this line. Currently,
141 * we assume the write will not block here; this is usually safe, as
142 * STARTTLS is sent very early on in the registration phase, where the
143 * user hasn't built up much sendq. Handling a blocked write here would
147 user->eh.AddIOHook(creator);
148 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
151 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
158 class ModuleSSLGnuTLS : public Module
160 issl_session* sessions;
162 gnutls_certificate_credentials x509_cred;
163 gnutls_dh_params dh_params;
164 gnutls_digest_algorithm_t hash;
165 gnutls_priority_t priority;
167 std::string sslports;
174 CommandStartTLS starttls;
176 GenericCap capHandler;
177 ServiceProvider iohook;
181 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
183 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
185 gnutls_global_init(); // This must be called once in the program
186 gnutls_x509_privkey_init(&x509_key);
187 // Init this here so it's always initialized, avoids an extra boolean
188 gnutls_priority_init(&priority, "NORMAL", NULL);
196 // Needs the flag as it ignores a plain /rehash
197 OnModuleRehash(NULL,"ssl");
199 ServerInstance->GenRandom = &randhandler;
201 // Void return, guess we assume success
202 gnutls_certificate_set_dh_params(x509_cred, dh_params);
203 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
204 I_OnEvent, I_OnHookIO };
205 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
207 ServerInstance->Modules->AddService(iohook);
208 ServerInstance->AddCommand(&starttls);
211 void OnRehash(User* user)
215 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
216 starttls.enabled = Conf->getBool("starttls", true);
218 if (Conf->getBool("showports", true))
220 sslports = Conf->getString("advertisedports");
221 if (!sslports.empty())
224 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
226 ListenSocket* port = ServerInstance->ports[i];
227 if (port->bind_tag->getString("ssl") != "gnutls")
230 const std::string& portid = port->bind_desc;
231 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
233 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
236 * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
237 * the IP:port in ISUPPORT.
239 * We used to advertise all ports seperated by a ';' char that matched the above criteria,
240 * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
241 * To solve this by default we now only display the first IP:port found and let the user
242 * configure the exact value for the 005 token, if necessary.
251 void OnModuleRehash(User* user, const std::string ¶m)
257 std::string certfile;
262 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
264 cafile = Conf->getString("cafile", "conf/ca.pem");
265 crlfile = Conf->getString("crlfile", "conf/crl.pem");
266 certfile = Conf->getString("certfile", "conf/cert.pem");
267 keyfile = Conf->getString("keyfile", "conf/key.pem");
268 dh_bits = Conf->getInt("dhbits");
269 std::string hashname = Conf->getString("hash", "md5");
271 // The GnuTLS manual states that the gnutls_set_default_priority()
272 // call we used previously when initializing the session is the same
273 // as setting the "NORMAL" priority string.
274 // Thus if the setting below is not in the config we will behave exactly
275 // the same as before, when the priority setting wasn't available.
276 std::string priorities = Conf->getString("priority", "NORMAL");
278 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
281 if (hashname == "md5")
282 hash = GNUTLS_DIG_MD5;
283 else if (hashname == "sha1")
284 hash = GNUTLS_DIG_SHA1;
286 throw ModuleException("Unknown hash type " + hashname);
293 gnutls_dh_params_deinit(dh_params);
299 // Deallocate the old credentials
300 gnutls_certificate_free_credentials(x509_cred);
302 for(unsigned int i=0; i < x509_certs.size(); i++)
303 gnutls_x509_crt_deinit(x509_certs[i]);
307 ret = gnutls_certificate_allocate_credentials(&x509_cred);
308 cred_alloc = (ret >= 0);
310 ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
312 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
313 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));
315 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
316 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));
320 reader.LoadFile(certfile);
321 std::string cert_string = reader.Contents();
322 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), cert_string.length() };
324 reader.LoadFile(keyfile);
325 std::string key_string = reader.Contents();
326 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), key_string.length() };
328 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
329 unsigned int certcount = Conf->getInt("certcount", 3);
330 x509_certs.resize(certcount);
331 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
333 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + std::string(gnutls_strerror(ret)));
334 x509_certs.resize(certcount);
336 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
337 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
339 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
340 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
342 // It's safe to call this every time as we cannot have this uninitialized, see constructor and below.
343 gnutls_priority_deinit(priority);
345 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
346 // If the user did not supply anything then the string is already set to "NORMAL"
347 const char* priocstr = priorities.c_str();
348 const char* prioerror;
350 if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0)
352 // gnutls did not understand the user supplied string, log and fall back to the default priorities
353 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set priorities to \"%s\": %s Syntax error at position %d, falling back to default (NORMAL)", priorities.c_str(), gnutls_strerror(ret), (prioerror - priocstr));
354 gnutls_priority_init(&priority, "NORMAL", NULL);
357 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
359 ret = gnutls_dh_params_init(&dh_params);
360 dh_alloc = (ret >= 0);
362 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
364 // This may be on a large (once a day or week) timer eventually.
368 void GenerateDHParams()
370 // Generate Diffie Hellman parameters - for use with DHE
371 // kx algorithms. These should be discarded and regenerated
372 // once a day, once a week or once a month. Depending on the
373 // security requirements.
380 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
381 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
386 for(unsigned int i=0; i < x509_certs.size(); i++)
387 gnutls_x509_crt_deinit(x509_certs[i]);
389 gnutls_x509_privkey_deinit(x509_key);
390 gnutls_priority_deinit(priority);
393 gnutls_dh_params_deinit(dh_params);
395 gnutls_certificate_free_credentials(x509_cred);
397 gnutls_global_deinit();
399 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
402 void OnCleanup(int target_type, void* item)
404 if(target_type == TYPE_USER)
406 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
408 if (user && user->eh.GetIOHook() == this)
410 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
411 // Potentially there could be multiple SSL modules loaded at once on different ports.
412 ServerInstance->Users->QuitUser(user, "SSL module unloading");
419 return Version("Provides SSL support for clients", VF_VENDOR);
423 void On005Numeric(std::string &output)
425 if (!sslports.empty())
426 output.append(" SSL=" + sslports);
427 if (starttls.enabled)
428 output.append(" STARTTLS");
431 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
433 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
435 /* Hook the user with our module */
436 user->AddIOHook(this);
440 void OnRequest(Request& request)
442 if (strcmp("GET_SSL_CERT", request.id) == 0)
444 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
445 int fd = req.sock->GetFd();
446 issl_session* session = &sessions[fd];
448 req.cert = session->cert;
452 void InitSession(StreamSocket* user, bool me_server)
454 issl_session* session = &sessions[user->GetFd()];
456 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
458 gnutls_priority_set(session->sess, priority);
459 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
460 gnutls_dh_set_prime_bits(session->sess, dh_bits);
461 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
462 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
463 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
466 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
468 Handshake(session, user);
471 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
473 issl_session* session = &sessions[user->GetFd()];
475 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
479 InitSession(user, true);
482 void OnStreamSocketConnect(StreamSocket* user)
484 InitSession(user, false);
487 void OnStreamSocketClose(StreamSocket* user)
489 CloseSession(&sessions[user->GetFd()]);
492 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
494 issl_session* session = &sessions[user->GetFd()];
498 CloseSession(session);
499 user->SetError("No SSL session");
503 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
505 // The handshake isn't finished, try to finish it.
507 if(!Handshake(session, user))
509 if (session->status != ISSL_CLOSING)
515 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
517 if (session->status == ISSL_HANDSHAKEN)
519 char* buffer = ServerInstance->GetReadBuffer();
520 size_t bufsiz = ServerInstance->Config->NetBufferSize;
521 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
524 recvq.append(buffer, ret);
527 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
533 user->SetError("SSL Connection closed");
534 CloseSession(session);
539 user->SetError(gnutls_strerror(ret));
540 CloseSession(session);
544 else if (session->status == ISSL_CLOSING)
550 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
552 issl_session* session = &sessions[user->GetFd()];
556 CloseSession(session);
557 user->SetError("No SSL session");
561 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
563 // The handshake isn't finished, try to finish it.
564 Handshake(session, user);
565 if (session->status != ISSL_CLOSING)
572 if (session->status == ISSL_HANDSHAKEN)
574 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
576 if (ret == (int)sendq.length())
578 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
583 sendq = sendq.substr(ret);
584 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
587 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
589 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
594 user->SetError(gnutls_strerror(ret));
595 CloseSession(session);
603 bool Handshake(issl_session* session, StreamSocket* user)
605 int ret = gnutls_handshake(session->sess);
609 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
611 // Handshake needs resuming later, read() or write() would have blocked.
613 if(gnutls_record_get_direction(session->sess) == 0)
615 // gnutls_handshake() wants to read() again.
616 session->status = ISSL_HANDSHAKING_READ;
617 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
621 // gnutls_handshake() wants to write() again.
622 session->status = ISSL_HANDSHAKING_WRITE;
623 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
628 user->SetError(std::string("Handshake Failed - ") + gnutls_strerror(ret));
629 CloseSession(session);
630 session->status = ISSL_CLOSING;
637 // Change the seesion state
638 session->status = ISSL_HANDSHAKEN;
640 VerifyCertificate(session,user);
642 // Finish writing, if any left
643 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
649 void OnUserConnect(LocalUser* user)
651 if (user->eh.GetIOHook() == this)
653 if (sessions[user->eh.GetFd()].sess)
655 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
656 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->eh.GetFd()].sess));
657 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->eh.GetFd()].sess))).append("-");
658 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->eh.GetFd()].sess)));
659 if (cert->fingerprint.empty())
660 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
662 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
663 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
668 void CloseSession(issl_session* session)
672 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
673 gnutls_deinit(session->sess);
675 session->sess = NULL;
676 session->cert = NULL;
677 session->status = ISSL_NONE;
680 void VerifyCertificate(issl_session* session, StreamSocket* user)
682 if (!session->sess || !user)
686 const gnutls_datum_t* cert_list;
688 unsigned int cert_list_size;
689 gnutls_x509_crt_t cert;
691 unsigned char digest[MAXBUF];
692 size_t digest_size = sizeof(digest);
693 size_t name_size = sizeof(name);
694 ssl_cert* certinfo = new ssl_cert;
695 session->cert = certinfo;
697 /* This verification function uses the trusted CAs in the credentials
698 * structure. So you must have installed one or more CA certificates.
700 ret = gnutls_certificate_verify_peers2(session->sess, &status);
704 certinfo->error = std::string(gnutls_strerror(ret));
708 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
709 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
710 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
711 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
713 /* Up to here the process is the same for X.509 certificates and
714 * OpenPGP keys. From now on X.509 certificates are assumed. This can
715 * be easily extended to work with openpgp keys as well.
717 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
719 certinfo->error = "No X509 keys sent";
723 ret = gnutls_x509_crt_init(&cert);
726 certinfo->error = gnutls_strerror(ret);
731 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
732 if (cert_list == NULL)
734 certinfo->error = "No certificate was found";
735 goto info_done_dealloc;
738 /* This is not a real world example, since we only check the first
739 * certificate in the given chain.
742 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
745 certinfo->error = gnutls_strerror(ret);
746 goto info_done_dealloc;
749 gnutls_x509_crt_get_dn(cert, name, &name_size);
752 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
753 certinfo->issuer = name;
755 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
757 certinfo->error = gnutls_strerror(ret);
761 certinfo->fingerprint = irc::hex(digest, digest_size);
764 /* Beware here we do not check for errors.
766 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
768 certinfo->error = "Not activated, or expired certificate";
772 gnutls_x509_crt_deinit(cert);
775 void OnEvent(Event& ev)
777 if (starttls.enabled)
778 capHandler.HandleEvent(ev);
782 MODULE_INIT(ModuleSSLGnuTLS)