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