2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2018-2020 Matt Schatz <genius3000@g3k.solutions>
5 * Copyright (C) 2018-2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6 * Copyright (C) 2013, 2017-2021 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>
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.
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
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/>.
31 #include "modules/dns.h"
32 #include "modules/stats.h"
34 /* Class holding data for a single entry */
35 class DNSBLConfEntry : public refcountbase
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;
43 unsigned long duration;
46 unsigned char records[256];
47 unsigned long stats_hits, stats_misses, stats_errors;
61 /** Resolver for CGI:IRC hostnames encoded in ident/real name
63 class DNSBLResolver : public DNS::Request
66 irc::sockets::sockaddrs theirsa;
68 LocalStringExt& nameExt;
69 LocalIntExt& countExt;
70 reference<DNSBLConfEntry> ConfEntry;
73 DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf)
74 : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true, conf->timeout)
75 , theirsa(u->client_sa)
83 /* Note: This may be called multiple times for multiple A record results */
84 void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
86 /* Check the user still exists */
87 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
88 if (!them || them->client_sa != theirsa)
90 ConfEntry->stats_misses++;
94 int i = countExt.get(them);
96 countExt.set(them, i - 1);
98 // The DNSBL reply must contain an A result.
99 const DNS::ResourceRecord* const ans_record = r->FindAnswerOfType(DNS::QUERY_A);
102 ConfEntry->stats_errors++;
103 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an result with no IPv4 address.",
104 ConfEntry->name.c_str());
108 // The DNSBL reply must be a valid IPv4 address.
110 if (inet_pton(AF_INET, ans_record->rdata.c_str(), &resultip) != 1)
112 ConfEntry->stats_errors++;
113 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an invalid IPv4 address: %s",
114 ConfEntry->name.c_str(), ans_record->rdata.c_str());
118 // The DNSBL reply should be in the 127.0.0.0/8 range.
119 if ((resultip.s_addr & 0xFF) != 127)
121 ConfEntry->stats_errors++;
122 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an IPv4 address which is outside of the 127.0.0.0/8 subnet: %s",
123 ConfEntry->name.c_str(), ans_record->rdata.c_str());
128 unsigned int result = 0;
129 switch (ConfEntry->type)
131 case DNSBLConfEntry::A_BITMASK:
133 result = (resultip.s_addr >> 24) & ConfEntry->bitmask;
134 match = (result != 0);
137 case DNSBLConfEntry::A_RECORD:
139 result = resultip.s_addr >> 24;
140 match = (ConfEntry->records[result] == 1);
147 std::string reason = ConfEntry->reason;
148 std::string::size_type x = reason.find("%ip%");
149 while (x != std::string::npos)
152 reason.insert(x, them->GetIPString());
153 x = reason.find("%ip%");
156 ConfEntry->stats_hits++;
158 switch (ConfEntry->banaction)
160 case DNSBLConfEntry::I_KILL:
162 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
165 case DNSBLConfEntry::I_MARK:
167 if (!ConfEntry->ident.empty())
169 them->WriteNotice("Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
170 them->ChangeIdent(ConfEntry->ident);
173 if (!ConfEntry->host.empty())
175 them->WriteNotice("Your host has been set to " + ConfEntry->host + " because you matched " + reason);
176 them->ChangeDisplayedHost(ConfEntry->host);
179 nameExt.set(them, ConfEntry->name);
182 case DNSBLConfEntry::I_KLINE:
184 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
185 "*", them->GetIPString());
186 if (ServerInstance->XLines->AddLine(kl,NULL))
188 ServerInstance->SNO->WriteToSnoMask('x', "K-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
189 them->GetIPString().c_str(), InspIRCd::DurationString(kl->duration).c_str(),
190 InspIRCd::TimeString(kl->expiry).c_str(), reason.c_str());
191 ServerInstance->XLines->ApplyLines();
200 case DNSBLConfEntry::I_GLINE:
202 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
203 "*", them->GetIPString());
204 if (ServerInstance->XLines->AddLine(gl,NULL))
206 ServerInstance->SNO->WriteToSnoMask('x', "G-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
207 them->GetIPString().c_str(), InspIRCd::DurationString(gl->duration).c_str(),
208 InspIRCd::TimeString(gl->expiry).c_str(), reason.c_str());
209 ServerInstance->XLines->ApplyLines();
218 case DNSBLConfEntry::I_ZLINE:
220 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
221 them->GetIPString());
222 if (ServerInstance->XLines->AddLine(zl,NULL))
224 ServerInstance->SNO->WriteToSnoMask('x', "Z-line added due to DNSBL match on %s to expire in %s (on %s): %s",
225 them->GetIPString().c_str(), InspIRCd::DurationString(zl->duration).c_str(),
226 InspIRCd::TimeString(zl->expiry).c_str(), reason.c_str());
227 ServerInstance->XLines->ApplyLines();
236 case DNSBLConfEntry::I_UNKNOWN:
241 ServerInstance->SNO->WriteGlobalSno('d', "Connecting user %s (%s) detected as being on the '%s' DNS blacklist with result %d",
242 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), result);
245 ConfEntry->stats_misses++;
248 void OnError(const DNS::Query *q) CXX11_OVERRIDE
253 case DNS::ERROR_NO_RECORDS:
254 case DNS::ERROR_DOMAIN_NOT_FOUND:
255 ConfEntry->stats_misses++;
259 ConfEntry->stats_errors++;
264 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
265 if (!them || them->client_sa != theirsa)
268 int i = countExt.get(them);
270 countExt.set(them, i - 1);
275 ServerInstance->SNO->WriteGlobalSno('d', "An error occurred whilst checking whether %s (%s) is on the '%s' DNS blacklist: %s",
276 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), this->manager->GetErrorStr(q->error).c_str());
280 typedef std::vector<reference<DNSBLConfEntry> > DNSBLConfList;
282 class ModuleDNSBL : public Module, public Stats::EventListener
284 DNSBLConfList DNSBLConfEntries;
285 dynamic_reference<DNS::Manager> DNS;
286 LocalStringExt nameExt;
287 LocalIntExt countExt;
290 * Convert a string to EnumBanaction
292 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
294 if (stdalgo::string::equalsci(action, "kill"))
295 return DNSBLConfEntry::I_KILL;
296 if (stdalgo::string::equalsci(action, "kline"))
297 return DNSBLConfEntry::I_KLINE;
298 if (stdalgo::string::equalsci(action, "zline"))
299 return DNSBLConfEntry::I_ZLINE;
300 if (stdalgo::string::equalsci(action, "gline"))
301 return DNSBLConfEntry::I_GLINE;
302 if (stdalgo::string::equalsci(action, "mark"))
303 return DNSBLConfEntry::I_MARK;
304 return DNSBLConfEntry::I_UNKNOWN;
308 : Stats::EventListener(this)
310 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
311 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
315 void init() CXX11_OVERRIDE
317 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
320 void Prioritize() CXX11_OVERRIDE
322 Module* corexline = ServerInstance->Modules->Find("core_xline");
323 ServerInstance->Modules->SetPriority(this, I_OnSetUserIP, PRIORITY_AFTER, corexline);
326 Version GetVersion() CXX11_OVERRIDE
328 return Version("Allows the server administrator to check the IP address of connecting users against a DNSBL.", VF_VENDOR);
331 /** Fill our conf vector with data
333 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
335 DNSBLConfList newentries;
337 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
338 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
340 ConfigTag* tag = i->second;
341 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
343 e->name = tag->getString("name");
344 e->ident = tag->getString("ident");
345 e->host = tag->getString("host");
346 e->reason = tag->getString("reason", "Your IP has been blacklisted.", 1);
347 e->domain = tag->getString("domain");
348 e->timeout = tag->getDuration("timeout", 0);
350 if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
352 e->type = DNSBLConfEntry::A_BITMASK;
353 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
357 memset(e->records, 0, sizeof(e->records));
358 e->type = DNSBLConfEntry::A_RECORD;
359 irc::portparser portrange(tag->getString("records"), false);
361 while ((item = portrange.GetToken()))
362 e->records[item] = 1;
365 e->banaction = str2banaction(tag->getString("action"));
366 e->duration = tag->getDuration("duration", 60, 1);
368 /* Use portparser for record replies */
370 /* yeah, logic here is a little messy */
371 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
373 throw ModuleException("Invalid <dnsbl:bitmask> at " + tag->getTagLocation());
375 else if (e->name.empty())
377 throw ModuleException("Empty <dnsbl:name> at " + tag->getTagLocation());
379 else if (e->domain.empty())
381 throw ModuleException("Empty <dnsbl:domain> at " + tag->getTagLocation());
383 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
385 throw ModuleException("Unknown <dnsbl:action> at " + tag->getTagLocation());
389 /* add it, all is ok */
390 newentries.push_back(e);
394 DNSBLConfEntries.swap(newentries);
397 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
399 if (user->exempt || user->quitting || !DNS)
402 // Clients can't be in a DNSBL if they aren't connected via IPv4 or IPv6.
403 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
408 if (!user->MyClass->config->getBool("usednsbl", true))
413 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
417 std::string reversedip;
418 if (user->client_sa.family() == AF_INET)
420 unsigned int a, b, c, d;
421 d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
422 c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
423 b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
424 a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
426 reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
428 else if (user->client_sa.family() == AF_INET6)
430 const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
432 std::string buf = BinToHex(ip, 16);
433 for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
435 reversedip.push_back(*it);
436 reversedip.push_back('.');
438 reversedip.erase(reversedip.length() - 1, 1);
443 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
445 countExt.set(user, DNSBLConfEntries.size());
447 // For each DNSBL, we will run through this lookup
448 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
450 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
451 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
453 /* now we'd need to fire off lookups for `hostname'. */
454 DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
457 this->DNS->Process(r);
459 catch (DNS::Exception &ex)
462 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
470 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
473 if (!myclass->config->readString("dnsbl", dnsbl))
474 return MOD_RES_PASSTHRU;
476 std::string* match = nameExt.get(user);
479 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it requires a DNSBL mark",
480 myclass->GetName().c_str());
484 if (!InspIRCd::Match(*match, dnsbl))
486 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as the DNSBL mark (%s) does not match %s",
487 myclass->GetName().c_str(), match->c_str(), dnsbl.c_str());
491 return MOD_RES_PASSTHRU;
494 ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
496 if (countExt.get(user))
498 return MOD_RES_PASSTHRU;
501 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
503 if (stats.GetSymbol() != 'd')
504 return MOD_RES_PASSTHRU;
506 unsigned long total_hits = 0;
507 unsigned long total_misses = 0;
508 unsigned long total_errors = 0;
509 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
511 total_hits += (*i)->stats_hits;
512 total_misses += (*i)->stats_misses;
513 total_errors += (*i)->stats_errors;
515 stats.AddRow(304, InspIRCd::Format("DNSBLSTATS \"%s\" had %lu hits, %lu misses, and %lu errors",
516 (*i)->name.c_str(), (*i)->stats_hits, (*i)->stats_misses, (*i)->stats_errors));
519 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
520 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
521 stats.AddRow(304, "DNSBLSTATS Total errors: " + ConvToStr(total_errors));
522 return MOD_RES_PASSTHRU;
526 MODULE_INIT(ModuleDNSBL)