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/>.
26 #include <gnutls/gnutls.h>
27 #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","") exec("libgcrypt-config --cflags") */
44 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") exec("libgcrypt-config --libs") */
47 // These don't exist in older GnuTLS versions
48 #if ((GNUTLS_VERSION_MAJOR > 2) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR > 1) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR == 1 && GNUTLS_VERSION_MICRO >= 7))
49 #define GNUTLS_NEW_PRIO_API
52 #if(GNUTLS_VERSION_MAJOR < 2)
53 typedef gnutls_certificate_credentials_t gnutls_certificate_credentials;
54 typedef gnutls_dh_params_t gnutls_dh_params;
57 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
59 static std::vector<gnutls_x509_crt_t> x509_certs;
60 static gnutls_x509_privkey_t x509_key;
61 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
62 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
63 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
65 st->type = GNUTLS_CRT_X509;
67 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
68 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr2_st * st) {
69 st->cert_type = GNUTLS_CRT_X509;
70 st->key_type = GNUTLS_PRIVKEY_X509;
72 st->ncerts = x509_certs.size();
73 st->cert.x509 = &x509_certs[0];
74 st->key.x509 = x509_key;
80 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t user_wrap, void* buffer, size_t size)
82 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
83 if (user->GetEventMask() & FD_READ_WILL_BLOCK)
88 int rv = ServerInstance->SE->Recv(user, reinterpret_cast<char *>(buffer), size, 0);
90 ServerInstance->SE->ChangeEventMask(user, FD_READ_WILL_BLOCK);
94 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t user_wrap, const void* buffer, size_t size)
96 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
97 if (user->GetEventMask() & FD_WRITE_WILL_BLOCK)
102 int rv = ServerInstance->SE->Send(user, reinterpret_cast<const char *>(buffer), size, 0);
104 ServerInstance->SE->ChangeEventMask(user, FD_WRITE_WILL_BLOCK);
108 class RandGen : public HandlerBase2<void, char*, size_t>
112 void Call(char* buffer, size_t len)
114 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
118 /** Represents an SSL user's extra data
123 gnutls_session_t sess;
125 reference<ssl_cert> cert;
126 issl_session() : sess(NULL) {}
129 class CommandStartTLS : public SplitCommand
133 CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
136 works_before_reg = true;
139 CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user)
143 user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
147 if (user->registered == REG_ALL)
149 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
153 if (!user->eh.GetIOHook())
155 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
156 /* We need to flush the write buffer prior to adding the IOHook,
157 * otherwise we'll be sending this line inside the SSL session - which
158 * won't start its handshake until the client gets this line. Currently,
159 * we assume the write will not block here; this is usually safe, as
160 * STARTTLS is sent very early on in the registration phase, where the
161 * user hasn't built up much sendq. Handling a blocked write here would
165 user->eh.AddIOHook(creator);
166 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
169 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
176 class ModuleSSLGnuTLS : public Module
178 issl_session* sessions;
180 gnutls_certificate_credentials_t x509_cred;
181 gnutls_dh_params_t dh_params;
182 gnutls_digest_algorithm_t hash;
183 #ifdef GNUTLS_NEW_PRIO_API
184 gnutls_priority_t priority;
187 std::string sslports;
194 CommandStartTLS starttls;
196 GenericCap capHandler;
197 ServiceProvider iohook;
201 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
203 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
205 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
207 gnutls_global_init(); // This must be called once in the program
208 gnutls_x509_privkey_init(&x509_key);
210 #ifdef GNUTLS_NEW_PRIO_API
211 // Init this here so it's always initialized, avoids an extra boolean
212 gnutls_priority_init(&priority, "NORMAL", NULL);
221 // Needs the flag as it ignores a plain /rehash
222 OnModuleRehash(NULL,"ssl");
224 ServerInstance->GenRandom = &randhandler;
226 // Void return, guess we assume success
227 gnutls_certificate_set_dh_params(x509_cred, dh_params);
228 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
229 I_OnEvent, I_OnHookIO };
230 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
232 ServerInstance->Modules->AddService(iohook);
233 ServerInstance->Modules->AddService(starttls);
236 void OnRehash(User* user)
240 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
241 starttls.enabled = Conf->getBool("starttls", true);
243 if (Conf->getBool("showports", true))
245 sslports = Conf->getString("advertisedports");
246 if (!sslports.empty())
249 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
251 ListenSocket* port = ServerInstance->ports[i];
252 if (port->bind_tag->getString("ssl") != "gnutls")
255 const std::string& portid = port->bind_desc;
256 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
258 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
261 * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
262 * the IP:port in ISUPPORT.
264 * We used to advertise all ports seperated by a ';' char that matched the above criteria,
265 * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
266 * To solve this by default we now only display the first IP:port found and let the user
267 * configure the exact value for the 005 token, if necessary.
276 void OnModuleRehash(User* user, const std::string ¶m)
282 std::string certfile;
287 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
289 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
290 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
291 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
292 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
293 dh_bits = Conf->getInt("dhbits");
294 std::string hashname = Conf->getString("hash", "md5");
296 // The GnuTLS manual states that the gnutls_set_default_priority()
297 // call we used previously when initializing the session is the same
298 // as setting the "NORMAL" priority string.
299 // Thus if the setting below is not in the config we will behave exactly
300 // the same as before, when the priority setting wasn't available.
301 std::string priorities = Conf->getString("priority", "NORMAL");
303 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
306 if (hashname == "md5")
307 hash = GNUTLS_DIG_MD5;
308 else if (hashname == "sha1")
309 hash = GNUTLS_DIG_SHA1;
311 throw ModuleException("Unknown hash type " + hashname);
318 gnutls_dh_params_deinit(dh_params);
324 // Deallocate the old credentials
325 gnutls_certificate_free_credentials(x509_cred);
327 for(unsigned int i=0; i < x509_certs.size(); i++)
328 gnutls_x509_crt_deinit(x509_certs[i]);
332 ret = gnutls_certificate_allocate_credentials(&x509_cred);
333 cred_alloc = (ret >= 0);
335 ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
337 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
338 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));
340 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
341 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));
345 reader.LoadFile(certfile);
346 std::string cert_string = reader.Contents();
347 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
349 reader.LoadFile(keyfile);
350 std::string key_string = reader.Contents();
351 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
353 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
354 unsigned int certcount = 3;
355 x509_certs.resize(certcount);
356 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
357 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
359 // 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
360 x509_certs.resize(certcount);
361 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
366 // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later
368 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read"));
370 x509_certs.resize(ret);
372 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
373 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
375 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
376 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
378 #ifdef GNUTLS_NEW_PRIO_API
379 // It's safe to call this every time as we cannot have this uninitialized, see constructor and below.
380 gnutls_priority_deinit(priority);
382 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
383 // If the user did not supply anything then the string is already set to "NORMAL"
384 const char* priocstr = priorities.c_str();
385 const char* prioerror;
387 if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0)
389 // gnutls did not understand the user supplied string, log and fall back to the default priorities
390 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));
391 gnutls_priority_init(&priority, "NORMAL", NULL);
395 if (priorities != "NORMAL")
396 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.");
399 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
400 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
402 gnutls_certificate_set_retrieve_function (x509_cred, cert_callback);
404 ret = gnutls_dh_params_init(&dh_params);
405 dh_alloc = (ret >= 0);
407 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
409 // This may be on a large (once a day or week) timer eventually.
413 void GenerateDHParams()
415 // Generate Diffie Hellman parameters - for use with DHE
416 // kx algorithms. These should be discarded and regenerated
417 // once a day, once a week or once a month. Depending on the
418 // security requirements.
425 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
426 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
431 for(unsigned int i=0; i < x509_certs.size(); i++)
432 gnutls_x509_crt_deinit(x509_certs[i]);
434 gnutls_x509_privkey_deinit(x509_key);
435 #ifdef GNUTLS_NEW_PRIO_API
436 gnutls_priority_deinit(priority);
440 gnutls_dh_params_deinit(dh_params);
442 gnutls_certificate_free_credentials(x509_cred);
444 gnutls_global_deinit();
446 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
449 void OnCleanup(int target_type, void* item)
451 if(target_type == TYPE_USER)
453 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
455 if (user && user->eh.GetIOHook() == this)
457 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
458 // Potentially there could be multiple SSL modules loaded at once on different ports.
459 ServerInstance->Users->QuitUser(user, "SSL module unloading");
466 return Version("Provides SSL support for clients", VF_VENDOR);
470 void On005Numeric(std::string &output)
472 if (!sslports.empty())
473 output.append(" SSL=" + sslports);
474 if (starttls.enabled)
475 output.append(" STARTTLS");
478 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
480 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
482 /* Hook the user with our module */
483 user->AddIOHook(this);
487 void OnRequest(Request& request)
489 if (strcmp("GET_SSL_CERT", request.id) == 0)
491 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
492 int fd = req.sock->GetFd();
493 issl_session* session = &sessions[fd];
495 req.cert = session->cert;
499 void InitSession(StreamSocket* user, bool me_server)
501 issl_session* session = &sessions[user->GetFd()];
503 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
505 #ifdef GNUTLS_NEW_PRIO_API
506 gnutls_priority_set(session->sess, priority);
508 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
509 gnutls_dh_set_prime_bits(session->sess, dh_bits);
510 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
511 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
512 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
515 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
517 Handshake(session, user);
520 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
522 issl_session* session = &sessions[user->GetFd()];
524 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
528 InitSession(user, true);
531 void OnStreamSocketConnect(StreamSocket* user)
533 InitSession(user, false);
536 void OnStreamSocketClose(StreamSocket* user)
538 CloseSession(&sessions[user->GetFd()]);
541 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
543 issl_session* session = &sessions[user->GetFd()];
547 CloseSession(session);
548 user->SetError("No SSL session");
552 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
554 // The handshake isn't finished, try to finish it.
556 if(!Handshake(session, user))
558 if (session->status != ISSL_CLOSING)
564 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
566 if (session->status == ISSL_HANDSHAKEN)
568 char* buffer = ServerInstance->GetReadBuffer();
569 size_t bufsiz = ServerInstance->Config->NetBufferSize;
570 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
573 recvq.append(buffer, ret);
576 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
582 user->SetError("Connection closed");
583 CloseSession(session);
588 user->SetError(gnutls_strerror(ret));
589 CloseSession(session);
593 else if (session->status == ISSL_CLOSING)
599 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
601 issl_session* session = &sessions[user->GetFd()];
605 CloseSession(session);
606 user->SetError("No SSL session");
610 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
612 // The handshake isn't finished, try to finish it.
613 Handshake(session, user);
614 if (session->status != ISSL_CLOSING)
621 if (session->status == ISSL_HANDSHAKEN)
623 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
625 if (ret == (int)sendq.length())
627 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
632 sendq = sendq.substr(ret);
633 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
636 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
638 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
643 user->SetError(gnutls_strerror(ret));
644 CloseSession(session);
652 bool Handshake(issl_session* session, StreamSocket* user)
654 int ret = gnutls_handshake(session->sess);
658 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
660 // Handshake needs resuming later, read() or write() would have blocked.
662 if(gnutls_record_get_direction(session->sess) == 0)
664 // gnutls_handshake() wants to read() again.
665 session->status = ISSL_HANDSHAKING_READ;
666 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
670 // gnutls_handshake() wants to write() again.
671 session->status = ISSL_HANDSHAKING_WRITE;
672 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
677 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
678 CloseSession(session);
679 session->status = ISSL_CLOSING;
686 // Change the seesion state
687 session->status = ISSL_HANDSHAKEN;
689 VerifyCertificate(session,user);
691 // Finish writing, if any left
692 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
698 void OnUserConnect(LocalUser* user)
700 if (user->eh.GetIOHook() == this)
702 if (sessions[user->eh.GetFd()].sess)
704 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
705 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->eh.GetFd()].sess));
706 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->eh.GetFd()].sess))).append("-");
707 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->eh.GetFd()].sess)));
708 if (cert->fingerprint.empty())
709 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
711 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
712 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
717 void CloseSession(issl_session* session)
721 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
722 gnutls_deinit(session->sess);
724 session->sess = NULL;
725 session->cert = NULL;
726 session->status = ISSL_NONE;
729 void VerifyCertificate(issl_session* session, StreamSocket* user)
731 if (!session->sess || !user)
735 const gnutls_datum_t* cert_list;
737 unsigned int cert_list_size;
738 gnutls_x509_crt_t cert;
740 unsigned char digest[MAXBUF];
741 size_t digest_size = sizeof(digest);
742 size_t name_size = sizeof(name);
743 ssl_cert* certinfo = new ssl_cert;
744 session->cert = certinfo;
746 /* This verification function uses the trusted CAs in the credentials
747 * structure. So you must have installed one or more CA certificates.
749 ret = gnutls_certificate_verify_peers2(session->sess, &status);
753 certinfo->error = std::string(gnutls_strerror(ret));
757 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
758 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
759 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
760 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
762 /* Up to here the process is the same for X.509 certificates and
763 * OpenPGP keys. From now on X.509 certificates are assumed. This can
764 * be easily extended to work with openpgp keys as well.
766 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
768 certinfo->error = "No X509 keys sent";
772 ret = gnutls_x509_crt_init(&cert);
775 certinfo->error = gnutls_strerror(ret);
780 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
781 if (cert_list == NULL)
783 certinfo->error = "No certificate was found";
784 goto info_done_dealloc;
787 /* This is not a real world example, since we only check the first
788 * certificate in the given chain.
791 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
794 certinfo->error = gnutls_strerror(ret);
795 goto info_done_dealloc;
798 gnutls_x509_crt_get_dn(cert, name, &name_size);
801 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
802 certinfo->issuer = name;
804 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
806 certinfo->error = gnutls_strerror(ret);
810 certinfo->fingerprint = irc::hex(digest, digest_size);
813 /* Beware here we do not check for errors.
815 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
817 certinfo->error = "Not activated, or expired certificate";
821 gnutls_x509_crt_deinit(cert);
824 void OnEvent(Event& ev)
826 if (starttls.enabled)
827 capHandler.HandleEvent(ev);
831 MODULE_INIT(ModuleSSLGnuTLS)