]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
Redo OnSetEndPoint logic to fix duplicate clones (#1549).
[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/ssl.h"
28 #include "modules/webirc.h"
29 #include "modules/whois.h"
30
31 enum
32 {
33         // InspIRCd-specific.
34         RPL_WHOISGATEWAY = 350
35 };
36
37 // Encapsulates information about an ident host.
38 class IdentHost
39 {
40  private:
41         std::string hostmask;
42         std::string newident;
43
44  public:
45         IdentHost(const std::string& mask, const std::string& ident)
46                 : hostmask(mask)
47                 , newident(ident)
48         {
49         }
50
51         const std::string& GetIdent() const
52         {
53                 return newident;
54         }
55
56         bool Matches(LocalUser* user) const
57         {
58                 if (!InspIRCd::Match(user->GetRealHost(), hostmask, ascii_case_insensitive_map))
59                         return false;
60
61                 return InspIRCd::MatchCIDR(user->GetIPString(), hostmask, ascii_case_insensitive_map);
62         }
63 };
64
65 // Encapsulates information about a WebIRC host.
66 class WebIRCHost
67 {
68  private:
69         std::string hostmask;
70         std::string fingerprint;
71         std::string password;
72         std::string passhash;
73
74  public:
75         WebIRCHost(const std::string& mask, const std::string& fp, const std::string& pass, const std::string& hash)
76                 : hostmask(mask)
77                 , fingerprint(fp)
78                 , password(pass)
79                 , passhash(hash)
80         {
81         }
82
83         bool Matches(LocalUser* user, const std::string& pass, UserCertificateAPI& sslapi) const
84         {
85                 // Did the user send a valid password?
86                 if (!password.empty() && !ServerInstance->PassCompare(user, password, pass, passhash))
87                         return false;
88
89                 // Does the user have a valid fingerprint?
90                 const std::string fp = sslapi ? sslapi->GetFingerprint(user) : "";
91                 if (!fingerprint.empty() && !InspIRCd::TimingSafeCompare(fp, fingerprint))
92                         return false;
93
94                 // Does the user's hostname match our hostmask?
95                 if (InspIRCd::Match(user->GetRealHost(), hostmask, ascii_case_insensitive_map))
96                         return true;
97
98                 // Does the user's IP address match our hostmask?
99                 return InspIRCd::MatchCIDR(user->GetIPString(), hostmask, ascii_case_insensitive_map);
100         }
101 };
102
103 /*
104  * WEBIRC
105  *  This is used for the webirc method of CGIIRC auth, and is (really) the best way to do these things.
106  *  Syntax: WEBIRC password gateway hostname ip
107  *  Where password is a shared key, gateway is the name of the WebIRC gateway and version (e.g. cgiirc), hostname
108  *  is the resolved host of the client issuing the command and IP is the real IP of the client.
109  *
110  * How it works:
111  *  To tie in with the rest of cgiirc module, and to avoid race conditions, /webirc is only processed locally
112  *  and simply sets metadata on the user, which is later decoded on full connect to give something meaningful.
113  */
114 class CommandWebIRC : public SplitCommand
115 {
116  public:
117         std::vector<WebIRCHost> hosts;
118         bool notify;
119         StringExtItem gateway;
120         StringExtItem realhost;
121         StringExtItem realip;
122         UserCertificateAPI sslapi;
123         Events::ModuleEventProvider webircevprov;
124
125         CommandWebIRC(Module* Creator)
126                 : SplitCommand(Creator, "WEBIRC", 4)
127                 , gateway("cgiirc_gateway", ExtensionItem::EXT_USER, Creator)
128                 , realhost("cgiirc_realhost", ExtensionItem::EXT_USER, Creator)
129                 , realip("cgiirc_realip", ExtensionItem::EXT_USER, Creator)
130                 , sslapi(Creator)
131                 , webircevprov(Creator, "event/webirc")
132         {
133                 allow_empty_last_param = false;
134                 works_before_reg = true;
135                 this->syntax = "<password> <gateway> <hostname> <ip> [flags]";
136         }
137
138         CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
139         {
140                 if (user->registered == REG_ALL || realhost.get(user))
141                         return CMD_FAILURE;
142
143                 for (std::vector<WebIRCHost>::const_iterator iter = hosts.begin(); iter != hosts.end(); ++iter)
144                 {
145                         // If we don't match the host then skip to the next host.
146                         if (!iter->Matches(user, parameters[0], sslapi))
147                                 continue;
148
149                         irc::sockets::sockaddrs ipaddr;
150                         if (!irc::sockets::aptosa(parameters[3], user->client_sa.port(), ipaddr))
151                         {
152                                 WriteLog("Connecting user %s (%s) tried to use WEBIRC but gave an invalid IP address.",
153                                         user->uuid.c_str(), user->GetIPString().c_str());
154                                 ServerInstance->Users->QuitUser(user, "WEBIRC: IP address is invalid: " + parameters[3]);
155                                 return CMD_FAILURE;
156                         }
157
158                         // The user matched a WebIRC block!
159                         gateway.set(user, parameters[1]);
160                         realhost.set(user, user->GetRealHost());
161                         realip.set(user, user->GetIPString());
162
163                         WriteLog("Connecting user %s is using a WebIRC gateway; changing their IP from %s to %s.",
164                                 user->uuid.c_str(), user->GetIPString().c_str(), parameters[3].c_str());
165
166                         // If we have custom flags then deal with them.
167                         WebIRC::FlagMap flags;
168                         const bool hasflags = (parameters.size() > 4);
169                         if (hasflags)
170                         {
171                                 // Parse the flags.
172                                 irc::spacesepstream flagstream(parameters[4]);
173                                 for (std::string flag; flagstream.GetToken(flag); )
174                                 {
175                                         // Does this flag have a value?
176                                         const size_t separator = flag.find('=');
177                                         if (separator == std::string::npos)
178                                         {
179                                                 flags[flag];
180                                                 continue;
181                                         }
182
183                                         // The flag has a value!
184                                         const std::string key = flag.substr(0, separator);
185                                         const std::string value = flag.substr(separator + 1);
186                                         flags[key] = value;
187                                 }
188                         }
189
190                         // Inform modules about the WebIRC attempt.
191                         FOREACH_MOD_CUSTOM(webircevprov, WebIRC::EventListener, OnWebIRCAuth, (user, (hasflags ? &flags : NULL)));
192
193                         // Set the IP address sent via WEBIRC. We ignore the hostname and lookup
194                         // instead do our own DNS lookups because of unreliable gateways.
195                         user->SetClientIP(ipaddr);
196                         return CMD_SUCCESS;
197                 }
198
199                 WriteLog("Connecting user %s (%s) tried to use WEBIRC but didn't match any configured WebIRC hosts.",
200                         user->uuid.c_str(), user->GetIPString().c_str());
201                 ServerInstance->Users->QuitUser(user, "WEBIRC: you don't match any configured WebIRC hosts.");
202                 return CMD_FAILURE;
203         }
204
205         void WriteLog(const char* message, ...) CUSTOM_PRINTF(2, 3)
206         {
207                 std::string buffer;
208                 VAFORMAT(buffer, message, message);
209
210                 // If we are sending a snotice then the message will already be
211                 // written to the logfile.
212                 if (notify)
213                         ServerInstance->SNO->WriteGlobalSno('w', buffer);
214                 else
215                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, buffer);
216         }
217 };
218
219 class ModuleCgiIRC
220         : public Module
221         , public WebIRC::EventListener
222         , public Whois::EventListener
223 {
224  private:
225         CommandWebIRC cmd;
226         std::vector<IdentHost> hosts;
227
228         static bool ParseIdent(LocalUser* user, irc::sockets::sockaddrs& out)
229         {
230                 const char* ident = NULL;
231                 if (user->ident.length() == 8)
232                 {
233                         // The ident is an IPv4 address encoded in hexadecimal with two characters
234                         // per address segment.
235                         ident = user->ident.c_str();
236                 }
237                 else if (user->ident.length() == 9 && user->ident[0] == '~')
238                 {
239                         // The same as above but m_ident got to this user before we did. Strip the
240                         // ident prefix and continue as normal.
241                         ident = user->ident.c_str() + 1;
242                 }
243                 else
244                 {
245                         // The user either does not have an IPv4 in their ident or the gateway server
246                         // is also running an identd. In the latter case there isn't really a lot we
247                         // can do so we just assume that the client in question is not connecting via
248                         // an ident gateway.
249                         return false;
250                 }
251
252                 // Try to convert the IP address to a string. If this fails then the user
253                 // does not have an IPv4 address in their ident.
254                 errno = 0;
255                 unsigned long address = strtoul(ident, NULL, 16);
256                 if (errno)
257                         return false;
258
259                 out.in4.sin_family = AF_INET;
260                 out.in4.sin_addr.s_addr = htonl(address);
261                 return true;
262         }
263
264  public:
265         ModuleCgiIRC()
266                 : WebIRC::EventListener(this)
267                 , Whois::EventListener(this)
268                 , cmd(this)
269         {
270         }
271
272         void init() CXX11_OVERRIDE
273         {
274                 ServerInstance->SNO->EnableSnomask('w', "CGIIRC");
275         }
276
277         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
278         {
279                 std::vector<IdentHost> identhosts;
280                 std::vector<WebIRCHost> webirchosts;
281
282                 ConfigTagList tags = ServerInstance->Config->ConfTags("cgihost");
283                 for (ConfigIter i = tags.first; i != tags.second; ++i)
284                 {
285                         ConfigTag* tag = i->second;
286
287                         // Ensure that we have the <cgihost:mask> parameter.
288                         const std::string mask = tag->getString("mask");
289                         if (mask.empty())
290                                 throw ModuleException("<cgihost:mask> is a mandatory field, at " + tag->getTagLocation());
291
292                         // Determine what lookup type this host uses.
293                         const std::string type = tag->getString("type");
294                         if (stdalgo::string::equalsci(type, "ident"))
295                         {
296                                 // The IP address should be looked up from the hex IP address.
297                                 const std::string newident = tag->getString("newident", "gateway", ServerInstance->IsIdent);
298                                 identhosts.push_back(IdentHost(mask, newident));
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 changed?
323                 cmd.notify = ServerInstance->Config->ConfValue("cgiirc")->getBool("opernotice", true);
324         }
325
326         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
327         {
328                 // If <connect:webirc> is not set then we have nothing to do.
329                 const std::string webirc = myclass->config->getString("webirc");
330                 if (webirc.empty())
331                         return MOD_RES_PASSTHRU;
332
333                 // If the user is not connecting via a WebIRC gateway then they
334                 // cannot match this connect class.
335                 const std::string* gateway = cmd.gateway.get(user);
336                 if (!gateway)
337                         return MOD_RES_DENY;
338
339                 // If the gateway matches the <connect:webirc> constraint then
340                 // allow the check to continue. Otherwise, reject it.
341                 return InspIRCd::Match(*gateway, webirc) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
342         }
343
344         ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
345         {
346                 // There is no need to check for gateways if one is already being used.
347                 if (cmd.realhost.get(user))
348                         return MOD_RES_PASSTHRU;
349
350                 for (std::vector<IdentHost>::const_iterator iter = hosts.begin(); iter != hosts.end(); ++iter)
351                 {
352                         // If we don't match the host then skip to the next host.
353                         if (!iter->Matches(user))
354                                 continue;
355
356                         // We have matched an <cgihost> block! Try to parse the encoded IPv4 address
357                         // out of the ident.
358                         irc::sockets::sockaddrs address(user->client_sa);
359                         if (!ParseIdent(user, address))
360                                 return MOD_RES_PASSTHRU;
361
362                         // Store the hostname and IP of the gateway for later use.
363                         cmd.realhost.set(user, user->GetRealHost());
364                         cmd.realip.set(user, user->GetIPString());
365
366                         const std::string& newident = iter->GetIdent();
367                         cmd.WriteLog("Connecting user %s is using an ident gateway; changing their IP from %s to %s and their ident from %s to %s.",
368                                 user->uuid.c_str(), user->GetIPString().c_str(), address.addr().c_str(), user->ident.c_str(), newident.c_str());
369
370                         user->ChangeIdent(newident);
371                         user->SetClientIP(address);
372                         break; 
373                 }
374                 return MOD_RES_PASSTHRU;
375         }
376
377         void OnWebIRCAuth(LocalUser* user, const WebIRC::FlagMap* flags) CXX11_OVERRIDE
378         {
379                 // We are only interested in connection flags. If none have been
380                 // given then we have nothing to do.
381                 if (!flags)
382                         return;
383
384                 WebIRC::FlagMap::const_iterator cport = flags->find("remote-port");
385                 if (cport != flags->end())
386                 {
387                         // If we can't parse the port then just give up.
388                         uint16_t port = ConvToNum<uint16_t>(cport->second);
389                         if (port)
390                         {
391                                 switch (user->client_sa.family())
392                                 {
393                                         case AF_INET:
394                                                 user->client_sa.in4.sin_port = htons(port);
395                                                 break;
396
397                                         case AF_INET6:
398                                                 user->client_sa.in6.sin6_port = htons(port);
399                                                 break;
400
401                                         default:
402                                                 // If we have reached this point then we have encountered a bug.
403                                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: OnWebIRCAuth(%s): socket type %d is unknown!",
404                                                         user->uuid.c_str(), user->client_sa.family());
405                                                 return;
406                                 }
407                         }
408                 }
409
410                 WebIRC::FlagMap::const_iterator sport = flags->find("local-port");
411                 if (sport != flags->end())
412                 {
413                         // If we can't parse the port then just give up.
414                         uint16_t port = ConvToNum<uint16_t>(sport->second);
415                         if (port)
416                         {
417                                 switch (user->server_sa.family())
418                                 {
419                                         case AF_INET:
420                                                 user->server_sa.in4.sin_port = htons(port);
421                                                 break;
422
423                                         case AF_INET6:
424                                                 user->server_sa.in6.sin6_port = htons(port);
425                                                 break;
426
427                                         default:
428                                                 // If we have reached this point then we have encountered a bug.
429                                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: OnWebIRCAuth(%s): socket type %d is unknown!",
430                                                         user->uuid.c_str(), user->server_sa.family());
431                                                 return;
432                                 }
433                         }
434                 }
435         }
436
437         void OnWhois(Whois::Context& whois) CXX11_OVERRIDE
438         {
439                 if (!whois.IsSelfWhois() && !whois.GetSource()->HasPrivPermission("users/auspex"))
440                         return;
441
442                 // If these fields are not set then the client is not using a gateway.
443                 const std::string* realhost = cmd.realhost.get(whois.GetTarget());
444                 const std::string* realip = cmd.realip.get(whois.GetTarget());
445                 if (!realhost || !realip)
446                         return;
447
448                 const std::string* gateway = cmd.gateway.get(whois.GetTarget());
449                 if (gateway)
450                         whois.SendLine(RPL_WHOISGATEWAY, *realhost, *realip, "is connected via the " + *gateway + " WebIRC gateway");
451                 else
452                         whois.SendLine(RPL_WHOISGATEWAY, *realhost, *realip, "is connected via an ident gateway");
453         }
454
455         Version GetVersion() CXX11_OVERRIDE
456         {
457                 return Version("Enables forwarding the real IP address of a user from a gateway to the IRC server", VF_VENDOR);
458         }
459 };
460
461 MODULE_INIT(ModuleCgiIRC)