2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
27 #include "modules/ssl.h"
28 #include "modules/webirc.h"
29 #include "modules/whois.h"
34 RPL_WHOISGATEWAY = 350
37 // We need this method up here so that it can be accessed from anywhere
38 static void ChangeIP(LocalUser* user, const irc::sockets::sockaddrs& sa)
40 // Set the users IP address and make sure they are in the right clone pool.
41 ServerInstance->Users->RemoveCloneCounts(user);
42 user->SetClientIP(sa);
43 ServerInstance->Users->AddClone(user);
47 // Recheck the connect class.
54 // Check if this user matches any XLines.
55 user->CheckLines(true);
60 // Encapsulates information about an ident host.
68 IdentHost(const std::string& mask, const std::string& ident)
74 const std::string& GetIdent() const
79 bool Matches(LocalUser* user) const
81 if (!InspIRCd::Match(user->GetRealHost(), hostmask, ascii_case_insensitive_map))
84 return InspIRCd::MatchCIDR(user->GetIPString(), hostmask, ascii_case_insensitive_map);
88 // Encapsulates information about a WebIRC host.
93 std::string fingerprint;
98 WebIRCHost(const std::string& mask, const std::string& fp, const std::string& pass, const std::string& hash)
106 bool Matches(LocalUser* user, const std::string& pass) const
108 // Did the user send a valid password?
109 if (!password.empty() && !ServerInstance->PassCompare(user, password, pass, passhash))
112 // Does the user have a valid fingerprint?
113 const std::string fp = SSLClientCert::GetFingerprint(&user->eh);
114 if (!fingerprint.empty() && fp != fingerprint)
117 // Does the user's hostname match our hostmask?
118 if (InspIRCd::Match(user->GetRealHost(), hostmask, ascii_case_insensitive_map))
121 // Does the user's IP address match our hostmask?
122 return InspIRCd::MatchCIDR(user->GetIPString(), hostmask, ascii_case_insensitive_map);
128 * This is used for the webirc method of CGIIRC auth, and is (really) the best way to do these things.
129 * Syntax: WEBIRC password gateway hostname ip
130 * Where password is a shared key, gateway is the name of the WebIRC gateway and version (e.g. cgiirc), hostname
131 * is the resolved host of the client issuing the command and IP is the real IP of the client.
134 * To tie in with the rest of cgiirc module, and to avoid race conditions, /webirc is only processed locally
135 * and simply sets metadata on the user, which is later decoded on full connect to give something meaningful.
137 class CommandWebIRC : public SplitCommand
140 std::vector<WebIRCHost> hosts;
142 StringExtItem gateway;
143 StringExtItem realhost;
144 StringExtItem realip;
145 Events::ModuleEventProvider webircevprov;
147 CommandWebIRC(Module* Creator)
148 : SplitCommand(Creator, "WEBIRC", 4)
149 , gateway("cgiirc_gateway", ExtensionItem::EXT_USER, Creator)
150 , realhost("cgiirc_realhost", ExtensionItem::EXT_USER, Creator)
151 , realip("cgiirc_realip", ExtensionItem::EXT_USER, Creator)
152 , webircevprov(Creator, "event/webirc")
154 allow_empty_last_param = false;
155 works_before_reg = true;
156 this->syntax = "<password> <gateway> <hostname> <ip> [flags]";
159 CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
161 if (user->registered == REG_ALL || realhost.get(user))
164 for (std::vector<WebIRCHost>::const_iterator iter = hosts.begin(); iter != hosts.end(); ++iter)
166 // If we don't match the host then skip to the next host.
167 if (!iter->Matches(user, parameters[0]))
170 irc::sockets::sockaddrs ipaddr;
171 if (!irc::sockets::aptosa(parameters[3], user->client_sa.port(), ipaddr))
173 user->CommandFloodPenalty += 5000;
174 WriteLog("Connecting user %s (%s) tried to use WEBIRC but gave an invalid IP address.",
175 user->uuid.c_str(), user->GetIPString().c_str());
179 // The user matched a WebIRC block!
180 gateway.set(user, parameters[1]);
181 realhost.set(user, user->GetRealHost());
182 realip.set(user, user->GetIPString());
184 WriteLog("Connecting user %s is using a WebIRC gateway; changing their IP from %s to %s.",
185 user->uuid.c_str(), user->GetIPString().c_str(), parameters[3].c_str());
187 // If we have custom flags then deal with them.
188 WebIRC::FlagMap flags;
189 const bool hasflags = (parameters.size() > 4);
193 irc::spacesepstream flagstream(parameters[4]);
194 for (std::string flag; flagstream.GetToken(flag); )
196 // Does this flag have a value?
197 const size_t separator = flag.find('=');
198 if (separator == std::string::npos)
204 // The flag has a value!
205 const std::string key = flag.substr(0, separator);
206 const std::string value = flag.substr(separator + 1);
211 // Inform modules about the WebIRC attempt.
212 FOREACH_MOD_CUSTOM(webircevprov, WebIRC::EventListener, OnWebIRCAuth, (user, (hasflags ? &flags : NULL)));
214 // Set the IP address sent via WEBIRC. We ignore the hostname and lookup
215 // instead do our own DNS lookups because of unreliable gateways.
216 ChangeIP(user, ipaddr);
220 user->CommandFloodPenalty += 5000;
221 WriteLog("Connecting user %s (%s) tried to use WEBIRC but didn't match any configured WebIRC hosts.",
222 user->uuid.c_str(), user->GetIPString().c_str());
226 void WriteLog(const char* message, ...) CUSTOM_PRINTF(2, 3)
229 VAFORMAT(buffer, message, message);
231 // If we are sending a snotice then the message will already be
232 // written to the logfile.
234 ServerInstance->SNO->WriteGlobalSno('w', buffer);
236 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, buffer);
242 , public WebIRC::EventListener
243 , public Whois::EventListener
247 std::vector<IdentHost> hosts;
249 static bool ParseIdent(LocalUser* user, irc::sockets::sockaddrs& out)
251 const char* ident = NULL;
252 if (user->ident.length() == 8)
254 // The ident is an IPv4 address encoded in hexadecimal with two characters
255 // per address segment.
256 ident = user->ident.c_str();
258 else if (user->ident.length() == 9 && user->ident[0] == '~')
260 // The same as above but m_ident got to this user before we did. Strip the
261 // ident prefix and continue as normal.
262 ident = user->ident.c_str() + 1;
266 // The user either does not have an IPv4 in their ident or the gateway server
267 // is also running an identd. In the latter case there isn't really a lot we
268 // can do so we just assume that the client in question is not connecting via
273 // Try to convert the IP address to a string. If this fails then the user
274 // does not have an IPv4 address in their ident.
276 unsigned long address = strtoul(ident, NULL, 16);
280 out.in4.sin_family = AF_INET;
281 out.in4.sin_addr.s_addr = htonl(address);
287 : WebIRC::EventListener(this)
288 , Whois::EventListener(this)
293 void init() CXX11_OVERRIDE
295 ServerInstance->SNO->EnableSnomask('w', "CGIIRC");
298 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
300 std::vector<IdentHost> identhosts;
301 std::vector<WebIRCHost> webirchosts;
303 ConfigTagList tags = ServerInstance->Config->ConfTags("cgihost");
304 for (ConfigIter i = tags.first; i != tags.second; ++i)
306 ConfigTag* tag = i->second;
308 // Ensure that we have the <cgihost:mask> parameter.
309 const std::string mask = tag->getString("mask");
311 throw ModuleException("<cgihost:mask> is a mandatory field, at " + tag->getTagLocation());
313 // Determine what lookup type this host uses.
314 const std::string type = tag->getString("type");
315 if (stdalgo::string::equalsci(type, "ident"))
317 // The IP address should be looked up from the hex IP address.
318 const std::string newident = tag->getString("newident", "gateway", ServerInstance->IsIdent);
319 identhosts.push_back(IdentHost(mask, newident));
321 else if (stdalgo::string::equalsci(type, "webirc"))
323 // The IP address will be received via the WEBIRC command.
324 const std::string fingerprint = tag->getString("fingerprint");
325 const std::string password = tag->getString("password");
327 // WebIRC blocks require a password.
328 if (fingerprint.empty() && password.empty())
329 throw ModuleException("When using <cgihost type=\"webirc\"> either the fingerprint or password field is required, at " + tag->getTagLocation());
331 webirchosts.push_back(WebIRCHost(mask, fingerprint, password, tag->getString("hash")));
335 throw ModuleException(type + " is an invalid <cgihost:mask> type, at " + tag->getTagLocation());
339 // The host configuration was valid so we can apply it.
340 hosts.swap(identhosts);
341 cmd.hosts.swap(webirchosts);
343 // Do we send an oper notice when a m_cgiirc client has their IP changed?
344 cmd.notify = ServerInstance->Config->ConfValue("cgiirc")->getBool("opernotice", true);
347 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
349 // If <connect:webirc> is not set then we have nothing to do.
350 const std::string webirc = myclass->config->getString("webirc");
352 return MOD_RES_PASSTHRU;
354 // If the user is not connecting via a WebIRC gateway then they
355 // cannot match this connect class.
356 const std::string* gateway = cmd.gateway.get(user);
360 // If the gateway matches the <connect:webirc> constraint then
361 // allow the check to continue. Otherwise, reject it.
362 return InspIRCd::Match(*gateway, webirc) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
365 ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
367 // There is no need to check for gateways if one is already being used.
368 if (cmd.realhost.get(user))
369 return MOD_RES_PASSTHRU;
371 for (std::vector<IdentHost>::const_iterator iter = hosts.begin(); iter != hosts.end(); ++iter)
373 // If we don't match the host then skip to the next host.
374 if (!iter->Matches(user))
377 // We have matched an <cgihost> block! Try to parse the encoded IPv4 address
379 irc::sockets::sockaddrs address(user->client_sa);
380 if (!ParseIdent(user, address))
381 return MOD_RES_PASSTHRU;
383 // Store the hostname and IP of the gateway for later use.
384 cmd.realhost.set(user, user->GetRealHost());
385 cmd.realip.set(user, user->GetIPString());
387 const std::string& newident = iter->GetIdent();
388 cmd.WriteLog("Connecting user %s is using an ident gateway; changing their IP from %s to %s and their ident from %s to %s.",
389 user->uuid.c_str(), user->GetIPString().c_str(), address.addr().c_str(), user->ident.c_str(), newident.c_str());
391 user->ChangeIdent(newident);
392 ChangeIP(user, address);
395 return MOD_RES_PASSTHRU;
398 void OnWebIRCAuth(LocalUser* user, const WebIRC::FlagMap* flags) CXX11_OVERRIDE
400 // We are only interested in connection flags. If none have been
401 // given then we have nothing to do.
405 WebIRC::FlagMap::const_iterator cport = flags->find("remote-port");
406 if (cport != flags->end())
408 // If we can't parse the port then just give up.
409 uint16_t port = ConvToNum<uint16_t>(cport->second);
412 switch (user->client_sa.family())
415 user->client_sa.in4.sin_port = htons(port);
419 user->client_sa.in6.sin6_port = htons(port);
423 // If we have reached this point then we have encountered a bug.
424 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: OnWebIRCAuth(%s): socket type %d is unknown!",
425 user->uuid.c_str(), user->client_sa.family());
431 WebIRC::FlagMap::const_iterator sport = flags->find("local-port");
432 if (sport != flags->end())
434 // If we can't parse the port then just give up.
435 uint16_t port = ConvToNum<uint16_t>(sport->second);
438 switch (user->server_sa.family())
441 user->server_sa.in4.sin_port = htons(port);
445 user->server_sa.in6.sin6_port = htons(port);
449 // If we have reached this point then we have encountered a bug.
450 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: OnWebIRCAuth(%s): socket type %d is unknown!",
451 user->uuid.c_str(), user->server_sa.family());
458 void OnWhois(Whois::Context& whois) CXX11_OVERRIDE
460 if (!whois.IsSelfWhois() && !whois.GetSource()->HasPrivPermission("users/auspex"))
463 // If these fields are not set then the client is not using a gateway.
464 const std::string* realhost = cmd.realhost.get(whois.GetTarget());
465 const std::string* realip = cmd.realip.get(whois.GetTarget());
466 if (!realhost || !realip)
469 const std::string* gateway = cmd.gateway.get(whois.GetTarget());
471 whois.SendLine(RPL_WHOISGATEWAY, *realhost, *realip, "is connected via the " + *gateway + " WebIRC gateway");
473 whois.SendLine(RPL_WHOISGATEWAY, *realhost, *realip, "is connected via an ident gateway");
476 Version GetVersion() CXX11_OVERRIDE
478 return Version("Enables forwarding the real IP address of a user from a gateway to the IRC server", VF_VENDOR);
482 MODULE_INIT(ModuleCgiIRC)