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