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