]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
Tidy up keywords on module methods.
[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 /* $ModDesc: Provides handling of DNS blacklists */
29
30 /* Class holding data for a single entry */
31 class DNSBLConfEntry
32 {
33         public:
34                 enum EnumBanaction { I_UNKNOWN, I_KILL, I_ZLINE, I_KLINE, I_GLINE, I_MARK };
35                 enum EnumType { A_RECORD, A_BITMASK };
36                 std::string name, ident, host, domain, reason;
37                 EnumBanaction banaction;
38                 EnumType type;
39                 long duration;
40                 int bitmask;
41                 unsigned char records[256];
42                 unsigned long stats_hits, stats_misses;
43                 DNSBLConfEntry(): type(A_BITMASK),duration(86400),bitmask(0),stats_hits(0), stats_misses(0) {}
44 };
45
46
47 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
48  */
49 class DNSBLResolver : public DNS::Request
50 {
51         std::string theiruid;
52         LocalStringExt& nameExt;
53         LocalIntExt& countExt;
54         DNSBLConfEntry *ConfEntry;
55
56  public:
57
58         DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, DNSBLConfEntry *conf)
59                 : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf)
60         {
61         }
62
63         /* Note: This may be called multiple times for multiple A record results */
64         void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
65         {
66                 /* Check the user still exists */
67                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
68                 if (!them)
69                         return;
70
71                 const DNS::ResourceRecord &ans_record = r->answers[0];
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->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
123                                                 them->ChangeIdent(ConfEntry->ident.c_str());
124                                         }
125
126                                         if (!ConfEntry->host.empty())
127                                         {
128                                                 them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason);
129                                                 them->ChangeDisplayedHost(ConfEntry->host.c_str());
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 = ServerInstance->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                                                 delete kl;
148                                         break;
149                                 }
150                                 case DNSBLConfEntry::I_GLINE:
151                                 {
152                                         GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
153                                                         "*", them->GetIPString());
154                                         if (ServerInstance->XLines->AddLine(gl,NULL))
155                                         {
156                                                 std::string timestr = ServerInstance->TimeString(gl->expiry);
157                                                 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
158                                                         them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
159                                                 ServerInstance->XLines->ApplyLines();
160                                         }
161                                         else
162                                                 delete gl;
163                                         break;
164                                 }
165                                 case DNSBLConfEntry::I_ZLINE:
166                                 {
167                                         ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
168                                                         them->GetIPString());
169                                         if (ServerInstance->XLines->AddLine(zl,NULL))
170                                         {
171                                                 std::string timestr = ServerInstance->TimeString(zl->expiry);
172                                                 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
173                                                         them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
174                                                 ServerInstance->XLines->ApplyLines();
175                                         }
176                                         else
177                                                 delete zl;
178                                         break;
179                                 }
180                                 case DNSBLConfEntry::I_UNKNOWN:
181                                 default:
182                                         break;
183                         }
184
185                         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);
186                 }
187                 else
188                         ConfEntry->stats_misses++;
189         }
190
191         void OnError(const DNS::Query *q) CXX11_OVERRIDE
192         {
193                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
194                 if (!them)
195                         return;
196
197                 int i = countExt.get(them);
198                 if (i)
199                         countExt.set(them, i - 1);
200
201                 if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND)
202                         ConfEntry->stats_misses++;
203         }
204 };
205
206 class ModuleDNSBL : public Module
207 {
208         std::vector<DNSBLConfEntry *> DNSBLConfEntries;
209         dynamic_reference<DNS::Manager> DNS;
210         LocalStringExt nameExt;
211         LocalIntExt countExt;
212
213         /*
214          *      Convert a string to EnumBanaction
215          */
216         DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
217         {
218                 if(action.compare("KILL")==0)
219                         return DNSBLConfEntry::I_KILL;
220                 if(action.compare("KLINE")==0)
221                         return DNSBLConfEntry::I_KLINE;
222                 if(action.compare("ZLINE")==0)
223                         return DNSBLConfEntry::I_ZLINE;
224                 if(action.compare("GLINE")==0)
225                         return DNSBLConfEntry::I_GLINE;
226                 if(action.compare("MARK")==0)
227                         return DNSBLConfEntry::I_MARK;
228
229                 return DNSBLConfEntry::I_UNKNOWN;
230         }
231  public:
232         ModuleDNSBL() : DNS(this, "DNS"), nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
233
234         void init() CXX11_OVERRIDE
235         {
236                 ReadConf();
237                 ServerInstance->Modules->AddService(nameExt);
238                 ServerInstance->Modules->AddService(countExt);
239                 Implementation eventlist[] = { I_OnRehash, I_OnSetUserIP, I_OnStats, I_OnSetConnectClass, I_OnCheckReady };
240                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
241         }
242
243         ~ModuleDNSBL()
244         {
245                 ClearEntries();
246         }
247
248         Version GetVersion() CXX11_OVERRIDE
249         {
250                 return Version("Provides handling of DNS blacklists", VF_VENDOR);
251         }
252
253         /** Clear entries and free the mem it was using
254          */
255         void ClearEntries()
256         {
257                 for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
258                         delete *i;
259                 DNSBLConfEntries.clear();
260         }
261
262         /** Fill our conf vector with data
263          */
264         void ReadConf()
265         {
266                 ClearEntries();
267
268                 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
269                 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
270                 {
271                         ConfigTag* tag = i->second;
272                         DNSBLConfEntry *e = new DNSBLConfEntry();
273
274                         e->name = tag->getString("name");
275                         e->ident = tag->getString("ident");
276                         e->host = tag->getString("host");
277                         e->reason = tag->getString("reason");
278                         e->domain = tag->getString("domain");
279
280                         if (tag->getString("type") == "bitmask")
281                         {
282                                 e->type = DNSBLConfEntry::A_BITMASK;
283                                 e->bitmask = tag->getInt("bitmask");
284                         }
285                         else
286                         {
287                                 memset(e->records, 0, sizeof(e->records));
288                                 e->type = DNSBLConfEntry::A_RECORD;
289                                 irc::portparser portrange(tag->getString("records"), false);
290                                 long item = -1;
291                                 while ((item = portrange.GetToken()))
292                                         e->records[item] = 1;
293                         }
294
295                         e->banaction = str2banaction(tag->getString("action"));
296                         e->duration = InspIRCd::Duration(tag->getString("duration", "60"));
297
298                         /* Use portparser for record replies */
299
300                         /* yeah, logic here is a little messy */
301                         if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
302                         {
303                                 std::string location = tag->getTagLocation();
304                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): invalid bitmask", location.c_str());
305                         }
306                         else if (e->name.empty())
307                         {
308                                 std::string location = tag->getTagLocation();
309                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid name", location.c_str());
310                         }
311                         else if (e->domain.empty())
312                         {
313                                 std::string location = tag->getTagLocation();
314                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid domain", location.c_str());
315                         }
316                         else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
317                         {
318                                 std::string location = tag->getTagLocation();
319                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid banaction", location.c_str());
320                         }
321                         else if (e->duration <= 0)
322                         {
323                                 std::string location = tag->getTagLocation();
324                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid duration", location.c_str());
325                         }
326                         else
327                         {
328                                 if (e->reason.empty())
329                                 {
330                                         std::string location = tag->getTagLocation();
331                                         ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): empty reason, using defaults", location.c_str());
332                                         e->reason = "Your IP has been blacklisted.";
333                                 }
334
335                                 /* add it, all is ok */
336                                 DNSBLConfEntries.push_back(e);
337                                 continue;
338                         }
339
340                         /* delete and drop it, error somewhere */
341                         delete e;
342                 }
343         }
344
345         void OnRehash(User* user) CXX11_OVERRIDE
346         {
347                 ReadConf();
348         }
349
350         void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
351         {
352                 if ((user->exempt) || (user->client_sa.sa.sa_family != AF_INET) || !DNS)
353                         return;
354
355                 if (user->MyClass)
356                 {
357                         if (!user->MyClass->config->getBool("usednsbl", true))
358                                 return;
359                 }
360                 else
361                         ServerInstance->Logs->Log("m_dnsbl", LOG_DEBUG, "User has no connect class in OnSetUserIP");
362
363                 unsigned char a, b, c, d;
364                 d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
365                 c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
366                 b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
367                 a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF;
368
369                 const std::string reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a);
370
371                 countExt.set(user, DNSBLConfEntries.size());
372
373                 // For each DNSBL, we will run through this lookup
374                 for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i)
375                 {
376                         // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
377                         std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
378
379                         /* now we'd need to fire off lookups for `hostname'. */
380                         DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]);
381                         try
382                         {
383                                 this->DNS->Process(r);
384                         }
385                         catch (DNS::Exception &ex)
386                         {
387                                 delete r;
388                                 ServerInstance->Logs->Log("m_dnsbl", LOG_DEBUG, std::string(ex.GetReason()));
389                         }
390
391                         if (user->quitting)
392                                 break;
393                 }
394         }
395
396         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
397         {
398                 std::string dnsbl;
399                 if (!myclass->config->readString("dnsbl", dnsbl))
400                         return MOD_RES_PASSTHRU;
401                 std::string* match = nameExt.get(user);
402                 std::string myname = match ? *match : "";
403                 if (dnsbl == myname)
404                         return MOD_RES_PASSTHRU;
405                 return MOD_RES_DENY;
406         }
407
408         ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
409         {
410                 if (countExt.get(user))
411                         return MOD_RES_DENY;
412                 return MOD_RES_PASSTHRU;
413         }
414
415         ModResult OnStats(char symbol, User* user, string_list &results) CXX11_OVERRIDE
416         {
417                 if (symbol != 'd')
418                         return MOD_RES_PASSTHRU;
419
420                 unsigned long total_hits = 0, total_misses = 0;
421
422                 for (std::vector<DNSBLConfEntry*>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
423                 {
424                         total_hits += (*i)->stats_hits;
425                         total_misses += (*i)->stats_misses;
426
427                         results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
428                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
429                 }
430
431                 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
432                 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
433
434                 return MOD_RES_PASSTHRU;
435         }
436 };
437
438 MODULE_INIT(ModuleDNSBL)