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