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