1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include <gnutls/gnutls.h>
16 #include <gnutls/x509.h>
22 #pragma comment(lib, "libgnutls-13.lib")
25 /* $ModDesc: Provides SSL support for clients */
26 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") */
27 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") */
29 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
31 static gnutls_x509_crt_t x509_cert;
32 static gnutls_x509_privkey_t x509_key;
33 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
34 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
36 st->type = GNUTLS_CRT_X509;
38 st->cert.x509 = &x509_cert;
39 st->key.x509 = x509_key;
45 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t user_wrap, void* buffer, size_t size)
47 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
48 if (user->GetEventMask() & FD_READ_WILL_BLOCK)
53 int rv = recv(user->GetFd(), buffer, size, 0);
55 ServerInstance->SE->ChangeEventMask(user, FD_READ_WILL_BLOCK);
59 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t user_wrap, const void* buffer, size_t size)
61 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
62 if (user->GetEventMask() & FD_WRITE_WILL_BLOCK)
67 int rv = send(user->GetFd(), buffer, size, 0);
69 ServerInstance->SE->ChangeEventMask(user, FD_WRITE_WILL_BLOCK);
73 class RandGen : public HandlerBase2<void, char*, size_t>
77 void Call(char* buffer, size_t len)
79 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
83 /** Represents an SSL user's extra data
88 gnutls_session_t sess;
90 reference<ssl_cert> cert;
91 issl_session() : sess(NULL) {}
94 class CommandStartTLS : public SplitCommand
98 CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
101 works_before_reg = true;
104 CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user)
108 user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
112 if (user->registered == REG_ALL)
114 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
118 if (!user->eh.GetIOHook())
120 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
121 /* We need to flush the write buffer prior to adding the IOHook,
122 * otherwise we'll be sending this line inside the SSL session - which
123 * won't start its handshake until the client gets this line. Currently,
124 * we assume the write will not block here; this is usually safe, as
125 * STARTTLS is sent very early on in the registration phase, where the
126 * user hasn't built up much sendq. Handling a blocked write here would
130 user->eh.AddIOHook(creator);
131 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
134 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
141 class ModuleSSLGnuTLS : public Module
143 issl_session* sessions;
145 gnutls_certificate_credentials x509_cred;
146 gnutls_dh_params dh_params;
147 gnutls_digest_algorithm_t hash;
149 std::string sslports;
155 CommandStartTLS starttls;
157 GenericCap capHandler;
158 ServiceProvider iohook;
162 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
164 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
166 gnutls_global_init(); // This must be called once in the program
167 gnutls_x509_crt_init(&x509_cert);
168 gnutls_x509_privkey_init(&x509_key);
175 // Needs the flag as it ignores a plain /rehash
176 OnModuleRehash(NULL,"ssl");
178 ServerInstance->GenRandom = &randhandler;
180 // Void return, guess we assume success
181 gnutls_certificate_set_dh_params(x509_cred, dh_params);
182 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
183 I_OnEvent, I_OnHookIO };
184 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
186 ServerInstance->Modules->AddService(iohook);
187 ServerInstance->AddCommand(&starttls);
190 void OnRehash(User* user)
194 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
195 starttls.enabled = Conf->getBool("starttls", true);
197 if (Conf->getBool("showports", true))
199 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
201 ListenSocket* port = ServerInstance->ports[i];
202 if (port->bind_tag->getString("ssl") != "gnutls")
205 const std::string& portid = port->bind_desc;
206 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
208 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
209 sslports.append(portid).append(";");
212 if (!sslports.empty())
213 sslports.erase(sslports.end() - 1);
217 void OnModuleRehash(User* user, const std::string ¶m)
223 std::string certfile;
228 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
230 cafile = Conf->getString("cafile", "conf/ca.pem");
231 crlfile = Conf->getString("crlfile", "conf/crl.pem");
232 certfile = Conf->getString("certfile", "conf/cert.pem");
233 keyfile = Conf->getString("keyfile", "conf/key.pem");
234 dh_bits = Conf->getInt("dhbits");
235 std::string hashname = Conf->getString("hash", "md5");
237 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
240 if (hashname == "md5")
241 hash = GNUTLS_DIG_MD5;
242 else if (hashname == "sha1")
243 hash = GNUTLS_DIG_SHA1;
245 throw ModuleException("Unknown hash type " + hashname);
252 // Deallocate the old credentials
253 gnutls_dh_params_deinit(dh_params);
254 gnutls_certificate_free_credentials(x509_cred);
259 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
260 ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
262 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
263 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));
265 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
266 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));
270 reader.LoadFile(certfile);
271 std::string cert_string = reader.Contents();
272 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), cert_string.length() };
274 reader.LoadFile(keyfile);
275 std::string key_string = reader.Contents();
276 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), key_string.length() };
278 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
279 if((ret = gnutls_x509_crt_import(x509_cert, &cert_datum, GNUTLS_X509_FMT_PEM)) < 0)
280 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + std::string(gnutls_strerror(ret)));
282 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
283 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
285 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_cert, 1, x509_key)) < 0)
286 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
288 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
290 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
291 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
293 // This may be on a large (once a day or week) timer eventually.
297 void GenerateDHParams()
299 // Generate Diffie Hellman parameters - for use with DHE
300 // kx algorithms. These should be discarded and regenerated
301 // once a day, once a week or once a month. Depending on the
302 // security requirements.
306 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
307 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
312 gnutls_x509_crt_deinit(x509_cert);
313 gnutls_x509_privkey_deinit(x509_key);
316 gnutls_dh_params_deinit(dh_params);
317 gnutls_certificate_free_credentials(x509_cred);
319 gnutls_global_deinit();
321 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
324 void OnCleanup(int target_type, void* item)
326 if(target_type == TYPE_USER)
328 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
330 if (user && user->eh.GetIOHook() == this)
332 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
333 // Potentially there could be multiple SSL modules loaded at once on different ports.
334 ServerInstance->Users->QuitUser(user, "SSL module unloading");
341 return Version("Provides SSL support for clients", VF_VENDOR);
345 void On005Numeric(std::string &output)
347 if (!sslports.empty())
348 output.append(" SSL=" + sslports);
349 if (starttls.enabled)
350 output.append(" STARTTLS");
353 void OnHookIO(StreamSocket* user, ListenSocket* lsb)
355 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
357 /* Hook the user with our module */
358 user->AddIOHook(this);
362 void OnRequest(Request& request)
364 if (strcmp("GET_SSL_CERT", request.id) == 0)
366 SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
367 int fd = req.sock->GetFd();
368 issl_session* session = &sessions[fd];
370 req.cert = session->cert;
374 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
376 int fd = user->GetFd();
377 issl_session* session = &sessions[fd];
379 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
383 gnutls_init(&session->sess, GNUTLS_SERVER);
385 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
386 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
387 gnutls_dh_set_prime_bits(session->sess, dh_bits);
389 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
390 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
391 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
393 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
395 Handshake(session, user);
398 void OnStreamSocketConnect(StreamSocket* user)
400 issl_session* session = &sessions[user->GetFd()];
402 gnutls_init(&session->sess, GNUTLS_CLIENT);
404 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
405 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
406 gnutls_dh_set_prime_bits(session->sess, dh_bits);
407 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
408 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
409 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
411 Handshake(session, user);
414 void OnStreamSocketClose(StreamSocket* user)
416 CloseSession(&sessions[user->GetFd()]);
419 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
421 issl_session* session = &sessions[user->GetFd()];
425 CloseSession(session);
426 user->SetError("No SSL session");
430 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
432 // The handshake isn't finished, try to finish it.
434 if(!Handshake(session, user))
436 if (session->status != ISSL_CLOSING)
442 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
444 if (session->status == ISSL_HANDSHAKEN)
446 char* buffer = ServerInstance->GetReadBuffer();
447 size_t bufsiz = ServerInstance->Config->NetBufferSize;
448 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
451 recvq.append(buffer, ret);
454 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
460 user->SetError("SSL Connection closed");
461 CloseSession(session);
466 user->SetError(gnutls_strerror(ret));
467 CloseSession(session);
471 else if (session->status == ISSL_CLOSING)
477 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
479 issl_session* session = &sessions[user->GetFd()];
483 CloseSession(session);
484 user->SetError("No SSL session");
488 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
490 // The handshake isn't finished, try to finish it.
491 Handshake(session, user);
492 if (session->status != ISSL_CLOSING)
499 if (session->status == ISSL_HANDSHAKEN)
501 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
503 if (ret == (int)sendq.length())
505 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
510 sendq = sendq.substr(ret);
511 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
514 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
516 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
521 CloseSession(session);
522 user->SetError("SSL Connection closed");
527 user->SetError(gnutls_strerror(ret));
528 CloseSession(session);
536 bool Handshake(issl_session* session, StreamSocket* user)
538 int ret = gnutls_handshake(session->sess);
542 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
544 // Handshake needs resuming later, read() or write() would have blocked.
546 if(gnutls_record_get_direction(session->sess) == 0)
548 // gnutls_handshake() wants to read() again.
549 session->status = ISSL_HANDSHAKING_READ;
550 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
554 // gnutls_handshake() wants to write() again.
555 session->status = ISSL_HANDSHAKING_WRITE;
556 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
561 user->SetError(std::string("Handshake Failed - ") + gnutls_strerror(ret));
562 CloseSession(session);
563 session->status = ISSL_CLOSING;
570 // Change the seesion state
571 session->status = ISSL_HANDSHAKEN;
573 VerifyCertificate(session,user);
575 // Finish writing, if any left
576 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
582 void OnUserConnect(LocalUser* user)
584 if (user->eh.GetIOHook() == this)
586 if (sessions[user->eh.GetFd()].sess)
588 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
589 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->eh.GetFd()].sess));
590 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->eh.GetFd()].sess))).append("-");
591 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->eh.GetFd()].sess)));
592 if (cert->fingerprint.empty())
593 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
595 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
596 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
601 void CloseSession(issl_session* session)
605 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
606 gnutls_deinit(session->sess);
608 session->sess = NULL;
609 session->cert = NULL;
610 session->status = ISSL_NONE;
613 void VerifyCertificate(issl_session* session, StreamSocket* user)
615 if (!session->sess || !user || session->cert)
619 const gnutls_datum_t* cert_list;
621 unsigned int cert_list_size;
622 gnutls_x509_crt_t cert;
624 unsigned char digest[MAXBUF];
625 size_t digest_size = sizeof(digest);
626 size_t name_size = sizeof(name);
627 ssl_cert* certinfo = new ssl_cert;
628 session->cert = certinfo;
630 /* This verification function uses the trusted CAs in the credentials
631 * structure. So you must have installed one or more CA certificates.
633 ret = gnutls_certificate_verify_peers2(session->sess, &status);
637 certinfo->error = std::string(gnutls_strerror(ret));
641 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
642 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
643 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
644 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
646 /* Up to here the process is the same for X.509 certificates and
647 * OpenPGP keys. From now on X.509 certificates are assumed. This can
648 * be easily extended to work with openpgp keys as well.
650 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
652 certinfo->error = "No X509 keys sent";
656 ret = gnutls_x509_crt_init(&cert);
659 certinfo->error = gnutls_strerror(ret);
664 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
665 if (cert_list == NULL)
667 certinfo->error = "No certificate was found";
668 goto info_done_dealloc;
671 /* This is not a real world example, since we only check the first
672 * certificate in the given chain.
675 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
678 certinfo->error = gnutls_strerror(ret);
679 goto info_done_dealloc;
682 gnutls_x509_crt_get_dn(cert, name, &name_size);
685 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
686 certinfo->issuer = name;
688 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
690 certinfo->error = gnutls_strerror(ret);
694 certinfo->fingerprint = irc::hex(digest, digest_size);
697 /* Beware here we do not check for errors.
699 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
701 certinfo->error = "Not activated, or expired certificate";
705 gnutls_x509_crt_deinit(cert);
708 void OnEvent(Event& ev)
710 if (starttls.enabled)
711 capHandler.HandleEvent(ev);
715 MODULE_INIT(ModuleSSLGnuTLS)