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