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