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