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