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 // assume this is more correct
100 if (user->registered != REG_ALL && user->host != user->dhost)
101 return MODEACTION_DENY;
103 std::string* cloak = ext.get(user);
107 /* Force creation of missing cloak */
108 creator->OnUserConnect(user);
109 cloak = ext.get(user);
113 user->ChangeDisplayedHost(cloak->c_str());
114 user->SetMode('x',true);
115 return MODEACTION_ALLOW;
118 return MODEACTION_DENY;
122 /* User is removing the mode, so restore their real host
123 * and make it match the displayed one.
125 user->SetMode('x',false);
126 user->ChangeDisplayedHost(user->host.c_str());
127 return MODEACTION_ALLOW;
133 class CommandCloak : public Command
136 CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
142 CmdResult Handle(const std::vector<std::string> ¶meters, User *user);
145 class ModuleCloaking : public Module
154 unsigned int compatkey[4];
156 dynamic_reference<HashProvider> Hash;
158 ModuleCloaking() : cu(this), mode(MODE_OPAQUE), ck(this), Hash(this, "hash/md5")
166 ServerInstance->Modules->AddService(cu);
167 ServerInstance->Modules->AddService(ck);
168 ServerInstance->Modules->AddService(cu.ext);
170 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect, I_OnChangeHost };
171 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
174 /** This function takes a domain name string and returns just the last two domain parts,
175 * or the last domain part if only two are available. Failing that it just returns what it was given.
177 * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
178 * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
179 * and if it is passed "localhost.localdomain" it will return ".localdomain".
181 * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
183 std::string LastTwoDomainParts(const std::string &host)
186 std::string::size_type splitdot = host.length();
188 for (std::string::size_type x = host.length() - 1; x; --x)
199 if (splitdot == host.length())
202 return host.substr(splitdot);
206 * 2.0-style cloaking function
207 * @param item The item to cloak (part of an IP or hostname)
208 * @param id A unique ID for this type of item (to make it unique if the item matches)
209 * @param len The length of the output. Maximum for MD5 is 16 characters.
211 std::string SegmentCloak(const std::string& item, char id, int len)
214 input.reserve(key.length() + 3 + item.length());
217 input.append(1, '\0'); // null does not terminate a C++ string
220 std::string rv = Hash->sum(input).substr(0,len);
221 for(int i=0; i < len; i++)
223 // this discards 3 bits per byte. We have an
224 // overabundance of bits in the hash output, doesn't
225 // matter which ones we are discarding.
226 rv[i] = base32[rv[i] & 0x1F];
231 std::string CompatCloak4(const char* ip)
233 irc::sepstream seps(ip, '.');
234 std::string octet[4];
237 for (int j = 0; j < 4; j++)
239 seps.GetToken(octet[j]);
240 i[j] = atoi(octet[j].c_str());
243 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
244 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
245 octet[1] = octet[0] + "." + octet[1];
247 /* Reset the Hash module and send it our IV */
251 /* Send the Hash module a different hex table for each octet group's Hash sum */
252 for (int k = 0; k < 4; k++)
254 rv.append(Hash->sumIV(compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]).substr(0,6));
258 /* Stick them all together */
262 std::string CompatCloak6(const char* ip)
264 std::vector<std::string> hashies;
268 /* Reset the Hash module and send it our IV */
270 for (const char* input = ip; *input; input++)
273 if (item.length() > 7)
275 hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
282 hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
284 /* Stick them all together */
285 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
288 std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
291 int hop1, hop2, hop3;
294 if (ip.sa.sa_family == AF_INET6)
296 bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
302 // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
304 rv.reserve(prefix.length() + 26 + suffix.length());
308 bindata = std::string((const char*)&ip.in4.sin_addr, 4);
313 // pfx s1.s2. (xxx.xxx or s3) sfx
314 rv.reserve(prefix.length() + 15 + suffix.length());
318 rv.append(SegmentCloak(bindata, 10, len1));
321 rv.append(SegmentCloak(bindata, 11, len2));
326 rv.append(SegmentCloak(bindata, 12, len2));
333 rv.append(SegmentCloak(bindata, 13, 6));
339 if (ip.sa.sa_family == AF_INET6)
341 snprintf(buf, 50, ".%02x%02x.%02x%02x%s",
342 ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
343 ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], suffix.c_str());
347 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
348 snprintf(buf, 50, ".%d.%d%s", ip4[1], ip4[0], suffix.c_str());
355 ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
357 LocalUser* lu = IS_LOCAL(user);
359 return MOD_RES_PASSTHRU;
362 std::string* cloak = cu.ext.get(user);
363 /* Check if they have a cloaked host, but are not using it */
364 if (cloak && *cloak != user->dhost)
367 snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
368 if (InspIRCd::Match(cmask,mask))
371 return MOD_RES_PASSTHRU;
376 /* Needs to be after m_banexception etc. */
377 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
380 // this unsets umode +x on every host change. If we are actually doing a +x
381 // mode change, we will call SetMode back to true AFTER the host change is done.
382 void OnChangeHost(User* u, const std::string& host)
384 if(u->IsModeSet('x'))
386 u->SetMode('x', false);
387 u->WriteServ("MODE %s -x", u->nick.c_str());
397 std::string testcloak = "broken";
402 case MODE_COMPAT_HOST:
403 testcloak = prefix + "-" + Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
405 case MODE_COMPAT_IPONLY:
406 testcloak = Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
408 case MODE_HALF_CLOAK:
409 testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
412 testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
415 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
418 void OnRehash(User* user)
420 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
421 prefix = tag->getString("prefix");
422 suffix = tag->getString("suffix", ".IP");
424 std::string modestr = tag->getString("mode");
425 if (modestr == "compat-host")
426 mode = MODE_COMPAT_HOST;
427 else if (modestr == "compat-ip")
428 mode = MODE_COMPAT_IPONLY;
429 else if (modestr == "half")
430 mode = MODE_HALF_CLOAK;
431 else if (modestr == "full")
434 throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full");
436 if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY)
438 bool lowercase = tag->getBool("lowercase");
440 /* These are *not* using the need_positive parameter of ReadInteger -
441 * that will limit the valid values to only the positive values in a
442 * signed int. Instead, accept any value that fits into an int and
443 * cast it to an unsigned int. That will, a bit oddly, give us the full
444 * spectrum of an unsigned integer. - Special
446 * We must limit the keys or else we get different results on
447 * amd64/x86 boxes. - psychon */
448 const unsigned int limit = 0x80000000;
449 compatkey[0] = (unsigned int) tag->getInt("key1");
450 compatkey[1] = (unsigned int) tag->getInt("key2");
451 compatkey[2] = (unsigned int) tag->getInt("key3");
452 compatkey[3] = (unsigned int) tag->getInt("key4");
456 xtab[0] = "F92E45D871BCA630";
457 xtab[1] = "A1B9D80C72E653F4";
458 xtab[2] = "1ABC078934DEF562";
459 xtab[3] = "ABCDEF5678901234";
463 xtab[0] = "f92e45d871bca630";
464 xtab[1] = "a1b9d80c72e653f4";
465 xtab[2] = "1abc078934def562";
466 xtab[3] = "abcdef5678901234";
470 prefix = ServerInstance->Config->Network;
472 if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] ||
473 compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit)
476 if (!compatkey[0] || compatkey[0] >= limit)
477 detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
478 else if (!compatkey[1] || compatkey[1] >= limit)
479 detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
480 else if (!compatkey[2] || compatkey[2] >= limit)
481 detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
482 else if (!compatkey[3] || compatkey[3] >= limit)
483 detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
485 throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
490 key = tag->getString("key");
491 if (key.empty() || key == "secret")
492 throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
496 std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
500 irc::sockets::sockaddrs hostip;
501 bool host_is_ip = irc::sockets::aptosa(host, ip.port(), hostip) && hostip == ip;
505 case MODE_COMPAT_HOST:
509 std::string tail = LastTwoDomainParts(host);
511 // xtab is not used here due to a bug in 1.2 cloaking
512 chost = prefix + "-" + Hash->sumIV(compatkey, "0123456789abcdef", host).substr(0,8) + tail;
514 /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
515 * according to the DNS RFC) then they get cloaked as an IP.
517 if (chost.length() <= 64)
520 // fall through to IP cloak
522 case MODE_COMPAT_IPONLY:
523 if (ip.sa.sa_family == AF_INET6)
524 chost = CompatCloak6(ipstr.c_str());
526 chost = CompatCloak4(ipstr.c_str());
528 case MODE_HALF_CLOAK:
531 chost = prefix + SegmentCloak(host, 1, 6) + LastTwoDomainParts(host);
532 if (chost.empty() || chost.length() > 50)
533 chost = SegmentIP(ip, false);
538 chost = SegmentIP(ip, true);
543 void OnUserConnect(LocalUser* dest)
545 std::string* cloak = cu.ext.get(dest);
549 cu.ext.set(dest, GenCloak(dest->client_sa, dest->GetIPString(), dest->host));
553 CmdResult CommandCloak::Handle(const std::vector<std::string> ¶meters, User *user)
555 ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
556 irc::sockets::sockaddrs sa;
559 if (irc::sockets::aptosa(parameters[0], 0, sa))
560 cloak = mod->GenCloak(sa, parameters[0], parameters[0]);
562 cloak = mod->GenCloak(sa, "", parameters[0]);
564 user->WriteServ("NOTICE %s :*** Cloak for %s is %s", user->nick.c_str(), parameters[0].c_str(), cloak.c_str());
569 MODULE_INIT(ModuleCloaking)