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