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