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-2019 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 const DNS::ResourceRecord* const ans_record = r->FindAnswerOfType(DNS::QUERY_A);
85 // All replies should be in 127.0.0.0/8
86 if (ans_record->rdata.compare(0, 4, "127.") != 0)
88 ServerInstance->SNO->WriteGlobalSno('d', "DNSBL: %s returned address outside of acceptable subnet 127.0.0.0/8: %s", ConfEntry->domain.c_str(), ans_record->rdata.c_str());
89 ConfEntry->stats_misses++;
93 int i = countExt.get(them);
95 countExt.set(them, i - 1);
97 // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
99 unsigned int bitmask = 0, record = 0;
103 inet_pton(AF_INET, ans_record->rdata.c_str(), &resultip);
105 switch (ConfEntry->type)
107 case DNSBLConfEntry::A_BITMASK:
108 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
109 bitmask &= ConfEntry->bitmask;
110 match = (bitmask != 0);
112 case DNSBLConfEntry::A_RECORD:
113 record = resultip.s_addr >> 24; /* Last octet */
114 match = (ConfEntry->records[record] == 1);
120 std::string reason = ConfEntry->reason;
121 std::string::size_type x = reason.find("%ip%");
122 while (x != std::string::npos)
125 reason.insert(x, them->GetIPString());
126 x = reason.find("%ip%");
129 ConfEntry->stats_hits++;
131 switch (ConfEntry->banaction)
133 case DNSBLConfEntry::I_KILL:
135 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
138 case DNSBLConfEntry::I_MARK:
140 if (!ConfEntry->ident.empty())
142 them->WriteNotice("Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
143 them->ChangeIdent(ConfEntry->ident);
146 if (!ConfEntry->host.empty())
148 them->WriteNotice("Your host has been set to " + ConfEntry->host + " because you matched " + reason);
149 them->ChangeDisplayedHost(ConfEntry->host);
152 nameExt.set(them, ConfEntry->name);
155 case DNSBLConfEntry::I_KLINE:
157 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
158 "*", them->GetIPString());
159 if (ServerInstance->XLines->AddLine(kl,NULL))
161 ServerInstance->SNO->WriteToSnoMask('x', "K-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
162 them->GetIPString().c_str(), InspIRCd::DurationString(kl->duration).c_str(),
163 InspIRCd::TimeString(kl->expiry).c_str(), reason.c_str());
164 ServerInstance->XLines->ApplyLines();
173 case DNSBLConfEntry::I_GLINE:
175 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
176 "*", them->GetIPString());
177 if (ServerInstance->XLines->AddLine(gl,NULL))
179 ServerInstance->SNO->WriteToSnoMask('x', "G-line added due to DNSBL match on *@%s to expire in %s (on %s): %s",
180 them->GetIPString().c_str(), InspIRCd::DurationString(gl->duration).c_str(),
181 InspIRCd::TimeString(gl->expiry).c_str(), reason.c_str());
182 ServerInstance->XLines->ApplyLines();
191 case DNSBLConfEntry::I_ZLINE:
193 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
194 them->GetIPString());
195 if (ServerInstance->XLines->AddLine(zl,NULL))
197 ServerInstance->SNO->WriteToSnoMask('x', "Z-line added due to DNSBL match on %s to expire in %s (on %s): %s",
198 them->GetIPString().c_str(), InspIRCd::DurationString(zl->duration).c_str(),
199 InspIRCd::TimeString(zl->expiry).c_str(), reason.c_str());
200 ServerInstance->XLines->ApplyLines();
209 case DNSBLConfEntry::I_UNKNOWN:
214 ServerInstance->SNO->WriteGlobalSno('d', "Connecting user %s (%s) detected as being on the '%s' DNS blacklist with result %d",
215 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), (ConfEntry->type==DNSBLConfEntry::A_BITMASK) ? bitmask : record);
218 ConfEntry->stats_misses++;
221 void OnError(const DNS::Query *q) CXX11_OVERRIDE
223 LocalUser* them = IS_LOCAL(ServerInstance->FindUUID(theiruid));
224 if (!them || them->client_sa != theirsa)
227 int i = countExt.get(them);
229 countExt.set(them, i - 1);
231 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
233 ConfEntry->stats_misses++;
237 ServerInstance->SNO->WriteGlobalSno('d', "An error occurred whilst checking whether %s (%s) is on the '%s' DNS blacklist: %s",
238 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), this->manager->GetErrorStr(q->error).c_str());
242 typedef std::vector<reference<DNSBLConfEntry> > DNSBLConfList;
244 class ModuleDNSBL : public Module, public Stats::EventListener
246 DNSBLConfList DNSBLConfEntries;
247 dynamic_reference<DNS::Manager> DNS;
248 LocalStringExt nameExt;
249 LocalIntExt countExt;
252 * Convert a string to EnumBanaction
254 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
256 if(action.compare("KILL")==0)
257 return DNSBLConfEntry::I_KILL;
258 if(action.compare("KLINE")==0)
259 return DNSBLConfEntry::I_KLINE;
260 if(action.compare("ZLINE")==0)
261 return DNSBLConfEntry::I_ZLINE;
262 if(action.compare("GLINE")==0)
263 return DNSBLConfEntry::I_GLINE;
264 if(action.compare("MARK")==0)
265 return DNSBLConfEntry::I_MARK;
267 return DNSBLConfEntry::I_UNKNOWN;
271 : Stats::EventListener(this)
273 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
274 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
278 void init() CXX11_OVERRIDE
280 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
283 Version GetVersion() CXX11_OVERRIDE
285 return Version("Allows the server administrator to check the IP address of connecting users against a DNSBL.", VF_VENDOR);
288 /** Fill our conf vector with data
290 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
292 DNSBLConfList newentries;
294 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
295 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
297 ConfigTag* tag = i->second;
298 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
300 e->name = tag->getString("name");
301 e->ident = tag->getString("ident");
302 e->host = tag->getString("host");
303 e->reason = tag->getString("reason");
304 e->domain = tag->getString("domain");
306 if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
308 e->type = DNSBLConfEntry::A_BITMASK;
309 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
313 memset(e->records, 0, sizeof(e->records));
314 e->type = DNSBLConfEntry::A_RECORD;
315 irc::portparser portrange(tag->getString("records"), false);
317 while ((item = portrange.GetToken()))
318 e->records[item] = 1;
321 e->banaction = str2banaction(tag->getString("action"));
322 e->duration = tag->getDuration("duration", 60, 1);
324 /* Use portparser for record replies */
326 /* yeah, logic here is a little messy */
327 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
329 throw ModuleException("Invalid <dnsbl:bitmask> at " + tag->getTagLocation());
331 else if (e->name.empty())
333 throw ModuleException("Empty <dnsbl:name> at " + tag->getTagLocation());
335 else if (e->domain.empty())
337 throw ModuleException("Empty <dnsbl:domain> at " + tag->getTagLocation());
339 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
341 throw ModuleException("Unknown <dnsbl:action> at " + tag->getTagLocation());
345 if (e->reason.empty())
347 std::string location = tag->getTagLocation();
348 ServerInstance->SNO->WriteGlobalSno('d', "DNSBL(%s): empty reason, using defaults", location.c_str());
349 e->reason = "Your IP has been blacklisted.";
352 /* add it, all is ok */
353 newentries.push_back(e);
357 DNSBLConfEntries.swap(newentries);
360 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
362 if ((user->exempt) || !DNS)
365 // Clients can't be in a DNSBL if they aren't connected via IPv4 or IPv6.
366 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
371 if (!user->MyClass->config->getBool("usednsbl", true))
375 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
377 std::string reversedip;
378 if (user->client_sa.family() == AF_INET)
380 unsigned int a, b, c, d;
381 d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
382 c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
383 b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
384 a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
386 reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
388 else if (user->client_sa.family() == AF_INET6)
390 const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
392 std::string buf = BinToHex(ip, 16);
393 for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
395 reversedip.push_back(*it);
396 reversedip.push_back('.');
398 reversedip.erase(reversedip.length() - 1, 1);
403 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
405 countExt.set(user, DNSBLConfEntries.size());
407 // For each DNSBL, we will run through this lookup
408 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
410 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
411 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
413 /* now we'd need to fire off lookups for `hostname'. */
414 DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
417 this->DNS->Process(r);
419 catch (DNS::Exception &ex)
422 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
430 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
433 if (!myclass->config->readString("dnsbl", dnsbl))
434 return MOD_RES_PASSTHRU;
436 std::string* match = nameExt.get(user);
440 if (InspIRCd::Match(*match, dnsbl))
441 return MOD_RES_PASSTHRU;
446 ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
448 if (countExt.get(user))
450 return MOD_RES_PASSTHRU;
453 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
455 if (stats.GetSymbol() != 'd')
456 return MOD_RES_PASSTHRU;
458 unsigned long total_hits = 0, total_misses = 0;
460 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
462 total_hits += (*i)->stats_hits;
463 total_misses += (*i)->stats_misses;
465 stats.AddRow(304, "DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
466 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
469 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
470 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
472 return MOD_RES_PASSTHRU;
476 MODULE_INIT(ModuleDNSBL)