]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
5800604642249a85362f872ff7c2f3305a6a3529
[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->SetSockAddr(them->GetProtocolFamily(), result.c_str(), them->GetPort());
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->SetSockAddr(user->GetProtocolFamily(), webirc_ip->c_str(), user->GetPort());
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 #ifdef IPV6
345                         if (user->GetProtocolFamily() == AF_INET6)
346                                 valid = (inet_pton(AF_INET6, user->password.c_str(), &((sockaddr_in6*)user->ip)->sin6_addr) > 0);
347                         else
348                                 valid = (inet_aton(user->password.c_str(), &((sockaddr_in*)user->ip)->sin_addr));
349 #else
350                         if (inet_aton(user->password.c_str(), &((sockaddr_in*)user->ip)->sin_addr))
351                                 valid = true;
352 #endif
353                         ServerInstance->Users->AddLocalClone(user);
354                         ServerInstance->Users->AddGlobalClone(user);
355                         user->CheckClass();
356
357                         if (valid)
358                         {
359                                 /* We were given a IP in the password, we don't do DNS so they get this is as their host as well. */
360                                 if(NotifyOpers)
361                                         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());
362                         }
363                         else
364                         {
365                                 /* We got as resolved hostname in the password. */
366                                 try
367                                 {
368
369                                         bool cached;
370                                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, user->password, false, user, user->GetFd(), "PASS", cached);
371                                         ServerInstance->AddResolver(r, cached);
372                                 }
373                                 catch (...)
374                                 {
375                                         if (NotifyOpers)
376                                                 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());
377                                 }
378                         }
379
380                         user->password.clear();
381                         return true;
382                 }
383
384                 return false;
385         }
386
387         bool CheckIdent(User* user)
388         {
389                 int ip[4];
390                 const char* ident;
391                 char newip[16];
392                 int len = user->ident.length();
393
394                 if(len == 8)
395                         ident = user->ident.c_str();
396                 else if(len == 9 && user->ident[0] == '~')
397                         ident = user->ident.c_str() + 1;
398                 else
399                         return false;
400
401                 for(int i = 0; i < 4; i++)
402                         if(!HexToInt(ip[i], ident + i*2))
403                                 return false;
404
405                 snprintf(newip, 16, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
406
407                 user->Extend("cgiirc_realhost", new std::string(user->host));
408                 user->Extend("cgiirc_realip", new std::string(user->GetIPString()));
409                 ServerInstance->Users->RemoveCloneCounts(user);
410                 user->SetSockAddr(user->GetProtocolFamily(), newip, user->GetPort());
411                 ServerInstance->Users->AddLocalClone(user);
412                 ServerInstance->Users->AddGlobalClone(user);
413                 user->CheckClass();
414                 try
415                 {
416                         user->host.assign(newip, 0, 16);
417                         user->dhost.assign(newip, 0, 16);
418                         user->ident.assign("~cgiirc", 0, 8);
419
420                         bool cached;
421                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, newip, false, user, user->GetFd(), "IDENT", cached);
422                         ServerInstance->AddResolver(r, cached);
423                 }
424                 catch (...)
425                 {
426                         user->host.assign(newip, 0, 16);
427                         user->dhost.assign(newip, 0, 16);
428                         user->ident.assign("~cgiirc", 0, 8);
429                         user->InvalidateCache();
430
431                         if(NotifyOpers)
432                                  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());
433                 }
434
435                 return true;
436         }
437
438         bool IsValidHost(const std::string &host)
439         {
440                 if(!host.size())
441                         return false;
442
443                 for(unsigned int i = 0; i < host.size(); i++)
444                 {
445                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
446                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
447                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
448                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
449                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
450
451                                 continue;
452                         else
453                                 return false;
454                 }
455
456                 return true;
457         }
458
459         bool IsValidIP(const std::string &ip)
460         {
461                 if(ip.size() < 7 || ip.size() > 15)
462                         return false;
463
464                 short sincedot = 0;
465                 short dots = 0;
466
467                 for(unsigned int i = 0; i < ip.size(); i++)
468                 {
469                         if((dots <= 3) && (sincedot <= 3))
470                         {
471                                 if((ip[i] >= '0') && (ip[i] <= '9'))
472                                 {
473                                         sincedot++;
474                                 }
475                                 else if(ip[i] == '.')
476                                 {
477                                         sincedot = 0;
478                                         dots++;
479                                 }
480                         }
481                         else
482                         {
483                                 return false;
484
485                         }
486                 }
487
488                 if(dots != 3)
489                         return false;
490
491                 return true;
492         }
493
494         bool HexToInt(int &out, const char* in)
495         {
496                 char ip[3];
497                 ip[0] = in[0];
498                 ip[1] = in[1];
499                 ip[2] = 0;
500                 out = strtol(ip, NULL, 16);
501
502                 if(out > 255 || out < 0)
503                         return false;
504
505                 return true;
506         }
507
508         virtual ~ModuleCgiIRC()
509         {
510         }
511
512         virtual Version GetVersion()
513         {
514                 return Version("$Id$",VF_VENDOR,API_VERSION);
515         }
516
517 };
518
519 MODULE_INIT(ModuleCgiIRC)