]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
Rewrite the m_cgiirc configuration handling.
[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 // We need this method up here so that it can be accessed from anywhere
31 static void ChangeIP(User* user, const std::string& newip)
32 {
33         ServerInstance->Users->RemoveCloneCounts(user);
34         user->SetClientIP(newip.c_str());
35         ServerInstance->Users->AddClone(user);
36 }
37
38 // Encapsulates information about a WebIRC host.
39 class WebIRCHost
40 {
41  private:
42         const std::string hostmask;
43         const std::string password;
44
45  public:
46         WebIRCHost(const std::string& mask, const std::string& pass)
47                 : hostmask(mask)
48                 , password(pass)
49         {
50         }
51
52         bool Matches(LocalUser* user, const std::string& pass) const
53         {
54                 // Did the user send a valid password?
55                 if (!InspIRCd::TimingSafeCompare(password, pass))
56                         return false;
57
58                 // Does the user's hostname match our hostmask?
59                 if (InspIRCd::Match(user->host, hostmask, ascii_case_insensitive_map))
60                         return true;
61
62                 // Does the user's IP address match our hostmask?
63                 return InspIRCd::MatchCIDR(user->GetIPString(), hostmask, ascii_case_insensitive_map);
64         }
65 };
66
67 /*
68  * WEBIRC
69  *  This is used for the webirc method of CGIIRC auth, and is (really) the best way to do these things.
70  *  Syntax: WEBIRC password gateway hostname ip
71  *  Where password is a shared key, gateway is the name of the WebIRC gateway and version (e.g. cgiirc), hostname
72  *  is the resolved host of the client issuing the command and IP is the real IP of the client.
73  *
74  * How it works:
75  *  To tie in with the rest of cgiirc module, and to avoid race conditions, /webirc is only processed locally
76  *  and simply sets metadata on the user, which is later decoded on full connect to give something meaningful.
77  */
78 class CommandWebIRC : public SplitCommand
79 {
80  public:
81         std::vector<WebIRCHost> hosts;
82         bool notify;
83         StringExtItem gateway;
84         StringExtItem realhost;
85         StringExtItem realip;
86
87         CommandWebIRC(Module* Creator)
88                 : SplitCommand(Creator, "WEBIRC", 4)
89                 , gateway("cgiirc_gateway", ExtensionItem::EXT_USER, Creator)
90                 , realhost("cgiirc_realhost", ExtensionItem::EXT_USER, Creator)
91                 , realip("cgiirc_realip", ExtensionItem::EXT_USER, Creator)
92                 {
93                         allow_empty_last_param = false;
94                         works_before_reg = true;
95                         this->syntax = "password gateway hostname ip";
96                 }
97                 CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user)
98                 {
99                         if(user->registered == REG_ALL)
100                                 return CMD_FAILURE;
101
102                         irc::sockets::sockaddrs ipaddr;
103                         if (!irc::sockets::aptosa(parameters[3], 0, ipaddr))
104                         {
105                                 user->CommandFloodPenalty += 5000;
106                                 ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s tried to use WEBIRC but gave an invalid IP address.", user->GetFullRealHost().c_str());
107                                 return CMD_FAILURE;
108                         }
109
110                         for (std::vector<WebIRCHost>::const_iterator iter = hosts.begin(); iter != hosts.end(); ++iter)
111                         {
112                                 // If we don't match the host then skip to the next host.
113                                 if (!iter->Matches(user, parameters[0]))
114                                         continue;
115
116                                 {
117                                         {
118                                                 gateway.set(user, parameters[1]);
119                                                 realhost.set(user, user->host);
120                                                 realip.set(user, user->GetIPString());
121
122                                                 // 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
123                                                 bool host_ok = (parameters[2].length() <= ServerInstance->Config->Limits.MaxHost) && (parameters[2].find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-") == std::string::npos);
124                                                 const std::string& newhost = (host_ok ? parameters[2] : parameters[3]);
125
126                                                 if (notify)
127                                                         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());
128
129                                                 // Where the magic happens - change their IP
130                                                 ChangeIP(user, parameters[3]);
131                                                 // And follow this up by changing their host
132                                                 user->host = user->dhost = newhost;
133                                                 user->InvalidateCache();
134
135                                                 return CMD_SUCCESS;
136                                         }
137                                 }
138                         }
139
140                         user->CommandFloodPenalty += 5000;
141                         ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str());
142                         return CMD_FAILURE;
143                 }
144 };
145
146
147 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
148  */
149 class CGIResolver : public DNS::Request
150 {
151         std::string theiruid;
152         LocalIntExt& waiting;
153         bool notify;
154  public:
155         CGIResolver(DNS::Manager* mgr, Module* me, bool NotifyOpers, const std::string &source, LocalUser* u, LocalIntExt& ext)
156                 : DNS::Request(mgr, me, source, DNS::QUERY_PTR)
157                 , theiruid(u->uuid)
158                 , waiting(ext)
159                 , notify(NotifyOpers)
160         {
161         }
162
163         void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
164         {
165                 /* Check the user still exists */
166                 User* them = ServerInstance->FindUUID(theiruid);
167                 if ((them) && (!them->quitting))
168                 {
169                         LocalUser* lu = IS_LOCAL(them);
170                         if (!lu)
171                                 return;
172
173                         const DNS::ResourceRecord &ans_record = r->answers[0];
174                         if (ans_record.rdata.empty() || ans_record.rdata.length() > ServerInstance->Config->Limits.MaxHost)
175                                 return;
176
177                         if (notify)
178                                 ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s", them->nick.c_str(), them->host.c_str(), ans_record.rdata.c_str());
179
180                         them->host = them->dhost = ans_record.rdata;
181                         them->InvalidateCache();
182                         lu->CheckLines(true);
183                 }
184         }
185
186         void OnError(const DNS::Query *r) CXX11_OVERRIDE
187         {
188                 if (!notify)
189                         return;
190
191                 User* them = ServerInstance->FindUUID(theiruid);
192                 if ((them) && (!them->quitting))
193                 {
194                         ServerInstance->SNO->WriteToSnoMask('w', "Connecting user %s detected as using CGI:IRC (%s), but their host can't be resolved!", them->nick.c_str(), them->host.c_str());
195                 }
196         }
197
198         ~CGIResolver()
199         {
200                 User* them = ServerInstance->FindUUID(theiruid);
201                 if (!them)
202                         return;
203                 int count = waiting.get(them);
204                 if (count)
205                         waiting.set(them, count - 1);
206         }
207 };
208
209 class ModuleCgiIRC : public Module
210 {
211         CommandWebIRC cmd;
212         LocalIntExt waiting;
213         dynamic_reference<DNS::Manager> DNS;
214         std::vector<std::string> hosts;
215
216         static void RecheckClass(LocalUser* user)
217         {
218                 user->MyClass = NULL;
219                 user->SetClass();
220                 user->CheckClass();
221         }
222
223         void HandleIdent(LocalUser* user, const std::string& newip)
224         {
225                 cmd.realhost.set(user, user->host);
226                 cmd.realip.set(user, user->GetIPString());
227                 ChangeIP(user, newip);
228                 user->host = user->dhost = user->GetIPString();
229                 user->InvalidateCache();
230                 RecheckClass(user);
231
232                 // Don't create the resolver if the core couldn't put the user in a connect class or when dns is disabled
233                 if (user->quitting || !DNS || !user->MyClass->resolvehostnames)
234                         return;
235
236                 CGIResolver* r = new CGIResolver(*this->DNS, this, cmd.notify, newip, user, waiting);
237                 try
238                 {
239                         waiting.set(user, waiting.get(user) + 1);
240                         this->DNS->Process(r);
241                 }
242                 catch (DNS::Exception &ex)
243                 {
244                         int count = waiting.get(user);
245                         if (count)
246                                 waiting.set(user, count - 1);
247                         delete r;
248                         if (cmd.notify)
249                                  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());
250                 }
251         }
252
253 public:
254         ModuleCgiIRC()
255                 : cmd(this)
256                 , waiting("cgiirc-delay", ExtensionItem::EXT_USER, this)
257                 , DNS(this, "DNS")
258         {
259         }
260
261         void init() CXX11_OVERRIDE
262         {
263                 ServerInstance->SNO->EnableSnomask('w', "CGIIRC");
264         }
265
266         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
267         {
268                 std::vector<std::string> identhosts;
269                 std::vector<WebIRCHost> webirchosts;
270
271                 ConfigTagList tags = ServerInstance->Config->ConfTags("cgihost");
272                 for (ConfigIter i = tags.first; i != tags.second; ++i)
273                 {
274                         ConfigTag* tag = i->second;
275
276                         // Ensure that we have the <cgihost:mask> parameter.
277                         const std::string mask = tag->getString("mask");
278                         if (mask.empty())
279                                 throw ModuleException("<cgihost:mask> is a mandatory field, at " + tag->getTagLocation());
280
281                         // Determine what lookup type this host uses.
282                         const std::string type = tag->getString("type");
283                         if (stdalgo::string::equalsci(type, "ident"))
284                         {
285                                 // The IP address should be looked up from the hex IP address.
286                                 identhosts.push_back(mask);
287                         }
288                         else if (stdalgo::string::equalsci(type, "webirc"))
289                         {
290                                 // The IP address will be received via the WEBIRC command.
291                                 const std::string password = tag->getString("password");
292
293                                 // WebIRC blocks require a password.
294                                 if (password.empty())
295                                         throw ModuleException("When using <cgihost type=\"webirc\"> the password field is required, at " + tag->getTagLocation());
296
297                                 webirchosts.push_back(WebIRCHost(mask, password));
298                         }
299                         else
300                         {
301                                 throw ModuleException(type + " is an invalid <cgihost:mask> type, at " + tag->getTagLocation()); 
302                         }
303                 }
304
305                 // The host configuration was valid so we can apply it.
306                 hosts.swap(identhosts);
307                 cmd.hosts.swap(webirchosts);
308
309                 // Do we send an oper notice when a m_cgiirc client has their IP/host changed?
310                 cmd.notify = ServerInstance->Config->ConfValue("cgiirc")->getBool("opernotice", true);
311         }
312
313         ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
314         {
315                 if (waiting.get(user))
316                         return MOD_RES_DENY;
317
318                 if (!cmd.realip.get(user))
319                         return MOD_RES_PASSTHRU;
320
321                 RecheckClass(user);
322                 if (user->quitting)
323                         return MOD_RES_DENY;
324
325                 user->CheckLines(true);
326                 if (user->quitting)
327                         return MOD_RES_DENY;
328
329                 return MOD_RES_PASSTHRU;
330         }
331
332         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
333         {
334                 // If <connect:webirc> is not set then we have nothing to do.
335                 const std::string webirc = myclass->config->getString("webirc");
336                 if (webirc.empty())
337                         return MOD_RES_PASSTHRU;
338
339                 // If the user is not connecting via a WebIRC gateway then they
340                 // cannot match this connect class.
341                 const std::string* gateway = cmd.gateway.get(user);
342                 if (!gateway)
343                         return MOD_RES_DENY;
344
345                 // If the gateway matches the <connect:webirc> constraint then
346                 // allow the check to continue. Otherwise, reject it.
347                 return InspIRCd::Match(*gateway, webirc) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
348         }
349
350         ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
351         {
352                 for (std::vector<std::string>::const_iterator iter = hosts.begin(); iter != hosts.end(); ++iter)
353                 {
354                         if (!InspIRCd::Match(user->host, *iter, ascii_case_insensitive_map) && !InspIRCd::MatchCIDR(user->GetIPString(), *iter, ascii_case_insensitive_map))
355                                 continue;
356
357                         CheckIdent(user); // Nothing on failure.
358                         user->CheckLines(true);
359                         break;
360                 }
361                 return MOD_RES_PASSTHRU;
362         }
363
364         bool CheckIdent(LocalUser* user)
365         {
366                 const char* ident;
367                 in_addr newip;
368
369                 if (user->ident.length() == 8)
370                         ident = user->ident.c_str();
371                 else if (user->ident.length() == 9 && user->ident[0] == '~')
372                         ident = user->ident.c_str() + 1;
373                 else
374                         return false;
375
376                 errno = 0;
377                 unsigned long ipaddr = strtoul(ident, NULL, 16);
378                 if (errno)
379                         return false;
380                 newip.s_addr = htonl(ipaddr);
381                 std::string newipstr(inet_ntoa(newip));
382
383                 user->ident = "~cgiirc";
384                 HandleIdent(user, newipstr);
385
386                 return true;
387         }
388
389         Version GetVersion() CXX11_OVERRIDE
390         {
391                 return Version("Change user's hosts connecting from known CGI:IRC hosts",VF_VENDOR);
392         }
393 };
394
395 MODULE_INIT(ModuleCgiIRC)