]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
Maxpara on these was 3, should be 2
[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://www.inspircd.org/wiki/index.php/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->WriteToSnoMask('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->WriteToSnoMask('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, int resultnum = 0)
105         {
106                 if (resultnum)
107                         return;
108
109                 /* Check the user still exists */
110                 if ((them) && (them == ServerInstance->SE->GetRef(theirfd)))
111                 {
112                         if (notify)
113                                 ServerInstance->SNO->WriteToSnoMask('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());
114
115                         them->host.assign(result,0, 64);
116                         them->dhost.assign(result, 0, 64);
117                         if (querytype)
118                                 them->SetSockAddr(them->GetProtocolFamily(), result.c_str(), them->GetPort());
119                         them->ident.assign("~cgiirc", 0, 8);
120                         them->InvalidateCache();
121                         them->CheckLines(true);
122                 }
123         }
124
125         virtual void OnError(ResolverError e, const std::string &errormessage)
126         {
127                 if ((them) && (them == ServerInstance->SE->GetRef(theirfd)))
128                 {
129                         if (notify)
130                                 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());
131                 }
132         }
133
134         virtual ~CGIResolver()
135         {
136         }
137 };
138
139 class ModuleCgiIRC : public Module
140 {
141         CommandWebirc* mycommand;
142         bool NotifyOpers;
143         CGIHostlist Hosts;
144 public:
145         ModuleCgiIRC(InspIRCd* Me) : Module(Me)
146         {
147
148                 OnRehash(NULL,"");
149                 mycommand = new CommandWebirc(Me, Hosts, NotifyOpers);
150                 ServerInstance->AddCommand(mycommand);
151
152                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCleanup, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUserDisconnect, I_OnUserConnect };
153                 ServerInstance->Modules->Attach(eventlist, this, 7);
154         }
155
156
157         virtual void Prioritize()
158         {
159                 ServerInstance->Modules->SetPriority(this, I_OnUserConnect, PRIORITY_FIRST);
160         }
161
162         virtual void OnRehash(User* user, const std::string &parameter)
163         {
164                 ConfigReader Conf(ServerInstance);
165                 Hosts.clear();
166
167                 NotifyOpers = Conf.ReadFlag("cgiirc", "opernotice", 0); // If we send an oper notice when a CGI:IRC has their host changed.
168
169                 if(Conf.GetError() == CONF_VALUE_NOT_FOUND)
170                         NotifyOpers = true;
171
172                 for(int i = 0; i < Conf.Enumerate("cgihost"); i++)
173                 {
174                         std::string hostmask = Conf.ReadValue("cgihost", "mask", i); // An allowed CGI:IRC host
175                         std::string type = Conf.ReadValue("cgihost", "type", i); // What type of user-munging we do on this host.
176                         std::string password = Conf.ReadValue("cgihost", "password", i);
177
178                         if(hostmask.length())
179                         {
180                                 if (type == "webirc" && !password.length()) {
181                                                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc: Missing password in config: %s", hostmask.c_str());
182                                 }
183                                 else
184                                 {
185                                         CGItype cgitype = INVALID;
186                                         if (type == "pass")
187                                                 cgitype = PASS;
188                                         else if (type == "ident")
189                                                 cgitype = IDENT;
190                                         else if (type == "passfirst")
191                                                 cgitype = PASSFIRST;
192                                         else if (type == "webirc")
193                                         {
194                                                 cgitype = WEBIRC;
195                                         }
196
197                                         if (cgitype == INVALID)
198                                                 cgitype = PASS;
199
200                                         Hosts.push_back(CGIhost(hostmask,cgitype, password.length() ? password : "" ));
201                                 }
202                         }
203                         else
204                         {
205                                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc.so: Invalid <cgihost:mask> value in config: %s", hostmask.c_str());
206                                 continue;
207                         }
208                 }
209         }
210
211         virtual void OnCleanup(int target_type, void* item)
212         {
213                 if(target_type == TYPE_USER)
214                 {
215                         User* user = (User*)item;
216                         std::string* realhost;
217                         std::string* realip;
218
219                         if(user->GetExt("cgiirc_realhost", realhost))
220                         {
221                                 delete realhost;
222                                 user->Shrink("cgiirc_realhost");
223                         }
224
225                         if(user->GetExt("cgiirc_realip", realip))
226                         {
227                                 delete realip;
228                                 user->Shrink("cgiirc_realip");
229                         }
230                 }
231         }
232
233         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
234         {
235                 if((extname == "cgiirc_realhost") || (extname == "cgiirc_realip"))
236                 {
237                         std::string* data;
238
239                         if(user->GetExt(extname, data))
240                         {
241                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, *data);
242                         }
243                 }
244         }
245
246         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
247         {
248                 if(target_type == TYPE_USER)
249                 {
250                         User* dest = (User*)target;
251                         std::string* bleh;
252                         if(((extname == "cgiirc_realhost") || (extname == "cgiirc_realip")) && (!dest->GetExt(extname, bleh)))
253                         {
254                                 dest->Extend(extname, new std::string(extdata));
255                         }
256                 }
257         }
258
259         virtual void OnUserDisconnect(User* user)
260         {
261                 OnCleanup(TYPE_USER, user);
262         }
263
264
265         virtual int OnUserRegister(User* user)
266         {
267                 for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++)
268                 {
269                         if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
270                         {
271                                 // Deal with it...
272                                 if(iter->type == PASS)
273                                 {
274                                         CheckPass(user); // We do nothing if it fails so...
275                                         user->CheckLines(true);
276                                 }
277                                 else if(iter->type == PASSFIRST && !CheckPass(user))
278                                 {
279                                         // If the password lookup failed, try the ident
280                                         CheckIdent(user);       // If this fails too, do nothing
281                                         user->CheckLines(true);
282                                 }
283                                 else if(iter->type == IDENT)
284                                 {
285                                         CheckIdent(user); // Nothing on failure.
286                                         user->CheckLines(true);
287                                 }
288                                 else if(iter->type == IDENTFIRST && !CheckIdent(user))
289                                 {
290                                         // If the ident lookup fails, try the password.
291                                         CheckPass(user);
292                                         user->CheckLines(true);
293                                 }
294                                 else if(iter->type == WEBIRC)
295                                 {
296                                         // We don't need to do anything here
297                                 }
298                                 return 0;
299                         }
300                 }
301                 return 0;
302         }
303
304         virtual void OnUserConnect(User* user)
305         {
306                 std::string *webirc_hostname, *webirc_ip;
307                 if(user->GetExt("cgiirc_webirc_hostname", webirc_hostname))
308                 {
309                         user->host.assign(*webirc_hostname, 0, 64);
310                         user->dhost.assign(*webirc_hostname, 0, 64);
311                         delete webirc_hostname;
312                         user->InvalidateCache();
313                         user->Shrink("cgiirc_webirc_hostname");
314                 }
315                 if(user->GetExt("cgiirc_webirc_ip", webirc_ip))
316                 {
317                         ServerInstance->Users->RemoveCloneCounts(user);
318                         user->SetSockAddr(user->GetProtocolFamily(), webirc_ip->c_str(), user->GetPort());
319                         delete webirc_ip;
320                         user->InvalidateCache();
321                         user->Shrink("cgiirc_webirc_ip");
322                         ServerInstance->Users->AddLocalClone(user);
323                         ServerInstance->Users->AddGlobalClone(user);
324                         user->CheckClass();
325                         user->CheckLines(true);
326                 }
327         }
328
329         bool CheckPass(User* user)
330         {
331                 if(IsValidHost(user->password))
332                 {
333                         user->Extend("cgiirc_realhost", new std::string(user->host));
334                         user->Extend("cgiirc_realip", new std::string(user->GetIPString()));
335                         user->host.assign(user->password, 0, 64);
336                         user->dhost.assign(user->password, 0, 64);
337                         user->InvalidateCache();
338
339                         bool valid = false;
340                         ServerInstance->Users->RemoveCloneCounts(user);
341 #ifdef IPV6
342                         if (user->GetProtocolFamily() == AF_INET6)
343                                 valid = (inet_pton(AF_INET6, user->password.c_str(), &((sockaddr_in6*)user->ip)->sin6_addr) > 0);
344                         else
345                                 valid = (inet_aton(user->password.c_str(), &((sockaddr_in*)user->ip)->sin_addr));
346 #else
347                         if (inet_aton(user->password.c_str(), &((sockaddr_in*)user->ip)->sin_addr))
348                                 valid = true;
349 #endif
350                         ServerInstance->Users->AddLocalClone(user);
351                         ServerInstance->Users->AddGlobalClone(user);
352                         user->CheckClass();
353
354                         if (valid)
355                         {
356                                 /* We were given a IP in the password, we don't do DNS so they get this is as their host as well. */
357                                 if(NotifyOpers)
358                                         ServerInstance->SNO->WriteToSnoMask('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());
359                         }
360                         else
361                         {
362                                 /* We got as resolved hostname in the password. */
363                                 try
364                                 {
365
366                                         bool cached;
367                                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, user->password, false, user, user->GetFd(), "PASS", cached);
368                                         ServerInstance->AddResolver(r, cached);
369                                 }
370                                 catch (...)
371                                 {
372                                         if (NotifyOpers)
373                                                 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());
374                                 }
375                         }
376
377                         user->password.clear();
378                         return true;
379                 }
380
381                 return false;
382         }
383
384         bool CheckIdent(User* user)
385         {
386                 int ip[4];
387                 const char* ident;
388                 char newip[16];
389                 int len = user->ident.length();
390
391                 if(len == 8)
392                         ident = user->ident.c_str();
393                 else if(len == 9 && user->ident[0] == '~')
394                         ident = user->ident.c_str() + 1;
395                 else
396                         return false;
397
398                 for(int i = 0; i < 4; i++)
399                         if(!HexToInt(ip[i], ident + i*2))
400                                 return false;
401
402                 snprintf(newip, 16, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
403
404                 user->Extend("cgiirc_realhost", new std::string(user->host));
405                 user->Extend("cgiirc_realip", new std::string(user->GetIPString()));
406                 ServerInstance->Users->RemoveCloneCounts(user);
407                 user->SetSockAddr(user->GetProtocolFamily(), newip, user->GetPort());
408                 ServerInstance->Users->AddLocalClone(user);
409                 ServerInstance->Users->AddGlobalClone(user);
410                 user->CheckClass();
411                 try
412                 {
413                         user->host.assign(newip, 0, 16);
414                         user->dhost.assign(newip, 0, 16);
415                         user->ident.assign("~cgiirc", 0, 8);
416
417                         bool cached;
418                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, newip, false, user, user->GetFd(), "IDENT", cached);
419                         ServerInstance->AddResolver(r, cached);
420                 }
421                 catch (...)
422                 {
423                         user->host.assign(newip, 0, 16);
424                         user->dhost.assign(newip, 0, 16);
425                         user->ident.assign("~cgiirc", 0, 8);
426                         user->InvalidateCache();
427
428                         if(NotifyOpers)
429                                  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());
430                 }
431
432                 return true;
433         }
434
435         bool IsValidHost(const std::string &host)
436         {
437                 if(!host.size())
438                         return false;
439
440                 for(unsigned int i = 0; i < host.size(); i++)
441                 {
442                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
443                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
444                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
445                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
446                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
447
448                                 continue;
449                         else
450                                 return false;
451                 }
452
453                 return true;
454         }
455
456         bool IsValidIP(const std::string &ip)
457         {
458                 if(ip.size() < 7 || ip.size() > 15)
459                         return false;
460
461                 short sincedot = 0;
462                 short dots = 0;
463
464                 for(unsigned int i = 0; i < ip.size(); i++)
465                 {
466                         if((dots <= 3) && (sincedot <= 3))
467                         {
468                                 if((ip[i] >= '0') && (ip[i] <= '9'))
469                                 {
470                                         sincedot++;
471                                 }
472                                 else if(ip[i] == '.')
473                                 {
474                                         sincedot = 0;
475                                         dots++;
476                                 }
477                         }
478                         else
479                         {
480                                 return false;
481
482                         }
483                 }
484
485                 if(dots != 3)
486                         return false;
487
488                 return true;
489         }
490
491         bool HexToInt(int &out, const char* in)
492         {
493                 char ip[3];
494                 ip[0] = in[0];
495                 ip[1] = in[1];
496                 ip[2] = 0;
497                 out = strtol(ip, NULL, 16);
498
499                 if(out > 255 || out < 0)
500                         return false;
501
502                 return true;
503         }
504
505         virtual ~ModuleCgiIRC()
506         {
507         }
508
509         virtual Version GetVersion()
510         {
511                 return Version("$Id$",VF_VENDOR,API_VERSION);
512         }
513
514 };
515
516 MODULE_INIT(ModuleCgiIRC)