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 /* $ModDesc: Provides handling of DNS blacklists */
30 /* Class holding data for a single entry */
34 enum EnumBanaction { I_UNKNOWN, I_KILL, I_ZLINE, I_KLINE, I_GLINE, I_MARK };
35 enum EnumType { A_RECORD, A_BITMASK };
36 std::string name, ident, host, domain, reason;
37 EnumBanaction banaction;
41 unsigned char records[256];
42 unsigned long stats_hits, stats_misses;
43 DNSBLConfEntry(): type(A_BITMASK),duration(86400),bitmask(0),stats_hits(0), stats_misses(0) {}
47 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
49 class DNSBLResolver : public DNS::Request
52 LocalStringExt& nameExt;
53 LocalIntExt& countExt;
54 DNSBLConfEntry *ConfEntry;
58 DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, DNSBLConfEntry *conf)
59 : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf)
63 /* Note: This may be called multiple times for multiple A record results */
64 void OnLookupComplete(const DNS::Query *r)
66 /* Check the user still exists */
67 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
71 const DNS::ResourceRecord &ans_record = r->answers[0];
73 int i = countExt.get(them);
75 countExt.set(them, i - 1);
77 // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
79 unsigned int bitmask = 0, record = 0;
83 inet_aton(ans_record.rdata.c_str(), &resultip);
85 switch (ConfEntry->type)
87 case DNSBLConfEntry::A_BITMASK:
88 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
89 bitmask &= ConfEntry->bitmask;
90 match = (bitmask != 0);
92 case DNSBLConfEntry::A_RECORD:
93 record = resultip.s_addr >> 24; /* Last octet */
94 match = (ConfEntry->records[record] == 1);
100 std::string reason = ConfEntry->reason;
101 std::string::size_type x = reason.find("%ip%");
102 while (x != std::string::npos)
105 reason.insert(x, them->GetIPString());
106 x = reason.find("%ip%");
109 ConfEntry->stats_hits++;
111 switch (ConfEntry->banaction)
113 case DNSBLConfEntry::I_KILL:
115 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
118 case DNSBLConfEntry::I_MARK:
120 if (!ConfEntry->ident.empty())
122 them->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
123 them->ChangeIdent(ConfEntry->ident.c_str());
126 if (!ConfEntry->host.empty())
128 them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason);
129 them->ChangeDisplayedHost(ConfEntry->host.c_str());
132 nameExt.set(them, ConfEntry->name);
135 case DNSBLConfEntry::I_KLINE:
137 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
138 "*", them->GetIPString());
139 if (ServerInstance->XLines->AddLine(kl,NULL))
141 std::string timestr = ServerInstance->TimeString(kl->expiry);
142 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
143 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
144 ServerInstance->XLines->ApplyLines();
150 case DNSBLConfEntry::I_GLINE:
152 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
153 "*", them->GetIPString());
154 if (ServerInstance->XLines->AddLine(gl,NULL))
156 std::string timestr = ServerInstance->TimeString(gl->expiry);
157 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
158 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
159 ServerInstance->XLines->ApplyLines();
165 case DNSBLConfEntry::I_ZLINE:
167 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
168 them->GetIPString());
169 if (ServerInstance->XLines->AddLine(zl,NULL))
171 std::string timestr = ServerInstance->TimeString(zl->expiry);
172 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
173 them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
174 ServerInstance->XLines->ApplyLines();
180 case DNSBLConfEntry::I_UNKNOWN:
185 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);
188 ConfEntry->stats_misses++;
191 void OnError(const DNS::Query *q)
193 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
197 int i = countExt.get(them);
199 countExt.set(them, i - 1);
201 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
202 ConfEntry->stats_misses++;
206 class ModuleDNSBL : public Module
208 std::vector<DNSBLConfEntry *> DNSBLConfEntries;
209 dynamic_reference<DNS::Manager> DNS;
210 LocalStringExt nameExt;
211 LocalIntExt countExt;
214 * Convert a string to EnumBanaction
216 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
218 if(action.compare("KILL")==0)
219 return DNSBLConfEntry::I_KILL;
220 if(action.compare("KLINE")==0)
221 return DNSBLConfEntry::I_KLINE;
222 if(action.compare("ZLINE")==0)
223 return DNSBLConfEntry::I_ZLINE;
224 if(action.compare("GLINE")==0)
225 return DNSBLConfEntry::I_GLINE;
226 if(action.compare("MARK")==0)
227 return DNSBLConfEntry::I_MARK;
229 return DNSBLConfEntry::I_UNKNOWN;
232 ModuleDNSBL() : DNS(this, "DNS"), nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
237 ServerInstance->Modules->AddService(nameExt);
238 ServerInstance->Modules->AddService(countExt);
239 Implementation eventlist[] = { I_OnRehash, I_OnSetUserIP, I_OnStats, I_OnSetConnectClass, I_OnCheckReady };
240 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
243 virtual ~ModuleDNSBL()
250 return Version("Provides handling of DNS blacklists", VF_VENDOR);
253 /** Clear entries and free the mem it was using
257 for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
259 DNSBLConfEntries.clear();
262 /** Fill our conf vector with data
268 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
269 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
271 ConfigTag* tag = i->second;
272 DNSBLConfEntry *e = new DNSBLConfEntry();
274 e->name = tag->getString("name");
275 e->ident = tag->getString("ident");
276 e->host = tag->getString("host");
277 e->reason = tag->getString("reason");
278 e->domain = tag->getString("domain");
280 if (tag->getString("type") == "bitmask")
282 e->type = DNSBLConfEntry::A_BITMASK;
283 e->bitmask = tag->getInt("bitmask");
287 memset(e->records, 0, sizeof(e->records));
288 e->type = DNSBLConfEntry::A_RECORD;
289 irc::portparser portrange(tag->getString("records"), false);
291 while ((item = portrange.GetToken()))
292 e->records[item] = 1;
295 e->banaction = str2banaction(tag->getString("action"));
296 e->duration = InspIRCd::Duration(tag->getString("duration", "60"));
298 /* Use portparser for record replies */
300 /* yeah, logic here is a little messy */
301 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
303 std::string location = tag->getTagLocation();
304 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): invalid bitmask", location.c_str());
306 else if (e->name.empty())
308 std::string location = tag->getTagLocation();
309 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid name", location.c_str());
311 else if (e->domain.empty())
313 std::string location = tag->getTagLocation();
314 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid domain", location.c_str());
316 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
318 std::string location = tag->getTagLocation();
319 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid banaction", location.c_str());
321 else if (e->duration <= 0)
323 std::string location = tag->getTagLocation();
324 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid duration", location.c_str());
328 if (e->reason.empty())
330 std::string location = tag->getTagLocation();
331 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): empty reason, using defaults", location.c_str());
332 e->reason = "Your IP has been blacklisted.";
335 /* add it, all is ok */
336 DNSBLConfEntries.push_back(e);
340 /* delete and drop it, error somewhere */
345 void OnRehash(User* user)
350 void OnSetUserIP(LocalUser* user)
352 if ((user->exempt) || (user->client_sa.sa.sa_family != AF_INET) || !DNS)
357 if (!user->MyClass->config->getBool("usednsbl", true))
361 ServerInstance->Logs->Log("m_dnsbl", LOG_DEBUG, "User has no connect class in OnSetUserIP");
363 unsigned char a, b, c, d;
364 d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
365 c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
366 b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
367 a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF;
369 const std::string reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
371 countExt.set(user, DNSBLConfEntries.size());
373 // For each DNSBL, we will run through this lookup
374 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
376 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
377 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
379 /* now we'd need to fire off lookups for `hostname'. */
380 DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
383 this->DNS->Process(r);
385 catch (DNS::Exception &ex)
388 ServerInstance->Logs->Log("m_dnsbl", LOG_DEBUG, std::string(ex.GetReason()));
396 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass)
399 if (!myclass->config->readString("dnsbl", dnsbl))
400 return MOD_RES_PASSTHRU;
401 std::string* match = nameExt.get(user);
402 std::string myname = match ? *match : "";
404 return MOD_RES_PASSTHRU;
408 ModResult OnCheckReady(LocalUser *user)
410 if (countExt.get(user))
412 return MOD_RES_PASSTHRU;
415 ModResult OnStats(char symbol, User* user, string_list &results)
418 return MOD_RES_PASSTHRU;
420 unsigned long total_hits = 0, total_misses = 0;
422 for (std::vector<DNSBLConfEntry*>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
424 total_hits += (*i)->stats_hits;
425 total_misses += (*i)->stats_misses;
427 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
428 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
431 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
432 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
434 return MOD_RES_PASSTHRU;
438 MODULE_INIT(ModuleDNSBL)