]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
Merge pull request #1417 from B00mX0r/master+fix_1416
[user/henk/code/inspircd.git] / src / modules / m_cloaking.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
7  *   Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2007 John Brooks <john.brooks@dereferenced.net>
9  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11  *
12  * This file is part of InspIRCd.  InspIRCd is free software: you can
13  * redistribute it and/or modify it under the terms of the GNU General Public
14  * License as published by the Free Software Foundation, version 2.
15  *
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25
26 #include "inspircd.h"
27 #include "modules/hash.h"
28
29 enum CloakMode
30 {
31         /** 2.0 cloak of "half" of the hostname plus the full IP hash */
32         MODE_HALF_CLOAK,
33         /** 2.0 cloak of IP hash, split at 2 common CIDR range points */
34         MODE_OPAQUE
35 };
36
37 // lowercase-only encoding similar to base64, used for hash output
38 static const char base32[] = "0123456789abcdefghijklmnopqrstuv";
39
40 /** Handles user mode +x
41  */
42 class CloakUser : public ModeHandler
43 {
44  public:
45         bool active;
46         LocalStringExt ext;
47         std::string debounce_uid;
48         time_t debounce_ts;
49         int debounce_count;
50
51         CloakUser(Module* source)
52                 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER)
53                 , active(false)
54                 , ext("cloaked_host", ExtensionItem::EXT_USER, source)
55                 , debounce_ts(0)
56                 , debounce_count(0)
57         {
58         }
59
60         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding) CXX11_OVERRIDE
61         {
62                 LocalUser* user = IS_LOCAL(dest);
63
64                 /* For remote clients, we don't take any action, we just allow it.
65                  * The local server where they are will set their cloak instead.
66                  * This is fine, as we will receive it later.
67                  */
68                 if (!user)
69                 {
70                         // Remote setters broadcast mode before host while local setters do the opposite, so this takes that into account
71                         active = IS_LOCAL(source) ? adding : !adding;
72                         dest->SetMode(this, adding);
73                         return MODEACTION_ALLOW;
74                 }
75
76                 if (user->uuid == debounce_uid && debounce_ts == ServerInstance->Time())
77                 {
78                         // prevent spamming using /mode user +x-x+x-x+x-x
79                         if (++debounce_count > 2)
80                                 return MODEACTION_DENY;
81                 }
82                 else
83                 {
84                         debounce_uid = user->uuid;
85                         debounce_count = 1;
86                         debounce_ts = ServerInstance->Time();
87                 }
88
89                 if (adding == user->IsModeSet(this))
90                         return MODEACTION_DENY;
91
92                 /* don't allow this user to spam modechanges */
93                 if (source == dest)
94                         user->CommandFloodPenalty += 5000;
95
96                 if (adding)
97                 {
98                         // assume this is more correct
99                         if (user->registered != REG_ALL && user->GetRealHost() != user->GetDisplayedHost())
100                                 return MODEACTION_DENY;
101
102                         std::string* cloak = ext.get(user);
103
104                         if (!cloak)
105                         {
106                                 /* Force creation of missing cloak */
107                                 creator->OnUserConnect(user);
108                                 cloak = ext.get(user);
109                         }
110                         if (cloak)
111                         {
112                                 user->ChangeDisplayedHost(*cloak);
113                                 user->SetMode(this, true);
114                                 return MODEACTION_ALLOW;
115                         }
116                         else
117                                 return MODEACTION_DENY;
118                 }
119                 else
120                 {
121                         /* User is removing the mode, so restore their real host
122                          * and make it match the displayed one.
123                          */
124                         user->SetMode(this, false);
125                         user->ChangeDisplayedHost(user->GetRealHost().c_str());
126                         return MODEACTION_ALLOW;
127                 }
128         }
129 };
130
131 class CommandCloak : public Command
132 {
133  public:
134         CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
135         {
136                 flags_needed = 'o';
137                 syntax = "<host>";
138         }
139
140         CmdResult Handle(const std::vector<std::string>& parameters, User* user) CXX11_OVERRIDE;
141 };
142
143 class ModuleCloaking : public Module
144 {
145  public:
146         CloakUser cu;
147         CloakMode mode;
148         CommandCloak ck;
149         std::string prefix;
150         std::string suffix;
151         std::string key;
152         unsigned int domainparts;
153         dynamic_reference<HashProvider> Hash;
154
155         ModuleCloaking()
156                 : cu(this)
157                 , mode(MODE_OPAQUE)
158                 , ck(this)
159                 , Hash(this, "hash/md5")
160         {
161         }
162
163         /** This function takes a domain name string and returns just the last two domain parts,
164          * or the last domain part if only two are available. Failing that it just returns what it was given.
165          *
166          * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
167          * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
168          * and if it is passed "localhost.localdomain" it will return ".localdomain".
169          *
170          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
171          */
172         std::string LastTwoDomainParts(const std::string &host)
173         {
174                 unsigned int dots = 0;
175                 std::string::size_type splitdot = host.length();
176
177                 for (std::string::size_type x = host.length() - 1; x; --x)
178                 {
179                         if (host[x] == '.')
180                         {
181                                 splitdot = x;
182                                 dots++;
183                         }
184                         if (dots >= domainparts)
185                                 break;
186                 }
187
188                 if (splitdot == host.length())
189                         return "";
190                 else
191                         return host.substr(splitdot);
192         }
193
194         /**
195          * 2.0-style cloaking function
196          * @param item The item to cloak (part of an IP or hostname)
197          * @param id A unique ID for this type of item (to make it unique if the item matches)
198          * @param len The length of the output. Maximum for MD5 is 16 characters.
199          */
200         std::string SegmentCloak(const std::string& item, char id, size_t len)
201         {
202                 std::string input;
203                 input.reserve(key.length() + 3 + item.length());
204                 input.append(1, id);
205                 input.append(key);
206                 input.append(1, '\0'); // null does not terminate a C++ string
207                 input.append(item);
208
209                 std::string rv = Hash->GenerateRaw(input).substr(0,len);
210                 for(size_t i = 0; i < len; i++)
211                 {
212                         // this discards 3 bits per byte. We have an
213                         // overabundance of bits in the hash output, doesn't
214                         // matter which ones we are discarding.
215                         rv[i] = base32[rv[i] & 0x1F];
216                 }
217                 return rv;
218         }
219
220         std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
221         {
222                 std::string bindata;
223                 size_t hop1, hop2, hop3;
224                 size_t len1, len2;
225                 std::string rv;
226                 if (ip.sa.sa_family == AF_INET6)
227                 {
228                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
229                         hop1 = 8;
230                         hop2 = 6;
231                         hop3 = 4;
232                         len1 = 6;
233                         len2 = 4;
234                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
235                         //     6  4  4    9/6
236                         rv.reserve(prefix.length() + 26 + suffix.length());
237                 }
238                 else
239                 {
240                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
241                         hop1 = 3;
242                         hop2 = 0;
243                         hop3 = 2;
244                         len1 = len2 = 3;
245                         // pfx s1.s2. (xxx.xxx or s3) sfx
246                         rv.reserve(prefix.length() + 15 + suffix.length());
247                 }
248
249                 rv.append(prefix);
250                 rv.append(SegmentCloak(bindata, 10, len1));
251                 rv.append(1, '.');
252                 bindata.erase(hop1);
253                 rv.append(SegmentCloak(bindata, 11, len2));
254                 if (hop2)
255                 {
256                         rv.append(1, '.');
257                         bindata.erase(hop2);
258                         rv.append(SegmentCloak(bindata, 12, len2));
259                 }
260
261                 if (full)
262                 {
263                         rv.append(1, '.');
264                         bindata.erase(hop3);
265                         rv.append(SegmentCloak(bindata, 13, 6));
266                         rv.append(suffix);
267                 }
268                 else
269                 {
270                         if (ip.sa.sa_family == AF_INET6)
271                         {
272                                 rv.append(InspIRCd::Format(".%02x%02x.%02x%02x%s",
273                                         ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
274                                         ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], suffix.c_str()));
275                         }
276                         else
277                         {
278                                 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
279                                 rv.append(InspIRCd::Format(".%d.%d%s", ip4[1], ip4[0], suffix.c_str()));
280                         }
281                 }
282                 return rv;
283         }
284
285         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) CXX11_OVERRIDE
286         {
287                 LocalUser* lu = IS_LOCAL(user);
288                 if (!lu)
289                         return MOD_RES_PASSTHRU;
290
291                 OnUserConnect(lu);
292                 std::string* cloak = cu.ext.get(user);
293                 /* Check if they have a cloaked host, but are not using it */
294                 if (cloak && *cloak != user->GetDisplayedHost())
295                 {
296                         const std::string cloakMask = user->nick + "!" + user->ident + "@" + *cloak;
297                         if (InspIRCd::Match(cloakMask, mask))
298                                 return MOD_RES_DENY;
299                 }
300                 return MOD_RES_PASSTHRU;
301         }
302
303         void Prioritize() CXX11_OVERRIDE
304         {
305                 /* Needs to be after m_banexception etc. */
306                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
307         }
308
309         // this unsets umode +x on every host change. If we are actually doing a +x
310         // mode change, we will call SetMode back to true AFTER the host change is done.
311         void OnChangeHost(User* u, const std::string& host) CXX11_OVERRIDE
312         {
313                 if (u->IsModeSet(cu) && !cu.active)
314                 {
315                         u->SetMode(cu, false);
316                         u->WriteCommand("MODE", "-" + ConvToStr(cu.GetModeChar()));
317                 }
318                 cu.active = false;
319         }
320
321         Version GetVersion() CXX11_OVERRIDE
322         {
323                 std::string testcloak = "broken";
324                 if (Hash)
325                 {
326                         switch (mode)
327                         {
328                                 case MODE_HALF_CLOAK:
329                                         // Use old cloaking verification to stay compatible with 2.0
330                                         // But verify domainparts when use 3.0-only features
331                                         if (domainparts == 3)
332                                                 testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
333                                         else
334                                         {
335                                                 irc::sockets::sockaddrs sa;
336                                                 testcloak = GenCloak(sa, "", testcloak + ConvToStr(domainparts));
337                                         }
338                                         break;
339                                 case MODE_OPAQUE:
340                                         testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
341                         }
342                 }
343                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
344         }
345
346         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
347         {
348                 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
349                 prefix = tag->getString("prefix");
350                 suffix = tag->getString("suffix", ".IP");
351
352                 std::string modestr = tag->getString("mode");
353                 if (modestr == "half")
354                 {
355                         mode = MODE_HALF_CLOAK;
356                         domainparts = tag->getInt("domainparts", 3, 1, 10);
357                 }
358                 else if (modestr == "full")
359                         mode = MODE_OPAQUE;
360                 else
361                         throw ModuleException("Bad value for <cloak:mode>; must be half or full");
362
363                 key = tag->getString("key");
364                 if (key.empty() || key == "secret")
365                         throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
366         }
367
368         std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
369         {
370                 std::string chost;
371
372                 irc::sockets::sockaddrs hostip;
373                 bool host_is_ip = irc::sockets::aptosa(host, ip.port(), hostip) && hostip == ip;
374
375                 switch (mode)
376                 {
377                         case MODE_HALF_CLOAK:
378                         {
379                                 if (!host_is_ip)
380                                         chost = prefix + SegmentCloak(host, 1, 6) + LastTwoDomainParts(host);
381                                 if (chost.empty() || chost.length() > 50)
382                                         chost = SegmentIP(ip, false);
383                                 break;
384                         }
385                         case MODE_OPAQUE:
386                         default:
387                                 chost = SegmentIP(ip, true);
388                 }
389                 return chost;
390         }
391
392         void OnUserConnect(LocalUser* dest) CXX11_OVERRIDE
393         {
394                 std::string* cloak = cu.ext.get(dest);
395                 if (cloak)
396                         return;
397
398                 cu.ext.set(dest, GenCloak(dest->client_sa, dest->GetIPString(), dest->GetRealHost()));
399         }
400 };
401
402 CmdResult CommandCloak::Handle(const std::vector<std::string> &parameters, User *user)
403 {
404         ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
405         irc::sockets::sockaddrs sa;
406         std::string cloak;
407
408         if (irc::sockets::aptosa(parameters[0], 0, sa))
409                 cloak = mod->GenCloak(sa, parameters[0], parameters[0]);
410         else
411                 cloak = mod->GenCloak(sa, "", parameters[0]);
412
413         user->WriteNotice("*** Cloak for " + parameters[0] + " is " + cloak);
414
415         return CMD_SUCCESS;
416 }
417
418 MODULE_INIT(ModuleCloaking)