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