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