]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
Merge pull request #1270 from SaberUK/master+sasl
[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         LocalStringExt ext;
46         std::string debounce_uid;
47         time_t debounce_ts;
48         int debounce_count;
49
50         CloakUser(Module* source)
51                 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER),
52                 ext("cloaked_host", ExtensionItem::EXT_USER, source), debounce_ts(0), debounce_count(0)
53         {
54         }
55
56         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
57         {
58                 LocalUser* user = IS_LOCAL(dest);
59
60                 /* For remote clients, we don't take any action, we just allow it.
61                  * The local server where they are will set their cloak instead.
62                  * This is fine, as we will receive it later.
63                  */
64                 if (!user)
65                 {
66                         dest->SetMode(this, adding);
67                         return MODEACTION_ALLOW;
68                 }
69
70                 if (user->uuid == debounce_uid && debounce_ts == ServerInstance->Time())
71                 {
72                         // prevent spamming using /mode user +x-x+x-x+x-x
73                         if (++debounce_count > 2)
74                                 return MODEACTION_DENY;
75                 }
76                 else
77                 {
78                         debounce_uid = user->uuid;
79                         debounce_count = 1;
80                         debounce_ts = ServerInstance->Time();
81                 }
82
83                 if (adding == user->IsModeSet(this))
84                         return MODEACTION_DENY;
85
86                 /* don't allow this user to spam modechanges */
87                 if (source == dest)
88                         user->CommandFloodPenalty += 5000;
89
90                 if (adding)
91                 {
92                         // assume this is more correct
93                         if (user->registered != REG_ALL && user->host != user->dhost)
94                                 return MODEACTION_DENY;
95
96                         std::string* cloak = ext.get(user);
97
98                         if (!cloak)
99                         {
100                                 /* Force creation of missing cloak */
101                                 creator->OnUserConnect(user);
102                                 cloak = ext.get(user);
103                         }
104                         if (cloak)
105                         {
106                                 user->ChangeDisplayedHost(*cloak);
107                                 user->SetMode(this, true);
108                                 return MODEACTION_ALLOW;
109                         }
110                         else
111                                 return MODEACTION_DENY;
112                 }
113                 else
114                 {
115                         /* User is removing the mode, so restore their real host
116                          * and make it match the displayed one.
117                          */
118                         user->SetMode(this, false);
119                         user->ChangeDisplayedHost(user->host.c_str());
120                         return MODEACTION_ALLOW;
121                 }
122         }
123 };
124
125 class CommandCloak : public Command
126 {
127  public:
128         CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
129         {
130                 flags_needed = 'o';
131                 syntax = "<host>";
132         }
133
134         CmdResult Handle(const std::vector<std::string> &parameters, User *user);
135 };
136
137 class ModuleCloaking : public Module
138 {
139  public:
140         CloakUser cu;
141         CloakMode mode;
142         CommandCloak ck;
143         std::string prefix;
144         std::string suffix;
145         std::string key;
146         dynamic_reference<HashProvider> Hash;
147
148         ModuleCloaking() : cu(this), mode(MODE_OPAQUE), ck(this), Hash(this, "hash/md5")
149         {
150         }
151
152         /** This function takes a domain name string and returns just the last two domain parts,
153          * or the last domain part if only two are available. Failing that it just returns what it was given.
154          *
155          * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
156          * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
157          * and if it is passed "localhost.localdomain" it will return ".localdomain".
158          *
159          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
160          */
161         std::string LastTwoDomainParts(const std::string &host)
162         {
163                 int dots = 0;
164                 std::string::size_type splitdot = host.length();
165
166                 for (std::string::size_type x = host.length() - 1; x; --x)
167                 {
168                         if (host[x] == '.')
169                         {
170                                 splitdot = x;
171                                 dots++;
172                         }
173                         if (dots >= 3)
174                                 break;
175                 }
176
177                 if (splitdot == host.length())
178                         return "";
179                 else
180                         return host.substr(splitdot);
181         }
182
183         /**
184          * 2.0-style cloaking function
185          * @param item The item to cloak (part of an IP or hostname)
186          * @param id A unique ID for this type of item (to make it unique if the item matches)
187          * @param len The length of the output. Maximum for MD5 is 16 characters.
188          */
189         std::string SegmentCloak(const std::string& item, char id, int len)
190         {
191                 std::string input;
192                 input.reserve(key.length() + 3 + item.length());
193                 input.append(1, id);
194                 input.append(key);
195                 input.append(1, '\0'); // null does not terminate a C++ string
196                 input.append(item);
197
198                 std::string rv = Hash->GenerateRaw(input).substr(0,len);
199                 for(int i=0; i < len; i++)
200                 {
201                         // this discards 3 bits per byte. We have an
202                         // overabundance of bits in the hash output, doesn't
203                         // matter which ones we are discarding.
204                         rv[i] = base32[rv[i] & 0x1F];
205                 }
206                 return rv;
207         }
208
209         std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
210         {
211                 std::string bindata;
212                 int hop1, hop2, hop3;
213                 int len1, len2;
214                 std::string rv;
215                 if (ip.sa.sa_family == AF_INET6)
216                 {
217                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
218                         hop1 = 8;
219                         hop2 = 6;
220                         hop3 = 4;
221                         len1 = 6;
222                         len2 = 4;
223                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
224                         //     6  4  4    9/6
225                         rv.reserve(prefix.length() + 26 + suffix.length());
226                 }
227                 else
228                 {
229                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
230                         hop1 = 3;
231                         hop2 = 0;
232                         hop3 = 2;
233                         len1 = len2 = 3;
234                         // pfx s1.s2. (xxx.xxx or s3) sfx
235                         rv.reserve(prefix.length() + 15 + suffix.length());
236                 }
237
238                 rv.append(prefix);
239                 rv.append(SegmentCloak(bindata, 10, len1));
240                 rv.append(1, '.');
241                 bindata.erase(hop1);
242                 rv.append(SegmentCloak(bindata, 11, len2));
243                 if (hop2)
244                 {
245                         rv.append(1, '.');
246                         bindata.erase(hop2);
247                         rv.append(SegmentCloak(bindata, 12, len2));
248                 }
249
250                 if (full)
251                 {
252                         rv.append(1, '.');
253                         bindata.erase(hop3);
254                         rv.append(SegmentCloak(bindata, 13, 6));
255                         rv.append(suffix);
256                 }
257                 else
258                 {
259                         if (ip.sa.sa_family == AF_INET6)
260                         {
261                                 rv.append(InspIRCd::Format(".%02x%02x.%02x%02x%s",
262                                         ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
263                                         ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], suffix.c_str()));
264                         }
265                         else
266                         {
267                                 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
268                                 rv.append(InspIRCd::Format(".%d.%d%s", ip4[1], ip4[0], suffix.c_str()));
269                         }
270                 }
271                 return rv;
272         }
273
274         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) CXX11_OVERRIDE
275         {
276                 LocalUser* lu = IS_LOCAL(user);
277                 if (!lu)
278                         return MOD_RES_PASSTHRU;
279
280                 OnUserConnect(lu);
281                 std::string* cloak = cu.ext.get(user);
282                 /* Check if they have a cloaked host, but are not using it */
283                 if (cloak && *cloak != user->dhost)
284                 {
285                         const std::string cloakMask = user->nick + "!" + user->ident + "@" + *cloak;
286                         if (InspIRCd::Match(cloakMask, mask))
287                                 return MOD_RES_DENY;
288                 }
289                 return MOD_RES_PASSTHRU;
290         }
291
292         void Prioritize() CXX11_OVERRIDE
293         {
294                 /* Needs to be after m_banexception etc. */
295                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
296         }
297
298         // this unsets umode +x on every host change. If we are actually doing a +x
299         // mode change, we will call SetMode back to true AFTER the host change is done.
300         void OnChangeHost(User* u, const std::string& host) CXX11_OVERRIDE
301         {
302                 if (u->IsModeSet(cu))
303                 {
304                         u->SetMode(cu, false);
305                         u->WriteCommand("MODE", "-" + ConvToStr(cu.GetModeChar()));
306                 }
307         }
308
309         Version GetVersion() CXX11_OVERRIDE
310         {
311                 std::string testcloak = "broken";
312                 if (Hash)
313                 {
314                         switch (mode)
315                         {
316                                 case MODE_HALF_CLOAK:
317                                         testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
318                                         break;
319                                 case MODE_OPAQUE:
320                                         testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
321                         }
322                 }
323                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
324         }
325
326         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
327         {
328                 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
329                 prefix = tag->getString("prefix");
330                 suffix = tag->getString("suffix", ".IP");
331
332                 std::string modestr = tag->getString("mode");
333                 if (modestr == "half")
334                         mode = MODE_HALF_CLOAK;
335                 else if (modestr == "full")
336                         mode = MODE_OPAQUE;
337                 else
338                         throw ModuleException("Bad value for <cloak:mode>; must be half or full");
339
340                 key = tag->getString("key");
341                 if (key.empty() || key == "secret")
342                         throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
343         }
344
345         std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
346         {
347                 std::string chost;
348
349                 irc::sockets::sockaddrs hostip;
350                 bool host_is_ip = irc::sockets::aptosa(host, ip.port(), hostip) && hostip == ip;
351
352                 switch (mode)
353                 {
354                         case MODE_HALF_CLOAK:
355                         {
356                                 if (!host_is_ip)
357                                         chost = prefix + SegmentCloak(host, 1, 6) + LastTwoDomainParts(host);
358                                 if (chost.empty() || chost.length() > 50)
359                                         chost = SegmentIP(ip, false);
360                                 break;
361                         }
362                         case MODE_OPAQUE:
363                         default:
364                                 chost = SegmentIP(ip, true);
365                 }
366                 return chost;
367         }
368
369         void OnUserConnect(LocalUser* dest) CXX11_OVERRIDE
370         {
371                 std::string* cloak = cu.ext.get(dest);
372                 if (cloak)
373                         return;
374
375                 cu.ext.set(dest, GenCloak(dest->client_sa, dest->GetIPString(), dest->host));
376         }
377 };
378
379 CmdResult CommandCloak::Handle(const std::vector<std::string> &parameters, User *user)
380 {
381         ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
382         irc::sockets::sockaddrs sa;
383         std::string cloak;
384
385         if (irc::sockets::aptosa(parameters[0], 0, sa))
386                 cloak = mod->GenCloak(sa, parameters[0], parameters[0]);
387         else
388                 cloak = mod->GenCloak(sa, "", parameters[0]);
389
390         user->WriteNotice("*** Cloak for " + parameters[0] + " is " + cloak);
391
392         return CMD_SUCCESS;
393 }
394
395 MODULE_INIT(ModuleCloaking)