]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
Merge pull request #1157 from SaberUK/insp20+fix-cron-restart
[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                         // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
74                         if(result.length())
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                                                 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
86                                                 bitmask &= ConfEntry->bitmask;
87                                                 match = (bitmask != 0);
88                                         break;
89                                         case DNSBLConfEntry::A_RECORD:
90                                                 record = resultip.s_addr >> 24; /* Last octet */
91                                                 match = (ConfEntry->records[record] == 1);
92                                         break;
93                                 }
94
95                                 if (match)
96                                 {
97                                         std::string reason = ConfEntry->reason;
98                                         std::string::size_type x = reason.find("%ip%");
99                                         while (x != std::string::npos)
100                                         {
101                                                 reason.erase(x, 4);
102                                                 reason.insert(x, them->GetIPString());
103                                                 x = reason.find("%ip%");
104                                         }
105
106                                         ConfEntry->stats_hits++;
107
108                                         switch (ConfEntry->banaction)
109                                         {
110                                                 case DNSBLConfEntry::I_KILL:
111                                                 {
112                                                         ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")");
113                                                         break;
114                                                 }
115                                                 case DNSBLConfEntry::I_MARK:
116                                                 {
117                                                         if (!ConfEntry->ident.empty())
118                                                         {
119                                                                 them->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
120                                                                 them->ChangeIdent(ConfEntry->ident.c_str());
121                                                         }
122
123                                                         if (!ConfEntry->host.empty())
124                                                         {
125                                                                 them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason);
126                                                                 them->ChangeDisplayedHost(ConfEntry->host.c_str());
127                                                         }
128
129                                                         nameExt.set(them, ConfEntry->name);
130                                                         break;
131                                                 }
132                                                 case DNSBLConfEntry::I_KLINE:
133                                                 {
134                                                         KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
135                                                                         "*", them->GetIPString());
136                                                         if (ServerInstance->XLines->AddLine(kl,NULL))
137                                                         {
138                                                                 std::string timestr = ServerInstance->TimeString(kl->expiry);
139                                                                 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s",
140                                                                         them->GetIPString(), timestr.c_str(), reason.c_str());
141                                                                 ServerInstance->XLines->ApplyLines();
142                                                         }
143                                                         else
144                                                         {
145                                                                 delete kl;
146                                                                 return;
147                                                         }
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(), timestr.c_str(), reason.c_str());
159                                                                 ServerInstance->XLines->ApplyLines();
160                                                         }
161                                                         else
162                                                         {
163                                                                 delete gl;
164                                                                 return;
165                                                         }
166                                                         break;
167                                                 }
168                                                 case DNSBLConfEntry::I_ZLINE:
169                                                 {
170                                                         ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(),
171                                                                         them->GetIPString());
172                                                         if (ServerInstance->XLines->AddLine(zl,NULL))
173                                                         {
174                                                                 std::string timestr = ServerInstance->TimeString(zl->expiry);
175                                                                 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s",
176                                                                         them->GetIPString(), timestr.c_str(), reason.c_str());
177                                                                 ServerInstance->XLines->ApplyLines();
178                                                         }
179                                                         else
180                                                         {
181                                                                 delete zl;
182                                                                 return;
183                                                         }
184                                                         break;
185                                                 }
186                                                 case DNSBLConfEntry::I_UNKNOWN:
187                                                 {
188                                                         break;
189                                                 }
190                                                 break;
191                                         }
192
193                                         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);
194                                 }
195                                 else
196                                         ConfEntry->stats_misses++;
197                         }
198                         else
199                                 ConfEntry->stats_misses++;
200                 }
201         }
202
203         virtual void OnError(ResolverError e, const std::string &errormessage)
204         {
205                 LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid);
206                 if (them)
207                 {
208                         int i = countExt.get(them);
209                         if (i)
210                                 countExt.set(them, i - 1);
211                 }
212         }
213
214         virtual ~DNSBLResolver()
215         {
216         }
217 };
218
219 class ModuleDNSBL : public Module
220 {
221         std::vector<reference<DNSBLConfEntry> > DNSBLConfEntries;
222         LocalStringExt nameExt;
223         LocalIntExt countExt;
224
225         /*
226          *      Convert a string to EnumBanaction
227          */
228         DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
229         {
230                 if(action.compare("KILL")==0)
231                         return DNSBLConfEntry::I_KILL;
232                 if(action.compare("KLINE")==0)
233                         return DNSBLConfEntry::I_KLINE;
234                 if(action.compare("ZLINE")==0)
235                         return DNSBLConfEntry::I_ZLINE;
236                 if(action.compare("GLINE")==0)
237                         return DNSBLConfEntry::I_GLINE;
238                 if(action.compare("MARK")==0)
239                         return DNSBLConfEntry::I_MARK;
240
241                 return DNSBLConfEntry::I_UNKNOWN;
242         }
243  public:
244         ModuleDNSBL() : nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { }
245
246         void init()
247         {
248                 ReadConf();
249                 ServerInstance->Modules->AddService(nameExt);
250                 ServerInstance->Modules->AddService(countExt);
251                 Implementation eventlist[] = { I_OnRehash, I_OnSetUserIP, I_OnStats, I_OnSetConnectClass, I_OnCheckReady };
252                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
253         }
254
255         Version GetVersion()
256         {
257                 return Version("Provides handling of DNS blacklists", VF_VENDOR);
258         }
259
260         /** Fill our conf vector with data
261          */
262         void ReadConf()
263         {
264                 DNSBLConfEntries.clear();
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                         reference<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 = ServerInstance->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                         }
336                 }
337         }
338
339         void OnRehash(User* user)
340         {
341                 ReadConf();
342         }
343
344         void OnSetUserIP(LocalUser* user)
345         {
346                 if ((user->exempt) || (user->client_sa.sa.sa_family != AF_INET))
347                         return;
348
349                 if (user->MyClass)
350                 {
351                         if (!user->MyClass->config->getBool("usednsbl", true))
352                                 return;
353                 }
354                 else
355                         ServerInstance->Logs->Log("m_dnsbl", DEBUG, "User has no connect class in OnSetUserIP");
356
357                 unsigned char a, b, c, d;
358                 char reversedipbuf[128];
359                 std::string reversedip;
360
361                 d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF;
362                 c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF;
363                 b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF;
364                 a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF;
365
366                 snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
367                 reversedip = std::string(reversedipbuf);
368
369                 countExt.set(user, DNSBLConfEntries.size());
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                         if (user->quitting)
383                                 break;
384                         i++;
385                 }
386         }
387
388         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass)
389         {
390                 std::string dnsbl;
391                 if (!myclass->config->readString("dnsbl", dnsbl))
392                         return MOD_RES_PASSTHRU;
393                 std::string* match = nameExt.get(user);
394                 std::string myname = match ? *match : "";
395                 if (dnsbl == myname)
396                         return MOD_RES_PASSTHRU;
397                 return MOD_RES_DENY;
398         }
399         
400         ModResult OnCheckReady(LocalUser *user)
401         {
402                 if (countExt.get(user))
403                         return MOD_RES_DENY;
404                 return MOD_RES_PASSTHRU;
405         }
406
407         ModResult OnStats(char symbol, User* user, string_list &results)
408         {
409                 if (symbol != 'd')
410                         return MOD_RES_PASSTHRU;
411
412                 unsigned long total_hits = 0, total_misses = 0;
413
414                 for (std::vector<reference<DNSBLConfEntry> >::const_iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); ++i)
415                 {
416                         total_hits += (*i)->stats_hits;
417                         total_misses += (*i)->stats_misses;
418
419                         results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
420                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
421                 }
422
423                 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
424                 results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
425
426                 return MOD_RES_PASSTHRU;
427         }
428 };
429
430 MODULE_INIT(ModuleDNSBL)