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