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