]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
8540ab41f3d87ab8028de00199c9f3840484fc31
[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         // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
358         int Handshake(StreamSocket* user)
359         {
360                 int ret;
361
362                 ERR_clear_error();
363                 if (outbound)
364                         ret = SSL_connect(sess);
365                 else
366                         ret = SSL_accept(sess);
367
368                 if (ret < 0)
369                 {
370                         int err = SSL_get_error(sess, ret);
371
372                         if (err == SSL_ERROR_WANT_READ)
373                         {
374                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
375                                 this->status = ISSL_HANDSHAKING;
376                                 return 0;
377                         }
378                         else if (err == SSL_ERROR_WANT_WRITE)
379                         {
380                                 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
381                                 this->status = ISSL_HANDSHAKING;
382                                 return 0;
383                         }
384                         else
385                         {
386                                 CloseSession();
387                                 return -1;
388                         }
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 1;
400                 }
401                 else if (ret == 0)
402                 {
403                         CloseSession();
404                 }
405                 return -1;
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         // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
506         int PrepareIO(StreamSocket* sock)
507         {
508                 if (status == ISSL_OPEN)
509                         return 1;
510                 else if (status == ISSL_HANDSHAKING)
511                 {
512                         // The handshake isn't finished, try to finish it
513                         return Handshake(sock);
514                 }
515
516                 CloseSession();
517                 return -1;
518         }
519
520         // Calls our private SSLInfoCallback()
521         friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
522
523  public:
524         OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool is_outbound, SSL* session, const reference<OpenSSL::Profile>& sslprofile)
525                 : SSLIOHook(hookprov)
526                 , sess(session)
527                 , status(ISSL_NONE)
528                 , outbound(is_outbound)
529                 , data_to_write(false)
530                 , profile(sslprofile)
531         {
532                 if (sess == NULL)
533                         return;
534                 if (SSL_set_fd(sess, sock->GetFd()) == 0)
535                         throw ModuleException("Can't set fd with SSL_set_fd: " + ConvToStr(sock->GetFd()));
536
537                 SSL_set_ex_data(sess, exdataindex, this);
538                 sock->AddIOHook(this);
539                 Handshake(sock);
540         }
541
542         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
543         {
544                 CloseSession();
545         }
546
547         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
548         {
549                 // Finish handshake if needed
550                 int prepret = PrepareIO(user);
551                 if (prepret <= 0)
552                         return prepret;
553
554                 // If we resumed the handshake then this->status will be 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
603         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
604         {
605                 // Finish handshake if needed
606                 int prepret = PrepareIO(user);
607                 if (prepret <= 0)
608                         return prepret;
609
610                 data_to_write = true;
611
612                 // Session is ready for transferring application data
613                 {
614                         ERR_clear_error();
615                         int ret = SSL_write(sess, buffer.data(), buffer.size());
616
617 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
618                         if (!CheckRenego(user))
619                                 return -1;
620 #endif
621
622                         if (ret == (int)buffer.length())
623                         {
624                                 data_to_write = false;
625                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
626                                 return 1;
627                         }
628                         else if (ret > 0)
629                         {
630                                 buffer.erase(0, ret);
631                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
632                                 return 0;
633                         }
634                         else if (ret == 0)
635                         {
636                                 CloseSession();
637                                 return -1;
638                         }
639                         else // if (ret < 0)
640                         {
641                                 int err = SSL_get_error(sess, ret);
642
643                                 if (err == SSL_ERROR_WANT_WRITE)
644                                 {
645                                         SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
646                                         return 0;
647                                 }
648                                 else if (err == SSL_ERROR_WANT_READ)
649                                 {
650                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
651                                         return 0;
652                                 }
653                                 else
654                                 {
655                                         CloseSession();
656                                         return -1;
657                                 }
658                         }
659                 }
660         }
661
662         void TellCiphersAndFingerprint(LocalUser* user)
663         {
664                 if (sess)
665                 {
666                         std::string text = "*** You are connected using SSL cipher '";
667                         GetCiphersuite(text);
668                         text += '\'';
669                         const std::string& fingerprint = certificate->fingerprint;
670                         if (!fingerprint.empty())
671                                 text += " and your SSL certificate fingerprint is " + fingerprint;
672
673                         user->WriteNotice(text);
674                 }
675         }
676
677         void GetCiphersuite(std::string& out) const
678         {
679                 out.append(SSL_get_version(sess)).push_back('-');
680                 out.append(SSL_get_cipher(sess));
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)