]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
Some more to fix still, modules probably wont load correctly atm
[user/henk/code/inspircd.git] / src / modules / m_dnsbl.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/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 };
31                 enum EnumType { A_RECORD, A_BITMASK };
32                 std::string name, 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         int theirfd;
49         User* them;
50         DNSBLConfEntry *ConfEntry;
51
52  public:
53
54         DNSBLResolver(Module *me, InspIRCd *ServerInstance, const std::string &hostname, User* u, int userfd, DNSBLConfEntry *conf, bool &cached)
55                 : Resolver(ServerInstance, hostname, DNS_QUERY_A, cached, me)
56         {
57                 theirfd = userfd;
58                 them = u;
59                 ConfEntry = conf;
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, int resultnum = 0)
64         {
65                 /* for bitmask reply types, we arent interested in any but the first result (number 0) */
66                 if ((ConfEntry->type == DNSBLConfEntry::A_BITMASK) && (resultnum))
67                         return;
68
69                 /* Check the user still exists */
70                 if ((them) && (them == ServerInstance->SE->GetRef(theirfd)))
71                 {
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 show = false, 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                                                         User::QuitUser(ServerInstance, them, std::string("Killed (") + reason + ")");
112                                                         break;
113                                                 }
114                                                 case DNSBLConfEntry::I_KLINE:
115                                                 {
116                                                         KLine* kl = new KLine(ServerInstance, ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName, reason.c_str(),
117                                                                         "*", them->GetIPString());
118                                                         if (ServerInstance->XLines->AddLine(kl,NULL))
119                                                         {
120                                                                 ServerInstance->XLines->ApplyLines();
121                                                         }
122                                                         else
123                                                                 delete kl;
124                                                         break;
125                                                 }
126                                                 case DNSBLConfEntry::I_GLINE:
127                                                 {
128                                                         GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName, reason.c_str(),
129                                                                         "*", them->GetIPString());
130                                                         if (ServerInstance->XLines->AddLine(gl,NULL))
131                                                         {
132                                                                 ServerInstance->XLines->ApplyLines();
133                                                         }
134                                                         else
135                                                                 delete gl;
136                                                         break;
137                                                 }
138                                                 case DNSBLConfEntry::I_ZLINE:
139                                                 {
140                                                         ZLine* zl = new ZLine(ServerInstance, ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName, reason.c_str(),
141                                                                         them->GetIPString());
142                                                         if (ServerInstance->XLines->AddLine(zl,NULL))
143                                                         {
144                                                                 ServerInstance->XLines->ApplyLines();
145                                                         }
146                                                         else 
147                                                                 delete zl;
148                                                         break;
149                                                 }
150                                                 case DNSBLConfEntry::I_UNKNOWN:
151                                                 {
152                                                         break;
153                                                 }
154                                                 break;
155                                         }
156
157                                         if (show)
158                                         {
159                                                 ServerInstance->WriteOpers("*** Connecting user %s detected as being on a DNS blacklist (%s) with result %d", them->GetFullRealHost(), ConfEntry->name.c_str(), bitmask);
160                                         }
161                                 }
162                                 else
163                                         ConfEntry->stats_misses++;
164                         }
165                         else
166                                 ConfEntry->stats_misses++;
167                 }
168         }
169
170         virtual void OnError(ResolverError e, const std::string &errormessage)
171         {
172         }
173
174         virtual ~DNSBLResolver()
175         {
176         }
177 };
178
179 class ModuleDNSBL : public Module
180 {
181  private:
182         std::vector<DNSBLConfEntry *> DNSBLConfEntries;
183
184         /*
185          *      Convert a string to EnumBanaction
186          */
187         DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
188         {
189                 if(action.compare("KILL")==0)
190                         return DNSBLConfEntry::I_KILL;
191                 if(action.compare("KLINE")==0)
192                         return DNSBLConfEntry::I_KLINE;
193                 if(action.compare("ZLINE")==0)
194                         return DNSBLConfEntry::I_ZLINE;
195                 if(action.compare("GLINE")==0)
196                         return DNSBLConfEntry::I_GLINE;
197
198                 return DNSBLConfEntry::I_UNKNOWN;
199         }
200  public:
201         ModuleDNSBL(InspIRCd *Me) : Module(Me)
202         {
203                 ReadConf();
204                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnStats };
205                 ServerInstance->Modules->Attach(eventlist, this, 3);
206         }
207
208         virtual ~ModuleDNSBL()
209         {
210                 ClearEntries();
211         }
212
213         virtual Version GetVersion()
214         {
215                 return Version(2, 0, 0, 1, VF_VENDOR, API_VERSION);
216         }
217
218         void Implements(char* List)
219         {
220                 List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnStats] = 1;
221         }
222
223         /** Clear entries and free the mem it was using
224          */
225         void ClearEntries()
226         {
227                 std::vector<DNSBLConfEntry *>::iterator i;
228                 for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
229                         delete *i;
230                 DNSBLConfEntries.clear();
231         }
232
233         /** Fill our conf vector with data
234          */
235         virtual void ReadConf()
236         {
237                 ConfigReader *MyConf = new ConfigReader(ServerInstance);
238                 ClearEntries();
239
240                 for (int i=0; i< MyConf->Enumerate("dnsbl"); i++)
241                 {
242                         DNSBLConfEntry *e = new DNSBLConfEntry();
243
244                         e->name = MyConf->ReadValue("dnsbl", "name", i);
245                         e->reason = MyConf->ReadValue("dnsbl", "reason", i);
246                         e->domain = MyConf->ReadValue("dnsbl", "domain", i);
247
248                         if (MyConf->ReadValue("dnsbl", "type", i) == "bitmask")
249                         {
250                                 e->type = DNSBLConfEntry::A_BITMASK;
251                                 e->bitmask = MyConf->ReadInteger("dnsbl", "bitmask", i, false);
252                         }
253                         else
254                         {
255                                 memset(e->records, 0, 256);
256                                 e->type = DNSBLConfEntry::A_RECORD;
257                                 irc::portparser portrange(MyConf->ReadValue("dnsbl", "records", i), false);
258                                 long item = -1;
259                                 while ((item = portrange.GetToken()))
260                                         e->records[item] = 1;
261                         }
262
263                         e->banaction = str2banaction(MyConf->ReadValue("dnsbl", "action", i));
264                         e->duration = ServerInstance->Duration(MyConf->ReadValue("dnsbl", "duration", i));
265                         
266                         /* Use portparser for record replies */
267
268                         /* yeah, logic here is a little messy */
269                         if (e->bitmask <= 0)
270                         {
271                                 ServerInstance->WriteOpers("*** DNSBL(#%d): invalid bitmask",i);
272                         }
273                         else if (e->name.empty())
274                         {
275                                 ServerInstance->WriteOpers("*** DNSBL(#%d): Invalid name",i);
276                         }
277                         else if (e->domain.empty())
278                         {
279                                 ServerInstance->WriteOpers("*** DNSBL(#%d): Invalid domain",i);
280                         }
281                         else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
282                         {
283                                 ServerInstance->WriteOpers("*** DNSBL(#%d): Invalid banaction", i);
284                         }
285                         else
286                         {
287                                 if (e->reason.empty())
288                                 {
289                                         ServerInstance->WriteOpers("*** DNSBL(#%d): empty reason, using defaults",i);
290                                         e->reason = "Your IP has been blacklisted.";
291                                 }
292
293                                 /* add it, all is ok */
294                                 DNSBLConfEntries.push_back(e);
295                                 continue;
296                         }
297
298                         /* delete and drop it, error somewhere */
299                         delete e;
300                 }
301
302                 delete MyConf;
303         }
304
305         virtual void OnRehash(User* user, const std::string &parameter)
306         {
307                 ReadConf();
308         }
309
310         virtual int OnUserRegister(User* user)
311         {
312                 /* only do lookups on local users */
313                 if (IS_LOCAL(user))
314                 {
315                         /* following code taken from bopm, reverses an IP address. */
316                         struct in_addr in;
317                         unsigned char a, b, c, d;
318                         char reversedipbuf[128];
319                         std::string reversedip;
320                         bool success = false;
321
322                         if (!inet_aton(user->GetIPString(), &in))
323                         {
324 #ifdef IPV6
325                                 /* We could have an ipv6 address here */
326                                 std::string x = user->GetIPString();
327                                 /* Is it a 4in6 address? (Compensate for this kernel kludge that people love) */
328                                 if (x.find("0::ffff:") == 0)
329                                 {
330                                         x.erase(x.begin(), x.begin() + 8);
331                                         if (inet_aton(x.c_str(), &in))
332                                                 success = true;
333                                 }
334 #endif
335                         }
336                         else
337                         {
338                                 success = true;
339                         }
340
341                         if (!success)
342                                 return 0;
343
344                         d = (unsigned char) (in.s_addr >> 24) & 0xFF;
345                         c = (unsigned char) (in.s_addr >> 16) & 0xFF;
346                         b = (unsigned char) (in.s_addr >> 8) & 0xFF;
347                         a = (unsigned char) in.s_addr & 0xFF;
348
349                         snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
350                         reversedip = std::string(reversedipbuf);
351
352                         // For each DNSBL, we will run through this lookup
353                         for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
354                         {
355                                 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
356                                 std::string hostname = reversedip + "." + (*i)->domain;
357
358                                 /* now we'd need to fire off lookups for `hostname'. */
359                                 bool cached;
360                                 DNSBLResolver *r = new DNSBLResolver(this, ServerInstance, hostname, user, user->GetFd(), *i, cached);
361                                 ServerInstance->AddResolver(r, cached);
362                         }
363                 }
364
365                 /* don't do anything with this hot potato */
366                 return 0;
367         }
368         
369         virtual int OnStats(char symbol, User* user, string_list &results)
370         {
371                 if (symbol != 'd')
372                         return 0;
373                 
374                 unsigned long total_hits = 0, total_misses = 0;
375
376                 for (std::vector<DNSBLConfEntry*>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
377                 {
378                         total_hits += (*i)->stats_hits;
379                         total_misses += (*i)->stats_misses;
380                         
381                         results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
382                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
383                 }
384                 
385                 results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
386                 results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
387                 
388                 return 0;
389         }
390 };
391
392 MODULE_INIT(ModuleDNSBL)