]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cloaking.cpp
Remove $Core and $Mod* comments apart from $ModDep.
[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", 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                         std::string* cloak = ext.get(user);
93
94                         if (!cloak)
95                         {
96                                 /* Force creation of missing cloak */
97                                 creator->OnUserConnect(user);
98                                 cloak = ext.get(user);
99                         }
100                         if (cloak)
101                         {
102                                 user->ChangeDisplayedHost(cloak->c_str());
103                                 user->SetMode(this, true);
104                                 return MODEACTION_ALLOW;
105                         }
106                         else
107                                 return MODEACTION_DENY;
108                 }
109                 else
110                 {
111                         /* User is removing the mode, so restore their real host
112                          * and make it match the displayed one.
113                          */
114                         user->SetMode(this, false);
115                         user->ChangeDisplayedHost(user->host.c_str());
116                         return MODEACTION_ALLOW;
117                 }
118         }
119 };
120
121 class CommandCloak : public Command
122 {
123  public:
124         CommandCloak(Module* Creator) : Command(Creator, "CLOAK", 1)
125         {
126                 flags_needed = 'o';
127                 syntax = "<host>";
128         }
129
130         CmdResult Handle(const std::vector<std::string> &parameters, User *user);
131 };
132
133 class ModuleCloaking : public Module
134 {
135  public:
136         CloakUser cu;
137         CloakMode mode;
138         CommandCloak ck;
139         std::string prefix;
140         std::string suffix;
141         std::string key;
142         const char* xtab[4];
143         dynamic_reference<HashProvider> Hash;
144
145         ModuleCloaking() : cu(this), mode(MODE_OPAQUE), ck(this), Hash(this, "hash/md5")
146         {
147         }
148
149         void init() CXX11_OVERRIDE
150         {
151                 OnRehash(NULL);
152
153                 ServerInstance->Modules->AddService(cu);
154                 ServerInstance->Modules->AddService(ck);
155                 ServerInstance->Modules->AddService(cu.ext);
156
157                 Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect, I_OnChangeHost };
158                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
159         }
160
161         /** This function takes a domain name string and returns just the last two domain parts,
162          * or the last domain part if only two are available. Failing that it just returns what it was given.
163          *
164          * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org".
165          * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk",
166          * and if it is passed "localhost.localdomain" it will return ".localdomain".
167          *
168          * This is used to ensure a significant part of the host is always cloaked (see Bug #216)
169          */
170         std::string LastTwoDomainParts(const std::string &host)
171         {
172                 int dots = 0;
173                 std::string::size_type splitdot = host.length();
174
175                 for (std::string::size_type x = host.length() - 1; x; --x)
176                 {
177                         if (host[x] == '.')
178                         {
179                                 splitdot = x;
180                                 dots++;
181                         }
182                         if (dots >= 3)
183                                 break;
184                 }
185
186                 if (splitdot == host.length())
187                         return "";
188                 else
189                         return host.substr(splitdot);
190         }
191
192         /**
193          * 2.0-style cloaking function
194          * @param item The item to cloak (part of an IP or hostname)
195          * @param id A unique ID for this type of item (to make it unique if the item matches)
196          * @param len The length of the output. Maximum for MD5 is 16 characters.
197          */
198         std::string SegmentCloak(const std::string& item, char id, int len)
199         {
200                 std::string input;
201                 input.reserve(key.length() + 3 + item.length());
202                 input.append(1, id);
203                 input.append(key);
204                 input.append(1, '\0'); // null does not terminate a C++ string
205                 input.append(item);
206
207                 std::string rv = Hash->sum(input).substr(0,len);
208                 for(int i=0; i < len; i++)
209                 {
210                         // this discards 3 bits per byte. We have an
211                         // overabundance of bits in the hash output, doesn't
212                         // matter which ones we are discarding.
213                         rv[i] = base32[rv[i] & 0x1F];
214                 }
215                 return rv;
216         }
217
218         std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full)
219         {
220                 std::string bindata;
221                 int hop1, hop2, hop3;
222                 int len1, len2;
223                 std::string rv;
224                 if (ip.sa.sa_family == AF_INET6)
225                 {
226                         bindata = std::string((const char*)ip.in6.sin6_addr.s6_addr, 16);
227                         hop1 = 8;
228                         hop2 = 6;
229                         hop3 = 4;
230                         len1 = 6;
231                         len2 = 4;
232                         // pfx s1.s2.s3. (xxxx.xxxx or s4) sfx
233                         //     6  4  4    9/6
234                         rv.reserve(prefix.length() + 26 + suffix.length());
235                 }
236                 else
237                 {
238                         bindata = std::string((const char*)&ip.in4.sin_addr, 4);
239                         hop1 = 3;
240                         hop2 = 0;
241                         hop3 = 2;
242                         len1 = len2 = 3;
243                         // pfx s1.s2. (xxx.xxx or s3) sfx
244                         rv.reserve(prefix.length() + 15 + suffix.length());
245                 }
246
247                 rv.append(prefix);
248                 rv.append(SegmentCloak(bindata, 10, len1));
249                 rv.append(1, '.');
250                 bindata.erase(hop1);
251                 rv.append(SegmentCloak(bindata, 11, len2));
252                 if (hop2)
253                 {
254                         rv.append(1, '.');
255                         bindata.erase(hop2);
256                         rv.append(SegmentCloak(bindata, 12, len2));
257                 }
258
259                 if (full)
260                 {
261                         rv.append(1, '.');
262                         bindata.erase(hop3);
263                         rv.append(SegmentCloak(bindata, 13, 6));
264                         rv.append(suffix);
265                 }
266                 else
267                 {
268                         char buf[50];
269                         if (ip.sa.sa_family == AF_INET6)
270                         {
271                                 snprintf(buf, 50, ".%02x%02x.%02x%02x%s",
272                                         ip.in6.sin6_addr.s6_addr[2], ip.in6.sin6_addr.s6_addr[3],
273                                         ip.in6.sin6_addr.s6_addr[0], ip.in6.sin6_addr.s6_addr[1], suffix.c_str());
274                         }
275                         else
276                         {
277                                 const unsigned char* ip4 = (const unsigned char*)&ip.in4.sin_addr;
278                                 snprintf(buf, 50, ".%d.%d%s", ip4[1], ip4[0], suffix.c_str());
279                         }
280                         rv.append(buf);
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->dhost)
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()
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))
314                 {
315                         u->SetMode(cu, false);
316                         u->WriteServ("MODE %s -%c", u->nick.c_str(), cu.GetModeChar());
317                 }
318         }
319
320         Version GetVersion() CXX11_OVERRIDE
321         {
322                 std::string testcloak = "broken";
323                 if (Hash)
324                 {
325                         switch (mode)
326                         {
327                                 case MODE_HALF_CLOAK:
328                                         testcloak = prefix + SegmentCloak("*", 3, 8) + suffix;
329                                         break;
330                                 case MODE_OPAQUE:
331                                         testcloak = prefix + SegmentCloak("*", 4, 8) + suffix;
332                         }
333                 }
334                 return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak);
335         }
336
337         void OnRehash(User* user) CXX11_OVERRIDE
338         {
339                 ConfigTag* tag = ServerInstance->Config->ConfValue("cloak");
340                 prefix = tag->getString("prefix");
341                 suffix = tag->getString("suffix", ".IP");
342
343                 std::string modestr = tag->getString("mode");
344                 if (modestr == "half")
345                         mode = MODE_HALF_CLOAK;
346                 else if (modestr == "full")
347                         mode = MODE_OPAQUE;
348                 else
349                         throw ModuleException("Bad value for <cloak:mode>; must be half or full");
350
351                 key = tag->getString("key");
352                 if (key.empty() || key == "secret")
353                         throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret.");
354         }
355
356         std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host)
357         {
358                 std::string chost;
359
360                 switch (mode)
361                 {
362                         case MODE_HALF_CLOAK:
363                         {
364                                 if (ipstr != host)
365                                         chost = prefix + SegmentCloak(host, 1, 6) + LastTwoDomainParts(host);
366                                 if (chost.empty() || chost.length() > 50)
367                                         chost = SegmentIP(ip, false);
368                                 break;
369                         }
370                         case MODE_OPAQUE:
371                         default:
372                                 chost = SegmentIP(ip, true);
373                 }
374                 return chost;
375         }
376
377         void OnUserConnect(LocalUser* dest) CXX11_OVERRIDE
378         {
379                 std::string* cloak = cu.ext.get(dest);
380                 if (cloak)
381                         return;
382
383                 cu.ext.set(dest, GenCloak(dest->client_sa, dest->GetIPString(), dest->host));
384         }
385 };
386
387 CmdResult CommandCloak::Handle(const std::vector<std::string> &parameters, User *user)
388 {
389         ModuleCloaking* mod = (ModuleCloaking*)(Module*)creator;
390         irc::sockets::sockaddrs sa;
391         std::string cloak;
392
393         if (irc::sockets::aptosa(parameters[0], 0, sa))
394                 cloak = mod->GenCloak(sa, parameters[0], parameters[0]);
395         else
396                 cloak = mod->GenCloak(sa, "", parameters[0]);
397
398         user->WriteNotice("*** Cloak for " + parameters[0] + " is " + cloak);
399
400         return CMD_SUCCESS;
401 }
402
403 MODULE_INIT(ModuleCloaking)