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