]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
3cd2f47178ad267907da517017c1f98bc16f9be8
[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                                         /* Cloaked host has been set before on this user, don't bother to recalculate and waste cpu */
106                                         dest->ChangeDisplayedHost(cloak->c_str());
107                                         dest->SetMode('x',true);
108                                         return MODEACTION_ALLOW;
109                                 }
110                         }
111                 }
112                 else
113                 {
114                         if (dest->IsModeSet('x'))
115                         {
116                                 /* User is removing the mode, so just restore their real host
117                                  * and make it match the displayed one.
118                                  */
119                                 dest->ChangeDisplayedHost(dest->host.c_str());
120                                 dest->SetMode('x',false);
121                                 return MODEACTION_ALLOW;
122                         }
123                 }
124
125                 return MODEACTION_DENY;
126         }
127
128         std::string Cloak4(const char* ip)
129         {
130                 unsigned int iv[] = { key1, key2, key3, key4 };
131                 irc::sepstream seps(ip, '.');
132                 std::string ra[4];;
133                 std::string octet[4];
134                 int i[4];
135
136                 for (int j = 0; j < 4; j++)
137                 {
138                         seps.GetToken(octet[j]);
139                         i[j] = atoi(octet[j].c_str());
140                 }
141
142                 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
143                 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
144                 octet[1] = octet[0] + "." + octet[1];
145
146                 /* Reset the Hash module and send it our IV */
147                 HashResetRequest(Sender, HashProvider).Send();
148                 HashKeyRequest(Sender, HashProvider, iv).Send();
149
150                 /* Send the Hash module a different hex table for each octet group's Hash sum */
151                 for (int k = 0; k < 4; k++)
152                 {
153                         HashHexRequest(Sender, HashProvider, xtab[(iv[k]+i[k]) % 4]).Send();
154                         ra[k] = std::string(HashSumRequest(Sender, HashProvider, octet[k]).Send()).substr(0,6);
155                 }
156                 /* Stick them all together */
157                 return std::string().append(ra[0]).append(".").append(ra[1]).append(".").append(ra[2]).append(".").append(ra[3]);
158         }
159
160         std::string Cloak6(const char* ip)
161         {
162                 /* Theyre using 4in6 (YUCK). Translate as ipv4 cloak */
163                 if (!strncmp(ip, "0::ffff:", 8))
164                         return Cloak4(ip + 8);
165
166                 /* If we get here, yes it really is an ipv6 ip */
167                 unsigned int iv[] = { key1, key2, key3, key4 };
168                 std::vector<std::string> hashies;
169                 std::string item;
170                 int rounds = 0;
171
172                 /* Reset the Hash module and send it our IV */
173                 HashResetRequest(Sender, HashProvider).Send();
174                 HashKeyRequest(Sender, HashProvider, iv).Send();
175
176                 for (const char* input = ip; *input; input++)
177                 {
178                         item += *input;
179                         if (item.length() > 7)
180                         {
181                                 /* Send the Hash module a different hex table for each octet group's Hash sum */
182                                 HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send();
183                                 hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8));
184                                 item.clear();
185                         }
186                         rounds++;
187                 }
188                 if (!item.empty())
189                 {
190                         /* Send the Hash module a different hex table for each octet group's Hash sum */
191                         HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send();
192                         hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8));
193                         item.clear();
194                 }
195                 /* Stick them all together */
196                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
197         }
198
199         void DoRehash()
200         {
201                 ConfigReader Conf(ServerInstance);
202                 bool lowercase;
203
204                 /* These are *not* using the need_positive parameter of ReadInteger -
205                  * that will limit the valid values to only the positive values in a
206                  * signed int. Instead, accept any value that fits into an int and
207                  * cast it to an unsigned int. That will, a bit oddly, give us the full
208                  * spectrum of an unsigned integer. - Special */
209                 key1 = key2 = key3 = key4 = 0;
210                 key1 = (unsigned int) Conf.ReadInteger("cloak","key1",0,false);
211                 key2 = (unsigned int) Conf.ReadInteger("cloak","key2",0,false);
212                 key3 = (unsigned int) Conf.ReadInteger("cloak","key3",0,false);
213                 key4 = (unsigned int) Conf.ReadInteger("cloak","key4",0,false);
214                 prefix = Conf.ReadValue("cloak","prefix",0);
215                 ipalways = Conf.ReadFlag("cloak", "ipalways", 0);
216                 lowercase = Conf.ReadFlag("cloak", "lowercase", 0);
217
218                 if (!lowercase)
219                 {
220                         xtab[0] = "F92E45D871BCA630";
221                         xtab[1] = "A1B9D80C72E653F4";
222                         xtab[2] = "1ABC078934DEF562";
223                         xtab[3] = "ABCDEF5678901234";
224                 }
225                 else
226                 {
227                         xtab[0] = "f92e45d871bca630";
228                         xtab[1] = "a1b9d80c72e653f4";
229                         xtab[2] = "1abc078934def562";
230                         xtab[3] = "abcdef5678901234";
231                 }
232
233                 if (prefix.empty())
234                         prefix = ServerInstance->Config->Network;
235
236                 if (!key1 || !key2 || !key3 || !key4)
237                 {
238                         std::string detail;
239                         if (!key1)
240                                 detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
241                         else if (!key2)
242                                 detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
243                         else if (!key3)
244                                 detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
245                         else if (!key4)
246                                 detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
247
248                         throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
249                 }
250         }
251 };
252
253
254 class ModuleCloaking : public Module
255 {
256  private:
257
258         CloakUser* cu;
259         Module* HashModule;
260
261  public:
262         ModuleCloaking(InspIRCd* Me)
263                 : Module(Me)
264         {
265                 /* Attempt to locate the md5 service provider, bail if we can't find it */
266                 HashModule = ServerInstance->Modules->Find("m_md5.so");
267                 if (!HashModule)
268                         throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_cloaking.so.");
269
270                 cu = new CloakUser(ServerInstance, this, HashModule);
271
272                 try
273                 {
274                         OnRehash(NULL,"");
275                 }
276                 catch (ModuleException &e)
277                 {
278                         delete cu;
279                         throw e;
280                 }
281
282                 /* Register it with the core */
283                 if (!ServerInstance->Modes->AddMode(cu))
284                 {
285                         delete cu;
286                         throw ModuleException("Could not add new modes!");
287                 }
288
289                 ServerInstance->Modules->UseInterface("HashRequest");
290
291                 Implementation eventlist[] = { I_OnRehash, I_OnUserDisconnect, I_OnCleanup, I_OnCheckBan, I_OnUserConnect, I_OnSyncUserMetaData };
292                 ServerInstance->Modules->Attach(eventlist, this, 6);
293         }
294
295         void OnSyncUserMetaData(User* user, Module* proto,void* opaque, const std::string &extname, bool displayable)
296         {
297                 if ((displayable) && (extname == "cloaked_host"))
298                 {
299                         std::string* cloak;
300                         if (user->GetExt("cloaked_host", cloak))
301                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, *cloak);
302                 }
303         }
304
305
306         virtual int OnCheckBan(User* user, Channel* chan)
307         {
308                 char mask[MAXBUF];
309                 std::string* tofree;
310                 /* Check if they have a cloaked host, but are not using it */
311                 if (user->GetExt("cloaked_host", tofree) && *tofree != user->dhost)
312                 {
313                         snprintf(mask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), tofree->c_str());
314                         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
315                         {
316                                 if (InspIRCd::Match(mask,i->data))
317                                         return -1;
318                         }
319                 }
320                 return 0;
321         }
322
323         void Prioritize()
324         {
325                 /* Needs to be after m_banexception etc. */
326                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIO_LAST);
327
328                 /* but before m_conn_umodes, so host is generated ready to apply */
329                 Module *um = ServerInstance->Modules->Find("m_conn_umodes.so");
330                 ServerInstance->Modules->SetPriority(this, I_OnUserConnect, PRIO_AFTER, &um);
331         }
332
333         virtual void OnUserDisconnect(User* user)
334         {
335                 std::string* tofree;
336                 if (user->GetExt("cloaked_host", tofree))
337                         delete tofree;
338         }
339
340         virtual void OnCleanup(int target_type, void* item)
341         {
342                 if (target_type == TYPE_USER)
343                         OnUserDisconnect((User*)item);
344         }
345
346         virtual ~ModuleCloaking()
347         {
348                 ServerInstance->Modes->DelMode(cu);
349                 delete cu;
350                 ServerInstance->Modules->DoneWithInterface("HashRequest");
351         }
352
353         virtual Version GetVersion()
354         {
355                 // returns the version number of the module to be
356                 // listed in /MODULES
357                 return Version("$Id$", VF_COMMON|VF_VENDOR,API_VERSION);
358         }
359
360         virtual void OnRehash(User* user, const std::string &parameter)
361         {
362                 cu->DoRehash();
363         }
364
365         virtual void OnUserConnect(User* dest)
366         {
367                 if (dest->host.find('.') != std::string::npos || dest->host.find(':') != std::string::npos)
368                 {
369                         unsigned int iv[] = { cu->key1, cu->key2, cu->key3, cu->key4 };
370                         std::string a = cu->LastTwoDomainParts(dest->host);
371                         std::string b;
372
373                         /* InspIRCd users have two hostnames; A displayed
374                          * hostname which can be modified by modules (e.g.
375                          * to create vhosts, implement chghost, etc) and a
376                          * 'real' hostname which you shouldnt write to.
377                          */
378
379                         /* 2008/08/18: add <cloak:ipalways> which always cloaks
380                          * the IP, for anonymity. --nenolod
381                          */
382                         if (!cu->ipalways)
383                         {
384                                 /** Reset the Hash module, and send it our IV and hex table */
385                                 HashResetRequest(this, cu->HashProvider).Send();
386                                 HashKeyRequest(this, cu->HashProvider, iv).Send();
387                                 HashHexRequest(this, cu->HashProvider, cu->xtab[(dest->host[0]) % 4]);
388
389                                 /* Generate a cloak using specialized Hash */
390                                 std::string hostcloak = cu->prefix + "-" + std::string(HashSumRequest(this, cu->HashProvider, dest->host.c_str()).Send()).substr(0,8) + a;
391
392                                 /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
393                                  * according to the DNS RFC) then tough titty, they get cloaked as an IP.
394                                  * Their ISP shouldnt go to town on subdomains, or they shouldnt have a kiddie
395                                  * vhost.
396                                  */
397 #ifdef IPV6
398                                 in6_addr testaddr;
399                                 in_addr testaddr2;
400                                 if ((dest->GetProtocolFamily() == AF_INET6) && (inet_pton(AF_INET6,dest->host.c_str(),&testaddr) < 1) && (hostcloak.length() <= 64))
401                                         /* Invalid ipv6 address, and ipv6 user (resolved host) */
402                                         b = hostcloak;
403                                 else if ((dest->GetProtocolFamily() == AF_INET) && (inet_aton(dest->host.c_str(),&testaddr2) < 1) && (hostcloak.length() <= 64))
404                                         /* Invalid ipv4 address, and ipv4 user (resolved host) */
405                                         b = hostcloak;
406                                 else
407                                         /* Valid ipv6 or ipv4 address (not resolved) ipv4 or ipv6 user */
408                                         b = ((!strchr(dest->host.c_str(),':')) ? cu->Cloak4(dest->host.c_str()) : cu->Cloak6(dest->host.c_str()));
409 #else
410                                 in_addr testaddr;
411                                 if ((inet_aton(dest->host.c_str(),&testaddr) < 1) && (hostcloak.length() <= 64))
412                                         /* Invalid ipv4 address, and ipv4 user (resolved host) */
413                                         b = hostcloak;
414                                 else
415                                         /* Valid ipv4 address (not resolved) ipv4 user */
416                                         b = cu->Cloak4(dest->host.c_str());
417 #endif
418                         }
419                         else
420                         {
421 #ifdef IPV6
422                                 if (dest->GetProtocolFamily() == AF_INET6)
423                                         b = cu->Cloak6(dest->GetIPString());
424 #endif
425                                 if (dest->GetProtocolFamily() == AF_INET)
426                                         b = cu->Cloak4(dest->GetIPString());
427                         }
428
429                         dest->Extend("cloaked_host", new std::string(b));
430                 }
431         }
432
433 };
434
435 MODULE_INIT(ModuleCloaking)