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