]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
11f4a365e64965459d61f8046789f31795087798
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_openssl.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
6  *   Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24  /* HACK: This prevents OpenSSL on OS X 10.7 and later from spewing deprecation
25   * warnings for every single function call. As far as I (SaberUK) know, Apple
26   * have no plans to remove OpenSSL so this warning just causes needless spam.
27   */
28 #ifdef __APPLE__
29 # define __AVAILABILITYMACROS__
30 # define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
31 #endif
32
33 #include "inspircd.h"
34 #include "iohook.h"
35 #include <openssl/ssl.h>
36 #include <openssl/err.h>
37 #include "modules/ssl.h"
38
39 #ifdef _WIN32
40 # pragma comment(lib, "libcrypto.lib")
41 # pragma comment(lib, "libssl.lib")
42 # pragma comment(lib, "user32.lib")
43 # pragma comment(lib, "advapi32.lib")
44 # pragma comment(lib, "libgcc.lib")
45 # pragma comment(lib, "libmingwex.lib")
46 # pragma comment(lib, "gdi32.lib")
47 # undef MAX_DESCRIPTORS
48 # define MAX_DESCRIPTORS 10000
49 #endif
50
51 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") -Wno-pedantic */
52 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */
53
54 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
55
56 static bool SelfSigned = false;
57
58 char* get_error()
59 {
60         return ERR_error_string(ERR_get_error(), NULL);
61 }
62
63 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
64
65 namespace OpenSSL
66 {
67         class Exception : public ModuleException
68         {
69          public:
70                 Exception(const std::string& reason)
71                         : ModuleException(reason) { }
72         };
73
74         class DHParams
75         {
76                 DH* dh;
77
78          public:
79                 DHParams(const std::string& filename)
80                 {
81                         FILE* dhpfile = fopen(filename.c_str(), "r");
82                         if (dhpfile == NULL)
83                                 throw Exception("Couldn't open DH file " + filename + ": " + strerror(errno));
84
85                         dh = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
86                         fclose(dhpfile);
87                         if (!dh)
88                                 throw Exception("Couldn't read DH params from file " + filename);
89                 }
90
91                 ~DHParams()
92                 {
93                         DH_free(dh);
94                 }
95
96                 DH* get()
97                 {
98                         return dh;
99                 }
100         };
101
102         class Context
103         {
104                 SSL_CTX* const ctx;
105
106          public:
107                 Context(SSL_CTX* context)
108                         : ctx(context)
109                 {
110                         SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
111                         SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
112                 }
113
114                 ~Context()
115                 {
116                         SSL_CTX_free(ctx);
117                 }
118
119                 bool SetDH(DHParams& dh)
120                 {
121                         return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
122                 }
123
124                 bool SetCiphers(const std::string& ciphers)
125                 {
126                         return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
127                 }
128
129                 bool SetCerts(const std::string& filename)
130                 {
131                         return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
132                 }
133
134                 bool SetPrivateKey(const std::string& filename)
135                 {
136                         return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
137                 }
138
139                 bool SetCA(const std::string& filename)
140                 {
141                         return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
142                 }
143
144                 SSL* CreateSession()
145                 {
146                         return SSL_new(ctx);
147                 }
148         };
149
150         class Profile : public refcountbase
151         {
152                 /** Name of this profile
153                  */
154                 const std::string name;
155
156                 /** DH parameters in use
157                  */
158                 DHParams dh;
159
160                 /** OpenSSL makes us have two contexts, one for servers and one for clients
161                  */
162                 Context ctx;
163                 Context clictx;
164
165                 /** Digest to use when generating fingerprints
166                  */
167                 const EVP_MD* digest;
168
169                 /** Last error, set by error_callback()
170                  */
171                 std::string lasterr;
172
173                 static int error_callback(const char* str, size_t len, void* u)
174                 {
175                         Profile* profile = reinterpret_cast<Profile*>(u);
176                         profile->lasterr = std::string(str, len - 1);
177                         return 0;
178                 }
179
180          public:
181                 Profile(const std::string& profilename, ConfigTag* tag)
182                         : name(profilename)
183                         , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem")))
184                         , ctx(SSL_CTX_new(SSLv23_server_method()))
185                         , clictx(SSL_CTX_new(SSLv23_client_method()))
186                 {
187                         if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
188                                 throw Exception("Couldn't set DH parameters");
189
190                         std::string hash = tag->getString("hash", "md5");
191                         digest = EVP_get_digestbyname(hash.c_str());
192                         if (digest == NULL)
193                                 throw Exception("Unknown hash type " + hash);
194
195                         std::string ciphers = tag->getString("ciphers");
196                         if (!ciphers.empty())
197                         {
198                                 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
199                                 {
200                                         ERR_print_errors_cb(error_callback, this);
201                                         throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
202                                 }
203                         }
204
205                         /* Load our keys and certificates
206                          * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
207                          */
208                         std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
209                         if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
210                         {
211                                 ERR_print_errors_cb(error_callback, this);
212                                 throw Exception("Can't read certificate file: " + lasterr);
213                         }
214
215                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
216                         if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
217                         {
218                                 ERR_print_errors_cb(error_callback, this);
219                                 throw Exception("Can't read key file: " + lasterr);
220                         }
221
222                         // Load the CAs we trust
223                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
224                         if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
225                         {
226                                 ERR_print_errors_cb(error_callback, this);
227                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Can't read CA list from %s. This is only a problem if you want to verify client certificates, otherwise it's safe to ignore this message. Error: %s", filename.c_str(), lasterr.c_str());
228                         }
229                 }
230
231                 const std::string& GetName() const { return name; }
232                 SSL* CreateServerSession() { return ctx.CreateSession(); }
233                 SSL* CreateClientSession() { return clictx.CreateSession(); }
234                 const EVP_MD* GetDigest() { return digest; }
235         };
236 }
237
238 /** Represents an SSL user's extra data
239  */
240 class issl_session
241 {
242 public:
243         SSL* sess;
244         issl_status status;
245         reference<ssl_cert> cert;
246         reference<OpenSSL::Profile> profile;
247
248         bool outbound;
249         bool data_to_write;
250
251         issl_session()
252         {
253                 outbound = false;
254                 data_to_write = false;
255         }
256 };
257
258 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
259 {
260         /* XXX: This will allow self signed certificates.
261          * In the future if we want an option to not allow this,
262          * we can just return preverify_ok here, and openssl
263          * will boot off self-signed and invalid peer certs.
264          */
265         int ve = X509_STORE_CTX_get_error(ctx);
266
267         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
268
269         return 1;
270 }
271
272 class OpenSSLIOHook : public SSLIOHook
273 {
274  private:
275         bool Handshake(StreamSocket* user, issl_session* session)
276         {
277                 int ret;
278
279                 if (session->outbound)
280                         ret = SSL_connect(session->sess);
281                 else
282                         ret = SSL_accept(session->sess);
283
284                 if (ret < 0)
285                 {
286                         int err = SSL_get_error(session->sess, ret);
287
288                         if (err == SSL_ERROR_WANT_READ)
289                         {
290                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
291                                 session->status = ISSL_HANDSHAKING;
292                                 return true;
293                         }
294                         else if (err == SSL_ERROR_WANT_WRITE)
295                         {
296                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
297                                 session->status = ISSL_HANDSHAKING;
298                                 return true;
299                         }
300                         else
301                         {
302                                 CloseSession(session);
303                         }
304
305                         return false;
306                 }
307                 else if (ret > 0)
308                 {
309                         // Handshake complete.
310                         VerifyCertificate(session, user);
311
312                         session->status = ISSL_OPEN;
313
314                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
315
316                         return true;
317                 }
318                 else if (ret == 0)
319                 {
320                         CloseSession(session);
321                         return true;
322                 }
323
324                 return true;
325         }
326
327         void CloseSession(issl_session* session)
328         {
329                 if (session->sess)
330                 {
331                         SSL_shutdown(session->sess);
332                         SSL_free(session->sess);
333                 }
334
335                 session->sess = NULL;
336                 session->status = ISSL_NONE;
337                 errno = EIO;
338         }
339
340         void VerifyCertificate(issl_session* session, StreamSocket* user)
341         {
342                 if (!session->sess || !user)
343                         return;
344
345                 X509* cert;
346                 ssl_cert* certinfo = new ssl_cert;
347                 session->cert = certinfo;
348                 unsigned int n;
349                 unsigned char md[EVP_MAX_MD_SIZE];
350
351                 cert = SSL_get_peer_certificate((SSL*)session->sess);
352
353                 if (!cert)
354                 {
355                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
356                         return;
357                 }
358
359                 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
360
361                 if (!SelfSigned)
362                 {
363                         certinfo->unknownsigner = false;
364                         certinfo->trusted = true;
365                 }
366                 else
367                 {
368                         certinfo->unknownsigner = true;
369                         certinfo->trusted = false;
370                 }
371
372                 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
373                 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
374
375                 if (!X509_digest(cert, session->profile->GetDigest(), md, &n))
376                 {
377                         certinfo->error = "Out of memory generating fingerprint";
378                 }
379                 else
380                 {
381                         certinfo->fingerprint = BinToHex(md, n);
382                 }
383
384                 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), ServerInstance->Time()) == 0))
385                 {
386                         certinfo->error = "Not activated, or expired certificate";
387                 }
388
389                 X509_free(cert);
390         }
391
392  public:
393         issl_session* sessions;
394
395         OpenSSLIOHook(Module* mod)
396                 : SSLIOHook(mod, "ssl/openssl")
397         {
398                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
399         }
400
401         ~OpenSSLIOHook()
402         {
403                 delete[] sessions;
404         }
405
406         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
407         {
408                 int fd = user->GetFd();
409
410                 issl_session* session = &sessions[fd];
411
412                 session->sess = session->profile->CreateServerSession();
413                 session->status = ISSL_NONE;
414                 session->outbound = false;
415                 session->cert = NULL;
416
417                 if (session->sess == NULL)
418                         return;
419
420                 if (SSL_set_fd(session->sess, fd) == 0)
421                 {
422                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Can't set fd with SSL_set_fd: %d", fd);
423                         return;
424                 }
425
426                 Handshake(user, session);
427         }
428
429         void OnStreamSocketConnect(StreamSocket* user) CXX11_OVERRIDE
430         {
431                 int fd = user->GetFd();
432                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
433                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
434                         return;
435
436                 issl_session* session = &sessions[fd];
437
438                 session->sess = session->profile->CreateClientSession();
439                 session->status = ISSL_NONE;
440                 session->outbound = true;
441
442                 if (session->sess == NULL)
443                         return;
444
445                 if (SSL_set_fd(session->sess, fd) == 0)
446                 {
447                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Can't set fd with SSL_set_fd: %d", fd);
448                         return;
449                 }
450
451                 Handshake(user, session);
452         }
453
454         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
455         {
456                 int fd = user->GetFd();
457                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
458                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
459                         return;
460
461                 CloseSession(&sessions[fd]);
462         }
463
464         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
465         {
466                 int fd = user->GetFd();
467                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
468                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
469                         return -1;
470
471                 issl_session* session = &sessions[fd];
472
473                 if (!session->sess)
474                 {
475                         CloseSession(session);
476                         return -1;
477                 }
478
479                 if (session->status == ISSL_HANDSHAKING)
480                 {
481                         // The handshake isn't finished and it wants to read, try to finish it.
482                         if (!Handshake(user, session))
483                         {
484                                 // Couldn't resume handshake.
485                                 if (session->status == ISSL_NONE)
486                                         return -1;
487                                 return 0;
488                         }
489                 }
490
491                 // If we resumed the handshake then session->status will be ISSL_OPEN
492
493                 if (session->status == ISSL_OPEN)
494                 {
495                         char* buffer = ServerInstance->GetReadBuffer();
496                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
497                         int ret = SSL_read(session->sess, buffer, bufsiz);
498
499                         if (ret > 0)
500                         {
501                                 recvq.append(buffer, ret);
502                                 if (session->data_to_write)
503                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
504                                 return 1;
505                         }
506                         else if (ret == 0)
507                         {
508                                 // Client closed connection.
509                                 CloseSession(session);
510                                 user->SetError("Connection closed");
511                                 return -1;
512                         }
513                         else if (ret < 0)
514                         {
515                                 int err = SSL_get_error(session->sess, ret);
516
517                                 if (err == SSL_ERROR_WANT_READ)
518                                 {
519                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
520                                         return 0;
521                                 }
522                                 else if (err == SSL_ERROR_WANT_WRITE)
523                                 {
524                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
525                                         return 0;
526                                 }
527                                 else
528                                 {
529                                         CloseSession(session);
530                                         return -1;
531                                 }
532                         }
533                 }
534
535                 return 0;
536         }
537
538         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
539         {
540                 int fd = user->GetFd();
541
542                 issl_session* session = &sessions[fd];
543
544                 if (!session->sess)
545                 {
546                         CloseSession(session);
547                         return -1;
548                 }
549
550                 session->data_to_write = true;
551
552                 if (session->status == ISSL_HANDSHAKING)
553                 {
554                         if (!Handshake(user, session))
555                         {
556                                 // Couldn't resume handshake.
557                                 if (session->status == ISSL_NONE)
558                                         return -1;
559                                 return 0;
560                         }
561                 }
562
563                 if (session->status == ISSL_OPEN)
564                 {
565                         int ret = SSL_write(session->sess, buffer.data(), buffer.size());
566                         if (ret == (int)buffer.length())
567                         {
568                                 session->data_to_write = false;
569                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
570                                 return 1;
571                         }
572                         else if (ret > 0)
573                         {
574                                 buffer = buffer.substr(ret);
575                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
576                                 return 0;
577                         }
578                         else if (ret == 0)
579                         {
580                                 CloseSession(session);
581                                 return -1;
582                         }
583                         else if (ret < 0)
584                         {
585                                 int err = SSL_get_error(session->sess, ret);
586
587                                 if (err == SSL_ERROR_WANT_WRITE)
588                                 {
589                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
590                                         return 0;
591                                 }
592                                 else if (err == SSL_ERROR_WANT_READ)
593                                 {
594                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
595                                         return 0;
596                                 }
597                                 else
598                                 {
599                                         CloseSession(session);
600                                         return -1;
601                                 }
602                         }
603                 }
604                 return 0;
605         }
606
607         ssl_cert* GetCertificate(StreamSocket* sock) CXX11_OVERRIDE
608         {
609                 int fd = sock->GetFd();
610                 issl_session* session = &sessions[fd];
611                 return session->cert;
612         }
613
614         void TellCiphersAndFingerprint(LocalUser* user)
615         {
616                 issl_session& s = sessions[user->eh.GetFd()];
617                 if (s.sess)
618                 {
619                         std::string text = "*** You are connected using SSL cipher '" + std::string(SSL_get_cipher(s.sess)) + "'";
620                         const std::string& fingerprint = s.cert->fingerprint;
621                         if (!fingerprint.empty())
622                                 text += " and your SSL fingerprint is " + fingerprint;
623
624                         user->WriteNotice(text);
625                 }
626         }
627 };
628
629 class ModuleSSLOpenSSL : public Module
630 {
631         typedef std::vector<reference<OpenSSL::Profile> > ProfileList;
632
633         std::string sslports;
634         OpenSSLIOHook iohook;
635         ProfileList profiles;
636
637         void ReadProfiles()
638         {
639                 ProfileList newprofiles;
640                 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
641                 if (tags.first == tags.second)
642                 {
643                         // Create a default profile named "openssl"
644                         const std::string defname = "openssl";
645                         ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
646                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
647
648                         try
649                         {
650                                 reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag));
651                                 newprofiles.push_back(profile);
652                         }
653                         catch (OpenSSL::Exception& ex)
654                         {
655                                 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
656                         }
657                 }
658
659                 for (ConfigIter i = tags.first; i != tags.second; ++i)
660                 {
661                         ConfigTag* tag = i->second;
662                         if (tag->getString("provider") != "openssl")
663                                 continue;
664
665                         std::string name = tag->getString("name");
666                         if (name.empty())
667                         {
668                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
669                                 continue;
670                         }
671
672                         reference<OpenSSL::Profile> profile;
673                         try
674                         {
675                                 profile = new OpenSSL::Profile(name, tag);
676                         }
677                         catch (CoreException& ex)
678                         {
679                                 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
680                         }
681
682                         newprofiles.push_back(profile);
683                 }
684
685                 profiles.swap(newprofiles);
686         }
687
688  public:
689         ModuleSSLOpenSSL() : iohook(this)
690         {
691                 // Initialize OpenSSL
692                 SSL_library_init();
693                 SSL_load_error_strings();
694         }
695
696         void init() CXX11_OVERRIDE
697         {
698                 ReadProfiles();
699         }
700
701         void OnHookIO(StreamSocket* user, ListenSocket* lsb) CXX11_OVERRIDE
702         {
703                 if (user->GetIOHook())
704                         return;
705
706                 ConfigTag* tag = lsb->bind_tag;
707                 std::string profilename = tag->getString("ssl");
708                 for (ProfileList::const_iterator i = profiles.begin(); i != profiles.end(); ++i)
709                 {
710                         if ((*i)->GetName() == profilename)
711                         {
712                                 iohook.sessions[user->GetFd()].profile = *i;
713                                 user->AddIOHook(&iohook);
714                                 break;
715                         }
716                 }
717         }
718
719         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
720         {
721                 sslports.clear();
722
723                 ConfigTag* Conf = ServerInstance->Config->ConfValue("openssl");
724
725                 if (Conf->getBool("showports", true))
726                 {
727                         sslports = Conf->getString("advertisedports");
728                         if (!sslports.empty())
729                                 return;
730
731                         for (size_t i = 0; i < ServerInstance->ports.size(); i++)
732                         {
733                                 ListenSocket* port = ServerInstance->ports[i];
734                                 if (port->bind_tag->getString("ssl") != "openssl")
735                                         continue;
736
737                                 const std::string& portid = port->bind_desc;
738                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Enabling SSL for port %s", portid.c_str());
739
740                                 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
741                                 {
742                                         /*
743                                          * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
744                                          * the IP:port in ISUPPORT.
745                                          *
746                                          * We used to advertise all ports seperated by a ';' char that matched the above criteria,
747                                          * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
748                                          * To solve this by default we now only display the first IP:port found and let the user
749                                          * configure the exact value for the 005 token, if necessary.
750                                          */
751                                         sslports = portid;
752                                         break;
753                                 }
754                         }
755                 }
756         }
757
758         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
759         {
760                 if (param != "ssl")
761                         return;
762
763                 try
764                 {
765                         ReadProfiles();
766                 }
767                 catch (ModuleException& ex)
768                 {
769                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
770                 }
771         }
772
773         void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
774         {
775                 if (!sslports.empty())
776                         tokens["SSL"] = sslports;
777         }
778
779         void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
780         {
781                 if (user->eh.GetIOHook() == &iohook)
782                         iohook.TellCiphersAndFingerprint(user);
783         }
784
785         void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
786         {
787                 if (target_type == TYPE_USER)
788                 {
789                         LocalUser* user = IS_LOCAL((User*)item);
790
791                         if (user && user->eh.GetIOHook() == &iohook)
792                         {
793                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
794                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
795                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
796                         }
797                 }
798         }
799
800         Version GetVersion() CXX11_OVERRIDE
801         {
802                 return Version("Provides SSL support for clients", VF_VENDOR);
803         }
804 };
805
806 MODULE_INIT(ModuleSSLOpenSSL)