]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
0a4e58edfc6714e6ac6c40160ee0515512244be7
[user/henk/code/inspircd.git] / src / modules / m_cloaking.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 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 "m_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         CloakUser(Module* source)
42                 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER),
43                 ext("cloaked_host", source)
44         {
45         }
46
47         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
48         {
49                 /* For remote clients, we don't take any action, we just allow it.
50                  * The local server where they are will set their cloak instead.
51                  * This is fine, as we will receive it later.
52                  */
53                 if (!IS_LOCAL(dest))
54                 {
55                         dest->SetMode('x',adding);
56                         return MODEACTION_ALLOW;
57                 }
58
59                 /* don't allow this user to spam modechanges */
60                 IS_LOCAL(dest)->CommandFloodPenalty += 5000;
61
62                 if (adding)
63                 {
64                         if(!dest->IsModeSet('x'))
65                         {
66                                 /* The mode is being turned on - so attempt to
67                                  * allocate the user a cloaked host using a non-reversible
68                                  * algorithm (its simple, but its non-reversible so the
69                                  * simplicity doesnt really matter). This algorithm
70                                  * will not work if the user has only one level of domain
71                                  * naming in their hostname (e.g. if they are on a lan or
72                                  * are connecting via localhost) -- this doesnt matter much.
73                                  */
74
75                                 std::string* cloak = ext.get(dest);
76
77                                 if (!cloak && IS_LOCAL(dest))
78                                 {
79                                         /* Force creation of missing cloak */
80                                         creator->OnUserConnect(IS_LOCAL(dest));
81                                         cloak = ext.get(dest);
82                                 }
83                                 if (cloak)
84                                 {
85                                         dest->ChangeDisplayedHost(cloak->c_str());
86                                         dest->SetMode('x',true);
87                                         return MODEACTION_ALLOW;
88                                 }
89                         }
90                 }
91                 else
92                 {
93                         if (dest->IsModeSet('x'))
94                         {
95                                 /* User is removing the mode, so just restore their real host
96                                  * and make it match the displayed one.
97                                  */
98                                 dest->ChangeDisplayedHost(dest->host.c_str());
99                                 dest->SetMode('x',false);
100                                 return MODEACTION_ALLOW;
101                         }
102                 }
103
104                 return MODEACTION_DENY;
105         }
106
107 };
108
109
110 class ModuleCloaking : public Module
111 {
112  private:
113         CloakUser cu;
114         CloakMode mode;
115         std::string prefix;
116         std::string key;
117         unsigned int compatkey[4];
118         const char* xtab[4];
119         Module* HashProvider;
120
121  public:
122         ModuleCloaking() : cu(this)
123         {
124                 /* Attempt to locate the md5 service provider, bail if we can't find it */
125                 HashProvider = ServerInstance->Modules->Find("m_md5.so");
126                 if (!HashProvider)
127                         throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_cloaking.so.");
128
129                 OnRehash(NULL);
130
131                 /* Register it with the core */
132                 if (!ServerInstance->Modes->AddMode(&cu))
133                         throw ModuleException("Could not add new modes!");
134
135                 ServerInstance->Modules->UseInterface("HashRequest");
136                 ServerInstance->Extensions.Register(&cu.ext);
137
138                 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect };
139                 ServerInstance->Modules->Attach(eventlist, this, 3);
140
141                 CloakExistingUsers();
142         }
143
144         /** This function takes a domain name string and returns just the last two domain parts,
145          * or the last domain part if only two are available. Failing that it just returns what it was given.
146          *
147          * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
148          * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
149          * and if it is passed "localhost.localdomain" it will return ".localdomain".
150          *
151          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
152          */
153         std::string LastTwoDomainParts(const std::string &host)
154         {
155                 int dots = 0;
156                 std::string::size_type splitdot = host.length();
157
158                 for (std::string::size_type x = host.length() - 1; x; --x)
159                 {
160                         if (host[x] == '.')
161                         {
162                                 splitdot = x;
163                                 dots++;
164                         }
165                         if (dots >= 3)
166                                 break;
167                 }
168
169                 if (splitdot == host.length())
170                         return host;
171                 else
172                         return host.substr(splitdot);
173         }
174
175         std::string CompatCloak4(const char* ip)
176         {
177                 irc::sepstream seps(ip, '.');
178                 std::string octet[4];
179                 int i[4];
180
181                 for (int j = 0; j < 4; j++)
182                 {
183                         seps.GetToken(octet[j]);
184                         i[j] = atoi(octet[j].c_str());
185                 }
186
187                 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
188                 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
189                 octet[1] = octet[0] + "." + octet[1];
190
191                 /* Reset the Hash module and send it our IV */
192
193                 std::string rv;
194
195                 /* Send the Hash module a different hex table for each octet group's Hash sum */
196                 for (int k = 0; k < 4; k++)
197                 {
198                         HashRequestIV hash(this, HashProvider, compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]);
199                         rv.append(hash.result.substr(0,6));
200                         if (k < 3)
201                                 rv.append(".");
202                 }
203                 /* Stick them all together */
204                 return rv;
205         }
206
207         std::string CompatCloak6(const char* ip)
208         {
209                 std::vector<std::string> hashies;
210                 std::string item;
211                 int rounds = 0;
212
213                 /* Reset the Hash module and send it our IV */
214
215                 for (const char* input = ip; *input; input++)
216                 {
217                         item += *input;
218                         if (item.length() > 7)
219                         {
220                                 HashRequestIV hash(this, HashProvider, compatkey, xtab[(compatkey[1]+rounds) % 4], item);
221                                 hashies.push_back(hash.result.substr(0,8));
222                                 item.clear();
223                         }
224                         rounds++;
225                 }
226                 if (!item.empty())
227                 {
228                         HashRequestIV hash(this, HashProvider, compatkey, xtab[(compatkey[1]+rounds) % 4], item);
229                         hashies.push_back(hash.result.substr(0,8));
230                 }
231                 /* Stick them all together */
232                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
233         }
234
235         std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
236         {
237                 std::string bindata;
238                 int hop1, hop2, hop3;
239                 std::string rv;
240                 if (ip.sa.sa_family == AF_INET6)
241                 {
242                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
243                         hop1 = 8;
244                         hop2 = 6;
245                         hop3 = 4;
246                         rv.reserve(prefix.length() + 37);
247                 }
248                 else
249                 {
250                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
251                         hop1 = 3;
252                         hop2 = 0;
253                         hop3 = 2;
254                         rv.reserve(prefix.length() + 30);
255                 }
256
257                 rv.append(prefix);
258                 rv.append(SegmentCloak(bindata, 10));
259                 rv.append(1, '.');
260                 bindata.erase(hop1);
261                 rv.append(SegmentCloak(bindata, 11));
262                 if (hop2)
263                 {
264                         rv.append(1, '.');
265                         bindata.erase(hop2);
266                         rv.append(SegmentCloak(bindata, 12));
267                 }
268
269                 if (full)
270                 {
271                         rv.append(1, '.');
272                         bindata.erase(hop3);
273                         rv.append(SegmentCloak(bindata, 13));
274                         rv.append(".IP");
275                 }
276                 else
277                 {
278                         char buf[50];
279                         if (ip.sa.sa_family == AF_INET6)
280                         {
281                                 snprintf(buf, 50, ".%02x%02x.%02x%02x.IP",
282                                         ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
283                                         ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1]);
284                         }
285                         else
286                         {
287                                 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
288                                 snprintf(buf, 50, ".%d.%d.IP", ip4[1], ip4[0]);
289                         }
290                         rv.append(buf);
291                 }
292                 return rv;
293         }
294
295         std::string SegmentCloak(const std::string& item, char id)
296         {
297                 std::string input;
298                 input.reserve(key.length() + 3 + item.length());
299                 input.append(1, id);
300                 input.append(key);
301                 input.append(1, 0); // null does not terminate a C++ string
302                 input.append(item);
303
304                 HashRequest hash(this, HashProvider, input);
305                 std::string rv = hash.binresult.substr(0,6);
306                 for(int i=0; i < 6; i++)
307                 {
308                         // this discards 3 bits per byte. We have an
309                         // overabundance of bits in the hash output, doesn't
310                         // matter which ones we are discarding.
311                         rv[i] = base32[rv[i] & 0x1F];
312                 }
313                 return rv;
314         }
315
316         void CloakExistingUsers()
317         {
318                 std::string* cloak;
319                 for (std::vector<LocalUser*>::iterator u = ServerInstance->Users->local_users.begin(); u != ServerInstance->Users->local_users.end(); u++)
320                 {
321                         cloak = cu.ext.get(*u);
322                         if (!cloak)
323                         {
324                                 OnUserConnect(*u);
325                         }
326                 }
327         }
328
329         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
330         {
331                 char cmask[MAXBUF];
332                 std::string* cloak = cu.ext.get(user);
333                 /* Check if they have a cloaked host, but are not using it */
334                 if (cloak && *cloak != user->dhost)
335                 {
336                         snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
337                         if (InspIRCd::Match(cmask,mask))
338                                 return MOD_RES_DENY;
339                 }
340                 return MOD_RES_PASSTHRU;
341         }
342
343         void Prioritize()
344         {
345                 /* Needs to be after m_banexception etc. */
346                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
347         }
348
349         ~ModuleCloaking()
350         {
351                 ServerInstance->Modules->DoneWithInterface("HashRequest");
352         }
353
354         Version GetVersion()
355         {
356                 // returns the version number of the module to be
357                 // listed in /MODULES
358                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR);
359         }
360
361         void OnRehash(User* user)
362         {
363                 ConfigReader Conf;
364                 prefix = Conf.ReadValue("cloak","prefix",0);
365
366                 std::string modestr = Conf.ReadValue("cloak", "mode", 0);
367                 if (modestr == "compat-host")
368                         mode = MODE_COMPAT_HOST;
369                 else if (modestr == "compat-ip")
370                         mode = MODE_COMPAT_IPONLY;
371                 else if (modestr == "half")
372                         mode = MODE_HALF_CLOAK;
373                 else if (modestr == "full")
374                         mode = MODE_OPAQUE;
375                 else
376                         throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full");
377
378                 if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY)
379                 {
380                         bool lowercase = Conf.ReadFlag("cloak", "lowercase", 0);
381
382                         /* These are *not* using the need_positive parameter of ReadInteger -
383                          * that will limit the valid values to only the positive values in a
384                          * signed int. Instead, accept any value that fits into an int and
385                          * cast it to an unsigned int. That will, a bit oddly, give us the full
386                          * spectrum of an unsigned integer. - Special
387                          *
388                          * We must limit the keys or else we get different results on
389                          * amd64/x86 boxes. - psychon */
390                         const unsigned int limit = 0x80000000;
391                         compatkey[0] = (unsigned int) Conf.ReadInteger("cloak","key1",0,false);
392                         compatkey[1] = (unsigned int) Conf.ReadInteger("cloak","key2",0,false);
393                         compatkey[2] = (unsigned int) Conf.ReadInteger("cloak","key3",0,false);
394                         compatkey[3] = (unsigned int) Conf.ReadInteger("cloak","key4",0,false);
395
396                         if (!lowercase)
397                         {
398                                 xtab[0] = "F92E45D871BCA630";
399                                 xtab[1] = "A1B9D80C72E653F4";
400                                 xtab[2] = "1ABC078934DEF562";
401                                 xtab[3] = "ABCDEF5678901234";
402                         }
403                         else
404                         {
405                                 xtab[0] = "f92e45d871bca630";
406                                 xtab[1] = "a1b9d80c72e653f4";
407                                 xtab[2] = "1abc078934def562";
408                                 xtab[3] = "abcdef5678901234";
409                         }
410
411                         if (prefix.empty())
412                                 prefix = ServerInstance->Config->Network;
413
414                         if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] ||
415                                 compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit)
416                         {
417                                 std::string detail;
418                                 if (!compatkey[0] || compatkey[0] >= limit)
419                                         detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
420                                 else if (!compatkey[1] || compatkey[1] >= limit)
421                                         detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
422                                 else if (!compatkey[2] || compatkey[2] >= limit)
423                                         detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
424                                 else if (!compatkey[3] || compatkey[3] >= limit)
425                                         detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
426
427                                 throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
428                         }
429                 }
430                 else
431                 {
432                         key = Conf.ReadFlag("cloak", "key", 0);
433                         if (key.empty() || key == "secret")
434                                 throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
435                 }
436         }
437
438         void OnUserConnect(LocalUser* dest)
439         {
440                 std::string* cloak = cu.ext.get(dest);
441                 if (cloak)
442                         return;
443
444                 if (dest->host.find('.') == std::string::npos && dest->host.find(':') == std::string::npos)
445                         return;
446
447                 std::string ipstr = dest->GetIPString();
448                 std::string chost;
449
450                 switch (mode)
451                 {
452                         case MODE_COMPAT_HOST:
453                         {
454                                 if (ipstr != dest->host)
455                                 {
456                                         std::string tail = LastTwoDomainParts(dest->host);
457
458                                         /** Reset the Hash module, and send it our IV and hex table */
459                                         HashRequestIV hash(this, HashProvider, compatkey, xtab[(dest->host[0]) % 4], dest->host);
460
461                                         /* Generate a cloak using specialized Hash */
462                                         chost = prefix + "-" + hash.result.substr(0,8) + tail;
463
464                                         /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
465                                          * according to the DNS RFC) then they get cloaked as an IP.
466                                          */
467                                         if (chost.length() <= 64)
468                                                 break;
469                                 }
470                                 // fall through to IP cloak
471                         }
472                         case MODE_COMPAT_IPONLY:
473                                 if (dest->client_sa.sa.sa_family == AF_INET6)
474                                         chost = CompatCloak6(ipstr.c_str());
475                                 else
476                                         chost = CompatCloak4(ipstr.c_str());
477                                 break;
478                         case MODE_HALF_CLOAK:
479                         {
480                                 if (ipstr != dest->host)
481                                         chost = prefix + SegmentCloak(dest->host, 1) + LastTwoDomainParts(dest->host);
482                                 if (chost.empty() || chost.length() > 50)
483                                         chost = SegmentIP(dest->client_sa, false);
484                                 break;
485                         }
486                         case MODE_OPAQUE:
487                         default:
488                                 chost = SegmentIP(dest->client_sa, true);
489                 }
490                 cu.ext.set(dest,chost);
491         }
492
493 };
494
495 MODULE_INIT(ModuleCloaking)