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