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, std::string("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 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
146 them->GetIPString(), ServerInstance->TimeString(kl->expiry).c_str(), reason.c_str());
147 ServerInstance->XLines->ApplyLines();
153 case DNSBLConfEntry::I_GLINE:
155 GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
156 "*", them->GetIPString());
157 if (ServerInstance->XLines->AddLine(gl,NULL))
159 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
160 them->GetIPString(), ServerInstance->TimeString(gl->expiry).c_str(), reason.c_str());
161 ServerInstance->XLines->ApplyLines();
167 case DNSBLConfEntry::I_ZLINE:
169 ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
170 them->GetIPString());
171 if (ServerInstance->XLines->AddLine(zl,NULL))
173 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
174 them->GetIPString(), ServerInstance->TimeString(zl->expiry).c_str(), reason.c_str());
175 ServerInstance->XLines->ApplyLines();
181 case DNSBLConfEntry::I_UNKNOWN:
188 ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s detected as being on a DNS blacklist (%s) with result %d", them->GetFullRealHost().c_str(), ConfEntry->domain.c_str(), (ConfEntry->type==DNSBLConfEntry::A_BITMASK) ? bitmask : record);
191 ConfEntry->stats_misses++;
194 ConfEntry->stats_misses++;
198 virtual void OnError(ResolverError e, const std::string &errormessage)
200 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
203 int i = countExt.get(them);
205 countExt.set(them, i - 1);
209 virtual ~DNSBLResolver()
214 class ModuleDNSBL : public Module
216 std::vector<DNSBLConfEntry *> DNSBLConfEntries;
217 LocalStringExt nameExt;
218 LocalIntExt countExt;
221 * Convert a string to EnumBanaction
223 DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
225 if(action.compare("KILL")==0)
226 return DNSBLConfEntry::I_KILL;
227 if(action.compare("KLINE")==0)
228 return DNSBLConfEntry::I_KLINE;
229 if(action.compare("ZLINE")==0)
230 return DNSBLConfEntry::I_ZLINE;
231 if(action.compare("GLINE")==0)
232 return DNSBLConfEntry::I_GLINE;
233 if(action.compare("MARK")==0)
234 return DNSBLConfEntry::I_MARK;
236 return DNSBLConfEntry::I_UNKNOWN;
239 ModuleDNSBL() : nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
244 ServerInstance->Modules->AddService(nameExt);
245 ServerInstance->Modules->AddService(countExt);
246 Implementation eventlist[] = { I_OnRehash, I_OnUserInit, I_OnStats, I_OnSetConnectClass, I_OnCheckReady };
247 ServerInstance->Modules->Attach(eventlist, this, 5);
250 virtual ~ModuleDNSBL()
257 return Version("Provides handling of DNS blacklists", VF_VENDOR);
260 /** Clear entries and free the mem it was using
264 for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
266 DNSBLConfEntries.clear();
269 /** Fill our conf vector with data
275 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
276 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
278 ConfigTag* tag = i->second;
279 DNSBLConfEntry *e = new DNSBLConfEntry();
281 e->name = tag->getString("name");
282 e->ident = tag->getString("ident");
283 e->host = tag->getString("host");
284 e->reason = tag->getString("reason");
285 e->domain = tag->getString("domain");
287 if (tag->getString("type") == "bitmask")
289 e->type = DNSBLConfEntry::A_BITMASK;
290 e->bitmask = tag->getInt("bitmask");
294 memset(e->records, 0, sizeof(e->records));
295 e->type = DNSBLConfEntry::A_RECORD;
296 irc::portparser portrange(tag->getString("records"), false);
298 while ((item = portrange.GetToken()))
299 e->records[item] = 1;
302 e->banaction = str2banaction(tag->getString("action"));
303 e->duration = ServerInstance->Duration(tag->getString("duration", "60"));
305 /* Use portparser for record replies */
307 /* yeah, logic here is a little messy */
308 if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
310 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): invalid bitmask",tag->getTagLocation().c_str());
312 else if (e->name.empty())
314 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid name",tag->getTagLocation().c_str());
316 else if (e->domain.empty())
318 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid domain",tag->getTagLocation().c_str());
320 else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
322 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid banaction",tag->getTagLocation().c_str());
324 else if (e->duration <= 0)
326 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid duration",tag->getTagLocation().c_str());
330 if (e->reason.empty())
332 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): empty reason, using defaults",tag->getTagLocation().c_str());
333 e->reason = "Your IP has been blacklisted.";
336 /* add it, all is ok */
337 DNSBLConfEntries.push_back(e);
341 /* delete and drop it, error somewhere */
346 void OnRehash(User* user)
351 void OnUserInit(LocalUser* user)
356 unsigned char a, b, c, d;
357 char reversedipbuf[128];
358 std::string reversedip;
360 if (user->client_sa.sa.sa_family != AF_INET)
363 d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
364 c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
365 b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
366 a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF;
368 snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
369 reversedip = std::string(reversedipbuf);
371 // For each DNSBL, we will run through this lookup
373 while (i < DNSBLConfEntries.size())
375 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
376 std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
378 /* now we'd need to fire off lookups for `hostname'. */
380 DNSBLResolver *r = new DNSBLResolver(this, nameExt, countExt, hostname, user, DNSBLConfEntries[i], cached);
381 ServerInstance->AddResolver(r, cached);
384 countExt.set(user, i);
387 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass)
390 if (!myclass->config->readString("dnsbl", dnsbl))
391 return MOD_RES_PASSTHRU;
392 std::string* match = nameExt.get(user);
393 std::string myname = match ? *match : "";
395 return MOD_RES_PASSTHRU;
399 ModResult OnCheckReady(LocalUser *user)
401 if (countExt.get(user))
403 return MOD_RES_PASSTHRU;
406 ModResult OnStats(char symbol, User* user, string_list &results)
409 return MOD_RES_PASSTHRU;
411 unsigned long total_hits = 0, total_misses = 0;
413 for (std::vector<DNSBLConfEntry*>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
415 total_hits += (*i)->stats_hits;
416 total_misses += (*i)->stats_misses;
418 results.push_back(std::string(ServerInstance->Config->ServerName.c_str()) + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
419 ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
422 results.push_back(std::string(ServerInstance->Config->ServerName.c_str()) + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
423 results.push_back(std::string(ServerInstance->Config->ServerName.c_str()) + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
425 return MOD_RES_PASSTHRU;
429 MODULE_INIT(ModuleDNSBL)