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