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