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