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;
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)
88 ConfEntry->stats_misses++;
92 int i = countExt.get(them);
94 countExt.set(them, i - 1);
96 // The DNSBL reply must contain an A result.
97 const DNS::ResourceRecord* const ans_record = r->FindAnswerOfType(DNS::QUERY_A);
100 ConfEntry->stats_errors++;
101 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an result with no IPv4 address.",
102 ConfEntry->name.c_str());
106 // The DNSBL reply must be a valid IPv4 address.
108 if (inet_pton(AF_INET, ans_record->rdata.c_str(), &resultip) != 1)
110 ConfEntry->stats_errors++;
111 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an invalid IPv4 address: %s",
112 ConfEntry->name.c_str(), ans_record->rdata.c_str());
116 // The DNSBL reply should be in the 127.0.0.0/8 range.
117 if ((resultip.s_addr & 0xFF) != 127)
119 ConfEntry->stats_errors++;
120 ServerInstance->SNO->WriteGlobalSno('d', "%s returned an IPv4 address which is outside of the 127.0.0.0/8 subnet: %s",
121 ConfEntry->name.c_str(), ans_record->rdata.c_str());
126 unsigned int result = 0;
127 switch (ConfEntry->type)
129 case DNSBLConfEntry::A_BITMASK:
131 result = (resultip.s_addr >> 24) & ConfEntry->bitmask;
132 match = (result != 0);
135 case DNSBLConfEntry::A_RECORD:
137 result = resultip.s_addr >> 24;
138 match = (ConfEntry->records[result] == 1);
145 std::string reason = ConfEntry->reason;
146 std::string::size_type x = reason.find("%ip%");
147 while (x != std::string::npos)
150 reason.insert(x, them->GetIPString());
151 x = reason.find("%ip%");
154 ConfEntry->stats_hits++;
156 switch (ConfEntry->banaction)
158 case DNSBLConfEntry::I_KILL:
160 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
163 case DNSBLConfEntry::I_MARK:
165 if (!ConfEntry->ident.empty())
167 them->WriteNotice("Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
168 them->ChangeIdent(ConfEntry->ident);
171 if (!ConfEntry->host.empty())
173 them->WriteNotice("Your host has been set to " + ConfEntry->host + " because you matched " + reason);
174 them->ChangeDisplayedHost(ConfEntry->host);
177 nameExt.set(them, ConfEntry->name);
180 case DNSBLConfEntry::I_KLINE:
182 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
183 "*", them->GetIPString());
184 if (ServerInstance->XLines->AddLine(kl,NULL))
186 ServerInstance->SNO->WriteToSnoMask('x', "K-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
187 them->GetIPString().c_str(), InspIRCd::DurationString(kl->duration).c_str(),
188 InspIRCd::TimeString(kl->expiry).c_str(), reason.c_str());
189 ServerInstance->XLines->ApplyLines();
198 case DNSBLConfEntry::I_GLINE:
200 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
201 "*", them->GetIPString());
202 if (ServerInstance->XLines->AddLine(gl,NULL))
204 ServerInstance->SNO->WriteToSnoMask('x', "G-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
205 them->GetIPString().c_str(), InspIRCd::DurationString(gl->duration).c_str(),
206 InspIRCd::TimeString(gl->expiry).c_str(), reason.c_str());
207 ServerInstance->XLines->ApplyLines();
216 case DNSBLConfEntry::I_ZLINE:
218 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
219 them->GetIPString());
220 if (ServerInstance->XLines->AddLine(zl,NULL))
222 ServerInstance->SNO->WriteToSnoMask('x', "Z-line added due to DNSBL match on %s to expire in %s (on %s): %s",
223 them->GetIPString().c_str(), InspIRCd::DurationString(zl->duration).c_str(),
224 InspIRCd::TimeString(zl->expiry).c_str(), reason.c_str());
225 ServerInstance->XLines->ApplyLines();
234 case DNSBLConfEntry::I_UNKNOWN:
239 ServerInstance->SNO->WriteGlobalSno('d', "Connecting user %s (%s) detected as being on the '%s' DNS blacklist with result %d",
240 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), result);
243 ConfEntry->stats_misses++;
246 void OnError(const DNS::Query *q) CXX11_OVERRIDE
251 case DNS::ERROR_NO_RECORDS:
252 case DNS::ERROR_DOMAIN_NOT_FOUND:
253 ConfEntry->stats_misses++;
257 ConfEntry->stats_errors++;
262 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
263 if (!them || them->client_sa != theirsa)
266 int i = countExt.get(them);
268 countExt.set(them, i - 1);
273 ServerInstance->SNO->WriteGlobalSno('d', "An error occurred whilst checking whether %s (%s) is on the '%s' DNS blacklist: %s",
274 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), this->manager->GetErrorStr(q->error).c_str());
278 typedef std::vector<reference<DNSBLConfEntry> > DNSBLConfList;
280 class ModuleDNSBL : public Module, public Stats::EventListener
282 DNSBLConfList DNSBLConfEntries;
283 dynamic_reference<DNS::Manager> DNS;
284 LocalStringExt nameExt;
285 LocalIntExt countExt;
288 * Convert a string to EnumBanaction
290 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
292 if (stdalgo::string::equalsci(action, "kill"))
293 return DNSBLConfEntry::I_KILL;
294 if (stdalgo::string::equalsci(action, "kline"))
295 return DNSBLConfEntry::I_KLINE;
296 if (stdalgo::string::equalsci(action, "zline"))
297 return DNSBLConfEntry::I_ZLINE;
298 if (stdalgo::string::equalsci(action, "gline"))
299 return DNSBLConfEntry::I_GLINE;
300 if (stdalgo::string::equalsci(action, "mark"))
301 return DNSBLConfEntry::I_MARK;
302 return DNSBLConfEntry::I_UNKNOWN;
306 : Stats::EventListener(this)
308 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
309 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
313 void init() CXX11_OVERRIDE
315 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
318 void Prioritize() CXX11_OVERRIDE
320 Module* corexline = ServerInstance->Modules->Find("core_xline");
321 ServerInstance->Modules->SetPriority(this, I_OnSetUserIP, PRIORITY_AFTER, corexline);
324 Version GetVersion() CXX11_OVERRIDE
326 return Version("Allows the server administrator to check the IP address of connecting users against a DNSBL.", VF_VENDOR);
329 /** Fill our conf vector with data
331 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
333 DNSBLConfList newentries;
335 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
336 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
338 ConfigTag* tag = i->second;
339 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
341 e->name = tag->getString("name");
342 e->ident = tag->getString("ident");
343 e->host = tag->getString("host");
344 e->reason = tag->getString("reason", "Your IP has been blacklisted.", 1);
345 e->domain = tag->getString("domain");
347 if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
349 e->type = DNSBLConfEntry::A_BITMASK;
350 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
354 memset(e->records, 0, sizeof(e->records));
355 e->type = DNSBLConfEntry::A_RECORD;
356 irc::portparser portrange(tag->getString("records"), false);
358 while ((item = portrange.GetToken()))
359 e->records[item] = 1;
362 e->banaction = str2banaction(tag->getString("action"));
363 e->duration = tag->getDuration("duration", 60, 1);
365 /* Use portparser for record replies */
367 /* yeah, logic here is a little messy */
368 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
370 throw ModuleException("Invalid <dnsbl:bitmask> at " + tag->getTagLocation());
372 else if (e->name.empty())
374 throw ModuleException("Empty <dnsbl:name> at " + tag->getTagLocation());
376 else if (e->domain.empty())
378 throw ModuleException("Empty <dnsbl:domain> at " + tag->getTagLocation());
380 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
382 throw ModuleException("Unknown <dnsbl:action> at " + tag->getTagLocation());
386 /* add it, all is ok */
387 newentries.push_back(e);
391 DNSBLConfEntries.swap(newentries);
394 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
396 if (user->exempt || user->quitting || !DNS)
399 // Clients can't be in a DNSBL if they aren't connected via IPv4 or IPv6.
400 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
405 if (!user->MyClass->config->getBool("usednsbl", true))
410 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
414 std::string reversedip;
415 if (user->client_sa.family() == AF_INET)
417 unsigned int a, b, c, d;
418 d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
419 c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
420 b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
421 a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
423 reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
425 else if (user->client_sa.family() == AF_INET6)
427 const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
429 std::string buf = BinToHex(ip, 16);
430 for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
432 reversedip.push_back(*it);
433 reversedip.push_back('.');
435 reversedip.erase(reversedip.length() - 1, 1);
440 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
442 countExt.set(user, DNSBLConfEntries.size());
444 // For each DNSBL, we will run through this lookup
445 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
447 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
448 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
450 /* now we'd need to fire off lookups for `hostname'. */
451 DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
454 this->DNS->Process(r);
456 catch (DNS::Exception &ex)
459 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
467 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
470 if (!myclass->config->readString("dnsbl", dnsbl))
471 return MOD_RES_PASSTHRU;
473 std::string* match = nameExt.get(user);
476 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it requires a DNSBL mark",
477 myclass->GetName().c_str());
481 if (!InspIRCd::Match(*match, dnsbl))
483 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as the DNSBL mark (%s) does not match %s",
484 myclass->GetName().c_str(), match->c_str(), dnsbl.c_str());
488 return MOD_RES_PASSTHRU;
491 ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
493 if (countExt.get(user))
495 return MOD_RES_PASSTHRU;
498 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
500 if (stats.GetSymbol() != 'd')
501 return MOD_RES_PASSTHRU;
503 unsigned long total_hits = 0;
504 unsigned long total_misses = 0;
505 unsigned long total_errors = 0;
506 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
508 total_hits += (*i)->stats_hits;
509 total_misses += (*i)->stats_misses;
510 total_errors += (*i)->stats_errors;
512 stats.AddRow(304, InspIRCd::Format("DNSBLSTATS \"%s\" had %lu hits, %lu misses, and %lu errors",
513 (*i)->name.c_str(), (*i)->stats_hits, (*i)->stats_misses, (*i)->stats_errors));
516 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
517 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
518 stats.AddRow(304, "DNSBLSTATS Total errors: " + ConvToStr(total_errors));
519 return MOD_RES_PASSTHRU;
523 MODULE_INIT(ModuleDNSBL)