]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
8a3a4e482fbbea7d3d2a04193b88f83461940a98
[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         std::string prefix;
25         unsigned int key1;
26         unsigned int key2;
27         unsigned int key3;
28         unsigned int key4;
29         bool ipalways;
30         Module* Sender;
31         Module* HashProvider;
32         const char *xtab[4];
33
34         /** This function takes a domain name string and returns just the last two domain parts,
35          * or the last domain part if only two are available. Failing that it just returns what it was given.
36          *
37          * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
38          * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
39          * and if it is passed "localhost.localdomain" it will return ".localdomain".
40          * 
41          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
42          */
43         std::string LastTwoDomainParts(const std::string &host)
44         {
45                 int dots = 0;
46                 std::string::size_type splitdot = host.length();
47
48                 for (std::string::size_type x = host.length() - 1; x; --x)
49                 {
50                         if (host[x] == '.')
51                         {
52                                 splitdot = x;
53                                 dots++;
54                         }
55                         if (dots >= 3)
56                                 break;
57                 }
58
59                 if (splitdot == host.length())
60                         return host;
61                 else
62                         return host.substr(splitdot);
63         }
64         
65  public:
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                         return MODEACTION_ALLOW;
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                                 char* n1 = strchr(dest->host,'.');
99                                 char* n2 = strchr(dest->host,':');
100                         
101                                 if (n1 || n2)
102                                 {
103                                         unsigned int iv[] = { key1, key2, key3, key4 };
104                                         std::string a = LastTwoDomainParts(dest->host);
105                                         std::string b;
106
107                                         /* InspIRCd users have two hostnames; A displayed
108                                          * hostname which can be modified by modules (e.g.
109                                          * to create vhosts, implement chghost, etc) and a
110                                          * 'real' hostname which you shouldnt write to.
111                                          */
112
113                                         /* 2008/08/18: add <cloak:ipalways> which always cloaks
114                                          * the IP, for anonymity. --nenolod
115                                          */
116                                         if (!ipalways)
117                                         {
118                                                 /** Reset the Hash module, and send it our IV and hex table */
119                                                 HashResetRequest(Sender, HashProvider).Send();
120                                                 HashKeyRequest(Sender, HashProvider, iv).Send();
121                                                 HashHexRequest(Sender, HashProvider, xtab[(*dest->host) % 4]);
122
123                                                 /* Generate a cloak using specialized Hash */
124                                                 std::string hostcloak = prefix + "-" + std::string(HashSumRequest(Sender, HashProvider, dest->host).Send()).substr(0,8) + a;
125
126                                                 /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes
127                                                  * according to the DNS RFC) then tough titty, they get cloaked as an IP. 
128                                                  * Their ISP shouldnt go to town on subdomains, or they shouldnt have a kiddie
129                                                  * vhost.
130                                                  */
131 #ifdef IPV6
132                                                 in6_addr testaddr;
133                                                 in_addr testaddr2;
134                                                 if ((dest->GetProtocolFamily() == AF_INET6) && (inet_pton(AF_INET6,dest->host,&testaddr) < 1) && (hostcloak.length() <= 64))
135                                                         /* Invalid ipv6 address, and ipv6 user (resolved host) */
136                                                         b = hostcloak;
137                                                 else if ((dest->GetProtocolFamily() == AF_INET) && (inet_aton(dest->host,&testaddr2) < 1) && (hostcloak.length() <= 64))
138                                                         /* Invalid ipv4 address, and ipv4 user (resolved host) */
139                                                         b = hostcloak;
140                                                 else
141                                                         /* Valid ipv6 or ipv4 address (not resolved) ipv4 or ipv6 user */
142                                                         b = ((!strchr(dest->host,':')) ? Cloak4(dest->host) : Cloak6(dest->host));
143 #else
144                                                 in_addr testaddr;
145                                                 if ((inet_aton(dest->host,&testaddr) < 1) && (hostcloak.length() <= 64))
146                                                         /* Invalid ipv4 address, and ipv4 user (resolved host) */
147                                                         b = hostcloak;
148                                                 else
149                                                         /* Valid ipv4 address (not resolved) ipv4 user */
150                                                         b = Cloak4(dest->host);
151 #endif
152                                         }
153                                         else
154                                         {
155 #ifdef IPV6
156                                                 if (dest->GetProtocolFamily() == AF_INET6)
157                                                         b = Cloak6(dest->GetIPString());
158 #endif
159                                                 if (dest->GetProtocolFamily() == AF_INET)
160                                                         b = Cloak4(dest->GetIPString());
161                                         }
162
163                                         dest->ChangeDisplayedHost(b.c_str());
164                                 }
165                                 
166                                 dest->SetMode('x',true);
167                                 return MODEACTION_ALLOW;
168                         }
169                 }
170                 else
171                 {
172                         if (dest->IsModeSet('x'))
173                         {
174                                 /* User is removing the mode, so just restore their real host
175                                  * and make it match the displayed one.
176                                  */
177                                 dest->ChangeDisplayedHost(dest->host);
178                                 dest->SetMode('x',false);
179                                 return MODEACTION_ALLOW;
180                         }
181                 }
182
183                 return MODEACTION_DENY;
184         }
185
186         std::string Cloak4(const char* ip)
187         {
188                 unsigned int iv[] = { key1, key2, key3, key4 };
189                 irc::sepstream seps(ip, '.');
190                 std::string ra[4];;
191                 std::string octet[4];
192                 int i[4];
193
194                 for (int j = 0; j < 4; j++)
195                 {
196                         seps.GetToken(octet[j]);
197                         i[j] = atoi(octet[j].c_str());
198                 }
199
200                 octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3];
201                 octet[2] = octet[0] + "." + octet[1] + "." + octet[2];
202                 octet[1] = octet[0] + "." + octet[1];
203
204                 /* Reset the Hash module and send it our IV */
205                 HashResetRequest(Sender, HashProvider).Send();
206                 HashKeyRequest(Sender, HashProvider, iv).Send();
207
208                 /* Send the Hash module a different hex table for each octet group's Hash sum */
209                 for (int k = 0; k < 4; k++)
210                 {
211                         HashHexRequest(Sender, HashProvider, xtab[(iv[k]+i[k]) % 4]).Send();
212                         ra[k] = std::string(HashSumRequest(Sender, HashProvider, octet[k]).Send()).substr(0,6);
213                 }
214                 /* Stick them all together */
215                 return std::string().append(ra[0]).append(".").append(ra[1]).append(".").append(ra[2]).append(".").append(ra[3]);
216         }
217
218         std::string Cloak6(const char* ip)
219         {
220                 /* Theyre using 4in6 (YUCK). Translate as ipv4 cloak */
221                 if (!strncmp(ip, "0::ffff:", 8))
222                         return Cloak4(ip + 8);
223
224                 /* If we get here, yes it really is an ipv6 ip */
225                 unsigned int iv[] = { key1, key2, key3, key4 };
226                 std::vector<std::string> hashies;
227                 std::string item;
228                 int rounds = 0;
229
230                 /* Reset the Hash module and send it our IV */
231                 HashResetRequest(Sender, HashProvider).Send();
232                 HashKeyRequest(Sender, HashProvider, iv).Send();
233
234                 for (const char* input = ip; *input; input++)
235                 {
236                         item += *input;
237                         if (item.length() > 7)
238                         {
239                                 /* Send the Hash module a different hex table for each octet group's Hash sum */
240                                 HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send();
241                                 hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8));
242                                 item.clear();
243                         }
244                         rounds++;
245                 }
246                 if (!item.empty())
247                 {
248                         /* Send the Hash module a different hex table for each octet group's Hash sum */
249                         HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send();
250                         hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8));
251                         item.clear();
252                 }
253                 /* Stick them all together */
254                 return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined();
255         }
256         
257         void DoRehash()
258         {
259                 ConfigReader Conf(ServerInstance);
260                 bool lowercase;
261                 
262                 /* These are *not* using the need_positive parameter of ReadInteger - 
263                  * that will limit the valid values to only the positive values in a
264                  * signed int. Instead, accept any value that fits into an int and
265                  * cast it to an unsigned int. That will, a bit oddly, give us the full
266                  * spectrum of an unsigned integer. - Special */
267                 key1 = key2 = key3 = key4 = 0;
268                 key1 = (unsigned int) Conf.ReadInteger("cloak","key1",0,false);
269                 key2 = (unsigned int) Conf.ReadInteger("cloak","key2",0,false);
270                 key3 = (unsigned int) Conf.ReadInteger("cloak","key3",0,false);
271                 key4 = (unsigned int) Conf.ReadInteger("cloak","key4",0,false);
272                 prefix = Conf.ReadValue("cloak","prefix",0);
273                 ipalways = Conf.ReadFlag("cloak", "ipalways", 0);
274                 lowercase = Conf.ReadFlag("cloak", "lowercase", 0);
275                 
276                 if (!lowercase)
277                 {
278                         xtab[0] = "F92E45D871BCA630";
279                         xtab[1] = "A1B9D80C72E653F4";
280                         xtab[2] = "1ABC078934DEF562";
281                         xtab[3] = "ABCDEF5678901234";
282                 }
283                 else
284                 {
285                         xtab[0] = "f92e45d871bca630";
286                         xtab[1] = "a1b9d80c72e653f4";
287                         xtab[2] = "1abc078934def562";
288                         xtab[3] = "abcdef5678901234";
289                 }
290
291                 if (prefix.empty())
292                         prefix = ServerInstance->Config->Network;
293
294                 if (!key1 || !key2 || !key3 || !key4)
295                 {
296                         std::string detail;
297                         if (!key1)
298                                 detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist.";
299                         else if (!key2)
300                                 detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist.";
301                         else if (!key3)
302                                 detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist.";
303                         else if (!key4)
304                                 detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist.";
305
306                         throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail);
307                 }
308         }
309 };
310
311
312 class ModuleCloaking : public Module
313 {
314  private:
315         
316         CloakUser* cu;
317         Module* HashModule;
318
319  public:
320         ModuleCloaking(InspIRCd* Me)
321                 : Module(Me)
322         {
323                 /* Attempt to locate the md5 service provider, bail if we can't find it */
324                 HashModule = ServerInstance->Modules->Find("m_md5.so");
325                 if (!HashModule)
326                         throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_cloaking.so.");
327
328                 cu = new CloakUser(ServerInstance, this, HashModule);
329
330                 try
331                 {
332                         OnRehash(NULL,"");
333                 }
334                 catch (CoreException &e)
335                 {
336                         delete cu;
337                         throw e;
338                 }
339
340                 /* Register it with the core */
341                 if (!ServerInstance->Modes->AddMode(cu))
342                 {
343                         delete cu;
344                         throw ModuleException("Could not add new modes!");
345                 }
346
347                 ServerInstance->Modules->UseInterface("HashRequest");
348
349                 Implementation eventlist[] = { I_OnRehash };
350                 ServerInstance->Modules->Attach(eventlist, this, 1);
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(1,2,0,2,VF_COMMON|VF_VENDOR,API_VERSION);
365         }
366
367         virtual void OnRehash(User* user, const std::string &parameter)
368         {
369                 cu->DoRehash();
370         }
371
372 };
373
374 MODULE_INIT(ModuleCloaking)