2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
7 * Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
8 * Copyright (C) 2007 John Brooks <john.brooks@dereferenced.net>
9 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
12 * This file is part of InspIRCd. InspIRCd is free software: you can
13 * redistribute it and/or modify it under the terms of the GNU General Public
14 * License as published by the Free Software Foundation, version 2.
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 /* $ModDesc: Provides masking of user hostnames */
33 /** 1.2-compatible host-based cloak */
35 /** 1.2-compatible IP-only cloak */
37 /** 2.0 cloak of "half" of the hostname plus the full IP hash */
39 /** 2.0 cloak of IP hash, split at 2 common CIDR range points */
43 // lowercase-only encoding similar to base64, used for hash output
44 static const char base32[] = "0123456789abcdefghijklmnopqrstuv";
46 /** Handles user mode +x
48 class CloakUser : public ModeHandler
53 std::string debounce_uid;
57 CloakUser(Module* source)
58 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER),
59 ext("cloaked_host", source), debounce_ts(0), debounce_count(0)
63 ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding)
65 LocalUser* user = IS_LOCAL(dest);
67 /* For remote clients, we don't take any action, we just allow it.
68 * The local server where they are will set their cloak instead.
69 * This is fine, as we will receive it later.
73 dest->SetMode('x',adding);
74 return MODEACTION_ALLOW;
77 if (user->uuid == debounce_uid && debounce_ts == ServerInstance->Time())
79 // prevent spamming using /mode user +x-x+x-x+x-x
80 if (++debounce_count > 2)
81 return MODEACTION_DENY;
85 debounce_uid = user->uuid;
87 debounce_ts = ServerInstance->Time();
90 if (adding == user->IsModeSet('x'))
91 return MODEACTION_DENY;
93 /* don't allow this user to spam modechanges */
95 user->CommandFloodPenalty += 5000;
99 std::string* cloak = ext.get(user);
103 /* Force creation of missing cloak */
104 creator->OnUserConnect(user);
105 cloak = ext.get(user);
109 user->ChangeDisplayedHost(cloak->c_str());
110 user->SetMode('x',true);
111 return MODEACTION_ALLOW;
114 return MODEACTION_DENY;
118 /* User is removing the mode, so restore their real host
119 * and make it match the displayed one.
121 user->SetMode('x',false);
122 user->ChangeDisplayedHost(user->host.c_str());
123 return MODEACTION_ALLOW;
129 class CommandCloak : public Command
132 CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
138 CmdResult Handle(const std::vector<std::string> ¶meters, User *user);
141 class ModuleCloaking : public Module
150 unsigned int compatkey[4];
152 dynamic_reference<HashProvider> Hash;
154 ModuleCloaking() : cu(this), mode(MODE_OPAQUE), ck(this), Hash(this, "hash/md5")
162 ServerInstance->Modules->AddService(cu);
163 ServerInstance->Modules->AddService(ck);
164 ServerInstance->Modules->AddService(cu.ext);
166 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect, I_OnChangeHost };
167 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
170 /** This function takes a domain name string and returns just the last two domain parts,
171 * or the last domain part if only two are available. Failing that it just returns what it was given.
173 * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
174 * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
175 * and if it is passed "localhost.localdomain" it will return ".localdomain".
177 * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
179 std::string LastTwoDomainParts(const std::string &host)
182 std::string::size_type splitdot = host.length();
184 for (std::string::size_type x = host.length() - 1; x; --x)
195 if (splitdot == host.length())
198 return host.substr(splitdot);
202 * 2.0-style cloaking function
203 * @param item The item to cloak (part of an IP or hostname)
204 * @param id A unique ID for this type of item (to make it unique if the item matches)
205 * @param len The length of the output. Maximum for MD5 is 16 characters.
207 std::string SegmentCloak(const std::string& item, char id, int len)
210 input.reserve(key.length() + 3 + item.length());
213 input.append(1, '\0'); // null does not terminate a C++ string
216 std::string rv = Hash->sum(input).substr(0,len);
217 for(int i=0; i < len; i++)
219 // this discards 3 bits per byte. We have an
220 // overabundance of bits in the hash output, doesn't
221 // matter which ones we are discarding.
222 rv[i] = base32[rv[i] & 0x1F];
227 std::string CompatCloak4(const char* ip)
229 irc::sepstream seps(ip, '.');
230 std::string octet[4];
233 for (int j = 0; j < 4; j++)
235 seps.GetToken(octet[j]);
236 i[j] = atoi(octet[j].c_str());
239 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
240 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
241 octet[1] = octet[0] + "." + octet[1];
243 /* Reset the Hash module and send it our IV */
247 /* Send the Hash module a different hex table for each octet group's Hash sum */
248 for (int k = 0; k < 4; k++)
250 rv.append(Hash->sumIV(compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]).substr(0,6));
254 /* Stick them all together */
258 std::string CompatCloak6(const char* ip)
260 std::vector<std::string> hashies;
264 /* Reset the Hash module and send it our IV */
266 for (const char* input = ip; *input; input++)
269 if (item.length() > 7)
271 hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
278 hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
280 /* Stick them all together */
281 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
284 std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
287 int hop1, hop2, hop3;
290 if (ip.sa.sa_family == AF_INET6)
292 bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
298 // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
300 rv.reserve(prefix.length() + 26 + suffix.length());
304 bindata = std::string((const char*)&ip.in4.sin_addr, 4);
309 // pfx s1.s2. (xxx.xxx or s3) sfx
310 rv.reserve(prefix.length() + 15 + suffix.length());
314 rv.append(SegmentCloak(bindata, 10, len1));
317 rv.append(SegmentCloak(bindata, 11, len2));
322 rv.append(SegmentCloak(bindata, 12, len2));
329 rv.append(SegmentCloak(bindata, 13, 6));
335 if (ip.sa.sa_family == AF_INET6)
337 snprintf(buf, 50, ".%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], suffix.c_str());
343 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
344 snprintf(buf, 50, ".%d.%d%s", ip4[1], ip4[0], suffix.c_str());
351 ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
353 LocalUser* lu = IS_LOCAL(user);
355 return MOD_RES_PASSTHRU;
358 std::string* cloak = cu.ext.get(user);
359 /* Check if they have a cloaked host, but are not using it */
360 if (cloak && *cloak != user->dhost)
363 snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
364 if (InspIRCd::Match(cmask,mask))
367 return MOD_RES_PASSTHRU;
372 /* Needs to be after m_banexception etc. */
373 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
376 // this unsets umode +x on every host change. If we are actually doing a +x
377 // mode change, we will call SetMode back to true AFTER the host change is done.
378 void OnChangeHost(User* u, const std::string& host)
380 if(u->IsModeSet('x'))
382 u->SetMode('x', false);
383 u->WriteServ("MODE %s -x", u->nick.c_str());
393 std::string testcloak = "broken";
398 case MODE_COMPAT_HOST:
399 testcloak = prefix + "-" + Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
401 case MODE_COMPAT_IPONLY:
402 testcloak = Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
404 case MODE_HALF_CLOAK:
405 testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
408 testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
411 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
414 void OnRehash(User* user)
416 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
417 prefix = tag->getString("prefix");
418 suffix = tag->getString("suffix", ".IP");
420 std::string modestr = tag->getString("mode");
421 if (modestr == "compat-host")
422 mode = MODE_COMPAT_HOST;
423 else if (modestr == "compat-ip")
424 mode = MODE_COMPAT_IPONLY;
425 else if (modestr == "half")
426 mode = MODE_HALF_CLOAK;
427 else if (modestr == "full")
430 throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full");
432 if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY)
434 bool lowercase = tag->getBool("lowercase");
436 /* These are *not* using the need_positive parameter of ReadInteger -
437 * that will limit the valid values to only the positive values in a
438 * signed int. Instead, accept any value that fits into an int and
439 * cast it to an unsigned int. That will, a bit oddly, give us the full
440 * spectrum of an unsigned integer. - Special
442 * We must limit the keys or else we get different results on
443 * amd64/x86 boxes. - psychon */
444 const unsigned int limit = 0x80000000;
445 compatkey[0] = (unsigned int) tag->getInt("key1");
446 compatkey[1] = (unsigned int) tag->getInt("key2");
447 compatkey[2] = (unsigned int) tag->getInt("key3");
448 compatkey[3] = (unsigned int) tag->getInt("key4");
452 xtab[0] = "F92E45D871BCA630";
453 xtab[1] = "A1B9D80C72E653F4";
454 xtab[2] = "1ABC078934DEF562";
455 xtab[3] = "ABCDEF5678901234";
459 xtab[0] = "f92e45d871bca630";
460 xtab[1] = "a1b9d80c72e653f4";
461 xtab[2] = "1abc078934def562";
462 xtab[3] = "abcdef5678901234";
466 prefix = ServerInstance->Config->Network;
468 if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] ||
469 compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit)
472 if (!compatkey[0] || compatkey[0] >= limit)
473 detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
474 else if (!compatkey[1] || compatkey[1] >= limit)
475 detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
476 else if (!compatkey[2] || compatkey[2] >= limit)
477 detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
478 else if (!compatkey[3] || compatkey[3] >= limit)
479 detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
481 throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
486 key = tag->getString("key");
487 if (key.empty() || key == "secret")
488 throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
492 std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
498 case MODE_COMPAT_HOST:
502 std::string tail = LastTwoDomainParts(host);
504 // xtab is not used here due to a bug in 1.2 cloaking
505 chost = prefix + "-" + Hash->sumIV(compatkey, "0123456789abcdef", host).substr(0,8) + tail;
507 /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
508 * according to the DNS RFC) then they get cloaked as an IP.
510 if (chost.length() <= 64)
513 // fall through to IP cloak
515 case MODE_COMPAT_IPONLY:
516 if (ip.sa.sa_family == AF_INET6)
517 chost = CompatCloak6(ipstr.c_str());
519 chost = CompatCloak4(ipstr.c_str());
521 case MODE_HALF_CLOAK:
524 chost = prefix + SegmentCloak(host, 1, 6) + LastTwoDomainParts(host);
525 if (chost.empty() || chost.length() > 50)
526 chost = SegmentIP(ip, false);
531 chost = SegmentIP(ip, true);
536 void OnUserConnect(LocalUser* dest)
538 std::string* cloak = cu.ext.get(dest);
542 cu.ext.set(dest, GenCloak(dest->client_sa, dest->GetIPString(), dest->host));
546 CmdResult CommandCloak::Handle(const std::vector<std::string> ¶meters, User *user)
548 ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
549 irc::sockets::sockaddrs sa;
552 if (irc::sockets::aptosa(parameters[0], 0, sa))
553 cloak = mod->GenCloak(sa, parameters[0], parameters[0]);
555 cloak = mod->GenCloak(sa, "", parameters[0]);
557 user->WriteServ("NOTICE %s :*** Cloak for %s is %s", user->nick.c_str(), parameters[0].c_str(), cloak.c_str());
562 MODULE_INIT(ModuleCloaking)