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, stats_errors;
59 /** Resolver for CGI:IRC hostnames encoded in ident/real name
61 class DNSBLResolver : public DNS::Request
64 irc::sockets::sockaddrs theirsa;
66 LocalStringExt& nameExt;
67 LocalIntExt& countExt;
68 reference<DNSBLConfEntry> ConfEntry;
71 DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf)
72 : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true)
73 , theirsa(u->client_sa)
81 /* Note: This may be called multiple times for multiple A record results */
82 void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
84 /* Check the user still exists */
85 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
86 if (!them || them->client_sa != theirsa)
89 int i = countExt.get(them);
91 countExt.set(them, i - 1);
93 // The DNSBL reply must contain an A result.
94 const DNS::ResourceRecord* const ans_record = r->FindAnswerOfType(DNS::QUERY_A);
97 ConfEntry->stats_errors++;
98 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an result with no IPv4 address.",
99 ConfEntry->name.c_str());
103 // The DNSBL reply must be a valid IPv4 address.
105 if (inet_pton(AF_INET, ans_record->rdata.c_str(), &resultip) != 1)
107 ConfEntry->stats_errors++;
108 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an invalid IPv4 address: %s",
109 ConfEntry->name.c_str(), ans_record->rdata.c_str());
113 // The DNSBL reply should be in the 127.0.0.0/8 range.
114 if ((resultip.s_addr & 0xFF) != 127)
116 ConfEntry->stats_errors++;
117 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an IPv4 address which is outside of the 127.0.0.0/8 subnet: %s",
118 ConfEntry->name.c_str(), ans_record->rdata.c_str());
123 unsigned int result = 0;
124 switch (ConfEntry->type)
126 case DNSBLConfEntry::A_BITMASK:
128 result = (resultip.s_addr >> 24) & ConfEntry->bitmask;
129 match = (result != 0);
132 case DNSBLConfEntry::A_RECORD:
134 result = resultip.s_addr >> 24;
135 match = (ConfEntry->records[result] == 1);
142 std::string reason = ConfEntry->reason;
143 std::string::size_type x = reason.find("%ip%");
144 while (x != std::string::npos)
147 reason.insert(x, them->GetIPString());
148 x = reason.find("%ip%");
151 ConfEntry->stats_hits++;
153 switch (ConfEntry->banaction)
155 case DNSBLConfEntry::I_KILL:
157 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
160 case DNSBLConfEntry::I_MARK:
162 if (!ConfEntry->ident.empty())
164 them->WriteNotice("Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
165 them->ChangeIdent(ConfEntry->ident);
168 if (!ConfEntry->host.empty())
170 them->WriteNotice("Your host has been set to " + ConfEntry->host + " because you matched " + reason);
171 them->ChangeDisplayedHost(ConfEntry->host);
174 nameExt.set(them, ConfEntry->name);
177 case DNSBLConfEntry::I_KLINE:
179 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
180 "*", them->GetIPString());
181 if (ServerInstance->XLines->AddLine(kl,NULL))
183 ServerInstance->SNO->WriteToSnoMask('x', "K-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
184 them->GetIPString().c_str(), InspIRCd::DurationString(kl->duration).c_str(),
185 InspIRCd::TimeString(kl->expiry).c_str(), reason.c_str());
186 ServerInstance->XLines->ApplyLines();
195 case DNSBLConfEntry::I_GLINE:
197 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
198 "*", them->GetIPString());
199 if (ServerInstance->XLines->AddLine(gl,NULL))
201 ServerInstance->SNO->WriteToSnoMask('x', "G-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
202 them->GetIPString().c_str(), InspIRCd::DurationString(gl->duration).c_str(),
203 InspIRCd::TimeString(gl->expiry).c_str(), reason.c_str());
204 ServerInstance->XLines->ApplyLines();
213 case DNSBLConfEntry::I_ZLINE:
215 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
216 them->GetIPString());
217 if (ServerInstance->XLines->AddLine(zl,NULL))
219 ServerInstance->SNO->WriteToSnoMask('x', "Z-line added due to DNSBL match on %s to expire in %s (on %s): %s",
220 them->GetIPString().c_str(), InspIRCd::DurationString(zl->duration).c_str(),
221 InspIRCd::TimeString(zl->expiry).c_str(), reason.c_str());
222 ServerInstance->XLines->ApplyLines();
231 case DNSBLConfEntry::I_UNKNOWN:
236 ServerInstance->SNO->WriteGlobalSno('d', "Connecting user %s (%s) detected as being on the '%s' DNS blacklist with result %d",
237 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), result);
240 ConfEntry->stats_misses++;
243 void OnError(const DNS::Query *q) CXX11_OVERRIDE
245 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
246 if (!them || them->client_sa != theirsa)
249 int i = countExt.get(them);
251 countExt.set(them, i - 1);
253 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
255 ConfEntry->stats_misses++;
259 ConfEntry->stats_errors++;
260 ServerInstance->SNO->WriteGlobalSno('d', "An error occurred whilst checking whether %s (%s) is on the '%s' DNS blacklist: %s",
261 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), this->manager->GetErrorStr(q->error).c_str());
265 typedef std::vector<reference<DNSBLConfEntry> > DNSBLConfList;
267 class ModuleDNSBL : public Module, public Stats::EventListener
269 DNSBLConfList DNSBLConfEntries;
270 dynamic_reference<DNS::Manager> DNS;
271 LocalStringExt nameExt;
272 LocalIntExt countExt;
275 * Convert a string to EnumBanaction
277 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
279 if (stdalgo::string::equalsci(action, "kill"))
280 return DNSBLConfEntry::I_KILL;
281 if (stdalgo::string::equalsci(action, "kline"))
282 return DNSBLConfEntry::I_KLINE;
283 if (stdalgo::string::equalsci(action, "zline"))
284 return DNSBLConfEntry::I_ZLINE;
285 if (stdalgo::string::equalsci(action, "gline"))
286 return DNSBLConfEntry::I_GLINE;
287 if (stdalgo::string::equalsci(action, "mark"))
288 return DNSBLConfEntry::I_MARK;
289 return DNSBLConfEntry::I_UNKNOWN;
293 : Stats::EventListener(this)
295 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
296 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
300 void init() CXX11_OVERRIDE
302 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
305 void Prioritize() CXX11_OVERRIDE
307 Module* corexline = ServerInstance->Modules->Find("core_xline");
308 ServerInstance->Modules->SetPriority(this, I_OnSetUserIP, PRIORITY_AFTER, corexline);
311 Version GetVersion() CXX11_OVERRIDE
313 return Version("Allows the server administrator to check the IP address of connecting users against a DNSBL.", VF_VENDOR);
316 /** Fill our conf vector with data
318 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
320 DNSBLConfList newentries;
322 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
323 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
325 ConfigTag* tag = i->second;
326 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
328 e->name = tag->getString("name");
329 e->ident = tag->getString("ident");
330 e->host = tag->getString("host");
331 e->reason = tag->getString("reason", "Your IP has been blacklisted.", 1);
332 e->domain = tag->getString("domain");
334 if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
336 e->type = DNSBLConfEntry::A_BITMASK;
337 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
341 memset(e->records, 0, sizeof(e->records));
342 e->type = DNSBLConfEntry::A_RECORD;
343 irc::portparser portrange(tag->getString("records"), false);
345 while ((item = portrange.GetToken()))
346 e->records[item] = 1;
349 e->banaction = str2banaction(tag->getString("action"));
350 e->duration = tag->getDuration("duration", 60, 1);
352 /* Use portparser for record replies */
354 /* yeah, logic here is a little messy */
355 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
357 throw ModuleException("Invalid <dnsbl:bitmask> at " + tag->getTagLocation());
359 else if (e->name.empty())
361 throw ModuleException("Empty <dnsbl:name> at " + tag->getTagLocation());
363 else if (e->domain.empty())
365 throw ModuleException("Empty <dnsbl:domain> at " + tag->getTagLocation());
367 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
369 throw ModuleException("Unknown <dnsbl:action> at " + tag->getTagLocation());
373 /* add it, all is ok */
374 newentries.push_back(e);
378 DNSBLConfEntries.swap(newentries);
381 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
383 if (user->exempt || user->quitting || !DNS)
386 // Clients can't be in a DNSBL if they aren't connected via IPv4 or IPv6.
387 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
392 if (!user->MyClass->config->getBool("usednsbl", true))
397 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
401 std::string reversedip;
402 if (user->client_sa.family() == AF_INET)
404 unsigned int a, b, c, d;
405 d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
406 c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
407 b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
408 a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
410 reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
412 else if (user->client_sa.family() == AF_INET6)
414 const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
416 std::string buf = BinToHex(ip, 16);
417 for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
419 reversedip.push_back(*it);
420 reversedip.push_back('.');
422 reversedip.erase(reversedip.length() - 1, 1);
427 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
429 countExt.set(user, DNSBLConfEntries.size());
431 // For each DNSBL, we will run through this lookup
432 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
434 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
435 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
437 /* now we'd need to fire off lookups for `hostname'. */
438 DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
441 this->DNS->Process(r);
443 catch (DNS::Exception &ex)
446 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
454 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
457 if (!myclass->config->readString("dnsbl", dnsbl))
458 return MOD_RES_PASSTHRU;
460 std::string* match = nameExt.get(user);
463 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it requires a DNSBL mark",
464 myclass->GetName().c_str());
468 if (!InspIRCd::Match(*match, dnsbl))
470 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as the DNSBL mark (%s) does not match %s",
471 myclass->GetName().c_str(), match->c_str(), dnsbl.c_str());
475 return MOD_RES_PASSTHRU;
478 ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
480 if (countExt.get(user))
482 return MOD_RES_PASSTHRU;
485 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
487 if (stats.GetSymbol() != 'd')
488 return MOD_RES_PASSTHRU;
490 unsigned long total_hits = 0;
491 unsigned long total_misses = 0;
492 unsigned long total_errors = 0;
493 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
495 total_hits += (*i)->stats_hits;
496 total_misses += (*i)->stats_misses;
497 total_errors += (*i)->stats_errors;
499 stats.AddRow(304, InspIRCd::Format("DNSBLSTATS \"%s\" had %lu hits, %lu misses, and %lu errors",
500 (*i)->name.c_str(), (*i)->stats_hits, (*i)->stats_misses, (*i)->stats_errors));
503 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
504 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
505 stats.AddRow(304, "DNSBLSTATS Total errors: " + ConvToStr(total_errors));
506 return MOD_RES_PASSTHRU;
510 MODULE_INIT(ModuleDNSBL)