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, 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>
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;
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) {}
51 /** Resolver for CGI:IRC hostnames encoded in ident/real name
53 class DNSBLResolver : public DNS::Request
56 irc::sockets::sockaddrs theirsa;
58 LocalStringExt& nameExt;
59 LocalIntExt& countExt;
60 reference<DNSBLConfEntry> ConfEntry;
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)
73 /* Note: This may be called multiple times for multiple A record results */
74 void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
76 /* Check the user still exists */
77 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
78 if (!them || them->client_sa != theirsa)
81 int i = countExt.get(them);
83 countExt.set(them, i - 1);
85 // The DNSBL reply must contain an A result.
86 const DNS::ResourceRecord* const ans_record = r->FindAnswerOfType(DNS::QUERY_A);
89 ConfEntry->stats_misses++;
90 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an result with no IPv4 address.",
91 ConfEntry->name.c_str());
95 // The DNSBL reply must be a valid IPv4 address.
97 if (inet_pton(AF_INET, ans_record->rdata.c_str(), &resultip) != 1)
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());
105 // The DNSBL reply should be in the 127.0.0.0/8 range.
106 if ((resultip.s_addr & 0xFF) != 127)
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());
115 unsigned int result = 0;
116 switch (ConfEntry->type)
118 case DNSBLConfEntry::A_BITMASK:
120 result = (resultip.s_addr >> 24) & ConfEntry->bitmask;
121 match = (result != 0);
124 case DNSBLConfEntry::A_RECORD:
126 result = resultip.s_addr >> 24;
127 match = (ConfEntry->records[result] == 1);
134 std::string reason = ConfEntry->reason;
135 std::string::size_type x = reason.find("%ip%");
136 while (x != std::string::npos)
139 reason.insert(x, them->GetIPString());
140 x = reason.find("%ip%");
143 ConfEntry->stats_hits++;
145 switch (ConfEntry->banaction)
147 case DNSBLConfEntry::I_KILL:
149 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
152 case DNSBLConfEntry::I_MARK:
154 if (!ConfEntry->ident.empty())
156 them->WriteNotice("Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
157 them->ChangeIdent(ConfEntry->ident);
160 if (!ConfEntry->host.empty())
162 them->WriteNotice("Your host has been set to " + ConfEntry->host + " because you matched " + reason);
163 them->ChangeDisplayedHost(ConfEntry->host);
166 nameExt.set(them, ConfEntry->name);
169 case DNSBLConfEntry::I_KLINE:
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))
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();
187 case DNSBLConfEntry::I_GLINE:
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))
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();
205 case DNSBLConfEntry::I_ZLINE:
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))
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();
223 case DNSBLConfEntry::I_UNKNOWN:
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);
232 ConfEntry->stats_misses++;
235 void OnError(const DNS::Query *q) CXX11_OVERRIDE
237 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
238 if (!them || them->client_sa != theirsa)
241 int i = countExt.get(them);
243 countExt.set(them, i - 1);
245 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
247 ConfEntry->stats_misses++;
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());
256 typedef std::vector<reference<DNSBLConfEntry> > DNSBLConfList;
258 class ModuleDNSBL : public Module, public Stats::EventListener
260 DNSBLConfList DNSBLConfEntries;
261 dynamic_reference<DNS::Manager> DNS;
262 LocalStringExt nameExt;
263 LocalIntExt countExt;
266 * Convert a string to EnumBanaction
268 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
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;
284 : Stats::EventListener(this)
286 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
287 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
291 void init() CXX11_OVERRIDE
293 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
296 void Prioritize() CXX11_OVERRIDE
298 Module* corexline = ServerInstance->Modules->Find("core_xline");
299 ServerInstance->Modules->SetPriority(this, I_OnSetUserIP, PRIORITY_AFTER, corexline);
302 Version GetVersion() CXX11_OVERRIDE
304 return Version("Allows the server administrator to check the IP address of connecting users against a DNSBL.", VF_VENDOR);
307 /** Fill our conf vector with data
309 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
311 DNSBLConfList newentries;
313 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
314 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
316 ConfigTag* tag = i->second;
317 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
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");
325 if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
327 e->type = DNSBLConfEntry::A_BITMASK;
328 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
332 memset(e->records, 0, sizeof(e->records));
333 e->type = DNSBLConfEntry::A_RECORD;
334 irc::portparser portrange(tag->getString("records"), false);
336 while ((item = portrange.GetToken()))
337 e->records[item] = 1;
340 e->banaction = str2banaction(tag->getString("action"));
341 e->duration = tag->getDuration("duration", 60, 1);
343 /* Use portparser for record replies */
345 /* yeah, logic here is a little messy */
346 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
348 throw ModuleException("Invalid <dnsbl:bitmask> at " + tag->getTagLocation());
350 else if (e->name.empty())
352 throw ModuleException("Empty <dnsbl:name> at " + tag->getTagLocation());
354 else if (e->domain.empty())
356 throw ModuleException("Empty <dnsbl:domain> at " + tag->getTagLocation());
358 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
360 throw ModuleException("Unknown <dnsbl:action> at " + tag->getTagLocation());
364 /* add it, all is ok */
365 newentries.push_back(e);
369 DNSBLConfEntries.swap(newentries);
372 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
374 if (user->exempt || user->quitting || !DNS)
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)
383 if (!user->MyClass->config->getBool("usednsbl", true))
388 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
392 std::string reversedip;
393 if (user->client_sa.family() == AF_INET)
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;
401 reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
403 else if (user->client_sa.family() == AF_INET6)
405 const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
407 std::string buf = BinToHex(ip, 16);
408 for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
410 reversedip.push_back(*it);
411 reversedip.push_back('.');
413 reversedip.erase(reversedip.length() - 1, 1);
418 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
420 countExt.set(user, DNSBLConfEntries.size());
422 // For each DNSBL, we will run through this lookup
423 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
425 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
426 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
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]);
432 this->DNS->Process(r);
434 catch (DNS::Exception &ex)
437 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
445 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
448 if (!myclass->config->readString("dnsbl", dnsbl))
449 return MOD_RES_PASSTHRU;
451 std::string* match = nameExt.get(user);
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());
459 if (!InspIRCd::Match(*match, dnsbl))
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());
466 return MOD_RES_PASSTHRU;
469 ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
471 if (countExt.get(user))
473 return MOD_RES_PASSTHRU;
476 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
478 if (stats.GetSymbol() != 'd')
479 return MOD_RES_PASSTHRU;
481 unsigned long total_hits = 0, total_misses = 0;
483 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
485 total_hits += (*i)->stats_hits;
486 total_misses += (*i)->stats_misses;
488 stats.AddRow(304, "DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
489 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
492 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
493 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
495 return MOD_RES_PASSTHRU;
499 MODULE_INIT(ModuleDNSBL)