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