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