]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
Update wiki links to use HTTPS and point to the correct pages.
[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
27 /* $ModDesc: Provides handling of DNS blacklists */
28
29 /* Class holding data for a single entry */
30 class DNSBLConfEntry : public refcountbase
31 {
32         public:
33                 enum EnumBanaction { I_UNKNOWN, I_KILL, I_ZLINE, I_KLINE, I_GLINE, I_MARK };
34                 enum EnumType { A_RECORD, A_BITMASK };
35                 std::string name, ident, host, domain, reason;
36                 EnumBanaction banaction;
37                 EnumType type;
38                 long duration;
39                 int bitmask;
40                 unsigned char records[256];
41                 unsigned long stats_hits, stats_misses;
42                 DNSBLConfEntry(): type(A_BITMASK),duration(86400),bitmask(0),stats_hits(0), stats_misses(0) {}
43                 ~DNSBLConfEntry() { }
44 };
45
46
47 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
48  */
49 class DNSBLResolver : public Resolver
50 {
51         std::string theiruid;
52         LocalStringExt& nameExt;
53         LocalIntExt& countExt;
54         reference<DNSBLConfEntry> ConfEntry;
55
56  public:
57
58         DNSBLResolver(Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf, bool &cached)
59                 : Resolver(hostname, DNS_QUERY_A, cached, me), 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         virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
65         {
66                 /* Check the user still exists */
67                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
68                 if (them)
69                 {
70                         int i = countExt.get(them);
71                         if (i)
72                                 countExt.set(them, i - 1);
73                         // All replies should be in 127.0.0.0/8
74                         if (result.compare(0, 4, "127.") == 0)
75                         {
76                                 unsigned int bitmask = 0, record = 0;
77                                 bool match = false;
78                                 in_addr resultip;
79
80                                 inet_aton(result.c_str(), &resultip);
81
82                                 switch (ConfEntry->type)
83                                 {
84                                         case DNSBLConfEntry::A_BITMASK:
85                                                 // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
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(), timestr.c_str(), reason.c_str());
142                                                                 ServerInstance->XLines->ApplyLines();
143                                                         }
144                                                         else
145                                                         {
146                                                                 delete kl;
147                                                                 return;
148                                                         }
149                                                         break;
150                                                 }
151                                                 case DNSBLConfEntry::I_GLINE:
152                                                 {
153                                                         GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
154                                                                         "*", them->GetIPString());
155                                                         if (ServerInstance->XLines->AddLine(gl,NULL))
156                                                         {
157                                                                 std::string timestr = ServerInstance->TimeString(gl->expiry);
158                                                                 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
159                                                                         them->GetIPString(), timestr.c_str(), reason.c_str());
160                                                                 ServerInstance->XLines->ApplyLines();
161                                                         }
162                                                         else
163                                                         {
164                                                                 delete gl;
165                                                                 return;
166                                                         }
167                                                         break;
168                                                 }
169                                                 case DNSBLConfEntry::I_ZLINE:
170                                                 {
171                                                         ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
172                                                                         them->GetIPString());
173                                                         if (ServerInstance->XLines->AddLine(zl,NULL))
174                                                         {
175                                                                 std::string timestr = ServerInstance->TimeString(zl->expiry);
176                                                                 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
177                                                                         them->GetIPString(), timestr.c_str(), reason.c_str());
178                                                                 ServerInstance->XLines->ApplyLines();
179                                                         }
180                                                         else
181                                                         {
182                                                                 delete zl;
183                                                                 return;
184                                                         }
185                                                         break;
186                                                 }
187                                                 case DNSBLConfEntry::I_UNKNOWN:
188                                                 {
189                                                         break;
190                                                 }
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                         else
200                         {
201                                 if (!result.empty())
202                                         ServerInstance->SNO->WriteGlobalSno('a', "DNSBL: %s returned address outside of acceptable subnet 127.0.0.0/8: %s", ConfEntry->domain.c_str(), result.c_str());
203                                 ConfEntry->stats_misses++;
204                         }
205                 }
206         }
207
208         virtual void OnError(ResolverError e, const std::string &errormessage)
209         {
210                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
211                 if (them)
212                 {
213                         int i = countExt.get(them);
214                         if (i)
215                                 countExt.set(them, i - 1);
216                 }
217         }
218
219         virtual ~DNSBLResolver()
220         {
221         }
222 };
223
224 class ModuleDNSBL : public Module
225 {
226         std::vector<reference<DNSBLConfEntry> > DNSBLConfEntries;
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() : nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
250
251         void init()
252         {
253                 ReadConf();
254                 ServerInstance->Modules->AddService(nameExt);
255                 ServerInstance->Modules->AddService(countExt);
256                 Implementation eventlist[] = { I_OnRehash, I_OnSetUserIP, I_OnStats, I_OnSetConnectClass, I_OnCheckReady };
257                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
258         }
259
260         Version GetVersion()
261         {
262                 return Version("Provides handling of DNS blacklists", VF_VENDOR);
263         }
264
265         /** Fill our conf vector with data
266          */
267         void ReadConf()
268         {
269                 DNSBLConfEntries.clear();
270
271                 ConfigTagList dnsbls = ServerInstance->Config->ConfTags("dnsbl");
272                 for(ConfigIter i = dnsbls.first; i != dnsbls.second; ++i)
273                 {
274                         ConfigTag* tag = i->second;
275                         reference<DNSBLConfEntry> e = new DNSBLConfEntry();
276
277                         e->name = tag->getString("name");
278                         e->ident = tag->getString("ident");
279                         e->host = tag->getString("host");
280                         e->reason = tag->getString("reason");
281                         e->domain = tag->getString("domain");
282
283                         if (tag->getString("type") == "bitmask")
284                         {
285                                 e->type = DNSBLConfEntry::A_BITMASK;
286                                 e->bitmask = tag->getInt("bitmask");
287                         }
288                         else
289                         {
290                                 memset(e->records, 0, sizeof(e->records));
291                                 e->type = DNSBLConfEntry::A_RECORD;
292                                 irc::portparser portrange(tag->getString("records"), false);
293                                 long item = -1;
294                                 while ((item = portrange.GetToken()))
295                                         e->records[item] = 1;
296                         }
297
298                         e->banaction = str2banaction(tag->getString("action"));
299                         e->duration = ServerInstance->Duration(tag->getString("duration", "60"));
300
301                         /* Use portparser for record replies */
302
303                         /* yeah, logic here is a little messy */
304                         if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
305                         {
306                                 std::string location = tag->getTagLocation();
307                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): invalid bitmask", location.c_str());
308                         }
309                         else if (e->name.empty())
310                         {
311                                 std::string location = tag->getTagLocation();
312                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid name", location.c_str());
313                         }
314                         else if (e->domain.empty())
315                         {
316                                 std::string location = tag->getTagLocation();
317                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid domain", location.c_str());
318                         }
319                         else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
320                         {
321                                 std::string location = tag->getTagLocation();
322                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid banaction", location.c_str());
323                         }
324                         else if (e->duration <= 0)
325                         {
326                                 std::string location = tag->getTagLocation();
327                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid duration", location.c_str());
328                         }
329                         else
330                         {
331                                 if (e->reason.empty())
332                                 {
333                                         std::string location = tag->getTagLocation();
334                                         ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): empty reason, using defaults", location.c_str());
335                                         e->reason = "Your IP has been blacklisted.";
336                                 }
337
338                                 /* add it, all is ok */
339                                 DNSBLConfEntries.push_back(e);
340                         }
341                 }
342         }
343
344         void OnRehash(User* user)
345         {
346                 ReadConf();
347         }
348
349         void OnSetUserIP(LocalUser* user)
350         {
351                 if ((user->exempt) || (user->client_sa.sa.sa_family != AF_INET))
352                         return;
353
354                 if (user->MyClass)
355                 {
356                         if (!user->MyClass->config->getBool("usednsbl", true))
357                                 return;
358                 }
359                 else
360                         ServerInstance->Logs->Log("m_dnsbl", DEBUG, "User has no connect class in OnSetUserIP");
361
362                 unsigned char a, b, c, d;
363                 char reversedipbuf[128];
364                 std::string reversedip;
365
366                 d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
367                 c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
368                 b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
369                 a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF;
370
371                 snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
372                 reversedip = std::string(reversedipbuf);
373
374                 countExt.set(user, DNSBLConfEntries.size());
375
376                 // For each DNSBL, we will run through this lookup
377                 unsigned int i = 0;
378                 while (i < DNSBLConfEntries.size())
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                         bool cached;
385                         DNSBLResolver *r = new DNSBLResolver(this, nameExt, countExt, hostname, user, DNSBLConfEntries[i], cached);
386                         ServerInstance->AddResolver(r, cached);
387                         if (user->quitting)
388                                 break;
389                         i++;
390                 }
391         }
392
393         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass)
394         {
395                 std::string dnsbl;
396                 if (!myclass->config->readString("dnsbl", dnsbl))
397                         return MOD_RES_PASSTHRU;
398                 std::string* match = nameExt.get(user);
399                 std::string myname = match ? *match : "";
400                 if (dnsbl == myname)
401                         return MOD_RES_PASSTHRU;
402                 return MOD_RES_DENY;
403         }
404         
405         ModResult OnCheckReady(LocalUser *user)
406         {
407                 if (countExt.get(user))
408                         return MOD_RES_DENY;
409                 return MOD_RES_PASSTHRU;
410         }
411
412         ModResult OnStats(char symbol, User* user, string_list &results)
413         {
414                 if (symbol != 'd')
415                         return MOD_RES_PASSTHRU;
416
417                 unsigned long total_hits = 0, total_misses = 0;
418
419                 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
420                 {
421                         total_hits += (*i)->stats_hits;
422                         total_misses += (*i)->stats_misses;
423
424                         results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
425                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
426                 }
427
428                 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
429                 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
430
431                 return MOD_RES_PASSTHRU;
432         }
433 };
434
435 MODULE_INIT(ModuleDNSBL)