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