1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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>
21 #pragma comment(lib, "libgnutls-13.lib")
24 /* $ModDesc: Provides SSL support for clients */
25 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") */
26 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") */
27 /* $ModDep: transport.h */
28 /* $CopyInstall: conf/key.pem $(CONPATH) */
29 /* $CopyInstall: conf/cert.pem $(CONPATH) */
31 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
33 static gnutls_x509_crt_t x509_cert;
34 static gnutls_x509_privkey_t x509_key;
35 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
36 const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
38 st->type = GNUTLS_CRT_X509;
40 st->cert.x509 = &x509_cert;
41 st->key.x509 = x509_key;
47 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t user_wrap, void* buffer, size_t size)
49 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
50 if (user->GetEventMask() & FD_READ_WILL_BLOCK)
55 int rv = recv(user->GetFd(), buffer, size, 0);
57 ServerInstance->SE->ChangeEventMask(user, FD_READ_WILL_BLOCK);
61 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t user_wrap, const void* buffer, size_t size)
63 StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
64 if (user->GetEventMask() & FD_WRITE_WILL_BLOCK)
69 int rv = send(user->GetFd(), buffer, size, 0);
71 ServerInstance->SE->ChangeEventMask(user, FD_WRITE_WILL_BLOCK);
75 /** Represents an SSL user's extra data
77 class issl_session : public classbase
85 gnutls_session_t sess;
89 class CommandStartTLS : public Command
92 CommandStartTLS (Module* mod) : Command(mod, "STARTTLS")
94 works_before_reg = true;
97 CmdResult Handle (const std::vector<std::string> ¶meters, User *user)
99 /* changed from == REG_ALL to catch clients sending STARTTLS
100 * after NICK and USER but before OnUserConnect completes and
101 * give a proper error message (see bug #645) - dz
103 if (user->registered != REG_NONE)
105 user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration has started", user->nick.c_str());
109 if (!user->GetIOHook())
111 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
112 user->AddIOHook(creator);
113 creator->OnStreamSocketAccept(user, NULL, NULL);
116 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
123 class ModuleSSLGnuTLS : public Module
125 issl_session* sessions;
127 gnutls_certificate_credentials x509_cred;
128 gnutls_dh_params dh_params;
131 std::string certfile;
134 std::string sslports;
139 CommandStartTLS starttls;
141 GenericCap capHandler;
145 : starttls(this), capHandler(this, "tls")
147 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
149 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
151 gnutls_global_init(); // This must be called once in the program
152 gnutls_x509_crt_init(&x509_cert);
153 gnutls_x509_privkey_init(&x509_key);
156 // Needs the flag as it ignores a plain /rehash
157 OnModuleRehash(NULL,"ssl");
159 // Void return, guess we assume success
160 gnutls_certificate_set_dh_params(x509_cred, dh_params);
161 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnPostConnect,
162 I_OnEvent, I_OnHookIO };
163 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
165 ServerInstance->AddCommand(&starttls);
168 void OnRehash(User* user)
174 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
176 ListenSocketBase* port = ServerInstance->ports[i];
177 if (port->hook != "gnutls")
180 const std::string& portid = port->GetBindDesc();
181 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
183 if (port->type == "clients" && port->GetIP() != "127.0.0.1")
184 sslports.append(portid).append(";");
187 if (!sslports.empty())
188 sslports.erase(sslports.end() - 1);
191 void OnModuleRehash(User* user, const std::string ¶m)
200 cafile = Conf.ReadValue("gnutls", "cafile", 0);
201 crlfile = Conf.ReadValue("gnutls", "crlfile", 0);
202 certfile = Conf.ReadValue("gnutls", "certfile", 0);
203 keyfile = Conf.ReadValue("gnutls", "keyfile", 0);
204 dh_bits = Conf.ReadInteger("gnutls", "dhbits", 0, false);
206 // Set all the default values needed.
208 cafile = "conf/ca.pem";
211 crlfile = "conf/crl.pem";
213 if (certfile.empty())
214 certfile = "conf/cert.pem";
217 keyfile = "conf/key.pem";
219 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
226 // Deallocate the old credentials
227 gnutls_dh_params_deinit(dh_params);
228 gnutls_certificate_free_credentials(x509_cred);
233 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
234 ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
236 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
237 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));
239 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
240 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));
244 reader.LoadFile(certfile);
245 std::string cert_string = reader.Contents();
246 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), cert_string.length() };
248 reader.LoadFile(keyfile);
249 std::string key_string = reader.Contents();
250 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), key_string.length() };
252 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
253 if((ret = gnutls_x509_crt_import(x509_cert, &cert_datum, GNUTLS_X509_FMT_PEM)) < 0)
254 throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + std::string(gnutls_strerror(ret)));
256 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
257 throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
259 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_cert, 1, x509_key)) < 0)
260 throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
262 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
264 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
265 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
267 // This may be on a large (once a day or week) timer eventually.
271 void GenerateDHParams()
273 // Generate Diffie Hellman parameters - for use with DHE
274 // kx algorithms. These should be discarded and regenerated
275 // once a day, once a week or once a month. Depending on the
276 // security requirements.
280 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
281 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
286 gnutls_x509_crt_deinit(x509_cert);
287 gnutls_x509_privkey_deinit(x509_key);
288 gnutls_dh_params_deinit(dh_params);
289 gnutls_certificate_free_credentials(x509_cred);
290 gnutls_global_deinit();
291 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
295 void OnCleanup(int target_type, void* item)
297 if(target_type == TYPE_USER)
299 User* user = static_cast<User*>(item);
301 if (user->GetIOHook() == this)
303 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
304 // Potentially there could be multiple SSL modules loaded at once on different ports.
305 ServerInstance->Users->QuitUser(user, "SSL module unloading");
313 return Version("Provides SSL support for clients", VF_VENDOR, API_VERSION);
317 void On005Numeric(std::string &output)
319 if (!sslports.empty())
320 output.append(" SSL=" + sslports);
321 output.append(" STARTTLS");
324 void OnHookIO(StreamSocket* user, ListenSocketBase* lsb)
326 if (!user->GetIOHook() && lsb->hook == "gnutls")
328 /* Hook the user with our module */
329 user->AddIOHook(this);
333 void OnRequest(Request& request)
335 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
337 sslinfo->OnRequest(request);
341 void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
343 int fd = user->GetFd();
344 issl_session* session = &sessions[fd];
346 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
350 gnutls_init(&session->sess, GNUTLS_SERVER);
352 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
353 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
354 gnutls_dh_set_prime_bits(session->sess, dh_bits);
356 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
357 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
358 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
360 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
362 Handshake(session, user);
365 void OnStreamSocketConnect(StreamSocket* user)
367 issl_session* session = &sessions[user->GetFd()];
369 gnutls_init(&session->sess, GNUTLS_CLIENT);
371 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
372 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
373 gnutls_dh_set_prime_bits(session->sess, dh_bits);
374 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
375 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
376 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
378 Handshake(session, user);
381 void OnStreamSocketClose(StreamSocket* user)
383 CloseSession(&sessions[user->GetFd()]);
386 int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
388 issl_session* session = &sessions[user->GetFd()];
392 CloseSession(session);
393 user->SetError("No SSL session");
397 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
399 // The handshake isn't finished, try to finish it.
401 if(!Handshake(session, user))
403 if (session->status != ISSL_CLOSING)
405 user->SetError("Handshake Failed");
410 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
412 if (session->status == ISSL_HANDSHAKEN)
414 char* buffer = ServerInstance->GetReadBuffer();
415 size_t bufsiz = ServerInstance->Config->NetBufferSize;
416 int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
419 recvq.append(buffer, ret);
422 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
428 user->SetError("SSL Connection closed");
429 CloseSession(session);
434 user->SetError(gnutls_strerror(ret));
435 CloseSession(session);
439 else if (session->status == ISSL_CLOSING)
445 int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
447 issl_session* session = &sessions[user->GetFd()];
451 CloseSession(session);
452 user->SetError("No SSL session");
456 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
458 // The handshake isn't finished, try to finish it.
459 Handshake(session, user);
460 if (session->status != ISSL_CLOSING)
462 user->SetError("Handshake Failed");
468 if (session->status == ISSL_HANDSHAKEN)
470 ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
472 if (ret == (int)sendq.length())
474 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
479 sendq = sendq.substr(ret);
480 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
483 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
485 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
490 CloseSession(session);
491 user->SetError("SSL Connection closed");
496 user->SetError(gnutls_strerror(ret));
497 CloseSession(session);
505 bool Handshake(issl_session* session, StreamSocket* user)
507 int ret = gnutls_handshake(session->sess);
511 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
513 // Handshake needs resuming later, read() or write() would have blocked.
515 if(gnutls_record_get_direction(session->sess) == 0)
517 // gnutls_handshake() wants to read() again.
518 session->status = ISSL_HANDSHAKING_READ;
519 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
523 // gnutls_handshake() wants to write() again.
524 session->status = ISSL_HANDSHAKING_WRITE;
525 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
530 CloseSession(session);
531 session->status = ISSL_CLOSING;
538 // Change the seesion state
539 session->status = ISSL_HANDSHAKEN;
541 VerifyCertificate(session,user);
543 // Finish writing, if any left
544 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
550 void OnPostConnect(User* user)
552 // This occurs AFTER OnUserConnect so we can be sure the
553 // protocol module has propagated the NICK message.
554 if (user->GetIOHook() == this && (IS_LOCAL(user)))
556 if (sessions[user->GetFd()].sess)
558 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
559 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
560 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
561 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
566 void CloseSession(issl_session* session)
570 gnutls_bye(session->sess, GNUTLS_SHUT_WR);
571 gnutls_deinit(session->sess);
574 session->sess = NULL;
575 session->status = ISSL_NONE;
578 void VerifyCertificate(issl_session* session, Extensible* user)
580 if (!session->sess || !user)
583 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
588 const gnutls_datum_t* cert_list;
590 unsigned int cert_list_size;
591 gnutls_x509_crt_t cert;
593 unsigned char digest[MAXBUF];
594 size_t digest_size = sizeof(digest);
595 size_t name_size = sizeof(name);
596 ssl_cert* certinfo = new ssl_cert;
598 /* This verification function uses the trusted CAs in the credentials
599 * structure. So you must have installed one or more CA certificates.
601 ret = gnutls_certificate_verify_peers2(session->sess, &status);
605 certinfo->error = std::string(gnutls_strerror(ret));
609 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
610 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
611 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
612 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
614 /* Up to here the process is the same for X.509 certificates and
615 * OpenPGP keys. From now on X.509 certificates are assumed. This can
616 * be easily extended to work with openpgp keys as well.
618 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
620 certinfo->error = "No X509 keys sent";
624 ret = gnutls_x509_crt_init(&cert);
627 certinfo->error = gnutls_strerror(ret);
632 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
633 if (cert_list == NULL)
635 certinfo->error = "No certificate was found";
636 goto info_done_dealloc;
639 /* This is not a real world example, since we only check the first
640 * certificate in the given chain.
643 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
646 certinfo->error = gnutls_strerror(ret);
647 goto info_done_dealloc;
650 gnutls_x509_crt_get_dn(cert, name, &name_size);
653 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
654 certinfo->issuer = name;
656 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
658 certinfo->error = gnutls_strerror(ret);
662 certinfo->fingerprint = irc::hex(digest, digest_size);
665 /* Beware here we do not check for errors.
667 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
669 certinfo->error = "Not activated, or expired certificate";
673 gnutls_x509_crt_deinit(cert);
675 SSLCertSubmission(user, this, sslinfo, certinfo);
678 void OnEvent(Event& ev)
680 capHandler.HandleEvent(ev);
684 MODULE_INIT(ModuleSSLGnuTLS)