2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2007 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2006-2007 Dennis Friis <peavey@inspircd.org>
8 * Copyright (C) 2007 John Brooks <john.brooks@dereferenced.net>
10 * This file is part of InspIRCd. InspIRCd is free software: you can
11 * redistribute it and/or modify it under the terms of the GNU General Public
12 * License as published by the Free Software Foundation, version 2.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include "modules/dns.h"
27 #include "modules/stats.h"
29 /* Class holding data for a single entry */
30 class DNSBLConfEntry : public refcountbase
33 enum EnumBanaction { I_UNKNOWN, I_KILL, I_ZLINE, I_KLINE, I_GLINE, I_MARK };
34 enum EnumType { A_RECORD, A_BITMASK };
35 std::string name, ident, host, domain, reason;
36 EnumBanaction banaction;
38 unsigned long duration;
40 unsigned char records[256];
41 unsigned long stats_hits, stats_misses;
42 DNSBLConfEntry(): type(A_BITMASK),duration(86400),bitmask(0),stats_hits(0), stats_misses(0) {}
46 /** Resolver for CGI:IRC hostnames encoded in ident/real name
48 class DNSBLResolver : public DNS::Request
51 LocalStringExt& nameExt;
52 LocalIntExt& countExt;
53 reference<DNSBLConfEntry> ConfEntry;
57 DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf)
58 : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf)
62 /* Note: This may be called multiple times for multiple A record results */
63 void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
65 /* Check the user still exists */
66 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
70 const DNS::ResourceRecord* const ans_record = r->FindAnswerOfType(DNS::QUERY_A);
74 // All replies should be in 127.0.0.0/8
75 if (ans_record->rdata.compare(0, 4, "127.") != 0)
77 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());
78 ConfEntry->stats_misses++;
82 int i = countExt.get(them);
84 countExt.set(them, i - 1);
86 // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
88 unsigned int bitmask = 0, record = 0;
92 inet_pton(AF_INET, ans_record->rdata.c_str(), &resultip);
94 switch (ConfEntry->type)
96 case DNSBLConfEntry::A_BITMASK:
97 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
98 bitmask &= ConfEntry->bitmask;
99 match = (bitmask != 0);
101 case DNSBLConfEntry::A_RECORD:
102 record = resultip.s_addr >> 24; /* Last octet */
103 match = (ConfEntry->records[record] == 1);
109 std::string reason = ConfEntry->reason;
110 std::string::size_type x = reason.find("%ip%");
111 while (x != std::string::npos)
114 reason.insert(x, them->GetIPString());
115 x = reason.find("%ip%");
118 ConfEntry->stats_hits++;
120 switch (ConfEntry->banaction)
122 case DNSBLConfEntry::I_KILL:
124 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
127 case DNSBLConfEntry::I_MARK:
129 if (!ConfEntry->ident.empty())
131 them->WriteNotice("Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
132 them->ChangeIdent(ConfEntry->ident);
135 if (!ConfEntry->host.empty())
137 them->WriteNotice("Your host has been set to " + ConfEntry->host + " because you matched " + reason);
138 them->ChangeDisplayedHost(ConfEntry->host);
141 nameExt.set(them, ConfEntry->name);
144 case DNSBLConfEntry::I_KLINE:
146 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
147 "*", them->GetIPString());
148 if (ServerInstance->XLines->AddLine(kl,NULL))
150 std::string timestr = InspIRCd::TimeString(kl->expiry);
151 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
152 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
153 ServerInstance->XLines->ApplyLines();
162 case DNSBLConfEntry::I_GLINE:
164 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
165 "*", them->GetIPString());
166 if (ServerInstance->XLines->AddLine(gl,NULL))
168 std::string timestr = InspIRCd::TimeString(gl->expiry);
169 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
170 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
171 ServerInstance->XLines->ApplyLines();
180 case DNSBLConfEntry::I_ZLINE:
182 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
183 them->GetIPString());
184 if (ServerInstance->XLines->AddLine(zl,NULL))
186 std::string timestr = InspIRCd::TimeString(zl->expiry);
187 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on %s to expire on %s: %s",
188 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
189 ServerInstance->XLines->ApplyLines();
198 case DNSBLConfEntry::I_UNKNOWN:
203 ServerInstance->SNO->WriteGlobalSno('d', "Connecting user %s (%s) detected as being on the '%s' DNS blacklist with result %d",
204 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), (ConfEntry->type==DNSBLConfEntry::A_BITMASK) ? bitmask : record);
207 ConfEntry->stats_misses++;
210 void OnError(const DNS::Query *q) CXX11_OVERRIDE
212 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
216 int i = countExt.get(them);
218 countExt.set(them, i - 1);
220 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
221 ConfEntry->stats_misses++;
223 ServerInstance->SNO->WriteGlobalSno('d', "An error occurred whilst checking whether %s (%s) is on the '%s' DNS blacklist: %s",
224 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), this->manager->GetErrorStr(q->error).c_str());
228 class ModuleDNSBL : public Module, public Stats::EventListener
230 std::vector<reference<DNSBLConfEntry> > DNSBLConfEntries;
231 dynamic_reference<DNS::Manager> DNS;
232 LocalStringExt nameExt;
233 LocalIntExt countExt;
236 * Convert a string to EnumBanaction
238 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
240 if(action.compare("KILL")==0)
241 return DNSBLConfEntry::I_KILL;
242 if(action.compare("KLINE")==0)
243 return DNSBLConfEntry::I_KLINE;
244 if(action.compare("ZLINE")==0)
245 return DNSBLConfEntry::I_ZLINE;
246 if(action.compare("GLINE")==0)
247 return DNSBLConfEntry::I_GLINE;
248 if(action.compare("MARK")==0)
249 return DNSBLConfEntry::I_MARK;
251 return DNSBLConfEntry::I_UNKNOWN;
255 : Stats::EventListener(this)
257 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
258 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
262 void init() CXX11_OVERRIDE
264 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
267 Version GetVersion() CXX11_OVERRIDE
269 return Version("Provides handling of DNS blacklists", VF_VENDOR);
272 /** Fill our conf vector with data
274 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
276 DNSBLConfEntries.clear();
278 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
279 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
281 ConfigTag* tag = i->second;
282 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
284 e->name = tag->getString("name");
285 e->ident = tag->getString("ident");
286 e->host = tag->getString("host");
287 e->reason = tag->getString("reason");
288 e->domain = tag->getString("domain");
290 if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
292 e->type = DNSBLConfEntry::A_BITMASK;
293 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
297 memset(e->records, 0, sizeof(e->records));
298 e->type = DNSBLConfEntry::A_RECORD;
299 irc::portparser portrange(tag->getString("records"), false);
301 while ((item = portrange.GetToken()))
302 e->records[item] = 1;
305 e->banaction = str2banaction(tag->getString("action"));
306 e->duration = tag->getDuration("duration", 60, 1);
308 /* Use portparser for record replies */
310 /* yeah, logic here is a little messy */
311 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
313 std::string location = tag->getTagLocation();
314 ServerInstance->SNO->WriteGlobalSno('d', "DNSBL(%s): invalid bitmask", location.c_str());
316 else if (e->name.empty())
318 std::string location = tag->getTagLocation();
319 ServerInstance->SNO->WriteGlobalSno('d', "DNSBL(%s): Invalid name", location.c_str());
321 else if (e->domain.empty())
323 std::string location = tag->getTagLocation();
324 ServerInstance->SNO->WriteGlobalSno('d', "DNSBL(%s): Invalid domain", location.c_str());
326 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
328 std::string location = tag->getTagLocation();
329 ServerInstance->SNO->WriteGlobalSno('d', "DNSBL(%s): Invalid banaction", location.c_str());
333 if (e->reason.empty())
335 std::string location = tag->getTagLocation();
336 ServerInstance->SNO->WriteGlobalSno('d', "DNSBL(%s): empty reason, using defaults", location.c_str());
337 e->reason = "Your IP has been blacklisted.";
340 /* add it, all is ok */
341 DNSBLConfEntries.push_back(e);
346 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
348 if ((user->exempt) || !DNS)
351 // Clients can't be in a DNSBL if they aren't connected via IPv4 or IPv6.
352 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
357 if (!user->MyClass->config->getBool("usednsbl", true))
361 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
363 std::string reversedip;
364 if (user->client_sa.family() == AF_INET)
366 unsigned int a, b, c, d;
367 d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
368 c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
369 b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
370 a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
372 reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
374 else if (user->client_sa.family() == AF_INET6)
376 const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
378 std::string buf = BinToHex(ip, 16);
379 for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
381 reversedip.push_back(*it);
382 reversedip.push_back('.');
388 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
390 countExt.set(user, DNSBLConfEntries.size());
392 // For each DNSBL, we will run through this lookup
393 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
395 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
396 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
398 /* now we'd need to fire off lookups for `hostname'. */
399 DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
402 this->DNS->Process(r);
404 catch (DNS::Exception &ex)
407 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
415 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
418 if (!myclass->config->readString("dnsbl", dnsbl))
419 return MOD_RES_PASSTHRU;
420 std::string* match = nameExt.get(user);
421 std::string myname = match ? *match : "";
423 return MOD_RES_PASSTHRU;
427 ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
429 if (countExt.get(user))
431 return MOD_RES_PASSTHRU;
434 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
436 if (stats.GetSymbol() != 'd')
437 return MOD_RES_PASSTHRU;
439 unsigned long total_hits = 0, total_misses = 0;
441 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
443 total_hits += (*i)->stats_hits;
444 total_misses += (*i)->stats_misses;
446 stats.AddRow(304, "DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
447 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
450 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
451 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
453 return MOD_RES_PASSTHRU;
457 MODULE_INIT(ModuleDNSBL)