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