]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
Fix IPv6 cloaking in compatability mode (was using the wrong xtab confusor)
[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->ChangeDisplayedHost(user->host.c_str());
110                         user->SetMode('x',false);
111                         return MODEACTION_ALLOW;
112                 }
113         }
114
115 };
116
117
118 class ModuleCloaking : public Module
119 {
120  private:
121         CloakUser cu;
122         CloakMode mode;
123         std::string prefix;
124         std::string suffix;
125         std::string key;
126         unsigned int compatkey[4];
127         const char* xtab[4];
128         dynamic_reference<HashProvider> Hash;
129
130  public:
131         ModuleCloaking() : cu(this), mode(MODE_OPAQUE), Hash(this, "hash/md5")
132         {
133         }
134
135         void init()
136         {
137                 OnRehash(NULL);
138
139                 /* Register it with the core */
140                 if (!ServerInstance->Modes->AddMode(&cu))
141                         throw ModuleException("Could not add new modes!");
142
143                 ServerInstance->Extensions.Register(&cu.ext);
144
145                 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect, I_OnChangeHost };
146                 ServerInstance->Modules->Attach(eventlist, this, 4);
147         }
148
149         /** This function takes a domain name string and returns just the last two domain parts,
150          * or the last domain part if only two are available. Failing that it just returns what it was given.
151          *
152          * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
153          * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
154          * and if it is passed "localhost.localdomain" it will return ".localdomain".
155          *
156          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
157          */
158         std::string LastTwoDomainParts(const std::string &host)
159         {
160                 int dots = 0;
161                 std::string::size_type splitdot = host.length();
162
163                 for (std::string::size_type x = host.length() - 1; x; --x)
164                 {
165                         if (host[x] == '.')
166                         {
167                                 splitdot = x;
168                                 dots++;
169                         }
170                         if (dots >= 3)
171                                 break;
172                 }
173
174                 if (splitdot == host.length())
175                         return "";
176                 else
177                         return host.substr(splitdot);
178         }
179
180         /**
181          * 2.0-style cloaking function
182          * @param item The item to cloak (part of an IP or hostname)
183          * @param id A unique ID for this type of item (to make it unique if the item matches)
184          * @param len The length of the output. Maximum for MD5 is 16 characters.
185          */
186         std::string SegmentCloak(const std::string& item, char id, int len)
187         {
188                 std::string input;
189                 input.reserve(key.length() + 3 + item.length());
190                 input.append(1, id);
191                 input.append(key);
192                 input.append(1, 0); // null does not terminate a C++ string
193                 input.append(item);
194
195                 std::string rv = Hash->sum(input).substr(0,len);
196                 for(int i=0; i < len; i++)
197                 {
198                         // this discards 3 bits per byte. We have an
199                         // overabundance of bits in the hash output, doesn't
200                         // matter which ones we are discarding.
201                         rv[i] = base32[rv[i] & 0x1F];
202                 }
203                 return rv;
204         }
205
206         std::string CompatCloak4(const char* ip)
207         {
208                 irc::sepstream seps(ip, '.');
209                 std::string octet[4];
210                 int i[4];
211
212                 for (int j = 0; j < 4; j++)
213                 {
214                         seps.GetToken(octet[j]);
215                         i[j] = atoi(octet[j].c_str());
216                 }
217
218                 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
219                 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
220                 octet[1] = octet[0] + "." + octet[1];
221
222                 /* Reset the Hash module and send it our IV */
223
224                 std::string rv;
225
226                 /* Send the Hash module a different hex table for each octet group's Hash sum */
227                 for (int k = 0; k < 4; k++)
228                 {
229                         rv.append(Hash->sumIV(compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]).substr(0,6));
230                         if (k < 3)
231                                 rv.append(".");
232                 }
233                 /* Stick them all together */
234                 return rv;
235         }
236
237         std::string CompatCloak6(const char* ip)
238         {
239                 std::vector<std::string> hashies;
240                 std::string item;
241                 int rounds = 0;
242
243                 /* Reset the Hash module and send it our IV */
244
245                 for (const char* input = ip; *input; input++)
246                 {
247                         item += *input;
248                         if (item.length() > 7)
249                         {
250                                 hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
251                                 item.clear();
252                         }
253                         rounds++;
254                 }
255                 if (!item.empty())
256                 {
257                         hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8));
258                 }
259                 /* Stick them all together */
260                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
261         }
262
263         std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
264         {
265                 std::string bindata;
266                 int hop1, hop2, hop3;
267                 int len1, len2;
268                 std::string rv;
269                 if (ip.sa.sa_family == AF_INET6)
270                 {
271                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
272                         hop1 = 8;
273                         hop2 = 6;
274                         hop3 = 4;
275                         len1 = 6;
276                         len2 = 4;
277                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
278                         //     6  4  4    9/6
279                         rv.reserve(prefix.length() + 26 + suffix.length());
280                 }
281                 else
282                 {
283                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
284                         hop1 = 3;
285                         hop2 = 0;
286                         hop3 = 2;
287                         len1 = len2 = 3;
288                         // pfx s1.s2. (xxx.xxx or s3) sfx
289                         rv.reserve(prefix.length() + 15 + suffix.length());
290                 }
291
292                 rv.append(prefix);
293                 rv.append(SegmentCloak(bindata, 10, len1));
294                 rv.append(1, '.');
295                 bindata.erase(hop1);
296                 rv.append(SegmentCloak(bindata, 11, len2));
297                 if (hop2)
298                 {
299                         rv.append(1, '.');
300                         bindata.erase(hop2);
301                         rv.append(SegmentCloak(bindata, 12, len2));
302                 }
303
304                 if (full)
305                 {
306                         rv.append(1, '.');
307                         bindata.erase(hop3);
308                         rv.append(SegmentCloak(bindata, 13, 6));
309                         rv.append(suffix);
310                 }
311                 else
312                 {
313                         char buf[50];
314                         if (ip.sa.sa_family == AF_INET6)
315                         {
316                                 snprintf(buf, 50, ".%02x%02x.%02x%02x%s",
317                                         ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
318                                         ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], suffix.c_str());
319                         }
320                         else
321                         {
322                                 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
323                                 snprintf(buf, 50, ".%d.%d%s", ip4[1], ip4[0], suffix.c_str());
324                         }
325                         rv.append(buf);
326                 }
327                 return rv;
328         }
329
330         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
331         {
332                 LocalUser* lu = IS_LOCAL(user);
333                 if (!lu)
334                         return MOD_RES_PASSTHRU;
335
336                 OnUserConnect(lu);
337                 std::string* cloak = cu.ext.get(user);
338                 /* Check if they have a cloaked host, but are not using it */
339                 if (cloak && *cloak != user->dhost)
340                 {
341                         char cmask[MAXBUF];
342                         snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
343                         if (InspIRCd::Match(cmask,mask))
344                                 return MOD_RES_DENY;
345                 }
346                 return MOD_RES_PASSTHRU;
347         }
348
349         void Prioritize()
350         {
351                 /* Needs to be after m_banexception etc. */
352                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
353         }
354
355         // this unsets umode +x on every host change. If we are actually doing a +x
356         // mode change, we will call SetMode back to true AFTER the host change is done.
357         void OnChangeHost(User* u, const std::string& host)
358         {
359                 u->SetMode('x', false);
360         }
361
362         ~ModuleCloaking()
363         {
364         }
365
366         Version GetVersion()
367         {
368                 std::string testcloak = "broken";
369                 if (Hash)
370                 {
371                         switch (mode)
372                         {
373                                 case MODE_COMPAT_HOST:
374                                         testcloak = prefix + "-" + Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
375                                         break;
376                                 case MODE_COMPAT_IPONLY:
377                                         testcloak = Hash->sumIV(compatkey, xtab[0], "*").substr(0,10);
378                                         break;
379                                 case MODE_HALF_CLOAK:
380                                         testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
381                                         break;
382                                 case MODE_OPAQUE:
383                                         testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
384                         }
385                 }
386                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
387         }
388
389         void OnRehash(User* user)
390         {
391                 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
392                 prefix = tag->getString("prefix");
393                 suffix = tag->getString("suffix", ".IP");
394
395                 std::string modestr = tag->getString("mode");
396                 if (modestr == "compat-host")
397                         mode = MODE_COMPAT_HOST;
398                 else if (modestr == "compat-ip")
399                         mode = MODE_COMPAT_IPONLY;
400                 else if (modestr == "half")
401                         mode = MODE_HALF_CLOAK;
402                 else if (modestr == "full")
403                         mode = MODE_OPAQUE;
404                 else
405                         throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full");
406
407                 if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY)
408                 {
409                         bool lowercase = tag->getBool("lowercase");
410
411                         /* These are *not* using the need_positive parameter of ReadInteger -
412                          * that will limit the valid values to only the positive values in a
413                          * signed int. Instead, accept any value that fits into an int and
414                          * cast it to an unsigned int. That will, a bit oddly, give us the full
415                          * spectrum of an unsigned integer. - Special
416                          *
417                          * We must limit the keys or else we get different results on
418                          * amd64/x86 boxes. - psychon */
419                         const unsigned int limit = 0x80000000;
420                         compatkey[0] = (unsigned int) tag->getInt("key1");
421                         compatkey[1] = (unsigned int) tag->getInt("key2");
422                         compatkey[2] = (unsigned int) tag->getInt("key3");
423                         compatkey[3] = (unsigned int) tag->getInt("key4");
424
425                         if (!lowercase)
426                         {
427                                 xtab[0] = "F92E45D871BCA630";
428                                 xtab[1] = "A1B9D80C72E653F4";
429                                 xtab[2] = "1ABC078934DEF562";
430                                 xtab[3] = "ABCDEF5678901234";
431                         }
432                         else
433                         {
434                                 xtab[0] = "f92e45d871bca630";
435                                 xtab[1] = "a1b9d80c72e653f4";
436                                 xtab[2] = "1abc078934def562";
437                                 xtab[3] = "abcdef5678901234";
438                         }
439
440                         if (prefix.empty())
441                                 prefix = ServerInstance->Config->Network;
442
443                         if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] ||
444                                 compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit)
445                         {
446                                 std::string detail;
447                                 if (!compatkey[0] || compatkey[0] >= limit)
448                                         detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
449                                 else if (!compatkey[1] || compatkey[1] >= limit)
450                                         detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
451                                 else if (!compatkey[2] || compatkey[2] >= limit)
452                                         detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
453                                 else if (!compatkey[3] || compatkey[3] >= limit)
454                                         detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
455
456                                 throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
457                         }
458                 }
459                 else
460                 {
461                         key = tag->getString("key");
462                         if (key.empty() || key == "secret")
463                                 throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
464                 }
465         }
466
467         void OnUserConnect(LocalUser* dest)
468         {
469                 std::string* cloak = cu.ext.get(dest);
470                 if (cloak)
471                         return;
472
473                 std::string ipstr = dest->GetIPString();
474                 std::string chost;
475
476                 switch (mode)
477                 {
478                         case MODE_COMPAT_HOST:
479                         {
480                                 if (ipstr != dest->host)
481                                 {
482                                         std::string tail = LastTwoDomainParts(dest->host);
483
484                                         /* Generate a cloak using specialized Hash */
485                                         chost = prefix + "-" + Hash->sumIV(compatkey, xtab[(dest->host[0]) % 4], dest->host).substr(0,8) + tail;
486
487                                         /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
488                                          * according to the DNS RFC) then they get cloaked as an IP.
489                                          */
490                                         if (chost.length() <= 64)
491                                                 break;
492                                 }
493                                 // fall through to IP cloak
494                         }
495                         case MODE_COMPAT_IPONLY:
496                                 if (dest->client_sa.sa.sa_family == AF_INET6)
497                                         chost = CompatCloak6(ipstr.c_str());
498                                 else
499                                         chost = CompatCloak4(ipstr.c_str());
500                                 break;
501                         case MODE_HALF_CLOAK:
502                         {
503                                 if (ipstr != dest->host)
504                                         chost = prefix + SegmentCloak(dest->host, 1, 6) + LastTwoDomainParts(dest->host);
505                                 if (chost.empty() || chost.length() > 50)
506                                         chost = SegmentIP(dest->client_sa, false);
507                                 break;
508                         }
509                         case MODE_OPAQUE:
510                         default:
511                                 chost = SegmentIP(dest->client_sa, true);
512                 }
513                 cu.ext.set(dest,chost);
514         }
515
516 };
517
518 MODULE_INIT(ModuleCloaking)