]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
Don't kill cloaking users when hash/md5 is missing.
[user/henk/code/inspircd.git] / src / modules / m_cloaking.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2017-2019 B00mX0r <b00mx0r@aureus.pw>
5  *   Copyright (C) 2017 Sheogorath <sheogorath@shivering-isles.com>
6  *   Copyright (C) 2016 Adam <Adam@anope.org>
7  *   Copyright (C) 2014 Thomas Fargeix <t.fargeix@gmail.com>
8  *   Copyright (C) 2013, 2018 Attila Molnar <attilamolnar@hush.com>
9  *   Copyright (C) 2013, 2016-2019 Sadie Powell <sadie@witchery.services>
10  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
11  *   Copyright (C) 2011 jackmcbarn <jackmcbarn@inspircd.org>
12  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
13  *   Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
14  *   Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
15  *   Copyright (C) 2007-2008 Dennis Friis <peavey@inspircd.org>
16  *   Copyright (C) 2006 Oliver Lupton <om@inspircd.org>
17  *
18  * This file is part of InspIRCd.  InspIRCd is free software: you can
19  * redistribute it and/or modify it under the terms of the GNU General Public
20  * License as published by the Free Software Foundation, version 2.
21  *
22  * This program is distributed in the hope that it will be useful, but WITHOUT
23  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
24  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
25  * details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
29  */
30
31
32 #include "inspircd.h"
33 #include "modules/hash.h"
34
35 enum CloakMode
36 {
37         /** 2.0 cloak of "half" of the hostname plus the full IP hash */
38         MODE_HALF_CLOAK,
39
40         /** 2.0 cloak of IP hash, split at 2 common CIDR range points */
41         MODE_OPAQUE
42 };
43
44 // lowercase-only encoding similar to base64, used for hash output
45 static const char base32[] = "0123456789abcdefghijklmnopqrstuv";
46
47 // The minimum length of a cloak key.
48 static const size_t minkeylen = 30;
49
50 struct CloakInfo
51 {
52         // The method used for cloaking users.
53         CloakMode mode;
54
55         // The number of parts of the hostname shown when using half cloaking.
56         unsigned int domainparts;
57
58         // Whether to ignore the case of a hostname when cloaking it.
59         bool ignorecase;
60
61         // The secret used for generating cloaks.
62         std::string key;
63
64         // The prefix for cloaks (e.g. MyNet-).
65         std::string prefix;
66
67         // The suffix for IP cloaks (e.g. .IP).
68         std::string suffix;
69
70         CloakInfo(CloakMode Mode, const std::string& Key, const std::string& Prefix, const std::string& Suffix, bool IgnoreCase, unsigned int DomainParts = 0)
71                 : mode(Mode)
72                 , domainparts(DomainParts)
73                 , ignorecase(IgnoreCase)
74                 , key(Key)
75                 , prefix(Prefix)
76                 , suffix(Suffix)
77         {
78         }
79 };
80
81 typedef std::vector<std::string> CloakList;
82
83 /** Handles user mode +x
84  */
85 class CloakUser : public ModeHandler
86 {
87  public:
88         bool active;
89         SimpleExtItem<CloakList> ext;
90         std::string debounce_uid;
91         time_t debounce_ts;
92         int debounce_count;
93
94         CloakUser(Module* source)
95                 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER)
96                 , active(false)
97                 , ext("cloaked_host", ExtensionItem::EXT_USER, source)
98                 , debounce_ts(0)
99                 , debounce_count(0)
100         {
101         }
102
103         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding) CXX11_OVERRIDE
104         {
105                 LocalUser* user = IS_LOCAL(dest);
106
107                 /* For remote clients, we don't take any action, we just allow it.
108                  * The local server where they are will set their cloak instead.
109                  * This is fine, as we will receive it later.
110                  */
111                 if (!user)
112                 {
113                         // Remote setters broadcast mode before host while local setters do the opposite, so this takes that into account
114                         active = IS_LOCAL(source) ? adding : !adding;
115                         dest->SetMode(this, adding);
116                         return MODEACTION_ALLOW;
117                 }
118
119                 if (user->uuid == debounce_uid && debounce_ts == ServerInstance->Time())
120                 {
121                         // prevent spamming using /mode user +x-x+x-x+x-x
122                         if (++debounce_count > 2)
123                                 return MODEACTION_DENY;
124                 }
125                 else
126                 {
127                         debounce_uid = user->uuid;
128                         debounce_count = 1;
129                         debounce_ts = ServerInstance->Time();
130                 }
131
132                 if (adding == user->IsModeSet(this))
133                         return MODEACTION_DENY;
134
135                 /* don't allow this user to spam modechanges */
136                 if (source == dest)
137                         user->CommandFloodPenalty += 5000;
138
139                 if (adding)
140                 {
141                         // assume this is more correct
142                         if (user->registered != REG_ALL && user->GetRealHost() != user->GetDisplayedHost())
143                                 return MODEACTION_DENY;
144
145                         CloakList* cloaks = ext.get(user);
146                         if (!cloaks)
147                         {
148                                 /* Force creation of missing cloak */
149                                 try
150                                 {
151                                         creator->OnUserConnect(user);
152                                         cloaks = ext.get(user);
153                                 }
154                                 catch (CoreException& modexcept)
155                                 {
156                                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Exception caught when generating cloak: " + modexcept.GetReason());
157                                         return MODEACTION_DENY;
158                                 }
159                         }
160
161                         // If we have a cloak then set the hostname.
162                         if (cloaks && !cloaks->empty())
163                         {
164                                 user->ChangeDisplayedHost(cloaks->front());
165                                 user->SetMode(this, true);
166                                 return MODEACTION_ALLOW;
167                         }
168                         else
169                                 return MODEACTION_DENY;
170                 }
171                 else
172                 {
173                         /* User is removing the mode, so restore their real host
174                          * and make it match the displayed one.
175                          */
176                         user->SetMode(this, false);
177                         user->ChangeDisplayedHost(user->GetRealHost().c_str());
178                         return MODEACTION_ALLOW;
179                 }
180         }
181 };
182
183 class CommandCloak : public Command
184 {
185  public:
186         CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
187         {
188                 flags_needed = 'o';
189                 syntax = "<host>";
190         }
191
192         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE;
193 };
194
195 class ModuleCloaking : public Module
196 {
197  public:
198         CloakUser cu;
199         CommandCloak ck;
200         std::vector<CloakInfo> cloaks;
201         dynamic_reference<HashProvider> Hash;
202
203         ModuleCloaking()
204                 : cu(this)
205                 , ck(this)
206                 , Hash(this, "hash/md5")
207         {
208         }
209
210         /** Takes a domain name and retrieves the subdomain which should be visible.
211          * This is usually the last \p domainparts labels but if not enough are
212          * present then all but the most specific label are used. If the domain name
213          * consists of one label only then none are used.
214          *
215          * Here are some examples for how domain names will be shortened assuming
216          * \p domainparts is set to the default of 3.
217          *
218          *   "this.is.an.example.com"  =>  ".an.example.com"
219          *   "an.example.com"          =>  ".example.com"
220          *   "example.com"             =>  ".com"
221          *   "localhost"               =>  ""
222          *
223          * @param host The hostname to cloak.
224          * @param domainparts The number of domain labels that should be visible.
225          * @return The visible segment of the hostname.
226          */
227         std::string VisibleDomainParts(const std::string& host, unsigned int domainparts)
228         {
229                 // The position at which we found the last dot.
230                 std::string::const_reverse_iterator dotpos;
231
232                 // The number of dots we have seen so far.
233                 unsigned int seendots = 0;
234
235                 for (std::string::const_reverse_iterator iter = host.rbegin(); iter != host.rend(); ++iter)
236                 {
237                         if (*iter != '.')
238                                 continue;
239
240                         // We have found a dot!
241                         dotpos = iter;
242                         seendots += 1;
243
244                         // Do we have enough segments to stop?
245                         if (seendots >= domainparts)
246                                 break;
247                 }
248
249                 // We only returns a domain part if more than one label is
250                 // present. See above for a full explanation.
251                 if (!seendots)
252                         return "";
253                 return std::string(dotpos.base() - 1, host.end());
254         }
255
256         /**
257          * 2.0-style cloaking function
258          * @param item The item to cloak (part of an IP or hostname)
259          * @param id A unique ID for this type of item (to make it unique if the item matches)
260          * @param len The length of the output. Maximum for MD5 is 16 characters.
261          */
262         std::string SegmentCloak(const CloakInfo& info, const std::string& item, char id, size_t len)
263         {
264                 std::string input;
265                 input.reserve(info.key.length() + 3 + item.length());
266                 input.append(1, id);
267                 input.append(info.key);
268                 input.append(1, '\0'); // null does not terminate a C++ string
269                 if (info.ignorecase)
270                         std::transform(item.begin(), item.end(), std::back_inserter(input), ::tolower);
271                 else
272                         input.append(item);
273
274                 std::string rv = Hash->GenerateRaw(input).substr(0,len);
275                 for(size_t i = 0; i < len; i++)
276                 {
277                         // this discards 3 bits per byte. We have an
278                         // overabundance of bits in the hash output, doesn't
279                         // matter which ones we are discarding.
280                         rv[i] = base32[rv[i] & 0x1F];
281                 }
282                 return rv;
283         }
284
285         std::string SegmentIP(const CloakInfo& info, const irc::sockets::sockaddrs& ip, bool full)
286         {
287                 std::string bindata;
288                 size_t hop1, hop2, hop3;
289                 size_t len1, len2;
290                 std::string rv;
291                 if (ip.family() == AF_INET6)
292                 {
293                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
294                         hop1 = 8;
295                         hop2 = 6;
296                         hop3 = 4;
297                         len1 = 6;
298                         len2 = 4;
299                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
300                         //     6  4  4    9/6
301                         rv.reserve(info.prefix.length() + 26 + info.suffix.length());
302                 }
303                 else
304                 {
305                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
306                         hop1 = 3;
307                         hop2 = 0;
308                         hop3 = 2;
309                         len1 = len2 = 3;
310                         // pfx s1.s2. (xxx.xxx or s3) sfx
311                         rv.reserve(info.prefix.length() + 15 + info.suffix.length());
312                 }
313
314                 rv.append(info.prefix);
315                 rv.append(SegmentCloak(info, bindata, 10, len1));
316                 rv.append(1, '.');
317                 bindata.erase(hop1);
318                 rv.append(SegmentCloak(info, bindata, 11, len2));
319                 if (hop2)
320                 {
321                         rv.append(1, '.');
322                         bindata.erase(hop2);
323                         rv.append(SegmentCloak(info, bindata, 12, len2));
324                 }
325
326                 if (full)
327                 {
328                         rv.append(1, '.');
329                         bindata.erase(hop3);
330                         rv.append(SegmentCloak(info, bindata, 13, 6));
331                         rv.append(info.suffix);
332                 }
333                 else
334                 {
335                         if (ip.family() == AF_INET6)
336                         {
337                                 rv.append(InspIRCd::Format(".%02x%02x.%02x%02x%s",
338                                         ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
339                                         ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], info.suffix.c_str()));
340                         }
341                         else
342                         {
343                                 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
344                                 rv.append(InspIRCd::Format(".%d.%d%s", ip4[1], ip4[0], info.suffix.c_str()));
345                         }
346                 }
347                 return rv;
348         }
349
350         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) CXX11_OVERRIDE
351         {
352                 LocalUser* lu = IS_LOCAL(user);
353                 if (!lu)
354                         return MOD_RES_PASSTHRU;
355
356                 // Force the creation of cloaks if not already set.
357                 OnUserConnect(lu);
358
359                 // If the user has no cloaks (i.e. UNIX socket) then we do nothing here.
360                 CloakList* cloaklist = cu.ext.get(user);
361                 if (!cloaklist || cloaklist->empty())
362                         return MOD_RES_PASSTHRU;
363
364                 // Check if they have a cloaked host but are not using it.
365                 for (CloakList::const_iterator iter = cloaklist->begin(); iter != cloaklist->end(); ++iter)
366                 {
367                         const std::string& cloak = *iter;
368                         if (cloak != user->GetDisplayedHost())
369                         {
370                                 const std::string cloakMask = user->nick + "!" + user->ident + "@" + cloak;
371                                 if (InspIRCd::Match(cloakMask, mask))
372                                         return MOD_RES_DENY;
373                         }
374                 }
375                 return MOD_RES_PASSTHRU;
376         }
377
378         void Prioritize() CXX11_OVERRIDE
379         {
380                 /* Needs to be after m_banexception etc. */
381                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
382         }
383
384         // this unsets umode +x on every host change. If we are actually doing a +x
385         // mode change, we will call SetMode back to true AFTER the host change is done.
386         void OnChangeHost(User* u, const std::string& host) CXX11_OVERRIDE
387         {
388                 if (u->IsModeSet(cu) && !cu.active)
389                 {
390                         u->SetMode(cu, false);
391
392                         LocalUser* luser = IS_LOCAL(u);
393                         if (!luser)
394                                 return;
395
396                         Modes::ChangeList modechangelist;
397                         modechangelist.push_remove(&cu);
398                         ClientProtocol::Events::Mode modeevent(ServerInstance->FakeClient, NULL, u, modechangelist);
399                         luser->Send(modeevent);
400                 }
401                 cu.active = false;
402         }
403
404         Version GetVersion() CXX11_OVERRIDE
405         {
406                 std::string testcloak = "broken";
407                 if (Hash && !cloaks.empty())
408                 {
409                         const CloakInfo& info = cloaks.front();
410                         switch (info.mode)
411                         {
412                                 case MODE_HALF_CLOAK:
413                                         // Use old cloaking verification to stay compatible with 2.0
414                                         // But verify domainparts and ignorecase when use 3.0-only features
415                                         if (info.domainparts == 3 && !info.ignorecase)
416                                                 testcloak = info.prefix + SegmentCloak(info, "*", 3, 8) + info.suffix;
417                                         else
418                                         {
419                                                 irc::sockets::sockaddrs sa;
420                                                 testcloak = GenCloak(info, sa, "", testcloak + ConvToStr(info.domainparts)) + (info.ignorecase ? "-ci" : "");
421                                         }
422                                         break;
423                                 case MODE_OPAQUE:
424                                         testcloak = info.prefix + SegmentCloak(info, "*", 4, 8) + info.suffix + (info.ignorecase ? "-ci" : "");
425                         }
426                 }
427                 return Version("Adds user mode x (cloak) which allows user hostnames to be hidden.", VF_COMMON|VF_VENDOR, testcloak);
428         }
429
430         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
431         {
432                 ConfigTagList tags = ServerInstance->Config->ConfTags("cloak");
433                 if (tags.first == tags.second)
434                         throw ModuleException("You have loaded the cloaking module but not configured any <cloak> tags!");
435
436                 std::vector<CloakInfo> newcloaks;
437                 for (ConfigIter i = tags.first; i != tags.second; ++i)
438                 {
439                         ConfigTag* tag = i->second;
440
441                         // Ensure that we have the <cloak:key> parameter.
442                         const std::string key = tag->getString("key");
443                         if (key.empty())
444                                 throw ModuleException("You have not defined a cloaking key. Define <cloak:key> as a " + ConvToStr(minkeylen) + "+ character network-wide secret, at " + tag->getTagLocation());
445
446                         // If we are the first cloak method then mandate a strong key.
447                         if (i == tags.first && key.length() < minkeylen)
448                                 throw ModuleException("Your cloaking key is not secure. It should be at least " + ConvToStr(minkeylen) + " characters long, at " + tag->getTagLocation());
449
450                         const bool ignorecase = tag->getBool("ignorecase");
451                         const std::string mode = tag->getString("mode");
452                         const std::string prefix = tag->getString("prefix");
453                         const std::string suffix = tag->getString("suffix", ".IP");
454                         if (stdalgo::string::equalsci(mode, "half"))
455                         {
456                                 unsigned int domainparts = tag->getUInt("domainparts", 3, 1, 10);
457                                 newcloaks.push_back(CloakInfo(MODE_HALF_CLOAK, key, prefix, suffix, ignorecase, domainparts));
458                         }
459                         else if (stdalgo::string::equalsci(mode, "full"))
460                                 newcloaks.push_back(CloakInfo(MODE_OPAQUE, key, prefix, suffix, ignorecase));
461                         else
462                                 throw ModuleException(mode + " is an invalid value for <cloak:mode>; acceptable values are 'half' and 'full', at " + tag->getTagLocation());
463                 }
464
465                 // The cloak configuration was valid so we can apply it.
466                 cloaks.swap(newcloaks);
467         }
468
469         std::string GenCloak(const CloakInfo& info, const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
470         {
471                 std::string chost;
472
473                 irc::sockets::sockaddrs hostip;
474                 bool host_is_ip = irc::sockets::aptosa(host, ip.port(), hostip) && hostip == ip;
475
476                 switch (info.mode)
477                 {
478                         case MODE_HALF_CLOAK:
479                         {
480                                 if (!host_is_ip)
481                                         chost = info.prefix + SegmentCloak(info, host, 1, 6) + VisibleDomainParts(host, info.domainparts);
482                                 if (chost.empty() || chost.length() > 50)
483                                         chost = SegmentIP(info, ip, false);
484                                 break;
485                         }
486                         case MODE_OPAQUE:
487                         default:
488                                 chost = SegmentIP(info, ip, true);
489                 }
490                 return chost;
491         }
492
493         void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
494         {
495                 // Connecting users are handled in OnUserConnect not here.
496                 if (user->registered != REG_ALL)
497                         return;
498
499                 // Remove the cloaks and generate new ones.
500                 cu.ext.unset(user);
501                 OnUserConnect(user);
502
503                 // If a user is using a cloak then update it.
504                 if (user->IsModeSet(cu))
505                 {
506                         CloakList* cloaklist = cu.ext.get(user);
507                         user->ChangeDisplayedHost(cloaklist->front());
508                 }
509         }
510
511         void OnUserConnect(LocalUser* dest) CXX11_OVERRIDE
512         {
513                 if (cu.ext.get(dest))
514                         return;
515
516                 // TODO: decide how we are going to cloak AF_UNIX hostnames.
517                 if (dest->client_sa.family() != AF_INET && dest->client_sa.family() != AF_INET6)
518                         return;
519
520                 CloakList cloaklist;
521                 for (std::vector<CloakInfo>::const_iterator iter = cloaks.begin(); iter != cloaks.end(); ++iter)
522                         cloaklist.push_back(GenCloak(*iter, dest->client_sa, dest->GetIPString(), dest->GetRealHost()));
523                 cu.ext.set(dest, cloaklist);
524         }
525 };
526
527 CmdResult CommandCloak::Handle(User* user, const Params& parameters)
528 {
529         ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
530
531         // If we're cloaking an IP address we pass it in the IP field too.
532         irc::sockets::sockaddrs sa;
533         const char* ipaddr = irc::sockets::aptosa(parameters[0], 0, sa) ? parameters[0].c_str() : "";
534
535         unsigned int id = 0;
536         for (std::vector<CloakInfo>::const_iterator iter = mod->cloaks.begin(); iter != mod->cloaks.end(); ++iter)
537         {
538                 const std::string cloak = mod->GenCloak(*iter, sa, ipaddr, parameters[0]);
539                 user->WriteNotice(InspIRCd::Format("*** Cloak #%u for %s is %s", ++id, parameters[0].c_str(), cloak.c_str()));
540         }
541         return CMD_SUCCESS;
542 }
543
544 MODULE_INIT(ModuleCloaking)