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