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