]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
3dd8a85441850515e3d87fc2140c2d9a74e81168
[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
25 #include "inspircd.h"
26 #include "iohook.h"
27 #include "modules/ssl.h"
28
29 // Ignore OpenSSL deprecation warnings on OS X Lion and newer.
30 #if defined __APPLE__
31 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
32 #endif
33
34 #include <openssl/ssl.h>
35 #include <openssl/err.h>
36
37 #ifdef _WIN32
38 # pragma comment(lib, "ssleay32.lib")
39 # pragma comment(lib, "libeay32.lib")
40 #endif
41
42 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
43 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */
44
45 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
46
47 static bool SelfSigned = false;
48 static int exdataindex;
49
50 char* get_error()
51 {
52         return ERR_error_string(ERR_get_error(), NULL);
53 }
54
55 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
56 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
57
58 namespace OpenSSL
59 {
60         class Exception : public ModuleException
61         {
62          public:
63                 Exception(const std::string& reason)
64                         : ModuleException(reason) { }
65         };
66
67         class DHParams
68         {
69                 DH* dh;
70
71          public:
72                 DHParams(const std::string& filename)
73                 {
74                         BIO* dhpfile = BIO_new_file(filename.c_str(), "r");
75                         if (dhpfile == NULL)
76                                 throw Exception("Couldn't open DH file " + filename);
77
78                         dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
79                         BIO_free(dhpfile);
80
81                         if (!dh)
82                                 throw Exception("Couldn't read DH params from file " + filename);
83                 }
84
85                 ~DHParams()
86                 {
87                         DH_free(dh);
88                 }
89
90                 DH* get()
91                 {
92                         return dh;
93                 }
94         };
95
96         class Context
97         {
98                 SSL_CTX* const ctx;
99                 long ctx_options;
100
101          public:
102                 Context(SSL_CTX* context)
103                         : ctx(context)
104                 {
105                         // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
106                         // and when choosing a cipher, use the server's preferences instead of the client preferences.
107                         long opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE;
108                         // Only turn options on if they exist
109 #ifdef SSL_OP_SINGLE_ECDH_USE
110                         opts |= SSL_OP_SINGLE_ECDH_USE;
111 #endif
112 #ifdef SSL_OP_NO_TICKET
113                         opts |= SSL_OP_NO_TICKET;
114 #endif
115
116                         ctx_options = SSL_CTX_set_options(ctx, opts);
117                         SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
118                         SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
119                         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
120                         SSL_CTX_set_info_callback(ctx, StaticSSLInfoCallback);
121                 }
122
123                 ~Context()
124                 {
125                         SSL_CTX_free(ctx);
126                 }
127
128                 bool SetDH(DHParams& dh)
129                 {
130                         ERR_clear_error();
131                         return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
132                 }
133
134 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
135                 void SetECDH(const std::string& curvename)
136                 {
137                         int nid = OBJ_sn2nid(curvename.c_str());
138                         if (nid == 0)
139                                 throw Exception("Unknown curve: " + curvename);
140
141                         EC_KEY* eckey = EC_KEY_new_by_curve_name(nid);
142                         if (!eckey)
143                                 throw Exception("Unable to create EC key object");
144
145                         ERR_clear_error();
146                         bool ret = (SSL_CTX_set_tmp_ecdh(ctx, eckey) >= 0);
147                         EC_KEY_free(eckey);
148                         if (!ret)
149                                 throw Exception("Couldn't set ECDH parameters");
150                 }
151 #endif
152
153                 bool SetCiphers(const std::string& ciphers)
154                 {
155                         ERR_clear_error();
156                         return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
157                 }
158
159                 bool SetCerts(const std::string& filename)
160                 {
161                         ERR_clear_error();
162                         return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
163                 }
164
165                 bool SetPrivateKey(const std::string& filename)
166                 {
167                         ERR_clear_error();
168                         return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
169                 }
170
171                 bool SetCA(const std::string& filename)
172                 {
173                         ERR_clear_error();
174                         return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
175                 }
176
177                 long GetDefaultContextOptions() const
178                 {
179                         return ctx_options;
180                 }
181
182                 long SetRawContextOptions(long setoptions, long clearoptions)
183                 {
184                         // Clear everything
185                         SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
186
187                         // Set the default options and what is in the conf
188                         SSL_CTX_set_options(ctx, ctx_options | setoptions);
189                         return SSL_CTX_clear_options(ctx, clearoptions);
190                 }
191
192                 SSL* CreateSession()
193                 {
194                         return SSL_new(ctx);
195                 }
196         };
197
198         class Profile : public refcountbase
199         {
200                 /** Name of this profile
201                  */
202                 const std::string name;
203
204                 /** DH parameters in use
205                  */
206                 DHParams dh;
207
208                 /** OpenSSL makes us have two contexts, one for servers and one for clients
209                  */
210                 Context ctx;
211                 Context clictx;
212
213                 /** Digest to use when generating fingerprints
214                  */
215                 const EVP_MD* digest;
216
217                 /** Last error, set by error_callback()
218                  */
219                 std::string lasterr;
220
221                 /** True if renegotiations are allowed, false if not
222                  */
223                 const bool allowrenego;
224
225                 static int error_callback(const char* str, size_t len, void* u)
226                 {
227                         Profile* profile = reinterpret_cast<Profile*>(u);
228                         profile->lasterr = std::string(str, len - 1);
229                         return 0;
230                 }
231
232                 /** Set raw OpenSSL context (SSL_CTX) options from a config tag
233                  * @param ctxname Name of the context, client or server
234                  * @param tag Config tag defining this profile
235                  * @param context Context object to manipulate
236                  */
237                 void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context)
238                 {
239                         long setoptions = tag->getInt(ctxname + "setoptions");
240                         long clearoptions = tag->getInt(ctxname + "clearoptions");
241 #ifdef SSL_OP_NO_COMPRESSION
242                         if (!tag->getBool("compression", true))
243                                 setoptions |= SSL_OP_NO_COMPRESSION;
244 #endif
245                         if (!tag->getBool("sslv3", true))
246                                 setoptions |= SSL_OP_NO_SSLv3;
247                         if (!tag->getBool("tlsv1", true))
248                                 setoptions |= SSL_OP_NO_TLSv1;
249
250                         if (!setoptions && !clearoptions)
251                                 return; // Nothing to do
252
253                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Setting %s %s context options, default: %ld set: %ld clear: %ld", name.c_str(), ctxname.c_str(), ctx.GetDefaultContextOptions(), setoptions, clearoptions);
254                         long final = context.SetRawContextOptions(setoptions, clearoptions);
255                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final);
256                 }
257
258          public:
259                 Profile(const std::string& profilename, ConfigTag* tag)
260                         : name(profilename)
261                         , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem")))
262                         , ctx(SSL_CTX_new(SSLv23_server_method()))
263                         , clictx(SSL_CTX_new(SSLv23_client_method()))
264                         , allowrenego(tag->getBool("renegotiation", true))
265                 {
266                         if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
267                                 throw Exception("Couldn't set DH parameters");
268
269                         std::string hash = tag->getString("hash", "md5");
270                         digest = EVP_get_digestbyname(hash.c_str());
271                         if (digest == NULL)
272                                 throw Exception("Unknown hash type " + hash);
273
274                         std::string ciphers = tag->getString("ciphers");
275                         if (!ciphers.empty())
276                         {
277                                 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
278                                 {
279                                         ERR_print_errors_cb(error_callback, this);
280                                         throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
281                                 }
282                         }
283
284 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
285                         std::string curvename = tag->getString("ecdhcurve", "prime256v1");
286                         if (!curvename.empty())
287                                 ctx.SetECDH(curvename);
288 #endif
289
290                         SetContextOptions("server", tag, ctx);
291                         SetContextOptions("client", tag, clictx);
292
293                         /* Load our keys and certificates
294                          * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
295                          */
296                         std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
297                         if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
298                         {
299                                 ERR_print_errors_cb(error_callback, this);
300                                 throw Exception("Can't read certificate file: " + lasterr);
301                         }
302
303                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
304                         if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
305                         {
306                                 ERR_print_errors_cb(error_callback, this);
307                                 throw Exception("Can't read key file: " + lasterr);
308                         }
309
310                         // Load the CAs we trust
311                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
312                         if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
313                         {
314                                 ERR_print_errors_cb(error_callback, this);
315                                 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());
316                         }
317                 }
318
319                 const std::string& GetName() const { return name; }
320                 SSL* CreateServerSession() { return ctx.CreateSession(); }
321                 SSL* CreateClientSession() { return clictx.CreateSession(); }
322                 const EVP_MD* GetDigest() { return digest; }
323                 bool AllowRenegotiation() const { return allowrenego; }
324         };
325 }
326
327 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
328 {
329         /* XXX: This will allow self signed certificates.
330          * In the future if we want an option to not allow this,
331          * we can just return preverify_ok here, and openssl
332          * will boot off self-signed and invalid peer certs.
333          */
334         int ve = X509_STORE_CTX_get_error(ctx);
335
336         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
337
338         return 1;
339 }
340
341 class OpenSSLIOHook : public SSLIOHook
342 {
343  private:
344         SSL* sess;
345         issl_status status;
346         const bool outbound;
347         bool data_to_write;
348         reference<OpenSSL::Profile> profile;
349
350         bool Handshake(StreamSocket* user)
351         {
352                 int ret;
353
354                 ERR_clear_error();
355                 if (outbound)
356                         ret = SSL_connect(sess);
357                 else
358                         ret = SSL_accept(sess);
359
360                 if (ret < 0)
361                 {
362                         int err = SSL_get_error(sess, ret);
363
364                         if (err == SSL_ERROR_WANT_READ)
365                         {
366                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
367                                 this->status = ISSL_HANDSHAKING;
368                                 return true;
369                         }
370                         else if (err == SSL_ERROR_WANT_WRITE)
371                         {
372                                 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
373                                 this->status = ISSL_HANDSHAKING;
374                                 return true;
375                         }
376                         else
377                         {
378                                 CloseSession();
379                         }
380
381                         return false;
382                 }
383                 else if (ret > 0)
384                 {
385                         // Handshake complete.
386                         VerifyCertificate();
387
388                         status = ISSL_OPEN;
389
390                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
391
392                         return true;
393                 }
394                 else if (ret == 0)
395                 {
396                         CloseSession();
397                 }
398                 return false;
399         }
400
401         void CloseSession()
402         {
403                 if (sess)
404                 {
405                         SSL_shutdown(sess);
406                         SSL_free(sess);
407                 }
408                 sess = NULL;
409                 certificate = NULL;
410                 status = ISSL_NONE;
411         }
412
413         void VerifyCertificate()
414         {
415                 X509* cert;
416                 ssl_cert* certinfo = new ssl_cert;
417                 this->certificate = certinfo;
418                 unsigned int n;
419                 unsigned char md[EVP_MAX_MD_SIZE];
420
421                 cert = SSL_get_peer_certificate(sess);
422
423                 if (!cert)
424                 {
425                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
426                         return;
427                 }
428
429                 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
430
431                 if (!SelfSigned)
432                 {
433                         certinfo->unknownsigner = false;
434                         certinfo->trusted = true;
435                 }
436                 else
437                 {
438                         certinfo->unknownsigner = true;
439                         certinfo->trusted = false;
440                 }
441
442                 char buf[512];
443                 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
444                 certinfo->dn = buf;
445                 // Make sure there are no chars in the string that we consider invalid
446                 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
447                         certinfo->dn.clear();
448
449                 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
450                 certinfo->issuer = buf;
451                 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
452                         certinfo->issuer.clear();
453
454                 if (!X509_digest(cert, profile->GetDigest(), md, &n))
455                 {
456                         certinfo->error = "Out of memory generating fingerprint";
457                 }
458                 else
459                 {
460                         certinfo->fingerprint = BinToHex(md, n);
461                 }
462
463                 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))
464                 {
465                         certinfo->error = "Not activated, or expired certificate";
466                 }
467
468                 X509_free(cert);
469         }
470
471 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
472         void SSLInfoCallback(int where, int rc)
473         {
474                 if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN))
475                 {
476                         if (profile->AllowRenegotiation())
477                                 return;
478
479                         // The other side is trying to renegotiate, kill the connection and change status
480                         // to ISSL_NONE so CheckRenego() closes the session
481                         status = ISSL_NONE;
482                         SocketEngine::Shutdown(SSL_get_fd(sess), 2);
483                 }
484         }
485
486         bool CheckRenego(StreamSocket* sock)
487         {
488                 if (status != ISSL_NONE)
489                         return true;
490
491                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess);
492                 CloseSession();
493                 sock->SetError("Renegotiation is not allowed");
494                 return false;
495         }
496 #endif
497
498         // Calls our private SSLInfoCallback()
499         friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
500
501  public:
502         OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool is_outbound, SSL* session, const reference<OpenSSL::Profile>& sslprofile)
503                 : SSLIOHook(hookprov)
504                 , sess(session)
505                 , status(ISSL_NONE)
506                 , outbound(is_outbound)
507                 , data_to_write(false)
508                 , profile(sslprofile)
509         {
510                 if (sess == NULL)
511                         return;
512                 if (SSL_set_fd(sess, sock->GetFd()) == 0)
513                         throw ModuleException("Can't set fd with SSL_set_fd: " + ConvToStr(sock->GetFd()));
514
515                 SSL_set_ex_data(sess, exdataindex, this);
516                 sock->AddIOHook(this);
517                 Handshake(sock);
518         }
519
520         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
521         {
522                 CloseSession();
523         }
524
525         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
526         {
527                 if (!sess)
528                 {
529                         CloseSession();
530                         return -1;
531                 }
532
533                 if (status == ISSL_HANDSHAKING)
534                 {
535                         // The handshake isn't finished and it wants to read, try to finish it.
536                         if (!Handshake(user))
537                         {
538                                 // Couldn't resume handshake.
539                                 if (status == ISSL_NONE)
540                                         return -1;
541                                 return 0;
542                         }
543                 }
544
545                 // If we resumed the handshake then this->status will be ISSL_OPEN
546
547                 if (status == ISSL_OPEN)
548                 {
549                         ERR_clear_error();
550                         char* buffer = ServerInstance->GetReadBuffer();
551                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
552                         int ret = SSL_read(sess, buffer, bufsiz);
553
554 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
555                         if (!CheckRenego(user))
556                                 return -1;
557 #endif
558
559                         if (ret > 0)
560                         {
561                                 recvq.append(buffer, ret);
562                                 if (data_to_write)
563                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
564                                 return 1;
565                         }
566                         else if (ret == 0)
567                         {
568                                 // Client closed connection.
569                                 CloseSession();
570                                 user->SetError("Connection closed");
571                                 return -1;
572                         }
573                         else if (ret < 0)
574                         {
575                                 int err = SSL_get_error(sess, ret);
576
577                                 if (err == SSL_ERROR_WANT_READ)
578                                 {
579                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
580                                         return 0;
581                                 }
582                                 else if (err == SSL_ERROR_WANT_WRITE)
583                                 {
584                                         SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
585                                         return 0;
586                                 }
587                                 else
588                                 {
589                                         CloseSession();
590                                         return -1;
591                                 }
592                         }
593                 }
594
595                 return 0;
596         }
597
598         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
599         {
600                 if (!sess)
601                 {
602                         CloseSession();
603                         return -1;
604                 }
605
606                 data_to_write = true;
607
608                 if (status == ISSL_HANDSHAKING)
609                 {
610                         if (!Handshake(user))
611                         {
612                                 // Couldn't resume handshake.
613                                 if (status == ISSL_NONE)
614                                         return -1;
615                                 return 0;
616                         }
617                 }
618
619                 if (status == ISSL_OPEN)
620                 {
621                         ERR_clear_error();
622                         int ret = SSL_write(sess, buffer.data(), buffer.size());
623
624 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
625                         if (!CheckRenego(user))
626                                 return -1;
627 #endif
628
629                         if (ret == (int)buffer.length())
630                         {
631                                 data_to_write = false;
632                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
633                                 return 1;
634                         }
635                         else if (ret > 0)
636                         {
637                                 buffer = buffer.substr(ret);
638                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
639                                 return 0;
640                         }
641                         else if (ret == 0)
642                         {
643                                 CloseSession();
644                                 return -1;
645                         }
646                         else if (ret < 0)
647                         {
648                                 int err = SSL_get_error(sess, ret);
649
650                                 if (err == SSL_ERROR_WANT_WRITE)
651                                 {
652                                         SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
653                                         return 0;
654                                 }
655                                 else if (err == SSL_ERROR_WANT_READ)
656                                 {
657                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
658                                         return 0;
659                                 }
660                                 else
661                                 {
662                                         CloseSession();
663                                         return -1;
664                                 }
665                         }
666                 }
667                 return 0;
668         }
669
670         void TellCiphersAndFingerprint(LocalUser* user)
671         {
672                 if (sess)
673                 {
674                         std::string text = "*** You are connected using SSL cipher '" + std::string(SSL_get_cipher(sess)) + "'";
675                         const std::string& fingerprint = certificate->fingerprint;
676                         if (!fingerprint.empty())
677                                 text += " and your SSL certificate fingerprint is " + fingerprint;
678
679                         user->WriteNotice(text);
680                 }
681         }
682 };
683
684 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc)
685 {
686 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
687         OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex));
688         hook->SSLInfoCallback(where, rc);
689 #endif
690 }
691
692 class OpenSSLIOHookProvider : public refcountbase, public IOHookProvider
693 {
694         reference<OpenSSL::Profile> profile;
695
696  public:
697         OpenSSLIOHookProvider(Module* mod, reference<OpenSSL::Profile>& prof)
698                 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
699                 , profile(prof)
700         {
701                 ServerInstance->Modules->AddService(*this);
702         }
703
704         ~OpenSSLIOHookProvider()
705         {
706                 ServerInstance->Modules->DelService(*this);
707         }
708
709         void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
710         {
711                 new OpenSSLIOHook(this, sock, false, profile->CreateServerSession(), profile);
712         }
713
714         void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
715         {
716                 new OpenSSLIOHook(this, sock, true, profile->CreateClientSession(), profile);
717         }
718 };
719
720 class ModuleSSLOpenSSL : public Module
721 {
722         typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
723
724         ProfileList profiles;
725
726         void ReadProfiles()
727         {
728                 ProfileList newprofiles;
729                 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
730                 if (tags.first == tags.second)
731                 {
732                         // Create a default profile named "openssl"
733                         const std::string defname = "openssl";
734                         ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
735                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
736
737                         try
738                         {
739                                 reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag));
740                                 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
741                         }
742                         catch (OpenSSL::Exception& ex)
743                         {
744                                 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
745                         }
746                 }
747
748                 for (ConfigIter i = tags.first; i != tags.second; ++i)
749                 {
750                         ConfigTag* tag = i->second;
751                         if (tag->getString("provider") != "openssl")
752                                 continue;
753
754                         std::string name = tag->getString("name");
755                         if (name.empty())
756                         {
757                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
758                                 continue;
759                         }
760
761                         reference<OpenSSL::Profile> profile;
762                         try
763                         {
764                                 profile = new OpenSSL::Profile(name, tag);
765                         }
766                         catch (CoreException& ex)
767                         {
768                                 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
769                         }
770
771                         newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
772                 }
773
774                 profiles.swap(newprofiles);
775         }
776
777  public:
778         ModuleSSLOpenSSL()
779         {
780                 // Initialize OpenSSL
781                 SSL_library_init();
782                 SSL_load_error_strings();
783         }
784
785         void init() CXX11_OVERRIDE
786         {
787                 // Register application specific data
788                 char exdatastr[] = "inspircd";
789                 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
790                 if (exdataindex < 0)
791                         throw ModuleException("Failed to register application specific data");
792
793                 ReadProfiles();
794         }
795
796         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
797         {
798                 if (param != "ssl")
799                         return;
800
801                 try
802                 {
803                         ReadProfiles();
804                 }
805                 catch (ModuleException& ex)
806                 {
807                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
808                 }
809         }
810
811         void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
812         {
813                 IOHook* hook = user->eh.GetIOHook();
814                 if (hook && hook->prov->creator == this)
815                         static_cast<OpenSSLIOHook*>(hook)->TellCiphersAndFingerprint(user);
816         }
817
818         void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
819         {
820                 if (target_type == TYPE_USER)
821                 {
822                         LocalUser* user = IS_LOCAL((User*)item);
823
824                         if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this)
825                         {
826                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
827                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
828                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
829                         }
830                 }
831         }
832
833         Version GetVersion() CXX11_OVERRIDE
834         {
835                 return Version("Provides SSL support for clients", VF_VENDOR);
836         }
837 };
838
839 MODULE_INIT(ModuleSSLOpenSSL)