]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_dnsbl.cpp
06709979b9143f0d074c8c3121f874d5c10729f6
[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, 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         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_MARK:
111                                                 {
112                                                         if (!ConfEntry->ident.empty())
113                                                         {
114                                                                 them->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason);
115                                                                 them->ChangeIdent(ConfEntry->ident.c_str());
116                                                         }
117
118                                                         if (!ConfEntry->host.empty())
119                                                         {
120                                                                 them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason);
121                                                                 them->ChangeDisplayedHost(ConfEntry->host.c_str());
122                                                         }
123
124                                                         break;
125                                                 }
126                                                 case DNSBLConfEntry::I_KLINE:
127                                                 {
128                                                         KLine* kl = new KLine(ServerInstance, ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName, reason.c_str(),
129                                                                         "*", them->GetIPString());
130                                                         if (ServerInstance->XLines->AddLine(kl,NULL))
131                                                         {
132                                                                 ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s", 
133                                                                         them->GetIPString(), ServerInstance->TimeString(kl->expiry).c_str(), reason.c_str());
134                                                                 ServerInstance->XLines->ApplyLines();
135                                                         }
136                                                         else
137                                                                 delete kl;
138                                                         break;
139                                                 }
140                                                 case DNSBLConfEntry::I_GLINE:
141                                                 {
142                                                         GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName, reason.c_str(),
143                                                                         "*", them->GetIPString());
144                                                         if (ServerInstance->XLines->AddLine(gl,NULL))
145                                                         {
146                                                                 ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s", 
147                                                                         them->GetIPString(), ServerInstance->TimeString(gl->expiry).c_str(), reason.c_str());
148                                                                 ServerInstance->XLines->ApplyLines();
149                                                         }
150                                                         else
151                                                                 delete gl;
152                                                         break;
153                                                 }
154                                                 case DNSBLConfEntry::I_ZLINE:
155                                                 {
156                                                         ZLine* zl = new ZLine(ServerInstance, ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName, reason.c_str(),
157                                                                         them->GetIPString());
158                                                         if (ServerInstance->XLines->AddLine(zl,NULL))
159                                                         {
160                                                                 ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s", 
161                                                                         them->GetIPString(), ServerInstance->TimeString(zl->expiry).c_str(), reason.c_str());
162                                                                 ServerInstance->XLines->ApplyLines();
163                                                         }
164                                                         else
165                                                                 delete zl;
166                                                         break;
167                                                 }
168                                                 case DNSBLConfEntry::I_UNKNOWN:
169                                                 {
170                                                         break;
171                                                 }
172                                                 break;
173                                         }
174
175                                         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);
176                                 }
177                                 else
178                                         ConfEntry->stats_misses++;
179                         }
180                         else
181                                 ConfEntry->stats_misses++;
182                 }
183         }
184
185         virtual void OnError(ResolverError e, const std::string &errormessage)
186         {
187         }
188
189         virtual ~DNSBLResolver()
190         {
191         }
192 };
193
194 class ModuleDNSBL : public Module
195 {
196  private:
197         std::vector<DNSBLConfEntry *> DNSBLConfEntries;
198
199         /*
200          *      Convert a string to EnumBanaction
201          */
202         DNSBLConfEntry::EnumBanaction str2banaction(const std::string &action)
203         {
204                 if(action.compare("KILL")==0)
205                         return DNSBLConfEntry::I_KILL;
206                 if(action.compare("KLINE")==0)
207                         return DNSBLConfEntry::I_KLINE;
208                 if(action.compare("ZLINE")==0)
209                         return DNSBLConfEntry::I_ZLINE;
210                 if(action.compare("GLINE")==0)
211                         return DNSBLConfEntry::I_GLINE;
212                 if(action.compare("MARK")==0)
213                         return DNSBLConfEntry::I_MARK;
214
215                 return DNSBLConfEntry::I_UNKNOWN;
216         }
217  public:
218         ModuleDNSBL(InspIRCd *Me) : Module(Me)
219         {
220                 ReadConf();
221                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnStats };
222                 ServerInstance->Modules->Attach(eventlist, this, 3);
223         }
224
225         virtual ~ModuleDNSBL()
226         {
227                 ClearEntries();
228         }
229
230         virtual Version GetVersion()
231         {
232                 return Version("Provides handling of DNS blacklists", VF_VENDOR, API_VERSION);
233         }
234
235
236         /** Clear entries and free the mem it was using
237          */
238         void ClearEntries()
239         {
240                 for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
241                         delete *i;
242                 DNSBLConfEntries.clear();
243         }
244
245         /** Fill our conf vector with data
246          */
247         virtual void ReadConf()
248         {
249                 ConfigReader *MyConf = new ConfigReader(ServerInstance);
250                 ClearEntries();
251
252                 for (int i=0; i< MyConf->Enumerate("dnsbl"); i++)
253                 {
254                         DNSBLConfEntry *e = new DNSBLConfEntry();
255
256                         e->name = MyConf->ReadValue("dnsbl", "name", i);
257                         e->ident = MyConf->ReadValue("dnsbl", "ident", i);
258                         e->host = MyConf->ReadValue("dnsbl", "host", i);
259                         e->reason = MyConf->ReadValue("dnsbl", "reason", i);
260                         e->domain = MyConf->ReadValue("dnsbl", "domain", i);
261
262                         if (MyConf->ReadValue("dnsbl", "type", i) == "bitmask")
263                         {
264                                 e->type = DNSBLConfEntry::A_BITMASK;
265                                 e->bitmask = MyConf->ReadInteger("dnsbl", "bitmask", i, false);
266                         }
267                         else
268                         {
269                                 memset(e->records, 0, sizeof(e->records));
270                                 e->type = DNSBLConfEntry::A_RECORD;
271                                 irc::portparser portrange(MyConf->ReadValue("dnsbl", "records", i), false);
272                                 long item = -1;
273                                 while ((item = portrange.GetToken()))
274                                         e->records[item] = 1;
275                         }
276
277                         e->banaction = str2banaction(MyConf->ReadValue("dnsbl", "action", i));
278                         e->duration = ServerInstance->Duration(MyConf->ReadValue("dnsbl", "duration", "60", i));
279
280                         /* Use portparser for record replies */
281
282                         /* yeah, logic here is a little messy */
283                         if ((e->bitmask <= 0) && (DNSBLConfEntry::A_BITMASK == e->type))
284                         {
285                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): invalid bitmask",i);
286                         }
287                         else if (e->name.empty())
288                         {
289                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): Invalid name",i);
290                         }
291                         else if (e->domain.empty())
292                         {
293                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): Invalid domain",i);
294                         }
295                         else if (e->banaction == DNSBLConfEntry::I_UNKNOWN)
296                         {
297                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): Invalid banaction", i);
298                         }
299                         else if (e->duration <= 0)
300                         {
301                                 ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): Invalid duration", i);
302                         }
303                         else
304                         {
305                                 if (e->reason.empty())
306                                 {
307                                         ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(#%d): empty reason, using defaults",i);
308                                         e->reason = "Your IP has been blacklisted.";
309                                 }
310
311                                 /* add it, all is ok */
312                                 DNSBLConfEntries.push_back(e);
313                                 continue;
314                         }
315
316                         /* delete and drop it, error somewhere */
317                         delete e;
318                 }
319
320                 delete MyConf;
321         }
322
323         virtual void OnRehash(User* user)
324         {
325                 ReadConf();
326         }
327
328         virtual ModResult OnUserRegister(User* user)
329         {
330                 /* only do lookups on local users */
331                 if (IS_LOCAL(user))
332                 {
333                         /* following code taken from bopm, reverses an IP address. */
334                         struct in_addr in;
335                         unsigned char a, b, c, d;
336                         char reversedipbuf[128];
337                         std::string reversedip;
338                         bool success;
339
340                         success = inet_aton(user->GetIPString(), &in);
341
342                         if (!success)
343                                 return MOD_RES_PASSTHRU;
344
345                         d = (unsigned char) (in.s_addr >> 24) & 0xFF;
346                         c = (unsigned char) (in.s_addr >> 16) & 0xFF;
347                         b = (unsigned char) (in.s_addr >> 8) & 0xFF;
348                         a = (unsigned char) in.s_addr & 0xFF;
349
350                         snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a);
351                         reversedip = std::string(reversedipbuf);
352
353                         // For each DNSBL, we will run through this lookup
354                         for (std::vector<DNSBLConfEntry *>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
355                         {
356                                 // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld)
357                                 std::string hostname = reversedip + "." + (*i)->domain;
358
359                                 /* now we'd need to fire off lookups for `hostname'. */
360                                 bool cached;
361                                 DNSBLResolver *r = new DNSBLResolver(this, ServerInstance, hostname, user, user->GetFd(), *i, cached);
362                                 ServerInstance->AddResolver(r, cached);
363                         }
364                 }
365
366                 /* don't do anything with this hot potato */
367                 return MOD_RES_PASSTHRU;
368         }
369
370         virtual ModResult OnStats(char symbol, User* user, string_list &results)
371         {
372                 if (symbol != 'd')
373                         return MOD_RES_PASSTHRU;
374
375                 unsigned long total_hits = 0, total_misses = 0;
376
377                 for (std::vector<DNSBLConfEntry*>::iterator i = DNSBLConfEntries.begin(); i != DNSBLConfEntries.end(); i++)
378                 {
379                         total_hits += (*i)->stats_hits;
380                         total_misses += (*i)->stats_misses;
381
382                         results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " +
383                                         ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses");
384                 }
385
386                 results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits));
387                 results.push_back(std::string(ServerInstance->Config->ServerName) + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses));
388
389                 return MOD_RES_PASSTHRU;
390         }
391 };
392
393 MODULE_INIT(ModuleDNSBL)