]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
Allow filtering WebIRC connections into a connect class by gateway.
[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 "xline.h"
28 #include "modules/dns.h"
29
30 enum CGItype { PASS, IDENT, PASSFIRST, IDENTFIRST, WEBIRC };
31
32 // We need this method up here so that it can be accessed from anywhere
33 static void ChangeIP(User* user, const std::string& newip)
34 {
35         ServerInstance->Users->RemoveCloneCounts(user);
36         user->SetClientIP(newip.c_str());
37         ServerInstance->Users->AddClone(user);
38 }
39
40 /** Holds a CGI site's details
41  */
42 class CGIhost
43 {
44 public:
45         std::string hostmask;
46         CGItype type;
47         std::string password;
48
49         CGIhost(const std::string &mask, CGItype t, const std::string &spassword)
50         : hostmask(mask), type(t), password(spassword)
51         {
52         }
53 };
54 typedef std::vector<CGIhost> CGIHostlist;
55
56 /*
57  * WEBIRC
58  *  This is used for the webirc method of CGIIRC auth, and is (really) the best way to do these things.
59  *  Syntax: WEBIRC password gateway hostname ip
60  *  Where password is a shared key, gateway is the name of the WebIRC gateway and version (e.g. cgiirc), hostname
61  *  is the resolved host of the client issuing the command and IP is the real IP of the client.
62  *
63  * How it works:
64  *  To tie in with the rest of cgiirc module, and to avoid race conditions, /webirc is only processed locally
65  *  and simply sets metadata on the user, which is later decoded on full connect to give something meaningful.
66  */
67 class CommandWebirc : public Command
68 {
69  public:
70         bool notify;
71         StringExtItem gateway;
72         StringExtItem realhost;
73         StringExtItem realip;
74
75         CGIHostlist Hosts;
76         CommandWebirc(Module* Creator)
77                 : Command(Creator, "WEBIRC", 4)
78                 , gateway("cgiirc_gateway", ExtensionItem::EXT_USER, Creator)
79                 , realhost("cgiirc_realhost", ExtensionItem::EXT_USER, Creator)
80                 , realip("cgiirc_realip", ExtensionItem::EXT_USER, Creator)
81                 {
82                         works_before_reg = true;
83                         this->syntax = "password gateway hostname ip";
84                 }
85                 CmdResult Handle(const std::vector<std::string> &parameters, User *user)
86                 {
87                         if(user->registered == REG_ALL)
88                                 return CMD_FAILURE;
89
90                         for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++)
91                         {
92                                 if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
93                                 {
94                                         if(iter->type == WEBIRC && parameters[0] == iter->password)
95                                         {
96                                                 gateway.set(user, parameters[1]);
97                                                 realhost.set(user, user->host);
98                                                 realip.set(user, user->GetIPString());
99
100                                                 // Check if we're happy with the provided hostname. If it's problematic then make sure we won't set a host later, just the IP
101                                                 bool host_ok = (parameters[2].length() <= ServerInstance->Config->Limits.MaxHost);
102                                                 const std::string& newhost = (host_ok ? parameters[2] : parameters[3]);
103
104                                                 if (notify)
105                                                         ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", user->nick.c_str(), user->host.c_str(), newhost.c_str(), user->host.c_str());
106
107                                                 // Where the magic happens - change their IP
108                                                 ChangeIP(user, parameters[3]);
109                                                 // And follow this up by changing their host
110                                                 user->host = user->dhost = newhost;
111                                                 user->InvalidateCache();
112
113                                                 return CMD_SUCCESS;
114                                         }
115                                 }
116                         }
117
118                         ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str());
119                         return CMD_FAILURE;
120                 }
121 };
122
123
124 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
125  */
126 class CGIResolver : public DNS::Request
127 {
128         std::string typ;
129         std::string theiruid;
130         LocalIntExt& waiting;
131         bool notify;
132  public:
133         CGIResolver(DNS::Manager *mgr, Module* me, bool NotifyOpers, const std::string &source, LocalUser* u,
134                         const std::string &ttype, LocalIntExt& ext)
135                 : DNS::Request(mgr, me, source, DNS::QUERY_PTR), typ(ttype), theiruid(u->uuid),
136                 waiting(ext), notify(NotifyOpers)
137         {
138         }
139
140         void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE
141         {
142                 /* Check the user still exists */
143                 User* them = ServerInstance->FindUUID(theiruid);
144                 if ((them) && (!them->quitting))
145                 {
146                         LocalUser* lu = IS_LOCAL(them);
147                         if (!lu)
148                                 return;
149
150                         const DNS::ResourceRecord &ans_record = r->answers[0];
151                         if (ans_record.rdata.empty() || ans_record.rdata.length() > ServerInstance->Config->Limits.MaxHost)
152                                 return;
153
154                         if (notify)
155                                 ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", them->nick.c_str(), them->host.c_str(), ans_record.rdata.c_str(), typ.c_str());
156
157                         them->host = them->dhost = ans_record.rdata;
158                         them->InvalidateCache();
159                         lu->CheckLines(true);
160                 }
161         }
162
163         void OnError(const DNS::Query *r) CXX11_OVERRIDE
164         {
165                 if (!notify)
166                         return;
167
168                 User* them = ServerInstance->FindUUID(theiruid);
169                 if ((them) && (!them->quitting))
170                 {
171                         ServerInstance->SNO->WriteToSnoMask('w', "Connecting user %s detected as using CGI:IRC (%s), but their host can't be resolved from their %s!", them->nick.c_str(), them->host.c_str(), typ.c_str());
172                 }
173         }
174
175         ~CGIResolver()
176         {
177                 User* them = ServerInstance->FindUUID(theiruid);
178                 if (!them)
179                         return;
180                 int count = waiting.get(them);
181                 if (count)
182                         waiting.set(them, count - 1);
183         }
184 };
185
186 class ModuleCgiIRC : public Module
187 {
188         CommandWebirc cmd;
189         LocalIntExt waiting;
190         dynamic_reference<DNS::Manager> DNS;
191
192         static void RecheckClass(LocalUser* user)
193         {
194                 user->MyClass = NULL;
195                 user->SetClass();
196                 user->CheckClass();
197         }
198
199         void HandleIdentOrPass(LocalUser* user, const std::string& newip, bool was_pass)
200         {
201                 cmd.realhost.set(user, user->host);
202                 cmd.realip.set(user, user->GetIPString());
203                 ChangeIP(user, newip);
204                 user->host = user->dhost = user->GetIPString();
205                 user->InvalidateCache();
206                 RecheckClass(user);
207
208                 // Don't create the resolver if the core couldn't put the user in a connect class or when dns is disabled
209                 if (user->quitting || !DNS || !user->MyClass->resolvehostnames)
210                         return;
211
212                 CGIResolver* r = new CGIResolver(*this->DNS, this, cmd.notify, newip, user, (was_pass ? "PASS" : "IDENT"), waiting);
213                 try
214                 {
215                         waiting.set(user, waiting.get(user) + 1);
216                         this->DNS->Process(r);
217                 }
218                 catch (DNS::Exception &ex)
219                 {
220                         int count = waiting.get(user);
221                         if (count)
222                                 waiting.set(user, count - 1);
223                         delete r;
224                         if (cmd.notify)
225                                  ServerInstance->SNO->WriteToSnoMask('w', "Connecting user %s detected as using CGI:IRC (%s), but I could not resolve their hostname; %s", user->nick.c_str(), user->host.c_str(), ex.GetReason().c_str());
226                 }
227         }
228
229 public:
230         ModuleCgiIRC()
231                 : cmd(this)
232                 , waiting("cgiirc-delay", ExtensionItem::EXT_USER, this)
233                 , DNS(this, "DNS")
234         {
235         }
236
237         void init() CXX11_OVERRIDE
238         {
239                 ServerInstance->SNO->EnableSnomask('w', "CGIIRC");
240         }
241
242         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
243         {
244                 cmd.Hosts.clear();
245
246                 // Do we send an oper notice when a CGI:IRC has their host changed?
247                 cmd.notify = ServerInstance->Config->ConfValue("cgiirc")->getBool("opernotice", true);
248
249                 ConfigTagList tags = ServerInstance->Config->ConfTags("cgihost");
250                 for (ConfigIter i = tags.first; i != tags.second; ++i)
251                 {
252                         ConfigTag* tag = i->second;
253                         std::string hostmask = tag->getString("mask"); // An allowed CGI:IRC host
254                         std::string type = tag->getString("type"); // What type of user-munging we do on this host.
255                         std::string password = tag->getString("password");
256
257                         if(hostmask.length())
258                         {
259                                 if (type == "webirc" && password.empty())
260                                 {
261                                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Missing password in config: %s", hostmask.c_str());
262                                 }
263                                 else
264                                 {
265                                         CGItype cgitype;
266                                         if (type == "pass")
267                                                 cgitype = PASS;
268                                         else if (type == "ident")
269                                                 cgitype = IDENT;
270                                         else if (type == "passfirst")
271                                                 cgitype = PASSFIRST;
272                                         else if (type == "webirc")
273                                                 cgitype = WEBIRC;
274                                         else
275                                         {
276                                                 cgitype = PASS;
277                                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Invalid <cgihost:type> value in config: %s, setting it to \"pass\"", type.c_str());
278                                         }
279
280                                         cmd.Hosts.push_back(CGIhost(hostmask, cgitype, password));
281                                 }
282                         }
283                         else
284                         {
285                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Invalid <cgihost:mask> value in config: %s", hostmask.c_str());
286                                 continue;
287                         }
288                 }
289         }
290
291         ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
292         {
293                 if (waiting.get(user))
294                         return MOD_RES_DENY;
295
296                 if (!cmd.realip.get(user))
297                         return MOD_RES_PASSTHRU;
298
299                 RecheckClass(user);
300                 if (user->quitting)
301                         return MOD_RES_DENY;
302
303                 user->CheckLines(true);
304                 if (user->quitting)
305                         return MOD_RES_DENY;
306
307                 return MOD_RES_PASSTHRU;
308         }
309
310         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
311         {
312                 // If <connect:webirc> is not set then we have nothing to do.
313                 const std::string webirc = myclass->config->getString("webirc");
314                 if (webirc.empty())
315                         return MOD_RES_PASSTHRU;
316
317                 // If the user is not connecting via a WebIRC gateway then they
318                 // cannot match this connect class.
319                 const std::string* gateway = cmd.gateway.get(user);
320                 if (!gateway)
321                         return MOD_RES_DENY;
322
323                 // If the gateway matches the <connect:webirc> constraint then
324                 // allow the check to continue. Otherwise, reject it.
325                 return InspIRCd::Match(*gateway, webirc) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
326         }
327
328         ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
329         {
330                 for(CGIHostlist::iterator iter = cmd.Hosts.begin(); iter != cmd.Hosts.end(); iter++)
331                 {
332                         if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
333                         {
334                                 // Deal with it...
335                                 if(iter->type == PASS)
336                                 {
337                                         CheckPass(user); // We do nothing if it fails so...
338                                         user->CheckLines(true);
339                                 }
340                                 else if(iter->type == PASSFIRST && !CheckPass(user))
341                                 {
342                                         // If the password lookup failed, try the ident
343                                         CheckIdent(user);       // If this fails too, do nothing
344                                         user->CheckLines(true);
345                                 }
346                                 else if(iter->type == IDENT)
347                                 {
348                                         CheckIdent(user); // Nothing on failure.
349                                         user->CheckLines(true);
350                                 }
351                                 else if(iter->type == IDENTFIRST && !CheckIdent(user))
352                                 {
353                                         // If the ident lookup fails, try the password.
354                                         CheckPass(user);
355                                         user->CheckLines(true);
356                                 }
357                                 else if(iter->type == WEBIRC)
358                                 {
359                                         // We don't need to do anything here
360                                 }
361                                 return MOD_RES_PASSTHRU;
362                         }
363                 }
364                 return MOD_RES_PASSTHRU;
365         }
366
367         bool CheckPass(LocalUser* user)
368         {
369                 if(IsValidHost(user->password))
370                 {
371                         HandleIdentOrPass(user, user->password, true);
372                         user->password.clear();
373                         return true;
374                 }
375
376                 return false;
377         }
378
379         bool CheckIdent(LocalUser* user)
380         {
381                 const char* ident;
382                 in_addr newip;
383
384                 if (user->ident.length() == 8)
385                         ident = user->ident.c_str();
386                 else if (user->ident.length() == 9 && user->ident[0] == '~')
387                         ident = user->ident.c_str() + 1;
388                 else
389                         return false;
390
391                 errno = 0;
392                 unsigned long ipaddr = strtoul(ident, NULL, 16);
393                 if (errno)
394                         return false;
395                 newip.s_addr = htonl(ipaddr);
396                 std::string newipstr(inet_ntoa(newip));
397
398                 user->ident = "~cgiirc";
399                 HandleIdentOrPass(user, newipstr, false);
400
401                 return true;
402         }
403
404         bool IsValidHost(const std::string &host)
405         {
406                 if(!host.size() || host.size() > ServerInstance->Config->Limits.MaxHost)
407                         return false;
408
409                 for(unsigned int i = 0; i < host.size(); i++)
410                 {
411                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
412                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
413                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
414                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
415                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
416
417                                 continue;
418                         else
419                                 return false;
420                 }
421
422                 return true;
423         }
424
425         Version GetVersion() CXX11_OVERRIDE
426         {
427                 return Version("Change user's hosts connecting from known CGI:IRC hosts",VF_VENDOR);
428         }
429 };
430
431 MODULE_INIT(ModuleCgiIRC)