]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_sasl.cpp
Merge pull request #1337 from SaberUK/master+merge
[user/henk/code/inspircd.git] / src / modules / m_sasl.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc>
6  *
7  * This file is part of InspIRCd.  InspIRCd is free software: you can
8  * redistribute it and/or modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation, version 2.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20
21 #include "inspircd.h"
22 #include "modules/cap.h"
23 #include "modules/account.h"
24 #include "modules/sasl.h"
25 #include "modules/ssl.h"
26 #include "modules/spanningtree.h"
27
28 static std::string sasl_target;
29
30 class ServerTracker : public SpanningTreeEventListener
31 {
32         bool online;
33
34         void Update(const Server* server, bool linked)
35         {
36                 if (sasl_target == "*")
37                         return;
38
39                 if (InspIRCd::Match(server->GetName(), sasl_target))
40                 {
41                         ServerInstance->Logs->Log(MODNAME, LOG_VERBOSE, "SASL target server \"%s\" %s", sasl_target.c_str(), (linked ? "came online" : "went offline"));
42                         online = linked;
43                 }
44         }
45
46         void OnServerLink(const Server* server) CXX11_OVERRIDE
47         {
48                 Update(server, true);
49         }
50
51         void OnServerSplit(const Server* server) CXX11_OVERRIDE
52         {
53                 Update(server, false);
54         }
55
56  public:
57         ServerTracker(Module* mod)
58                 : SpanningTreeEventListener(mod)
59         {
60                 Reset();
61         }
62
63         void Reset()
64         {
65                 if (sasl_target == "*")
66                 {
67                         online = true;
68                         return;
69                 }
70
71                 online = false;
72
73                 ProtocolInterface::ServerList servers;
74                 ServerInstance->PI->GetServerList(servers);
75                 for (ProtocolInterface::ServerList::const_iterator i = servers.begin(); i != servers.end(); ++i)
76                 {
77                         const ProtocolInterface::ServerInfo& server = *i;
78                         if (InspIRCd::Match(server.servername, sasl_target))
79                         {
80                                 online = true;
81                                 break;
82                         }
83                 }
84         }
85
86         bool IsOnline() const { return online; }
87 };
88
89 class SASLCap : public Cap::Capability
90 {
91         std::string mechlist;
92         const ServerTracker& servertracker;
93
94         bool OnRequest(LocalUser* user, bool adding) CXX11_OVERRIDE
95         {
96                 // Requesting this cap is allowed anytime
97                 if (adding)
98                         return true;
99
100                 // But removing it can only be done when unregistered
101                 return (user->registered != REG_ALL);
102         }
103
104         bool OnList(LocalUser* user) CXX11_OVERRIDE
105         {
106                 return servertracker.IsOnline();
107         }
108
109         const std::string* GetValue(LocalUser* user) const CXX11_OVERRIDE
110         {
111                 return &mechlist;
112         }
113
114  public:
115         SASLCap(Module* mod, const ServerTracker& tracker)
116                 : Cap::Capability(mod, "sasl")
117                 , servertracker(tracker)
118         {
119         }
120
121         void SetMechlist(const std::string& newmechlist)
122         {
123                 if (mechlist == newmechlist)
124                         return;
125
126                 mechlist = newmechlist;
127                 NotifyValueChange();
128         }
129 };
130
131 enum SaslState { SASL_INIT, SASL_COMM, SASL_DONE };
132 enum SaslResult { SASL_OK, SASL_FAIL, SASL_ABORT };
133
134 static Events::ModuleEventProvider* saslevprov;
135
136 static void SendSASL(const parameterlist& params)
137 {
138         if (!ServerInstance->PI->SendEncapsulatedData(sasl_target, "SASL", params))
139         {
140                 FOREACH_MOD_CUSTOM(*saslevprov, SASLEventListener, OnSASLAuth, (params));
141         }
142 }
143
144 /**
145  * Tracks SASL authentication state like charybdis does. --nenolod
146  */
147 class SaslAuthenticator
148 {
149  private:
150         std::string agent;
151         User *user;
152         SaslState state;
153         SaslResult result;
154         bool state_announced;
155
156         /* taken from m_services_account */
157         static bool ReadCGIIRCExt(const char* extname, User* user, std::string& out)
158         {
159                 ExtensionItem* wiext = ServerInstance->Extensions.GetItem(extname);
160                 if (!wiext)
161                         return false;
162
163                 if (wiext->creator->ModuleSourceFile != "m_cgiirc.so")
164                         return false;
165
166                 StringExtItem* stringext = static_cast<StringExtItem*>(wiext);
167                 std::string* addr = stringext->get(user);
168                 if (!addr)
169                         return false;
170
171                 out = *addr;
172                 return true;
173         }
174
175
176         void SendHostIP()
177         {
178                 std::string host, ip;
179
180                 if (!ReadCGIIRCExt("cgiirc_webirc_hostname", user, host))
181                 {
182                         host = user->host;
183                 }
184                 if (!ReadCGIIRCExt("cgiirc_webirc_ip", user, ip))
185                 {
186                         ip = user->GetIPString();
187                 }
188                 else
189                 {
190                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
191                         if (ip.c_str()[0] == ':')
192                                 ip.insert(ip.begin(),1,'0');
193                 }
194
195                 parameterlist params;
196                 params.push_back(sasl_target);
197                 params.push_back("SASL");
198                 params.push_back(user->uuid);
199                 params.push_back("*");
200                 params.push_back("H");
201                 params.push_back(host);
202                 params.push_back(ip);
203
204                 SendSASL(params);
205         }
206
207  public:
208         SaslAuthenticator(User* user_, const std::string& method)
209                 : user(user_), state(SASL_INIT), state_announced(false)
210         {
211                 SendHostIP();
212
213                 parameterlist params;
214                 params.push_back(user->uuid);
215                 params.push_back("*");
216                 params.push_back("S");
217                 params.push_back(method);
218
219                 LocalUser* localuser = IS_LOCAL(user);
220                 if (method == "EXTERNAL" && localuser)
221                 {
222                         std::string fp = SSLClientCert::GetFingerprint(&localuser->eh);
223
224                         if (fp.size())
225                                 params.push_back(fp);
226                 }
227
228                 SendSASL(params);
229         }
230
231         SaslResult GetSaslResult(const std::string &result_)
232         {
233                 if (result_ == "F")
234                         return SASL_FAIL;
235
236                 if (result_ == "A")
237                         return SASL_ABORT;
238
239                 return SASL_OK;
240         }
241
242         /* checks for and deals with a state change. */
243         SaslState ProcessInboundMessage(const std::vector<std::string> &msg)
244         {
245                 switch (this->state)
246                 {
247                  case SASL_INIT:
248                         this->agent = msg[0];
249                         this->state = SASL_COMM;
250                         /* fall through */
251                  case SASL_COMM:
252                         if (msg[0] != this->agent)
253                                 return this->state;
254
255                         if (msg.size() < 4)
256                                 return this->state;
257
258                         if (msg[2] == "C")
259                                 this->user->Write("AUTHENTICATE %s", msg[3].c_str());
260                         else if (msg[2] == "D")
261                         {
262                                 this->state = SASL_DONE;
263                                 this->result = this->GetSaslResult(msg[3]);
264                         }
265                         else if (msg[2] == "M")
266                                 this->user->WriteNumeric(908, msg[3], "are available SASL mechanisms");
267                         else
268                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Services sent an unknown SASL message \"%s\" \"%s\"", msg[2].c_str(), msg[3].c_str());
269
270                         break;
271                  case SASL_DONE:
272                         break;
273                  default:
274                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WTF: SaslState is not a known state (%d)", this->state);
275                         break;
276                 }
277
278                 return this->state;
279         }
280
281         void Abort(void)
282         {
283                 this->state = SASL_DONE;
284                 this->result = SASL_ABORT;
285         }
286
287         bool SendClientMessage(const std::vector<std::string>& parameters)
288         {
289                 if (this->state != SASL_COMM)
290                         return true;
291
292                 parameterlist params;
293                 params.push_back(this->user->uuid);
294                 params.push_back(this->agent);
295                 params.push_back("C");
296
297                 params.insert(params.end(), parameters.begin(), parameters.end());
298
299                 SendSASL(params);
300
301                 if (parameters[0].c_str()[0] == '*')
302                 {
303                         this->Abort();
304                         return false;
305                 }
306
307                 return true;
308         }
309
310         void AnnounceState(void)
311         {
312                 if (this->state_announced)
313                         return;
314
315                 switch (this->result)
316                 {
317                  case SASL_OK:
318                         this->user->WriteNumeric(903, "SASL authentication successful");
319                         break;
320                  case SASL_ABORT:
321                         this->user->WriteNumeric(906, "SASL authentication aborted");
322                         break;
323                  case SASL_FAIL:
324                         this->user->WriteNumeric(904, "SASL authentication failed");
325                         break;
326                  default:
327                         break;
328                 }
329
330                 this->state_announced = true;
331         }
332 };
333
334 class CommandAuthenticate : public Command
335 {
336  public:
337         SimpleExtItem<SaslAuthenticator>& authExt;
338         Cap::Capability& cap;
339         CommandAuthenticate(Module* Creator, SimpleExtItem<SaslAuthenticator>& ext, Cap::Capability& Cap)
340                 : Command(Creator, "AUTHENTICATE", 1), authExt(ext), cap(Cap)
341         {
342                 works_before_reg = true;
343                 allow_empty_last_param = false;
344         }
345
346         CmdResult Handle (const std::vector<std::string>& parameters, User *user)
347         {
348                 {
349                         if (!cap.get(user))
350                                 return CMD_FAILURE;
351
352                         if (parameters[0].find(' ') != std::string::npos || parameters[0][0] == ':')
353                                 return CMD_FAILURE;
354
355                         SaslAuthenticator *sasl = authExt.get(user);
356                         if (!sasl)
357                                 authExt.set(user, new SaslAuthenticator(user, parameters[0]));
358                         else if (sasl->SendClientMessage(parameters) == false)  // IAL abort extension --nenolod
359                         {
360                                 sasl->AnnounceState();
361                                 authExt.unset(user);
362                         }
363                 }
364                 return CMD_FAILURE;
365         }
366 };
367
368 class CommandSASL : public Command
369 {
370  public:
371         SimpleExtItem<SaslAuthenticator>& authExt;
372         CommandSASL(Module* Creator, SimpleExtItem<SaslAuthenticator>& ext) : Command(Creator, "SASL", 2), authExt(ext)
373         {
374                 this->flags_needed = FLAG_SERVERONLY; // should not be called by users
375         }
376
377         CmdResult Handle(const std::vector<std::string>& parameters, User *user)
378         {
379                 User* target = ServerInstance->FindUUID(parameters[1]);
380                 if (!target)
381                 {
382                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User not found in sasl ENCAP event: %s", parameters[1].c_str());
383                         return CMD_FAILURE;
384                 }
385
386                 SaslAuthenticator *sasl = authExt.get(target);
387                 if (!sasl)
388                         return CMD_FAILURE;
389
390                 SaslState state = sasl->ProcessInboundMessage(parameters);
391                 if (state == SASL_DONE)
392                 {
393                         sasl->AnnounceState();
394                         authExt.unset(target);
395                 }
396                 return CMD_SUCCESS;
397         }
398
399         RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters)
400         {
401                 return ROUTE_BROADCAST;
402         }
403 };
404
405 class ModuleSASL : public Module
406 {
407         SimpleExtItem<SaslAuthenticator> authExt;
408         ServerTracker servertracker;
409         SASLCap cap;
410         CommandAuthenticate auth;
411         CommandSASL sasl;
412         Events::ModuleEventProvider sasleventprov;
413
414  public:
415         ModuleSASL()
416                 : authExt("sasl_auth", ExtensionItem::EXT_USER, this)
417                 , servertracker(this)
418                 , cap(this, servertracker)
419                 , auth(this, authExt, cap)
420                 , sasl(this, authExt)
421                 , sasleventprov(this, "event/sasl")
422         {
423                 saslevprov = &sasleventprov;
424         }
425
426         void init() CXX11_OVERRIDE
427         {
428                 if (!ServerInstance->Modules->Find("m_services_account.so") || !ServerInstance->Modules->Find("m_cap.so"))
429                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: m_services_account.so and m_cap.so are not loaded! m_sasl.so will NOT function correctly until these two modules are loaded!");
430         }
431
432         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
433         {
434                 sasl_target = ServerInstance->Config->ConfValue("sasl")->getString("target", "*");
435                 servertracker.Reset();
436         }
437
438         void OnUserConnect(LocalUser *user) CXX11_OVERRIDE
439         {
440                 SaslAuthenticator *sasl_ = authExt.get(user);
441                 if (sasl_)
442                 {
443                         sasl_->Abort();
444                         authExt.unset(user);
445                 }
446         }
447
448         void OnDecodeMetaData(Extensible* target, const std::string& extname, const std::string& extdata) CXX11_OVERRIDE
449         {
450                 if ((target == NULL) && (extname == "saslmechlist"))
451                         cap.SetMechlist(extdata);
452         }
453
454         Version GetVersion() CXX11_OVERRIDE
455         {
456                 return Version("Provides support for IRC Authentication Layer (aka: SASL) via AUTHENTICATE.", VF_VENDOR);
457         }
458 };
459
460 MODULE_INIT(ModuleSASL)