]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Deduplicate hex string creation code
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_gnutls.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
9  *
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.
13  *
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
17  * details.
18  *
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/>.
21  */
22
23
24 #include "inspircd.h"
25 #include <gcrypt.h>
26 #include <gnutls/gnutls.h>
27 #include <gnutls/x509.h>
28 #include "modules/ssl.h"
29 #include "modules/cap.h"
30
31 #ifdef _WIN32
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")
40 #endif
41
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") */
45 /* $NoPedantic */
46
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
50 #endif
51
52 #if(GNUTLS_VERSION_MAJOR < 2)
53 typedef gnutls_certificate_credentials_t gnutls_certificate_credentials;
54 typedef gnutls_dh_params_t gnutls_dh_params;
55 #endif
56
57 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
58
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) {
64
65         st->type = GNUTLS_CRT_X509;
66 #else
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;
71 #endif
72         st->ncerts = x509_certs.size();
73         st->cert.x509 = &x509_certs[0];
74         st->key.x509 = x509_key;
75         st->deinit_all = 0;
76
77         return 0;
78 }
79
80 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t user_wrap, void* buffer, size_t size)
81 {
82         StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
83         if (user->GetEventMask() & FD_READ_WILL_BLOCK)
84         {
85                 errno = EAGAIN;
86                 return -1;
87         }
88         int rv = ServerInstance->SE->Recv(user, reinterpret_cast<char *>(buffer), size, 0);
89         if (rv < 0)
90         {
91                 /* On Windows we need to set errno for gnutls */
92                 if (SocketEngine::IgnoreError())
93                         errno = EAGAIN;
94         }
95         if (rv < (int)size)
96                 ServerInstance->SE->ChangeEventMask(user, FD_READ_WILL_BLOCK);
97         return rv;
98 }
99
100 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t user_wrap, const void* buffer, size_t size)
101 {
102         StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
103         if (user->GetEventMask() & FD_WRITE_WILL_BLOCK)
104         {
105                 errno = EAGAIN;
106                 return -1;
107         }
108         int rv = ServerInstance->SE->Send(user, reinterpret_cast<const char *>(buffer), size, 0);
109         if (rv < 0)
110         {
111                 /* On Windows we need to set errno for gnutls */
112                 if (SocketEngine::IgnoreError())
113                         errno = EAGAIN;
114         }
115         if (rv < (int)size)
116                 ServerInstance->SE->ChangeEventMask(user, FD_WRITE_WILL_BLOCK);
117         return rv;
118 }
119
120 class RandGen : public HandlerBase2<void, char*, size_t>
121 {
122  public:
123         RandGen() {}
124         void Call(char* buffer, size_t len)
125         {
126                 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
127         }
128 };
129
130 /** Represents an SSL user's extra data
131  */
132 class issl_session
133 {
134 public:
135         gnutls_session_t sess;
136         issl_status status;
137         reference<ssl_cert> cert;
138         issl_session() : sess(NULL) {}
139 };
140
141 class CommandStartTLS : public SplitCommand
142 {
143  public:
144         bool enabled;
145         CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
146         {
147                 enabled = true;
148                 works_before_reg = true;
149         }
150
151         CmdResult HandleLocal(const std::vector<std::string> &parameters, LocalUser *user)
152         {
153                 if (!enabled)
154                 {
155                         user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
156                         return CMD_FAILURE;
157                 }
158
159                 if (user->registered == REG_ALL)
160                 {
161                         user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
162                 }
163                 else
164                 {
165                         if (!user->eh.GetIOHook())
166                         {
167                                 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
168                                 /* We need to flush the write buffer prior to adding the IOHook,
169                                  * otherwise we'll be sending this line inside the SSL session - which
170                                  * won't start its handshake until the client gets this line. Currently,
171                                  * we assume the write will not block here; this is usually safe, as
172                                  * STARTTLS is sent very early on in the registration phase, where the
173                                  * user hasn't built up much sendq. Handling a blocked write here would
174                                  * be very annoying.
175                                  */
176                                 user->eh.DoWrite();
177                                 user->eh.AddIOHook(creator);
178                                 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
179                         }
180                         else
181                                 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
182                 }
183
184                 return CMD_FAILURE;
185         }
186 };
187
188 class ModuleSSLGnuTLS : public Module
189 {
190         issl_session* sessions;
191
192         gnutls_certificate_credentials_t x509_cred;
193         gnutls_dh_params_t dh_params;
194         gnutls_digest_algorithm_t hash;
195         #ifdef GNUTLS_NEW_PRIO_API
196         gnutls_priority_t priority;
197         #endif
198
199         std::string sslports;
200         int dh_bits;
201
202         bool cred_alloc;
203         bool dh_alloc;
204
205         RandGen randhandler;
206         CommandStartTLS starttls;
207
208         GenericCap capHandler;
209         ServiceProvider iohook;
210
211         inline static const char* UnknownIfNULL(const char* str)
212         {
213                 return str ? str : "UNKNOWN";
214         }
215
216  public:
217         ModuleSSLGnuTLS()
218                 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
219         {
220                 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
221
222                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
223
224                 gnutls_global_init(); // This must be called once in the program
225                 gnutls_x509_privkey_init(&x509_key);
226
227                 #ifdef GNUTLS_NEW_PRIO_API
228                 // Init this here so it's always initialized, avoids an extra boolean
229                 gnutls_priority_init(&priority, "NORMAL", NULL);
230                 #endif
231
232                 cred_alloc = false;
233                 dh_alloc = false;
234         }
235
236         void init() CXX11_OVERRIDE
237         {
238                 // Needs the flag as it ignores a plain /rehash
239                 OnModuleRehash(NULL,"ssl");
240
241                 ServerInstance->GenRandom = &randhandler;
242
243                 // Void return, guess we assume success
244                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
245                 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
246                         I_OnEvent, I_OnHookIO };
247                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
248
249                 ServerInstance->Modules->AddService(iohook);
250                 ServerInstance->Modules->AddService(starttls);
251         }
252
253         void OnRehash(User* user) CXX11_OVERRIDE
254         {
255                 sslports.clear();
256
257                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
258                 starttls.enabled = Conf->getBool("starttls", true);
259
260                 if (Conf->getBool("showports", true))
261                 {
262                         sslports = Conf->getString("advertisedports");
263                         if (!sslports.empty())
264                                 return;
265
266                         for (size_t i = 0; i < ServerInstance->ports.size(); i++)
267                         {
268                                 ListenSocket* port = ServerInstance->ports[i];
269                                 if (port->bind_tag->getString("ssl") != "gnutls")
270                                         continue;
271
272                                 const std::string& portid = port->bind_desc;
273                                 ServerInstance->Logs->Log("m_ssl_gnutls", LOG_DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
274
275                                 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
276                                 {
277                                         /*
278                                          * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
279                                          * the IP:port in ISUPPORT.
280                                          *
281                                          * We used to advertise all ports seperated by a ';' char that matched the above criteria,
282                                          * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
283                                          * To solve this by default we now only display the first IP:port found and let the user
284                                          * configure the exact value for the 005 token, if necessary.
285                                          */
286                                         sslports = portid;
287                                         break;
288                                 }
289                         }
290                 }
291         }
292
293         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
294         {
295                 if(param != "ssl")
296                         return;
297
298                 std::string keyfile;
299                 std::string certfile;
300                 std::string cafile;
301                 std::string crlfile;
302                 OnRehash(user);
303
304                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
305
306                 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
307                 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
308                 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
309                 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
310                 dh_bits = Conf->getInt("dhbits");
311                 std::string hashname = Conf->getString("hash", "md5");
312
313                 // The GnuTLS manual states that the gnutls_set_default_priority()
314                 // call we used previously when initializing the session is the same
315                 // as setting the "NORMAL" priority string.
316                 // Thus if the setting below is not in the config we will behave exactly
317                 // the same as before, when the priority setting wasn't available.
318                 std::string priorities = Conf->getString("priority", "NORMAL");
319
320                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
321                         dh_bits = 1024;
322
323                 if (hashname == "md5")
324                         hash = GNUTLS_DIG_MD5;
325                 else if (hashname == "sha1")
326                         hash = GNUTLS_DIG_SHA1;
327                 else
328                         throw ModuleException("Unknown hash type " + hashname);
329
330
331                 int ret;
332
333                 if (dh_alloc)
334                 {
335                         gnutls_dh_params_deinit(dh_params);
336                         dh_alloc = false;
337                         dh_params = NULL;
338                 }
339
340                 if (cred_alloc)
341                 {
342                         // Deallocate the old credentials
343                         gnutls_certificate_free_credentials(x509_cred);
344
345                         for(unsigned int i=0; i < x509_certs.size(); i++)
346                                 gnutls_x509_crt_deinit(x509_certs[i]);
347                         x509_certs.clear();
348                 }
349
350                 ret = gnutls_certificate_allocate_credentials(&x509_cred);
351                 cred_alloc = (ret >= 0);
352                 if (!cred_alloc)
353                         ServerInstance->Logs->Log("m_ssl_gnutls",LOG_DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
354
355                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
356                         ServerInstance->Logs->Log("m_ssl_gnutls",LOG_DEBUG, "m_ssl_gnutls.so: Failed to set X.509 trust file '%s': %s", cafile.c_str(), gnutls_strerror(ret));
357
358                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
359                         ServerInstance->Logs->Log("m_ssl_gnutls",LOG_DEBUG, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret));
360
361                 FileReader reader;
362
363                 reader.LoadFile(certfile);
364                 std::string cert_string = reader.Contents();
365                 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
366
367                 reader.LoadFile(keyfile);
368                 std::string key_string = reader.Contents();
369                 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
370
371                 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
372                 unsigned int certcount = 3;
373                 x509_certs.resize(certcount);
374                 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
375                 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
376                 {
377                         // 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
378                         x509_certs.resize(certcount);
379                         ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
380                 }
381
382                 if (ret <= 0)
383                 {
384                         // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later
385                         x509_certs.clear();
386                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read"));
387                 }
388                 x509_certs.resize(ret);
389
390                 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
391                         throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
392
393                 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
394                         throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
395
396                 #ifdef GNUTLS_NEW_PRIO_API
397                 // It's safe to call this every time as we cannot have this uninitialized, see constructor and below.
398                 gnutls_priority_deinit(priority);
399
400                 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
401                 // If the user did not supply anything then the string is already set to "NORMAL"
402                 const char* priocstr = priorities.c_str();
403                 const char* prioerror;
404
405                 if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0)
406                 {
407                         // gnutls did not understand the user supplied string, log and fall back to the default priorities
408                         ServerInstance->Logs->Log("m_ssl_gnutls",LOG_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));
409                         gnutls_priority_init(&priority, "NORMAL", NULL);
410                 }
411
412                 #else
413                 if (priorities != "NORMAL")
414                         ServerInstance->Logs->Log("m_ssl_gnutls",LOG_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.");
415                 #endif
416
417                 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
418                 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
419                 #else
420                 gnutls_certificate_set_retrieve_function (x509_cred, cert_callback);
421                 #endif
422                 ret = gnutls_dh_params_init(&dh_params);
423                 dh_alloc = (ret >= 0);
424                 if (!dh_alloc)
425                 {
426                         ServerInstance->Logs->Log("m_ssl_gnutls", LOG_DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
427                         return;
428                 }
429
430                 std::string dhfile = Conf->getString("dhfile");
431                 if (!dhfile.empty())
432                 {
433                         // Try to load DH params from file
434                         reader.LoadFile(dhfile);
435                         std::string dhstring = reader.Contents();
436                         gnutls_datum_t dh_datum = { (unsigned char*)dhstring.data(), static_cast<unsigned int>(dhstring.length()) };
437
438                         if ((ret = gnutls_dh_params_import_pkcs3(dh_params, &dh_datum, GNUTLS_X509_FMT_PEM)) < 0)
439                         {
440                                 // File unreadable or GnuTLS was unhappy with the contents, generate the DH primes now
441                                 ServerInstance->Logs->Log("m_ssl_gnutls", LOG_DEFAULT, "m_ssl_gnutls.so: Generating DH parameters because I failed to load them from file '%s': %s", dhfile.c_str(), gnutls_strerror(ret));
442                                 GenerateDHParams();
443                         }
444                 }
445                 else
446                 {
447                         GenerateDHParams();
448                 }
449         }
450
451         void GenerateDHParams()
452         {
453                 // Generate Diffie Hellman parameters - for use with DHE
454                 // kx algorithms. These should be discarded and regenerated
455                 // once a day, once a week or once a month. Depending on the
456                 // security requirements.
457
458                 if (!dh_alloc)
459                         return;
460
461                 int ret;
462
463                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
464                         ServerInstance->Logs->Log("m_ssl_gnutls",LOG_DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
465         }
466
467         ~ModuleSSLGnuTLS()
468         {
469                 for(unsigned int i=0; i < x509_certs.size(); i++)
470                         gnutls_x509_crt_deinit(x509_certs[i]);
471
472                 gnutls_x509_privkey_deinit(x509_key);
473                 #ifdef GNUTLS_NEW_PRIO_API
474                 gnutls_priority_deinit(priority);
475                 #endif
476
477                 if (dh_alloc)
478                         gnutls_dh_params_deinit(dh_params);
479                 if (cred_alloc)
480                         gnutls_certificate_free_credentials(x509_cred);
481
482                 gnutls_global_deinit();
483                 delete[] sessions;
484                 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
485         }
486
487         void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
488         {
489                 if(target_type == TYPE_USER)
490                 {
491                         LocalUser* user = IS_LOCAL(static_cast<User*>(item));
492
493                         if (user && user->eh.GetIOHook() == this)
494                         {
495                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
496                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
497                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
498                         }
499                 }
500         }
501
502         Version GetVersion() CXX11_OVERRIDE
503         {
504                 return Version("Provides SSL support for clients", VF_VENDOR);
505         }
506
507         void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
508         {
509                 if (!sslports.empty())
510                         tokens["SSL"] = sslports;
511                 if (starttls.enabled)
512                         tokens["STARTTLS"];
513         }
514
515         void OnHookIO(StreamSocket* user, ListenSocket* lsb) CXX11_OVERRIDE
516         {
517                 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
518                 {
519                         /* Hook the user with our module */
520                         user->AddIOHook(this);
521                 }
522         }
523
524         void OnRequest(Request& request) CXX11_OVERRIDE
525         {
526                 if (strcmp("GET_SSL_CERT", request.id) == 0)
527                 {
528                         SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
529                         int fd = req.sock->GetFd();
530                         issl_session* session = &sessions[fd];
531
532                         req.cert = session->cert;
533                 }
534         }
535
536         void InitSession(StreamSocket* user, bool me_server)
537         {
538                 issl_session* session = &sessions[user->GetFd()];
539
540                 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
541
542                 #ifdef GNUTLS_NEW_PRIO_API
543                 gnutls_priority_set(session->sess, priority);
544                 #endif
545                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
546                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
547                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
548                 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
549                 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
550
551                 if (me_server)
552                         gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
553
554                 Handshake(session, user);
555         }
556
557         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
558         {
559                 issl_session* session = &sessions[user->GetFd()];
560
561                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
562                 if (session->sess)
563                         return;
564
565                 InitSession(user, true);
566         }
567
568         void OnStreamSocketConnect(StreamSocket* user) CXX11_OVERRIDE
569         {
570                 InitSession(user, false);
571         }
572
573         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
574         {
575                 CloseSession(&sessions[user->GetFd()]);
576         }
577
578         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
579         {
580                 issl_session* session = &sessions[user->GetFd()];
581
582                 if (!session->sess)
583                 {
584                         CloseSession(session);
585                         user->SetError("No SSL session");
586                         return -1;
587                 }
588
589                 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
590                 {
591                         // The handshake isn't finished, try to finish it.
592
593                         if(!Handshake(session, user))
594                         {
595                                 if (session->status != ISSL_CLOSING)
596                                         return 0;
597                                 return -1;
598                         }
599                 }
600
601                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
602
603                 if (session->status == ISSL_HANDSHAKEN)
604                 {
605                         char* buffer = ServerInstance->GetReadBuffer();
606                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
607                         int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
608                         if (ret > 0)
609                         {
610                                 recvq.append(buffer, ret);
611                                 return 1;
612                         }
613                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
614                         {
615                                 return 0;
616                         }
617                         else if (ret == 0)
618                         {
619                                 user->SetError("Connection closed");
620                                 CloseSession(session);
621                                 return -1;
622                         }
623                         else
624                         {
625                                 user->SetError(gnutls_strerror(ret));
626                                 CloseSession(session);
627                                 return -1;
628                         }
629                 }
630                 else if (session->status == ISSL_CLOSING)
631                         return -1;
632
633                 return 0;
634         }
635
636         int OnStreamSocketWrite(StreamSocket* user, std::string& sendq) CXX11_OVERRIDE
637         {
638                 issl_session* session = &sessions[user->GetFd()];
639
640                 if (!session->sess)
641                 {
642                         CloseSession(session);
643                         user->SetError("No SSL session");
644                         return -1;
645                 }
646
647                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
648                 {
649                         // The handshake isn't finished, try to finish it.
650                         Handshake(session, user);
651                         if (session->status != ISSL_CLOSING)
652                                 return 0;
653                         return -1;
654                 }
655
656                 int ret = 0;
657
658                 if (session->status == ISSL_HANDSHAKEN)
659                 {
660                         ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
661
662                         if (ret == (int)sendq.length())
663                         {
664                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
665                                 return 1;
666                         }
667                         else if (ret > 0)
668                         {
669                                 sendq = sendq.substr(ret);
670                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
671                                 return 0;
672                         }
673                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
674                         {
675                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
676                                 return 0;
677                         }
678                         else // (ret < 0)
679                         {
680                                 user->SetError(gnutls_strerror(ret));
681                                 CloseSession(session);
682                                 return -1;
683                         }
684                 }
685
686                 return 0;
687         }
688
689         bool Handshake(issl_session* session, StreamSocket* user)
690         {
691                 int ret = gnutls_handshake(session->sess);
692
693                 if (ret < 0)
694                 {
695                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
696                         {
697                                 // Handshake needs resuming later, read() or write() would have blocked.
698
699                                 if(gnutls_record_get_direction(session->sess) == 0)
700                                 {
701                                         // gnutls_handshake() wants to read() again.
702                                         session->status = ISSL_HANDSHAKING_READ;
703                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
704                                 }
705                                 else
706                                 {
707                                         // gnutls_handshake() wants to write() again.
708                                         session->status = ISSL_HANDSHAKING_WRITE;
709                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
710                                 }
711                         }
712                         else
713                         {
714                                 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
715                                 CloseSession(session);
716                                 session->status = ISSL_CLOSING;
717                         }
718
719                         return false;
720                 }
721                 else
722                 {
723                         // Change the seesion state
724                         session->status = ISSL_HANDSHAKEN;
725
726                         VerifyCertificate(session,user);
727
728                         // Finish writing, if any left
729                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
730
731                         return true;
732                 }
733         }
734
735         void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
736         {
737                 if (user->eh.GetIOHook() == this)
738                 {
739                         if (sessions[user->eh.GetFd()].sess)
740                         {
741                                 const gnutls_session_t& sess = sessions[user->eh.GetFd()].sess;
742                                 std::string cipher = UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)));
743                                 cipher.append("-").append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).append("-");
744                                 cipher.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess))));
745
746                                 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
747                                 if (cert->fingerprint.empty())
748                                         user->WriteNotice("*** You are connected using SSL cipher '" + cipher + "'");
749                                 else
750                                         user->WriteNotice("*** You are connected using SSL cipher '" + cipher +
751                                                 "' and your SSL fingerprint is " + cert->fingerprint);
752                         }
753                 }
754         }
755
756         void CloseSession(issl_session* session)
757         {
758                 if (session->sess)
759                 {
760                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
761                         gnutls_deinit(session->sess);
762                 }
763                 session->sess = NULL;
764                 session->cert = NULL;
765                 session->status = ISSL_NONE;
766         }
767
768         void VerifyCertificate(issl_session* session, StreamSocket* user)
769         {
770                 if (!session->sess || !user)
771                         return;
772
773                 unsigned int status;
774                 const gnutls_datum_t* cert_list;
775                 int ret;
776                 unsigned int cert_list_size;
777                 gnutls_x509_crt_t cert;
778                 char name[MAXBUF];
779                 unsigned char digest[MAXBUF];
780                 size_t digest_size = sizeof(digest);
781                 size_t name_size = sizeof(name);
782                 ssl_cert* certinfo = new ssl_cert;
783                 session->cert = certinfo;
784
785                 /* This verification function uses the trusted CAs in the credentials
786                  * structure. So you must have installed one or more CA certificates.
787                  */
788                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
789
790                 if (ret < 0)
791                 {
792                         certinfo->error = std::string(gnutls_strerror(ret));
793                         return;
794                 }
795
796                 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
797                 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
798                 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
799                 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
800
801                 /* Up to here the process is the same for X.509 certificates and
802                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
803                  * be easily extended to work with openpgp keys as well.
804                  */
805                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
806                 {
807                         certinfo->error = "No X509 keys sent";
808                         return;
809                 }
810
811                 ret = gnutls_x509_crt_init(&cert);
812                 if (ret < 0)
813                 {
814                         certinfo->error = gnutls_strerror(ret);
815                         return;
816                 }
817
818                 cert_list_size = 0;
819                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
820                 if (cert_list == NULL)
821                 {
822                         certinfo->error = "No certificate was found";
823                         goto info_done_dealloc;
824                 }
825
826                 /* This is not a real world example, since we only check the first
827                  * certificate in the given chain.
828                  */
829
830                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
831                 if (ret < 0)
832                 {
833                         certinfo->error = gnutls_strerror(ret);
834                         goto info_done_dealloc;
835                 }
836
837                 gnutls_x509_crt_get_dn(cert, name, &name_size);
838                 certinfo->dn = name;
839
840                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
841                 certinfo->issuer = name;
842
843                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
844                 {
845                         certinfo->error = gnutls_strerror(ret);
846                 }
847                 else
848                 {
849                         certinfo->fingerprint = BinToHex(digest, digest_size);
850                 }
851
852                 /* Beware here we do not check for errors.
853                  */
854                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
855                 {
856                         certinfo->error = "Not activated, or expired certificate";
857                 }
858
859 info_done_dealloc:
860                 gnutls_x509_crt_deinit(cert);
861         }
862
863         void OnEvent(Event& ev) CXX11_OVERRIDE
864         {
865                 if (starttls.enabled)
866                         capHandler.HandleEvent(ev);
867         }
868 };
869
870 MODULE_INIT(ModuleSSLGnuTLS)