]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
Improve TLS security configuration in m_ssl_openssl.
[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 /// $CompilerFlags: find_compiler_flags("openssl")
25 /// $LinkerFlags: find_linker_flags("openssl" "-lssl -lcrypto")
26
27 /// $PackageInfo: require_system("centos") openssl-devel pkgconfig
28 /// $PackageInfo: require_system("darwin") openssl pkg-config
29 /// $PackageInfo: require_system("debian") libssl-dev openssl pkg-config
30 /// $PackageInfo: require_system("ubuntu") libssl-dev openssl pkg-config
31
32
33 #include "inspircd.h"
34 #include "iohook.h"
35 #include "modules/ssl.h"
36
37 // Ignore OpenSSL deprecation warnings on OS X Lion and newer.
38 #if defined __APPLE__
39 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
40 #endif
41
42 // Fix warnings about the use of `long long` on C++03.
43 #if defined __clang__
44 # pragma clang diagnostic ignored "-Wc++11-long-long"
45 #elif defined __GNUC__
46 # pragma GCC diagnostic ignored "-Wlong-long"
47 #endif
48
49 #include <openssl/ssl.h>
50 #include <openssl/err.h>
51
52 #ifdef _WIN32
53 # pragma comment(lib, "ssleay32.lib")
54 # pragma comment(lib, "libeay32.lib")
55 #endif
56
57 #if ((OPENSSL_VERSION_NUMBER >= 0x10000000L) && (!(defined(OPENSSL_NO_ECDH))))
58 // OpenSSL 0.9.8 includes some ECC support, but it's unfinished. Enable only for 1.0.0 and later.
59 #define INSPIRCD_OPENSSL_ENABLE_ECDH
60 #endif
61
62 // BIO is opaque in OpenSSL 1.1 but the access API does not exist in 1.0 and older.
63 #if ((defined LIBRESSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x10100000L))
64 # define BIO_get_data(BIO) BIO->ptr
65 # define BIO_set_data(BIO, VALUE) BIO->ptr = VALUE;
66 # define BIO_set_init(BIO, VALUE) BIO->init = VALUE;
67 #else
68 # define INSPIRCD_OPENSSL_OPAQUE_BIO
69 #endif
70
71 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
72
73 static bool SelfSigned = false;
74 static int exdataindex;
75
76 char* get_error()
77 {
78         return ERR_error_string(ERR_get_error(), NULL);
79 }
80
81 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
82 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
83
84 namespace OpenSSL
85 {
86         class Exception : public ModuleException
87         {
88          public:
89                 Exception(const std::string& reason)
90                         : ModuleException(reason) { }
91         };
92
93         class DHParams
94         {
95                 DH* dh;
96
97          public:
98                 DHParams(const std::string& filename)
99                 {
100                         BIO* dhpfile = BIO_new_file(filename.c_str(), "r");
101                         if (dhpfile == NULL)
102                                 throw Exception("Couldn't open DH file " + filename);
103
104                         dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
105                         BIO_free(dhpfile);
106
107                         if (!dh)
108                                 throw Exception("Couldn't read DH params from file " + filename);
109                 }
110
111                 ~DHParams()
112                 {
113                         DH_free(dh);
114                 }
115
116                 DH* get()
117                 {
118                         return dh;
119                 }
120         };
121
122         class Context
123         {
124                 SSL_CTX* const ctx;
125                 long ctx_options;
126
127          public:
128                 Context(SSL_CTX* context)
129                         : ctx(context)
130                 {
131                         // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
132                         // and when choosing a cipher, use the server's preferences instead of the client preferences.
133                         long opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE;
134                         // Only turn options on if they exist
135 #ifdef SSL_OP_SINGLE_ECDH_USE
136                         opts |= SSL_OP_SINGLE_ECDH_USE;
137 #endif
138 #ifdef SSL_OP_NO_TICKET
139                         opts |= SSL_OP_NO_TICKET;
140 #endif
141
142                         ctx_options = SSL_CTX_set_options(ctx, opts);
143
144                         long mode = SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
145 #ifdef SSL_MODE_RELEASE_BUFFERS
146                         mode |= SSL_MODE_RELEASE_BUFFERS;
147 #endif
148                         SSL_CTX_set_mode(ctx, mode);
149                         SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
150                         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
151                         SSL_CTX_set_info_callback(ctx, StaticSSLInfoCallback);
152                 }
153
154                 ~Context()
155                 {
156                         SSL_CTX_free(ctx);
157                 }
158
159                 bool SetDH(DHParams& dh)
160                 {
161                         ERR_clear_error();
162                         return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
163                 }
164
165 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
166                 void SetECDH(const std::string& curvename)
167                 {
168                         int nid = OBJ_sn2nid(curvename.c_str());
169                         if (nid == 0)
170                                 throw Exception("Unknown curve: " + curvename);
171
172                         EC_KEY* eckey = EC_KEY_new_by_curve_name(nid);
173                         if (!eckey)
174                                 throw Exception("Unable to create EC key object");
175
176                         ERR_clear_error();
177                         bool ret = (SSL_CTX_set_tmp_ecdh(ctx, eckey) >= 0);
178                         EC_KEY_free(eckey);
179                         if (!ret)
180                                 throw Exception("Couldn't set ECDH parameters");
181                 }
182 #endif
183
184                 bool SetCiphers(const std::string& ciphers)
185                 {
186                         ERR_clear_error();
187                         return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
188                 }
189
190                 bool SetCerts(const std::string& filename)
191                 {
192                         ERR_clear_error();
193                         return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
194                 }
195
196                 bool SetPrivateKey(const std::string& filename)
197                 {
198                         ERR_clear_error();
199                         return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
200                 }
201
202                 bool SetCA(const std::string& filename)
203                 {
204                         ERR_clear_error();
205                         return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
206                 }
207
208                 long GetDefaultContextOptions() const
209                 {
210                         return ctx_options;
211                 }
212
213                 long SetRawContextOptions(long setoptions, long clearoptions)
214                 {
215                         // Clear everything
216                         SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
217
218                         // Set the default options and what is in the conf
219                         SSL_CTX_set_options(ctx, ctx_options | setoptions);
220                         return SSL_CTX_clear_options(ctx, clearoptions);
221                 }
222
223                 void SetVerifyCert()
224                 {
225                         SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
226                 }
227
228                 SSL* CreateServerSession()
229                 {
230                         SSL* sess = SSL_new(ctx);
231                         SSL_set_accept_state(sess); // Act as server
232                         return sess;
233                 }
234
235                 SSL* CreateClientSession()
236                 {
237                         SSL* sess = SSL_new(ctx);
238                         SSL_set_connect_state(sess); // Act as client
239                         return sess;
240                 }
241         };
242
243         class Profile
244         {
245                 /** Name of this profile
246                  */
247                 const std::string name;
248
249                 /** DH parameters in use
250                  */
251                 DHParams dh;
252
253                 /** OpenSSL makes us have two contexts, one for servers and one for clients
254                  */
255                 Context ctx;
256                 Context clictx;
257
258                 /** Digest to use when generating fingerprints
259                  */
260                 const EVP_MD* digest;
261
262                 /** Last error, set by error_callback()
263                  */
264                 std::string lasterr;
265
266                 /** True if renegotiations are allowed, false if not
267                  */
268                 const bool allowrenego;
269
270                 /** Rough max size of records to send
271                  */
272                 const unsigned int outrecsize;
273
274                 static int error_callback(const char* str, size_t len, void* u)
275                 {
276                         Profile* profile = reinterpret_cast<Profile*>(u);
277                         profile->lasterr = std::string(str, len - 1);
278                         return 0;
279                 }
280
281                 /** Set raw OpenSSL context (SSL_CTX) options from a config tag
282                  * @param ctxname Name of the context, client or server
283                  * @param tag Config tag defining this profile
284                  * @param context Context object to manipulate
285                  */
286                 void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context)
287                 {
288                         long setoptions = tag->getInt(ctxname + "setoptions");
289                         long clearoptions = tag->getInt(ctxname + "clearoptions");
290 #ifdef SSL_OP_NO_COMPRESSION
291                         if (!tag->getBool("compression", false)) // Disable compression by default
292                                 setoptions |= SSL_OP_NO_COMPRESSION;
293 #endif
294                         // Disable TLSv1.0 by default.
295                         if (!tag->getBool("tlsv1", false))
296                                 setoptions |= SSL_OP_NO_TLSv1;
297
298                         if (!setoptions && !clearoptions)
299                                 return; // Nothing to do
300
301                         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);
302                         long final = context.SetRawContextOptions(setoptions, clearoptions);
303                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final);
304                 }
305
306          public:
307                 Profile(const std::string& profilename, ConfigTag* tag)
308                         : name(profilename)
309                         , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dhparams.pem")))
310                         , ctx(SSL_CTX_new(SSLv23_server_method()))
311                         , clictx(SSL_CTX_new(SSLv23_client_method()))
312                         , allowrenego(tag->getBool("renegotiation")) // Disallow by default
313                         , outrecsize(tag->getInt("outrecsize", 2048, 512, 16384))
314                 {
315                         if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
316                                 throw Exception("Couldn't set DH parameters");
317
318                         std::string hash = tag->getString("hash", "md5");
319                         digest = EVP_get_digestbyname(hash.c_str());
320                         if (digest == NULL)
321                                 throw Exception("Unknown hash type " + hash);
322
323                         std::string ciphers = tag->getString("ciphers");
324                         if (!ciphers.empty())
325                         {
326                                 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
327                                 {
328                                         ERR_print_errors_cb(error_callback, this);
329                                         throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
330                                 }
331                         }
332
333 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
334                         std::string curvename = tag->getString("ecdhcurve", "prime256v1");
335                         if (!curvename.empty())
336                                 ctx.SetECDH(curvename);
337 #endif
338
339                         SetContextOptions("server", tag, ctx);
340                         SetContextOptions("client", tag, clictx);
341
342                         /* Load our keys and certificates
343                          * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
344                          */
345                         std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
346                         if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
347                         {
348                                 ERR_print_errors_cb(error_callback, this);
349                                 throw Exception("Can't read certificate file: " + lasterr);
350                         }
351
352                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
353                         if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
354                         {
355                                 ERR_print_errors_cb(error_callback, this);
356                                 throw Exception("Can't read key file: " + lasterr);
357                         }
358
359                         // Load the CAs we trust
360                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
361                         if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
362                         {
363                                 ERR_print_errors_cb(error_callback, this);
364                                 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());
365                         }
366
367                         clictx.SetVerifyCert();
368                         if (tag->getBool("requestclientcert", true))
369                                 ctx.SetVerifyCert();
370                 }
371
372                 const std::string& GetName() const { return name; }
373                 SSL* CreateServerSession() { return ctx.CreateServerSession(); }
374                 SSL* CreateClientSession() { return clictx.CreateClientSession(); }
375                 const EVP_MD* GetDigest() { return digest; }
376                 bool AllowRenegotiation() const { return allowrenego; }
377                 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
378         };
379
380         namespace BIOMethod
381         {
382                 static int create(BIO* bio)
383                 {
384                         BIO_set_init(bio, 1);
385                         return 1;
386                 }
387
388                 static int destroy(BIO* bio)
389                 {
390                         // XXX: Dummy function to avoid a memory leak in OpenSSL.
391                         // The memory leak happens in BIO_free() (bio_lib.c) when the destroy func of the BIO is NULL.
392                         // This is fixed in OpenSSL but some distros still ship the unpatched version hence we provide this workaround.
393                         return 1;
394                 }
395
396                 static long ctrl(BIO* bio, int cmd, long num, void* ptr)
397                 {
398                         if (cmd == BIO_CTRL_FLUSH)
399                                 return 1;
400                         return 0;
401                 }
402
403                 static int read(BIO* bio, char* buf, int len);
404                 static int write(BIO* bio, const char* buf, int len);
405
406 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
407                 static BIO_METHOD* alloc()
408                 {
409                         BIO_METHOD* meth = BIO_meth_new(100 | BIO_TYPE_SOURCE_SINK, "inspircd");
410                         BIO_meth_set_write(meth, OpenSSL::BIOMethod::write);
411                         BIO_meth_set_read(meth, OpenSSL::BIOMethod::read);
412                         BIO_meth_set_ctrl(meth, OpenSSL::BIOMethod::ctrl);
413                         BIO_meth_set_create(meth, OpenSSL::BIOMethod::create);
414                         BIO_meth_set_destroy(meth, OpenSSL::BIOMethod::destroy);
415                         return meth;
416                 }
417 #endif
418         }
419 }
420
421 // BIO_METHOD is opaque in OpenSSL 1.1 so we can't do this.
422 // See OpenSSL::BIOMethod::alloc for the new method.
423 #ifndef INSPIRCD_OPENSSL_OPAQUE_BIO
424 static BIO_METHOD biomethods =
425 {
426         (100 | BIO_TYPE_SOURCE_SINK),
427         "inspircd",
428         OpenSSL::BIOMethod::write,
429         OpenSSL::BIOMethod::read,
430         NULL, // puts
431         NULL, // gets
432         OpenSSL::BIOMethod::ctrl,
433         OpenSSL::BIOMethod::create,
434         OpenSSL::BIOMethod::destroy, // destroy, does nothing, see function body for more info
435         NULL // callback_ctrl
436 };
437 #else
438 static BIO_METHOD* biomethods;
439 #endif
440
441 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
442 {
443         /* XXX: This will allow self signed certificates.
444          * In the future if we want an option to not allow this,
445          * we can just return preverify_ok here, and openssl
446          * will boot off self-signed and invalid peer certs.
447          */
448         int ve = X509_STORE_CTX_get_error(ctx);
449
450         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
451
452         return 1;
453 }
454
455 class OpenSSLIOHook : public SSLIOHook
456 {
457  private:
458         SSL* sess;
459         issl_status status;
460         bool data_to_write;
461
462         // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
463         int Handshake(StreamSocket* user)
464         {
465                 ERR_clear_error();
466                 int ret = SSL_do_handshake(sess);
467                 if (ret < 0)
468                 {
469                         int err = SSL_get_error(sess, ret);
470
471                         if (err == SSL_ERROR_WANT_READ)
472                         {
473                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
474                                 this->status = ISSL_HANDSHAKING;
475                                 return 0;
476                         }
477                         else if (err == SSL_ERROR_WANT_WRITE)
478                         {
479                                 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
480                                 this->status = ISSL_HANDSHAKING;
481                                 return 0;
482                         }
483                         else
484                         {
485                                 CloseSession();
486                                 return -1;
487                         }
488                 }
489                 else if (ret > 0)
490                 {
491                         // Handshake complete.
492                         VerifyCertificate();
493
494                         status = ISSL_OPEN;
495
496                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
497
498                         return 1;
499                 }
500                 else if (ret == 0)
501                 {
502                         CloseSession();
503                 }
504                 return -1;
505         }
506
507         void CloseSession()
508         {
509                 if (sess)
510                 {
511                         SSL_shutdown(sess);
512                         SSL_free(sess);
513                 }
514                 sess = NULL;
515                 certificate = NULL;
516                 status = ISSL_NONE;
517         }
518
519         void VerifyCertificate()
520         {
521                 X509* cert;
522                 ssl_cert* certinfo = new ssl_cert;
523                 this->certificate = certinfo;
524                 unsigned int n;
525                 unsigned char md[EVP_MAX_MD_SIZE];
526
527                 cert = SSL_get_peer_certificate(sess);
528
529                 if (!cert)
530                 {
531                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
532                         return;
533                 }
534
535                 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
536
537                 if (!SelfSigned)
538                 {
539                         certinfo->unknownsigner = false;
540                         certinfo->trusted = true;
541                 }
542                 else
543                 {
544                         certinfo->unknownsigner = true;
545                         certinfo->trusted = false;
546                 }
547
548                 char buf[512];
549                 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
550                 certinfo->dn = buf;
551                 // Make sure there are no chars in the string that we consider invalid
552                 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
553                         certinfo->dn.clear();
554
555                 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
556                 certinfo->issuer = buf;
557                 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
558                         certinfo->issuer.clear();
559
560                 if (!X509_digest(cert, GetProfile().GetDigest(), md, &n))
561                 {
562                         certinfo->error = "Out of memory generating fingerprint";
563                 }
564                 else
565                 {
566                         certinfo->fingerprint = BinToHex(md, n);
567                 }
568
569                 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))
570                 {
571                         certinfo->error = "Not activated, or expired certificate";
572                 }
573
574                 X509_free(cert);
575         }
576
577         void SSLInfoCallback(int where, int rc)
578         {
579                 if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN))
580                 {
581                         if (GetProfile().AllowRenegotiation())
582                                 return;
583
584                         // The other side is trying to renegotiate, kill the connection and change status
585                         // to ISSL_NONE so CheckRenego() closes the session
586                         status = ISSL_NONE;
587                         BIO* bio = SSL_get_rbio(sess);
588                         EventHandler* eh = static_cast<StreamSocket*>(BIO_get_data(bio));
589                         SocketEngine::Shutdown(eh, 2);
590                 }
591         }
592
593         bool CheckRenego(StreamSocket* sock)
594         {
595                 if (status != ISSL_NONE)
596                         return true;
597
598                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess);
599                 CloseSession();
600                 sock->SetError("Renegotiation is not allowed");
601                 return false;
602         }
603
604         // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
605         int PrepareIO(StreamSocket* sock)
606         {
607                 if (status == ISSL_OPEN)
608                         return 1;
609                 else if (status == ISSL_HANDSHAKING)
610                 {
611                         // The handshake isn't finished, try to finish it
612                         return Handshake(sock);
613                 }
614
615                 CloseSession();
616                 return -1;
617         }
618
619         // Calls our private SSLInfoCallback()
620         friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc);
621
622  public:
623         OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, SSL* session)
624                 : SSLIOHook(hookprov)
625                 , sess(session)
626                 , status(ISSL_NONE)
627                 , data_to_write(false)
628         {
629                 // Create BIO instance and store a pointer to the socket in it which will be used by the read and write functions
630 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
631                 BIO* bio = BIO_new(biomethods);
632 #else
633                 BIO* bio = BIO_new(&biomethods);
634 #endif
635                 BIO_set_data(bio, sock);
636                 SSL_set_bio(sess, bio, bio);
637
638                 SSL_set_ex_data(sess, exdataindex, this);
639                 sock->AddIOHook(this);
640                 Handshake(sock);
641         }
642
643         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
644         {
645                 CloseSession();
646         }
647
648         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
649         {
650                 // Finish handshake if needed
651                 int prepret = PrepareIO(user);
652                 if (prepret <= 0)
653                         return prepret;
654
655                 // If we resumed the handshake then this->status will be ISSL_OPEN
656                 {
657                         ERR_clear_error();
658                         char* buffer = ServerInstance->GetReadBuffer();
659                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
660                         int ret = SSL_read(sess, buffer, bufsiz);
661
662                         if (!CheckRenego(user))
663                                 return -1;
664
665                         if (ret > 0)
666                         {
667                                 recvq.append(buffer, ret);
668                                 int mask = 0;
669                                 // Schedule a read if there is still data in the OpenSSL buffer
670                                 if (SSL_pending(sess) > 0)
671                                         mask |= FD_ADD_TRIAL_READ;
672                                 if (data_to_write)
673                                         mask |= FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE;
674                                 if (mask != 0)
675                                         SocketEngine::ChangeEventMask(user, mask);
676                                 return 1;
677                         }
678                         else if (ret == 0)
679                         {
680                                 // Client closed connection.
681                                 CloseSession();
682                                 user->SetError("Connection closed");
683                                 return -1;
684                         }
685                         else // if (ret < 0)
686                         {
687                                 int err = SSL_get_error(sess, ret);
688
689                                 if (err == SSL_ERROR_WANT_READ)
690                                 {
691                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
692                                         return 0;
693                                 }
694                                 else if (err == SSL_ERROR_WANT_WRITE)
695                                 {
696                                         SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
697                                         return 0;
698                                 }
699                                 else
700                                 {
701                                         CloseSession();
702                                         return -1;
703                                 }
704                         }
705                 }
706         }
707
708         int OnStreamSocketWrite(StreamSocket* user, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
709         {
710                 // Finish handshake if needed
711                 int prepret = PrepareIO(user);
712                 if (prepret <= 0)
713                         return prepret;
714
715                 data_to_write = true;
716
717                 // Session is ready for transferring application data
718                 while (!sendq.empty())
719                 {
720                         ERR_clear_error();
721                         FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
722                         const StreamSocket::SendQueue::Element& buffer = sendq.front();
723                         int ret = SSL_write(sess, buffer.data(), buffer.size());
724
725                         if (!CheckRenego(user))
726                                 return -1;
727
728                         if (ret == (int)buffer.length())
729                         {
730                                 // Wrote entire record, continue sending
731                                 sendq.pop_front();
732                         }
733                         else if (ret > 0)
734                         {
735                                 sendq.erase_front(ret);
736                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
737                                 return 0;
738                         }
739                         else if (ret == 0)
740                         {
741                                 CloseSession();
742                                 return -1;
743                         }
744                         else // if (ret < 0)
745                         {
746                                 int err = SSL_get_error(sess, ret);
747
748                                 if (err == SSL_ERROR_WANT_WRITE)
749                                 {
750                                         SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
751                                         return 0;
752                                 }
753                                 else if (err == SSL_ERROR_WANT_READ)
754                                 {
755                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
756                                         return 0;
757                                 }
758                                 else
759                                 {
760                                         CloseSession();
761                                         return -1;
762                                 }
763                         }
764                 }
765
766                 data_to_write = false;
767                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
768                 return 1;
769         }
770
771         void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
772         {
773                 if (!IsHandshakeDone())
774                         return;
775                 out.append(SSL_get_version(sess)).push_back('-');
776                 out.append(SSL_get_cipher(sess));
777         }
778
779         bool GetServerName(std::string& out) const CXX11_OVERRIDE
780         {
781                 const char* name = SSL_get_servername(sess, TLSEXT_NAMETYPE_host_name);
782                 if (!name)
783                         return false;
784
785                 out.append(name);
786                 return true;
787         }
788
789         bool IsHandshakeDone() const { return (status == ISSL_OPEN); }
790         OpenSSL::Profile& GetProfile();
791 };
792
793 static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc)
794 {
795         OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex));
796         hook->SSLInfoCallback(where, rc);
797 }
798
799 static int OpenSSL::BIOMethod::write(BIO* bio, const char* buffer, int size)
800 {
801         BIO_clear_retry_flags(bio);
802
803         StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
804         if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
805         {
806                 // Writes blocked earlier, don't retry syscall
807                 BIO_set_retry_write(bio);
808                 return -1;
809         }
810
811         int ret = SocketEngine::Send(sock, buffer, size, 0);
812         if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
813         {
814                 // Blocked, set retry flag for OpenSSL
815                 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
816                 BIO_set_retry_write(bio);
817         }
818
819         return ret;
820 }
821
822 static int OpenSSL::BIOMethod::read(BIO* bio, char* buffer, int size)
823 {
824         BIO_clear_retry_flags(bio);
825
826         StreamSocket* sock = static_cast<StreamSocket*>(BIO_get_data(bio));
827         if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
828         {
829                 // Reads blocked earlier, don't retry syscall
830                 BIO_set_retry_read(bio);
831                 return -1;
832         }
833
834         int ret = SocketEngine::Recv(sock, buffer, size, 0);
835         if ((ret < size) && ((ret > 0) || (SocketEngine::IgnoreError())))
836         {
837                 // Blocked, set retry flag for OpenSSL
838                 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
839                 BIO_set_retry_read(bio);
840         }
841
842         return ret;
843 }
844
845 class OpenSSLIOHookProvider : public IOHookProvider
846 {
847         OpenSSL::Profile profile;
848
849  public:
850         OpenSSLIOHookProvider(Module* mod, const std::string& profilename, ConfigTag* tag)
851                 : IOHookProvider(mod, "ssl/" + profilename, IOHookProvider::IOH_SSL)
852                 , profile(profilename, tag)
853         {
854                 ServerInstance->Modules->AddService(*this);
855         }
856
857         ~OpenSSLIOHookProvider()
858         {
859                 ServerInstance->Modules->DelService(*this);
860         }
861
862         void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
863         {
864                 new OpenSSLIOHook(this, sock, profile.CreateServerSession());
865         }
866
867         void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
868         {
869                 new OpenSSLIOHook(this, sock, profile.CreateClientSession());
870         }
871
872         OpenSSL::Profile& GetProfile() { return profile; }
873 };
874
875 OpenSSL::Profile& OpenSSLIOHook::GetProfile()
876 {
877         IOHookProvider* hookprov = prov;
878         return static_cast<OpenSSLIOHookProvider*>(hookprov)->GetProfile();
879 }
880
881 class ModuleSSLOpenSSL : public Module
882 {
883         typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
884
885         ProfileList profiles;
886
887         void ReadProfiles()
888         {
889                 ProfileList newprofiles;
890                 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
891                 if (tags.first == tags.second)
892                 {
893                         // Create a default profile named "openssl"
894                         const std::string defname = "openssl";
895                         ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
896                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
897
898                         try
899                         {
900                                 newprofiles.push_back(new OpenSSLIOHookProvider(this, defname, tag));
901                         }
902                         catch (OpenSSL::Exception& ex)
903                         {
904                                 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
905                         }
906                 }
907
908                 for (ConfigIter i = tags.first; i != tags.second; ++i)
909                 {
910                         ConfigTag* tag = i->second;
911                         if (tag->getString("provider") != "openssl")
912                                 continue;
913
914                         std::string name = tag->getString("name");
915                         if (name.empty())
916                         {
917                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
918                                 continue;
919                         }
920
921                         reference<OpenSSLIOHookProvider> prov;
922                         try
923                         {
924                                 prov = new OpenSSLIOHookProvider(this, name, tag);
925                         }
926                         catch (CoreException& ex)
927                         {
928                                 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
929                         }
930
931                         newprofiles.push_back(prov);
932                 }
933
934                 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
935                 {
936                         OpenSSLIOHookProvider& prov = **i;
937                         ServerInstance->Modules.DelService(prov);
938                 }
939
940                 profiles.swap(newprofiles);
941         }
942
943  public:
944         ModuleSSLOpenSSL()
945         {
946                 // Initialize OpenSSL
947                 SSL_library_init();
948                 SSL_load_error_strings();
949 #ifdef INSPIRCD_OPENSSL_OPAQUE_BIO
950                 biomethods = OpenSSL::BIOMethod::alloc();
951         }
952
953         ~ModuleSSLOpenSSL()
954         {
955                 BIO_meth_free(biomethods);
956 #endif
957         }
958
959         void init() CXX11_OVERRIDE
960         {
961                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "OpenSSL lib version \"%s\" module was compiled for \"" OPENSSL_VERSION_TEXT "\"", SSLeay_version(SSLEAY_VERSION));
962
963                 // Register application specific data
964                 char exdatastr[] = "inspircd";
965                 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
966                 if (exdataindex < 0)
967                         throw ModuleException("Failed to register application specific data");
968
969                 ReadProfiles();
970         }
971
972         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
973         {
974                 if (param != "ssl")
975                         return;
976
977                 try
978                 {
979                         ReadProfiles();
980                 }
981                 catch (ModuleException& ex)
982                 {
983                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
984                 }
985         }
986
987         void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
988         {
989                 if (type == ExtensionItem::EXT_USER)
990                 {
991                         LocalUser* user = IS_LOCAL((User*)item);
992
993                         if ((user) && (user->eh.GetModHook(this)))
994                         {
995                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
996                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
997                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
998                         }
999                 }
1000         }
1001
1002         ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
1003         {
1004                 const OpenSSLIOHook* const iohook = static_cast<OpenSSLIOHook*>(user->eh.GetModHook(this));
1005                 if ((iohook) && (!iohook->IsHandshakeDone()))
1006                         return MOD_RES_DENY;
1007                 return MOD_RES_PASSTHRU;
1008         }
1009
1010         Version GetVersion() CXX11_OVERRIDE
1011         {
1012                 return Version("Provides SSL support for clients", VF_VENDOR);
1013         }
1014 };
1015
1016 MODULE_INIT(ModuleSSLOpenSSL)