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