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 (stdalgo::string::equalsci(action, "kill"))
257 return DNSBLConfEntry::I_KILL;
258 if (stdalgo::string::equalsci(action, "kline"))
259 return DNSBLConfEntry::I_KLINE;
260 if (stdalgo::string::equalsci(action, "zline"))
261 return DNSBLConfEntry::I_ZLINE;
262 if (stdalgo::string::equalsci(action, "gline"))
263 return DNSBLConfEntry::I_GLINE;
264 if (stdalgo::string::equalsci(action, "mark"))
265 return DNSBLConfEntry::I_MARK;
266 return DNSBLConfEntry::I_UNKNOWN;
270 : Stats::EventListener(this)
272 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
273 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
277 void init() CXX11_OVERRIDE
279 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
282 Version GetVersion() CXX11_OVERRIDE
284 return Version("Allows the server administrator to check the IP address of connecting users against a DNSBL.", VF_VENDOR);
287 /** Fill our conf vector with data
289 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
291 DNSBLConfList newentries;
293 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
294 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
296 ConfigTag* tag = i->second;
297 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
299 e->name = tag->getString("name");
300 e->ident = tag->getString("ident");
301 e->host = tag->getString("host");
302 e->reason = tag->getString("reason", "Your IP has been blacklisted.", 1);
303 e->domain = tag->getString("domain");
305 if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
307 e->type = DNSBLConfEntry::A_BITMASK;
308 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
312 memset(e->records, 0, sizeof(e->records));
313 e->type = DNSBLConfEntry::A_RECORD;
314 irc::portparser portrange(tag->getString("records"), false);
316 while ((item = portrange.GetToken()))
317 e->records[item] = 1;
320 e->banaction = str2banaction(tag->getString("action"));
321 e->duration = tag->getDuration("duration", 60, 1);
323 /* Use portparser for record replies */
325 /* yeah, logic here is a little messy */
326 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
328 throw ModuleException("Invalid <dnsbl:bitmask> at " + tag->getTagLocation());
330 else if (e->name.empty())
332 throw ModuleException("Empty <dnsbl:name> at " + tag->getTagLocation());
334 else if (e->domain.empty())
336 throw ModuleException("Empty <dnsbl:domain> at " + tag->getTagLocation());
338 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
340 throw ModuleException("Unknown <dnsbl:action> at " + tag->getTagLocation());
344 /* add it, all is ok */
345 newentries.push_back(e);
349 DNSBLConfEntries.swap(newentries);
352 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
354 if ((user->exempt) || !DNS)
357 // Clients can't be in a DNSBL if they aren't connected via IPv4 or IPv6.
358 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
363 if (!user->MyClass->config->getBool("usednsbl", true))
367 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
369 std::string reversedip;
370 if (user->client_sa.family() == AF_INET)
372 unsigned int a, b, c, d;
373 d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
374 c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
375 b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
376 a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
378 reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
380 else if (user->client_sa.family() == AF_INET6)
382 const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
384 std::string buf = BinToHex(ip, 16);
385 for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
387 reversedip.push_back(*it);
388 reversedip.push_back('.');
390 reversedip.erase(reversedip.length() - 1, 1);
395 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
397 countExt.set(user, DNSBLConfEntries.size());
399 // For each DNSBL, we will run through this lookup
400 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
402 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
403 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
405 /* now we'd need to fire off lookups for `hostname'. */
406 DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
409 this->DNS->Process(r);
411 catch (DNS::Exception &ex)
414 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
422 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
425 if (!myclass->config->readString("dnsbl", dnsbl))
426 return MOD_RES_PASSTHRU;
428 std::string* match = nameExt.get(user);
432 if (InspIRCd::Match(*match, dnsbl))
433 return MOD_RES_PASSTHRU;
438 ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
440 if (countExt.get(user))
442 return MOD_RES_PASSTHRU;
445 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
447 if (stats.GetSymbol() != 'd')
448 return MOD_RES_PASSTHRU;
450 unsigned long total_hits = 0, total_misses = 0;
452 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
454 total_hits += (*i)->stats_hits;
455 total_misses += (*i)->stats_misses;
457 stats.AddRow(304, "DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
458 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
461 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
462 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
464 return MOD_RES_PASSTHRU;
468 MODULE_INIT(ModuleDNSBL)