]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
d1ca800b36fcebfd34bddef7e631b0e67baa0a2c
[user/henk/code/inspircd.git] / src / modules / m_dnsbl.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
9  *
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.
13  *
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
17  * details.
18  *
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/>.
21  */
22
23
24 #include "inspircd.h"
25 #include "xline.h"
26 #include "modules/dns.h"
27 #include "modules/stats.h"
28
29 /* Class holding data for a single entry */
30 class DNSBLConfEntry : public refcountbase
31 {
32         public:
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;
37                 EnumType type;
38                 unsigned long duration;
39                 unsigned int bitmask;
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) {}
43 };
44
45
46 /** Resolver for CGI:IRC hostnames encoded in ident/real name
47  */
48 class DNSBLResolver : public DNS::Request
49 {
50         std::string theiruid;
51         LocalStringExt& nameExt;
52         LocalIntExt& countExt;
53         reference<DNSBLConfEntry> ConfEntry;
54
55  public:
56
57         DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf)
58                 : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf)
59         {
60         }
61
62         /* Note: This may be called multiple times for multiple A record results */
63         void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
64         {
65                 /* Check the user still exists */
66                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
67                 if (!them)
68                         return;
69
70                 const DNS::ResourceRecord* const ans_record = r->FindAnswerOfType(DNS::QUERY_A);
71                 if (!ans_record)
72                         return;
73
74                 // All replies should be in 127.0.0.0/8
75                 if (ans_record->rdata.compare(0, 4, "127.") != 0)
76                 {
77                         ServerInstance->SNO->WriteGlobalSno('d', "DNSBL: %s returned address outside of acceptable subnet 127.0.0.0/8: %s", ConfEntry->domain.c_str(), ans_record->rdata.c_str());
78                         ConfEntry->stats_misses++;
79                         return;
80                 }
81
82                 int i = countExt.get(them);
83                 if (i)
84                         countExt.set(them, i - 1);
85
86                 // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
87
88                 unsigned int bitmask = 0, record = 0;
89                 bool match = false;
90                 in_addr resultip;
91
92                 inet_pton(AF_INET, ans_record->rdata.c_str(), &resultip);
93
94                 switch (ConfEntry->type)
95                 {
96                         case DNSBLConfEntry::A_BITMASK:
97                                 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
98                                 bitmask &= ConfEntry->bitmask;
99                                 match = (bitmask != 0);
100                         break;
101                         case DNSBLConfEntry::A_RECORD:
102                                 record = resultip.s_addr >> 24; /* Last octet */
103                                 match = (ConfEntry->records[record] == 1);
104                         break;
105                 }
106
107                 if (match)
108                 {
109                         std::string reason = ConfEntry->reason;
110                         std::string::size_type x = reason.find("%ip%");
111                         while (x != std::string::npos)
112                         {
113                                 reason.erase(x, 4);
114                                 reason.insert(x, them->GetIPString());
115                                 x = reason.find("%ip%");
116                         }
117
118                         ConfEntry->stats_hits++;
119
120                         switch (ConfEntry->banaction)
121                         {
122                                 case DNSBLConfEntry::I_KILL:
123                                 {
124                                         ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
125                                         break;
126                                 }
127                                 case DNSBLConfEntry::I_MARK:
128                                 {
129                                         if (!ConfEntry->ident.empty())
130                                         {
131                                                 them->WriteNotice("Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
132                                                 them->ChangeIdent(ConfEntry->ident);
133                                         }
134
135                                         if (!ConfEntry->host.empty())
136                                         {
137                                                 them->WriteNotice("Your host has been set to " + ConfEntry->host + " because you matched " + reason);
138                                                 them->ChangeDisplayedHost(ConfEntry->host);
139                                         }
140
141                                         nameExt.set(them, ConfEntry->name);
142                                         break;
143                                 }
144                                 case DNSBLConfEntry::I_KLINE:
145                                 {
146                                         KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
147                                                         "*", them->GetIPString());
148                                         if (ServerInstance->XLines->AddLine(kl,NULL))
149                                         {
150                                                 std::string timestr = InspIRCd::TimeString(kl->expiry);
151                                                 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
152                                                         them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
153                                                 ServerInstance->XLines->ApplyLines();
154                                         }
155                                         else
156                                         {
157                                                 delete kl;
158                                                 return;
159                                         }
160                                         break;
161                                 }
162                                 case DNSBLConfEntry::I_GLINE:
163                                 {
164                                         GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
165                                                         "*", them->GetIPString());
166                                         if (ServerInstance->XLines->AddLine(gl,NULL))
167                                         {
168                                                 std::string timestr = InspIRCd::TimeString(gl->expiry);
169                                                 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
170                                                         them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
171                                                 ServerInstance->XLines->ApplyLines();
172                                         }
173                                         else
174                                         {
175                                                 delete gl;
176                                                 return;
177                                         }
178                                         break;
179                                 }
180                                 case DNSBLConfEntry::I_ZLINE:
181                                 {
182                                         ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
183                                                         them->GetIPString());
184                                         if (ServerInstance->XLines->AddLine(zl,NULL))
185                                         {
186                                                 std::string timestr = InspIRCd::TimeString(zl->expiry);
187                                                 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on %s to expire on %s: %s",
188                                                         them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
189                                                 ServerInstance->XLines->ApplyLines();
190                                         }
191                                         else
192                                         {
193                                                 delete zl;
194                                                 return;
195                                         }
196                                         break;
197                                 }
198                                 case DNSBLConfEntry::I_UNKNOWN:
199                                 default:
200                                         break;
201                         }
202
203                         ServerInstance->SNO->WriteGlobalSno('d', "Connecting user %s (%s) detected as being on the '%s' DNS blacklist with result %d",
204                                 them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), (ConfEntry->type==DNSBLConfEntry::A_BITMASK) ? bitmask : record);
205                 }
206                 else
207                         ConfEntry->stats_misses++;
208         }
209
210         void OnError(const DNS::Query *q) CXX11_OVERRIDE
211         {
212                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
213                 if (!them)
214                         return;
215
216                 int i = countExt.get(them);
217                 if (i)
218                         countExt.set(them, i - 1);
219
220                 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
221                 {
222                         ConfEntry->stats_misses++;
223                         return;
224                 }
225
226                 ServerInstance->SNO->WriteGlobalSno('d', "An error occurred whilst checking whether %s (%s) is on the '%s' DNS blacklist: %s",
227                         them->GetFullRealHost().c_str(), them->GetIPString().c_str(), ConfEntry->name.c_str(), this->manager->GetErrorStr(q->error).c_str());
228         }
229 };
230
231 typedef std::vector<reference<DNSBLConfEntry> > DNSBLConfList;
232
233 class ModuleDNSBL : public Module, public Stats::EventListener
234 {
235         DNSBLConfList DNSBLConfEntries;
236         dynamic_reference<DNS::Manager> DNS;
237         LocalStringExt nameExt;
238         LocalIntExt countExt;
239
240         /*
241          *      Convert a string to EnumBanaction
242          */
243         DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
244         {
245                 if(action.compare("KILL")==0)
246                         return DNSBLConfEntry::I_KILL;
247                 if(action.compare("KLINE")==0)
248                         return DNSBLConfEntry::I_KLINE;
249                 if(action.compare("ZLINE")==0)
250                         return DNSBLConfEntry::I_ZLINE;
251                 if(action.compare("GLINE")==0)
252                         return DNSBLConfEntry::I_GLINE;
253                 if(action.compare("MARK")==0)
254                         return DNSBLConfEntry::I_MARK;
255
256                 return DNSBLConfEntry::I_UNKNOWN;
257         }
258  public:
259         ModuleDNSBL()
260                 : Stats::EventListener(this)
261                 , DNS(this, "DNS")
262                 , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this)
263                 , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this)
264         {
265         }
266
267         void init() CXX11_OVERRIDE
268         {
269                 ServerInstance->SNO->EnableSnomask('d', "DNSBL");
270         }
271
272         Version GetVersion() CXX11_OVERRIDE
273         {
274                 return Version("Provides handling of DNS blacklists", VF_VENDOR);
275         }
276
277         /** Fill our conf vector with data
278          */
279         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
280         {
281                 DNSBLConfList newentries;
282
283                 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
284                 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
285                 {
286                         ConfigTag* tag = i->second;
287                         reference<DNSBLConfEntry> e = new DNSBLConfEntry();
288
289                         e->name = tag->getString("name");
290                         e->ident = tag->getString("ident");
291                         e->host = tag->getString("host");
292                         e->reason = tag->getString("reason");
293                         e->domain = tag->getString("domain");
294
295                         if (stdalgo::string::equalsci(tag->getString("type"), "bitmask"))
296                         {
297                                 e->type = DNSBLConfEntry::A_BITMASK;
298                                 e->bitmask = tag->getUInt("bitmask", 0, 0, UINT_MAX);
299                         }
300                         else
301                         {
302                                 memset(e->records, 0, sizeof(e->records));
303                                 e->type = DNSBLConfEntry::A_RECORD;
304                                 irc::portparser portrange(tag->getString("records"), false);
305                                 long item = -1;
306                                 while ((item = portrange.GetToken()))
307                                         e->records[item] = 1;
308                         }
309
310                         e->banaction = str2banaction(tag->getString("action"));
311                         e->duration = tag->getDuration("duration", 60, 1);
312
313                         /* Use portparser for record replies */
314
315                         /* yeah, logic here is a little messy */
316                         if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
317                         {
318                                 throw ModuleException("Invalid <dnsbl:bitmask> at " + tag->getTagLocation());
319                         }
320                         else if (e->name.empty())
321                         {
322                                 throw ModuleException("Empty <dnsbl:name> at " + tag->getTagLocation());
323                         }
324                         else if (e->domain.empty())
325                         {
326                                 throw ModuleException("Empty <dnsbl:domain> at " + tag->getTagLocation());
327                         }
328                         else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
329                         {
330                                 throw ModuleException("Unknown <dnsbl:action> at " + tag->getTagLocation());
331                         }
332                         else
333                         {
334                                 if (e->reason.empty())
335                                 {
336                                         std::string location = tag->getTagLocation();
337                                         ServerInstance->SNO->WriteGlobalSno('d', "DNSBL(%s): empty reason, using defaults", location.c_str());
338                                         e->reason = "Your IP has been blacklisted.";
339                                 }
340
341                                 /* add it, all is ok */
342                                 newentries.push_back(e);
343                         }
344                 }
345
346                 DNSBLConfEntries.swap(newentries);
347         }
348
349         void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
350         {
351                 if ((user->exempt) || !DNS)
352                         return;
353
354                 // Clients can't be in a DNSBL if they aren't connected via IPv4 or IPv6.
355                 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
356                         return;
357
358                 if (user->MyClass)
359                 {
360                         if (!user->MyClass->config->getBool("usednsbl", true))
361                                 return;
362                 }
363                 else
364                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP");
365
366                 std::string reversedip;
367                 if (user->client_sa.family() == AF_INET)
368                 {
369                         unsigned int a, b, c, d;
370                         d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
371                         c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
372                         b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
373                         a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF;
374
375                         reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
376                 }
377                 else if (user->client_sa.family() == AF_INET6)
378                 {
379                         const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr;
380
381                         std::string buf = BinToHex(ip, 16);
382                         for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it)
383                         {
384                                 reversedip.push_back(*it);
385                                 reversedip.push_back('.');
386                         }
387                 }
388                 else
389                         return;
390
391                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str());
392
393                 countExt.set(user, DNSBLConfEntries.size());
394
395                 // For each DNSBL, we will run through this lookup
396                 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
397                 {
398                         // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
399                         std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
400
401                         /* now we'd need to fire off lookups for `hostname'. */
402                         DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
403                         try
404                         {
405                                 this->DNS->Process(r);
406                         }
407                         catch (DNS::Exception &ex)
408                         {
409                                 delete r;
410                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
411                         }
412
413                         if (user->quitting)
414                                 break;
415                 }
416         }
417
418         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
419         {
420                 std::string dnsbl;
421                 if (!myclass->config->readString("dnsbl", dnsbl))
422                         return MOD_RES_PASSTHRU;
423                 std::string* match = nameExt.get(user);
424                 std::string myname = match ? *match : "";
425                 if (dnsbl == myname)
426                         return MOD_RES_PASSTHRU;
427                 return MOD_RES_DENY;
428         }
429
430         ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
431         {
432                 if (countExt.get(user))
433                         return MOD_RES_DENY;
434                 return MOD_RES_PASSTHRU;
435         }
436
437         ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
438         {
439                 if (stats.GetSymbol() != 'd')
440                         return MOD_RES_PASSTHRU;
441
442                 unsigned long total_hits = 0, total_misses = 0;
443
444                 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
445                 {
446                         total_hits += (*i)->stats_hits;
447                         total_misses += (*i)->stats_misses;
448
449                         stats.AddRow(304, "DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
450                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
451                 }
452
453                 stats.AddRow(304, "DNSBLSTATS Total hits: " + ConvToStr(total_hits));
454                 stats.AddRow(304, "DNSBLSTATS Total misses: " + ConvToStr(total_misses));
455
456                 return MOD_RES_PASSTHRU;
457         }
458 };
459
460 MODULE_INIT(ModuleDNSBL)