]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
Merge pull request #1230 from SaberUK/insp20+ipcache
[user/henk/code/inspircd.git] / src / modules / m_cloaking.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
11  *
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.
15  *
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
19  * details.
20  *
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/>.
23  */
24
25
26 #include "inspircd.h"
27 #include "hash.h"
28
29 /* $ModDesc: Provides masking of user hostnames */
30
31 enum CloakMode
32 {
33         /** 1.2-compatible host-based cloak */
34         MODE_COMPAT_HOST,
35         /** 1.2-compatible IP-only cloak */
36         MODE_COMPAT_IPONLY,
37         /** 2.0 cloak of "half" of the hostname plus the full IP hash */
38         MODE_HALF_CLOAK,
39         /** 2.0 cloak of IP hash, split at 2 common CIDR range points */
40         MODE_OPAQUE
41 };
42
43 // lowercase-only encoding similar to base64, used for hash output
44 static const char base32[] = "0123456789abcdefghijklmnopqrstuv";
45
46 /** Handles user mode +x
47  */
48 class CloakUser : public ModeHandler
49 {
50  public:
51         LocalStringExt ext;
52
53         std::string debounce_uid;
54         time_t debounce_ts;
55         int debounce_count;
56
57         CloakUser(Module* source)
58                 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER),
59                 ext("cloaked_host", source), debounce_ts(0), debounce_count(0)
60         {
61         }
62
63         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
64         {
65                 LocalUser* user = IS_LOCAL(dest);
66
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.
70                  */
71                 if (!user)
72                 {
73                         dest->SetMode('x',adding);
74                         return MODEACTION_ALLOW;
75                 }
76
77                 if (user->uuid == debounce_uid && debounce_ts == ServerInstance->Time())
78                 {
79                         // prevent spamming using /mode user +x-x+x-x+x-x
80                         if (++debounce_count > 2)
81                                 return MODEACTION_DENY;
82                 }
83                 else
84                 {
85                         debounce_uid = user->uuid;
86                         debounce_count = 1;
87                         debounce_ts = ServerInstance->Time();
88                 }
89
90                 if (adding == user->IsModeSet('x'))
91                         return MODEACTION_DENY;
92
93                 /* don't allow this user to spam modechanges */
94                 if (source == dest)
95                         user->CommandFloodPenalty += 5000;
96
97                 if (adding)
98                 {
99                         std::string* cloak = ext.get(user);
100
101                         if (!cloak)
102                         {
103                                 /* Force creation of missing cloak */
104                                 creator->OnUserConnect(user);
105                                 cloak = ext.get(user);
106                         }
107                         if (cloak)
108                         {
109                                 user->ChangeDisplayedHost(cloak->c_str());
110                                 user->SetMode('x',true);
111                                 return MODEACTION_ALLOW;
112                         }
113                         else
114                                 return MODEACTION_DENY;
115                 }
116                 else
117                 {
118                         /* User is removing the mode, so restore their real host
119                          * and make it match the displayed one.
120                          */
121                         user->SetMode('x',false);
122                         user->ChangeDisplayedHost(user->host.c_str());
123                         return MODEACTION_ALLOW;
124                 }
125         }
126
127 };
128
129 class CommandCloak : public Command
130 {
131  public:
132         CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
133         {
134                 flags_needed = 'o';
135                 syntax = "<host>";
136         }
137
138         CmdResult Handle(const std::vector<std::string> &parameters, User *user);
139 };
140
141 class ModuleCloaking : public Module
142 {
143  public:
144         CloakUser cu;
145         CloakMode mode;
146         CommandCloak ck;
147         std::string prefix;
148         std::string suffix;
149         std::string key;
150         unsigned int compatkey[4];
151         const char* xtab[4];
152         dynamic_reference<HashProvider> Hash;
153
154         ModuleCloaking() : cu(this), mode(MODE_OPAQUE), ck(this), Hash(this, "hash/md5")
155         {
156         }
157
158         void init()
159         {
160                 OnRehash(NULL);
161
162                 ServerInstance->Modules->AddService(cu);
163                 ServerInstance->Modules->AddService(ck);
164                 ServerInstance->Modules->AddService(cu.ext);
165
166                 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect, I_OnChangeHost };
167                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
168         }
169
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.
172          *
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".
176          *
177          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
178          */
179         std::string LastTwoDomainParts(const std::string &host)
180         {
181                 int dots = 0;
182                 std::string::size_type splitdot = host.length();
183
184                 for (std::string::size_type x = host.length() - 1; x; --x)
185                 {
186                         if (host[x] == '.')
187                         {
188                                 splitdot = x;
189                                 dots++;
190                         }
191                         if (dots >= 3)
192                                 break;
193                 }
194
195                 if (splitdot == host.length())
196                         return "";
197                 else
198                         return host.substr(splitdot);
199         }
200
201         /**
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.
206          */
207         std::string SegmentCloak(const std::string& item, char id, int len)
208         {
209                 std::string input;
210                 input.reserve(key.length() + 3 + item.length());
211                 input.append(1, id);
212                 input.append(key);
213                 input.append(1, '\0'); // null does not terminate a C++ string
214                 input.append(item);
215
216                 std::string rv = Hash->sum(input).substr(0,len);
217                 for(int i=0; i < len; i++)
218                 {
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];
223                 }
224                 return rv;
225         }
226
227         std::string CompatCloak4(const char* ip)
228         {
229                 irc::sepstream seps(ip, '.');
230                 std::string octet[4];
231                 int i[4];
232
233                 for (int j = 0; j < 4; j++)
234                 {
235                         seps.GetToken(octet[j]);
236                         i[j] = atoi(octet[j].c_str());
237                 }
238
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];
242
243                 /* Reset the Hash module and send it our IV */
244
245                 std::string rv;
246
247                 /* Send the Hash module a different hex table for each octet group's Hash sum */
248                 for (int k = 0; k < 4; k++)
249                 {
250                         rv.append(Hash->sumIV(compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]).substr(0,6));
251                         if (k < 3)
252                                 rv.append(".");
253                 }
254                 /* Stick them all together */
255                 return rv;
256         }
257
258         std::string CompatCloak6(const char* ip)
259         {
260                 std::vector<std::string> hashies;
261                 std::string item;
262                 int rounds = 0;
263
264                 /* Reset the Hash module and send it our IV */
265
266                 for (const char* input = ip; *input; input++)
267                 {
268                         item += *input;
269                         if (item.length() > 7)
270                         {
271                                 hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
272                                 item.clear();
273                         }
274                         rounds++;
275                 }
276                 if (!item.empty())
277                 {
278                         hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
279                 }
280                 /* Stick them all together */
281                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
282         }
283
284         std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
285         {
286                 std::string bindata;
287                 int hop1, hop2, hop3;
288                 int len1, len2;
289                 std::string rv;
290                 if (ip.sa.sa_family == AF_INET6)
291                 {
292                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
293                         hop1 = 8;
294                         hop2 = 6;
295                         hop3 = 4;
296                         len1 = 6;
297                         len2 = 4;
298                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
299                         //     6  4  4    9/6
300                         rv.reserve(prefix.length() + 26 + suffix.length());
301                 }
302                 else
303                 {
304                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
305                         hop1 = 3;
306                         hop2 = 0;
307                         hop3 = 2;
308                         len1 = len2 = 3;
309                         // pfx s1.s2. (xxx.xxx or s3) sfx
310                         rv.reserve(prefix.length() + 15 + suffix.length());
311                 }
312
313                 rv.append(prefix);
314                 rv.append(SegmentCloak(bindata, 10, len1));
315                 rv.append(1, '.');
316                 bindata.erase(hop1);
317                 rv.append(SegmentCloak(bindata, 11, len2));
318                 if (hop2)
319                 {
320                         rv.append(1, '.');
321                         bindata.erase(hop2);
322                         rv.append(SegmentCloak(bindata, 12, len2));
323                 }
324
325                 if (full)
326                 {
327                         rv.append(1, '.');
328                         bindata.erase(hop3);
329                         rv.append(SegmentCloak(bindata, 13, 6));
330                         rv.append(suffix);
331                 }
332                 else
333                 {
334                         char buf[50];
335                         if (ip.sa.sa_family == AF_INET6)
336                         {
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());
340                         }
341                         else
342                         {
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());
345                         }
346                         rv.append(buf);
347                 }
348                 return rv;
349         }
350
351         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
352         {
353                 LocalUser* lu = IS_LOCAL(user);
354                 if (!lu)
355                         return MOD_RES_PASSTHRU;
356
357                 OnUserConnect(lu);
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)
361                 {
362                         char cmask[MAXBUF];
363                         snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
364                         if (InspIRCd::Match(cmask,mask))
365                                 return MOD_RES_DENY;
366                 }
367                 return MOD_RES_PASSTHRU;
368         }
369
370         void Prioritize()
371         {
372                 /* Needs to be after m_banexception etc. */
373                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
374         }
375
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)
379         {
380                 if(u->IsModeSet('x'))
381                 {
382                         u->SetMode('x', false);
383                         u->WriteServ("MODE %s -x", u->nick.c_str());
384                 }
385         }
386
387         ~ModuleCloaking()
388         {
389         }
390
391         Version GetVersion()
392         {
393                 std::string testcloak = "broken";
394                 if (Hash)
395                 {
396                         switch (mode)
397                         {
398                                 case MODE_COMPAT_HOST:
399                                         testcloak = prefix + "-" + Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
400                                         break;
401                                 case MODE_COMPAT_IPONLY:
402                                         testcloak = Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
403                                         break;
404                                 case MODE_HALF_CLOAK:
405                                         testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
406                                         break;
407                                 case MODE_OPAQUE:
408                                         testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
409                         }
410                 }
411                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
412         }
413
414         void OnRehash(User* user)
415         {
416                 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
417                 prefix = tag->getString("prefix");
418                 suffix = tag->getString("suffix", ".IP");
419
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")
428                         mode = MODE_OPAQUE;
429                 else
430                         throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full");
431
432                 if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY)
433                 {
434                         bool lowercase = tag->getBool("lowercase");
435
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
441                          *
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");
449
450                         if (!lowercase)
451                         {
452                                 xtab[0] = "F92E45D871BCA630";
453                                 xtab[1] = "A1B9D80C72E653F4";
454                                 xtab[2] = "1ABC078934DEF562";
455                                 xtab[3] = "ABCDEF5678901234";
456                         }
457                         else
458                         {
459                                 xtab[0] = "f92e45d871bca630";
460                                 xtab[1] = "a1b9d80c72e653f4";
461                                 xtab[2] = "1abc078934def562";
462                                 xtab[3] = "abcdef5678901234";
463                         }
464
465                         if (prefix.empty())
466                                 prefix = ServerInstance->Config->Network;
467
468                         if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] ||
469                                 compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit)
470                         {
471                                 std::string detail;
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.";
480
481                                 throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
482                         }
483                 }
484                 else
485                 {
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.");
489                 }
490         }
491
492         std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
493         {
494                 std::string chost;
495
496                 irc::sockets::sockaddrs hostip;
497                 bool host_is_ip = irc::sockets::aptosa(host, ip.port(), hostip) && hostip == ip;
498
499                 switch (mode)
500                 {
501                         case MODE_COMPAT_HOST:
502                         {
503                                 if (!host_is_ip)
504                                 {
505                                         std::string tail = LastTwoDomainParts(host);
506
507                                         // xtab is not used here due to a bug in 1.2 cloaking
508                                         chost = prefix + "-" + Hash->sumIV(compatkey, "0123456789abcdef", host).substr(0,8) + tail;
509
510                                         /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
511                                          * according to the DNS RFC) then they get cloaked as an IP.
512                                          */
513                                         if (chost.length() <= 64)
514                                                 break;
515                                 }
516                                 // fall through to IP cloak
517                         }
518                         case MODE_COMPAT_IPONLY:
519                                 if (ip.sa.sa_family == AF_INET6)
520                                         chost = CompatCloak6(ipstr.c_str());
521                                 else
522                                         chost = CompatCloak4(ipstr.c_str());
523                                 break;
524                         case MODE_HALF_CLOAK:
525                         {
526                                 if (!host_is_ip)
527                                         chost = prefix + SegmentCloak(host, 1, 6) + LastTwoDomainParts(host);
528                                 if (chost.empty() || chost.length() > 50)
529                                         chost = SegmentIP(ip, false);
530                                 break;
531                         }
532                         case MODE_OPAQUE:
533                         default:
534                                 chost = SegmentIP(ip, true);
535                 }
536                 return chost;
537         }
538
539         void OnUserConnect(LocalUser* dest)
540         {
541                 std::string* cloak = cu.ext.get(dest);
542                 if (cloak)
543                         return;
544
545                 cu.ext.set(dest, GenCloak(dest->client_sa, dest->GetIPString(), dest->host));
546         }
547 };
548
549 CmdResult CommandCloak::Handle(const std::vector<std::string> &parameters, User *user)
550 {
551         ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
552         irc::sockets::sockaddrs sa;
553         std::string cloak;
554
555         if (irc::sockets::aptosa(parameters[0], 0, sa))
556                 cloak = mod->GenCloak(sa, parameters[0], parameters[0]);
557         else
558                 cloak = mod->GenCloak(sa, "", parameters[0]);
559
560         user->WriteServ("NOTICE %s :*** Cloak for %s is %s", user->nick.c_str(), parameters[0].c_str(), cloak.c_str());
561
562         return CMD_SUCCESS;
563 }
564
565 MODULE_INIT(ModuleCloaking)