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