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