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