]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
Penalise clients that use WEBIRC incorrectly.
[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                                                 bool host_ok = (parameters[2].length() < 64);
103                                                 const std::string& newhost = (host_ok ? parameters[2] : parameters[3]);
104
105                                                 if (notify)
106                                                         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());
107
108                                                 // 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
109                                                 if (host_ok)
110                                                         webirc_hostname.set(user, parameters[2]);
111                                                 else
112                                                         webirc_hostname.unset(user);
113
114                                                 webirc_ip.set(user, parameters[3]);
115                                                 return CMD_SUCCESS;
116                                         }
117                                 }
118                         }
119
120                         IS_LOCAL(user)->CommandFloodPenalty += 5000;
121                         ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str());
122                         return CMD_FAILURE;
123                 }
124 };
125
126
127 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
128  */
129 class CGIResolver : public Resolver
130 {
131         std::string typ;
132         std::string theiruid;
133         LocalIntExt& waiting;
134         bool notify;
135  public:
136         CGIResolver(Module* me, bool NotifyOpers, const std::string &source, LocalUser* u,
137                         const std::string &type, bool &cached, LocalIntExt& ext)
138                 : Resolver(source, DNS_QUERY_PTR4, cached, me), typ(type), theiruid(u->uuid),
139                 waiting(ext), notify(NotifyOpers)
140         {
141         }
142
143         virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
144         {
145                 /* Check the user still exists */
146                 User* them = ServerInstance->FindUUID(theiruid);
147                 if ((them) && (!them->quitting))
148                 {
149                         if (notify)
150                                 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());
151
152                         if (result.length() > 64)
153                                 return;
154                         them->host = result;
155                         them->dhost = result;
156                         them->InvalidateCache();
157                         them->CheckLines(true);
158                 }
159         }
160
161         virtual void OnError(ResolverError e, const std::string &errormessage)
162         {
163                 if (!notify)
164                         return;
165
166                 User* them = ServerInstance->FindUUID(theiruid);
167                 if ((them) && (!them->quitting))
168                 {
169                         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());
170                 }
171         }
172
173         virtual ~CGIResolver()
174         {
175                 User* them = ServerInstance->FindUUID(theiruid);
176                 if (!them)
177                         return;
178                 int count = waiting.get(them);
179                 if (count)
180                         waiting.set(them, count - 1);
181         }
182 };
183
184 class ModuleCgiIRC : public Module
185 {
186         CommandWebirc cmd;
187         LocalIntExt waiting;
188
189         static void RecheckClass(LocalUser* user)
190         {
191                 user->MyClass = NULL;
192                 user->SetClass();
193                 user->CheckClass();
194         }
195
196         static void ChangeIP(LocalUser* user, const std::string& newip)
197         {
198                 ServerInstance->Users->RemoveCloneCounts(user);
199                 user->SetClientIP(newip.c_str());
200                 ServerInstance->Users->AddLocalClone(user);
201                 ServerInstance->Users->AddGlobalClone(user);
202         }
203
204         void HandleIdentOrPass(LocalUser* user, const std::string& newip, bool was_pass)
205         {
206                 cmd.realhost.set(user, user->host);
207                 cmd.realip.set(user, user->GetIPString());
208                 ChangeIP(user, newip);
209                 user->host = user->dhost = user->GetIPString();
210                 user->InvalidateCache();
211                 RecheckClass(user);
212                 // Don't create the resolver if the core couldn't put the user in a connect class or when dns is disabled
213                 if (user->quitting || ServerInstance->Config->NoUserDns)
214                         return;
215
216                 try
217                 {
218                         bool cached;
219                         CGIResolver* r = new CGIResolver(this, cmd.notify, newip, user, (was_pass ? "PASS" : "IDENT"), cached, waiting);
220                         waiting.set(user, waiting.get(user) + 1);
221                         ServerInstance->AddResolver(r, cached);
222                 }
223                 catch (...)
224                 {
225                         if (cmd.notify)
226                                  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());
227                 }
228         }
229
230 public:
231         ModuleCgiIRC() : cmd(this), waiting("cgiirc-delay", this)
232         {
233         }
234
235         void init()
236         {
237                 OnRehash(NULL);
238                 ServiceProvider* providerlist[] = { &cmd, &cmd.realhost, &cmd.realip, &cmd.webirc_hostname, &cmd.webirc_ip, &waiting };
239                 ServerInstance->Modules->AddServices(providerlist, sizeof(providerlist)/sizeof(ServiceProvider*));
240
241                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCheckReady };
242                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
243         }
244
245         void OnRehash(User* user)
246         {
247                 cmd.Hosts.clear();
248
249                 // Do we send an oper notice when a CGI:IRC has their host changed?
250                 cmd.notify = ServerInstance->Config->ConfValue("cgiirc")->getBool("opernotice", true);
251
252                 ConfigTagList tags = ServerInstance->Config->ConfTags("cgihost");
253                 for (ConfigIter i = tags.first; i != tags.second; ++i)
254                 {
255                         ConfigTag* tag = i->second;
256                         std::string hostmask = tag->getString("mask"); // An allowed CGI:IRC host
257                         std::string type = tag->getString("type"); // What type of user-munging we do on this host.
258                         std::string password = tag->getString("password");
259
260                         if(hostmask.length())
261                         {
262                                 if (type == "webirc" && password.empty())
263                                 {
264                                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc: Missing password in config: %s", hostmask.c_str());
265                                 }
266                                 else
267                                 {
268                                         CGItype cgitype;
269                                         if (type == "pass")
270                                                 cgitype = PASS;
271                                         else if (type == "ident")
272                                                 cgitype = IDENT;
273                                         else if (type == "passfirst")
274                                                 cgitype = PASSFIRST;
275                                         else if (type == "webirc")
276                                                 cgitype = WEBIRC;
277                                         else
278                                         {
279                                                 cgitype = PASS;
280                                                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc.so: Invalid <cgihost:type> value in config: %s, setting it to \"pass\"", type.c_str());
281                                         }
282
283                                         cmd.Hosts.push_back(CGIhost(hostmask, cgitype, password));
284                                 }
285                         }
286                         else
287                         {
288                                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc.so: Invalid <cgihost:mask> value in config: %s", hostmask.c_str());
289                                 continue;
290                         }
291                 }
292         }
293
294         ModResult OnCheckReady(LocalUser *user)
295         {
296                 if (waiting.get(user))
297                         return MOD_RES_DENY;
298
299                 std::string *webirc_ip = cmd.webirc_ip.get(user);
300                 if (!webirc_ip)
301                         return MOD_RES_PASSTHRU;
302
303                 ChangeIP(user, *webirc_ip);
304
305                 std::string* webirc_hostname = cmd.webirc_hostname.get(user);
306                 user->host = user->dhost = (webirc_hostname ? *webirc_hostname : user->GetIPString());
307                 user->InvalidateCache();
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                 cmd.webirc_hostname.unset(user);
318                 cmd.webirc_ip.unset(user);
319
320                 return MOD_RES_PASSTHRU;
321         }
322
323         ModResult OnUserRegister(LocalUser* user)
324         {
325                 for(CGIHostlist::iterator iter = cmd.Hosts.begin(); iter != cmd.Hosts.end(); iter++)
326                 {
327                         if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
328                         {
329                                 // Deal with it...
330                                 if(iter->type == PASS)
331                                 {
332                                         CheckPass(user); // We do nothing if it fails so...
333                                         user->CheckLines(true);
334                                 }
335                                 else if(iter->type == PASSFIRST && !CheckPass(user))
336                                 {
337                                         // If the password lookup failed, try the ident
338                                         CheckIdent(user);       // If this fails too, do nothing
339                                         user->CheckLines(true);
340                                 }
341                                 else if(iter->type == IDENT)
342                                 {
343                                         CheckIdent(user); // Nothing on failure.
344                                         user->CheckLines(true);
345                                 }
346                                 else if(iter->type == IDENTFIRST && !CheckIdent(user))
347                                 {
348                                         // If the ident lookup fails, try the password.
349                                         CheckPass(user);
350                                         user->CheckLines(true);
351                                 }
352                                 else if(iter->type == WEBIRC)
353                                 {
354                                         // We don't need to do anything here
355                                 }
356                                 return MOD_RES_PASSTHRU;
357                         }
358                 }
359                 return MOD_RES_PASSTHRU;
360         }
361
362         bool CheckPass(LocalUser* user)
363         {
364                 if(IsValidHost(user->password))
365                 {
366                         HandleIdentOrPass(user, user->password, true);
367                         user->password.clear();
368                         return true;
369                 }
370
371                 return false;
372         }
373
374         bool CheckIdent(LocalUser* user)
375         {
376                 const char* ident;
377                 in_addr newip;
378
379                 if (user->ident.length() == 8)
380                         ident = user->ident.c_str();
381                 else if (user->ident.length() == 9 && user->ident[0] == '~')
382                         ident = user->ident.c_str() + 1;
383                 else
384                         return false;
385
386                 errno = 0;
387                 unsigned long ipaddr = strtoul(ident, NULL, 16);
388                 if (errno)
389                         return false;
390                 newip.s_addr = htonl(ipaddr);
391                 std::string newipstr(inet_ntoa(newip));
392
393                 user->ident = "~cgiirc";
394                 HandleIdentOrPass(user, newipstr, false);
395
396                 return true;
397         }
398
399         bool IsValidHost(const std::string &host)
400         {
401                 if(!host.size() || host.size() > 64)
402                         return false;
403
404                 for(unsigned int i = 0; i < host.size(); i++)
405                 {
406                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
407                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
408                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
409                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
410                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
411
412                                 continue;
413                         else
414                                 return false;
415                 }
416
417                 return true;
418         }
419
420         virtual Version GetVersion()
421         {
422                 return Version("Change user's hosts connecting from known CGI:IRC hosts",VF_VENDOR);
423         }
424
425 };
426
427 MODULE_INIT(ModuleCgiIRC)