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