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