]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
m_ssl_openssl Store a pointer to the OpenSSLIOHook object in SSL objects
[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 #include <openssl/ssl.h>
35 #include <openssl/err.h>
36
37 #ifdef _WIN32
38 # pragma comment(lib, "ssleay32.lib")
39 # pragma comment(lib, "libeay32.lib")
40 #endif
41
42 /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
43 /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */
44
45 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
46
47 static bool SelfSigned = false;
48 static int exdataindex;
49
50 char* get_error()
51 {
52         return ERR_error_string(ERR_get_error(), NULL);
53 }
54
55 static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx);
56
57 namespace OpenSSL
58 {
59         class Exception : public ModuleException
60         {
61          public:
62                 Exception(const std::string& reason)
63                         : ModuleException(reason) { }
64         };
65
66         class DHParams
67         {
68                 DH* dh;
69
70          public:
71                 DHParams(const std::string& filename)
72                 {
73                         BIO* dhpfile = BIO_new_file(filename.c_str(), "r");
74                         if (dhpfile == NULL)
75                                 throw Exception("Couldn't open DH file " + filename);
76
77                         dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
78                         BIO_free(dhpfile);
79
80                         if (!dh)
81                                 throw Exception("Couldn't read DH params from file " + filename);
82                 }
83
84                 ~DHParams()
85                 {
86                         DH_free(dh);
87                 }
88
89                 DH* get()
90                 {
91                         return dh;
92                 }
93         };
94
95         class Context
96         {
97                 SSL_CTX* const ctx;
98
99          public:
100                 Context(SSL_CTX* context)
101                         : ctx(context)
102                 {
103                         // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
104                         // and when choosing a cipher, use the server's preferences instead of the client preferences.
105                         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE);
106                         SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
107                         SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
108
109                         const unsigned char session_id[] = "inspircd";
110                         SSL_CTX_set_session_id_context(ctx, session_id, sizeof(session_id) - 1);
111                 }
112
113                 ~Context()
114                 {
115                         SSL_CTX_free(ctx);
116                 }
117
118                 bool SetDH(DHParams& dh)
119                 {
120                         return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0);
121                 }
122
123                 bool SetCiphers(const std::string& ciphers)
124                 {
125                         return SSL_CTX_set_cipher_list(ctx, ciphers.c_str());
126                 }
127
128                 bool SetCerts(const std::string& filename)
129                 {
130                         return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str());
131                 }
132
133                 bool SetPrivateKey(const std::string& filename)
134                 {
135                         return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM);
136                 }
137
138                 bool SetCA(const std::string& filename)
139                 {
140                         return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0);
141                 }
142
143                 SSL* CreateSession()
144                 {
145                         return SSL_new(ctx);
146                 }
147         };
148
149         class Profile : public refcountbase
150         {
151                 /** Name of this profile
152                  */
153                 const std::string name;
154
155                 /** DH parameters in use
156                  */
157                 DHParams dh;
158
159                 /** OpenSSL makes us have two contexts, one for servers and one for clients
160                  */
161                 Context ctx;
162                 Context clictx;
163
164                 /** Digest to use when generating fingerprints
165                  */
166                 const EVP_MD* digest;
167
168                 /** Last error, set by error_callback()
169                  */
170                 std::string lasterr;
171
172                 static int error_callback(const char* str, size_t len, void* u)
173                 {
174                         Profile* profile = reinterpret_cast<Profile*>(u);
175                         profile->lasterr = std::string(str, len - 1);
176                         return 0;
177                 }
178
179          public:
180                 Profile(const std::string& profilename, ConfigTag* tag)
181                         : name(profilename)
182                         , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem")))
183                         , ctx(SSL_CTX_new(SSLv23_server_method()))
184                         , clictx(SSL_CTX_new(SSLv23_client_method()))
185                 {
186                         if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh)))
187                                 throw Exception("Couldn't set DH parameters");
188
189                         std::string hash = tag->getString("hash", "md5");
190                         digest = EVP_get_digestbyname(hash.c_str());
191                         if (digest == NULL)
192                                 throw Exception("Unknown hash type " + hash);
193
194                         std::string ciphers = tag->getString("ciphers");
195                         if (!ciphers.empty())
196                         {
197                                 if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers)))
198                                 {
199                                         ERR_print_errors_cb(error_callback, this);
200                                         throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr);
201                                 }
202                         }
203
204                         /* Load our keys and certificates
205                          * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
206                          */
207                         std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem"));
208                         if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename)))
209                         {
210                                 ERR_print_errors_cb(error_callback, this);
211                                 throw Exception("Can't read certificate file: " + lasterr);
212                         }
213
214                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem"));
215                         if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename)))
216                         {
217                                 ERR_print_errors_cb(error_callback, this);
218                                 throw Exception("Can't read key file: " + lasterr);
219                         }
220
221                         // Load the CAs we trust
222                         filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem"));
223                         if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename)))
224                         {
225                                 ERR_print_errors_cb(error_callback, this);
226                                 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());
227                         }
228                 }
229
230                 const std::string& GetName() const { return name; }
231                 SSL* CreateServerSession() { return ctx.CreateSession(); }
232                 SSL* CreateClientSession() { return clictx.CreateSession(); }
233                 const EVP_MD* GetDigest() { return digest; }
234         };
235 }
236
237 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
238 {
239         /* XXX: This will allow self signed certificates.
240          * In the future if we want an option to not allow this,
241          * we can just return preverify_ok here, and openssl
242          * will boot off self-signed and invalid peer certs.
243          */
244         int ve = X509_STORE_CTX_get_error(ctx);
245
246         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
247
248         return 1;
249 }
250
251 class OpenSSLIOHook : public SSLIOHook
252 {
253  private:
254         SSL* sess;
255         issl_status status;
256         const bool outbound;
257         bool data_to_write;
258         reference<OpenSSL::Profile> profile;
259
260         bool Handshake(StreamSocket* user)
261         {
262                 int ret;
263
264                 if (outbound)
265                         ret = SSL_connect(sess);
266                 else
267                         ret = SSL_accept(sess);
268
269                 if (ret < 0)
270                 {
271                         int err = SSL_get_error(sess, ret);
272
273                         if (err == SSL_ERROR_WANT_READ)
274                         {
275                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
276                                 this->status = ISSL_HANDSHAKING;
277                                 return true;
278                         }
279                         else if (err == SSL_ERROR_WANT_WRITE)
280                         {
281                                 SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
282                                 this->status = ISSL_HANDSHAKING;
283                                 return true;
284                         }
285                         else
286                         {
287                                 CloseSession();
288                         }
289
290                         return false;
291                 }
292                 else if (ret > 0)
293                 {
294                         // Handshake complete.
295                         VerifyCertificate();
296
297                         status = ISSL_OPEN;
298
299                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
300
301                         return true;
302                 }
303                 else if (ret == 0)
304                 {
305                         CloseSession();
306                         return true;
307                 }
308
309                 return true;
310         }
311
312         void CloseSession()
313         {
314                 if (sess)
315                 {
316                         SSL_shutdown(sess);
317                         SSL_free(sess);
318                 }
319                 sess = NULL;
320                 certificate = NULL;
321                 status = ISSL_NONE;
322                 errno = EIO;
323         }
324
325         void VerifyCertificate()
326         {
327                 X509* cert;
328                 ssl_cert* certinfo = new ssl_cert;
329                 this->certificate = certinfo;
330                 unsigned int n;
331                 unsigned char md[EVP_MAX_MD_SIZE];
332
333                 cert = SSL_get_peer_certificate(sess);
334
335                 if (!cert)
336                 {
337                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
338                         return;
339                 }
340
341                 certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK);
342
343                 if (!SelfSigned)
344                 {
345                         certinfo->unknownsigner = false;
346                         certinfo->trusted = true;
347                 }
348                 else
349                 {
350                         certinfo->unknownsigner = true;
351                         certinfo->trusted = false;
352                 }
353
354                 char buf[512];
355                 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
356                 certinfo->dn = buf;
357                 // Make sure there are no chars in the string that we consider invalid
358                 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
359                         certinfo->dn.clear();
360
361                 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
362                 certinfo->issuer = buf;
363                 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
364                         certinfo->issuer.clear();
365
366                 if (!X509_digest(cert, profile->GetDigest(), md, &n))
367                 {
368                         certinfo->error = "Out of memory generating fingerprint";
369                 }
370                 else
371                 {
372                         certinfo->fingerprint = BinToHex(md, n);
373                 }
374
375                 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))
376                 {
377                         certinfo->error = "Not activated, or expired certificate";
378                 }
379
380                 X509_free(cert);
381         }
382
383  public:
384         OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool is_outbound, SSL* session, const reference<OpenSSL::Profile>& sslprofile)
385                 : SSLIOHook(hookprov)
386                 , sess(session)
387                 , status(ISSL_NONE)
388                 , outbound(is_outbound)
389                 , data_to_write(false)
390                 , profile(sslprofile)
391         {
392                 if (sess == NULL)
393                         return;
394                 if (SSL_set_fd(sess, sock->GetFd()) == 0)
395                         throw ModuleException("Can't set fd with SSL_set_fd: " + ConvToStr(sock->GetFd()));
396
397                 SSL_set_ex_data(sess, exdataindex, this);
398                 sock->AddIOHook(this);
399                 Handshake(sock);
400         }
401
402         void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE
403         {
404                 CloseSession();
405         }
406
407         int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE
408         {
409                 if (!sess)
410                 {
411                         CloseSession();
412                         return -1;
413                 }
414
415                 if (status == ISSL_HANDSHAKING)
416                 {
417                         // The handshake isn't finished and it wants to read, try to finish it.
418                         if (!Handshake(user))
419                         {
420                                 // Couldn't resume handshake.
421                                 if (status == ISSL_NONE)
422                                         return -1;
423                                 return 0;
424                         }
425                 }
426
427                 // If we resumed the handshake then this->status will be ISSL_OPEN
428
429                 if (status == ISSL_OPEN)
430                 {
431                         char* buffer = ServerInstance->GetReadBuffer();
432                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
433                         int ret = SSL_read(sess, buffer, bufsiz);
434
435                         if (ret > 0)
436                         {
437                                 recvq.append(buffer, ret);
438                                 if (data_to_write)
439                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
440                                 return 1;
441                         }
442                         else if (ret == 0)
443                         {
444                                 // Client closed connection.
445                                 CloseSession();
446                                 user->SetError("Connection closed");
447                                 return -1;
448                         }
449                         else if (ret < 0)
450                         {
451                                 int err = SSL_get_error(sess, ret);
452
453                                 if (err == SSL_ERROR_WANT_READ)
454                                 {
455                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
456                                         return 0;
457                                 }
458                                 else if (err == SSL_ERROR_WANT_WRITE)
459                                 {
460                                         SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
461                                         return 0;
462                                 }
463                                 else
464                                 {
465                                         CloseSession();
466                                         return -1;
467                                 }
468                         }
469                 }
470
471                 return 0;
472         }
473
474         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE
475         {
476                 if (!sess)
477                 {
478                         CloseSession();
479                         return -1;
480                 }
481
482                 data_to_write = true;
483
484                 if (status == ISSL_HANDSHAKING)
485                 {
486                         if (!Handshake(user))
487                         {
488                                 // Couldn't resume handshake.
489                                 if (status == ISSL_NONE)
490                                         return -1;
491                                 return 0;
492                         }
493                 }
494
495                 if (status == ISSL_OPEN)
496                 {
497                         int ret = SSL_write(sess, buffer.data(), buffer.size());
498                         if (ret == (int)buffer.length())
499                         {
500                                 data_to_write = false;
501                                 SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
502                                 return 1;
503                         }
504                         else if (ret > 0)
505                         {
506                                 buffer = buffer.substr(ret);
507                                 SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
508                                 return 0;
509                         }
510                         else if (ret == 0)
511                         {
512                                 CloseSession();
513                                 return -1;
514                         }
515                         else if (ret < 0)
516                         {
517                                 int err = SSL_get_error(sess, ret);
518
519                                 if (err == SSL_ERROR_WANT_WRITE)
520                                 {
521                                         SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
522                                         return 0;
523                                 }
524                                 else if (err == SSL_ERROR_WANT_READ)
525                                 {
526                                         SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ);
527                                         return 0;
528                                 }
529                                 else
530                                 {
531                                         CloseSession();
532                                         return -1;
533                                 }
534                         }
535                 }
536                 return 0;
537         }
538
539         void TellCiphersAndFingerprint(LocalUser* user)
540         {
541                 if (sess)
542                 {
543                         std::string text = "*** You are connected using SSL cipher '" + std::string(SSL_get_cipher(sess)) + "'";
544                         const std::string& fingerprint = certificate->fingerprint;
545                         if (!fingerprint.empty())
546                                 text += " and your SSL certificate fingerprint is " + fingerprint;
547
548                         user->WriteNotice(text);
549                 }
550         }
551 };
552
553 class OpenSSLIOHookProvider : public refcountbase, public IOHookProvider
554 {
555         reference<OpenSSL::Profile> profile;
556
557  public:
558         OpenSSLIOHookProvider(Module* mod, reference<OpenSSL::Profile>& prof)
559                 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
560                 , profile(prof)
561         {
562                 ServerInstance->Modules->AddService(*this);
563         }
564
565         ~OpenSSLIOHookProvider()
566         {
567                 ServerInstance->Modules->DelService(*this);
568         }
569
570         void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
571         {
572                 new OpenSSLIOHook(this, sock, false, profile->CreateServerSession(), profile);
573         }
574
575         void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
576         {
577                 new OpenSSLIOHook(this, sock, true, profile->CreateClientSession(), profile);
578         }
579 };
580
581 class ModuleSSLOpenSSL : public Module
582 {
583         typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList;
584
585         ProfileList profiles;
586
587         void ReadProfiles()
588         {
589                 ProfileList newprofiles;
590                 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
591                 if (tags.first == tags.second)
592                 {
593                         // Create a default profile named "openssl"
594                         const std::string defname = "openssl";
595                         ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
596                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag");
597
598                         try
599                         {
600                                 reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag));
601                                 newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
602                         }
603                         catch (OpenSSL::Exception& ex)
604                         {
605                                 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
606                         }
607                 }
608
609                 for (ConfigIter i = tags.first; i != tags.second; ++i)
610                 {
611                         ConfigTag* tag = i->second;
612                         if (tag->getString("provider") != "openssl")
613                                 continue;
614
615                         std::string name = tag->getString("name");
616                         if (name.empty())
617                         {
618                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
619                                 continue;
620                         }
621
622                         reference<OpenSSL::Profile> profile;
623                         try
624                         {
625                                 profile = new OpenSSL::Profile(name, tag);
626                         }
627                         catch (CoreException& ex)
628                         {
629                                 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
630                         }
631
632                         newprofiles.push_back(new OpenSSLIOHookProvider(this, profile));
633                 }
634
635                 profiles.swap(newprofiles);
636         }
637
638  public:
639         ModuleSSLOpenSSL()
640         {
641                 // Initialize OpenSSL
642                 SSL_library_init();
643                 SSL_load_error_strings();
644         }
645
646         void init() CXX11_OVERRIDE
647         {
648                 // Register application specific data
649                 char exdatastr[] = "inspircd";
650                 exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL);
651                 if (exdataindex < 0)
652                         throw ModuleException("Failed to register application specific data");
653
654                 ReadProfiles();
655         }
656
657         void OnModuleRehash(User* user, const std::string &param) CXX11_OVERRIDE
658         {
659                 if (param != "ssl")
660                         return;
661
662                 try
663                 {
664                         ReadProfiles();
665                 }
666                 catch (ModuleException& ex)
667                 {
668                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
669                 }
670         }
671
672         void OnUserConnect(LocalUser* user) CXX11_OVERRIDE
673         {
674                 IOHook* hook = user->eh.GetIOHook();
675                 if (hook && hook->prov->creator == this)
676                         static_cast<OpenSSLIOHook*>(hook)->TellCiphersAndFingerprint(user);
677         }
678
679         void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
680         {
681                 if (target_type == TYPE_USER)
682                 {
683                         LocalUser* user = IS_LOCAL((User*)item);
684
685                         if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this)
686                         {
687                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
688                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
689                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
690                         }
691                 }
692         }
693
694         Version GetVersion() CXX11_OVERRIDE
695         {
696                 return Version("Provides SSL support for clients", VF_VENDOR);
697         }
698 };
699
700 MODULE_INIT(ModuleSSLOpenSSL)