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