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