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