]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Create SSLIOHook interface that provides GetCertificate()
[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 SSLIOHook
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                 : SSLIOHook(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         ssl_cert* GetCertificate(StreamSocket* sock) CXX11_OVERRIDE
505         {
506                 int fd = sock->GetFd();
507                 issl_session* session = &sessions[fd];
508                 return session->cert;
509         }
510
511         void TellCiphersAndFingerprint(LocalUser* user)
512         {
513                 const gnutls_session_t& sess = sessions[user->eh.GetFd()].sess;
514                 if (sess)
515                 {
516                         std::string text = "*** You are connected using SSL cipher '";
517
518                         text += UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)));
519                         text.append("-").append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).append("-");
520                         text.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess)))).append("'");
521
522                         ssl_cert* cert = sessions[user->eh.GetFd()].cert;
523                         if (!cert->fingerprint.empty())
524                                 text += " and your SSL fingerprint is " + cert->fingerprint;
525
526                         user->WriteNotice(text);
527                 }
528         }
529 };
530
531 class CommandStartTLS : public SplitCommand
532 {
533         IOHook& hook;
534
535  public:
536         bool enabled;
537         CommandStartTLS(Module* mod, IOHook& Hook)
538                 : SplitCommand(mod, "STARTTLS")
539                 , hook(Hook)
540         {
541                 enabled = true;
542                 works_before_reg = true;
543         }
544
545         CmdResult HandleLocal(const std::vector<std::string> &parameters, LocalUser *user)
546         {
547                 if (!enabled)
548                 {
549                         user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
550                         return CMD_FAILURE;
551                 }
552
553                 if (user->registered == REG_ALL)
554                 {
555                         user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
556                 }
557                 else
558                 {
559                         if (!user->eh.GetIOHook())
560                         {
561                                 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
562                                 /* We need to flush the write buffer prior to adding the IOHook,
563                                  * otherwise we'll be sending this line inside the SSL session - which
564                                  * won't start its handshake until the client gets this line. Currently,
565                                  * we assume the write will not block here; this is usually safe, as
566                                  * STARTTLS is sent very early on in the registration phase, where the
567                                  * user hasn't built up much sendq. Handling a blocked write here would
568                                  * be very annoying.
569                                  */
570                                 user->eh.DoWrite();
571                                 user->eh.AddIOHook(&hook);
572                                 hook.OnStreamSocketAccept(&user->eh, NULL, NULL);
573                         }
574                         else
575                                 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
576                 }
577
578                 return CMD_FAILURE;
579         }
580 };
581
582 class ModuleSSLGnuTLS : public Module
583 {
584         GnuTLSIOHook iohook;
585
586         gnutls_dh_params_t dh_params;
587
588         std::string sslports;
589
590         bool cred_alloc;
591         bool dh_alloc;
592
593         RandGen randhandler;
594         CommandStartTLS starttls;
595
596         GenericCap capHandler;
597
598  public:
599         ModuleSSLGnuTLS()
600                 : iohook(this), starttls(this, iohook), capHandler(this, "tls")
601         {
602                 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
603
604                 gnutls_global_init(); // This must be called once in the program
605                 gnutls_x509_privkey_init(&x509_key);
606
607                 #ifdef GNUTLS_NEW_PRIO_API
608                 // Init this here so it's always initialized, avoids an extra boolean
609                 gnutls_priority_init(&iohook.priority, "NORMAL", NULL);
610                 #endif
611
612                 cred_alloc = false;
613                 dh_alloc = false;
614         }
615
616         void init() CXX11_OVERRIDE
617         {
618                 // Needs the flag as it ignores a plain /rehash
619                 OnModuleRehash(NULL,"ssl");
620
621                 ServerInstance->GenRandom = &randhandler;
622
623                 // Void return, guess we assume success
624                 gnutls_certificate_set_dh_params(iohook.x509_cred, dh_params);
625                 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
626                         I_OnEvent, I_OnHookIO };
627                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
628
629                 ServerInstance->Modules->AddService(iohook);
630                 ServerInstance->Modules->AddService(starttls);
631         }
632
633         void OnRehash(User* user) CXX11_OVERRIDE
634         {
635                 sslports.clear();
636
637                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
638                 starttls.enabled = Conf->getBool("starttls", true);
639
640                 if (Conf->getBool("showports", true))
641                 {
642                         sslports = Conf->getString("advertisedports");
643                         if (!sslports.empty())
644                                 return;
645
646                         for (size_t i = 0; i < ServerInstance->ports.size(); i++)
647                         {
648                                 ListenSocket* port = ServerInstance->ports[i];
649                                 if (port->bind_tag->getString("ssl") != "gnutls")
650                                         continue;
651
652                                 const std::string& portid = port->bind_desc;
653                                 ServerInstance->Logs->Log("m_ssl_gnutls", LOG_DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
654
655                                 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
656                                 {
657                                         /*
658                                          * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
659                                          * the IP:port in ISUPPORT.
660                                          *
661                                          * We used to advertise all ports seperated by a ';' char that matched the above criteria,
662                                          * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
663                                          * To solve this by default we now only display the first IP:port found and let the user
664                                          * configure the exact value for the 005 token, if necessary.
665                                          */
666                                         sslports = portid;
667                                         break;
668                                 }
669                         }
670                 }
671         }
672
673         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
674         {
675                 if(param != "ssl")
676                         return;
677
678                 std::string keyfile;
679                 std::string certfile;
680                 std::string cafile;
681                 std::string crlfile;
682                 OnRehash(user);
683
684                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
685
686                 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
687                 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
688                 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
689                 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
690                 int dh_bits = Conf->getInt("dhbits");
691                 std::string hashname = Conf->getString("hash", "md5");
692
693                 // The GnuTLS manual states that the gnutls_set_default_priority()
694                 // call we used previously when initializing the session is the same
695                 // as setting the "NORMAL" priority string.
696                 // Thus if the setting below is not in the config we will behave exactly
697                 // the same as before, when the priority setting wasn't available.
698                 std::string priorities = Conf->getString("priority", "NORMAL");
699
700                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
701                         dh_bits = 1024;
702
703                 iohook.dh_bits = dh_bits;
704
705                 if (hashname == "md5")
706                         iohook.hash = GNUTLS_DIG_MD5;
707                 else if (hashname == "sha1")
708                         iohook.hash = GNUTLS_DIG_SHA1;
709                 else
710                         throw ModuleException("Unknown hash type " + hashname);
711
712
713                 int ret;
714
715                 if (dh_alloc)
716                 {
717                         gnutls_dh_params_deinit(dh_params);
718                         dh_alloc = false;
719                         dh_params = NULL;
720                 }
721
722                 if (cred_alloc)
723                 {
724                         // Deallocate the old credentials
725                         gnutls_certificate_free_credentials(iohook.x509_cred);
726
727                         for(unsigned int i=0; i < x509_certs.size(); i++)
728                                 gnutls_x509_crt_deinit(x509_certs[i]);
729                         x509_certs.clear();
730                 }
731
732                 ret = gnutls_certificate_allocate_credentials(&iohook.x509_cred);
733                 cred_alloc = (ret >= 0);
734                 if (!cred_alloc)
735                         ServerInstance->Logs->Log("m_ssl_gnutls", LOG_DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
736
737                 if((ret =gnutls_certificate_set_x509_trust_file(iohook.x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
738                         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));
739
740                 if((ret = gnutls_certificate_set_x509_crl_file (iohook.x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
741                         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));
742
743                 FileReader reader;
744
745                 reader.Load(certfile);
746                 std::string cert_string = reader.GetString();
747                 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
748
749                 reader.Load(keyfile);
750                 std::string key_string = reader.GetString();
751                 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
752
753                 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
754                 unsigned int certcount = 3;
755                 x509_certs.resize(certcount);
756                 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
757                 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
758                 {
759                         // 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
760                         x509_certs.resize(certcount);
761                         ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
762                 }
763
764                 if (ret <= 0)
765                 {
766                         // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later
767                         x509_certs.clear();
768                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read"));
769                 }
770                 x509_certs.resize(ret);
771
772                 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
773                         throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
774
775                 if((ret = gnutls_certificate_set_x509_key(iohook.x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
776                         throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
777
778                 #ifdef GNUTLS_NEW_PRIO_API
779                 // It's safe to call this every time as we cannot have this uninitialized, see constructor and below.
780                 gnutls_priority_deinit(iohook.priority);
781
782                 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
783                 // If the user did not supply anything then the string is already set to "NORMAL"
784                 const char* priocstr = priorities.c_str();
785                 const char* prioerror;
786
787                 if ((ret = gnutls_priority_init(&iohook.priority, priocstr, &prioerror)) < 0)
788                 {
789                         // gnutls did not understand the user supplied string, log and fall back to the default priorities
790                         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));
791                         gnutls_priority_init(&iohook.priority, "NORMAL", NULL);
792                 }
793
794                 #else
795                 if (priorities != "NORMAL")
796                         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.");
797                 #endif
798
799                 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
800                 gnutls_certificate_client_set_retrieve_function (iohook.x509_cred, cert_callback);
801                 #else
802                 gnutls_certificate_set_retrieve_function (iohook.x509_cred, cert_callback);
803                 #endif
804                 ret = gnutls_dh_params_init(&dh_params);
805                 dh_alloc = (ret >= 0);
806                 if (!dh_alloc)
807                 {
808                         ServerInstance->Logs->Log("m_ssl_gnutls", LOG_DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
809                         return;
810                 }
811
812                 std::string dhfile = Conf->getString("dhfile");
813                 if (!dhfile.empty())
814                 {
815                         // Try to load DH params from file
816                         reader.Load(dhfile);
817                         std::string dhstring = reader.GetString();
818                         gnutls_datum_t dh_datum = { (unsigned char*)dhstring.data(), static_cast<unsigned int>(dhstring.length()) };
819
820                         if ((ret = gnutls_dh_params_import_pkcs3(dh_params, &dh_datum, GNUTLS_X509_FMT_PEM)) < 0)
821                         {
822                                 // File unreadable or GnuTLS was unhappy with the contents, generate the DH primes now
823                                 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));
824                                 GenerateDHParams();
825                         }
826                 }
827                 else
828                 {
829                         GenerateDHParams();
830                 }
831         }
832
833         void GenerateDHParams()
834         {
835                 // Generate Diffie Hellman parameters - for use with DHE
836                 // kx algorithms. These should be discarded and regenerated
837                 // once a day, once a week or once a month. Depending on the
838                 // security requirements.
839
840                 if (!dh_alloc)
841                         return;
842
843                 int ret;
844
845                 if((ret = gnutls_dh_params_generate2(dh_params, iohook.dh_bits)) < 0)
846                         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));
847         }
848
849         ~ModuleSSLGnuTLS()
850         {
851                 for(unsigned int i=0; i < x509_certs.size(); i++)
852                         gnutls_x509_crt_deinit(x509_certs[i]);
853
854                 gnutls_x509_privkey_deinit(x509_key);
855                 #ifdef GNUTLS_NEW_PRIO_API
856                 gnutls_priority_deinit(iohook.priority);
857                 #endif
858
859                 if (dh_alloc)
860                         gnutls_dh_params_deinit(dh_params);
861                 if (cred_alloc)
862                         gnutls_certificate_free_credentials(iohook.x509_cred);
863
864                 gnutls_global_deinit();
865                 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
866         }
867
868         void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
869         {
870                 if(target_type == TYPE_USER)
871                 {
872                         LocalUser* user = IS_LOCAL(static_cast<User*>(item));
873
874                         if (user && user->eh.GetIOHook() == &iohook)
875                         {
876                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
877                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
878                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
879                         }
880                 }
881         }
882
883         Version GetVersion() CXX11_OVERRIDE
884         {
885                 return Version("Provides SSL support for clients", VF_VENDOR);
886         }
887
888         void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
889         {
890                 if (!sslports.empty())
891                         tokens["SSL"] = sslports;
892                 if (starttls.enabled)
893                         tokens["STARTTLS"];
894         }
895
896         void OnHookIO(StreamSocket* user, ListenSocket* lsb) CXX11_OVERRIDE
897         {
898                 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
899                 {
900                         /* Hook the user with our module */
901                         user->AddIOHook(&iohook);
902                 }
903         }
904
905         void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
906         {
907                 if (user->eh.GetIOHook() == &iohook)
908                         iohook.TellCiphersAndFingerprint(user);
909         }
910
911         void OnEvent(Event& ev) CXX11_OVERRIDE
912         {
913                 if (starttls.enabled)
914                         capHandler.HandleEvent(ev);
915         }
916 };
917
918 MODULE_INIT(ModuleSSLGnuTLS)