]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cgiirc.cpp
c72e183906a5e5350a0705fe71569f84d16ef6bf
[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         StringExtItem realhost;
59         StringExtItem realip;
60         LocalStringExt webirc_hostname;
61         LocalStringExt webirc_ip;
62
63         CGIHostlist Hosts;
64         CommandWebirc(InspIRCd* Instance, Module* Creator, bool bnotify)
65                 : Command(Instance, Creator, "WEBIRC", 0, 4, true), notify(bnotify),
66                   realhost("cgiirc_realhost", Creator), realip("cgiirc_realip", Creator),
67                   webirc_hostname("cgiirc_webirc_hostname", Creator), webirc_ip("cgiirc_webirc_ip", Creator)
68                 {
69                         this->syntax = "password client hostname ip";
70                 }
71                 CmdResult Handle(const std::vector<std::string> &parameters, User *user)
72                 {
73                         if(user->registered == REG_ALL)
74                                 return CMD_FAILURE;
75
76                         for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++)
77                         {
78                                 if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
79                                 {
80                                         if(iter->type == WEBIRC && parameters[0] == iter->password)
81                                         {
82                                                 realhost.set(user, user->host);
83                                                 realip.set(user, user->GetIPString());
84                                                 if (notify)
85                                                         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());
86                                                 webirc_hostname.set(user, parameters[2]);
87                                                 webirc_ip.set(user, parameters[3]);
88                                                 return CMD_SUCCESS;
89                                         }
90                                 }
91                         }
92
93                         ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str());
94                         return CMD_FAILURE;
95                 }
96 };
97
98
99 /** Resolver for CGI:IRC hostnames encoded in ident/GECOS
100  */
101 class CGIResolver : public Resolver
102 {
103         std::string typ;
104         int theirfd;
105         User* them;
106         bool notify;
107  public:
108         CGIResolver(Module* me, InspIRCd* Instance, bool NotifyOpers, const std::string &source, bool forward, User* u, int userfd, const std::string &type, bool &cached)
109                 : Resolver(Instance, source, forward ? DNS_QUERY_A : DNS_QUERY_PTR4, cached, me), typ(type), theirfd(userfd), them(u), notify(NotifyOpers) { }
110
111         virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
112         {
113                 /* Check the user still exists */
114                 if ((them) && (them == ServerInstance->SE->GetRef(theirfd)))
115                 {
116                         if (notify)
117                                 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());
118
119                         them->host.assign(result,0, 64);
120                         them->dhost.assign(result, 0, 64);
121                         if (querytype)
122                                 them->SetClientIP(result.c_str());
123                         them->ident.assign("~cgiirc", 0, 8);
124                         them->InvalidateCache();
125                         them->CheckLines(true);
126                 }
127         }
128
129         virtual void OnError(ResolverError e, const std::string &errormessage)
130         {
131                 if ((them) && (them == ServerInstance->SE->GetRef(theirfd)))
132                 {
133                         if (notify)
134                                 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());
135                 }
136         }
137
138         virtual ~CGIResolver()
139         {
140         }
141 };
142
143 class ModuleCgiIRC : public Module
144 {
145         CommandWebirc cmd;
146         bool NotifyOpers;
147 public:
148         ModuleCgiIRC(InspIRCd* Me) : Module(Me), cmd(Me, this, NotifyOpers)
149         {
150                 OnRehash(NULL);
151                 ServerInstance->AddCommand(&cmd);
152                 Extensible::Register(&cmd.realhost);
153                 Extensible::Register(&cmd.realip);
154                 Extensible::Register(&cmd.webirc_hostname);
155                 Extensible::Register(&cmd.webirc_ip);
156
157                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCleanup, I_OnSyncUser, I_OnDecodeMetaData, I_OnUserDisconnect, I_OnUserConnect };
158                 ServerInstance->Modules->Attach(eventlist, this, 7);
159         }
160
161
162         virtual void Prioritize()
163         {
164                 ServerInstance->Modules->SetPriority(this, I_OnUserConnect, PRIORITY_FIRST);
165         }
166
167         virtual void OnRehash(User* user)
168         {
169                 ConfigReader Conf(ServerInstance);
170                 cmd.Hosts.clear();
171
172                 NotifyOpers = Conf.ReadFlag("cgiirc", "opernotice", 0); // If we send an oper notice when a CGI:IRC has their host changed.
173
174                 if(Conf.GetError() == CONF_VALUE_NOT_FOUND)
175                         NotifyOpers = true;
176
177                 for(int i = 0; i < Conf.Enumerate("cgihost"); i++)
178                 {
179                         std::string hostmask = Conf.ReadValue("cgihost", "mask", i); // An allowed CGI:IRC host
180                         std::string type = Conf.ReadValue("cgihost", "type", i); // What type of user-munging we do on this host.
181                         std::string password = Conf.ReadValue("cgihost", "password", i);
182
183                         if(hostmask.length())
184                         {
185                                 if (type == "webirc" && !password.length()) {
186                                                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc: Missing password in config: %s", hostmask.c_str());
187                                 }
188                                 else
189                                 {
190                                         CGItype cgitype = INVALID;
191                                         if (type == "pass")
192                                                 cgitype = PASS;
193                                         else if (type == "ident")
194                                                 cgitype = IDENT;
195                                         else if (type == "passfirst")
196                                                 cgitype = PASSFIRST;
197                                         else if (type == "webirc")
198                                         {
199                                                 cgitype = WEBIRC;
200                                         }
201
202                                         if (cgitype == INVALID)
203                                                 cgitype = PASS;
204
205                                         cmd.Hosts.push_back(CGIhost(hostmask,cgitype, password.length() ? password : "" ));
206                                 }
207                         }
208                         else
209                         {
210                                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc.so: Invalid <cgihost:mask> value in config: %s", hostmask.c_str());
211                                 continue;
212                         }
213                 }
214         }
215
216         virtual ModResult OnUserRegister(User* user)
217         {
218                 for(CGIHostlist::iterator iter = cmd.Hosts.begin(); iter != cmd.Hosts.end(); iter++)
219                 {
220                         if(InspIRCd::Match(user->host, iter->hostmask, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(user->GetIPString(), iter->hostmask, ascii_case_insensitive_map))
221                         {
222                                 // Deal with it...
223                                 if(iter->type == PASS)
224                                 {
225                                         CheckPass(user); // We do nothing if it fails so...
226                                         user->CheckLines(true);
227                                 }
228                                 else if(iter->type == PASSFIRST && !CheckPass(user))
229                                 {
230                                         // If the password lookup failed, try the ident
231                                         CheckIdent(user);       // If this fails too, do nothing
232                                         user->CheckLines(true);
233                                 }
234                                 else if(iter->type == IDENT)
235                                 {
236                                         CheckIdent(user); // Nothing on failure.
237                                         user->CheckLines(true);
238                                 }
239                                 else if(iter->type == IDENTFIRST && !CheckIdent(user))
240                                 {
241                                         // If the ident lookup fails, try the password.
242                                         CheckPass(user);
243                                         user->CheckLines(true);
244                                 }
245                                 else if(iter->type == WEBIRC)
246                                 {
247                                         // We don't need to do anything here
248                                 }
249                                 return MOD_RES_PASSTHRU;
250                         }
251                 }
252                 return MOD_RES_PASSTHRU;
253         }
254
255         virtual void OnUserConnect(User* user)
256         {
257                 std::string *webirc_hostname = cmd.webirc_hostname.get(user);
258                 std::string *webirc_ip = cmd.webirc_ip.get(user);
259                 if (webirc_hostname)
260                 {
261                         user->host.assign(*webirc_hostname, 0, 64);
262                         user->dhost.assign(*webirc_hostname, 0, 64);
263                         user->InvalidateCache();
264                         cmd.webirc_hostname.unset(user);
265                 }
266                 if (webirc_ip)
267                 {
268                         ServerInstance->Users->RemoveCloneCounts(user);
269                         user->SetClientIP(webirc_ip->c_str());
270                         user->InvalidateCache();
271                         cmd.webirc_ip.unset(user);
272                         ServerInstance->Users->AddLocalClone(user);
273                         ServerInstance->Users->AddGlobalClone(user);
274                         user->CheckClass();
275                         user->CheckLines(true);
276                 }
277         }
278
279         bool CheckPass(User* user)
280         {
281                 if(IsValidHost(user->password))
282                 {
283                         cmd.realhost.set(user, user->host);
284                         cmd.realip.set(user, user->GetIPString());
285                         user->host.assign(user->password, 0, 64);
286                         user->dhost.assign(user->password, 0, 64);
287                         user->InvalidateCache();
288
289                         bool valid = false;
290                         ServerInstance->Users->RemoveCloneCounts(user);
291                         valid = user->SetClientIP(user->password.c_str());
292                         ServerInstance->Users->AddLocalClone(user);
293                         ServerInstance->Users->AddGlobalClone(user);
294                         user->CheckClass();
295
296                         if (valid)
297                         {
298                                 /* We were given a IP in the password, we don't do DNS so they get this is as their host as well. */
299                                 if(NotifyOpers)
300                                         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());
301                         }
302                         else
303                         {
304                                 /* We got as resolved hostname in the password. */
305                                 try
306                                 {
307
308                                         bool cached;
309                                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, user->password, false, user, user->GetFd(), "PASS", cached);
310                                         ServerInstance->AddResolver(r, cached);
311                                 }
312                                 catch (...)
313                                 {
314                                         if (NotifyOpers)
315                                                 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());
316                                 }
317                         }
318
319                         user->password.clear();
320                         return true;
321                 }
322
323                 return false;
324         }
325
326         bool CheckIdent(User* user)
327         {
328                 const char* ident;
329                 int len = user->ident.length();
330                 in_addr newip;
331
332                 if(len == 8)
333                         ident = user->ident.c_str();
334                 else if(len == 9 && user->ident[0] == '~')
335                         ident = user->ident.c_str() + 1;
336                 else
337                         return false;
338
339                 errno = 0;
340                 unsigned long ipaddr = strtoul(ident, NULL, 16);
341                 if (errno)
342                         return false;
343                 newip.s_addr = htonl(ipaddr);
344                 char* newipstr = inet_ntoa(newip);
345
346                 cmd.realhost.set(user, user->host);
347                 cmd.realip.set(user, user->GetIPString());
348                 ServerInstance->Users->RemoveCloneCounts(user);
349                 user->SetClientIP(newipstr);
350                 ServerInstance->Users->AddLocalClone(user);
351                 ServerInstance->Users->AddGlobalClone(user);
352                 user->CheckClass();
353                 user->host = newipstr;
354                 user->dhost = newipstr;
355                 user->ident.assign("~cgiirc", 0, 8);
356                 try
357                 {
358
359                         bool cached;
360                         CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, newipstr, false, user, user->GetFd(), "IDENT", cached);
361                         ServerInstance->AddResolver(r, cached);
362                 }
363                 catch (...)
364                 {
365                         user->InvalidateCache();
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                 return true;
372         }
373
374         bool IsValidHost(const std::string &host)
375         {
376                 if(!host.size())
377                         return false;
378
379                 for(unsigned int i = 0; i < host.size(); i++)
380                 {
381                         if(     ((host[i] >= '0') && (host[i] <= '9')) ||
382                                         ((host[i] >= 'A') && (host[i] <= 'Z')) ||
383                                         ((host[i] >= 'a') && (host[i] <= 'z')) ||
384                                         ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) ||
385                                         ((host[i] == '.') && (i > 0) && (i+1 < host.size())) )
386
387                                 continue;
388                         else
389                                 return false;
390                 }
391
392                 return true;
393         }
394
395         bool IsValidIP(const std::string &ip)
396         {
397                 if(ip.size() < 7 || ip.size() > 15)
398                         return false;
399
400                 short sincedot = 0;
401                 short dots = 0;
402
403                 for(unsigned int i = 0; i < ip.size(); i++)
404                 {
405                         if((dots <= 3) && (sincedot <= 3))
406                         {
407                                 if((ip[i] >= '0') && (ip[i] <= '9'))
408                                 {
409                                         sincedot++;
410                                 }
411                                 else if(ip[i] == '.')
412                                 {
413                                         sincedot = 0;
414                                         dots++;
415                                 }
416                         }
417                         else
418                         {
419                                 return false;
420
421                         }
422                 }
423
424                 if(dots != 3)
425                         return false;
426
427                 return true;
428         }
429
430         virtual ~ModuleCgiIRC()
431         {
432         }
433
434         virtual Version GetVersion()
435         {
436                 return Version("$Id$",VF_VENDOR,API_VERSION);
437         }
438
439 };
440
441 MODULE_INIT(ModuleCgiIRC)