]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
8b7a77941d666c935fe02abccd12f309a9bc87bf
[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_OnSyncUserMetaData, 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 OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
228         {
229                 if((extname == "cgiirc_realhost") || (extname == "cgiirc_realip"))
230                 {
231                         std::string* data;
232
233                         if(user->GetExt(extname, data))
234                         {
235                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, *data);
236                         }
237                 }
238         }
239
240         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
241         {
242                 if(target_type == TYPE_USER)
243                 {
244                         User* dest = (User*)target;
245                         std::string* bleh;
246                         if(((extname == "cgiirc_realhost") || (extname == "cgiirc_realip")) && (!dest->GetExt(extname, bleh)))
247                         {
248                                 dest->Extend(extname, new std::string(extdata));
249                         }
250                 }
251         }
252
253         virtual void OnUserDisconnect(User* user)
254         {
255                 OnCleanup(TYPE_USER, user);
256         }
257
258
259         virtual int OnUserRegister(User* user)
260         {
261                 for(CGIHostlist::iterator iter = cmd.Hosts.begin(); iter != cmd.Hosts.end(); iter++)
262                 {
263                         if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
264                         {
265                                 // Deal with it...
266                                 if(iter->type == PASS)
267                                 {
268                                         CheckPass(user); // We do nothing if it fails so...
269                                         user->CheckLines(true);
270                                 }
271                                 else if(iter->type == PASSFIRST && !CheckPass(user))
272                                 {
273                                         // If the password lookup failed, try the ident
274                                         CheckIdent(user);       // If this fails too, do nothing
275                                         user->CheckLines(true);
276                                 }
277                                 else if(iter->type == IDENT)
278                                 {
279                                         CheckIdent(user); // Nothing on failure.
280                                         user->CheckLines(true);
281                                 }
282                                 else if(iter->type == IDENTFIRST && !CheckIdent(user))
283                                 {
284                                         // If the ident lookup fails, try the password.
285                                         CheckPass(user);
286                                         user->CheckLines(true);
287                                 }
288                                 else if(iter->type == WEBIRC)
289                                 {
290                                         // We don't need to do anything here
291                                 }
292                                 return 0;
293                         }
294                 }
295                 return 0;
296         }
297
298         virtual void OnUserConnect(User* user)
299         {
300                 std::string *webirc_hostname, *webirc_ip;
301                 if(user->GetExt("cgiirc_webirc_hostname", webirc_hostname))
302                 {
303                         user->host.assign(*webirc_hostname, 0, 64);
304                         user->dhost.assign(*webirc_hostname, 0, 64);
305                         delete webirc_hostname;
306                         user->InvalidateCache();
307                         user->Shrink("cgiirc_webirc_hostname");
308                 }
309                 if(user->GetExt("cgiirc_webirc_ip", webirc_ip))
310                 {
311                         ServerInstance->Users->RemoveCloneCounts(user);
312                         user->SetClientIP(webirc_ip->c_str());
313                         delete webirc_ip;
314                         user->InvalidateCache();
315                         user->Shrink("cgiirc_webirc_ip");
316                         ServerInstance->Users->AddLocalClone(user);
317                         ServerInstance->Users->AddGlobalClone(user);
318                         user->CheckClass();
319                         user->CheckLines(true);
320                 }
321         }
322
323         bool CheckPass(User* user)
324         {
325                 if(IsValidHost(user->password))
326                 {
327                         user->Extend("cgiirc_realhost", new std::string(user->host));
328                         user->Extend("cgiirc_realip", new std::string(user->GetIPString()));
329                         user->host.assign(user->password, 0, 64);
330                         user->dhost.assign(user->password, 0, 64);
331                         user->InvalidateCache();
332
333                         bool valid = false;
334                         ServerInstance->Users->RemoveCloneCounts(user);
335                         valid = user->SetClientIP(user->password.c_str());
336                         ServerInstance->Users->AddLocalClone(user);
337                         ServerInstance->Users->AddGlobalClone(user);
338                         user->CheckClass();
339
340                         if (valid)
341                         {
342                                 /* We were given a IP in the password, we don't do DNS so they get this is as their host as well. */
343                                 if(NotifyOpers)
344                                         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());
345                         }
346                         else
347                         {
348                                 /* We got as resolved hostname in the password. */
349                                 try
350                                 {
351
352                                         bool cached;
353                                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, user->password, false, user, user->GetFd(), "PASS", cached);
354                                         ServerInstance->AddResolver(r, cached);
355                                 }
356                                 catch (...)
357                                 {
358                                         if (NotifyOpers)
359                                                 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());
360                                 }
361                         }
362
363                         user->password.clear();
364                         return true;
365                 }
366
367                 return false;
368         }
369
370         bool CheckIdent(User* user)
371         {
372                 const char* ident;
373                 int len = user->ident.length();
374                 in_addr newip;
375
376                 if(len == 8)
377                         ident = user->ident.c_str();
378                 else if(len == 9 && user->ident[0] == '~')
379                         ident = user->ident.c_str() + 1;
380                 else
381                         return false;
382
383                 errno = 0;
384                 unsigned long ipaddr = strtoul(ident, NULL, 16);
385                 if (errno)
386                         return false;
387                 newip.s_addr = htonl(ipaddr);
388                 char* newipstr = inet_ntoa(newip);
389
390                 user->Extend("cgiirc_realhost", new std::string(user->host));
391                 user->Extend("cgiirc_realip", new std::string(user->GetIPString()));
392                 ServerInstance->Users->RemoveCloneCounts(user);
393                 user->SetClientIP(newipstr);
394                 ServerInstance->Users->AddLocalClone(user);
395                 ServerInstance->Users->AddGlobalClone(user);
396                 user->CheckClass();
397                 user->host = newipstr;
398                 user->dhost = newipstr;
399                 user->ident.assign("~cgiirc", 0, 8);
400                 try
401                 {
402
403                         bool cached;
404                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, newipstr, false, user, user->GetFd(), "IDENT", cached);
405                         ServerInstance->AddResolver(r, cached);
406                 }
407                 catch (...)
408                 {
409                         user->InvalidateCache();
410
411                         if(NotifyOpers)
412                                  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());
413                 }
414
415                 return true;
416         }
417
418         bool IsValidHost(const std::string &host)
419         {
420                 if(!host.size())
421                         return false;
422
423                 for(unsigned int i = 0; i < host.size(); i++)
424                 {
425                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
426                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
427                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
428                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
429                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
430
431                                 continue;
432                         else
433                                 return false;
434                 }
435
436                 return true;
437         }
438
439         bool IsValidIP(const std::string &ip)
440         {
441                 if(ip.size() < 7 || ip.size() > 15)
442                         return false;
443
444                 short sincedot = 0;
445                 short dots = 0;
446
447                 for(unsigned int i = 0; i < ip.size(); i++)
448                 {
449                         if((dots <= 3) && (sincedot <= 3))
450                         {
451                                 if((ip[i] >= '0') && (ip[i] <= '9'))
452                                 {
453                                         sincedot++;
454                                 }
455                                 else if(ip[i] == '.')
456                                 {
457                                         sincedot = 0;
458                                         dots++;
459                                 }
460                         }
461                         else
462                         {
463                                 return false;
464
465                         }
466                 }
467
468                 if(dots != 3)
469                         return false;
470
471                 return true;
472         }
473
474         virtual ~ModuleCgiIRC()
475         {
476         }
477
478         virtual Version GetVersion()
479         {
480                 return Version("$Id$",VF_VENDOR,API_VERSION);
481         }
482
483 };
484
485 MODULE_INIT(ModuleCgiIRC)