2 * InspIRCd -- Internet Relay Chat Daemon
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-2020 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 Dennis Friis <peavey@inspircd.org>
15 * Copyright (C) 2007 John Brooks <special@inspircd.org>
16 * Copyright (C) 2006 Oliver Lupton <om@inspircd.org>
17 * Copyright (C) 2003, 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
19 * This file is part of InspIRCd. InspIRCd is free software: you can
20 * redistribute it and/or modify it under the terms of the GNU General Public
21 * License as published by the Free Software Foundation, version 2.
23 * This program is distributed in the hope that it will be useful, but WITHOUT
24 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
25 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 #include "modules/hash.h"
38 /** 2.0 cloak of "half" of the hostname plus the full IP hash */
41 /** 2.0 cloak of IP hash, split at 2 common CIDR range points */
45 // lowercase-only encoding similar to base64, used for hash output
46 static const char base32[] = "0123456789abcdefghijklmnopqrstuv";
48 // The minimum length of a cloak key.
49 static const size_t minkeylen = 30;
53 // The method used for cloaking users.
56 // The number of parts of the hostname shown when using half cloaking.
57 unsigned int domainparts;
59 // Whether to ignore the case of a hostname when cloaking it.
62 // The secret used for generating cloaks.
65 // The prefix for cloaks (e.g. MyNet-).
68 // The suffix for IP cloaks (e.g. .IP).
71 CloakInfo(CloakMode Mode, const std::string& Key, const std::string& Prefix, const std::string& Suffix, bool IgnoreCase, unsigned int DomainParts = 0)
73 , domainparts(DomainParts)
74 , ignorecase(IgnoreCase)
82 typedef std::vector<std::string> CloakList;
84 class CloakExtItem : public SimpleExtItem<CloakList>
87 CloakExtItem(Module* Creator)
88 : SimpleExtItem("cloaks", ExtensionItem::EXT_USER, Creator)
92 std::string ToHuman(const Extensible* container, void* item) const CXX11_OVERRIDE
94 return stdalgo::string::join(*static_cast<CloakList*>(item), ' ');
98 class CloakUser : public ModeHandler
103 std::string debounce_uid;
107 CloakUser(Module* source)
108 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER)
116 ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding) CXX11_OVERRIDE
118 LocalUser* user = IS_LOCAL(dest);
120 /* For remote clients, we don't take any action, we just allow it.
121 * The local server where they are will set their cloak instead.
122 * This is fine, as we will receive it later.
126 // Remote setters broadcast mode before host while local setters do the opposite, so this takes that into account
127 active = IS_LOCAL(source) ? adding : !adding;
128 dest->SetMode(this, adding);
129 return MODEACTION_ALLOW;
132 if (user->uuid == debounce_uid && debounce_ts == ServerInstance->Time())
134 // prevent spamming using /mode user +x-x+x-x+x-x
135 if (++debounce_count > 2)
136 return MODEACTION_DENY;
140 debounce_uid = user->uuid;
142 debounce_ts = ServerInstance->Time();
145 if (adding == user->IsModeSet(this))
146 return MODEACTION_DENY;
148 /* don't allow this user to spam modechanges */
150 user->CommandFloodPenalty += 5000;
154 // assume this is more correct
155 if (user->registered != REG_ALL && user->GetRealHost() != user->GetDisplayedHost())
156 return MODEACTION_DENY;
158 CloakList* cloaks = ext.get(user);
161 /* Force creation of missing cloak */
164 creator->OnUserConnect(user);
165 cloaks = ext.get(user);
167 catch (CoreException& modexcept)
169 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Exception caught when generating cloak: " + modexcept.GetReason());
170 return MODEACTION_DENY;
174 // If we have a cloak then set the hostname.
175 if (cloaks && !cloaks->empty())
177 user->ChangeDisplayedHost(cloaks->front());
178 user->SetMode(this, true);
179 return MODEACTION_ALLOW;
182 return MODEACTION_DENY;
186 /* User is removing the mode, so restore their real host
187 * and make it match the displayed one.
189 user->SetMode(this, false);
190 user->ChangeDisplayedHost(user->GetRealHost().c_str());
191 return MODEACTION_ALLOW;
196 class CommandCloak : public Command
199 CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
205 CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE;
208 class ModuleCloaking : public Module
213 std::vector<CloakInfo> cloaks;
214 dynamic_reference<HashProvider> Hash;
219 , Hash(this, "hash/md5")
223 /** Takes a domain name and retrieves the subdomain which should be visible.
224 * This is usually the last \p domainparts labels but if not enough are
225 * present then all but the most specific label are used. If the domain name
226 * consists of one label only then none are used.
228 * Here are some examples for how domain names will be shortened assuming
229 * \p domainparts is set to the default of 3.
231 * "this.is.an.example.com" => ".an.example.com"
232 * "an.example.com" => ".example.com"
233 * "example.com" => ".com"
236 * @param host The hostname to cloak.
237 * @param domainparts The number of domain labels that should be visible.
238 * @return The visible segment of the hostname.
240 std::string VisibleDomainParts(const std::string& host, unsigned int domainparts)
242 // The position at which we found the last dot.
243 std::string::const_reverse_iterator dotpos;
245 // The number of dots we have seen so far.
246 unsigned int seendots = 0;
248 for (std::string::const_reverse_iterator iter = host.rbegin(); iter != host.rend(); ++iter)
253 // We have found a dot!
257 // Do we have enough segments to stop?
258 if (seendots >= domainparts)
262 // We only returns a domain part if more than one label is
263 // present. See above for a full explanation.
266 return std::string(dotpos.base() - 1, host.end());
270 * 2.0-style cloaking function
271 * @param item The item to cloak (part of an IP or hostname)
272 * @param id A unique ID for this type of item (to make it unique if the item matches)
273 * @param len The length of the output. Maximum for MD5 is 16 characters.
275 std::string SegmentCloak(const CloakInfo& info, const std::string& item, char id, size_t len)
278 input.reserve(info.key.length() + 3 + item.length());
280 input.append(info.key);
281 input.append(1, '\0'); // null does not terminate a C++ string
283 std::transform(item.begin(), item.end(), std::back_inserter(input), ::tolower);
287 std::string rv = Hash->GenerateRaw(input).substr(0,len);
288 for(size_t i = 0; i < len; i++)
290 // this discards 3 bits per byte. We have an
291 // overabundance of bits in the hash output, doesn't
292 // matter which ones we are discarding.
293 rv[i] = base32[rv[i] & 0x1F];
298 std::string SegmentIP(const CloakInfo& info, const irc::sockets::sockaddrs& ip, bool full)
301 size_t hop1, hop2, hop3;
304 if (ip.family() == AF_INET6)
306 bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
312 // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
314 rv.reserve(info.prefix.length() + 26 + info.suffix.length());
318 bindata = std::string((const char*)&ip.in4.sin_addr, 4);
323 // pfx s1.s2. (xxx.xxx or s3) sfx
324 rv.reserve(info.prefix.length() + 15 + info.suffix.length());
327 rv.append(info.prefix);
328 rv.append(SegmentCloak(info, bindata, 10, len1));
331 rv.append(SegmentCloak(info, bindata, 11, len2));
336 rv.append(SegmentCloak(info, bindata, 12, len2));
343 rv.append(SegmentCloak(info, bindata, 13, 6));
344 rv.append(info.suffix);
348 if (ip.family() == AF_INET6)
350 rv.append(InspIRCd::Format(".%02x%02x.%02x%02x%s",
351 ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
352 ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], info.suffix.c_str()));
356 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
357 rv.append(InspIRCd::Format(".%d.%d%s", ip4[1], ip4[0], info.suffix.c_str()));
363 ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) CXX11_OVERRIDE
365 LocalUser* lu = IS_LOCAL(user);
367 return MOD_RES_PASSTHRU;
369 // Force the creation of cloaks if not already set.
372 // If the user has no cloaks (i.e. UNIX socket) then we do nothing here.
373 CloakList* cloaklist = cu.ext.get(user);
374 if (!cloaklist || cloaklist->empty())
375 return MOD_RES_PASSTHRU;
377 // Check if they have a cloaked host but are not using it.
378 for (CloakList::const_iterator iter = cloaklist->begin(); iter != cloaklist->end(); ++iter)
380 const std::string& cloak = *iter;
381 if (cloak != user->GetDisplayedHost())
383 const std::string cloakMask = user->nick + "!" + user->ident + "@" + cloak;
384 if (InspIRCd::Match(cloakMask, mask))
388 return MOD_RES_PASSTHRU;
391 void Prioritize() CXX11_OVERRIDE
393 /* Needs to be after m_banexception etc. */
394 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
397 // this unsets umode +x on every host change. If we are actually doing a +x
398 // mode change, we will call SetMode back to true AFTER the host change is done.
399 void OnChangeHost(User* u, const std::string& host) CXX11_OVERRIDE
401 if (u->IsModeSet(cu) && !cu.active)
403 u->SetMode(cu, false);
405 LocalUser* luser = IS_LOCAL(u);
409 Modes::ChangeList modechangelist;
410 modechangelist.push_remove(&cu);
411 ClientProtocol::Events::Mode modeevent(ServerInstance->FakeClient, NULL, u, modechangelist);
412 luser->Send(modeevent);
417 Version GetVersion() CXX11_OVERRIDE
419 std::string testcloak = "broken";
420 if (Hash && !cloaks.empty())
422 const CloakInfo& info = cloaks.front();
425 case MODE_HALF_CLOAK:
426 // Use old cloaking verification to stay compatible with 2.0
427 // But verify domainparts and ignorecase when use 3.0-only features
428 if (info.domainparts == 3 && !info.ignorecase)
429 testcloak = info.prefix + SegmentCloak(info, "*", 3, 8) + info.suffix;
432 irc::sockets::sockaddrs sa;
433 testcloak = GenCloak(info, sa, "", testcloak + ConvToStr(info.domainparts)) + (info.ignorecase ? "-ci" : "");
437 testcloak = info.prefix + SegmentCloak(info, "*", 4, 8) + info.suffix + (info.ignorecase ? "-ci" : "");
440 return Version("Adds user mode x (cloak) which allows user hostnames to be hidden.", VF_COMMON|VF_VENDOR, testcloak);
443 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
445 ConfigTagList tags = ServerInstance->Config->ConfTags("cloak");
446 if (tags.first == tags.second)
447 throw ModuleException("You have loaded the cloaking module but not configured any <cloak> tags!");
449 std::vector<CloakInfo> newcloaks;
450 for (ConfigIter i = tags.first; i != tags.second; ++i)
452 ConfigTag* tag = i->second;
454 // Ensure that we have the <cloak:key> parameter.
455 const std::string key = tag->getString("key");
457 throw ModuleException("You have not defined a cloaking key. Define <cloak:key> as a " + ConvToStr(minkeylen) + "+ character network-wide secret, at " + tag->getTagLocation());
459 // If we are the first cloak method then mandate a strong key.
460 if (i == tags.first && key.length() < minkeylen)
461 throw ModuleException("Your cloaking key is not secure. It should be at least " + ConvToStr(minkeylen) + " characters long, at " + tag->getTagLocation());
463 const bool ignorecase = tag->getBool("ignorecase");
464 const std::string mode = tag->getString("mode");
465 const std::string prefix = tag->getString("prefix");
466 const std::string suffix = tag->getString("suffix", ".IP");
467 if (stdalgo::string::equalsci(mode, "half"))
469 unsigned int domainparts = tag->getUInt("domainparts", 3, 1, 10);
470 newcloaks.push_back(CloakInfo(MODE_HALF_CLOAK, key, prefix, suffix, ignorecase, domainparts));
472 else if (stdalgo::string::equalsci(mode, "full"))
473 newcloaks.push_back(CloakInfo(MODE_OPAQUE, key, prefix, suffix, ignorecase));
475 throw ModuleException(mode + " is an invalid value for <cloak:mode>; acceptable values are 'half' and 'full', at " + tag->getTagLocation());
478 // The cloak configuration was valid so we can apply it.
479 cloaks.swap(newcloaks);
482 std::string GenCloak(const CloakInfo& info, const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
486 irc::sockets::sockaddrs hostip;
487 bool host_is_ip = irc::sockets::aptosa(host, ip.port(), hostip) && hostip == ip;
491 case MODE_HALF_CLOAK:
494 chost = info.prefix + SegmentCloak(info, host, 1, 6) + VisibleDomainParts(host, info.domainparts);
495 if (chost.empty() || chost.length() > 50)
496 chost = SegmentIP(info, ip, false);
501 chost = SegmentIP(info, ip, true);
506 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
508 // Connecting users are handled in OnUserConnect not here.
509 if (user->registered != REG_ALL || user->quitting)
512 // Remove the cloaks and generate new ones.
516 // If a user is using a cloak then update it.
517 if (user->IsModeSet(cu))
519 CloakList* cloaklist = cu.ext.get(user);
520 user->ChangeDisplayedHost(cloaklist->front());
524 void OnUserConnect(LocalUser* dest) CXX11_OVERRIDE
526 if (cu.ext.get(dest))
529 // TODO: decide how we are going to cloak AF_UNIX hostnames.
530 if (dest->client_sa.family() != AF_INET && dest->client_sa.family() != AF_INET6)
534 for (std::vector<CloakInfo>::const_iterator iter = cloaks.begin(); iter != cloaks.end(); ++iter)
535 cloaklist.push_back(GenCloak(*iter, dest->client_sa, dest->GetIPString(), dest->GetRealHost()));
536 cu.ext.set(dest, cloaklist);
540 CmdResult CommandCloak::Handle(User* user, const Params& parameters)
542 ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
544 // If we're cloaking an IP address we pass it in the IP field too.
545 irc::sockets::sockaddrs sa;
546 const char* ipaddr = irc::sockets::aptosa(parameters[0], 0, sa) ? parameters[0].c_str() : "";
549 for (std::vector<CloakInfo>::const_iterator iter = mod->cloaks.begin(); iter != mod->cloaks.end(); ++iter)
551 const std::string cloak = mod->GenCloak(*iter, sa, ipaddr, parameters[0]);
552 user->WriteNotice(InspIRCd::Format("*** Cloak #%u for %s is %s", ++id, parameters[0].c_str(), cloak.c_str()));
557 MODULE_INIT(ModuleCloaking)