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