]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
eab28db4a2482de5f49bfc73d28a776f42a56d39
[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
34         /** 2.0 cloak of IP hash, split at 2 common CIDR range points */
35         MODE_OPAQUE
36 };
37
38 // lowercase-only encoding similar to base64, used for hash output
39 static const char base32[] = "0123456789abcdefghijklmnopqrstuv";
40
41 // The minimum length of a cloak key.
42 static const size_t minkeylen = 30;
43
44 struct CloakInfo
45 {
46         // The method used for cloaking users.
47         CloakMode mode;
48
49         // The number of parts of the hostname shown when using half cloaking.
50         unsigned int domainparts;
51
52         // Whether to ignore the case of a hostname when cloaking it.
53         bool ignorecase;
54
55         // The secret used for generating cloaks.
56         std::string key;
57
58         // The prefix for cloaks (e.g. MyNet-).
59         std::string prefix;
60
61         // The suffix for IP cloaks (e.g. .IP).
62         std::string suffix;
63
64         CloakInfo(CloakMode Mode, const std::string& Key, const std::string& Prefix, const std::string& Suffix, bool IgnoreCase, unsigned int DomainParts = 0)
65                 : mode(Mode)
66                 , domainparts(DomainParts)
67                 , ignorecase(IgnoreCase)
68                 , key(Key)
69                 , prefix(Prefix)
70                 , suffix(Suffix)
71         {
72         }
73 };
74
75 typedef std::vector<std::string> CloakList;
76
77 /** Handles user mode +x
78  */
79 class CloakUser : public ModeHandler
80 {
81  public:
82         bool active;
83         SimpleExtItem<CloakList> ext;
84         std::string debounce_uid;
85         time_t debounce_ts;
86         int debounce_count;
87
88         CloakUser(Module* source)
89                 : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER)
90                 , active(false)
91                 , ext("cloaked_host", ExtensionItem::EXT_USER, source)
92                 , debounce_ts(0)
93                 , debounce_count(0)
94         {
95         }
96
97         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding) CXX11_OVERRIDE
98         {
99                 LocalUser* user = IS_LOCAL(dest);
100
101                 /* For remote clients, we don't take any action, we just allow it.
102                  * The local server where they are will set their cloak instead.
103                  * This is fine, as we will receive it later.
104                  */
105                 if (!user)
106                 {
107                         // Remote setters broadcast mode before host while local setters do the opposite, so this takes that into account
108                         active = IS_LOCAL(source) ? adding : !adding;
109                         dest->SetMode(this, adding);
110                         return MODEACTION_ALLOW;
111                 }
112
113                 if (user->uuid == debounce_uid && debounce_ts == ServerInstance->Time())
114                 {
115                         // prevent spamming using /mode user +x-x+x-x+x-x
116                         if (++debounce_count > 2)
117                                 return MODEACTION_DENY;
118                 }
119                 else
120                 {
121                         debounce_uid = user->uuid;
122                         debounce_count = 1;
123                         debounce_ts = ServerInstance->Time();
124                 }
125
126                 if (adding == user->IsModeSet(this))
127                         return MODEACTION_DENY;
128
129                 /* don't allow this user to spam modechanges */
130                 if (source == dest)
131                         user->CommandFloodPenalty += 5000;
132
133                 if (adding)
134                 {
135                         // assume this is more correct
136                         if (user->registered != REG_ALL && user->GetRealHost() != user->GetDisplayedHost())
137                                 return MODEACTION_DENY;
138
139                         CloakList* cloaks = ext.get(user);
140                         if (!cloaks)
141                         {
142                                 /* Force creation of missing cloak */
143                                 creator->OnUserConnect(user);
144                                 cloaks = ext.get(user);
145                         }
146
147                         // If we have a cloak then set the hostname.
148                         if (cloaks && !cloaks->empty())
149                         {
150                                 user->ChangeDisplayedHost(cloaks->front());
151                                 user->SetMode(this, true);
152                                 return MODEACTION_ALLOW;
153                         }
154                         else
155                                 return MODEACTION_DENY;
156                 }
157                 else
158                 {
159                         /* User is removing the mode, so restore their real host
160                          * and make it match the displayed one.
161                          */
162                         user->SetMode(this, false);
163                         user->ChangeDisplayedHost(user->GetRealHost().c_str());
164                         return MODEACTION_ALLOW;
165                 }
166         }
167 };
168
169 class CommandCloak : public Command
170 {
171  public:
172         CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
173         {
174                 flags_needed = 'o';
175                 syntax = "<host>";
176         }
177
178         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE;
179 };
180
181 class ModuleCloaking : public Module
182 {
183  public:
184         CloakUser cu;
185         CommandCloak ck;
186         std::vector<CloakInfo> cloaks;
187         dynamic_reference<HashProvider> Hash;
188
189         ModuleCloaking()
190                 : cu(this)
191                 , ck(this)
192                 , Hash(this, "hash/md5")
193         {
194         }
195
196         /** Takes a domain name and retrieves the subdomain which should be visible.
197          * This is usually the last \p domainparts labels but if not enough are
198          * present then all but the most specific label are used. If the domain name
199          * consists of one label only then none are used.
200          *
201          * Here are some examples for how domain names will be shortened assuming
202          * \p domainparts is set to the default of 3.
203          *
204          *   "this.is.an.example.com"  =>  ".an.example.com"
205          *   "an.example.com"          =>  ".example.com"
206          *   "example.com"             =>  ".com"
207          *   "localhost"               =>  ""
208          *
209          * @param host The hostname to cloak.
210          * @param domainparts The number of domain labels that should be visible.
211          * @return The visible segment of the hostname.
212          */
213         std::string VisibleDomainParts(const std::string& host, unsigned int domainparts)
214         {
215                 // The position at which we found the last dot.
216                 std::string::const_reverse_iterator dotpos;
217
218                 // The number of dots we have seen so far.
219                 unsigned int seendots = 0;
220
221                 for (std::string::const_reverse_iterator iter = host.rbegin(); iter != host.rend(); ++iter)
222                 {
223                         if (*iter != '.')
224                                 continue;
225
226                         // We have found a dot!
227                         dotpos = iter;
228                         seendots += 1;
229
230                         // Do we have enough segments to stop?
231                         if (seendots >= domainparts)
232                                 break;
233                 }
234
235                 // We only returns a domain part if more than one label is
236                 // present. See above for a full explanation.
237                 if (!seendots)
238                         return "";
239                 return std::string(dotpos.base() - 1, host.end());
240         }
241
242         /**
243          * 2.0-style cloaking function
244          * @param item The item to cloak (part of an IP or hostname)
245          * @param id A unique ID for this type of item (to make it unique if the item matches)
246          * @param len The length of the output. Maximum for MD5 is 16 characters.
247          */
248         std::string SegmentCloak(const CloakInfo& info, const std::string& item, char id, size_t len)
249         {
250                 std::string input;
251                 input.reserve(info.key.length() + 3 + item.length());
252                 input.append(1, id);
253                 input.append(info.key);
254                 input.append(1, '\0'); // null does not terminate a C++ string
255                 if (info.ignorecase)
256                         std::transform(item.begin(), item.end(), std::back_inserter(input), ::tolower);
257                 else
258                         input.append(item);
259
260                 std::string rv = Hash->GenerateRaw(input).substr(0,len);
261                 for(size_t i = 0; i < len; i++)
262                 {
263                         // this discards 3 bits per byte. We have an
264                         // overabundance of bits in the hash output, doesn't
265                         // matter which ones we are discarding.
266                         rv[i] = base32[rv[i] & 0x1F];
267                 }
268                 return rv;
269         }
270
271         std::string SegmentIP(const CloakInfo& info, const irc::sockets::sockaddrs& ip, bool full)
272         {
273                 std::string bindata;
274                 size_t hop1, hop2, hop3;
275                 size_t len1, len2;
276                 std::string rv;
277                 if (ip.family() == AF_INET6)
278                 {
279                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
280                         hop1 = 8;
281                         hop2 = 6;
282                         hop3 = 4;
283                         len1 = 6;
284                         len2 = 4;
285                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
286                         //     6  4  4    9/6
287                         rv.reserve(info.prefix.length() + 26 + info.suffix.length());
288                 }
289                 else
290                 {
291                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
292                         hop1 = 3;
293                         hop2 = 0;
294                         hop3 = 2;
295                         len1 = len2 = 3;
296                         // pfx s1.s2. (xxx.xxx or s3) sfx
297                         rv.reserve(info.prefix.length() + 15 + info.suffix.length());
298                 }
299
300                 rv.append(info.prefix);
301                 rv.append(SegmentCloak(info, bindata, 10, len1));
302                 rv.append(1, '.');
303                 bindata.erase(hop1);
304                 rv.append(SegmentCloak(info, bindata, 11, len2));
305                 if (hop2)
306                 {
307                         rv.append(1, '.');
308                         bindata.erase(hop2);
309                         rv.append(SegmentCloak(info, bindata, 12, len2));
310                 }
311
312                 if (full)
313                 {
314                         rv.append(1, '.');
315                         bindata.erase(hop3);
316                         rv.append(SegmentCloak(info, bindata, 13, 6));
317                         rv.append(info.suffix);
318                 }
319                 else
320                 {
321                         if (ip.family() == AF_INET6)
322                         {
323                                 rv.append(InspIRCd::Format(".%02x%02x.%02x%02x%s",
324                                         ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
325                                         ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], info.suffix.c_str()));
326                         }
327                         else
328                         {
329                                 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
330                                 rv.append(InspIRCd::Format(".%d.%d%s", ip4[1], ip4[0], info.suffix.c_str()));
331                         }
332                 }
333                 return rv;
334         }
335
336         ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) CXX11_OVERRIDE
337         {
338                 LocalUser* lu = IS_LOCAL(user);
339                 if (!lu)
340                         return MOD_RES_PASSTHRU;
341
342                 // Force the creation of cloaks if not already set.
343                 OnUserConnect(lu);
344
345                 // If the user has no cloaks (i.e. UNIX socket) then we do nothing here.
346                 CloakList* cloaklist = cu.ext.get(user);
347                 if (!cloaklist || cloaklist->empty())
348                         return MOD_RES_PASSTHRU;
349
350                 // Check if they have a cloaked host but are not using it.
351                 for (CloakList::const_iterator iter = cloaklist->begin(); iter != cloaklist->end(); ++iter)
352                 {
353                         const std::string& cloak = *iter;
354                         if (cloak != user->GetDisplayedHost())
355                         {
356                                 const std::string cloakMask = user->nick + "!" + user->ident + "@" + cloak;
357                                 if (InspIRCd::Match(cloakMask, mask))
358                                         return MOD_RES_DENY;
359                         }
360                 }
361                 return MOD_RES_PASSTHRU;
362         }
363
364         void Prioritize() CXX11_OVERRIDE
365         {
366                 /* Needs to be after m_banexception etc. */
367                 ServerInstance->Modules->SetPriority(this, I_OnCheckBan, PRIORITY_LAST);
368         }
369
370         // this unsets umode +x on every host change. If we are actually doing a +x
371         // mode change, we will call SetMode back to true AFTER the host change is done.
372         void OnChangeHost(User* u, const std::string& host) CXX11_OVERRIDE
373         {
374                 if (u->IsModeSet(cu) && !cu.active)
375                 {
376                         u->SetMode(cu, false);
377
378                         LocalUser* luser = IS_LOCAL(u);
379                         if (!luser)
380                                 return;
381
382                         Modes::ChangeList modechangelist;
383                         modechangelist.push_remove(&cu);
384                         ClientProtocol::Events::Mode modeevent(ServerInstance->FakeClient, NULL, u, modechangelist);
385                         luser->Send(modeevent);
386                 }
387                 cu.active = false;
388         }
389
390         Version GetVersion() CXX11_OVERRIDE
391         {
392                 std::string testcloak = "broken";
393                 if (Hash && !cloaks.empty())
394                 {
395                         const CloakInfo& info = cloaks.front();
396                         switch (info.mode)
397                         {
398                                 case MODE_HALF_CLOAK:
399                                         // Use old cloaking verification to stay compatible with 2.0
400                                         // But verify domainparts and ignorecase when use 3.0-only features
401                                         if (info.domainparts == 3 && !info.ignorecase)
402                                                 testcloak = info.prefix + SegmentCloak(info, "*", 3, 8) + info.suffix;
403                                         else
404                                         {
405                                                 irc::sockets::sockaddrs sa;
406                                                 testcloak = GenCloak(info, sa, "", testcloak + ConvToStr(info.domainparts)) + (info.ignorecase ? "-ci" : "");
407                                         }
408                                         break;
409                                 case MODE_OPAQUE:
410                                         testcloak = info.prefix + SegmentCloak(info, "*", 4, 8) + info.suffix + (info.ignorecase ? "-ci" : "");
411                         }
412                 }
413                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
414         }
415
416         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
417         {
418                 ConfigTagList tags = ServerInstance->Config->ConfTags("cloak");
419                 if (tags.first == tags.second)
420                         throw ModuleException("You have loaded the cloaking module but not configured any <cloak> tags!");
421
422                 std::vector<CloakInfo> newcloaks;
423                 for (ConfigIter i = tags.first; i != tags.second; ++i)
424                 {
425                         ConfigTag* tag = i->second;
426
427                         // Ensure that we have the <cloak:key> parameter.
428                         const std::string key = tag->getString("key");
429                         if (key.empty())
430                                 throw ModuleException("You have not defined a cloaking key. Define <cloak:key> as a " + ConvToStr(minkeylen) + "+ character network-wide secret, at " + tag->getTagLocation());
431
432                         // If we are the first cloak method then mandate a strong key.
433                         if (i == tags.first && key.length() < minkeylen)
434                                 throw ModuleException("Your cloaking key is not secure. It should be at least " + ConvToStr(minkeylen) + " characters long, at " + tag->getTagLocation());
435
436                         const bool ignorecase = tag->getBool("ignorecase");
437                         const std::string mode = tag->getString("mode");
438                         const std::string prefix = tag->getString("prefix");
439                         const std::string suffix = tag->getString("suffix", ".IP");
440                         if (stdalgo::string::equalsci(mode, "half"))
441                         {
442                                 unsigned int domainparts = tag->getUInt("domainparts", 3, 1, 10);
443                                 newcloaks.push_back(CloakInfo(MODE_HALF_CLOAK, key, prefix, suffix, ignorecase, domainparts));
444                         }
445                         else if (stdalgo::string::equalsci(mode, "full"))
446                                 newcloaks.push_back(CloakInfo(MODE_OPAQUE, key, prefix, suffix, ignorecase));
447                         else
448                                 throw ModuleException(mode + " is an invalid value for <cloak:mode>; acceptable values are 'half' and 'full', at " + tag->getTagLocation());
449                 }
450
451                 // The cloak configuration was valid so we can apply it.
452                 cloaks.swap(newcloaks);
453         }
454
455         std::string GenCloak(const CloakInfo& info, const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
456         {
457                 std::string chost;
458
459                 irc::sockets::sockaddrs hostip;
460                 bool host_is_ip = irc::sockets::aptosa(host, ip.port(), hostip) && hostip == ip;
461
462                 switch (info.mode)
463                 {
464                         case MODE_HALF_CLOAK:
465                         {
466                                 if (!host_is_ip)
467                                         chost = info.prefix + SegmentCloak(info, host, 1, 6) + VisibleDomainParts(host, info.domainparts);
468                                 if (chost.empty() || chost.length() > 50)
469                                         chost = SegmentIP(info, ip, false);
470                                 break;
471                         }
472                         case MODE_OPAQUE:
473                         default:
474                                 chost = SegmentIP(info, ip, true);
475                 }
476                 return chost;
477         }
478
479         void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
480         {
481                 // Connecting users are handled in OnUserConnect not here.
482                 if (user->registered != REG_ALL)
483                         return;
484
485                 // Remove the cloaks and generate new ones.
486                 cu.ext.unset(user);
487                 OnUserConnect(user);
488
489                 // If a user is using a cloak then update it.
490                 if (user->IsModeSet(cu))
491                 {
492                         CloakList* cloaklist = cu.ext.get(user);
493                         user->ChangeDisplayedHost(cloaklist->front());
494                 }
495         }
496
497         void OnUserConnect(LocalUser* dest) CXX11_OVERRIDE
498         {
499                 if (cu.ext.get(dest))
500                         return;
501
502                 // TODO: decide how we are going to cloak AF_UNIX hostnames.
503                 if (dest->client_sa.family() != AF_INET && dest->client_sa.family() != AF_INET6)
504                         return;
505
506                 CloakList cloaklist;
507                 for (std::vector<CloakInfo>::const_iterator iter = cloaks.begin(); iter != cloaks.end(); ++iter)
508                         cloaklist.push_back(GenCloak(*iter, dest->client_sa, dest->GetIPString(), dest->GetRealHost()));
509                 cu.ext.set(dest, cloaklist);
510         }
511 };
512
513 CmdResult CommandCloak::Handle(User* user, const Params& parameters)
514 {
515         ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
516
517         // If we're cloaking an IP address we pass it in the IP field too.
518         irc::sockets::sockaddrs sa;
519         const char* ipaddr = irc::sockets::aptosa(parameters[0], 0, sa) ? parameters[0].c_str() : "";
520
521         unsigned int id = 0;
522         for (std::vector<CloakInfo>::const_iterator iter = mod->cloaks.begin(); iter != mod->cloaks.end(); ++iter)
523         {
524                 const std::string cloak = mod->GenCloak(*iter, sa, ipaddr, parameters[0]);
525                 user->WriteNotice(InspIRCd::Format("*** Cloak #%u for %s is %s", ++id, parameters[0].c_str(), cloak.c_str()));
526         }
527         return CMD_SUCCESS;
528 }
529
530 MODULE_INIT(ModuleCloaking)