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 # pragma comment(lib, "libgnutls-30.lib")
34 /* $ModDesc: Provides SSL support for clients */
35 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") iflt("pkg-config --modversion gnutls","2.12") exec("libgcrypt-config --cflags") */
36 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") iflt("pkg-config --modversion gnutls","2.12") exec("libgcrypt-config --libs") */
39 #ifndef GNUTLS_VERSION_MAJOR
40 #define GNUTLS_VERSION_MAJOR LIBGNUTLS_VERSION_MAJOR
41 #define GNUTLS_VERSION_MINOR LIBGNUTLS_VERSION_MINOR
42 #define GNUTLS_VERSION_PATCH LIBGNUTLS_VERSION_PATCH
45 // These don't exist in older GnuTLS versions
46 #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))
47 #define GNUTLS_NEW_PRIO_API
50 #if(GNUTLS_VERSION_MAJOR < 2)
51 typedef gnutls_certificate_credentials_t gnutls_certificate_credentials;
52 typedef gnutls_dh_params_t gnutls_dh_params;
55 #if (GNUTLS_VERSION_MAJOR > 2 || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR >= 12))
56 # define GNUTLS_HAS_RND
57 # include <gnutls/crypto.h>
62 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
64 struct SSLConfig : public refcountbase
66 gnutls_certificate_credentials_t x509_cred;
67 std::vector<gnutls_x509_crt_t> x509_certs;
68 gnutls_x509_privkey_t x509_key;
69 gnutls_dh_params_t dh_params;
70 #ifdef GNUTLS_NEW_PRIO_API
71 gnutls_priority_t priority;
78 #ifdef GNUTLS_NEW_PRIO_API
86 ServerInstance->Logs->Log("m_ssl_gnutls", DEBUG, "Destroying SSLConfig %p", (void*)this);
89 gnutls_certificate_free_credentials(x509_cred);
91 for (unsigned int i = 0; i < x509_certs.size(); i++)
92 gnutls_x509_crt_deinit(x509_certs[i]);
95 gnutls_x509_privkey_deinit(x509_key);
98 gnutls_dh_params_deinit(dh_params);
100 #ifdef GNUTLS_NEW_PRIO_API
102 gnutls_priority_deinit(priority);
107 static reference<SSLConfig> currconf;
109 static SSLConfig* GetSessionConfig(gnutls_session_t session);
111 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
112 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
113 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
115 st->type = GNUTLS_CRT_X509;
117 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
118 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr2_st * st) {
119 st->cert_type = GNUTLS_CRT_X509;
120 st->key_type = GNUTLS_PRIVKEY_X509;
122 SSLConfig* conf = GetSessionConfig(session);
123 std::vector<gnutls_x509_crt_t>& x509_certs = conf->x509_certs;
124 st->ncerts = x509_certs.size();
125 st->cert.x509 = &x509_certs[0];
126 st->key.x509 = conf->x509_key;
132 class RandGen : public HandlerBase2<void, char*, size_t>
136 void Call(char* buffer, size_t len)
138 #ifdef GNUTLS_HAS_RND
139 gnutls_rnd(GNUTLS_RND_RANDOM, buffer, len);
141 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
146 /** Represents an SSL user's extra data
151 StreamSocket* socket;
152 gnutls_session_t sess;
154 reference<ssl_cert> cert;
155 reference<SSLConfig> config;
157 issl_session() : socket(NULL), sess(NULL), status(ISSL_NONE) {}
160 static SSLConfig* GetSessionConfig(gnutls_session_t sess)
162 issl_session* session = reinterpret_cast<issl_session*>(gnutls_transport_get_ptr(sess));
163 return session->config;
166 class CommandStartTLS : public SplitCommand
170 CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
173 works_before_reg = true;
176 CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user)
180 user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
184 if (user->registered == REG_ALL)
186 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
190 if (!user->eh.GetIOHook())
192 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
193 /* We need to flush the write buffer prior to adding the IOHook,
194 * otherwise we'll be sending this line inside the SSL session - which
195 * won't start its handshake until the client gets this line. Currently,
196 * we assume the write will not block here; this is usually safe, as
197 * STARTTLS is sent very early on in the registration phase, where the
198 * user hasn't built up much sendq. Handling a blocked write here would
202 user->eh.AddIOHook(creator);
203 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
206 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
213 class ModuleSSLGnuTLS : public Module
215 issl_session* sessions;
217 gnutls_digest_algorithm_t hash;
219 std::string sslports;
223 CommandStartTLS starttls;
225 GenericCap capHandler;
226 ServiceProvider iohook;
228 inline static const char* UnknownIfNULL(const char* str)
230 return str ? str : "UNKNOWN";
233 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
235 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
236 if (session->socket->GetEventMask() & FD_READ_WILL_BLOCK)
239 gnutls_transport_set_errno(session->sess, EAGAIN);
246 int rv = ServerInstance->SE->Recv(session->socket, reinterpret_cast<char *>(buffer), size, 0);
251 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
252 * and then set errno appropriately.
253 * The gnutls library may also have a different errno variable than us, see
254 * gnutls_transport_set_errno(3).
256 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
261 ServerInstance->SE->ChangeEventMask(session->socket, FD_READ_WILL_BLOCK);
265 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
267 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
268 if (session->socket->GetEventMask() & FD_WRITE_WILL_BLOCK)
271 gnutls_transport_set_errno(session->sess, EAGAIN);
278 int rv = ServerInstance->SE->Send(session->socket, reinterpret_cast<const char *>(buffer), size, 0);
283 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
284 * and then set errno appropriately.
285 * The gnutls library may also have a different errno variable than us, see
286 * gnutls_transport_set_errno(3).
288 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
293 ServerInstance->SE->ChangeEventMask(session->socket, FD_WRITE_WILL_BLOCK);
300 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
302 #ifndef GNUTLS_HAS_RND
303 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
306 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
308 gnutls_global_init(); // This must be called once in the program
313 currconf = new SSLConfig;
314 InitSSLConfig(currconf);
316 ServerInstance->GenRandom = &randhandler;
318 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
319 I_OnEvent, I_OnHookIO, I_OnCheckReady };
320 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
322 ServerInstance->Modules->AddService(iohook);
323 ServerInstance->Modules->AddService(starttls);
326 void OnRehash(User* user)
330 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
331 starttls.enabled = Conf->getBool("starttls", true);
333 if (Conf->getBool("showports", true))
335 sslports = Conf->getString("advertisedports");
336 if (!sslports.empty())
339 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
341 ListenSocket* port = ServerInstance->ports[i];
342 if (port->bind_tag->getString("ssl") != "gnutls")
345 const std::string& portid = port->bind_desc;
346 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
348 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
351 * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
352 * the IP:port in ISUPPORT.
354 * We used to advertise all ports seperated by a ';' char that matched the above criteria,
355 * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
356 * To solve this by default we now only display the first IP:port found and let the user
357 * configure the exact value for the 005 token, if necessary.
366 void OnModuleRehash(User* user, const std::string ¶m)
371 reference<SSLConfig> newconf = new SSLConfig;
374 InitSSLConfig(newconf);
376 catch (ModuleException& ex)
378 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls: Not applying new config. %s", ex.GetReason());
382 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);
386 void InitSSLConfig(SSLConfig* config)
388 ServerInstance->Logs->Log("m_ssl_gnutls", DEBUG, "Initializing new SSLConfig %p", (void*)config);
391 std::string certfile;
396 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
398 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
399 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
400 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
401 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
402 dh_bits = Conf->getInt("dhbits");
403 std::string hashname = Conf->getString("hash", "md5");
405 // The GnuTLS manual states that the gnutls_set_default_priority()
406 // call we used previously when initializing the session is the same
407 // as setting the "NORMAL" priority string.
408 // Thus if the setting below is not in the config we will behave exactly
409 // the same as before, when the priority setting wasn't available.
410 std::string priorities = Conf->getString("priority", "NORMAL");
412 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
415 if (hashname == "md5")
416 hash = GNUTLS_DIG_MD5;
417 else if (hashname == "sha1")
418 hash = GNUTLS_DIG_SHA1;
419 #ifdef INSPIRCD_GNUTLS_ENABLE_SHA256_FINGERPRINT
420 else if (hashname == "sha256")
421 hash = GNUTLS_DIG_SHA256;
424 throw ModuleException("Unknown hash type " + hashname);
429 gnutls_certificate_credentials_t& x509_cred = config->x509_cred;
431 ret = gnutls_certificate_allocate_credentials(&x509_cred);
434 // Set to NULL because we can't be sure what value is in it and we must not try to
435 // deallocate it in case of an error
437 throw ModuleException("Failed to allocate certificate credentials: " + std::string(gnutls_strerror(ret)));
440 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
441 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));
443 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
444 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));
448 reader.LoadFile(certfile);
449 std::string cert_string = reader.Contents();
450 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
452 reader.LoadFile(keyfile);
453 std::string key_string = reader.Contents();
454 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
456 std::vector<gnutls_x509_crt_t>& x509_certs = config->x509_certs;
458 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
459 unsigned int certcount = 3;
460 x509_certs.resize(certcount);
461 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
462 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
464 // 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
465 x509_certs.resize(certcount);
466 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
471 // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later
473 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read"));
475 x509_certs.resize(ret);
477 gnutls_x509_privkey_t& x509_key = config->x509_key;
478 if (gnutls_x509_privkey_init(&x509_key) < 0)
480 // Make sure the destructor does not try to deallocate this, see above
482 throw ModuleException("Unable to initialize private key");
485 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
486 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
488 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
489 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
491 #ifdef GNUTLS_NEW_PRIO_API
492 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
493 // If the user did not supply anything then the string is already set to "NORMAL"
494 const char* priocstr = priorities.c_str();
495 const char* prioerror;
497 gnutls_priority_t& priority = config->priority;
498 if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0)
500 // gnutls did not understand the user supplied string, log and fall back to the default priorities
501 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));
502 gnutls_priority_init(&priority, "NORMAL", NULL);
506 if (priorities != "NORMAL")
507 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.");
510 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
511 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
513 gnutls_certificate_set_retrieve_function (x509_cred, cert_callback);
516 gnutls_dh_params_t& dh_params = config->dh_params;
517 ret = gnutls_dh_params_init(&dh_params);
520 // Make sure the destructor does not try to deallocate this, see above
522 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
526 std::string dhfile = Conf->getString("dhfile");
529 // Try to load DH params from file
530 reader.LoadFile(dhfile);
531 std::string dhstring = reader.Contents();
532 gnutls_datum_t dh_datum = { (unsigned char*)dhstring.data(), static_cast<unsigned int>(dhstring.length()) };
534 if ((ret = gnutls_dh_params_import_pkcs3(dh_params, &dh_datum, GNUTLS_X509_FMT_PEM)) < 0)
536 // File unreadable or GnuTLS was unhappy with the contents, generate the DH primes now
537 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));
538 GenerateDHParams(dh_params);
543 GenerateDHParams(dh_params);
546 gnutls_certificate_set_dh_params(x509_cred, dh_params);
549 void GenerateDHParams(gnutls_dh_params_t dh_params)
551 // Generate Diffie Hellman parameters - for use with DHE
552 // kx algorithms. These should be discarded and regenerated
553 // once a day, once a week or once a month. Depending on the
554 // security requirements.
558 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
559 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
566 gnutls_global_deinit();
568 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
571 void OnCleanup(int target_type, void* item)
573 if(target_type == TYPE_USER)
575 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
577 if (user && user->eh.GetIOHook() == this)
579 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
580 // Potentially there could be multiple SSL modules loaded at once on different ports.
581 ServerInstance->Users->QuitUser(user, "SSL module unloading");
588 return Version("Provides SSL support for clients", VF_VENDOR);
592 void On005Numeric(std::string &output)
594 if (!sslports.empty())
595 output.append(" SSL=" + sslports);
596 if (starttls.enabled)
597 output.append(" STARTTLS");
600 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
602 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
604 /* Hook the user with our module */
605 user->AddIOHook(this);
609 void OnRequest(Request& request)
611 if (strcmp("GET_SSL_CERT", request.id) == 0)
613 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
614 int fd = req.sock->GetFd();
615 issl_session* session = &sessions[fd];
617 req.cert = session->cert;
619 else if (!strcmp("GET_RAW_SSL_SESSION", request.id))
621 SSLRawSessionRequest& req = static_cast<SSLRawSessionRequest&>(request);
622 if ((req.fd >= 0) && (req.fd < ServerInstance->SE->GetMaxFds()))
623 req.data = reinterpret_cast<void*>(sessions[req.fd].sess);
627 void InitSession(StreamSocket* user, bool me_server)
629 issl_session* session = &sessions[user->GetFd()];
631 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
632 session->socket = user;
633 session->config = currconf;
635 #ifdef GNUTLS_NEW_PRIO_API
636 gnutls_priority_set(session->sess, currconf->priority);
638 gnutls_set_default_priority(session->sess);
640 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, currconf->x509_cred);
641 gnutls_dh_set_prime_bits(session->sess, dh_bits);
642 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(session));
643 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
644 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
647 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
649 Handshake(session, user);
652 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
654 issl_session* session = &sessions[user->GetFd()];
656 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
660 InitSession(user, true);
663 void OnStreamSocketConnect(StreamSocket* user)
665 InitSession(user, false);
668 void OnStreamSocketClose(StreamSocket* user)
670 CloseSession(&sessions[user->GetFd()]);
673 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
675 issl_session* session = &sessions[user->GetFd()];
679 CloseSession(session);
680 user->SetError("No SSL session");
684 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
686 // The handshake isn't finished, try to finish it.
688 if(!Handshake(session, user))
690 if (session->status != ISSL_CLOSING)
696 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
698 if (session->status == ISSL_HANDSHAKEN)
700 char* buffer = ServerInstance->GetReadBuffer();
701 size_t bufsiz = ServerInstance->Config->NetBufferSize;
702 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
705 recvq.append(buffer, ret);
708 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
714 user->SetError("Connection closed");
715 CloseSession(session);
720 user->SetError(gnutls_strerror(ret));
721 CloseSession(session);
725 else if (session->status == ISSL_CLOSING)
731 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
733 issl_session* session = &sessions[user->GetFd()];
737 CloseSession(session);
738 user->SetError("No SSL session");
742 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
744 // The handshake isn't finished, try to finish it.
745 Handshake(session, user);
746 if (session->status != ISSL_CLOSING)
753 if (session->status == ISSL_HANDSHAKEN)
755 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
757 if (ret == (int)sendq.length())
759 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
764 sendq = sendq.substr(ret);
765 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
768 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
770 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
775 user->SetError(gnutls_strerror(ret));
776 CloseSession(session);
784 bool Handshake(issl_session* session, StreamSocket* user)
786 int ret = gnutls_handshake(session->sess);
790 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
792 // Handshake needs resuming later, read() or write() would have blocked.
794 if(gnutls_record_get_direction(session->sess) == 0)
796 // gnutls_handshake() wants to read() again.
797 session->status = ISSL_HANDSHAKING_READ;
798 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
802 // gnutls_handshake() wants to write() again.
803 session->status = ISSL_HANDSHAKING_WRITE;
804 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
809 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
810 CloseSession(session);
811 session->status = ISSL_CLOSING;
818 // Change the seesion state
819 session->status = ISSL_HANDSHAKEN;
821 VerifyCertificate(session,user);
823 // Finish writing, if any left
824 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
830 void OnUserConnect(LocalUser* user)
832 if (user->eh.GetIOHook() == this)
834 if (sessions[user->eh.GetFd()].sess)
836 const gnutls_session_t& sess = sessions[user->eh.GetFd()].sess;
837 std::string cipher = UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)));
838 cipher.append("-").append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).append("-");
839 cipher.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
841 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
842 if (cert->fingerprint.empty())
843 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
845 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
846 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
851 void CloseSession(issl_session* session)
855 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
856 gnutls_deinit(session->sess);
858 session->socket = NULL;
859 session->sess = NULL;
860 session->cert = NULL;
861 session->status = ISSL_NONE;
862 session->config = NULL;
865 void VerifyCertificate(issl_session* session, StreamSocket* user)
867 if (!session->sess || !user)
871 const gnutls_datum_t* cert_list;
873 unsigned int cert_list_size;
874 gnutls_x509_crt_t cert;
876 unsigned char digest[MAXBUF];
877 size_t digest_size = sizeof(digest);
878 size_t name_size = sizeof(name);
879 ssl_cert* certinfo = new ssl_cert;
880 session->cert = certinfo;
882 /* This verification function uses the trusted CAs in the credentials
883 * structure. So you must have installed one or more CA certificates.
885 ret = gnutls_certificate_verify_peers2(session->sess, &status);
889 certinfo->error = std::string(gnutls_strerror(ret));
893 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
894 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
895 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
896 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
898 /* Up to here the process is the same for X.509 certificates and
899 * OpenPGP keys. From now on X.509 certificates are assumed. This can
900 * be easily extended to work with openpgp keys as well.
902 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
904 certinfo->error = "No X509 keys sent";
908 ret = gnutls_x509_crt_init(&cert);
911 certinfo->error = gnutls_strerror(ret);
916 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
917 if (cert_list == NULL)
919 certinfo->error = "No certificate was found";
920 goto info_done_dealloc;
923 /* This is not a real world example, since we only check the first
924 * certificate in the given chain.
927 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
930 certinfo->error = gnutls_strerror(ret);
931 goto info_done_dealloc;
934 if (gnutls_x509_crt_get_dn(cert, name, &name_size) == 0)
936 std::string& dn = certinfo->dn;
938 // Make sure there are no chars in the string that we consider invalid
939 if (dn.find_first_of("\r\n") != std::string::npos)
943 name_size = sizeof(name);
944 if (gnutls_x509_crt_get_issuer_dn(cert, name, &name_size) == 0)
946 std::string& issuer = certinfo->issuer;
948 if (issuer.find_first_of("\r\n") != std::string::npos)
952 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
954 certinfo->error = gnutls_strerror(ret);
958 certinfo->fingerprint = irc::hex(digest, digest_size);
961 /* Beware here we do not check for errors.
963 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
965 certinfo->error = "Not activated, or expired certificate";
969 gnutls_x509_crt_deinit(cert);
972 void OnEvent(Event& ev)
974 if (starttls.enabled)
975 capHandler.HandleEvent(ev);
978 ModResult OnCheckReady(LocalUser* user)
980 if ((user->eh.GetIOHook() == this) && (sessions[user->eh.GetFd()].status != ISSL_HANDSHAKEN))
982 return MOD_RES_PASSTHRU;
986 MODULE_INIT(ModuleSSLGnuTLS)