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