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