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