]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
Merge pull request #1328 from Adam-/insp20+sakick
[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                         // assume this is more correct
100                         if (user->registered != REG_ALL && user->host != user->dhost)
101                                 return MODEACTION_DENY;
102
103                         std::string* cloak = ext.get(user);
104
105                         if (!cloak)
106                         {
107                                 /* Force creation of missing cloak */
108                                 creator->OnUserConnect(user);
109                                 cloak = ext.get(user);
110                         }
111                         if (cloak)
112                         {
113                                 user->ChangeDisplayedHost(cloak->c_str());
114                                 user->SetMode('x',true);
115                                 return MODEACTION_ALLOW;
116                         }
117                         else
118                                 return MODEACTION_DENY;
119                 }
120                 else
121                 {
122                         /* User is removing the mode, so restore their real host
123                          * and make it match the displayed one.
124                          */
125                         user->SetMode('x',false);
126                         user->ChangeDisplayedHost(user->host.c_str());
127                         return MODEACTION_ALLOW;
128                 }
129         }
130
131 };
132
133 class CommandCloak : public Command
134 {
135  public:
136         CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
137         {
138                 flags_needed = 'o';
139                 syntax = "<host>";
140         }
141
142         CmdResult Handle(const std::vector<std::string> &parameters, User *user);
143 };
144
145 class ModuleCloaking : public Module
146 {
147  public:
148         CloakUser cu;
149         CloakMode mode;
150         CommandCloak ck;
151         std::string prefix;
152         std::string suffix;
153         std::string key;
154         unsigned int compatkey[4];
155         const char* xtab[4];
156         dynamic_reference<HashProvider> Hash;
157
158         ModuleCloaking() : cu(this), mode(MODE_OPAQUE), ck(this), Hash(this, "hash/md5")
159         {
160         }
161
162         void init()
163         {
164                 OnRehash(NULL);
165
166                 ServerInstance->Modules->AddService(cu);
167                 ServerInstance->Modules->AddService(ck);
168                 ServerInstance->Modules->AddService(cu.ext);
169
170                 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect, I_OnChangeHost };
171                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
172         }
173
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.
176          *
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".
180          *
181          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
182          */
183         std::string LastTwoDomainParts(const std::string &host)
184         {
185                 int dots = 0;
186                 std::string::size_type splitdot = host.length();
187
188                 for (std::string::size_type x = host.length() - 1; x; --x)
189                 {
190                         if (host[x] == '.')
191                         {
192                                 splitdot = x;
193                                 dots++;
194                         }
195                         if (dots >= 3)
196                                 break;
197                 }
198
199                 if (splitdot == host.length())
200                         return "";
201                 else
202                         return host.substr(splitdot);
203         }
204
205         /**
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.
210          */
211         std::string SegmentCloak(const std::string& item, char id, int len)
212         {
213                 std::string input;
214                 input.reserve(key.length() + 3 + item.length());
215                 input.append(1, id);
216                 input.append(key);
217                 input.append(1, '\0'); // null does not terminate a C++ string
218                 input.append(item);
219
220                 std::string rv = Hash->sum(input).substr(0,len);
221                 for(int i=0; i < len; i++)
222                 {
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];
227                 }
228                 return rv;
229         }
230
231         std::string CompatCloak4(const char* ip)
232         {
233                 irc::sepstream seps(ip, '.');
234                 std::string octet[4];
235                 int i[4];
236
237                 for (int j = 0; j < 4; j++)
238                 {
239                         seps.GetToken(octet[j]);
240                         i[j] = atoi(octet[j].c_str());
241                 }
242
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];
246
247                 /* Reset the Hash module and send it our IV */
248
249                 std::string rv;
250
251                 /* Send the Hash module a different hex table for each octet group's Hash sum */
252                 for (int k = 0; k < 4; k++)
253                 {
254                         rv.append(Hash->sumIV(compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]).substr(0,6));
255                         if (k < 3)
256                                 rv.append(".");
257                 }
258                 /* Stick them all together */
259                 return rv;
260         }
261
262         std::string CompatCloak6(const char* ip)
263         {
264                 std::vector<std::string> hashies;
265                 std::string item;
266                 int rounds = 0;
267
268                 /* Reset the Hash module and send it our IV */
269
270                 for (const char* input = ip; *input; input++)
271                 {
272                         item += *input;
273                         if (item.length() > 7)
274                         {
275                                 hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
276                                 item.clear();
277                         }
278                         rounds++;
279                 }
280                 if (!item.empty())
281                 {
282                         hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
283                 }
284                 /* Stick them all together */
285                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
286         }
287
288         std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
289         {
290                 std::string bindata;
291                 int hop1, hop2, hop3;
292                 int len1, len2;
293                 std::string rv;
294                 if (ip.sa.sa_family == AF_INET6)
295                 {
296                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
297                         hop1 = 8;
298                         hop2 = 6;
299                         hop3 = 4;
300                         len1 = 6;
301                         len2 = 4;
302                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
303                         //     6  4  4    9/6
304                         rv.reserve(prefix.length() + 26 + suffix.length());
305                 }
306                 else
307                 {
308                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
309                         hop1 = 3;
310                         hop2 = 0;
311                         hop3 = 2;
312                         len1 = len2 = 3;
313                         // pfx s1.s2. (xxx.xxx or s3) sfx
314                         rv.reserve(prefix.length() + 15 + suffix.length());
315                 }
316
317                 rv.append(prefix);
318                 rv.append(SegmentCloak(bindata, 10, len1));
319                 rv.append(1, '.');
320                 bindata.erase(hop1);
321                 rv.append(SegmentCloak(bindata, 11, len2));
322                 if (hop2)
323                 {
324                         rv.append(1, '.');
325                         bindata.erase(hop2);
326                         rv.append(SegmentCloak(bindata, 12, len2));
327                 }
328
329                 if (full)
330                 {
331                         rv.append(1, '.');
332                         bindata.erase(hop3);
333                         rv.append(SegmentCloak(bindata, 13, 6));
334                         rv.append(suffix);
335                 }
336                 else
337                 {
338                         char buf[50];
339                         if (ip.sa.sa_family == AF_INET6)
340                         {
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());
344                         }
345                         else
346                         {
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());
349                         }
350                         rv.append(buf);
351                 }
352                 return rv;
353         }
354
355         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
356         {
357                 LocalUser* lu = IS_LOCAL(user);
358                 if (!lu)
359                         return MOD_RES_PASSTHRU;
360
361                 OnUserConnect(lu);
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)
365                 {
366                         char cmask[MAXBUF];
367                         snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
368                         if (InspIRCd::Match(cmask,mask))
369                                 return MOD_RES_DENY;
370                 }
371                 return MOD_RES_PASSTHRU;
372         }
373
374         void Prioritize()
375         {
376                 /* Needs to be after m_banexception etc. */
377                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
378         }
379
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)
383         {
384                 if(u->IsModeSet('x'))
385                 {
386                         u->SetMode('x', false);
387                         u->WriteServ("MODE %s -x", u->nick.c_str());
388                 }
389         }
390
391         ~ModuleCloaking()
392         {
393         }
394
395         Version GetVersion()
396         {
397                 std::string testcloak = "broken";
398                 if (Hash)
399                 {
400                         switch (mode)
401                         {
402                                 case MODE_COMPAT_HOST:
403                                         testcloak = prefix + "-" + Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
404                                         break;
405                                 case MODE_COMPAT_IPONLY:
406                                         testcloak = Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
407                                         break;
408                                 case MODE_HALF_CLOAK:
409                                         testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
410                                         break;
411                                 case MODE_OPAQUE:
412                                         testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
413                         }
414                 }
415                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
416         }
417
418         void OnRehash(User* user)
419         {
420                 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
421                 prefix = tag->getString("prefix");
422                 suffix = tag->getString("suffix", ".IP");
423
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")
432                         mode = MODE_OPAQUE;
433                 else
434                         throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full");
435
436                 if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY)
437                 {
438                         bool lowercase = tag->getBool("lowercase");
439
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
445                          *
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");
453
454                         if (!lowercase)
455                         {
456                                 xtab[0] = "F92E45D871BCA630";
457                                 xtab[1] = "A1B9D80C72E653F4";
458                                 xtab[2] = "1ABC078934DEF562";
459                                 xtab[3] = "ABCDEF5678901234";
460                         }
461                         else
462                         {
463                                 xtab[0] = "f92e45d871bca630";
464                                 xtab[1] = "a1b9d80c72e653f4";
465                                 xtab[2] = "1abc078934def562";
466                                 xtab[3] = "abcdef5678901234";
467                         }
468
469                         if (prefix.empty())
470                                 prefix = ServerInstance->Config->Network;
471
472                         if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] ||
473                                 compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit)
474                         {
475                                 std::string detail;
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.";
484
485                                 throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
486                         }
487                 }
488                 else
489                 {
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.");
493                 }
494         }
495
496         std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
497         {
498                 std::string chost;
499
500                 irc::sockets::sockaddrs hostip;
501                 bool host_is_ip = irc::sockets::aptosa(host, ip.port(), hostip) && hostip == ip;
502
503                 switch (mode)
504                 {
505                         case MODE_COMPAT_HOST:
506                         {
507                                 if (!host_is_ip)
508                                 {
509                                         std::string tail = LastTwoDomainParts(host);
510
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;
513
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.
516                                          */
517                                         if (chost.length() <= 64)
518                                                 break;
519                                 }
520                                 // fall through to IP cloak
521                         }
522                         case MODE_COMPAT_IPONLY:
523                                 if (ip.sa.sa_family == AF_INET6)
524                                         chost = CompatCloak6(ipstr.c_str());
525                                 else
526                                         chost = CompatCloak4(ipstr.c_str());
527                                 break;
528                         case MODE_HALF_CLOAK:
529                         {
530                                 if (!host_is_ip)
531                                         chost = prefix + SegmentCloak(host, 1, 6) + LastTwoDomainParts(host);
532                                 if (chost.empty() || chost.length() > 50)
533                                         chost = SegmentIP(ip, false);
534                                 break;
535                         }
536                         case MODE_OPAQUE:
537                         default:
538                                 chost = SegmentIP(ip, true);
539                 }
540                 return chost;
541         }
542
543         void OnUserConnect(LocalUser* dest)
544         {
545                 std::string* cloak = cu.ext.get(dest);
546                 if (cloak)
547                         return;
548
549                 cu.ext.set(dest, GenCloak(dest->client_sa, dest->GetIPString(), dest->host));
550         }
551 };
552
553 CmdResult CommandCloak::Handle(const std::vector<std::string> &parameters, User *user)
554 {
555         ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
556         irc::sockets::sockaddrs sa;
557         std::string cloak;
558
559         if (irc::sockets::aptosa(parameters[0], 0, sa))
560                 cloak = mod->GenCloak(sa, parameters[0], parameters[0]);
561         else
562                 cloak = mod->GenCloak(sa, "", parameters[0]);
563
564         user->WriteServ("NOTICE %s :*** Cloak for %s is %s", user->nick.c_str(), parameters[0].c_str(), cloak.c_str());
565
566         return CMD_SUCCESS;
567 }
568
569 MODULE_INIT(ModuleCloaking)