1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
17 /* $ModDesc: Provides masking of user hostnames */
21 /** 1.2-compatible host-based cloak */
23 /** 1.2-compatible IP-only cloak */
25 /** 2.0 cloak of "half" of the hostname plus the full IP hash */
27 /** 2.0 cloak of IP hash, split at 2 common CIDR range points */
31 // lowercase-only encoding similar to base64, used for hash output
32 static const char base32[] = "0123456789abcdefghijklmnopqrstuv";
34 /** Handles user mode +x
36 class CloakUser : public ModeHandler
41 CloakUser(Module* source)
42 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER),
43 ext("cloaked_host", source)
47 ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding)
49 /* For remote clients, we don't take any action, we just allow it.
50 * The local server where they are will set their cloak instead.
51 * This is fine, as we will receive it later.
55 dest->SetMode('x',adding);
56 return MODEACTION_ALLOW;
59 /* don't allow this user to spam modechanges */
60 IS_LOCAL(dest)->Penalty += 5;
64 if(!dest->IsModeSet('x'))
66 /* The mode is being turned on - so attempt to
67 * allocate the user a cloaked host using a non-reversible
68 * algorithm (its simple, but its non-reversible so the
69 * simplicity doesnt really matter). This algorithm
70 * will not work if the user has only one level of domain
71 * naming in their hostname (e.g. if they are on a lan or
72 * are connecting via localhost) -- this doesnt matter much.
75 std::string* cloak = ext.get(dest);
77 if (!cloak && IS_LOCAL(dest))
79 /* Force creation of missing cloak */
80 creator->OnUserConnect(IS_LOCAL(dest));
81 cloak = ext.get(dest);
85 dest->ChangeDisplayedHost(cloak->c_str());
86 dest->SetMode('x',true);
87 return MODEACTION_ALLOW;
93 if (dest->IsModeSet('x'))
95 /* User is removing the mode, so just restore their real host
96 * and make it match the displayed one.
98 dest->ChangeDisplayedHost(dest->host.c_str());
99 dest->SetMode('x',false);
100 return MODEACTION_ALLOW;
104 return MODEACTION_DENY;
110 class ModuleCloaking : public Module
117 unsigned int compatkey[4];
119 Module* HashProvider;
122 ModuleCloaking() : cu(this)
124 /* Attempt to locate the md5 service provider, bail if we can't find it */
125 HashProvider = ServerInstance->Modules->Find("m_md5.so");
127 throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_cloaking.so.");
131 /* Register it with the core */
132 if (!ServerInstance->Modes->AddMode(&cu))
133 throw ModuleException("Could not add new modes!");
135 ServerInstance->Modules->UseInterface("HashRequest");
136 ServerInstance->Extensions.Register(&cu.ext);
138 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect };
139 ServerInstance->Modules->Attach(eventlist, this, 3);
141 CloakExistingUsers();
144 /** This function takes a domain name string and returns just the last two domain parts,
145 * or the last domain part if only two are available. Failing that it just returns what it was given.
147 * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
148 * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
149 * and if it is passed "localhost.localdomain" it will return ".localdomain".
151 * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
153 std::string LastTwoDomainParts(const std::string &host)
156 std::string::size_type splitdot = host.length();
158 for (std::string::size_type x = host.length() - 1; x; --x)
169 if (splitdot == host.length())
172 return host.substr(splitdot);
175 std::string CompatCloak4(const char* ip)
177 irc::sepstream seps(ip, '.');
178 std::string octet[4];
181 for (int j = 0; j < 4; j++)
183 seps.GetToken(octet[j]);
184 i[j] = atoi(octet[j].c_str());
187 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
188 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
189 octet[1] = octet[0] + "." + octet[1];
191 /* Reset the Hash module and send it our IV */
195 /* Send the Hash module a different hex table for each octet group's Hash sum */
196 for (int k = 0; k < 4; k++)
198 HashRequestIV hash(this, HashProvider, compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]);
199 rv.append(hash.result.substr(0,6));
203 /* Stick them all together */
207 std::string CompatCloak6(const char* ip)
209 std::vector<std::string> hashies;
213 /* Reset the Hash module and send it our IV */
215 for (const char* input = ip; *input; input++)
218 if (item.length() > 7)
220 HashRequestIV hash(this, HashProvider, compatkey, xtab[(compatkey[1]+rounds) % 4], item);
221 hashies.push_back(hash.result.substr(0,8));
228 HashRequestIV hash(this, HashProvider, compatkey, xtab[(compatkey[1]+rounds) % 4], item);
229 hashies.push_back(hash.result.substr(0,8));
231 /* Stick them all together */
232 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
235 std::string ReversePartialIP(const irc::sockets::sockaddrs& ip)
238 if (ip.sa.sa_family == AF_INET6)
240 snprintf(rv, 50, ".%02x%02x.%02x%02x.%02x%02x.IP",
241 ip.in6.sin6_addr.s6_addr[4], ip.in6.sin6_addr.s6_addr[5],
242 ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
243 ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1]);
247 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
248 snprintf(rv, 50, ".%d.%d.IP", ip4[1], ip4[0]);
253 std::string SegmentIP(const irc::sockets::sockaddrs& ip)
257 if (ip.sa.sa_family == AF_INET6)
259 bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
265 bindata = std::string((const char*)&ip.in4.sin_addr, 4);
271 rv.reserve(prefix.length() + 30);
273 rv.append(SegmentCloak(bindata, 2));
276 rv.append(SegmentCloak(bindata, 3));
279 rv.append(SegmentCloak(bindata, 4));
284 std::string SegmentCloak(const std::string& item, char id)
287 input.reserve(key.length() + 3 + item.length());
290 input.append(1, 0); // null does not terminate a C++ string
293 HashRequest hash(this, HashProvider, input);
294 std::string rv = hash.binresult.substr(0,6);
295 for(int i=0; i < 6; i++)
297 // this discards 3 bits per byte. We have an
298 // overabundance of bits in the hash output, doesn't
299 // matter which ones we are discarding.
300 rv[i] = base32[rv[i] & 0x1F];
305 void CloakExistingUsers()
308 for (std::vector<LocalUser*>::iterator u = ServerInstance->Users->local_users.begin(); u != ServerInstance->Users->local_users.end(); u++)
310 cloak = cu.ext.get(*u);
318 ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
321 std::string* cloak = cu.ext.get(user);
322 /* Check if they have a cloaked host, but are not using it */
323 if (cloak && *cloak != user->dhost)
325 snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
326 if (InspIRCd::Match(cmask,mask))
329 return MOD_RES_PASSTHRU;
334 /* Needs to be after m_banexception etc. */
335 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
340 ServerInstance->Modules->DoneWithInterface("HashRequest");
345 // returns the version number of the module to be
346 // listed in /MODULES
347 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR);
350 void OnRehash(User* user)
353 prefix = Conf.ReadValue("cloak","prefix",0);
355 std::string modestr = Conf.ReadValue("cloak", "mode", 0);
356 if (modestr == "compat-host")
357 mode = MODE_COMPAT_HOST;
358 else if (modestr == "compat-ip")
359 mode = MODE_COMPAT_IPONLY;
360 else if (modestr == "half")
361 mode = MODE_HALF_CLOAK;
362 else if (modestr == "full")
365 throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full");
367 if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY)
369 bool lowercase = Conf.ReadFlag("cloak", "lowercase", 0);
371 /* These are *not* using the need_positive parameter of ReadInteger -
372 * that will limit the valid values to only the positive values in a
373 * signed int. Instead, accept any value that fits into an int and
374 * cast it to an unsigned int. That will, a bit oddly, give us the full
375 * spectrum of an unsigned integer. - Special
377 * We must limit the keys or else we get different results on
378 * amd64/x86 boxes. - psychon */
379 const unsigned int limit = 0x80000000;
380 compatkey[0] = (unsigned int) Conf.ReadInteger("cloak","key1",0,false);
381 compatkey[1] = (unsigned int) Conf.ReadInteger("cloak","key2",0,false);
382 compatkey[2] = (unsigned int) Conf.ReadInteger("cloak","key3",0,false);
383 compatkey[3] = (unsigned int) Conf.ReadInteger("cloak","key4",0,false);
387 xtab[0] = "F92E45D871BCA630";
388 xtab[1] = "A1B9D80C72E653F4";
389 xtab[2] = "1ABC078934DEF562";
390 xtab[3] = "ABCDEF5678901234";
394 xtab[0] = "f92e45d871bca630";
395 xtab[1] = "a1b9d80c72e653f4";
396 xtab[2] = "1abc078934def562";
397 xtab[3] = "abcdef5678901234";
401 prefix = ServerInstance->Config->Network;
403 if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] ||
404 compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit)
407 if (!compatkey[0] || compatkey[0] >= limit)
408 detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
409 else if (!compatkey[1] || compatkey[1] >= limit)
410 detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
411 else if (!compatkey[2] || compatkey[2] >= limit)
412 detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
413 else if (!compatkey[3] || compatkey[3] >= limit)
414 detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
416 throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
421 key = Conf.ReadFlag("cloak", "key", 0);
422 if (key.empty() || key == "secret")
423 throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
427 void OnUserConnect(LocalUser* dest)
429 std::string* cloak = cu.ext.get(dest);
433 if (dest->host.find('.') == std::string::npos && dest->host.find(':') == std::string::npos)
436 std::string ipstr = dest->GetIPString();
441 case MODE_COMPAT_HOST:
443 if (ipstr != dest->host)
445 std::string tail = LastTwoDomainParts(dest->host);
447 /** Reset the Hash module, and send it our IV and hex table */
448 HashRequestIV hash(this, HashProvider, compatkey, xtab[(dest->host[0]) % 4], dest->host);
450 /* Generate a cloak using specialized Hash */
451 chost = prefix + "-" + hash.result.substr(0,8) + tail;
453 /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
454 * according to the DNS RFC) then they get cloaked as an IP.
456 if (chost.length() <= 64)
459 // fall through to IP cloak
461 case MODE_COMPAT_IPONLY:
462 if (dest->client_sa.sa.sa_family == AF_INET6)
463 chost = CompatCloak6(ipstr.c_str());
465 chost = CompatCloak4(ipstr.c_str());
467 case MODE_HALF_CLOAK:
470 if (ipstr != dest->host)
471 tail = LastTwoDomainParts(dest->host);
472 if (tail.empty() || tail.length() > 50)
473 tail = ReversePartialIP(dest->client_sa);
474 chost = prefix + SegmentCloak(dest->host, 1) + tail;
479 chost = prefix + SegmentIP(dest->client_sa);
481 cu.ext.set(dest,chost);
486 MODULE_INIT(ModuleCloaking)