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