]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
Add LOG_ prefix to the log level enum values.
[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
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 };
44
45
46 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
47  */
48 class DNSBLResolver : public Resolver
49 {
50         std::string theiruid;
51         LocalStringExt& nameExt;
52         LocalIntExt& countExt;
53         DNSBLConfEntry *ConfEntry;
54
55  public:
56
57         DNSBLResolver(Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, DNSBLConfEntry *conf, bool &cached)
58                 : Resolver(hostname, DNS_QUERY_A, cached, me), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf)
59         {
60         }
61
62         /* Note: This may be called multiple times for multiple A record results */
63         virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
64         {
65                 /* Check the user still exists */
66                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
67                 if (them)
68                 {
69                         int i = countExt.get(them);
70                         if (i)
71                                 countExt.set(them, i - 1);
72                         // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
73                         if(result.length())
74                         {
75                                 unsigned int bitmask = 0, record = 0;
76                                 bool match = false;
77                                 in_addr resultip;
78
79                                 inet_aton(result.c_str(), &resultip);
80
81                                 switch (ConfEntry->type)
82                                 {
83                                         case DNSBLConfEntry::A_BITMASK:
84                                                 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
85                                                 bitmask &= ConfEntry->bitmask;
86                                                 match = (bitmask != 0);
87                                         break;
88                                         case DNSBLConfEntry::A_RECORD:
89                                                 record = resultip.s_addr >> 24; /* Last octet */
90                                                 match = (ConfEntry->records[record] == 1);
91                                         break;
92                                 }
93
94                                 if (match)
95                                 {
96                                         std::string reason = ConfEntry->reason;
97                                         std::string::size_type x = reason.find("%ip%");
98                                         while (x != std::string::npos)
99                                         {
100                                                 reason.erase(x, 4);
101                                                 reason.insert(x, them->GetIPString());
102                                                 x = reason.find("%ip%");
103                                         }
104
105                                         ConfEntry->stats_hits++;
106
107                                         switch (ConfEntry->banaction)
108                                         {
109                                                 case DNSBLConfEntry::I_KILL:
110                                                 {
111                                                         ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
112                                                         break;
113                                                 }
114                                                 case DNSBLConfEntry::I_MARK:
115                                                 {
116                                                         if (!ConfEntry->ident.empty())
117                                                         {
118                                                                 them->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
119                                                                 them->ChangeIdent(ConfEntry->ident.c_str());
120                                                         }
121
122                                                         if (!ConfEntry->host.empty())
123                                                         {
124                                                                 them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason);
125                                                                 them->ChangeDisplayedHost(ConfEntry->host.c_str());
126                                                         }
127
128                                                         nameExt.set(them, ConfEntry->name);
129                                                         break;
130                                                 }
131                                                 case DNSBLConfEntry::I_KLINE:
132                                                 {
133                                                         KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
134                                                                         "*", them->GetIPString());
135                                                         if (ServerInstance->XLines->AddLine(kl,NULL))
136                                                         {
137                                                                 std::string timestr = ServerInstance->TimeString(kl->expiry);
138                                                                 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
139                                                                         them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
140                                                                 ServerInstance->XLines->ApplyLines();
141                                                         }
142                                                         else
143                                                                 delete kl;
144                                                         break;
145                                                 }
146                                                 case DNSBLConfEntry::I_GLINE:
147                                                 {
148                                                         GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
149                                                                         "*", them->GetIPString());
150                                                         if (ServerInstance->XLines->AddLine(gl,NULL))
151                                                         {
152                                                                 std::string timestr = ServerInstance->TimeString(gl->expiry);
153                                                                 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s",
154                                                                         them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
155                                                                 ServerInstance->XLines->ApplyLines();
156                                                         }
157                                                         else
158                                                                 delete gl;
159                                                         break;
160                                                 }
161                                                 case DNSBLConfEntry::I_ZLINE:
162                                                 {
163                                                         ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
164                                                                         them->GetIPString());
165                                                         if (ServerInstance->XLines->AddLine(zl,NULL))
166                                                         {
167                                                                 std::string timestr = ServerInstance->TimeString(zl->expiry);
168                                                                 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
169                                                                         them->GetIPString().c_str(), timestr.c_str(), reason.c_str());
170                                                                 ServerInstance->XLines->ApplyLines();
171                                                         }
172                                                         else
173                                                                 delete zl;
174                                                         break;
175                                                 }
176                                                 case DNSBLConfEntry::I_UNKNOWN:
177                                                 {
178                                                         break;
179                                                 }
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                         else
189                                 ConfEntry->stats_misses++;
190                 }
191         }
192
193         virtual void OnError(ResolverError e, const std::string &errormessage)
194         {
195                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
196                 if (them)
197                 {
198                         int i = countExt.get(them);
199                         if (i)
200                                 countExt.set(them, i - 1);
201                 }
202         }
203 };
204
205 class ModuleDNSBL : public Module
206 {
207         std::vector<DNSBLConfEntry *> DNSBLConfEntries;
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() : nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
231
232         void init()
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         virtual ~ModuleDNSBL()
242         {
243                 ClearEntries();
244         }
245
246         Version GetVersion()
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)
344         {
345                 ReadConf();
346         }
347
348         void OnSetUserIP(LocalUser* user)
349         {
350                 if ((user->exempt) || (user->client_sa.sa.sa_family != AF_INET))
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                 char reversedipbuf[128];
363                 std::string reversedip;
364
365                 d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
366                 c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
367                 b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
368                 a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF;
369
370                 snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
371                 reversedip = std::string(reversedipbuf);
372
373                 countExt.set(user, DNSBLConfEntries.size());
374
375                 // For each DNSBL, we will run through this lookup
376                 unsigned int i = 0;
377                 while (i < DNSBLConfEntries.size())
378                 {
379                         // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
380                         std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain;
381
382                         /* now we'd need to fire off lookups for `hostname'. */
383                         bool cached;
384                         DNSBLResolver *r = new DNSBLResolver(this, nameExt, countExt, hostname, user, DNSBLConfEntries[i], cached);
385                         ServerInstance->AddResolver(r, cached);
386                         if (user->quitting)
387                                 break;
388                         i++;
389                 }
390         }
391
392         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass)
393         {
394                 std::string dnsbl;
395                 if (!myclass->config->readString("dnsbl", dnsbl))
396                         return MOD_RES_PASSTHRU;
397                 std::string* match = nameExt.get(user);
398                 std::string myname = match ? *match : "";
399                 if (dnsbl == myname)
400                         return MOD_RES_PASSTHRU;
401                 return MOD_RES_DENY;
402         }
403
404         ModResult OnCheckReady(LocalUser *user)
405         {
406                 if (countExt.get(user))
407                         return MOD_RES_DENY;
408                 return MOD_RES_PASSTHRU;
409         }
410
411         ModResult OnStats(char symbol, User* user, string_list &results)
412         {
413                 if (symbol != 'd')
414                         return MOD_RES_PASSTHRU;
415
416                 unsigned long total_hits = 0, total_misses = 0;
417
418                 for (std::vector<DNSBLConfEntry*>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
419                 {
420                         total_hits += (*i)->stats_hits;
421                         total_misses += (*i)->stats_misses;
422
423                         results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
424                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
425                 }
426
427                 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
428                 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
429
430                 return MOD_RES_PASSTHRU;
431         }
432 };
433
434 MODULE_INIT(ModuleDNSBL)