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