]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
f8bbb1a04c6609ccef3791fec4a27133fbe2275f
[user/henk/code/inspircd.git] / src / modules / m_dnsbl.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2018-2020 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2018-2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6  *   Copyright (C) 2013, 2016-2020 Sadie Powell <sadie@witchery.services>
7  *   Copyright (C) 2013, 2015-2016 Adam <Adam@anope.org>
8  *   Copyright (C) 2012-2016 Attila Molnar <attilamolnar@hush.com>
9  *   Copyright (C) 2012, 2018 Robby <robby@chatbelgie.be>
10  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
11  *   Copyright (C) 2007, 2010 Craig Edwards <brain@inspircd.org>
12  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13  *   Copyright (C) 2006-2009 Robin Burchell <robin+git@viroteck.net>
14  *
15  * This file is part of InspIRCd.  InspIRCd is free software: you can
16  * redistribute it and/or modify it under the terms of the GNU General Public
17  * License as published by the Free Software Foundation, version 2.
18  *
19  * This program is distributed in the hope that it will be useful, but WITHOUT
20  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  */
27
28
29 #include "inspircd.h"
30 #include "xline.h"
31 #include "modules/dns.h"
32 #include "modules/stats.h"
33
34 /* Class holding data for a single entry */
35 class DNSBLConfEntry : public refcountbase
36 {
37         public:
38                 enum EnumBanaction { I_UNKNOWN, I_KILL, I_ZLINE, I_KLINE, I_GLINE, I_MARK };
39                 enum EnumType { A_RECORD, A_BITMASK };
40                 std::string name, ident, host, domain, reason;
41                 EnumBanaction banaction;
42                 EnumType type;
43                 unsigned long duration;
44                 unsigned int bitmask;
45                 unsigned char records[256];
46                 unsigned long stats_hits, stats_misses;
47                 DNSBLConfEntry(): type(A_BITMASK),duration(86400),bitmask(0),stats_hits(0), stats_misses(0) {}
48 };
49
50
51 /** Resolver for CGI:IRC hostnames encoded in ident/real name
52  */
53 class DNSBLResolver : public DNS::Request
54 {
55  private:
56         irc::sockets::sockaddrs theirsa;
57         std::string theiruid;
58         LocalStringExt& nameExt;
59         LocalIntExt& countExt;
60         reference<DNSBLConfEntry> ConfEntry;
61
62  public:
63         DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf)
64                 : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true)
65                 , theirsa(u->client_sa)
66                 , theiruid(u->uuid)
67                 , nameExt(match)
68                 , countExt(ctr)
69                 , ConfEntry(conf)
70         {
71         }
72
73         /* Note: This may be called multiple times for multiple A record results */
74         void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
75         {
76                 /* Check the user still exists */
77                 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
78                 if (!them || them->client_sa != theirsa)
79                         return;
80
81                 int i = countExt.get(them);
82                 if (i)
83                         countExt.set(them, i - 1);
84
85                 // The DNSBL reply must contain an A result.
86                 const DNS::ResourceRecord* const ans_record = r->FindAnswerOfType(DNS::QUERY_A);
87                 if (!ans_record)
88                 {
89                         ConfEntry->stats_misses++;
90                         ServerInstance->SNO->WriteGlobalSno('d', "%s returned an result with no IPv4 address.",
91                                 ConfEntry->name.c_str());
92                         return;
93                 }
94
95                 // The DNSBL reply must be a valid IPv4 address.
96                 in_addr resultip;
97                 if (inet_pton(AF_INET, ans_record->rdata.c_str(), &resultip) != 1)
98                 {
99                         ConfEntry->stats_misses++;
100                         ServerInstance->SNO->WriteGlobalSno('d', "%s returned an invalid IPv4 address: %s",
101                                 ConfEntry->name.c_str(), ans_record->rdata.c_str());
102                         return;
103                 }
104
105                 // The DNSBL reply should be in the 127.0.0.0/8 range.
106                 if ((resultip.s_addr & 0xFF) != 127)
107                 {
108                         ConfEntry->stats_misses++;
109                         ServerInstance->SNO->WriteGlobalSno('d', "%s returned an IPv4 address which is outside of the 127.0.0.0/8 subnet: %s",
110                                 ConfEntry->name.c_str(), ans_record->rdata.c_str());
111                         return;
112                 }
113
114                 bool match = false;
115                 unsigned int result = 0;
116                 switch (ConfEntry->type)
117                 {
118                         case DNSBLConfEntry::A_BITMASK:
119                         {
120                                 result = (resultip.s_addr >> 24) & ConfEntry->bitmask;
121                                 match = (result != 0);
122                                 break;
123                         }
124                         case DNSBLConfEntry::A_RECORD:
125                         {
126                                 result = resultip.s_addr >> 24;
127                                 match = (ConfEntry->records[result] == 1);
128                                 break;
129                         }
130                 }
131
132                 if (match)
133                 {
134                         std::string reason = ConfEntry->reason;
135                         std::string::size_type x = reason.find("%ip%");
136                         while (x != std::string::npos)
137                         {
138                                 reason.erase(x, 4);
139                                 reason.insert(x, them->GetIPString());
140                                 x = reason.find("%ip%");
141                         }
142
143                         ConfEntry->stats_hits++;
144
145                         switch (ConfEntry->banaction)
146                         {
147                                 case DNSBLConfEntry::I_KILL:
148                                 {
149                                         ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
150                                         break;
151                                 }
152                                 case DNSBLConfEntry::I_MARK:
153                                 {
154                                         if (!ConfEntry->ident.empty())
155                                         {
156                                                 them->WriteNotice("Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
157                                                 them->ChangeIdent(ConfEntry->ident);
158                                         }
159
160                                         if (!ConfEntry->host.empty())
161                                         {
162                                                 them->WriteNotice("Your host has been set to " + ConfEntry->host + " because you matched " + reason);
163                                                 them->ChangeDisplayedHost(ConfEntry->host);
164                                         }
165
166                                         nameExt.set(them, ConfEntry->name);
167                                         break;
168                                 }
169                                 case DNSBLConfEntry::I_KLINE:
170                                 {
171                                         KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
172                                                         "*", them->GetIPString());
173                                         if (ServerInstance->XLines->AddLine(kl,NULL))
174                                         {
175                                                 ServerInstance->SNO->WriteToSnoMask('x', "K-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
176                                                         them->GetIPString().c_str(), InspIRCd::DurationString(kl->duration).c_str(),
177                                                         InspIRCd::TimeString(kl->expiry).c_str(), reason.c_str());
178                                                 ServerInstance->XLines->ApplyLines();
179                                         }
180                                         else
181                                         {
182                                                 delete kl;
183                                                 return;
184                                         }
185                                         break;
186                                 }
187                                 case DNSBLConfEntry::I_GLINE:
188                                 {
189                                         GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
190                                                         "*", them->GetIPString());
191                                         if (ServerInstance->XLines->AddLine(gl,NULL))
192                                         {
193                                                 ServerInstance->SNO->WriteToSnoMask('x', "G-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
194                                                         them->GetIPString().c_str(), InspIRCd::DurationString(gl->duration).c_str(),
195                                                         InspIRCd::TimeString(gl->expiry).c_str(), reason.c_str());
196                                                 ServerInstance->XLines->ApplyLines();
197                                         }
198                                         else
199                                         {
200                                                 delete gl;
201                                                 return;
202                                         }
203                                         break;
204                                 }
205                                 case DNSBLConfEntry::I_ZLINE:
206                                 {
207                                         ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
208                                                         them->GetIPString());
209                                         if (ServerInstance->XLines->AddLine(zl,NULL))
210                                         {
211                                                 ServerInstance->SNO->WriteToSnoMask('x', "Z-line added due to DNSBL match on %s to expire in %s (on %s): %s",
212                                                         them->GetIPString().c_str(), InspIRCd::DurationString(zl->duration).c_str(),
213                                                         InspIRCd::TimeString(zl->expiry).c_str(), reason.c_str());
214                                                 ServerInstance->XLines->ApplyLines();
215                                         }
216                                         else
217                                         {
218                                                 delete zl;
219                                                 return;
220                                         }
221                                         break;
222                                 }
223                                 case DNSBLConfEntry::I_UNKNOWN:
224                                 default:
225                                         break;
226                         }
227
228                         ServerInstance->SNO->WriteGlobalSno('d', "Connecting user %s (%s) detected as being on the '%s' DNS blacklist with result %d",
229                                 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), result);
230                 }
231                 else
232                         ConfEntry->stats_misses++;
233         }
234
235         void OnError(const DNS::Query *q) CXX11_OVERRIDE
236         {
237                 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
238                 if (!them || them->client_sa != theirsa)
239                         return;
240
241                 int i = countExt.get(them);
242                 if (i)
243                         countExt.set(them, i - 1);
244
245                 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
246                 {
247                         ConfEntry->stats_misses++;
248                         return;
249                 }
250
251                 ServerInstance->SNO->WriteGlobalSno('d', "An error occurred whilst checking whether %s (%s) is on the '%s' DNS blacklist: %s",
252                         them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), this->manager->GetErrorStr(q->error).c_str());
253         }
254 };
255
256 typedef std::vector<reference<DNSBLConfEntry> > DNSBLConfList;
257
258 class ModuleDNSBL : public Module, public Stats::EventListener
259 {
260         DNSBLConfList DNSBLConfEntries;
261         dynamic_reference<DNS::Manager> DNS;
262         LocalStringExt nameExt;
263         LocalIntExt countExt;
264
265         /*
266          *      Convert a string to EnumBanaction
267          */
268         DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
269         {
270                 if (stdalgo::string::equalsci(action, "kill"))
271                         return DNSBLConfEntry::I_KILL;
272                 if (stdalgo::string::equalsci(action, "kline"))
273                         return DNSBLConfEntry::I_KLINE;
274                 if (stdalgo::string::equalsci(action, "zline"))
275                         return DNSBLConfEntry::I_ZLINE;
276                 if (stdalgo::string::equalsci(action, "gline"))
277                         return DNSBLConfEntry::I_GLINE;
278                 if (stdalgo::string::equalsci(action, "mark"))
279                         return DNSBLConfEntry::I_MARK;
280                 return DNSBLConfEntry::I_UNKNOWN;
281         }
282  public:
283         ModuleDNSBL()
284                 : Stats::EventListener(this)
285                 , DNS(this, "DNS")
286                 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
287                 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
288         {
289         }
290
291         void init() CXX11_OVERRIDE
292         {
293                 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
294         }
295
296         void Prioritize() CXX11_OVERRIDE
297         {
298                 Module* corexline = ServerInstance->Modules->Find("core_xline");
299                 ServerInstance->Modules->SetPriority(this, I_OnSetUserIP, PRIORITY_AFTER, corexline);
300         }
301
302         Version GetVersion() CXX11_OVERRIDE
303         {
304                 return Version("Allows the server administrator to check the IP address of connecting users against a DNSBL.", VF_VENDOR);
305         }
306
307         /** Fill our conf vector with data
308          */
309         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
310         {
311                 DNSBLConfList newentries;
312
313                 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
314                 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
315                 {
316                         ConfigTag* tag = i->second;
317                         reference<DNSBLConfEntry> e = new DNSBLConfEntry();
318
319                         e->name = tag->getString("name");
320                         e->ident = tag->getString("ident");
321                         e->host = tag->getString("host");
322                         e->reason = tag->getString("reason", "Your IP has been blacklisted.", 1);
323                         e->domain = tag->getString("domain");
324
325                         if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
326                         {
327                                 e->type = DNSBLConfEntry::A_BITMASK;
328                                 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
329                         }
330                         else
331                         {
332                                 memset(e->records, 0, sizeof(e->records));
333                                 e->type = DNSBLConfEntry::A_RECORD;
334                                 irc::portparser portrange(tag->getString("records"), false);
335                                 long item = -1;
336                                 while ((item = portrange.GetToken()))
337                                         e->records[item] = 1;
338                         }
339
340                         e->banaction = str2banaction(tag->getString("action"));
341                         e->duration = tag->getDuration("duration", 60, 1);
342
343                         /* Use portparser for record replies */
344
345                         /* yeah, logic here is a little messy */
346                         if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
347                         {
348                                 throw ModuleException("Invalid <dnsbl:bitmask> at " + tag->getTagLocation());
349                         }
350                         else if (e->name.empty())
351                         {
352                                 throw ModuleException("Empty <dnsbl:name> at " + tag->getTagLocation());
353                         }
354                         else if (e->domain.empty())
355                         {
356                                 throw ModuleException("Empty <dnsbl:domain> at " + tag->getTagLocation());
357                         }
358                         else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
359                         {
360                                 throw ModuleException("Unknown <dnsbl:action> at " + tag->getTagLocation());
361                         }
362                         else
363                         {
364                                 /* add it, all is ok */
365                                 newentries.push_back(e);
366                         }
367                 }
368
369                 DNSBLConfEntries.swap(newentries);
370         }
371
372         void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
373         {
374                 if (user->exempt || user->quitting || !DNS)
375                         return;
376
377                 // Clients can't be in a DNSBL if they aren't connected via IPv4 or IPv6.
378                 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
379                         return;
380
381                 if (user->MyClass)
382                 {
383                         if (!user->MyClass->config->getBool("usednsbl", true))
384                                 return;
385                 }
386                 else
387                 {
388                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
389                         return;
390                 }
391
392                 std::string reversedip;
393                 if (user->client_sa.family() == AF_INET)
394                 {
395                         unsigned int a, b, c, d;
396                         d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
397                         c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
398                         b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
399                         a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
400
401                         reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
402                 }
403                 else if (user->client_sa.family() == AF_INET6)
404                 {
405                         const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
406
407                         std::string buf = BinToHex(ip, 16);
408                         for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
409                         {
410                                 reversedip.push_back(*it);
411                                 reversedip.push_back('.');
412                         }
413                         reversedip.erase(reversedip.length() - 1, 1);
414                 }
415                 else
416                         return;
417
418                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
419
420                 countExt.set(user, DNSBLConfEntries.size());
421
422                 // For each DNSBL, we will run through this lookup
423                 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
424                 {
425                         // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
426                         std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
427
428                         /* now we'd need to fire off lookups for `hostname'. */
429                         DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
430                         try
431                         {
432                                 this->DNS->Process(r);
433                         }
434                         catch (DNS::Exception &ex)
435                         {
436                                 delete r;
437                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
438                         }
439
440                         if (user->quitting)
441                                 break;
442                 }
443         }
444
445         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
446         {
447                 std::string dnsbl;
448                 if (!myclass->config->readString("dnsbl", dnsbl))
449                         return MOD_RES_PASSTHRU;
450
451                 std::string* match = nameExt.get(user);
452                 if (!match)
453                 {
454                         ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it requires a DNSBL mark",
455                                         myclass->GetName().c_str());
456                         return MOD_RES_DENY;
457                 }
458
459                 if (!InspIRCd::Match(*match, dnsbl))
460                 {
461                         ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as the DNSBL mark (%s) does not match %s",
462                                         myclass->GetName().c_str(), match->c_str(), dnsbl.c_str());
463                         return MOD_RES_DENY;
464                 }
465
466                 return MOD_RES_PASSTHRU;
467         }
468
469         ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
470         {
471                 if (countExt.get(user))
472                         return MOD_RES_DENY;
473                 return MOD_RES_PASSTHRU;
474         }
475
476         ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
477         {
478                 if (stats.GetSymbol() != 'd')
479                         return MOD_RES_PASSTHRU;
480
481                 unsigned long total_hits = 0, total_misses = 0;
482
483                 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
484                 {
485                         total_hits += (*i)->stats_hits;
486                         total_misses += (*i)->stats_misses;
487
488                         stats.AddRow(304, "DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
489                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
490                 }
491
492                 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
493                 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
494
495                 return MOD_RES_PASSTHRU;
496         }
497 };
498
499 MODULE_INIT(ModuleDNSBL)