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/>.
28 #include <gnutls/gnutls.h>
29 #include <gnutls/x509.h>
34 # pragma comment(lib, "libgnutls-28.lib")
37 /* $ModDesc: Provides SSL support for clients */
38 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") exec("libgcrypt-config --cflags") */
39 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") exec("libgcrypt-config --libs") */
42 #ifndef GNUTLS_VERSION_MAJOR
43 #define GNUTLS_VERSION_MAJOR LIBGNUTLS_VERSION_MAJOR
44 #define GNUTLS_VERSION_MINOR LIBGNUTLS_VERSION_MINOR
45 #define GNUTLS_VERSION_PATCH LIBGNUTLS_VERSION_PATCH
48 // These don't exist in older GnuTLS versions
49 #if ((GNUTLS_VERSION_MAJOR > 2) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR > 1) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR == 1 && GNUTLS_VERSION_PATCH >= 7))
50 #define GNUTLS_NEW_PRIO_API
53 #if(GNUTLS_VERSION_MAJOR < 2)
54 typedef gnutls_certificate_credentials_t gnutls_certificate_credentials;
55 typedef gnutls_dh_params_t gnutls_dh_params;
58 #if (defined(_WIN32) && (GNUTLS_VERSION_MAJOR > 2 || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR >= 12)))
59 # define GNUTLS_HAS_RND
60 # include <gnutls/crypto.h>
65 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
67 struct SSLConfig : public refcountbase
69 gnutls_certificate_credentials_t x509_cred;
70 std::vector<gnutls_x509_crt_t> x509_certs;
71 gnutls_x509_privkey_t x509_key;
72 gnutls_dh_params_t dh_params;
73 #ifdef GNUTLS_NEW_PRIO_API
74 gnutls_priority_t priority;
81 #ifdef GNUTLS_NEW_PRIO_API
89 ServerInstance->Logs->Log("m_ssl_gnutls", DEBUG, "Destroying SSLConfig %p", (void*)this);
92 gnutls_certificate_free_credentials(x509_cred);
94 for (unsigned int i = 0; i < x509_certs.size(); i++)
95 gnutls_x509_crt_deinit(x509_certs[i]);
98 gnutls_x509_privkey_deinit(x509_key);
101 gnutls_dh_params_deinit(dh_params);
103 #ifdef GNUTLS_NEW_PRIO_API
105 gnutls_priority_deinit(priority);
110 static reference<SSLConfig> currconf;
112 static SSLConfig* GetSessionConfig(gnutls_session_t session);
114 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
115 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
116 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
118 st->type = GNUTLS_CRT_X509;
120 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
121 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr2_st * st) {
122 st->cert_type = GNUTLS_CRT_X509;
123 st->key_type = GNUTLS_PRIVKEY_X509;
125 SSLConfig* conf = GetSessionConfig(session);
126 std::vector<gnutls_x509_crt_t>& x509_certs = conf->x509_certs;
127 st->ncerts = x509_certs.size();
128 st->cert.x509 = &x509_certs[0];
129 st->key.x509 = conf->x509_key;
135 class RandGen : public HandlerBase2<void, char*, size_t>
139 void Call(char* buffer, size_t len)
141 #ifdef GNUTLS_HAS_RND
142 gnutls_rnd(GNUTLS_RND_RANDOM, buffer, len);
144 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
149 /** Represents an SSL user's extra data
154 StreamSocket* socket;
155 gnutls_session_t sess;
157 reference<ssl_cert> cert;
158 reference<SSLConfig> config;
160 issl_session() : socket(NULL), sess(NULL) {}
163 static SSLConfig* GetSessionConfig(gnutls_session_t sess)
165 issl_session* session = reinterpret_cast<issl_session*>(gnutls_transport_get_ptr(sess));
166 return session->config;
169 class CommandStartTLS : public SplitCommand
173 CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
176 works_before_reg = true;
179 CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user)
183 user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
187 if (user->registered == REG_ALL)
189 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
193 if (!user->eh.GetIOHook())
195 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
196 /* We need to flush the write buffer prior to adding the IOHook,
197 * otherwise we'll be sending this line inside the SSL session - which
198 * won't start its handshake until the client gets this line. Currently,
199 * we assume the write will not block here; this is usually safe, as
200 * STARTTLS is sent very early on in the registration phase, where the
201 * user hasn't built up much sendq. Handling a blocked write here would
205 user->eh.AddIOHook(creator);
206 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
209 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
216 class ModuleSSLGnuTLS : public Module
218 issl_session* sessions;
220 gnutls_digest_algorithm_t hash;
222 std::string sslports;
226 CommandStartTLS starttls;
228 GenericCap capHandler;
229 ServiceProvider iohook;
231 inline static const char* UnknownIfNULL(const char* str)
233 return str ? str : "UNKNOWN";
236 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
238 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
239 if (session->socket->GetEventMask() & FD_READ_WILL_BLOCK)
242 gnutls_transport_set_errno(session->sess, EAGAIN);
249 int rv = ServerInstance->SE->Recv(session->socket, reinterpret_cast<char *>(buffer), size, 0);
254 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
255 * and then set errno appropriately.
256 * The gnutls library may also have a different errno variable than us, see
257 * gnutls_transport_set_errno(3).
259 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
264 ServerInstance->SE->ChangeEventMask(session->socket, FD_READ_WILL_BLOCK);
268 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
270 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
271 if (session->socket->GetEventMask() & FD_WRITE_WILL_BLOCK)
274 gnutls_transport_set_errno(session->sess, EAGAIN);
281 int rv = ServerInstance->SE->Send(session->socket, reinterpret_cast<const char *>(buffer), size, 0);
286 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
287 * and then set errno appropriately.
288 * The gnutls library may also have a different errno variable than us, see
289 * gnutls_transport_set_errno(3).
291 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
296 ServerInstance->SE->ChangeEventMask(session->socket, FD_WRITE_WILL_BLOCK);
303 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
305 #ifndef GNUTLS_HAS_RND
306 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
309 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
311 gnutls_global_init(); // This must be called once in the program
316 currconf = new SSLConfig;
317 InitSSLConfig(currconf);
319 ServerInstance->GenRandom = &randhandler;
321 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
322 I_OnEvent, I_OnHookIO };
323 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
325 ServerInstance->Modules->AddService(iohook);
326 ServerInstance->Modules->AddService(starttls);
329 void OnRehash(User* user)
333 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
334 starttls.enabled = Conf->getBool("starttls", true);
336 if (Conf->getBool("showports", true))
338 sslports = Conf->getString("advertisedports");
339 if (!sslports.empty())
342 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
344 ListenSocket* port = ServerInstance->ports[i];
345 if (port->bind_tag->getString("ssl") != "gnutls")
348 const std::string& portid = port->bind_desc;
349 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
351 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
354 * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
355 * the IP:port in ISUPPORT.
357 * We used to advertise all ports seperated by a ';' char that matched the above criteria,
358 * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
359 * To solve this by default we now only display the first IP:port found and let the user
360 * configure the exact value for the 005 token, if necessary.
369 void OnModuleRehash(User* user, const std::string ¶m)
374 reference<SSLConfig> newconf = new SSLConfig;
377 InitSSLConfig(newconf);
379 catch (ModuleException& ex)
381 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls: Not applying new config. %s", ex.GetReason());
385 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls: Applying new config, old config is in use by %d connection(s)", currconf->GetReferenceCount()-1);
389 void InitSSLConfig(SSLConfig* config)
391 ServerInstance->Logs->Log("m_ssl_gnutls", DEBUG, "Initializing new SSLConfig %p", (void*)config);
394 std::string certfile;
399 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
401 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
402 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
403 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
404 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
405 dh_bits = Conf->getInt("dhbits");
406 std::string hashname = Conf->getString("hash", "md5");
408 // The GnuTLS manual states that the gnutls_set_default_priority()
409 // call we used previously when initializing the session is the same
410 // as setting the "NORMAL" priority string.
411 // Thus if the setting below is not in the config we will behave exactly
412 // the same as before, when the priority setting wasn't available.
413 std::string priorities = Conf->getString("priority", "NORMAL");
415 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
418 if (hashname == "md5")
419 hash = GNUTLS_DIG_MD5;
420 else if (hashname == "sha1")
421 hash = GNUTLS_DIG_SHA1;
423 throw ModuleException("Unknown hash type " + hashname);
428 gnutls_certificate_credentials_t& x509_cred = config->x509_cred;
430 ret = gnutls_certificate_allocate_credentials(&x509_cred);
433 // Set to NULL because we can't be sure what value is in it and we must not try to
434 // deallocate it in case of an error
436 throw ModuleException("Failed to allocate certificate credentials: " + std::string(gnutls_strerror(ret)));
439 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
440 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));
442 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
443 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));
447 reader.LoadFile(certfile);
448 std::string cert_string = reader.Contents();
449 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
451 reader.LoadFile(keyfile);
452 std::string key_string = reader.Contents();
453 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
455 std::vector<gnutls_x509_crt_t>& x509_certs = config->x509_certs;
457 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
458 unsigned int certcount = 3;
459 x509_certs.resize(certcount);
460 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
461 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
463 // the buffer wasn't big enough to hold all certs but gnutls updated certcount to the number of available certs, try again with a bigger buffer
464 x509_certs.resize(certcount);
465 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
470 // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later
472 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read"));
474 x509_certs.resize(ret);
476 gnutls_x509_privkey_t& x509_key = config->x509_key;
477 if (gnutls_x509_privkey_init(&x509_key) < 0)
479 // Make sure the destructor does not try to deallocate this, see above
481 throw ModuleException("Unable to initialize private key");
484 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
485 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
487 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
488 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
490 #ifdef GNUTLS_NEW_PRIO_API
491 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
492 // If the user did not supply anything then the string is already set to "NORMAL"
493 const char* priocstr = priorities.c_str();
494 const char* prioerror;
496 gnutls_priority_t& priority = config->priority;
497 if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0)
499 // gnutls did not understand the user supplied string, log and fall back to the default priorities
500 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set priorities to \"%s\": %s Syntax error at position %u, falling back to default (NORMAL)", priorities.c_str(), gnutls_strerror(ret), (unsigned int) (prioerror - priocstr));
501 gnutls_priority_init(&priority, "NORMAL", NULL);
505 if (priorities != "NORMAL")
506 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: You've set <gnutls:priority> to a value other than the default, but this is only supported with GnuTLS v2.1.7 or newer. Your GnuTLS version is older than that so the option will have no effect.");
509 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
510 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
512 gnutls_certificate_set_retrieve_function (x509_cred, cert_callback);
515 gnutls_dh_params_t& dh_params = config->dh_params;
516 ret = gnutls_dh_params_init(&dh_params);
519 // Make sure the destructor does not try to deallocate this, see above
521 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
525 std::string dhfile = Conf->getString("dhfile");
528 // Try to load DH params from file
529 reader.LoadFile(dhfile);
530 std::string dhstring = reader.Contents();
531 gnutls_datum_t dh_datum = { (unsigned char*)dhstring.data(), static_cast<unsigned int>(dhstring.length()) };
533 if ((ret = gnutls_dh_params_import_pkcs3(dh_params, &dh_datum, GNUTLS_X509_FMT_PEM)) < 0)
535 // File unreadable or GnuTLS was unhappy with the contents, generate the DH primes now
536 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Generating DH parameters because I failed to load them from file '%s': %s", dhfile.c_str(), gnutls_strerror(ret));
537 GenerateDHParams(dh_params);
542 GenerateDHParams(dh_params);
545 gnutls_certificate_set_dh_params(x509_cred, dh_params);
548 void GenerateDHParams(gnutls_dh_params_t dh_params)
550 // Generate Diffie Hellman parameters - for use with DHE
551 // kx algorithms. These should be discarded and regenerated
552 // once a day, once a week or once a month. Depending on the
553 // security requirements.
557 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
558 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
565 gnutls_global_deinit();
567 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
570 void OnCleanup(int target_type, void* item)
572 if(target_type == TYPE_USER)
574 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
576 if (user && user->eh.GetIOHook() == this)
578 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
579 // Potentially there could be multiple SSL modules loaded at once on different ports.
580 ServerInstance->Users->QuitUser(user, "SSL module unloading");
587 return Version("Provides SSL support for clients", VF_VENDOR);
591 void On005Numeric(std::string &output)
593 if (!sslports.empty())
594 output.append(" SSL=" + sslports);
595 if (starttls.enabled)
596 output.append(" STARTTLS");
599 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
601 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
603 /* Hook the user with our module */
604 user->AddIOHook(this);
608 void OnRequest(Request& request)
610 if (strcmp("GET_SSL_CERT", request.id) == 0)
612 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
613 int fd = req.sock->GetFd();
614 issl_session* session = &sessions[fd];
616 req.cert = session->cert;
618 else if (!strcmp("GET_RAW_SSL_SESSION", request.id))
620 SSLRawSessionRequest& req = static_cast<SSLRawSessionRequest&>(request);
621 if ((req.fd >= 0) && (req.fd < ServerInstance->SE->GetMaxFds()))
622 req.data = reinterpret_cast<void*>(sessions[req.fd].sess);
626 void InitSession(StreamSocket* user, bool me_server)
628 issl_session* session = &sessions[user->GetFd()];
630 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
631 session->socket = user;
632 session->config = currconf;
634 #ifdef GNUTLS_NEW_PRIO_API
635 gnutls_priority_set(session->sess, currconf->priority);
637 gnutls_set_default_priority(session->sess);
639 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, currconf->x509_cred);
640 gnutls_dh_set_prime_bits(session->sess, dh_bits);
641 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(session));
642 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
643 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
646 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
648 Handshake(session, user);
651 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
653 issl_session* session = &sessions[user->GetFd()];
655 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
659 InitSession(user, true);
662 void OnStreamSocketConnect(StreamSocket* user)
664 InitSession(user, false);
667 void OnStreamSocketClose(StreamSocket* user)
669 CloseSession(&sessions[user->GetFd()]);
672 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
674 issl_session* session = &sessions[user->GetFd()];
678 CloseSession(session);
679 user->SetError("No SSL session");
683 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
685 // The handshake isn't finished, try to finish it.
687 if(!Handshake(session, user))
689 if (session->status != ISSL_CLOSING)
695 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
697 if (session->status == ISSL_HANDSHAKEN)
699 char* buffer = ServerInstance->GetReadBuffer();
700 size_t bufsiz = ServerInstance->Config->NetBufferSize;
701 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
704 recvq.append(buffer, ret);
707 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
713 user->SetError("Connection closed");
714 CloseSession(session);
719 user->SetError(gnutls_strerror(ret));
720 CloseSession(session);
724 else if (session->status == ISSL_CLOSING)
730 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
732 issl_session* session = &sessions[user->GetFd()];
736 CloseSession(session);
737 user->SetError("No SSL session");
741 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
743 // The handshake isn't finished, try to finish it.
744 Handshake(session, user);
745 if (session->status != ISSL_CLOSING)
752 if (session->status == ISSL_HANDSHAKEN)
754 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
756 if (ret == (int)sendq.length())
758 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
763 sendq = sendq.substr(ret);
764 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
767 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
769 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
774 user->SetError(gnutls_strerror(ret));
775 CloseSession(session);
783 bool Handshake(issl_session* session, StreamSocket* user)
785 int ret = gnutls_handshake(session->sess);
789 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
791 // Handshake needs resuming later, read() or write() would have blocked.
793 if(gnutls_record_get_direction(session->sess) == 0)
795 // gnutls_handshake() wants to read() again.
796 session->status = ISSL_HANDSHAKING_READ;
797 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
801 // gnutls_handshake() wants to write() again.
802 session->status = ISSL_HANDSHAKING_WRITE;
803 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
808 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
809 CloseSession(session);
810 session->status = ISSL_CLOSING;
817 // Change the seesion state
818 session->status = ISSL_HANDSHAKEN;
820 VerifyCertificate(session,user);
822 // Finish writing, if any left
823 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
829 void OnUserConnect(LocalUser* user)
831 if (user->eh.GetIOHook() == this)
833 if (sessions[user->eh.GetFd()].sess)
835 const gnutls_session_t& sess = sessions[user->eh.GetFd()].sess;
836 std::string cipher = UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)));
837 cipher.append("-").append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).append("-");
838 cipher.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
840 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
841 if (cert->fingerprint.empty())
842 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
844 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
845 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
850 void CloseSession(issl_session* session)
854 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
855 gnutls_deinit(session->sess);
857 session->socket = NULL;
858 session->sess = NULL;
859 session->cert = NULL;
860 session->status = ISSL_NONE;
861 session->config = NULL;
864 void VerifyCertificate(issl_session* session, StreamSocket* user)
866 if (!session->sess || !user)
870 const gnutls_datum_t* cert_list;
872 unsigned int cert_list_size;
873 gnutls_x509_crt_t cert;
875 unsigned char digest[MAXBUF];
876 size_t digest_size = sizeof(digest);
877 size_t name_size = sizeof(name);
878 ssl_cert* certinfo = new ssl_cert;
879 session->cert = certinfo;
881 /* This verification function uses the trusted CAs in the credentials
882 * structure. So you must have installed one or more CA certificates.
884 ret = gnutls_certificate_verify_peers2(session->sess, &status);
888 certinfo->error = std::string(gnutls_strerror(ret));
892 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
893 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
894 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
895 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
897 /* Up to here the process is the same for X.509 certificates and
898 * OpenPGP keys. From now on X.509 certificates are assumed. This can
899 * be easily extended to work with openpgp keys as well.
901 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
903 certinfo->error = "No X509 keys sent";
907 ret = gnutls_x509_crt_init(&cert);
910 certinfo->error = gnutls_strerror(ret);
915 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
916 if (cert_list == NULL)
918 certinfo->error = "No certificate was found";
919 goto info_done_dealloc;
922 /* This is not a real world example, since we only check the first
923 * certificate in the given chain.
926 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
929 certinfo->error = gnutls_strerror(ret);
930 goto info_done_dealloc;
933 if (gnutls_x509_crt_get_dn(cert, name, &name_size) == 0)
935 std::string& dn = certinfo->dn;
937 // Make sure there are no chars in the string that we consider invalid
938 if (dn.find_first_of("\r\n") != std::string::npos)
942 name_size = sizeof(name);
943 if (gnutls_x509_crt_get_issuer_dn(cert, name, &name_size) == 0)
945 std::string& issuer = certinfo->issuer;
947 if (issuer.find_first_of("\r\n") != std::string::npos)
951 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
953 certinfo->error = gnutls_strerror(ret);
957 certinfo->fingerprint = irc::hex(digest, digest_size);
960 /* Beware here we do not check for errors.
962 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
964 certinfo->error = "Not activated, or expired certificate";
968 gnutls_x509_crt_deinit(cert);
971 void OnEvent(Event& ev)
973 if (starttls.enabled)
974 capHandler.HandleEvent(ev);
978 MODULE_INIT(ModuleSSLGnuTLS)