]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
Fix comparator logic for ordering by channel
[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                         allow_empty_last_param = false;
77                         works_before_reg = true;
78                         this->syntax = "password client hostname ip";
79                 }
80                 CmdResult Handle(const std::vector<std::string> &parameters, User *user)
81                 {
82                         if(user->registered == REG_ALL)
83                                 return CMD_FAILURE;
84
85                         irc::sockets::sockaddrs ipaddr;
86                         if (!irc::sockets::aptosa(parameters[3], 0, ipaddr))
87                         {
88                                 IS_LOCAL(user)->CommandFloodPenalty += 5000;
89                                 ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s tried to use WEBIRC but gave an invalid IP address.", user->GetFullRealHost().c_str());
90                                 return CMD_FAILURE;
91                         }
92
93                         for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++)
94                         {
95                                 if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
96                                 {
97                                         if(iter->type == WEBIRC && parameters[0] == iter->password)
98                                         {
99                                                 realhost.set(user, user->host);
100                                                 realip.set(user, user->GetIPString());
101
102                                                 // Check if we're happy with the provided hostname. If it's problematic then use the IP instead.
103                                                 bool host_ok = (parameters[2].length() < 64) && (parameters[2].find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-") == std::string::npos);
104                                                 const std::string& newhost = (host_ok ? parameters[2] : parameters[3]);
105
106                                                 if (notify)
107                                                         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());
108
109                                                 webirc_hostname.set(user, newhost);
110                                                 webirc_ip.set(user, parameters[3]);
111                                                 return CMD_SUCCESS;
112                                         }
113                                 }
114                         }
115
116                         IS_LOCAL(user)->CommandFloodPenalty += 5000;
117                         ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str());
118                         return CMD_FAILURE;
119                 }
120 };
121
122
123 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
124  */
125 class CGIResolver : public Resolver
126 {
127         std::string typ;
128         std::string theiruid;
129         LocalIntExt& waiting;
130         bool notify;
131  public:
132         CGIResolver(Module* me, bool NotifyOpers, const std::string &source, LocalUser* u,
133                         const std::string &type, bool &cached, LocalIntExt& ext)
134                 : Resolver(source, DNS_QUERY_PTR4, cached, me), typ(type), theiruid(u->uuid),
135                 waiting(ext), notify(NotifyOpers)
136         {
137         }
138
139         virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
140         {
141                 /* Check the user still exists */
142                 User* them = ServerInstance->FindUUID(theiruid);
143                 if ((them) && (!them->quitting))
144                 {
145                         if (notify)
146                                 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());
147
148                         if (result.length() > 64)
149                                 return;
150                         them->host = result;
151                         them->dhost = result;
152                         them->InvalidateCache();
153                         them->CheckLines(true);
154                 }
155         }
156
157         virtual void OnError(ResolverError e, const std::string &errormessage)
158         {
159                 if (!notify)
160                         return;
161
162                 User* them = ServerInstance->FindUUID(theiruid);
163                 if ((them) && (!them->quitting))
164                 {
165                         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());
166                 }
167         }
168
169         virtual ~CGIResolver()
170         {
171                 User* them = ServerInstance->FindUUID(theiruid);
172                 if (!them)
173                         return;
174                 int count = waiting.get(them);
175                 if (count)
176                         waiting.set(them, count - 1);
177         }
178 };
179
180 class ModuleCgiIRC : public Module
181 {
182         CommandWebirc cmd;
183         LocalIntExt waiting;
184
185         static void RecheckClass(LocalUser* user)
186         {
187                 user->MyClass = NULL;
188                 user->SetClass();
189                 user->CheckClass();
190         }
191
192         static void ChangeIP(LocalUser* user, const std::string& newip)
193         {
194                 ServerInstance->Users->RemoveCloneCounts(user);
195                 user->SetClientIP(newip.c_str());
196                 ServerInstance->Users->AddLocalClone(user);
197                 ServerInstance->Users->AddGlobalClone(user);
198         }
199
200         void HandleIdentOrPass(LocalUser* user, const std::string& newip, bool was_pass)
201         {
202                 cmd.realhost.set(user, user->host);
203                 cmd.realip.set(user, user->GetIPString());
204                 ChangeIP(user, newip);
205                 user->host = user->dhost = user->GetIPString();
206                 user->InvalidateCache();
207                 RecheckClass(user);
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 || ServerInstance->Config->NoUserDns)
210                         return;
211
212                 try
213                 {
214                         bool cached;
215                         CGIResolver* r = new CGIResolver(this, cmd.notify, newip, user, (was_pass ? "PASS" : "IDENT"), cached, waiting);
216                         waiting.set(user, waiting.get(user) + 1);
217                         ServerInstance->AddResolver(r, cached);
218                 }
219                 catch (...)
220                 {
221                         if (cmd.notify)
222                                  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());
223                 }
224         }
225
226 public:
227         ModuleCgiIRC() : cmd(this), waiting("cgiirc-delay", this)
228         {
229         }
230
231         void init()
232         {
233                 OnRehash(NULL);
234                 ServiceProvider* providerlist[] = { &cmd, &cmd.realhost, &cmd.realip, &cmd.webirc_hostname, &cmd.webirc_ip, &waiting };
235                 ServerInstance->Modules->AddServices(providerlist, sizeof(providerlist)/sizeof(ServiceProvider*));
236
237                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCheckReady };
238                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
239         }
240
241         void OnRehash(User* user)
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",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",DEFAULT, "m_cgiirc.so: 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",DEFAULT, "m_cgiirc.so: Invalid <cgihost:mask> value in config: %s", hostmask.c_str());
285                                 continue;
286                         }
287                 }
288         }
289
290         ModResult OnCheckReady(LocalUser *user)
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                 user->InvalidateCache();
304
305                 RecheckClass(user);
306                 if (user->quitting)
307                         return MOD_RES_DENY;
308
309                 user->CheckLines(true);
310                 if (user->quitting)
311                         return MOD_RES_DENY;
312
313                 cmd.webirc_hostname.unset(user);
314                 cmd.webirc_ip.unset(user);
315
316                 return MOD_RES_PASSTHRU;
317         }
318
319         ModResult OnUserRegister(LocalUser* user)
320         {
321                 for(CGIHostlist::iterator iter = cmd.Hosts.begin(); iter != cmd.Hosts.end(); iter++)
322                 {
323                         if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
324                         {
325                                 // Deal with it...
326                                 if(iter->type == PASS)
327                                 {
328                                         CheckPass(user); // We do nothing if it fails so...
329                                         user->CheckLines(true);
330                                 }
331                                 else if(iter->type == PASSFIRST && !CheckPass(user))
332                                 {
333                                         // If the password lookup failed, try the ident
334                                         CheckIdent(user);       // If this fails too, do nothing
335                                         user->CheckLines(true);
336                                 }
337                                 else if(iter->type == IDENT)
338                                 {
339                                         CheckIdent(user); // Nothing on failure.
340                                         user->CheckLines(true);
341                                 }
342                                 else if(iter->type == IDENTFIRST && !CheckIdent(user))
343                                 {
344                                         // If the ident lookup fails, try the password.
345                                         CheckPass(user);
346                                         user->CheckLines(true);
347                                 }
348                                 else if(iter->type == WEBIRC)
349                                 {
350                                         // We don't need to do anything here
351                                 }
352                                 return MOD_RES_PASSTHRU;
353                         }
354                 }
355                 return MOD_RES_PASSTHRU;
356         }
357
358         bool CheckPass(LocalUser* user)
359         {
360                 if(IsValidHost(user->password))
361                 {
362                         HandleIdentOrPass(user, user->password, true);
363                         user->password.clear();
364                         return true;
365                 }
366
367                 return false;
368         }
369
370         bool CheckIdent(LocalUser* user)
371         {
372                 const char* ident;
373                 in_addr newip;
374
375                 if (user->ident.length() == 8)
376                         ident = user->ident.c_str();
377                 else if (user->ident.length() == 9 && user->ident[0] == '~')
378                         ident = user->ident.c_str() + 1;
379                 else
380                         return false;
381
382                 errno = 0;
383                 unsigned long ipaddr = strtoul(ident, NULL, 16);
384                 if (errno)
385                         return false;
386                 newip.s_addr = htonl(ipaddr);
387                 std::string newipstr(inet_ntoa(newip));
388
389                 user->ident = "~cgiirc";
390                 HandleIdentOrPass(user, newipstr, false);
391
392                 return true;
393         }
394
395         bool IsValidHost(const std::string &host)
396         {
397                 if(!host.size() || host.size() > 64)
398                         return false;
399
400                 for(unsigned int i = 0; i < host.size(); i++)
401                 {
402                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
403                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
404                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
405                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
406                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
407
408                                 continue;
409                         else
410                                 return false;
411                 }
412
413                 return true;
414         }
415
416         virtual Version GetVersion()
417         {
418                 return Version("Change user's hosts connecting from known CGI:IRC hosts",VF_VENDOR);
419         }
420
421 };
422
423 MODULE_INIT(ModuleCgiIRC)