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