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