2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5 * Copyright (C) 2014 md_5 <git@md-5.net>
6 * Copyright (C) 2014 Googolplexed <googol@googolplexed.net>
7 * Copyright (C) 2013, 2017-2018, 2020-2021 Sadie Powell <sadie@witchery.services>
8 * Copyright (C) 2013 Adam <Adam@anope.org>
9 * Copyright (C) 2012-2013, 2015 Attila Molnar <attilamolnar@hush.com>
10 * Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
11 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
12 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
13 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
14 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
15 * Copyright (C) 2006-2007, 2010 Craig Edwards <brain@inspircd.org>
17 * This file is part of InspIRCd. InspIRCd is free software: you can
18 * redistribute it and/or modify it under the terms of the GNU General Public
19 * License as published by the Free Software Foundation, version 2.
21 * This program is distributed in the hope that it will be useful, but WITHOUT
22 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
23 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
26 * You should have received a copy of the GNU General Public License
27 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 #include "modules/ssl.h"
33 #include "modules/webirc.h"
34 #include "modules/whois.h"
39 RPL_WHOISGATEWAY = 350
42 // One or more hostmask globs or CIDR ranges.
43 typedef std::vector<std::string> MaskList;
45 // Encapsulates information about an ident host.
53 IdentHost(const MaskList& masks, const std::string& ident)
59 const std::string& GetIdent() const
64 bool Matches(LocalUser* user) const
66 for (MaskList::const_iterator iter = hostmasks.begin(); iter != hostmasks.end(); ++iter)
68 // Does the user's hostname match this hostmask?
69 if (InspIRCd::Match(user->GetRealHost(), *iter, ascii_case_insensitive_map))
72 // Does the user's IP address match this hostmask?
73 if (InspIRCd::MatchCIDR(user->GetIPString(), *iter, ascii_case_insensitive_map))
77 // The user didn't match any hostmasks.
82 // Encapsulates information about a WebIRC host.
87 std::string fingerprint;
92 WebIRCHost(const MaskList& masks, const std::string& fp, const std::string& pass, const std::string& hash)
100 bool Matches(LocalUser* user, const std::string& pass, UserCertificateAPI& sslapi) const
102 // Did the user send a valid password?
103 if (!password.empty() && !ServerInstance->PassCompare(user, password, pass, passhash))
106 // Does the user have a valid fingerprint?
107 const std::string fp = sslapi ? sslapi->GetFingerprint(user) : "";
108 if (!fingerprint.empty() && !InspIRCd::TimingSafeCompare(fp, fingerprint))
111 for (MaskList::const_iterator iter = hostmasks.begin(); iter != hostmasks.end(); ++iter)
113 // Does the user's hostname match this hostmask?
114 if (InspIRCd::Match(user->GetRealHost(), *iter, ascii_case_insensitive_map))
117 // Does the user's IP address match this hostmask?
118 if (InspIRCd::MatchCIDR(user->GetIPString(), *iter, ascii_case_insensitive_map))
122 // The user didn't match any hostmasks.
127 class CommandHexIP : public SplitCommand
130 CommandHexIP(Module* Creator)
131 : SplitCommand(Creator, "HEXIP", 1)
133 allow_empty_last_param = false;
135 syntax = "<hex-ip|raw-ip>";
138 CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
140 irc::sockets::sockaddrs sa;
141 if (irc::sockets::aptosa(parameters[0], 0, sa))
143 if (sa.family() != AF_INET)
145 user->WriteNotice("*** HEXIP: You can only hex encode an IPv4 address!");
149 uint32_t addr = sa.in4.sin_addr.s_addr;
150 user->WriteNotice(InspIRCd::Format("*** HEXIP: %s encodes to %02x%02x%02x%02x.",
151 sa.addr().c_str(), (addr & 0xFF), ((addr >> 8) & 0xFF), ((addr >> 16) & 0xFF),
152 ((addr >> 24) & 0xFF)));
156 if (ParseIP(parameters[0], sa))
158 user->WriteNotice(InspIRCd::Format("*** HEXIP: %s decodes to %s.",
159 parameters[0].c_str(), sa.addr().c_str()));
163 user->WriteNotice(InspIRCd::Format("*** HEXIP: %s is not a valid raw or hex encoded IPv4 address.",
164 parameters[0].c_str()));
168 static bool ParseIP(const std::string& in, irc::sockets::sockaddrs& out)
170 const char* ident = NULL;
171 if (in.length() == 8)
173 // The ident is an IPv4 address encoded in hexadecimal with two characters
174 // per address segment.
177 else if (in.length() == 9 && in[0] == '~')
179 // The same as above but m_ident got to this user before we did. Strip the
180 // ident prefix and continue as normal.
181 ident = in.c_str() + 1;
185 // The user either does not have an IPv4 in their ident or the gateway server
186 // is also running an identd. In the latter case there isn't really a lot we
187 // can do so we just assume that the client in question is not connecting via
192 // Try to convert the IP address to a string. If this fails then the user
193 // does not have an IPv4 address in their ident.
195 unsigned long address = strtoul(ident, NULL, 16);
199 out.in4.sin_family = AF_INET;
200 out.in4.sin_addr.s_addr = htonl(address);
205 class CommandWebIRC : public SplitCommand
208 std::vector<WebIRCHost> hosts;
210 StringExtItem gateway;
211 StringExtItem realhost;
212 StringExtItem realip;
213 UserCertificateAPI sslapi;
214 Events::ModuleEventProvider webircevprov;
216 CommandWebIRC(Module* Creator)
217 : SplitCommand(Creator, "WEBIRC", 4)
218 , gateway("cgiirc_gateway", ExtensionItem::EXT_USER, Creator)
219 , realhost("cgiirc_realhost", ExtensionItem::EXT_USER, Creator)
220 , realip("cgiirc_realip", ExtensionItem::EXT_USER, Creator)
222 , webircevprov(Creator, "event/webirc")
224 allow_empty_last_param = false;
225 works_before_reg = true;
226 this->syntax = "<password> <gateway> <hostname> <ip> [<flags>]";
229 CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
231 if (user->registered == REG_ALL || realhost.get(user))
234 for (std::vector<WebIRCHost>::const_iterator iter = hosts.begin(); iter != hosts.end(); ++iter)
236 // If we don't match the host then skip to the next host.
237 if (!iter->Matches(user, parameters[0], sslapi))
240 irc::sockets::sockaddrs ipaddr;
241 if (!irc::sockets::aptosa(parameters[3], user->client_sa.port(), ipaddr))
243 WriteLog("Connecting user %s (%s) tried to use WEBIRC but gave an invalid IP address.",
244 user->uuid.c_str(), user->GetIPString().c_str());
245 ServerInstance->Users->QuitUser(user, "WEBIRC: IP address is invalid: " + parameters[3]);
249 // The user matched a WebIRC block!
250 gateway.set(user, parameters[1]);
251 realhost.set(user, user->GetRealHost());
252 realip.set(user, user->GetIPString());
254 WriteLog("Connecting user %s is using the %s WebIRC gateway; changing their IP from %s to %s.",
255 user->uuid.c_str(), parameters[1].c_str(),
256 user->GetIPString().c_str(), parameters[3].c_str());
258 // If we have custom flags then deal with them.
259 WebIRC::FlagMap flags;
260 const bool hasflags = (parameters.size() > 4);
264 irc::spacesepstream flagstream(parameters[4]);
265 for (std::string flag; flagstream.GetToken(flag); )
267 // Does this flag have a value?
268 const size_t separator = flag.find('=');
269 if (separator == std::string::npos)
275 // The flag has a value!
276 const std::string key = flag.substr(0, separator);
277 const std::string value = flag.substr(separator + 1);
282 // Inform modules about the WebIRC attempt.
283 FOREACH_MOD_CUSTOM(webircevprov, WebIRC::EventListener, OnWebIRCAuth, (user, (hasflags ? &flags : NULL)));
285 // Set the IP address sent via WEBIRC. We ignore the hostname and lookup
286 // instead do our own DNS lookups because of unreliable gateways.
287 user->SetClientIP(ipaddr);
291 WriteLog("Connecting user %s (%s) tried to use WEBIRC but didn't match any configured WebIRC hosts.",
292 user->uuid.c_str(), user->GetIPString().c_str());
293 ServerInstance->Users->QuitUser(user, "WEBIRC: you don't match any configured WebIRC hosts.");
297 void WriteLog(const char* message, ...) CUSTOM_PRINTF(2, 3)
300 VAFORMAT(buffer, message, message);
302 // If we are sending a snotice then the message will already be
303 // written to the logfile.
305 ServerInstance->SNO->WriteGlobalSno('w', buffer);
307 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, buffer);
313 , public WebIRC::EventListener
314 , public Whois::EventListener
317 CommandHexIP cmdhexip;
318 CommandWebIRC cmdwebirc;
319 std::vector<IdentHost> hosts;
323 : WebIRC::EventListener(this)
324 , Whois::EventListener(this)
330 void init() CXX11_OVERRIDE
332 ServerInstance->SNO->EnableSnomask('w', "CGIIRC");
335 ModResult OnCheckBan(User* user, Channel*, const std::string& mask) CXX11_OVERRIDE
337 if (mask.length() <= 2 || mask[0] != 'w' || mask[1] != ':')
338 return MOD_RES_PASSTHRU;
340 const std::string* gateway = cmdwebirc.gateway.get(user);
342 return MOD_RES_PASSTHRU;
344 if (InspIRCd::Match(*gateway, mask.substr(2)))
347 return MOD_RES_PASSTHRU;
350 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
352 std::vector<IdentHost> identhosts;
353 std::vector<WebIRCHost> webirchosts;
355 ConfigTagList tags = ServerInstance->Config->ConfTags("cgihost");
356 for (ConfigIter i = tags.first; i != tags.second; ++i)
358 ConfigTag* tag = i->second;
361 irc::spacesepstream maskstream(tag->getString("mask"));
362 for (std::string mask; maskstream.GetToken(mask); )
363 masks.push_back(mask);
365 // Ensure that we have the <cgihost:mask> parameter.
367 throw ModuleException("<cgihost:mask> is a mandatory field, at " + tag->getTagLocation());
369 // Determine what lookup type this host uses.
370 const std::string type = tag->getString("type");
371 if (stdalgo::string::equalsci(type, "ident"))
373 // The IP address should be looked up from the hex IP address.
374 const std::string newident = tag->getString("newident", "gateway", ServerInstance->IsIdent);
375 identhosts.push_back(IdentHost(masks, newident));
377 else if (stdalgo::string::equalsci(type, "webirc"))
379 // The IP address will be received via the WEBIRC command.
380 const std::string fingerprint = tag->getString("fingerprint");
381 const std::string password = tag->getString("password");
382 const std::string passwordhash = tag->getString("hash", "plaintext", 1);
384 // WebIRC blocks require a password.
385 if (fingerprint.empty() && password.empty())
386 throw ModuleException("When using <cgihost type=\"webirc\"> either the fingerprint or password field is required, at " + tag->getTagLocation());
388 if (!password.empty() && stdalgo::string::equalsci(passwordhash, "plaintext"))
390 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<cgihost> tag at %s contains an plain text password, this is insecure!",
391 tag->getTagLocation().c_str());
394 webirchosts.push_back(WebIRCHost(masks, fingerprint, password, passwordhash));
398 throw ModuleException(type + " is an invalid <cgihost:mask> type, at " + tag->getTagLocation());
402 // The host configuration was valid so we can apply it.
403 hosts.swap(identhosts);
404 cmdwebirc.hosts.swap(webirchosts);
406 // Do we send an oper notice when a m_cgiirc client has their IP changed?
407 cmdwebirc.notify = ServerInstance->Config->ConfValue("cgiirc")->getBool("opernotice", true);
410 ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
412 // If <connect:webirc> is not set then we have nothing to do.
413 const std::string webirc = myclass->config->getString("webirc");
415 return MOD_RES_PASSTHRU;
417 // If the user is not connecting via a WebIRC gateway then they
418 // cannot match this connect class.
419 const std::string* gateway = cmdwebirc.gateway.get(user);
422 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it requires a connection via a WebIRC gateway",
423 myclass->GetName().c_str());
427 // If the gateway matches the <connect:webirc> constraint then
428 // allow the check to continue. Otherwise, reject it.
429 if (!InspIRCd::Match(*gateway, webirc))
431 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as the WebIRC gateway name (%s) does not match %s",
432 myclass->GetName().c_str(), gateway->c_str(), webirc.c_str());
436 return MOD_RES_PASSTHRU;
439 ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
441 // There is no need to check for gateways if one is already being used.
442 if (cmdwebirc.realhost.get(user))
443 return MOD_RES_PASSTHRU;
445 for (std::vector<IdentHost>::const_iterator iter = hosts.begin(); iter != hosts.end(); ++iter)
447 // If we don't match the host then skip to the next host.
448 if (!iter->Matches(user))
451 // We have matched an <cgihost> block! Try to parse the encoded IPv4 address
453 irc::sockets::sockaddrs address(user->client_sa);
454 if (!CommandHexIP::ParseIP(user->ident, address))
455 return MOD_RES_PASSTHRU;
457 // Store the hostname and IP of the gateway for later use.
458 cmdwebirc.realhost.set(user, user->GetRealHost());
459 cmdwebirc.realip.set(user, user->GetIPString());
461 const std::string& newident = iter->GetIdent();
462 cmdwebirc.WriteLog("Connecting user %s is using an ident gateway; changing their IP from %s to %s and their ident from %s to %s.",
463 user->uuid.c_str(), user->GetIPString().c_str(), address.addr().c_str(), user->ident.c_str(), newident.c_str());
465 user->ChangeIdent(newident);
466 user->SetClientIP(address);
469 return MOD_RES_PASSTHRU;
472 void OnWebIRCAuth(LocalUser* user, const WebIRC::FlagMap* flags) CXX11_OVERRIDE
474 // We are only interested in connection flags. If none have been
475 // given then we have nothing to do.
479 WebIRC::FlagMap::const_iterator cport = flags->find("remote-port");
480 if (cport != flags->end())
482 // If we can't parse the port then just give up.
483 uint16_t port = ConvToNum<uint16_t>(cport->second);
486 switch (user->client_sa.family())
489 user->client_sa.in4.sin_port = htons(port);
493 user->client_sa.in6.sin6_port = htons(port);
497 // If we have reached this point then we have encountered a bug.
498 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: OnWebIRCAuth(%s): socket type %d is unknown!",
499 user->uuid.c_str(), user->client_sa.family());
505 WebIRC::FlagMap::const_iterator sport = flags->find("local-port");
506 if (sport != flags->end())
508 // If we can't parse the port then just give up.
509 uint16_t port = ConvToNum<uint16_t>(sport->second);
512 switch (user->server_sa.family())
515 user->server_sa.in4.sin_port = htons(port);
519 user->server_sa.in6.sin6_port = htons(port);
523 // If we have reached this point then we have encountered a bug.
524 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: OnWebIRCAuth(%s): socket type %d is unknown!",
525 user->uuid.c_str(), user->server_sa.family());
532 void OnWhois(Whois::Context& whois) CXX11_OVERRIDE
534 // If these fields are not set then the client is not using a gateway.
535 std::string* realhost = cmdwebirc.realhost.get(whois.GetTarget());
536 std::string* realip = cmdwebirc.realip.get(whois.GetTarget());
537 if (!realhost || !realip)
540 // If the source doesn't have the right privs then only show the gateway name.
541 std::string hidden = "*";
542 if (!whois.GetSource()->HasPrivPermission("users/auspex"))
543 realhost = realip = &hidden;
545 const std::string* gateway = cmdwebirc.gateway.get(whois.GetTarget());
547 whois.SendLine(RPL_WHOISGATEWAY, *realhost, *realip, "is connected via the " + *gateway + " WebIRC gateway");
549 whois.SendLine(RPL_WHOISGATEWAY, *realhost, *realip, "is connected via an ident gateway");
552 Version GetVersion() CXX11_OVERRIDE
554 return Version("Adds the ability for IRC gateways to forward the real IP address of users connecting through them.", VF_VENDOR);
558 MODULE_INIT(ModuleCgiIRC)