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 static std::vector<gnutls_x509_crt_t> x509_certs;
68 static gnutls_x509_privkey_t x509_key;
69 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
70 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
71 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
73 st->type = GNUTLS_CRT_X509;
75 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
76 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr2_st * st) {
77 st->cert_type = GNUTLS_CRT_X509;
78 st->key_type = GNUTLS_PRIVKEY_X509;
80 st->ncerts = x509_certs.size();
81 st->cert.x509 = &x509_certs[0];
82 st->key.x509 = x509_key;
88 class RandGen : public HandlerBase2<void, char*, size_t>
92 void Call(char* buffer, size_t len)
95 gnutls_rnd(GNUTLS_RND_RANDOM, buffer, len);
97 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
102 /** Represents an SSL user's extra data
107 StreamSocket* socket;
108 gnutls_session_t sess;
110 reference<ssl_cert> cert;
112 issl_session() : socket(NULL), sess(NULL) {}
115 class CommandStartTLS : public SplitCommand
119 CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
122 works_before_reg = true;
125 CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user)
129 user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
133 if (user->registered == REG_ALL)
135 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
139 if (!user->eh.GetIOHook())
141 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
142 /* We need to flush the write buffer prior to adding the IOHook,
143 * otherwise we'll be sending this line inside the SSL session - which
144 * won't start its handshake until the client gets this line. Currently,
145 * we assume the write will not block here; this is usually safe, as
146 * STARTTLS is sent very early on in the registration phase, where the
147 * user hasn't built up much sendq. Handling a blocked write here would
151 user->eh.AddIOHook(creator);
152 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
155 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
162 class ModuleSSLGnuTLS : public Module
164 issl_session* sessions;
166 gnutls_certificate_credentials_t x509_cred;
167 gnutls_dh_params_t dh_params;
168 gnutls_digest_algorithm_t hash;
169 #ifdef GNUTLS_NEW_PRIO_API
170 gnutls_priority_t priority;
173 std::string sslports;
180 CommandStartTLS starttls;
182 GenericCap capHandler;
183 ServiceProvider iohook;
185 inline static const char* UnknownIfNULL(const char* str)
187 return str ? str : "UNKNOWN";
190 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size)
192 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
193 if (session->socket->GetEventMask() & FD_READ_WILL_BLOCK)
196 gnutls_transport_set_errno(session->sess, EAGAIN);
203 int rv = ServerInstance->SE->Recv(session->socket, reinterpret_cast<char *>(buffer), size, 0);
208 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
209 * and then set errno appropriately.
210 * The gnutls library may also have a different errno variable than us, see
211 * gnutls_transport_set_errno(3).
213 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
218 ServerInstance->SE->ChangeEventMask(session->socket, FD_READ_WILL_BLOCK);
222 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size)
224 issl_session* session = reinterpret_cast<issl_session*>(session_wrap);
225 if (session->socket->GetEventMask() & FD_WRITE_WILL_BLOCK)
228 gnutls_transport_set_errno(session->sess, EAGAIN);
235 int rv = ServerInstance->SE->Send(session->socket, reinterpret_cast<const char *>(buffer), size, 0);
240 /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError()
241 * and then set errno appropriately.
242 * The gnutls library may also have a different errno variable than us, see
243 * gnutls_transport_set_errno(3).
245 gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno);
250 ServerInstance->SE->ChangeEventMask(session->socket, FD_WRITE_WILL_BLOCK);
257 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
259 #ifndef GNUTLS_HAS_RND
260 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
263 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
265 gnutls_global_init(); // This must be called once in the program
266 gnutls_x509_privkey_init(&x509_key);
268 #ifdef GNUTLS_NEW_PRIO_API
269 // Init this here so it's always initialized, avoids an extra boolean
270 gnutls_priority_init(&priority, "NORMAL", NULL);
279 // Needs the flag as it ignores a plain /rehash
280 OnModuleRehash(NULL,"ssl");
282 ServerInstance->GenRandom = &randhandler;
284 // Void return, guess we assume success
285 gnutls_certificate_set_dh_params(x509_cred, dh_params);
286 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
287 I_OnEvent, I_OnHookIO };
288 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
290 ServerInstance->Modules->AddService(iohook);
291 ServerInstance->Modules->AddService(starttls);
294 void OnRehash(User* user)
298 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
299 starttls.enabled = Conf->getBool("starttls", true);
301 if (Conf->getBool("showports", true))
303 sslports = Conf->getString("advertisedports");
304 if (!sslports.empty())
307 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
309 ListenSocket* port = ServerInstance->ports[i];
310 if (port->bind_tag->getString("ssl") != "gnutls")
313 const std::string& portid = port->bind_desc;
314 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
316 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
319 * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
320 * the IP:port in ISUPPORT.
322 * We used to advertise all ports seperated by a ';' char that matched the above criteria,
323 * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
324 * To solve this by default we now only display the first IP:port found and let the user
325 * configure the exact value for the 005 token, if necessary.
334 void OnModuleRehash(User* user, const std::string ¶m)
340 std::string certfile;
345 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
347 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
348 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
349 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
350 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
351 dh_bits = Conf->getInt("dhbits");
352 std::string hashname = Conf->getString("hash", "md5");
354 // The GnuTLS manual states that the gnutls_set_default_priority()
355 // call we used previously when initializing the session is the same
356 // as setting the "NORMAL" priority string.
357 // Thus if the setting below is not in the config we will behave exactly
358 // the same as before, when the priority setting wasn't available.
359 std::string priorities = Conf->getString("priority", "NORMAL");
361 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
364 if (hashname == "md5")
365 hash = GNUTLS_DIG_MD5;
366 else if (hashname == "sha1")
367 hash = GNUTLS_DIG_SHA1;
369 throw ModuleException("Unknown hash type " + hashname);
376 gnutls_dh_params_deinit(dh_params);
383 // Deallocate the old credentials
384 gnutls_certificate_free_credentials(x509_cred);
386 for(unsigned int i=0; i < x509_certs.size(); i++)
387 gnutls_x509_crt_deinit(x509_certs[i]);
391 ret = gnutls_certificate_allocate_credentials(&x509_cred);
392 cred_alloc = (ret >= 0);
394 ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
396 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
397 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));
399 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
400 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));
404 reader.LoadFile(certfile);
405 std::string cert_string = reader.Contents();
406 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
408 reader.LoadFile(keyfile);
409 std::string key_string = reader.Contents();
410 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
412 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
413 unsigned int certcount = 3;
414 x509_certs.resize(certcount);
415 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
416 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
418 // 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
419 x509_certs.resize(certcount);
420 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
425 // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later
427 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read"));
429 x509_certs.resize(ret);
431 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
432 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
434 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
435 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
437 #ifdef GNUTLS_NEW_PRIO_API
438 // It's safe to call this every time as we cannot have this uninitialized, see constructor and below.
439 gnutls_priority_deinit(priority);
441 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
442 // If the user did not supply anything then the string is already set to "NORMAL"
443 const char* priocstr = priorities.c_str();
444 const char* prioerror;
446 if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0)
448 // gnutls did not understand the user supplied string, log and fall back to the default priorities
449 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));
450 gnutls_priority_init(&priority, "NORMAL", NULL);
454 if (priorities != "NORMAL")
455 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.");
458 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
459 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
461 gnutls_certificate_set_retrieve_function (x509_cred, cert_callback);
463 ret = gnutls_dh_params_init(&dh_params);
464 dh_alloc = (ret >= 0);
467 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
471 std::string dhfile = Conf->getString("dhfile");
474 // Try to load DH params from file
475 reader.LoadFile(dhfile);
476 std::string dhstring = reader.Contents();
477 gnutls_datum_t dh_datum = { (unsigned char*)dhstring.data(), static_cast<unsigned int>(dhstring.length()) };
479 if ((ret = gnutls_dh_params_import_pkcs3(dh_params, &dh_datum, GNUTLS_X509_FMT_PEM)) < 0)
481 // File unreadable or GnuTLS was unhappy with the contents, generate the DH primes now
482 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));
492 void GenerateDHParams()
494 // Generate Diffie Hellman parameters - for use with DHE
495 // kx algorithms. These should be discarded and regenerated
496 // once a day, once a week or once a month. Depending on the
497 // security requirements.
504 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
505 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
510 for(unsigned int i=0; i < x509_certs.size(); i++)
511 gnutls_x509_crt_deinit(x509_certs[i]);
513 gnutls_x509_privkey_deinit(x509_key);
514 #ifdef GNUTLS_NEW_PRIO_API
515 gnutls_priority_deinit(priority);
519 gnutls_dh_params_deinit(dh_params);
521 gnutls_certificate_free_credentials(x509_cred);
523 gnutls_global_deinit();
525 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
528 void OnCleanup(int target_type, void* item)
530 if(target_type == TYPE_USER)
532 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
534 if (user && user->eh.GetIOHook() == this)
536 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
537 // Potentially there could be multiple SSL modules loaded at once on different ports.
538 ServerInstance->Users->QuitUser(user, "SSL module unloading");
545 return Version("Provides SSL support for clients", VF_VENDOR);
549 void On005Numeric(std::string &output)
551 if (!sslports.empty())
552 output.append(" SSL=" + sslports);
553 if (starttls.enabled)
554 output.append(" STARTTLS");
557 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
559 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
561 /* Hook the user with our module */
562 user->AddIOHook(this);
566 void OnRequest(Request& request)
568 if (strcmp("GET_SSL_CERT", request.id) == 0)
570 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
571 int fd = req.sock->GetFd();
572 issl_session* session = &sessions[fd];
574 req.cert = session->cert;
578 void InitSession(StreamSocket* user, bool me_server)
580 issl_session* session = &sessions[user->GetFd()];
582 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
583 session->socket = user;
585 #ifdef GNUTLS_NEW_PRIO_API
586 gnutls_priority_set(session->sess, priority);
588 gnutls_set_default_priority(session->sess);
590 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
591 gnutls_dh_set_prime_bits(session->sess, dh_bits);
592 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(session));
593 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
594 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
597 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
599 Handshake(session, user);
602 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
604 issl_session* session = &sessions[user->GetFd()];
606 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
610 InitSession(user, true);
613 void OnStreamSocketConnect(StreamSocket* user)
615 InitSession(user, false);
618 void OnStreamSocketClose(StreamSocket* user)
620 CloseSession(&sessions[user->GetFd()]);
623 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
625 issl_session* session = &sessions[user->GetFd()];
629 CloseSession(session);
630 user->SetError("No SSL session");
634 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
636 // The handshake isn't finished, try to finish it.
638 if(!Handshake(session, user))
640 if (session->status != ISSL_CLOSING)
646 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
648 if (session->status == ISSL_HANDSHAKEN)
650 char* buffer = ServerInstance->GetReadBuffer();
651 size_t bufsiz = ServerInstance->Config->NetBufferSize;
652 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
655 recvq.append(buffer, ret);
658 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
664 user->SetError("Connection closed");
665 CloseSession(session);
670 user->SetError(gnutls_strerror(ret));
671 CloseSession(session);
675 else if (session->status == ISSL_CLOSING)
681 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
683 issl_session* session = &sessions[user->GetFd()];
687 CloseSession(session);
688 user->SetError("No SSL session");
692 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
694 // The handshake isn't finished, try to finish it.
695 Handshake(session, user);
696 if (session->status != ISSL_CLOSING)
703 if (session->status == ISSL_HANDSHAKEN)
705 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
707 if (ret == (int)sendq.length())
709 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
714 sendq = sendq.substr(ret);
715 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
718 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
720 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
725 user->SetError(gnutls_strerror(ret));
726 CloseSession(session);
734 bool Handshake(issl_session* session, StreamSocket* user)
736 int ret = gnutls_handshake(session->sess);
740 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
742 // Handshake needs resuming later, read() or write() would have blocked.
744 if(gnutls_record_get_direction(session->sess) == 0)
746 // gnutls_handshake() wants to read() again.
747 session->status = ISSL_HANDSHAKING_READ;
748 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
752 // gnutls_handshake() wants to write() again.
753 session->status = ISSL_HANDSHAKING_WRITE;
754 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
759 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
760 CloseSession(session);
761 session->status = ISSL_CLOSING;
768 // Change the seesion state
769 session->status = ISSL_HANDSHAKEN;
771 VerifyCertificate(session,user);
773 // Finish writing, if any left
774 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
780 void OnUserConnect(LocalUser* user)
782 if (user->eh.GetIOHook() == this)
784 if (sessions[user->eh.GetFd()].sess)
786 const gnutls_session_t& sess = sessions[user->eh.GetFd()].sess;
787 std::string cipher = UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)));
788 cipher.append("-").append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).append("-");
789 cipher.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
791 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
792 if (cert->fingerprint.empty())
793 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
795 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
796 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
801 void CloseSession(issl_session* session)
805 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
806 gnutls_deinit(session->sess);
808 session->socket = NULL;
809 session->sess = NULL;
810 session->cert = NULL;
811 session->status = ISSL_NONE;
814 void VerifyCertificate(issl_session* session, StreamSocket* user)
816 if (!session->sess || !user)
820 const gnutls_datum_t* cert_list;
822 unsigned int cert_list_size;
823 gnutls_x509_crt_t cert;
825 unsigned char digest[MAXBUF];
826 size_t digest_size = sizeof(digest);
827 size_t name_size = sizeof(name);
828 ssl_cert* certinfo = new ssl_cert;
829 session->cert = certinfo;
831 /* This verification function uses the trusted CAs in the credentials
832 * structure. So you must have installed one or more CA certificates.
834 ret = gnutls_certificate_verify_peers2(session->sess, &status);
838 certinfo->error = std::string(gnutls_strerror(ret));
842 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
843 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
844 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
845 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
847 /* Up to here the process is the same for X.509 certificates and
848 * OpenPGP keys. From now on X.509 certificates are assumed. This can
849 * be easily extended to work with openpgp keys as well.
851 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
853 certinfo->error = "No X509 keys sent";
857 ret = gnutls_x509_crt_init(&cert);
860 certinfo->error = gnutls_strerror(ret);
865 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
866 if (cert_list == NULL)
868 certinfo->error = "No certificate was found";
869 goto info_done_dealloc;
872 /* This is not a real world example, since we only check the first
873 * certificate in the given chain.
876 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
879 certinfo->error = gnutls_strerror(ret);
880 goto info_done_dealloc;
883 if (gnutls_x509_crt_get_dn(cert, name, &name_size) == 0)
885 std::string& dn = certinfo->dn;
887 // Make sure there are no chars in the string that we consider invalid
888 if (dn.find_first_of("\r\n") != std::string::npos)
892 name_size = sizeof(name);
893 if (gnutls_x509_crt_get_issuer_dn(cert, name, &name_size) == 0)
895 std::string& issuer = certinfo->issuer;
897 if (issuer.find_first_of("\r\n") != std::string::npos)
901 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
903 certinfo->error = gnutls_strerror(ret);
907 certinfo->fingerprint = irc::hex(digest, digest_size);
910 /* Beware here we do not check for errors.
912 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
914 certinfo->error = "Not activated, or expired certificate";
918 gnutls_x509_crt_deinit(cert);
921 void OnEvent(Event& ev)
923 if (starttls.enabled)
924 capHandler.HandleEvent(ev);
928 MODULE_INIT(ModuleSSLGnuTLS)