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