]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
Include explicit routing information in Command, will replace CMD_LOCALONLY return...
[user/henk/code/inspircd.git] / src / modules / m_dnsbl.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 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 : public classbase
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 *Instance, const std::string &hostname, User* u, int userfd, DNSBLConfEntry *conf, bool &cached)
55                 : Resolver(Instance, 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)
64         {
65                 /* Check the user still exists */
66                 if ((them) && (them == ServerInstance->SE->GetRef(theirfd)))
67                 {
68                         // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d
69                         if(result.length())
70                         {
71                                 unsigned int bitmask = 0, record = 0;
72                                 bool match = false;
73                                 in_addr resultip;
74
75                                 inet_aton(result.c_str(), &resultip);
76
77                                 switch (ConfEntry->type)
78                                 {
79                                         case DNSBLConfEntry::A_BITMASK:
80                                                 bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */
81                                                 bitmask &= ConfEntry->bitmask;
82                                                 match = (bitmask != 0);
83                                         break;
84                                         case DNSBLConfEntry::A_RECORD:
85                                                 record = resultip.s_addr >> 24; /* Last octet */
86                                                 match = (ConfEntry->records[record] == 1);
87                                         break;
88                                 }
89
90                                 if (match)
91                                 {
92                                         std::string reason = ConfEntry->reason;
93                                         std::string::size_type x = reason.find("%ip%");
94                                         while (x != std::string::npos)
95                                         {
96                                                 reason.erase(x, 4);
97                                                 reason.insert(x, them->GetIPString());
98                                                 x = reason.find("%ip%");
99                                         }
100
101                                         ConfEntry->stats_hits++;
102
103                                         switch (ConfEntry->banaction)
104                                         {
105                                                 case DNSBLConfEntry::I_KILL:
106                                                 {
107                                                         ServerInstance->Users->QuitUser(them, std::string("Killed (") + reason + ")");
108                                                         break;
109                                                 }
110                                                 case DNSBLConfEntry::I_KLINE:
111                                                 {
112                                                         KLine* kl = new KLine(ServerInstance, ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName, reason.c_str(),
113                                                                         "*", them->GetIPString());
114                                                         if (ServerInstance->XLines->AddLine(kl,NULL))
115                                                         {
116                                                                 ServerInstance->SNO->WriteToSnoMask('x',"m_dnsbl added K:line on *@%s to expire on %s (%s).", 
117                                                                         them->GetIPString(), ServerInstance->TimeString(kl->expiry).c_str(), reason.c_str());
118                                                                 ServerInstance->XLines->ApplyLines();
119                                                         }
120                                                         else
121                                                                 delete kl;
122                                                         break;
123                                                 }
124                                                 case DNSBLConfEntry::I_GLINE:
125                                                 {
126                                                         GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName, reason.c_str(),
127                                                                         "*", them->GetIPString());
128                                                         if (ServerInstance->XLines->AddLine(gl,NULL))
129                                                         {
130                                                                 ServerInstance->SNO->WriteToSnoMask('x',"m_dnsbl added G:line on *@%s to expire on %s (%s).", 
131                                                                         them->GetIPString(), ServerInstance->TimeString(gl->expiry).c_str(), reason.c_str());
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->SNO->WriteToSnoMask('x',"m_dnsbl added Z:line on *@%s to expire on %s (%s).", 
145                                                                         them->GetIPString(), ServerInstance->TimeString(zl->expiry).c_str(), reason.c_str());
146                                                                 ServerInstance->XLines->ApplyLines();
147                                                         }
148                                                         else
149                                                                 delete zl;
150                                                         break;
151                                                 }
152                                                 case DNSBLConfEntry::I_UNKNOWN:
153                                                 {
154                                                         break;
155                                                 }
156                                                 break;
157                                         }
158
159                                         ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s detected as being on a DNS blacklist (%s) with result %d", them->GetFullRealHost().c_str(), ConfEntry->name.c_str(), (ConfEntry->type==DNSBLConfEntry::A_BITMASK) ? bitmask : record);
160                                 }
161                                 else
162                                         ConfEntry->stats_misses++;
163                         }
164                         else
165                                 ConfEntry->stats_misses++;
166                 }
167         }
168
169         virtual void OnError(ResolverError e, const std::string &errormessage)
170         {
171         }
172
173         virtual ~DNSBLResolver()
174         {
175         }
176 };
177
178 class ModuleDNSBL : public Module
179 {
180  private:
181         std::vector<DNSBLConfEntry *> DNSBLConfEntries;
182
183         /*
184          *      Convert a string to EnumBanaction
185          */
186         DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
187         {
188                 if(action.compare("KILL")==0)
189                         return DNSBLConfEntry::I_KILL;
190                 if(action.compare("KLINE")==0)
191                         return DNSBLConfEntry::I_KLINE;
192                 if(action.compare("ZLINE")==0)
193                         return DNSBLConfEntry::I_ZLINE;
194                 if(action.compare("GLINE")==0)
195                         return DNSBLConfEntry::I_GLINE;
196
197                 return DNSBLConfEntry::I_UNKNOWN;
198         }
199  public:
200         ModuleDNSBL(InspIRCd *Me) : Module(Me)
201         {
202                 ReadConf();
203                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnStats };
204                 ServerInstance->Modules->Attach(eventlist, this, 3);
205         }
206
207         virtual ~ModuleDNSBL()
208         {
209                 ClearEntries();
210         }
211
212         virtual Version GetVersion()
213         {
214                 return Version("$Id$", VF_VENDOR, API_VERSION);
215         }
216
217
218         /** Clear entries and free the mem it was using
219          */
220         void ClearEntries()
221         {
222                 for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
223                         delete *i;
224                 DNSBLConfEntries.clear();
225         }
226
227         /** Fill our conf vector with data
228          */
229         virtual void ReadConf()
230         {
231                 ConfigReader *MyConf = new ConfigReader(ServerInstance);
232                 ClearEntries();
233
234                 for (int i=0; i< MyConf->Enumerate("dnsbl"); i++)
235                 {
236                         DNSBLConfEntry *e = new DNSBLConfEntry();
237
238                         e->name = MyConf->ReadValue("dnsbl", "name", i);
239                         e->reason = MyConf->ReadValue("dnsbl", "reason", i);
240                         e->domain = MyConf->ReadValue("dnsbl", "domain", i);
241
242                         if (MyConf->ReadValue("dnsbl", "type", i) == "bitmask")
243                         {
244                                 e->type = DNSBLConfEntry::A_BITMASK;
245                                 e->bitmask = MyConf->ReadInteger("dnsbl", "bitmask", i, false);
246                         }
247                         else
248                         {
249                                 memset(e->records, 0, sizeof(e->records));
250                                 e->type = DNSBLConfEntry::A_RECORD;
251                                 irc::portparser portrange(MyConf->ReadValue("dnsbl", "records", i), false);
252                                 long item = -1;
253                                 while ((item = portrange.GetToken()))
254                                         e->records[item] = 1;
255                         }
256
257                         e->banaction = str2banaction(MyConf->ReadValue("dnsbl", "action", i));
258                         e->duration = ServerInstance->Duration(MyConf->ReadValue("dnsbl", "duration", "60", i));
259
260                         /* Use portparser for record replies */
261
262                         /* yeah, logic here is a little messy */
263                         if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
264                         {
265                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): invalid bitmask",i);
266                         }
267                         else if (e->name.empty())
268                         {
269                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): Invalid name",i);
270                         }
271                         else if (e->domain.empty())
272                         {
273                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): Invalid domain",i);
274                         }
275                         else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
276                         {
277                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): Invalid banaction", i);
278                         }
279                         else if (e->duration <= 0)
280                         {
281                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): Invalid duration", i);
282                         }
283                         else
284                         {
285                                 if (e->reason.empty())
286                                 {
287                                         ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): empty reason, using defaults",i);
288                                         e->reason = "Your IP has been blacklisted.";
289                                 }
290
291                                 /* add it, all is ok */
292                                 DNSBLConfEntries.push_back(e);
293                                 continue;
294                         }
295
296                         /* delete and drop it, error somewhere */
297                         delete e;
298                 }
299
300                 delete MyConf;
301         }
302
303         virtual void OnRehash(User* user)
304         {
305                 ReadConf();
306         }
307
308         virtual int OnUserRegister(User* user)
309         {
310                 /* only do lookups on local users */
311                 if (IS_LOCAL(user))
312                 {
313                         /* following code taken from bopm, reverses an IP address. */
314                         struct in_addr in;
315                         unsigned char a, b, c, d;
316                         char reversedipbuf[128];
317                         std::string reversedip;
318                         bool success;
319
320                         success = inet_aton(user->GetIPString(), &in);
321
322                         if (!success)
323                                 return 0;
324
325                         d = (unsigned char) (in.s_addr >> 24) & 0xFF;
326                         c = (unsigned char) (in.s_addr >> 16) & 0xFF;
327                         b = (unsigned char) (in.s_addr >> 8) & 0xFF;
328                         a = (unsigned char) in.s_addr & 0xFF;
329
330                         snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
331                         reversedip = std::string(reversedipbuf);
332
333                         // For each DNSBL, we will run through this lookup
334                         for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
335                         {
336                                 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
337                                 std::string hostname = reversedip + "." + (*i)->domain;
338
339                                 /* now we'd need to fire off lookups for `hostname'. */
340                                 bool cached;
341                                 DNSBLResolver *r = new DNSBLResolver(this, ServerInstance, hostname, user, user->GetFd(), *i, cached);
342                                 ServerInstance->AddResolver(r, cached);
343                         }
344                 }
345
346                 /* don't do anything with this hot potato */
347                 return 0;
348         }
349
350         virtual int OnStats(char symbol, User* user, string_list &results)
351         {
352                 if (symbol != 'd')
353                         return 0;
354
355                 unsigned long total_hits = 0, total_misses = 0;
356
357                 for (std::vector<DNSBLConfEntry*>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
358                 {
359                         total_hits += (*i)->stats_hits;
360                         total_misses += (*i)->stats_misses;
361
362                         results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
363                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
364                 }
365
366                 results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
367                 results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
368
369                 return 0;
370         }
371 };
372
373 MODULE_INIT(ModuleDNSBL)