]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
Fix excessive snomask sending on fitler add/removal
[user/henk/code/inspircd.git] / src / modules / m_cgiirc.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15
16 #ifndef WINDOWS
17 #include <sys/socket.h>
18 #include <netinet/in.h>
19 #include <arpa/inet.h>
20 #endif
21
22 /* $ModDesc: Change user's hosts connecting from known CGI:IRC hosts */
23
24 enum CGItype { INVALID, PASS, IDENT, PASSFIRST, IDENTFIRST, WEBIRC };
25
26
27 /** Holds a CGI site's details
28  */
29 class CGIhost : public classbase
30 {
31 public:
32         std::string hostmask;
33         CGItype type;
34         std::string password;
35
36         CGIhost(const std::string &mask = "", CGItype t = IDENTFIRST, const std::string &spassword ="")
37         : hostmask(mask), type(t), password(spassword)
38         {
39         }
40 };
41 typedef std::vector<CGIhost> CGIHostlist;
42
43 /*
44  * WEBIRC
45  *  This is used for the webirc method of CGIIRC auth, and is (really) the best way to do these things.
46  *  Syntax: WEBIRC password client hostname ip
47  *  Where password is a shared key, client is the name of the "client" and version (e.g. cgiirc), hostname
48  *  is the resolved host of the client issuing the command and IP is the real IP of the client.
49  *
50  * How it works:
51  *  To tie in with the rest of cgiirc module, and to avoid race conditions, /webirc is only processed locally
52  *  and simply sets metadata on the user, which is later decoded on full connect to give something meaningful.
53  */
54 class CommandWebirc : public Command
55 {
56         CGIHostlist Hosts;
57         bool notify;
58         public:
59                 CommandWebirc(InspIRCd* Instance, CGIHostlist &cHosts, bool bnotify) : Command(Instance, "WEBIRC", 0, 4, true), Hosts(cHosts), notify(bnotify)
60                 {
61                         this->source = "m_cgiirc.so";
62                         this->syntax = "password client hostname ip";
63                 }
64                 CmdResult Handle(const std::vector<std::string> &parameters, User *user)
65                 {
66                         if(user->registered == REG_ALL)
67                                 return CMD_FAILURE;
68
69                         for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++)
70                         {
71                                 if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
72                                 {
73                                         if(iter->type == WEBIRC && parameters[0] == iter->password)
74                                         {
75                                                 user->Extend("cgiirc_realhost", new std::string(user->host));
76                                                 user->Extend("cgiirc_realip", new std::string(user->GetIPString()));
77                                                 if (notify)
78                                                         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());
79                                                 user->Extend("cgiirc_webirc_hostname", new std::string(parameters[2]));
80                                                 user->Extend("cgiirc_webirc_ip", new std::string(parameters[3]));
81                                                 return CMD_LOCALONLY;
82                                         }
83                                 }
84                         }
85
86                         ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str());
87                         return CMD_FAILURE;
88                 }
89 };
90
91
92 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
93  */
94 class CGIResolver : public Resolver
95 {
96         std::string typ;
97         int theirfd;
98         User* them;
99         bool notify;
100  public:
101         CGIResolver(Module* me, InspIRCd* Instance, bool NotifyOpers, const std::string &source, bool forward, User* u, int userfd, const std::string &type, bool &cached)
102                 : Resolver(Instance, source, forward ? DNS_QUERY_A : DNS_QUERY_PTR4, cached, me), typ(type), theirfd(userfd), them(u), notify(NotifyOpers) { }
103
104         virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
105         {
106                 /* Check the user still exists */
107                 if ((them) && (them == ServerInstance->SE->GetRef(theirfd)))
108                 {
109                         if (notify)
110                                 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());
111
112                         them->host.assign(result,0, 64);
113                         them->dhost.assign(result, 0, 64);
114                         if (querytype)
115                                 them->SetSockAddr(them->GetProtocolFamily(), result.c_str(), them->GetPort());
116                         them->ident.assign("~cgiirc", 0, 8);
117                         them->InvalidateCache();
118                         them->CheckLines(true);
119                 }
120         }
121
122         virtual void OnError(ResolverError e, const std::string &errormessage)
123         {
124                 if ((them) && (them == ServerInstance->SE->GetRef(theirfd)))
125                 {
126                         if (notify)
127                                 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());
128                 }
129         }
130
131         virtual ~CGIResolver()
132         {
133         }
134 };
135
136 class ModuleCgiIRC : public Module
137 {
138         CommandWebirc* mycommand;
139         bool NotifyOpers;
140         CGIHostlist Hosts;
141 public:
142         ModuleCgiIRC(InspIRCd* Me) : Module(Me)
143         {
144
145                 OnRehash(NULL);
146                 mycommand = new CommandWebirc(Me, Hosts, NotifyOpers);
147                 ServerInstance->AddCommand(mycommand);
148
149                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCleanup, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUserDisconnect, I_OnUserConnect };
150                 ServerInstance->Modules->Attach(eventlist, this, 7);
151         }
152
153
154         virtual void Prioritize()
155         {
156                 ServerInstance->Modules->SetPriority(this, I_OnUserConnect, PRIORITY_FIRST);
157         }
158
159         virtual void OnRehash(User* user)
160         {
161                 ConfigReader Conf(ServerInstance);
162                 Hosts.clear();
163
164                 NotifyOpers = Conf.ReadFlag("cgiirc", "opernotice", 0); // If we send an oper notice when a CGI:IRC has their host changed.
165
166                 if(Conf.GetError() == CONF_VALUE_NOT_FOUND)
167                         NotifyOpers = true;
168
169                 for(int i = 0; i < Conf.Enumerate("cgihost"); i++)
170                 {
171                         std::string hostmask = Conf.ReadValue("cgihost", "mask", i); // An allowed CGI:IRC host
172                         std::string type = Conf.ReadValue("cgihost", "type", i); // What type of user-munging we do on this host.
173                         std::string password = Conf.ReadValue("cgihost", "password", i);
174
175                         if(hostmask.length())
176                         {
177                                 if (type == "webirc" && !password.length()) {
178                                                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc: Missing password in config: %s", hostmask.c_str());
179                                 }
180                                 else
181                                 {
182                                         CGItype cgitype = INVALID;
183                                         if (type == "pass")
184                                                 cgitype = PASS;
185                                         else if (type == "ident")
186                                                 cgitype = IDENT;
187                                         else if (type == "passfirst")
188                                                 cgitype = PASSFIRST;
189                                         else if (type == "webirc")
190                                         {
191                                                 cgitype = WEBIRC;
192                                         }
193
194                                         if (cgitype == INVALID)
195                                                 cgitype = PASS;
196
197                                         Hosts.push_back(CGIhost(hostmask,cgitype, password.length() ? password : "" ));
198                                 }
199                         }
200                         else
201                         {
202                                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc.so: Invalid <cgihost:mask> value in config: %s", hostmask.c_str());
203                                 continue;
204                         }
205                 }
206         }
207
208         virtual void OnCleanup(int target_type, void* item)
209         {
210                 if(target_type == TYPE_USER)
211                 {
212                         User* user = (User*)item;
213                         std::string* realhost;
214                         std::string* realip;
215
216                         if(user->GetExt("cgiirc_realhost", realhost))
217                         {
218                                 delete realhost;
219                                 user->Shrink("cgiirc_realhost");
220                         }
221
222                         if(user->GetExt("cgiirc_realip", realip))
223                         {
224                                 delete realip;
225                                 user->Shrink("cgiirc_realip");
226                         }
227                 }
228         }
229
230         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
231         {
232                 if((extname == "cgiirc_realhost") || (extname == "cgiirc_realip"))
233                 {
234                         std::string* data;
235
236                         if(user->GetExt(extname, data))
237                         {
238                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, *data);
239                         }
240                 }
241         }
242
243         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
244         {
245                 if(target_type == TYPE_USER)
246                 {
247                         User* dest = (User*)target;
248                         std::string* bleh;
249                         if(((extname == "cgiirc_realhost") || (extname == "cgiirc_realip")) && (!dest->GetExt(extname, bleh)))
250                         {
251                                 dest->Extend(extname, new std::string(extdata));
252                         }
253                 }
254         }
255
256         virtual void OnUserDisconnect(User* user)
257         {
258                 OnCleanup(TYPE_USER, user);
259         }
260
261
262         virtual int OnUserRegister(User* user)
263         {
264                 for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++)
265                 {
266                         if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
267                         {
268                                 // Deal with it...
269                                 if(iter->type == PASS)
270                                 {
271                                         CheckPass(user); // We do nothing if it fails so...
272                                         user->CheckLines(true);
273                                 }
274                                 else if(iter->type == PASSFIRST && !CheckPass(user))
275                                 {
276                                         // If the password lookup failed, try the ident
277                                         CheckIdent(user);       // If this fails too, do nothing
278                                         user->CheckLines(true);
279                                 }
280                                 else if(iter->type == IDENT)
281                                 {
282                                         CheckIdent(user); // Nothing on failure.
283                                         user->CheckLines(true);
284                                 }
285                                 else if(iter->type == IDENTFIRST && !CheckIdent(user))
286                                 {
287                                         // If the ident lookup fails, try the password.
288                                         CheckPass(user);
289                                         user->CheckLines(true);
290                                 }
291                                 else if(iter->type == WEBIRC)
292                                 {
293                                         // We don't need to do anything here
294                                 }
295                                 return 0;
296                         }
297                 }
298                 return 0;
299         }
300
301         virtual void OnUserConnect(User* user)
302         {
303                 std::string *webirc_hostname, *webirc_ip;
304                 if(user->GetExt("cgiirc_webirc_hostname", webirc_hostname))
305                 {
306                         user->host.assign(*webirc_hostname, 0, 64);
307                         user->dhost.assign(*webirc_hostname, 0, 64);
308                         delete webirc_hostname;
309                         user->InvalidateCache();
310                         user->Shrink("cgiirc_webirc_hostname");
311                 }
312                 if(user->GetExt("cgiirc_webirc_ip", webirc_ip))
313                 {
314                         ServerInstance->Users->RemoveCloneCounts(user);
315                         user->SetSockAddr(user->GetProtocolFamily(), webirc_ip->c_str(), user->GetPort());
316                         delete webirc_ip;
317                         user->InvalidateCache();
318                         user->Shrink("cgiirc_webirc_ip");
319                         ServerInstance->Users->AddLocalClone(user);
320                         ServerInstance->Users->AddGlobalClone(user);
321                         user->CheckClass();
322                         user->CheckLines(true);
323                 }
324         }
325
326         bool CheckPass(User* user)
327         {
328                 if(IsValidHost(user->password))
329                 {
330                         user->Extend("cgiirc_realhost", new std::string(user->host));
331                         user->Extend("cgiirc_realip", new std::string(user->GetIPString()));
332                         user->host.assign(user->password, 0, 64);
333                         user->dhost.assign(user->password, 0, 64);
334                         user->InvalidateCache();
335
336                         bool valid = false;
337                         ServerInstance->Users->RemoveCloneCounts(user);
338 #ifdef IPV6
339                         if (user->GetProtocolFamily() == AF_INET6)
340                                 valid = (inet_pton(AF_INET6, user->password.c_str(), &((sockaddr_in6*)user->ip)->sin6_addr) > 0);
341                         else
342                                 valid = (inet_aton(user->password.c_str(), &((sockaddr_in*)user->ip)->sin_addr));
343 #else
344                         if (inet_aton(user->password.c_str(), &((sockaddr_in*)user->ip)->sin_addr))
345                                 valid = true;
346 #endif
347                         ServerInstance->Users->AddLocalClone(user);
348                         ServerInstance->Users->AddGlobalClone(user);
349                         user->CheckClass();
350
351                         if (valid)
352                         {
353                                 /* We were given a IP in the password, we don't do DNS so they get this is as their host as well. */
354                                 if(NotifyOpers)
355                                         ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from PASS", user->nick.c_str(), user->host.c_str(), user->password.c_str());
356                         }
357                         else
358                         {
359                                 /* We got as resolved hostname in the password. */
360                                 try
361                                 {
362
363                                         bool cached;
364                                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, user->password, false, user, user->GetFd(), "PASS", cached);
365                                         ServerInstance->AddResolver(r, cached);
366                                 }
367                                 catch (...)
368                                 {
369                                         if (NotifyOpers)
370                                                 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());
371                                 }
372                         }
373
374                         user->password.clear();
375                         return true;
376                 }
377
378                 return false;
379         }
380
381         bool CheckIdent(User* user)
382         {
383                 int ip[4];
384                 const char* ident;
385                 char newip[16];
386                 int len = user->ident.length();
387
388                 if(len == 8)
389                         ident = user->ident.c_str();
390                 else if(len == 9 && user->ident[0] == '~')
391                         ident = user->ident.c_str() + 1;
392                 else
393                         return false;
394
395                 for(int i = 0; i < 4; i++)
396                         if(!HexToInt(ip[i], ident + i*2))
397                                 return false;
398
399                 snprintf(newip, 16, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
400
401                 user->Extend("cgiirc_realhost", new std::string(user->host));
402                 user->Extend("cgiirc_realip", new std::string(user->GetIPString()));
403                 ServerInstance->Users->RemoveCloneCounts(user);
404                 user->SetSockAddr(user->GetProtocolFamily(), newip, user->GetPort());
405                 ServerInstance->Users->AddLocalClone(user);
406                 ServerInstance->Users->AddGlobalClone(user);
407                 user->CheckClass();
408                 try
409                 {
410                         user->host.assign(newip, 0, 16);
411                         user->dhost.assign(newip, 0, 16);
412                         user->ident.assign("~cgiirc", 0, 8);
413
414                         bool cached;
415                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, newip, false, user, user->GetFd(), "IDENT", cached);
416                         ServerInstance->AddResolver(r, cached);
417                 }
418                 catch (...)
419                 {
420                         user->host.assign(newip, 0, 16);
421                         user->dhost.assign(newip, 0, 16);
422                         user->ident.assign("~cgiirc", 0, 8);
423                         user->InvalidateCache();
424
425                         if(NotifyOpers)
426                                  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());
427                 }
428
429                 return true;
430         }
431
432         bool IsValidHost(const std::string &host)
433         {
434                 if(!host.size())
435                         return false;
436
437                 for(unsigned int i = 0; i < host.size(); i++)
438                 {
439                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
440                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
441                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
442                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
443                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
444
445                                 continue;
446                         else
447                                 return false;
448                 }
449
450                 return true;
451         }
452
453         bool IsValidIP(const std::string &ip)
454         {
455                 if(ip.size() < 7 || ip.size() > 15)
456                         return false;
457
458                 short sincedot = 0;
459                 short dots = 0;
460
461                 for(unsigned int i = 0; i < ip.size(); i++)
462                 {
463                         if((dots <= 3) && (sincedot <= 3))
464                         {
465                                 if((ip[i] >= '0') && (ip[i] <= '9'))
466                                 {
467                                         sincedot++;
468                                 }
469                                 else if(ip[i] == '.')
470                                 {
471                                         sincedot = 0;
472                                         dots++;
473                                 }
474                         }
475                         else
476                         {
477                                 return false;
478
479                         }
480                 }
481
482                 if(dots != 3)
483                         return false;
484
485                 return true;
486         }
487
488         bool HexToInt(int &out, const char* in)
489         {
490                 char ip[3];
491                 ip[0] = in[0];
492                 ip[1] = in[1];
493                 ip[2] = 0;
494                 out = strtol(ip, NULL, 16);
495
496                 if(out > 255 || out < 0)
497                         return false;
498
499                 return true;
500         }
501
502         virtual ~ModuleCgiIRC()
503         {
504         }
505
506         virtual Version GetVersion()
507         {
508                 return Version("$Id$",VF_VENDOR,API_VERSION);
509         }
510
511 };
512
513 MODULE_INIT(ModuleCgiIRC)