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