]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
Fix stats letter for shuns
[user/henk/code/inspircd.git] / src / modules / m_cloaking.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "hash.h"
16
17 /* $ModDesc: Provides masking of user hostnames */
18
19 enum CloakMode
20 {
21         /** 1.2-compatible host-based cloak */
22         MODE_COMPAT_HOST,
23         /** 1.2-compatible IP-only cloak */
24         MODE_COMPAT_IPONLY,
25         /** 2.0 cloak of "half" of the hostname plus the full IP hash */
26         MODE_HALF_CLOAK,
27         /** 2.0 cloak of IP hash, split at 2 common CIDR range points */
28         MODE_OPAQUE
29 };
30
31 // lowercase-only encoding similar to base64, used for hash output
32 static const char base32[] = "0123456789abcdefghijklmnopqrstuv";
33
34 /** Handles user mode +x
35  */
36 class CloakUser : public ModeHandler
37 {
38  public:
39         LocalStringExt ext;
40
41         std::string debounce_uid;
42         time_t debounce_ts;
43         int debounce_count;
44
45         CloakUser(Module* source)
46                 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER),
47                 ext("cloaked_host", source), debounce_ts(0), debounce_count(0)
48         {
49         }
50
51         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
52         {
53                 LocalUser* user = IS_LOCAL(dest);
54
55                 /* For remote clients, we don't take any action, we just allow it.
56                  * The local server where they are will set their cloak instead.
57                  * This is fine, as we will receive it later.
58                  */
59                 if (!user)
60                 {
61                         dest->SetMode('x',adding);
62                         return MODEACTION_ALLOW;
63                 }
64
65                 if (user->uuid == debounce_uid && debounce_ts == ServerInstance->Time())
66                 {
67                         // prevent spamming using /mode user +x-x+x-x+x-x
68                         if (++debounce_count > 2)
69                                 return MODEACTION_DENY;
70                 }
71                 else
72                 {
73                         debounce_uid = user->uuid;
74                         debounce_count = 1;
75                         debounce_ts = ServerInstance->Time();
76                 }
77
78                 if (adding == user->IsModeSet('x'))
79                         return MODEACTION_DENY;
80
81                 /* don't allow this user to spam modechanges */
82                 if (source == dest)
83                         user->CommandFloodPenalty += 5000;
84
85                 if (adding)
86                 {
87                         std::string* cloak = ext.get(user);
88
89                         if (!cloak)
90                         {
91                                 /* Force creation of missing cloak */
92                                 creator->OnUserConnect(user);
93                                 cloak = ext.get(user);
94                         }
95                         if (cloak)
96                         {
97                                 user->ChangeDisplayedHost(cloak->c_str());
98                                 user->SetMode('x',true);
99                                 return MODEACTION_ALLOW;
100                         }
101                         else
102                                 return MODEACTION_DENY;
103                 }
104                 else
105                 {
106                         /* User is removing the mode, so restore their real host
107                          * and make it match the displayed one.
108                          */
109                         user->SetMode('x',false);
110                         user->ChangeDisplayedHost(user->host.c_str());
111                         return MODEACTION_ALLOW;
112                 }
113         }
114
115 };
116
117 class CommandCloak : public Command
118 {
119  public:
120         CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
121         {
122                 flags_needed = 'o';
123                 syntax = "<host>";
124         }
125
126         CmdResult Handle(const std::vector<std::string> &parameters, User *user);
127 };
128
129 class ModuleCloaking : public Module
130 {
131  public:
132         CloakUser cu;
133         CloakMode mode;
134         CommandCloak ck;
135         std::string prefix;
136         std::string suffix;
137         std::string key;
138         unsigned int compatkey[4];
139         const char* xtab[4];
140         dynamic_reference<HashProvider> Hash;
141
142         ModuleCloaking() : cu(this), mode(MODE_OPAQUE), ck(this), Hash(this, "hash/md5")
143         {
144         }
145
146         void init()
147         {
148                 OnRehash(NULL);
149
150                 ServerInstance->Modules->AddService(cu);
151                 ServerInstance->Modules->AddService(ck);
152                 ServerInstance->Modules->AddService(cu.ext);
153
154                 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect, I_OnChangeHost };
155                 ServerInstance->Modules->Attach(eventlist, this, 4);
156         }
157
158         /** This function takes a domain name string and returns just the last two domain parts,
159          * or the last domain part if only two are available. Failing that it just returns what it was given.
160          *
161          * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
162          * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
163          * and if it is passed "localhost.localdomain" it will return ".localdomain".
164          *
165          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
166          */
167         std::string LastTwoDomainParts(const std::string &host)
168         {
169                 int dots = 0;
170                 std::string::size_type splitdot = host.length();
171
172                 for (std::string::size_type x = host.length() - 1; x; --x)
173                 {
174                         if (host[x] == '.')
175                         {
176                                 splitdot = x;
177                                 dots++;
178                         }
179                         if (dots >= 3)
180                                 break;
181                 }
182
183                 if (splitdot == host.length())
184                         return "";
185                 else
186                         return host.substr(splitdot);
187         }
188
189         /**
190          * 2.0-style cloaking function
191          * @param item The item to cloak (part of an IP or hostname)
192          * @param id A unique ID for this type of item (to make it unique if the item matches)
193          * @param len The length of the output. Maximum for MD5 is 16 characters.
194          */
195         std::string SegmentCloak(const std::string& item, char id, int len)
196         {
197                 std::string input;
198                 input.reserve(key.length() + 3 + item.length());
199                 input.append(1, id);
200                 input.append(key);
201                 input.append(1, '\0'); // null does not terminate a C++ string
202                 input.append(item);
203
204                 std::string rv = Hash->sum(input).substr(0,len);
205                 for(int i=0; i < len; i++)
206                 {
207                         // this discards 3 bits per byte. We have an
208                         // overabundance of bits in the hash output, doesn't
209                         // matter which ones we are discarding.
210                         rv[i] = base32[rv[i] & 0x1F];
211                 }
212                 return rv;
213         }
214
215         std::string CompatCloak4(const char* ip)
216         {
217                 irc::sepstream seps(ip, '.');
218                 std::string octet[4];
219                 int i[4];
220
221                 for (int j = 0; j < 4; j++)
222                 {
223                         seps.GetToken(octet[j]);
224                         i[j] = atoi(octet[j].c_str());
225                 }
226
227                 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
228                 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
229                 octet[1] = octet[0] + "." + octet[1];
230
231                 /* Reset the Hash module and send it our IV */
232
233                 std::string rv;
234
235                 /* Send the Hash module a different hex table for each octet group's Hash sum */
236                 for (int k = 0; k < 4; k++)
237                 {
238                         rv.append(Hash->sumIV(compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]).substr(0,6));
239                         if (k < 3)
240                                 rv.append(".");
241                 }
242                 /* Stick them all together */
243                 return rv;
244         }
245
246         std::string CompatCloak6(const char* ip)
247         {
248                 std::vector<std::string> hashies;
249                 std::string item;
250                 int rounds = 0;
251
252                 /* Reset the Hash module and send it our IV */
253
254                 for (const char* input = ip; *input; input++)
255                 {
256                         item += *input;
257                         if (item.length() > 7)
258                         {
259                                 hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
260                                 item.clear();
261                         }
262                         rounds++;
263                 }
264                 if (!item.empty())
265                 {
266                         hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
267                 }
268                 /* Stick them all together */
269                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
270         }
271
272         std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
273         {
274                 std::string bindata;
275                 int hop1, hop2, hop3;
276                 int len1, len2;
277                 std::string rv;
278                 if (ip.sa.sa_family == AF_INET6)
279                 {
280                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
281                         hop1 = 8;
282                         hop2 = 6;
283                         hop3 = 4;
284                         len1 = 6;
285                         len2 = 4;
286                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
287                         //     6  4  4    9/6
288                         rv.reserve(prefix.length() + 26 + suffix.length());
289                 }
290                 else
291                 {
292                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
293                         hop1 = 3;
294                         hop2 = 0;
295                         hop3 = 2;
296                         len1 = len2 = 3;
297                         // pfx s1.s2. (xxx.xxx or s3) sfx
298                         rv.reserve(prefix.length() + 15 + suffix.length());
299                 }
300
301                 rv.append(prefix);
302                 rv.append(SegmentCloak(bindata, 10, len1));
303                 rv.append(1, '.');
304                 bindata.erase(hop1);
305                 rv.append(SegmentCloak(bindata, 11, len2));
306                 if (hop2)
307                 {
308                         rv.append(1, '.');
309                         bindata.erase(hop2);
310                         rv.append(SegmentCloak(bindata, 12, len2));
311                 }
312
313                 if (full)
314                 {
315                         rv.append(1, '.');
316                         bindata.erase(hop3);
317                         rv.append(SegmentCloak(bindata, 13, 6));
318                         rv.append(suffix);
319                 }
320                 else
321                 {
322                         char buf[50];
323                         if (ip.sa.sa_family == AF_INET6)
324                         {
325                                 snprintf(buf, 50, ".%02x%02x.%02x%02x%s",
326                                         ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
327                                         ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], suffix.c_str());
328                         }
329                         else
330                         {
331                                 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
332                                 snprintf(buf, 50, ".%d.%d%s", ip4[1], ip4[0], suffix.c_str());
333                         }
334                         rv.append(buf);
335                 }
336                 return rv;
337         }
338
339         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
340         {
341                 LocalUser* lu = IS_LOCAL(user);
342                 if (!lu)
343                         return MOD_RES_PASSTHRU;
344
345                 OnUserConnect(lu);
346                 std::string* cloak = cu.ext.get(user);
347                 /* Check if they have a cloaked host, but are not using it */
348                 if (cloak && *cloak != user->dhost)
349                 {
350                         char cmask[MAXBUF];
351                         snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
352                         if (InspIRCd::Match(cmask,mask))
353                                 return MOD_RES_DENY;
354                 }
355                 return MOD_RES_PASSTHRU;
356         }
357
358         void Prioritize()
359         {
360                 /* Needs to be after m_banexception etc. */
361                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
362         }
363
364         // this unsets umode +x on every host change. If we are actually doing a +x
365         // mode change, we will call SetMode back to true AFTER the host change is done.
366         void OnChangeHost(User* u, const std::string& host)
367         {
368                 if(u->IsModeSet('x'))
369                 {
370                         u->SetMode('x', false);
371                         u->WriteServ("MODE %s -x", u->nick.c_str());
372                 }
373         }
374
375         ~ModuleCloaking()
376         {
377         }
378
379         Version GetVersion()
380         {
381                 std::string testcloak = "broken";
382                 if (Hash)
383                 {
384                         switch (mode)
385                         {
386                                 case MODE_COMPAT_HOST:
387                                         testcloak = prefix + "-" + Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
388                                         break;
389                                 case MODE_COMPAT_IPONLY:
390                                         testcloak = Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
391                                         break;
392                                 case MODE_HALF_CLOAK:
393                                         testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
394                                         break;
395                                 case MODE_OPAQUE:
396                                         testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
397                         }
398                 }
399                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
400         }
401
402         void OnRehash(User* user)
403         {
404                 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
405                 prefix = tag->getString("prefix");
406                 suffix = tag->getString("suffix", ".IP");
407
408                 std::string modestr = tag->getString("mode");
409                 if (modestr == "compat-host")
410                         mode = MODE_COMPAT_HOST;
411                 else if (modestr == "compat-ip")
412                         mode = MODE_COMPAT_IPONLY;
413                 else if (modestr == "half")
414                         mode = MODE_HALF_CLOAK;
415                 else if (modestr == "full")
416                         mode = MODE_OPAQUE;
417                 else
418                         throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full");
419
420                 if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY)
421                 {
422                         bool lowercase = tag->getBool("lowercase");
423
424                         /* These are *not* using the need_positive parameter of ReadInteger -
425                          * that will limit the valid values to only the positive values in a
426                          * signed int. Instead, accept any value that fits into an int and
427                          * cast it to an unsigned int. That will, a bit oddly, give us the full
428                          * spectrum of an unsigned integer. - Special
429                          *
430                          * We must limit the keys or else we get different results on
431                          * amd64/x86 boxes. - psychon */
432                         const unsigned int limit = 0x80000000;
433                         compatkey[0] = (unsigned int) tag->getInt("key1");
434                         compatkey[1] = (unsigned int) tag->getInt("key2");
435                         compatkey[2] = (unsigned int) tag->getInt("key3");
436                         compatkey[3] = (unsigned int) tag->getInt("key4");
437
438                         if (!lowercase)
439                         {
440                                 xtab[0] = "F92E45D871BCA630";
441                                 xtab[1] = "A1B9D80C72E653F4";
442                                 xtab[2] = "1ABC078934DEF562";
443                                 xtab[3] = "ABCDEF5678901234";
444                         }
445                         else
446                         {
447                                 xtab[0] = "f92e45d871bca630";
448                                 xtab[1] = "a1b9d80c72e653f4";
449                                 xtab[2] = "1abc078934def562";
450                                 xtab[3] = "abcdef5678901234";
451                         }
452
453                         if (prefix.empty())
454                                 prefix = ServerInstance->Config->Network;
455
456                         if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] ||
457                                 compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit)
458                         {
459                                 std::string detail;
460                                 if (!compatkey[0] || compatkey[0] >= limit)
461                                         detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
462                                 else if (!compatkey[1] || compatkey[1] >= limit)
463                                         detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
464                                 else if (!compatkey[2] || compatkey[2] >= limit)
465                                         detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
466                                 else if (!compatkey[3] || compatkey[3] >= limit)
467                                         detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
468
469                                 throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
470                         }
471                 }
472                 else
473                 {
474                         key = tag->getString("key");
475                         if (key.empty() || key == "secret")
476                                 throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
477                 }
478         }
479
480         std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
481         {
482                 std::string chost;
483
484                 switch (mode)
485                 {
486                         case MODE_COMPAT_HOST:
487                         {
488                                 if (ipstr != host)
489                                 {
490                                         std::string tail = LastTwoDomainParts(host);
491
492                                         // xtab is not used here due to a bug in 1.2 cloaking
493                                         chost = prefix + "-" + Hash->sumIV(compatkey, "0123456789abcdef", host).substr(0,8) + tail;
494
495                                         /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
496                                          * according to the DNS RFC) then they get cloaked as an IP.
497                                          */
498                                         if (chost.length() <= 64)
499                                                 break;
500                                 }
501                                 // fall through to IP cloak
502                         }
503                         case MODE_COMPAT_IPONLY:
504                                 if (ip.sa.sa_family == AF_INET6)
505                                         chost = CompatCloak6(ipstr.c_str());
506                                 else
507                                         chost = CompatCloak4(ipstr.c_str());
508                                 break;
509                         case MODE_HALF_CLOAK:
510                         {
511                                 if (ipstr != host)
512                                         chost = prefix + SegmentCloak(host, 1, 6) + LastTwoDomainParts(host);
513                                 if (chost.empty() || chost.length() > 50)
514                                         chost = SegmentIP(ip, false);
515                                 break;
516                         }
517                         case MODE_OPAQUE:
518                         default:
519                                 chost = SegmentIP(ip, true);
520                 }
521                 return chost;
522         }
523
524         void OnUserConnect(LocalUser* dest)
525         {
526                 std::string* cloak = cu.ext.get(dest);
527                 if (cloak)
528                         return;
529
530                 cu.ext.set(dest, GenCloak(dest->client_sa, dest->GetIPString(), dest->host));
531         }
532 };
533
534 CmdResult CommandCloak::Handle(const std::vector<std::string> &parameters, User *user)
535 {
536         ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
537         irc::sockets::sockaddrs sa;
538         std::string cloak;
539
540         if (irc::sockets::aptosa(parameters[0], 0, sa))
541                 cloak = mod->GenCloak(sa, parameters[0], parameters[0]);
542         else
543                 cloak = mod->GenCloak(sa, "", parameters[0]);
544
545         user->WriteServ("NOTICE %s :*** Cloak for %s is %s", user->nick.c_str(), parameters[0].c_str(), cloak.c_str());
546
547         return CMD_SUCCESS;
548 }
549
550 MODULE_INIT(ModuleCloaking)