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