]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
25d997798192c1044d529b643f7df54c4d150bfb
[user/henk/code/inspircd.git] / src / modules / m_cloaking.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 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 /* $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* HashProvider;
32         const char *xtab[4];
33         LocalStringExt ext;
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(Module* source, Module* Hash)
67                 : ModeHandler(source, 'x', PARAM_NONE, MODETYPE_USER), HashProvider(Hash),
68                 ext("cloaked_host", source)
69         {
70         }
71
72         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
73         {
74                 /* For remote clients, we dont take any action, we just allow it.
75                  * The local server where they are will set their cloak instead.
76                  * This is fine, as we will recieve it later.
77                  */
78                 if (!IS_LOCAL(dest))
79                 {
80                         dest->SetMode('x',adding);
81                         return MODEACTION_ALLOW;
82                 }
83
84                 /* don't allow this user to spam modechanges */
85                 dest->IncreasePenalty(5);
86
87                 if (adding)
88                 {
89                         if(!dest->IsModeSet('x'))
90                         {
91                                 /* The mode is being turned on - so attempt to
92                                  * allocate the user a cloaked host using a non-reversible
93                                  * algorithm (its simple, but its non-reversible so the
94                                  * simplicity doesnt really matter). This algorithm
95                                  * will not work if the user has only one level of domain
96                                  * naming in their hostname (e.g. if they are on a lan or
97                                  * are connecting via localhost) -- this doesnt matter much.
98                                  */
99
100                                 std::string* cloak = ext.get(dest);
101
102                                 if (!cloak)
103                                 {
104                                         /* Force creation of missing cloak */
105                                         creator->OnUserConnect(dest);
106                                         cloak = ext.get(dest);
107                                 }
108                                 if (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(creator, HashProvider).Send();
152                 HashKeyRequest(creator, 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(creator, HashProvider, xtab[(iv[k]+i[k]) % 4]).Send();
158                         ra[k] = std::string(HashSumRequest(creator, 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                 unsigned int iv[] = { key1, key2, key3, key4 };
167                 std::vector<std::string> hashies;
168                 std::string item;
169                 int rounds = 0;
170
171                 /* Reset the Hash module and send it our IV */
172                 HashResetRequest(creator, HashProvider).Send();
173                 HashKeyRequest(creator, HashProvider, iv).Send();
174
175                 for (const char* input = ip; *input; input++)
176                 {
177                         item += *input;
178                         if (item.length() > 7)
179                         {
180                                 /* Send the Hash module a different hex table for each octet group's Hash sum */
181                                 HashHexRequest(creator, HashProvider, xtab[(key1+rounds) % 4]).Send();
182                                 hashies.push_back(std::string(HashSumRequest(creator, HashProvider, item).Send()).substr(0,8));
183                                 item.clear();
184                         }
185                         rounds++;
186                 }
187                 if (!item.empty())
188                 {
189                         /* Send the Hash module a different hex table for each octet group's Hash sum */
190                         HashHexRequest(creator, HashProvider, xtab[(key1+rounds) % 4]).Send();
191                         hashies.push_back(std::string(HashSumRequest(creator, HashProvider, item).Send()).substr(0,8));
192                         item.clear();
193                 }
194                 /* Stick them all together */
195                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
196         }
197
198         void DoRehash()
199         {
200                 ConfigReader Conf(ServerInstance);
201                 bool lowercase;
202
203                 /* These are *not* using the need_positive parameter of ReadInteger -
204                  * that will limit the valid values to only the positive values in a
205                  * signed int. Instead, accept any value that fits into an int and
206                  * cast it to an unsigned int. That will, a bit oddly, give us the full
207                  * spectrum of an unsigned integer. - Special */
208                 key1 = key2 = key3 = key4 = 0;
209                 key1 = (unsigned int) Conf.ReadInteger("cloak","key1",0,false);
210                 key2 = (unsigned int) Conf.ReadInteger("cloak","key2",0,false);
211                 key3 = (unsigned int) Conf.ReadInteger("cloak","key3",0,false);
212                 key4 = (unsigned int) Conf.ReadInteger("cloak","key4",0,false);
213                 prefix = Conf.ReadValue("cloak","prefix",0);
214                 ipalways = Conf.ReadFlag("cloak", "ipalways", 0);
215                 lowercase = Conf.ReadFlag("cloak", "lowercase", 0);
216
217                 if (!lowercase)
218                 {
219                         xtab[0] = "F92E45D871BCA630";
220                         xtab[1] = "A1B9D80C72E653F4";
221                         xtab[2] = "1ABC078934DEF562";
222                         xtab[3] = "ABCDEF5678901234";
223                 }
224                 else
225                 {
226                         xtab[0] = "f92e45d871bca630";
227                         xtab[1] = "a1b9d80c72e653f4";
228                         xtab[2] = "1abc078934def562";
229                         xtab[3] = "abcdef5678901234";
230                 }
231
232                 if (prefix.empty())
233                         prefix = ServerInstance->Config->Network;
234
235                 if (!key1 || !key2 || !key3 || !key4)
236                 {
237                         std::string detail;
238                         if (!key1)
239                                 detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
240                         else if (!key2)
241                                 detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
242                         else if (!key3)
243                                 detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
244                         else if (!key4)
245                                 detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
246
247                         throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
248                 }
249         }
250 };
251
252
253 class ModuleCloaking : public Module
254 {
255  private:
256         CloakUser* cu;
257
258  public:
259         ModuleCloaking(InspIRCd*)
260         {
261                 /* Attempt to locate the md5 service provider, bail if we can't find it */
262                 Module* HashModule = ServerInstance->Modules->Find("m_md5.so");
263                 if (!HashModule)
264                         throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_cloaking.so.");
265
266                 cu = new CloakUser(this, HashModule);
267
268                 try
269                 {
270                         OnRehash(NULL);
271                 }
272                 catch (ModuleException &e)
273                 {
274                         delete cu;
275                         throw e;
276                 }
277
278                 /* Register it with the core */
279                 if (!ServerInstance->Modes->AddMode(cu))
280                 {
281                         delete cu;
282                         throw ModuleException("Could not add new modes!");
283                 }
284
285                 ServerInstance->Modules->UseInterface("HashRequest");
286                 Extensible::Register(&cu->ext);
287
288                 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect };
289                 ServerInstance->Modules->Attach(eventlist, this, 3);
290
291                 CloakExistingUsers();
292         }
293
294         void CloakExistingUsers()
295         {
296                 std::string* cloak;
297                 for (std::vector<User*>::iterator u = ServerInstance->Users->local_users.begin(); u != ServerInstance->Users->local_users.end(); u++)
298                 {
299                         cloak = cu->ext.get(*u);
300                         if (!cloak)
301                         {
302                                 OnUserConnect(*u);
303                         }
304                 }
305         }
306
307         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask)
308         {
309                 char cmask[MAXBUF];
310                 std::string* cloak = cu->ext.get(user);
311                 /* Check if they have a cloaked host, but are not using it */
312                 if (cloak && *cloak != user->dhost)
313                 {
314                         snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str());
315                         if (InspIRCd::Match(cmask,mask))
316                                 return MOD_RES_DENY;
317                 }
318                 return MOD_RES_PASSTHRU;
319         }
320
321         void Prioritize()
322         {
323                 /* Needs to be after m_banexception etc. */
324                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
325
326                 /* but before m_conn_umodes, so host is generated ready to apply */
327                 Module *um = ServerInstance->Modules->Find("m_conn_umodes.so");
328                 ServerInstance->Modules->SetPriority(this, I_OnUserConnect, PRIORITY_AFTER, &um);
329         }
330
331         ~ModuleCloaking()
332         {
333                 ServerInstance->Modes->DelMode(cu);
334                 delete cu;
335                 ServerInstance->Modules->DoneWithInterface("HashRequest");
336         }
337
338         Version GetVersion()
339         {
340                 // returns the version number of the module to be
341                 // listed in /MODULES
342                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR,API_VERSION);
343         }
344
345         void OnRehash(User* user)
346         {
347                 cu->DoRehash();
348         }
349
350         void OnUserConnect(User* dest)
351         {
352                 std::string* cloak = cu->ext.get(dest);
353                 if (cloak)
354                         return;
355
356                 if (dest->host.find('.') != std::string::npos || dest->host.find(':') != std::string::npos)
357                 {
358                         unsigned int iv[] = { cu->key1, cu->key2, cu->key3, cu->key4 };
359                         std::string a = cu->LastTwoDomainParts(dest->host);
360                         std::string b;
361
362                         /* InspIRCd users have two hostnames; A displayed
363                          * hostname which can be modified by modules (e.g.
364                          * to create vhosts, implement chghost, etc) and a
365                          * 'real' hostname which you shouldnt write to.
366                          */
367
368                         /* 2008/08/18: add <cloak:ipalways> which always cloaks
369                          * the IP, for anonymity. --nenolod
370                          */
371                         if (!cu->ipalways)
372                         {
373                                 /** Reset the Hash module, and send it our IV and hex table */
374                                 HashResetRequest(this, cu->HashProvider).Send();
375                                 HashKeyRequest(this, cu->HashProvider, iv).Send();
376                                 HashHexRequest(this, cu->HashProvider, cu->xtab[(dest->host[0]) % 4]);
377
378                                 /* Generate a cloak using specialized Hash */
379                                 std::string hostcloak = cu->prefix + "-" + std::string(HashSumRequest(this, cu->HashProvider, dest->host.c_str()).Send()).substr(0,8) + a;
380
381                                 /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
382                                  * according to the DNS RFC) then tough titty, they get cloaked as an IP.
383                                  * Their ISP shouldnt go to town on subdomains, or they shouldnt have a kiddie
384                                  * vhost.
385                                  */
386                                 std::string testaddr;
387                                 int testport;
388                                 if (!irc::sockets::satoap(&dest->client_sa, testaddr, testport) && (hostcloak.length() <= 64))
389                                         /* not a valid address, must have been a host, so cloak as a host */
390                                         b = hostcloak;
391                                 else if (dest->client_sa.sa.sa_family == AF_INET6)
392                                         b = cu->Cloak6(dest->GetIPString());
393                                 else
394                                         b = cu->Cloak4(dest->GetIPString());
395                         }
396                         else
397                         {
398                                 if (dest->client_sa.sa.sa_family == AF_INET6)
399                                         b = cu->Cloak6(dest->GetIPString());
400                                 else
401                                         b = cu->Cloak4(dest->GetIPString());
402                         }
403
404                         cu->ext.set(dest,b);
405                 }
406         }
407
408 };
409
410 MODULE_INIT(ModuleCloaking)