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/>.
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
34 /* $ModDesc: Provides handling of DNS blacklists */
36 /* Class holding data for a single entry */
40 enum EnumBanaction { I_UNKNOWN, I_KILL, I_ZLINE, I_KLINE, I_GLINE, I_MARK };
41 enum EnumType { A_RECORD, A_BITMASK };
42 std::string name, ident, host, domain, reason;
43 EnumBanaction banaction;
47 unsigned char records[256];
48 unsigned long stats_hits, stats_misses;
49 DNSBLConfEntry(): type(A_BITMASK),duration(86400),bitmask(0),stats_hits(0), stats_misses(0) {}
54 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
56 class DNSBLResolver : public Resolver
59 LocalStringExt& nameExt;
60 LocalIntExt& countExt;
61 DNSBLConfEntry *ConfEntry;
65 DNSBLResolver(Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, DNSBLConfEntry *conf, bool &cached)
66 : Resolver(hostname, DNS_QUERY_A, cached, me), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf)
70 /* Note: This may be called multiple times for multiple A record results */
71 virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
73 /* Check the user still exists */
74 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
77 int i = countExt.get(them);
79 countExt.set(them, i - 1);
80 // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
83 unsigned int bitmask = 0, record = 0;
87 inet_aton(result.c_str(), &resultip);
89 switch (ConfEntry->type)
91 case DNSBLConfEntry::A_BITMASK:
92 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
93 bitmask &= ConfEntry->bitmask;
94 match = (bitmask != 0);
96 case DNSBLConfEntry::A_RECORD:
97 record = resultip.s_addr >> 24; /* Last octet */
98 match = (ConfEntry->records[record] == 1);
104 std::string reason = ConfEntry->reason;
105 std::string::size_type x = reason.find("%ip%");
106 while (x != std::string::npos)
109 reason.insert(x, them->GetIPString());
110 x = reason.find("%ip%");
113 ConfEntry->stats_hits++;
115 switch (ConfEntry->banaction)
117 case DNSBLConfEntry::I_KILL:
119 ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
122 case DNSBLConfEntry::I_MARK:
124 if (!ConfEntry->ident.empty())
126 them->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
127 them->ChangeIdent(ConfEntry->ident.c_str());
130 if (!ConfEntry->host.empty())
132 them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason);
133 them->ChangeDisplayedHost(ConfEntry->host.c_str());
136 nameExt.set(them, ConfEntry->name);
139 case DNSBLConfEntry::I_KLINE:
141 KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
142 "*", them->GetIPString());
143 if (ServerInstance->XLines->AddLine(kl,NULL))
145 std::string timestr = ServerInstance->TimeString(kl->expiry);
146 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
147 them->GetIPString(), timestr.c_str(), reason.c_str());
148 ServerInstance->XLines->ApplyLines();
154 case DNSBLConfEntry::I_GLINE:
156 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
157 "*", them->GetIPString());
158 if (ServerInstance->XLines->AddLine(gl,NULL))
160 std::string timestr = ServerInstance->TimeString(gl->expiry);
161 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
162 them->GetIPString(), timestr.c_str(), reason.c_str());
163 ServerInstance->XLines->ApplyLines();
169 case DNSBLConfEntry::I_ZLINE:
171 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
172 them->GetIPString());
173 if (ServerInstance->XLines->AddLine(zl,NULL))
175 std::string timestr = ServerInstance->TimeString(zl->expiry);
176 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
177 them->GetIPString(), timestr.c_str(), reason.c_str());
178 ServerInstance->XLines->ApplyLines();
184 case DNSBLConfEntry::I_UNKNOWN:
191 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);
194 ConfEntry->stats_misses++;
197 ConfEntry->stats_misses++;
201 virtual void OnError(ResolverError e, const std::string &errormessage)
203 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
206 int i = countExt.get(them);
208 countExt.set(them, i - 1);
212 virtual ~DNSBLResolver()
217 class ModuleDNSBL : public Module
219 std::vector<DNSBLConfEntry *> DNSBLConfEntries;
220 LocalStringExt nameExt;
221 LocalIntExt countExt;
224 * Convert a string to EnumBanaction
226 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
228 if(action.compare("KILL")==0)
229 return DNSBLConfEntry::I_KILL;
230 if(action.compare("KLINE")==0)
231 return DNSBLConfEntry::I_KLINE;
232 if(action.compare("ZLINE")==0)
233 return DNSBLConfEntry::I_ZLINE;
234 if(action.compare("GLINE")==0)
235 return DNSBLConfEntry::I_GLINE;
236 if(action.compare("MARK")==0)
237 return DNSBLConfEntry::I_MARK;
239 return DNSBLConfEntry::I_UNKNOWN;
242 ModuleDNSBL() : nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
247 ServerInstance->Modules->AddService(nameExt);
248 ServerInstance->Modules->AddService(countExt);
249 Implementation eventlist[] = { I_OnRehash, I_OnSetUserIP, I_OnStats, I_OnSetConnectClass, I_OnCheckReady };
250 ServerInstance->Modules->Attach(eventlist, this, 5);
253 virtual ~ModuleDNSBL()
260 return Version("Provides handling of DNS blacklists", VF_VENDOR);
263 /** Clear entries and free the mem it was using
267 for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
269 DNSBLConfEntries.clear();
272 /** Fill our conf vector with data
278 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
279 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
281 ConfigTag* tag = i->second;
282 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 (tag->getString("type") == "bitmask")
292 e->type = DNSBLConfEntry::A_BITMASK;
293 e->bitmask = tag->getInt("bitmask");
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 = ServerInstance->Duration(tag->getString("duration", "60"));
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('a', "DNSBL(%s): invalid bitmask", location.c_str());
316 else if (e->name.empty())
318 std::string location = tag->getTagLocation();
319 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid name", location.c_str());
321 else if (e->domain.empty())
323 std::string location = tag->getTagLocation();
324 ServerInstance->SNO->WriteGlobalSno('a', "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('a', "DNSBL(%s): Invalid banaction", location.c_str());
331 else if (e->duration <= 0)
333 std::string location = tag->getTagLocation();
334 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid duration", location.c_str());
338 if (e->reason.empty())
340 std::string location = tag->getTagLocation();
341 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): empty reason, using defaults", location.c_str());
342 e->reason = "Your IP has been blacklisted.";
345 /* add it, all is ok */
346 DNSBLConfEntries.push_back(e);
350 /* delete and drop it, error somewhere */
355 void OnRehash(User* user)
360 void OnSetUserIP(LocalUser* user)
365 unsigned char a, b, c, d;
366 char reversedipbuf[128];
367 std::string reversedip;
369 if (user->client_sa.sa.sa_family != AF_INET)
372 d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
373 c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
374 b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
375 a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF;
377 snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
378 reversedip = std::string(reversedipbuf);
380 // For each DNSBL, we will run through this lookup
382 while (i < DNSBLConfEntries.size())
384 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
385 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
387 /* now we'd need to fire off lookups for `hostname'. */
389 DNSBLResolver *r = new DNSBLResolver(this, nameExt, countExt, hostname, user, DNSBLConfEntries[i], cached);
390 ServerInstance->AddResolver(r, cached);
393 countExt.set(user, i);
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(std::string(ServerInstance->Config->ServerName.c_str()) + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
428 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
431 results.push_back(std::string(ServerInstance->Config->ServerName.c_str()) + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
432 results.push_back(std::string(ServerInstance->Config->ServerName.c_str()) + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
434 return MOD_RES_PASSTHRU;
438 MODULE_INIT(ModuleDNSBL)