]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
Merge pull request #677 from Robby-/master-dnsblzline
[user/henk/code/inspircd.git] / src / modules / m_cgiirc.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 John Brooks <john.brooks@dereferenced.net>
6  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
7  *   Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
9  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11  *
12  * This file is part of InspIRCd.  InspIRCd is free software: you can
13  * redistribute it and/or modify it under the terms of the GNU General Public
14  * License as published by the Free Software Foundation, version 2.
15  *
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25
26 #include "inspircd.h"
27 #include "xline.h"
28 #include "modules/dns.h"
29
30 enum CGItype { PASS, IDENT, PASSFIRST, IDENTFIRST, WEBIRC };
31
32 // We need this method up here so that it can be accessed from anywhere
33 static void ChangeIP(User* user, const std::string& newip)
34 {
35         ServerInstance->Users->RemoveCloneCounts(user);
36         user->SetClientIP(newip.c_str());
37         ServerInstance->Users->AddClone(user);
38 }
39
40 /** Holds a CGI site's details
41  */
42 class CGIhost
43 {
44 public:
45         std::string hostmask;
46         CGItype type;
47         std::string password;
48
49         CGIhost(const std::string &mask, CGItype t, const std::string &spassword)
50         : hostmask(mask), type(t), password(spassword)
51         {
52         }
53 };
54 typedef std::vector<CGIhost> CGIHostlist;
55
56 /*
57  * WEBIRC
58  *  This is used for the webirc method of CGIIRC auth, and is (really) the best way to do these things.
59  *  Syntax: WEBIRC password client hostname ip
60  *  Where password is a shared key, client is the name of the "client" and version (e.g. cgiirc), hostname
61  *  is the resolved host of the client issuing the command and IP is the real IP of the client.
62  *
63  * How it works:
64  *  To tie in with the rest of cgiirc module, and to avoid race conditions, /webirc is only processed locally
65  *  and simply sets metadata on the user, which is later decoded on full connect to give something meaningful.
66  */
67 class CommandWebirc : public Command
68 {
69  public:
70         bool notify;
71         StringExtItem realhost;
72         StringExtItem realip;
73
74         CGIHostlist Hosts;
75         CommandWebirc(Module* Creator)
76                 : Command(Creator, "WEBIRC", 4),
77                   realhost("cgiirc_realhost", ExtensionItem::EXT_USER, Creator)
78                   , realip("cgiirc_realip", ExtensionItem::EXT_USER, Creator)
79                 {
80                         allow_empty_last_param = false;
81                         works_before_reg = true;
82                         this->syntax = "password client hostname ip";
83                 }
84                 CmdResult Handle(const std::vector<std::string> &parameters, User *user)
85                 {
86                         if(user->registered == REG_ALL)
87                                 return CMD_FAILURE;
88
89                         irc::sockets::sockaddrs ipaddr;
90                         if (!irc::sockets::aptosa(parameters[3], 0, ipaddr))
91                         {
92                                 IS_LOCAL(user)->CommandFloodPenalty += 5000;
93                                 ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s tried to use WEBIRC but gave an invalid IP address.", user->GetFullRealHost().c_str());
94                                 return CMD_FAILURE;
95                         }
96
97                         for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++)
98                         {
99                                 if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
100                                 {
101                                         if(iter->type == WEBIRC && parameters[0] == iter->password)
102                                         {
103                                                 realhost.set(user, user->host);
104                                                 realip.set(user, user->GetIPString());
105
106                                                 // Check if we're happy with the provided hostname. If it's problematic then make sure we won't set a host later, just the IP
107                                                 bool host_ok = (parameters[2].length() <= ServerInstance->Config->Limits.MaxHost);
108                                                 const std::string& newhost = (host_ok ? parameters[2] : parameters[3]);
109
110                                                 if (notify)
111                                                         ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", user->nick.c_str(), user->host.c_str(), newhost.c_str(), user->host.c_str());
112
113                                                 // Where the magic happens - change their IP
114                                                 ChangeIP(user, parameters[3]);
115                                                 // And follow this up by changing their host
116                                                 user->host = user->dhost = newhost;
117                                                 user->InvalidateCache();
118
119                                                 return CMD_SUCCESS;
120                                         }
121                                 }
122                         }
123
124                         IS_LOCAL(user)->CommandFloodPenalty += 5000;
125                         ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str());
126                         return CMD_FAILURE;
127                 }
128 };
129
130
131 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
132  */
133 class CGIResolver : public DNS::Request
134 {
135         std::string typ;
136         std::string theiruid;
137         LocalIntExt& waiting;
138         bool notify;
139  public:
140         CGIResolver(DNS::Manager *mgr, Module* me, bool NotifyOpers, const std::string &source, LocalUser* u,
141                         const std::string &ttype, LocalIntExt& ext)
142                 : DNS::Request(mgr, me, source, DNS::QUERY_PTR), typ(ttype), theiruid(u->uuid),
143                 waiting(ext), notify(NotifyOpers)
144         {
145         }
146
147         void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
148         {
149                 /* Check the user still exists */
150                 User* them = ServerInstance->FindUUID(theiruid);
151                 if ((them) && (!them->quitting))
152                 {
153                         LocalUser* lu = IS_LOCAL(them);
154                         if (!lu)
155                                 return;
156
157                         const DNS::ResourceRecord &ans_record = r->answers[0];
158                         if (ans_record.rdata.empty() || ans_record.rdata.length() > ServerInstance->Config->Limits.MaxHost)
159                                 return;
160
161                         if (notify)
162                                 ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", them->nick.c_str(), them->host.c_str(), ans_record.rdata.c_str(), typ.c_str());
163
164                         them->host = them->dhost = ans_record.rdata;
165                         them->InvalidateCache();
166                         lu->CheckLines(true);
167                 }
168         }
169
170         void OnError(const DNS::Query *r) CXX11_OVERRIDE
171         {
172                 if (!notify)
173                         return;
174
175                 User* them = ServerInstance->FindUUID(theiruid);
176                 if ((them) && (!them->quitting))
177                 {
178                         ServerInstance->SNO->WriteToSnoMask('w', "Connecting user %s detected as using CGI:IRC (%s), but their host can't be resolved from their %s!", them->nick.c_str(), them->host.c_str(), typ.c_str());
179                 }
180         }
181
182         ~CGIResolver()
183         {
184                 User* them = ServerInstance->FindUUID(theiruid);
185                 if (!them)
186                         return;
187                 int count = waiting.get(them);
188                 if (count)
189                         waiting.set(them, count - 1);
190         }
191 };
192
193 class ModuleCgiIRC : public Module
194 {
195         CommandWebirc cmd;
196         LocalIntExt waiting;
197         dynamic_reference<DNS::Manager> DNS;
198
199         static void RecheckClass(LocalUser* user)
200         {
201                 user->MyClass = NULL;
202                 user->SetClass();
203                 user->CheckClass();
204         }
205
206         void HandleIdentOrPass(LocalUser* user, const std::string& newip, bool was_pass)
207         {
208                 cmd.realhost.set(user, user->host);
209                 cmd.realip.set(user, user->GetIPString());
210                 ChangeIP(user, newip);
211                 user->host = user->dhost = user->GetIPString();
212                 user->InvalidateCache();
213                 RecheckClass(user);
214
215                 // Don't create the resolver if the core couldn't put the user in a connect class or when dns is disabled
216                 if (user->quitting || !DNS || !user->MyClass->resolvehostnames)
217                         return;
218
219                 CGIResolver* r = new CGIResolver(*this->DNS, this, cmd.notify, newip, user, (was_pass ? "PASS" : "IDENT"), waiting);
220                 try
221                 {
222                         waiting.set(user, waiting.get(user) + 1);
223                         this->DNS->Process(r);
224                 }
225                 catch (DNS::Exception &ex)
226                 {
227                         int count = waiting.get(user);
228                         if (count)
229                                 waiting.set(user, count - 1);
230                         delete r;
231                         if (cmd.notify)
232                                  ServerInstance->SNO->WriteToSnoMask('w', "Connecting user %s detected as using CGI:IRC (%s), but I could not resolve their hostname; %s", user->nick.c_str(), user->host.c_str(), ex.GetReason().c_str());
233                 }
234         }
235
236 public:
237         ModuleCgiIRC()
238                 : cmd(this)
239                 , waiting("cgiirc-delay", ExtensionItem::EXT_USER, this)
240                 , DNS(this, "DNS")
241         {
242         }
243
244         void init() CXX11_OVERRIDE
245         {
246                 ServerInstance->SNO->EnableSnomask('w', "CGIIRC");
247         }
248
249         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
250         {
251                 cmd.Hosts.clear();
252
253                 // Do we send an oper notice when a CGI:IRC has their host changed?
254                 cmd.notify = ServerInstance->Config->ConfValue("cgiirc")->getBool("opernotice", true);
255
256                 ConfigTagList tags = ServerInstance->Config->ConfTags("cgihost");
257                 for (ConfigIter i = tags.first; i != tags.second; ++i)
258                 {
259                         ConfigTag* tag = i->second;
260                         std::string hostmask = tag->getString("mask"); // An allowed CGI:IRC host
261                         std::string type = tag->getString("type"); // What type of user-munging we do on this host.
262                         std::string password = tag->getString("password");
263
264                         if(hostmask.length())
265                         {
266                                 if (type == "webirc" && password.empty())
267                                 {
268                                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Missing password in config: %s", hostmask.c_str());
269                                 }
270                                 else
271                                 {
272                                         CGItype cgitype;
273                                         if (type == "pass")
274                                                 cgitype = PASS;
275                                         else if (type == "ident")
276                                                 cgitype = IDENT;
277                                         else if (type == "passfirst")
278                                                 cgitype = PASSFIRST;
279                                         else if (type == "webirc")
280                                                 cgitype = WEBIRC;
281                                         else
282                                         {
283                                                 cgitype = PASS;
284                                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Invalid <cgihost:type> value in config: %s, setting it to \"pass\"", type.c_str());
285                                         }
286
287                                         cmd.Hosts.push_back(CGIhost(hostmask, cgitype, password));
288                                 }
289                         }
290                         else
291                         {
292                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Invalid <cgihost:mask> value in config: %s", hostmask.c_str());
293                                 continue;
294                         }
295                 }
296         }
297
298         ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
299         {
300                 if (waiting.get(user))
301                         return MOD_RES_DENY;
302
303                 if (!cmd.realip.get(user))
304                         return MOD_RES_PASSTHRU;
305
306                 RecheckClass(user);
307                 if (user->quitting)
308                         return MOD_RES_DENY;
309
310                 user->CheckLines(true);
311                 if (user->quitting)
312                         return MOD_RES_DENY;
313
314                 return MOD_RES_PASSTHRU;
315         }
316
317         ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
318         {
319                 for(CGIHostlist::iterator iter = cmd.Hosts.begin(); iter != cmd.Hosts.end(); iter++)
320                 {
321                         if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
322                         {
323                                 // Deal with it...
324                                 if(iter->type == PASS)
325                                 {
326                                         CheckPass(user); // We do nothing if it fails so...
327                                         user->CheckLines(true);
328                                 }
329                                 else if(iter->type == PASSFIRST && !CheckPass(user))
330                                 {
331                                         // If the password lookup failed, try the ident
332                                         CheckIdent(user);       // If this fails too, do nothing
333                                         user->CheckLines(true);
334                                 }
335                                 else if(iter->type == IDENT)
336                                 {
337                                         CheckIdent(user); // Nothing on failure.
338                                         user->CheckLines(true);
339                                 }
340                                 else if(iter->type == IDENTFIRST && !CheckIdent(user))
341                                 {
342                                         // If the ident lookup fails, try the password.
343                                         CheckPass(user);
344                                         user->CheckLines(true);
345                                 }
346                                 else if(iter->type == WEBIRC)
347                                 {
348                                         // We don't need to do anything here
349                                 }
350                                 return MOD_RES_PASSTHRU;
351                         }
352                 }
353                 return MOD_RES_PASSTHRU;
354         }
355
356         bool CheckPass(LocalUser* user)
357         {
358                 if(IsValidHost(user->password))
359                 {
360                         HandleIdentOrPass(user, user->password, true);
361                         user->password.clear();
362                         return true;
363                 }
364
365                 return false;
366         }
367
368         bool CheckIdent(LocalUser* user)
369         {
370                 const char* ident;
371                 in_addr newip;
372
373                 if (user->ident.length() == 8)
374                         ident = user->ident.c_str();
375                 else if (user->ident.length() == 9 && user->ident[0] == '~')
376                         ident = user->ident.c_str() + 1;
377                 else
378                         return false;
379
380                 errno = 0;
381                 unsigned long ipaddr = strtoul(ident, NULL, 16);
382                 if (errno)
383                         return false;
384                 newip.s_addr = htonl(ipaddr);
385                 std::string newipstr(inet_ntoa(newip));
386
387                 user->ident = "~cgiirc";
388                 HandleIdentOrPass(user, newipstr, false);
389
390                 return true;
391         }
392
393         bool IsValidHost(const std::string &host)
394         {
395                 if(!host.size() || host.size() > ServerInstance->Config->Limits.MaxHost)
396                         return false;
397
398                 for(unsigned int i = 0; i < host.size(); i++)
399                 {
400                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
401                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
402                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
403                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
404                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
405
406                                 continue;
407                         else
408                                 return false;
409                 }
410
411                 return true;
412         }
413
414         Version GetVersion() CXX11_OVERRIDE
415         {
416                 return Version("Change user's hosts connecting from known CGI:IRC hosts",VF_VENDOR);
417         }
418 };
419
420 MODULE_INIT(ModuleCgiIRC)