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/>.
27 /* $ModDesc: Provides handling of DNS blacklists */
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;
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) {}
47 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
49 class DNSBLResolver : public Resolver
52 LocalStringExt& nameExt;
53 LocalIntExt& countExt;
54 reference<DNSBLConfEntry> ConfEntry;
58 DNSBLResolver(Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf, bool &cached)
59 : Resolver(hostname, DNS_QUERY_A, cached, me), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf)
63 /* Note: This may be called multiple times for multiple A record results */
64 virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
66 /* Check the user still exists */
67 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
70 int i = countExt.get(them);
72 countExt.set(them, i - 1);
73 // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
76 unsigned int bitmask = 0, record = 0;
80 inet_aton(result.c_str(), &resultip);
82 switch (ConfEntry->type)
84 case DNSBLConfEntry::A_BITMASK:
85 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
86 bitmask &= ConfEntry->bitmask;
87 match = (bitmask != 0);
89 case DNSBLConfEntry::A_RECORD:
90 record = resultip.s_addr >> 24; /* Last octet */
91 match = (ConfEntry->records[record] == 1);
97 std::string reason = ConfEntry->reason;
98 std::string::size_type x = reason.find("%ip%");
99 while (x != std::string::npos)
102 reason.insert(x, them->GetIPString());
103 x = reason.find("%ip%");
106 ConfEntry->stats_hits++;
108 switch (ConfEntry->banaction)
110 case DNSBLConfEntry::I_KILL:
112 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
115 case DNSBLConfEntry::I_MARK:
117 if (!ConfEntry->ident.empty())
119 them->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
120 them->ChangeIdent(ConfEntry->ident.c_str());
123 if (!ConfEntry->host.empty())
125 them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason);
126 them->ChangeDisplayedHost(ConfEntry->host.c_str());
129 nameExt.set(them, ConfEntry->name);
132 case DNSBLConfEntry::I_KLINE:
134 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
135 "*", them->GetIPString());
136 if (ServerInstance->XLines->AddLine(kl,NULL))
138 std::string timestr = ServerInstance->TimeString(kl->expiry);
139 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
140 them->GetIPString(), timestr.c_str(), reason.c_str());
141 ServerInstance->XLines->ApplyLines();
147 case DNSBLConfEntry::I_GLINE:
149 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
150 "*", them->GetIPString());
151 if (ServerInstance->XLines->AddLine(gl,NULL))
153 std::string timestr = ServerInstance->TimeString(gl->expiry);
154 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
155 them->GetIPString(), timestr.c_str(), reason.c_str());
156 ServerInstance->XLines->ApplyLines();
162 case DNSBLConfEntry::I_ZLINE:
164 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
165 them->GetIPString());
166 if (ServerInstance->XLines->AddLine(zl,NULL))
168 std::string timestr = ServerInstance->TimeString(zl->expiry);
169 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
170 them->GetIPString(), timestr.c_str(), reason.c_str());
171 ServerInstance->XLines->ApplyLines();
177 case DNSBLConfEntry::I_UNKNOWN:
184 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);
187 ConfEntry->stats_misses++;
190 ConfEntry->stats_misses++;
194 virtual void OnError(ResolverError e, const std::string &errormessage)
196 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
199 int i = countExt.get(them);
201 countExt.set(them, i - 1);
205 virtual ~DNSBLResolver()
210 class ModuleDNSBL : public Module
212 std::vector<reference<DNSBLConfEntry> > DNSBLConfEntries;
213 LocalStringExt nameExt;
214 LocalIntExt countExt;
217 * Convert a string to EnumBanaction
219 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
221 if(action.compare("KILL")==0)
222 return DNSBLConfEntry::I_KILL;
223 if(action.compare("KLINE")==0)
224 return DNSBLConfEntry::I_KLINE;
225 if(action.compare("ZLINE")==0)
226 return DNSBLConfEntry::I_ZLINE;
227 if(action.compare("GLINE")==0)
228 return DNSBLConfEntry::I_GLINE;
229 if(action.compare("MARK")==0)
230 return DNSBLConfEntry::I_MARK;
232 return DNSBLConfEntry::I_UNKNOWN;
235 ModuleDNSBL() : nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
240 ServerInstance->Modules->AddService(nameExt);
241 ServerInstance->Modules->AddService(countExt);
242 Implementation eventlist[] = { I_OnRehash, I_OnSetUserIP, I_OnStats, I_OnSetConnectClass, I_OnCheckReady };
243 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
248 return Version("Provides handling of DNS blacklists", VF_VENDOR);
251 /** Fill our conf vector with data
255 DNSBLConfEntries.clear();
257 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
258 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
260 ConfigTag* tag = i->second;
261 reference<DNSBLConfEntry> e = new DNSBLConfEntry();
263 e->name = tag->getString("name");
264 e->ident = tag->getString("ident");
265 e->host = tag->getString("host");
266 e->reason = tag->getString("reason");
267 e->domain = tag->getString("domain");
269 if (tag->getString("type") == "bitmask")
271 e->type = DNSBLConfEntry::A_BITMASK;
272 e->bitmask = tag->getInt("bitmask");
276 memset(e->records, 0, sizeof(e->records));
277 e->type = DNSBLConfEntry::A_RECORD;
278 irc::portparser portrange(tag->getString("records"), false);
280 while ((item = portrange.GetToken()))
281 e->records[item] = 1;
284 e->banaction = str2banaction(tag->getString("action"));
285 e->duration = ServerInstance->Duration(tag->getString("duration", "60"));
287 /* Use portparser for record replies */
289 /* yeah, logic here is a little messy */
290 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
292 std::string location = tag->getTagLocation();
293 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): invalid bitmask", location.c_str());
295 else if (e->name.empty())
297 std::string location = tag->getTagLocation();
298 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid name", location.c_str());
300 else if (e->domain.empty())
302 std::string location = tag->getTagLocation();
303 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid domain", location.c_str());
305 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
307 std::string location = tag->getTagLocation();
308 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid banaction", location.c_str());
310 else if (e->duration <= 0)
312 std::string location = tag->getTagLocation();
313 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid duration", location.c_str());
317 if (e->reason.empty())
319 std::string location = tag->getTagLocation();
320 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): empty reason, using defaults", location.c_str());
321 e->reason = "Your IP has been blacklisted.";
324 /* add it, all is ok */
325 DNSBLConfEntries.push_back(e);
330 void OnRehash(User* user)
335 void OnSetUserIP(LocalUser* user)
337 if ((user->exempt) || (user->client_sa.sa.sa_family != AF_INET))
342 if (!user->MyClass->config->getBool("usednsbl", true))
346 ServerInstance->Logs->Log("m_dnsbl", DEBUG, "User has no connect class in OnSetUserIP");
348 unsigned char a, b, c, d;
349 char reversedipbuf[128];
350 std::string reversedip;
352 d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
353 c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
354 b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
355 a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF;
357 snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
358 reversedip = std::string(reversedipbuf);
360 countExt.set(user, DNSBLConfEntries.size());
362 // For each DNSBL, we will run through this lookup
364 while (i < DNSBLConfEntries.size())
366 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
367 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
369 /* now we'd need to fire off lookups for `hostname'. */
371 DNSBLResolver *r = new DNSBLResolver(this, nameExt, countExt, hostname, user, DNSBLConfEntries[i], cached);
372 ServerInstance->AddResolver(r, cached);
379 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass)
382 if (!myclass->config->readString("dnsbl", dnsbl))
383 return MOD_RES_PASSTHRU;
384 std::string* match = nameExt.get(user);
385 std::string myname = match ? *match : "";
387 return MOD_RES_PASSTHRU;
391 ModResult OnCheckReady(LocalUser *user)
393 if (countExt.get(user))
395 return MOD_RES_PASSTHRU;
398 ModResult OnStats(char symbol, User* user, string_list &results)
401 return MOD_RES_PASSTHRU;
403 unsigned long total_hits = 0, total_misses = 0;
405 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
407 total_hits += (*i)->stats_hits;
408 total_misses += (*i)->stats_misses;
410 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
411 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
414 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
415 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
417 return MOD_RES_PASSTHRU;
421 MODULE_INIT(ModuleDNSBL)