]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
The module hook is kinda required.
[user/henk/code/inspircd.git] / src / modules / m_cloaking.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/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 /* $ModDep: m_hash.h */
19
20 /** Handles user mode +x
21  */
22 class CloakUser : public ModeHandler
23 {
24  public:
25         std::string prefix;
26         unsigned int key1;
27         unsigned int key2;
28         unsigned int key3;
29         unsigned int key4;
30         bool ipalways;
31         Module* Sender;
32         Module* HashProvider;
33         const char *xtab[4];
34
35         /** This function takes a domain name string and returns just the last two domain parts,
36          * or the last domain part if only two are available. Failing that it just returns what it was given.
37          *
38          * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
39          * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
40          * and if it is passed "localhost.localdomain" it will return ".localdomain".
41          *
42          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
43          */
44         std::string LastTwoDomainParts(const std::string &host)
45         {
46                 int dots = 0;
47                 std::string::size_type splitdot = host.length();
48
49                 for (std::string::size_type x = host.length() - 1; x; --x)
50                 {
51                         if (host[x] == '.')
52                         {
53                                 splitdot = x;
54                                 dots++;
55                         }
56                         if (dots >= 3)
57                                 break;
58                 }
59
60                 if (splitdot == host.length())
61                         return host;
62                 else
63                         return host.substr(splitdot);
64         }
65
66         CloakUser(InspIRCd* Instance, Module* source, Module* Hash) : ModeHandler(Instance, 'x', 0, 0, false, MODETYPE_USER, false), Sender(source), HashProvider(Hash)
67         {
68         }
69
70         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding, bool)
71         {
72                 if (source != dest)
73                         return MODEACTION_DENY;
74
75                 /* For remote clients, we dont take any action, we just allow it.
76                  * The local server where they are will set their cloak instead.
77                  * This is fine, as we will recieve it later.
78                  */
79                 if (!IS_LOCAL(dest))
80                 {
81                         dest->SetMode('x',adding);
82                         return MODEACTION_ALLOW;
83                 }
84
85                 /* don't allow this user to spam modechanges */
86                 dest->IncreasePenalty(5);
87
88                 if (adding)
89                 {
90                         if(!dest->IsModeSet('x'))
91                         {
92                                 /* The mode is being turned on - so attempt to
93                                  * allocate the user a cloaked host using a non-reversible
94                                  * algorithm (its simple, but its non-reversible so the
95                                  * simplicity doesnt really matter). This algorithm
96                                  * will not work if the user has only one level of domain
97                                  * naming in their hostname (e.g. if they are on a lan or
98                                  * are connecting via localhost) -- this doesnt matter much.
99                                  */
100
101                                 std::string* cloak;
102
103                                 if (!dest->GetExt("cloaked_host", cloak))
104                                 {
105                                         /* Force creation of missing cloak */
106                                         Sender->OnUserConnect(dest);
107                                 }
108                                 if (dest->GetExt("cloaked_host", cloak))
109                                 {
110                                         dest->ChangeDisplayedHost(cloak->c_str());
111                                         dest->SetMode('x',true);
112                                         return MODEACTION_ALLOW;
113                                 }
114                         }
115                 }
116                 else
117                 {
118                         if (dest->IsModeSet('x'))
119                         {
120                                 /* User is removing the mode, so just restore their real host
121                                  * and make it match the displayed one.
122                                  */
123                                 dest->ChangeDisplayedHost(dest->host.c_str());
124                                 dest->SetMode('x',false);
125                                 return MODEACTION_ALLOW;
126                         }
127                 }
128
129                 return MODEACTION_DENY;
130         }
131
132         std::string Cloak4(const char* ip)
133         {
134                 unsigned int iv[] = { key1, key2, key3, key4 };
135                 irc::sepstream seps(ip, '.');
136                 std::string ra[4];;
137                 std::string octet[4];
138                 int i[4];
139
140                 for (int j = 0; j < 4; j++)
141                 {
142                         seps.GetToken(octet[j]);
143                         i[j] = atoi(octet[j].c_str());
144                 }
145
146                 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
147                 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
148                 octet[1] = octet[0] + "." + octet[1];
149
150                 /* Reset the Hash module and send it our IV */
151                 HashResetRequest(Sender, HashProvider).Send();
152                 HashKeyRequest(Sender, HashProvider, iv).Send();
153
154                 /* Send the Hash module a different hex table for each octet group's Hash sum */
155                 for (int k = 0; k < 4; k++)
156                 {
157                         HashHexRequest(Sender, HashProvider, xtab[(iv[k]+i[k]) % 4]).Send();
158                         ra[k] = std::string(HashSumRequest(Sender, HashProvider, octet[k]).Send()).substr(0,6);
159                 }
160                 /* Stick them all together */
161                 return std::string().append(ra[0]).append(".").append(ra[1]).append(".").append(ra[2]).append(".").append(ra[3]);
162         }
163
164         std::string Cloak6(const char* ip)
165         {
166                 /* Theyre using 4in6 (YUCK). Translate as ipv4 cloak */
167                 if (!strncmp(ip, "0::ffff:", 8))
168                         return Cloak4(ip + 8);
169
170                 /* If we get here, yes it really is an ipv6 ip */
171                 unsigned int iv[] = { key1, key2, key3, key4 };
172                 std::vector<std::string> hashies;
173                 std::string item;
174                 int rounds = 0;
175
176                 /* Reset the Hash module and send it our IV */
177                 HashResetRequest(Sender, HashProvider).Send();
178                 HashKeyRequest(Sender, HashProvider, iv).Send();
179
180                 for (const char* input = ip; *input; input++)
181                 {
182                         item += *input;
183                         if (item.length() > 7)
184                         {
185                                 /* Send the Hash module a different hex table for each octet group's Hash sum */
186                                 HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send();
187                                 hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8));
188                                 item.clear();
189                         }
190                         rounds++;
191                 }
192                 if (!item.empty())
193                 {
194                         /* Send the Hash module a different hex table for each octet group's Hash sum */
195                         HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send();
196                         hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8));
197                         item.clear();
198                 }
199                 /* Stick them all together */
200                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
201         }
202
203         void DoRehash()
204         {
205                 ConfigReader Conf(ServerInstance);
206                 bool lowercase;
207
208                 /* These are *not* using the need_positive parameter of ReadInteger -
209                  * that will limit the valid values to only the positive values in a
210                  * signed int. Instead, accept any value that fits into an int and
211                  * cast it to an unsigned int. That will, a bit oddly, give us the full
212                  * spectrum of an unsigned integer. - Special */
213                 key1 = key2 = key3 = key4 = 0;
214                 key1 = (unsigned int) Conf.ReadInteger("cloak","key1",0,false);
215                 key2 = (unsigned int) Conf.ReadInteger("cloak","key2",0,false);
216                 key3 = (unsigned int) Conf.ReadInteger("cloak","key3",0,false);
217                 key4 = (unsigned int) Conf.ReadInteger("cloak","key4",0,false);
218                 prefix = Conf.ReadValue("cloak","prefix",0);
219                 ipalways = Conf.ReadFlag("cloak", "ipalways", 0);
220                 lowercase = Conf.ReadFlag("cloak", "lowercase", 0);
221
222                 if (!lowercase)
223                 {
224                         xtab[0] = "F92E45D871BCA630";
225                         xtab[1] = "A1B9D80C72E653F4";
226                         xtab[2] = "1ABC078934DEF562";
227                         xtab[3] = "ABCDEF5678901234";
228                 }
229                 else
230                 {
231                         xtab[0] = "f92e45d871bca630";
232                         xtab[1] = "a1b9d80c72e653f4";
233                         xtab[2] = "1abc078934def562";
234                         xtab[3] = "abcdef5678901234";
235                 }
236
237                 if (prefix.empty())
238                         prefix = ServerInstance->Config->Network;
239
240                 if (!key1 || !key2 || !key3 || !key4)
241                 {
242                         std::string detail;
243                         if (!key1)
244                                 detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
245                         else if (!key2)
246                                 detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
247                         else if (!key3)
248                                 detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
249                         else if (!key4)
250                                 detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
251
252                         throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
253                 }
254         }
255 };
256
257
258 class ModuleCloaking : public Module
259 {
260  private:
261
262         CloakUser* cu;
263         Module* HashModule;
264
265  public:
266         ModuleCloaking(InspIRCd* Me)
267                 : Module(Me)
268         {
269                 /* Attempt to locate the md5 service provider, bail if we can't find it */
270                 HashModule = ServerInstance->Modules->Find("m_md5.so");
271                 if (!HashModule)
272                         throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_cloaking.so.");
273
274                 cu = new CloakUser(ServerInstance, this, HashModule);
275
276                 try
277                 {
278                         OnRehash(NULL,"");
279                 }
280                 catch (ModuleException &e)
281                 {
282                         delete cu;
283                         throw e;
284                 }
285
286                 /* Register it with the core */
287                 if (!ServerInstance->Modes->AddMode(cu))
288                 {
289                         delete cu;
290                         throw ModuleException("Could not add new modes!");
291                 }
292
293                 ServerInstance->Modules->UseInterface("HashRequest");
294
295                 Implementation eventlist[] = { I_OnRehash, I_OnUserDisconnect, I_OnCleanup, I_OnCheckBan, I_OnUserConnect, I_OnSyncUserMetaData, I_OnCleanup };
296                 ServerInstance->Modules->Attach(eventlist, this, 6);
297
298                 CloakExistingUsers();
299         }
300
301         void OnSyncUserMetaData(User* user, Module* proto,void* opaque, const std::string &extname, bool displayable)
302         {
303                 if ((displayable) && (extname == "cloaked_host"))
304                 {
305                         std::string* cloak;
306                         if (user->GetExt("cloaked_host", cloak))
307                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, *cloak);
308                 }
309         }
310
311         void CloakExistingUsers()
312         {
313                 std::string* cloak;
314                 for (std::vector<User*>::iterator u = ServerInstance->Users->local_users.begin(); u != ServerInstance->Users->local_users.end(); u++)
315                 {
316                         if (!(*u)->GetExt("cloaked_host", cloak))
317                         {
318                                 OnUserConnect(*u);
319                         }
320                 }
321         }
322
323         virtual int OnCheckBan(User* user, Channel* chan)
324         {
325                 char mask[MAXBUF];
326                 std::string* tofree;
327                 /* Check if they have a cloaked host, but are not using it */
328                 if (user->GetExt("cloaked_host", tofree) && *tofree != user->dhost)
329                 {
330                         snprintf(mask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), tofree->c_str());
331                         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
332                         {
333                                 if (InspIRCd::Match(mask,i->data))
334                                         return -1;
335                         }
336                 }
337                 return 0;
338         }
339
340         void Prioritize()
341         {
342                 /* Needs to be after m_banexception etc. */
343                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIO_LAST);
344
345                 /* but before m_conn_umodes, so host is generated ready to apply */
346                 Module *um = ServerInstance->Modules->Find("m_conn_umodes.so");
347                 ServerInstance->Modules->SetPriority(this, I_OnUserConnect, PRIO_AFTER, &um);
348         }
349
350         virtual void OnUserDisconnect(User* user)
351         {
352                 std::string* tofree;
353                 if (user->GetExt("cloaked_host", tofree))
354                 {
355                         delete tofree;
356                         user->Shrink("cloaked_host");
357                 }
358         }
359
360         virtual void OnCleanup(int target_type, void* item)
361         {
362                 if (target_type == TYPE_USER)
363                         OnUserDisconnect((User*)item);
364         }
365
366         virtual ~ModuleCloaking()
367         {
368                 ServerInstance->Modes->DelMode(cu);
369                 delete cu;
370                 ServerInstance->Modules->DoneWithInterface("HashRequest");
371         }
372
373         virtual Version GetVersion()
374         {
375                 // returns the version number of the module to be
376                 // listed in /MODULES
377                 return Version("$Id$", VF_COMMON|VF_VENDOR,API_VERSION);
378         }
379
380         virtual void OnRehash(User* user, const std::string &parameter)
381         {
382                 cu->DoRehash();
383         }
384
385         virtual void OnUserConnect(User* dest)
386         {
387                 std::string* tofree;
388                 if (dest->GetExt("cloaked_host", tofree))
389                         return;
390
391                 if (dest->host.find('.') != std::string::npos || dest->host.find(':') != std::string::npos)
392                 {
393                         unsigned int iv[] = { cu->key1, cu->key2, cu->key3, cu->key4 };
394                         std::string a = cu->LastTwoDomainParts(dest->host);
395                         std::string b;
396
397                         /* InspIRCd users have two hostnames; A displayed
398                          * hostname which can be modified by modules (e.g.
399                          * to create vhosts, implement chghost, etc) and a
400                          * 'real' hostname which you shouldnt write to.
401                          */
402
403                         /* 2008/08/18: add <cloak:ipalways> which always cloaks
404                          * the IP, for anonymity. --nenolod
405                          */
406                         if (!cu->ipalways)
407                         {
408                                 /** Reset the Hash module, and send it our IV and hex table */
409                                 HashResetRequest(this, cu->HashProvider).Send();
410                                 HashKeyRequest(this, cu->HashProvider, iv).Send();
411                                 HashHexRequest(this, cu->HashProvider, cu->xtab[(dest->host[0]) % 4]);
412
413                                 /* Generate a cloak using specialized Hash */
414                                 std::string hostcloak = cu->prefix + "-" + std::string(HashSumRequest(this, cu->HashProvider, dest->host.c_str()).Send()).substr(0,8) + a;
415
416                                 /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
417                                  * according to the DNS RFC) then tough titty, they get cloaked as an IP.
418                                  * Their ISP shouldnt go to town on subdomains, or they shouldnt have a kiddie
419                                  * vhost.
420                                  */
421 #ifdef IPV6
422                                 in6_addr testaddr;
423                                 in_addr testaddr2;
424                                 if ((dest->GetProtocolFamily() == AF_INET6) && (inet_pton(AF_INET6,dest->host.c_str(),&testaddr) < 1) && (hostcloak.length() <= 64))
425                                         /* Invalid ipv6 address, and ipv6 user (resolved host) */
426                                         b = hostcloak;
427                                 else if ((dest->GetProtocolFamily() == AF_INET) && (inet_aton(dest->host.c_str(),&testaddr2) < 1) && (hostcloak.length() <= 64))
428                                         /* Invalid ipv4 address, and ipv4 user (resolved host) */
429                                         b = hostcloak;
430                                 else
431                                         /* Valid ipv6 or ipv4 address (not resolved) ipv4 or ipv6 user */
432                                         b = ((!strchr(dest->host.c_str(),':')) ? cu->Cloak4(dest->host.c_str()) : cu->Cloak6(dest->host.c_str()));
433 #else
434                                 in_addr testaddr;
435                                 if ((inet_aton(dest->host.c_str(),&testaddr) < 1) && (hostcloak.length() <= 64))
436                                         /* Invalid ipv4 address, and ipv4 user (resolved host) */
437                                         b = hostcloak;
438                                 else
439                                         /* Valid ipv4 address (not resolved) ipv4 user */
440                                         b = cu->Cloak4(dest->host.c_str());
441 #endif
442                         }
443                         else
444                         {
445 #ifdef IPV6
446                                 if (dest->GetProtocolFamily() == AF_INET6)
447                                         b = cu->Cloak6(dest->GetIPString());
448 #endif
449                                 if (dest->GetProtocolFamily() == AF_INET)
450                                         b = cu->Cloak4(dest->GetIPString());
451                         }
452
453                         dest->Extend("cloaked_host", new std::string(b));
454                 }
455         }
456
457 };
458
459 MODULE_INIT(ModuleCloaking)