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