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