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