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