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"
28 /* Class holding data for a single entry */
29 class DNSBLConfEntry : public refcountbase
32 enum EnumBanaction { I_UNKNOWN, I_KILL, I_ZLINE, I_KLINE, I_GLINE, I_MARK };
33 enum EnumType { A_RECORD, A_BITMASK };
34 std::string name, ident, host, domain, reason;
35 EnumBanaction banaction;
39 unsigned char records[256];
40 unsigned long stats_hits, stats_misses;
41 DNSBLConfEntry(): type(A_BITMASK),duration(86400),bitmask(0),stats_hits(0), stats_misses(0) {}
45 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
47 class DNSBLResolver : public DNS::Request
50 LocalStringExt& nameExt;
51 LocalIntExt& countExt;
52 reference<DNSBLConfEntry> ConfEntry;
56 DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf)
57 : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf)
61 /* Note: This may be called multiple times for multiple A record results */
62 void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
64 /* Check the user still exists */
65 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
69 const DNS::ResourceRecord &ans_record = r->answers[0];
71 int i = countExt.get(them);
73 countExt.set(them, i - 1);
75 // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
77 unsigned int bitmask = 0, record = 0;
81 inet_aton(ans_record.rdata.c_str(), &resultip);
83 switch (ConfEntry->type)
85 case DNSBLConfEntry::A_BITMASK:
86 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
87 bitmask &= ConfEntry->bitmask;
88 match = (bitmask != 0);
90 case DNSBLConfEntry::A_RECORD:
91 record = resultip.s_addr >> 24; /* Last octet */
92 match = (ConfEntry->records[record] == 1);
98 std::string reason = ConfEntry->reason;
99 std::string::size_type x = reason.find("%ip%");
100 while (x != std::string::npos)
103 reason.insert(x, them->GetIPString());
104 x = reason.find("%ip%");
107 ConfEntry->stats_hits++;
109 switch (ConfEntry->banaction)
111 case DNSBLConfEntry::I_KILL:
113 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
116 case DNSBLConfEntry::I_MARK:
118 if (!ConfEntry->ident.empty())
120 them->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
121 them->ChangeIdent(ConfEntry->ident);
124 if (!ConfEntry->host.empty())
126 them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason);
127 them->ChangeDisplayedHost(ConfEntry->host);
130 nameExt.set(them, ConfEntry->name);
133 case DNSBLConfEntry::I_KLINE:
135 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
136 "*", them->GetIPString());
137 if (ServerInstance->XLines->AddLine(kl,NULL))
139 std::string timestr = ServerInstance->TimeString(kl->expiry);
140 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
141 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
142 ServerInstance->XLines->ApplyLines();
148 case DNSBLConfEntry::I_GLINE:
150 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
151 "*", them->GetIPString());
152 if (ServerInstance->XLines->AddLine(gl,NULL))
154 std::string timestr = ServerInstance->TimeString(gl->expiry);
155 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
156 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
157 ServerInstance->XLines->ApplyLines();
163 case DNSBLConfEntry::I_ZLINE:
165 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
166 them->GetIPString());
167 if (ServerInstance->XLines->AddLine(zl,NULL))
169 std::string timestr = ServerInstance->TimeString(zl->expiry);
170 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
171 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
172 ServerInstance->XLines->ApplyLines();
178 case DNSBLConfEntry::I_UNKNOWN:
183 ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s%s detected as being on a DNS blacklist (%s) with result %d", them->nick.empty() ? "<unknown>" : "", them->GetFullRealHost().c_str(), ConfEntry->domain.c_str(), (ConfEntry->type==DNSBLConfEntry::A_BITMASK) ? bitmask : record);
186 ConfEntry->stats_misses++;
189 void OnError(const DNS::Query *q) CXX11_OVERRIDE
191 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
195 int i = countExt.get(them);
197 countExt.set(them, i - 1);
199 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
200 ConfEntry->stats_misses++;
204 class ModuleDNSBL : public Module
206 std::vector<reference<DNSBLConfEntry> > DNSBLConfEntries;
207 dynamic_reference<DNS::Manager> DNS;
208 LocalStringExt nameExt;
209 LocalIntExt countExt;
212 * Convert a string to EnumBanaction
214 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
216 if(action.compare("KILL")==0)
217 return DNSBLConfEntry::I_KILL;
218 if(action.compare("KLINE")==0)
219 return DNSBLConfEntry::I_KLINE;
220 if(action.compare("ZLINE")==0)
221 return DNSBLConfEntry::I_ZLINE;
222 if(action.compare("GLINE")==0)
223 return DNSBLConfEntry::I_GLINE;
224 if(action.compare("MARK")==0)
225 return DNSBLConfEntry::I_MARK;
227 return DNSBLConfEntry::I_UNKNOWN;
230 ModuleDNSBL() : DNS(this, "DNS"), nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
232 Version GetVersion() CXX11_OVERRIDE
234 return Version("Provides handling of DNS blacklists", VF_VENDOR);
237 /** Fill our conf vector with data
239 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
241 DNSBLConfEntries.clear();
243 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
244 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
246 ConfigTag* tag = i->second;
247 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
249 e->name = tag->getString("name");
250 e->ident = tag->getString("ident");
251 e->host = tag->getString("host");
252 e->reason = tag->getString("reason");
253 e->domain = tag->getString("domain");
255 if (tag->getString("type") == "bitmask")
257 e->type = DNSBLConfEntry::A_BITMASK;
258 e->bitmask = tag->getInt("bitmask");
262 memset(e->records, 0, sizeof(e->records));
263 e->type = DNSBLConfEntry::A_RECORD;
264 irc::portparser portrange(tag->getString("records"), false);
266 while ((item = portrange.GetToken()))
267 e->records[item] = 1;
270 e->banaction = str2banaction(tag->getString("action"));
271 e->duration = tag->getDuration("duration", 60, 1);
273 /* Use portparser for record replies */
275 /* yeah, logic here is a little messy */
276 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
278 std::string location = tag->getTagLocation();
279 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): invalid bitmask", location.c_str());
281 else if (e->name.empty())
283 std::string location = tag->getTagLocation();
284 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid name", location.c_str());
286 else if (e->domain.empty())
288 std::string location = tag->getTagLocation();
289 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid domain", location.c_str());
291 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
293 std::string location = tag->getTagLocation();
294 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid banaction", location.c_str());
298 if (e->reason.empty())
300 std::string location = tag->getTagLocation();
301 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): empty reason, using defaults", location.c_str());
302 e->reason = "Your IP has been blacklisted.";
305 /* add it, all is ok */
306 DNSBLConfEntries.push_back(e);
311 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
313 if ((user->exempt) || (user->client_sa.sa.sa_family != AF_INET) || !DNS)
318 if (!user->MyClass->config->getBool("usednsbl", true))
322 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
324 unsigned int a, b, c, d;
325 d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
326 c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
327 b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
328 a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
330 const std::string reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
332 countExt.set(user, DNSBLConfEntries.size());
334 // For each DNSBL, we will run through this lookup
335 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
337 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
338 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
340 /* now we'd need to fire off lookups for `hostname'. */
341 DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
344 this->DNS->Process(r);
346 catch (DNS::Exception &ex)
349 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, std::string(ex.GetReason()));
357 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
360 if (!myclass->config->readString("dnsbl", dnsbl))
361 return MOD_RES_PASSTHRU;
362 std::string* match = nameExt.get(user);
363 std::string myname = match ? *match : "";
365 return MOD_RES_PASSTHRU;
369 ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
371 if (countExt.get(user))
373 return MOD_RES_PASSTHRU;
376 ModResult OnStats(char symbol, User* user, string_list &results) CXX11_OVERRIDE
379 return MOD_RES_PASSTHRU;
381 unsigned long total_hits = 0, total_misses = 0;
383 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
385 total_hits += (*i)->stats_hits;
386 total_misses += (*i)->stats_misses;
388 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
389 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
392 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
393 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
395 return MOD_RES_PASSTHRU;
399 MODULE_INIT(ModuleDNSBL)