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