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