]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
Merge insp20
[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* CreateServerSession()
200                 {
201                         SSL* sess = SSL_new(ctx);
202                         SSL_set_accept_state(sess); // Act as server
203                         return sess;
204                 }
205
206                 SSL* CreateClientSession()
207                 {
208                         SSL* sess = SSL_new(ctx);
209                         SSL_set_connect_state(sess); // Act as client
210                         return sess;
211                 }
212         };
213
214         class Profile : public refcountbase
215         {
216                 /** Name of this profile
217                  */
218                 const std::string name;
219
220                 /** DH parameters in use
221                  */
222                 DHParams dh;
223
224                 /** OpenSSL makes us have two contexts, one for servers and one for clients
225                  */
226                 Context ctx;
227                 Context clictx;
228
229                 /** Digest to use when generating fingerprints
230                  */
231                 const EVP_MD* digest;
232
233                 /** Last error, set by error_callback()
234                  */
235                 std::string lasterr;
236
237                 /** True if renegotiations are allowed, false if not
238                  */
239                 const bool allowrenego;
240
241                 static int error_callback(const char* str, size_t len, void* u)
242                 {
243                         Profile* profile = reinterpret_cast<Profile*>(u);
244                         profile->lasterr = std::string(str, len - 1);
245                         return 0;
246                 }
247
248                 /** Set raw OpenSSL context (SSL_CTX) options from a config tag
249                  * @param ctxname Name of the context, client or server
250                  * @param tag Config tag defining this profile
251                  * @param context Context object to manipulate
252                  */
253                 void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context)
254                 {
255                         long setoptions = tag->getInt(ctxname + "setoptions");
256                         long clearoptions = tag->getInt(ctxname + "clearoptions");
257 #ifdef SSL_OP_NO_COMPRESSION
258                         if (!tag->getBool("compression", true))
259                                 setoptions |= SSL_OP_NO_COMPRESSION;
260 #endif
261                         if (!tag->getBool("sslv3", true))
262                                 setoptions |= SSL_OP_NO_SSLv3;
263                         if (!tag->getBool("tlsv1", true))
264                                 setoptions |= SSL_OP_NO_TLSv1;
265
266                         if (!setoptions && !clearoptions)
267                                 return; // Nothing to do
268
269                         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);
270                         long final = context.SetRawContextOptions(setoptions, clearoptions);
271                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final);
272                 }
273
274          public:
275                 Profile(const std::string& profilename, ConfigTag* tag)
276                         : name(profilename)
277                         , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem")))
278                         , ctx(SSL_CTX_new(SSLv23_server_method()))
279                         , clictx(SSL_CTX_new(SSLv23_client_method()))
280                         , allowrenego(tag->getBool("renegotiation", true))
281                 {
282                         if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
283                                 throw Exception("Couldn't set DH parameters");
284
285                         std::string hash = tag->getString("hash", "md5");
286                         digest = EVP_get_digestbyname(hash.c_str());
287                         if (digest == NULL)
288                                 throw Exception("Unknown hash type " + hash);
289
290                         std::string ciphers = tag->getString("ciphers");
291                         if (!ciphers.empty())
292                         {
293                                 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
294                                 {
295                                         ERR_print_errors_cb(error_callback, this);
296                                         throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
297                                 }
298                         }
299
300 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
301                         std::string curvename = tag->getString("ecdhcurve", "prime256v1");
302                         if (!curvename.empty())
303                                 ctx.SetECDH(curvename);
304 #endif
305
306                         SetContextOptions("server", tag, ctx);
307                         SetContextOptions("client", tag, clictx);
308
309                         /* Load our keys and certificates
310                          * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
311                          */
312                         std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
313                         if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
314                         {
315                                 ERR_print_errors_cb(error_callback, this);
316                                 throw Exception("Can't read certificate file: " + lasterr);
317                         }
318
319                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
320                         if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
321                         {
322                                 ERR_print_errors_cb(error_callback, this);
323                                 throw Exception("Can't read key file: " + lasterr);
324                         }
325
326                         // Load the CAs we trust
327                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
328                         if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
329                         {
330                                 ERR_print_errors_cb(error_callback, this);
331                                 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());
332                         }
333                 }
334
335                 const std::string& GetName() const { return name; }
336                 SSL* CreateServerSession() { return ctx.CreateServerSession(); }
337                 SSL* CreateClientSession() { return clictx.CreateClientSession(); }
338                 const EVP_MD* GetDigest() { return digest; }
339                 bool AllowRenegotiation() const { return allowrenego; }
340         };
341 }
342
343 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
344 {
345         /* XXX: This will allow self signed certificates.
346          * In the future if we want an option to not allow this,
347          * we can just return preverify_ok here, and openssl
348          * will boot off self-signed and invalid peer certs.
349          */
350         int ve = X509_STORE_CTX_get_error(ctx);
351
352         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
353
354         return 1;
355 }
356
357 class OpenSSLIOHook : public SSLIOHook
358 {
359  private:
360         SSL* sess;
361         issl_status status;
362         bool data_to_write;
363         reference<OpenSSL::Profile> profile;
364
365         // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
366         int Handshake(StreamSocket* user)
367         {
368                 ERR_clear_error();
369                 int ret = SSL_do_handshake(sess);
370                 if (ret < 0)
371                 {
372                         int err = SSL_get_error(sess, ret);
373
374                         if (err == SSL_ERROR_WANT_READ)
375                         {
376                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
377                                 this->status = ISSL_HANDSHAKING;
378                                 return 0;
379                         }
380                         else if (err == SSL_ERROR_WANT_WRITE)
381                         {
382                                 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
383                                 this->status = ISSL_HANDSHAKING;
384                                 return 0;
385                         }
386                         else
387                         {
388                                 CloseSession();
389                                 return -1;
390                         }
391                 }
392                 else if (ret > 0)
393                 {
394                         // Handshake complete.
395                         VerifyCertificate();
396
397                         status = ISSL_OPEN;
398
399                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
400
401                         return 1;
402                 }
403                 else if (ret == 0)
404                 {
405                         CloseSession();
406                 }
407                 return -1;
408         }
409
410         void CloseSession()
411         {
412                 if (sess)
413                 {
414                         SSL_shutdown(sess);
415                         SSL_free(sess);
416                 }
417                 sess = NULL;
418                 certificate = NULL;
419                 status = ISSL_NONE;
420         }
421
422         void VerifyCertificate()
423         {
424                 X509* cert;
425                 ssl_cert* certinfo = new ssl_cert;
426                 this->certificate = certinfo;
427                 unsigned int n;
428                 unsigned char md[EVP_MAX_MD_SIZE];
429
430                 cert = SSL_get_peer_certificate(sess);
431
432                 if (!cert)
433                 {
434                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
435                         return;
436                 }
437
438                 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
439
440                 if (!SelfSigned)
441                 {
442                         certinfo->unknownsigner = false;
443                         certinfo->trusted = true;
444                 }
445                 else
446                 {
447                         certinfo->unknownsigner = true;
448                         certinfo->trusted = false;
449                 }
450
451                 char buf[512];
452                 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
453                 certinfo->dn = buf;
454                 // Make sure there are no chars in the string that we consider invalid
455                 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
456                         certinfo->dn.clear();
457
458                 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
459                 certinfo->issuer = buf;
460                 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
461                         certinfo->issuer.clear();
462
463                 if (!X509_digest(cert, profile->GetDigest(), md, &n))
464                 {
465                         certinfo->error = "Out of memory generating fingerprint";
466                 }
467                 else
468                 {
469                         certinfo->fingerprint = BinToHex(md, n);
470                 }
471
472                 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))
473                 {
474                         certinfo->error = "Not activated, or expired certificate";
475                 }
476
477                 X509_free(cert);
478         }
479
480 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
481         void SSLInfoCallback(int where, int rc)
482         {
483                 if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN))
484                 {
485                         if (profile->AllowRenegotiation())
486                                 return;
487
488                         // The other side is trying to renegotiate, kill the connection and change status
489                         // to ISSL_NONE so CheckRenego() closes the session
490                         status = ISSL_NONE;
491                         SocketEngine::Shutdown(SSL_get_fd(sess), 2);
492                 }
493         }
494
495         bool CheckRenego(StreamSocket* sock)
496         {
497                 if (status != ISSL_NONE)
498                         return true;
499
500                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess);
501                 CloseSession();
502                 sock->SetError("Renegotiation is not allowed");
503                 return false;
504         }
505 #endif
506
507         // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
508         int PrepareIO(StreamSocket* sock)
509         {
510                 if (status == ISSL_OPEN)
511                         return 1;
512                 else if (status == ISSL_HANDSHAKING)
513                 {
514                         // The handshake isn't finished, try to finish it
515                         return Handshake(sock);
516                 }
517
518                 CloseSession();
519                 return -1;
520         }
521
522         // Calls our private SSLInfoCallback()
523         friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
524
525  public:
526         OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, SSL* session, const reference<OpenSSL::Profile>& sslprofile)
527                 : SSLIOHook(hookprov)
528                 , sess(session)
529                 , status(ISSL_NONE)
530                 , data_to_write(false)
531                 , profile(sslprofile)
532         {
533                 if (sess == NULL)
534                         return;
535                 if (SSL_set_fd(sess, sock->GetFd()) == 0)
536                         throw ModuleException("Can't set fd with SSL_set_fd: " + ConvToStr(sock->GetFd()));
537
538                 SSL_set_ex_data(sess, exdataindex, this);
539                 sock->AddIOHook(this);
540                 Handshake(sock);
541         }
542
543         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
544         {
545                 CloseSession();
546         }
547
548         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
549         {
550                 // Finish handshake if needed
551                 int prepret = PrepareIO(user);
552                 if (prepret <= 0)
553                         return prepret;
554
555                 // If we resumed the handshake then this->status will be ISSL_OPEN
556                 {
557                         ERR_clear_error();
558                         char* buffer = ServerInstance->GetReadBuffer();
559                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
560                         int ret = SSL_read(sess, buffer, bufsiz);
561
562 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
563                         if (!CheckRenego(user))
564                                 return -1;
565 #endif
566
567                         if (ret > 0)
568                         {
569                                 recvq.append(buffer, ret);
570                                 if (data_to_write)
571                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
572                                 return 1;
573                         }
574                         else if (ret == 0)
575                         {
576                                 // Client closed connection.
577                                 CloseSession();
578                                 user->SetError("Connection closed");
579                                 return -1;
580                         }
581                         else // if (ret < 0)
582                         {
583                                 int err = SSL_get_error(sess, ret);
584
585                                 if (err == SSL_ERROR_WANT_READ)
586                                 {
587                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
588                                         return 0;
589                                 }
590                                 else if (err == SSL_ERROR_WANT_WRITE)
591                                 {
592                                         SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
593                                         return 0;
594                                 }
595                                 else
596                                 {
597                                         CloseSession();
598                                         return -1;
599                                 }
600                         }
601                 }
602         }
603
604         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
605         {
606                 // Finish handshake if needed
607                 int prepret = PrepareIO(user);
608                 if (prepret <= 0)
609                         return prepret;
610
611                 data_to_write = true;
612
613                 // Session is ready for transferring application data
614                 {
615                         ERR_clear_error();
616                         int ret = SSL_write(sess, buffer.data(), buffer.size());
617
618 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
619                         if (!CheckRenego(user))
620                                 return -1;
621 #endif
622
623                         if (ret == (int)buffer.length())
624                         {
625                                 data_to_write = false;
626                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
627                                 return 1;
628                         }
629                         else if (ret > 0)
630                         {
631                                 buffer.erase(0, ret);
632                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
633                                 return 0;
634                         }
635                         else if (ret == 0)
636                         {
637                                 CloseSession();
638                                 return -1;
639                         }
640                         else // if (ret < 0)
641                         {
642                                 int err = SSL_get_error(sess, ret);
643
644                                 if (err == SSL_ERROR_WANT_WRITE)
645                                 {
646                                         SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
647                                         return 0;
648                                 }
649                                 else if (err == SSL_ERROR_WANT_READ)
650                                 {
651                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
652                                         return 0;
653                                 }
654                                 else
655                                 {
656                                         CloseSession();
657                                         return -1;
658                                 }
659                         }
660                 }
661         }
662
663         void TellCiphersAndFingerprint(LocalUser* user)
664         {
665                 if (sess)
666                 {
667                         std::string text = "*** You are connected using SSL cipher '";
668                         GetCiphersuite(text);
669                         text += '\'';
670                         const std::string& fingerprint = certificate->fingerprint;
671                         if (!fingerprint.empty())
672                                 text += " and your SSL certificate fingerprint is " + fingerprint;
673
674                         user->WriteNotice(text);
675                 }
676         }
677
678         void GetCiphersuite(std::string& out) const
679         {
680                 out.append(SSL_get_version(sess)).push_back('-');
681                 out.append(SSL_get_cipher(sess));
682         }
683
684         bool IsHandshakeDone() const { return (status == ISSL_OPEN); }
685 };
686
687 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc)
688 {
689 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
690         OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex));
691         hook->SSLInfoCallback(where, rc);
692 #endif
693 }
694
695 class OpenSSLIOHookProvider : public refcountbase, public IOHookProvider
696 {
697         reference<OpenSSL::Profile> profile;
698
699  public:
700         OpenSSLIOHookProvider(Module* mod, reference<OpenSSL::Profile>& prof)
701                 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
702                 , profile(prof)
703         {
704                 ServerInstance->Modules->AddService(*this);
705         }
706
707         ~OpenSSLIOHookProvider()
708         {
709                 ServerInstance->Modules->DelService(*this);
710         }
711
712         void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
713         {
714                 new OpenSSLIOHook(this, sock, profile->CreateServerSession(), profile);
715         }
716
717         void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
718         {
719                 new OpenSSLIOHook(this, sock, profile->CreateClientSession(), profile);
720         }
721 };
722
723 class ModuleSSLOpenSSL : public Module
724 {
725         typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
726
727         ProfileList profiles;
728
729         void ReadProfiles()
730         {
731                 ProfileList newprofiles;
732                 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
733                 if (tags.first == tags.second)
734                 {
735                         // Create a default profile named "openssl"
736                         const std::string defname = "openssl";
737                         ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
738                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
739
740                         try
741                         {
742                                 reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag));
743                                 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
744                         }
745                         catch (OpenSSL::Exception& ex)
746                         {
747                                 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
748                         }
749                 }
750
751                 for (ConfigIter i = tags.first; i != tags.second; ++i)
752                 {
753                         ConfigTag* tag = i->second;
754                         if (tag->getString("provider") != "openssl")
755                                 continue;
756
757                         std::string name = tag->getString("name");
758                         if (name.empty())
759                         {
760                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
761                                 continue;
762                         }
763
764                         reference<OpenSSL::Profile> profile;
765                         try
766                         {
767                                 profile = new OpenSSL::Profile(name, tag);
768                         }
769                         catch (CoreException& ex)
770                         {
771                                 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
772                         }
773
774                         newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
775                 }
776
777                 profiles.swap(newprofiles);
778         }
779
780  public:
781         ModuleSSLOpenSSL()
782         {
783                 // Initialize OpenSSL
784                 SSL_library_init();
785                 SSL_load_error_strings();
786         }
787
788         void init() CXX11_OVERRIDE
789         {
790                 // Register application specific data
791                 char exdatastr[] = "inspircd";
792                 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
793                 if (exdataindex < 0)
794                         throw ModuleException("Failed to register application specific data");
795
796                 ReadProfiles();
797         }
798
799         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
800         {
801                 if (param != "ssl")
802                         return;
803
804                 try
805                 {
806                         ReadProfiles();
807                 }
808                 catch (ModuleException& ex)
809                 {
810                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
811                 }
812         }
813
814         void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
815         {
816                 IOHook* hook = user->eh.GetIOHook();
817                 if (hook && hook->prov->creator == this)
818                         static_cast<OpenSSLIOHook*>(hook)->TellCiphersAndFingerprint(user);
819         }
820
821         void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
822         {
823                 if (target_type == TYPE_USER)
824                 {
825                         LocalUser* user = IS_LOCAL((User*)item);
826
827                         if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this)
828                         {
829                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
830                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
831                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
832                         }
833                 }
834         }
835
836         ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
837         {
838                 if ((user->eh.GetIOHook()) && (user->eh.GetIOHook()->prov->creator == this))
839                 {
840                         OpenSSLIOHook* iohook = static_cast<OpenSSLIOHook*>(user->eh.GetIOHook());
841                         if (!iohook->IsHandshakeDone())
842                                 return MOD_RES_DENY;
843                 }
844
845                 return MOD_RES_PASSTHRU;
846         }
847
848         Version GetVersion() CXX11_OVERRIDE
849         {
850                 return Version("Provides SSL support for clients", VF_VENDOR);
851         }
852 };
853
854 MODULE_INIT(ModuleSSLOpenSSL)