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