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