]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_sasl.cpp
Fix an shadowing warning in the spanningtree module.
[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/server.h"
27
28 enum
29 {
30         // From IRCv3 sasl-3.1
31         RPL_SASLSUCCESS = 903,
32         ERR_SASLFAIL = 904,
33         ERR_SASLTOOLONG = 905,
34         ERR_SASLABORTED = 906,
35         RPL_SASLMECHS = 908
36 };
37
38 static std::string sasl_target;
39
40 class ServerTracker
41         : public ServerProtocol::LinkEventListener
42 {
43         // Stop GCC warnings about the deprecated OnServerSplit event.
44         using ServerProtocol::LinkEventListener::OnServerSplit;
45
46         bool online;
47
48         void Update(const Server* server, bool linked)
49         {
50                 if (sasl_target == "*")
51                         return;
52
53                 if (InspIRCd::Match(server->GetName(), sasl_target))
54                 {
55                         ServerInstance->Logs->Log(MODNAME, LOG_VERBOSE, "SASL target server \"%s\" %s", sasl_target.c_str(), (linked ? "came online" : "went offline"));
56                         online = linked;
57                 }
58         }
59
60         void OnServerLink(const Server* server) CXX11_OVERRIDE
61         {
62                 Update(server, true);
63         }
64
65         void OnServerSplit(const Server* server, bool error) CXX11_OVERRIDE
66         {
67                 Update(server, false);
68         }
69
70  public:
71         ServerTracker(Module* mod)
72                 : ServerProtocol::LinkEventListener(mod)
73         {
74                 Reset();
75         }
76
77         void Reset()
78         {
79                 if (sasl_target == "*")
80                 {
81                         online = true;
82                         return;
83                 }
84
85                 online = false;
86
87                 ProtocolInterface::ServerList servers;
88                 ServerInstance->PI->GetServerList(servers);
89                 for (ProtocolInterface::ServerList::const_iterator i = servers.begin(); i != servers.end(); ++i)
90                 {
91                         const ProtocolInterface::ServerInfo& server = *i;
92                         if (InspIRCd::Match(server.servername, sasl_target))
93                         {
94                                 online = true;
95                                 break;
96                         }
97                 }
98         }
99
100         bool IsOnline() const { return online; }
101 };
102
103 class SASLCap : public Cap::Capability
104 {
105         std::string mechlist;
106         const ServerTracker& servertracker;
107
108         bool OnRequest(LocalUser* user, bool adding) CXX11_OVERRIDE
109         {
110                 // Servers MUST NAK any sasl capability request if the authentication layer
111                 // is unavailable.
112                 return servertracker.IsOnline();
113         }
114
115         bool OnList(LocalUser* user) CXX11_OVERRIDE
116         {
117                 // Servers MUST NOT advertise the sasl capability if the authentication layer
118                 // is unavailable.
119                 return servertracker.IsOnline();
120         }
121
122         const std::string* GetValue(LocalUser* user) const CXX11_OVERRIDE
123         {
124                 return &mechlist;
125         }
126
127  public:
128         SASLCap(Module* mod, const ServerTracker& tracker)
129                 : Cap::Capability(mod, "sasl")
130                 , servertracker(tracker)
131         {
132         }
133
134         void SetMechlist(const std::string& newmechlist)
135         {
136                 if (mechlist == newmechlist)
137                         return;
138
139                 mechlist = newmechlist;
140                 NotifyValueChange();
141         }
142 };
143
144 enum SaslState { SASL_INIT, SASL_COMM, SASL_DONE };
145 enum SaslResult { SASL_OK, SASL_FAIL, SASL_ABORT };
146
147 static Events::ModuleEventProvider* saslevprov;
148
149 static void SendSASL(LocalUser* user, const std::string& agent, char mode, const std::vector<std::string>& parameters)
150 {
151         CommandBase::Params params;
152         params.push_back(user->uuid);
153         params.push_back(agent);
154         params.push_back(ConvToStr(mode));
155         params.insert(params.end(), parameters.begin(), parameters.end());
156
157         if (!ServerInstance->PI->SendEncapsulatedData(sasl_target, "SASL", params))
158         {
159                 FOREACH_MOD_CUSTOM(*saslevprov, SASLEventListener, OnSASLAuth, (params));
160         }
161 }
162
163 static ClientProtocol::EventProvider* g_protoev;
164
165 /**
166  * Tracks SASL authentication state like charybdis does. --nenolod
167  */
168 class SaslAuthenticator
169 {
170  private:
171         std::string agent;
172         LocalUser* user;
173         SaslState state;
174         SaslResult result;
175         bool state_announced;
176
177         void SendHostIP(UserCertificateAPI& sslapi)
178         {
179                 std::vector<std::string> params;
180                 params.push_back(user->GetRealHost());
181                 params.push_back(user->GetIPString());
182                 params.push_back(sslapi && sslapi->GetCertificate(user) ? "S" : "P");
183
184                 SendSASL(user, "*", 'H', params);
185         }
186
187  public:
188         SaslAuthenticator(LocalUser* user_, const std::string& method, UserCertificateAPI& sslapi)
189                 : user(user_)
190                 , state(SASL_INIT)
191                 , state_announced(false)
192         {
193                 SendHostIP(sslapi);
194
195                 std::vector<std::string> params;
196                 params.push_back(method);
197
198                 const std::string fp = sslapi ? sslapi->GetFingerprint(user) : "";
199                 if (fp.size())
200                         params.push_back(fp);
201
202                 SendSASL(user, "*", 'S', params);
203         }
204
205         SaslResult GetSaslResult(const std::string &result_)
206         {
207                 if (result_ == "F")
208                         return SASL_FAIL;
209
210                 if (result_ == "A")
211                         return SASL_ABORT;
212
213                 return SASL_OK;
214         }
215
216         /* checks for and deals with a state change. */
217         SaslState ProcessInboundMessage(const CommandBase::Params& msg)
218         {
219                 switch (this->state)
220                 {
221                  case SASL_INIT:
222                         this->agent = msg[0];
223                         this->state = SASL_COMM;
224                         /* fall through */
225                  case SASL_COMM:
226                         if (msg[0] != this->agent)
227                                 return this->state;
228
229                         if (msg.size() < 4)
230                                 return this->state;
231
232                         if (msg[2] == "C")
233                         {
234                                 ClientProtocol::Message authmsg("AUTHENTICATE");
235                                 authmsg.PushParamRef(msg[3]);
236
237                                 ClientProtocol::Event authevent(*g_protoev, authmsg);
238                                 LocalUser* const localuser = IS_LOCAL(user);
239                                 if (localuser)
240                                         localuser->Send(authevent);
241                         }
242                         else if (msg[2] == "D")
243                         {
244                                 this->state = SASL_DONE;
245                                 this->result = this->GetSaslResult(msg[3]);
246                         }
247                         else if (msg[2] == "M")
248                                 this->user->WriteNumeric(RPL_SASLMECHS, msg[3], "are available SASL mechanisms");
249                         else
250                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Services sent an unknown SASL message \"%s\" \"%s\"", msg[2].c_str(), msg[3].c_str());
251
252                         break;
253                  case SASL_DONE:
254                         break;
255                  default:
256                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WTF: SaslState is not a known state (%d)", this->state);
257                         break;
258                 }
259
260                 return this->state;
261         }
262
263         bool SendClientMessage(const std::vector<std::string>& parameters)
264         {
265                 if (this->state != SASL_COMM)
266                         return true;
267
268                 SendSASL(this->user, this->agent, 'C', parameters);
269
270                 if (parameters[0].c_str()[0] == '*')
271                 {
272                         this->state = SASL_DONE;
273                         this->result = SASL_ABORT;
274                         return false;
275                 }
276
277                 return true;
278         }
279
280         void AnnounceState(void)
281         {
282                 if (this->state_announced)
283                         return;
284
285                 switch (this->result)
286                 {
287                  case SASL_OK:
288                         this->user->WriteNumeric(RPL_SASLSUCCESS, "SASL authentication successful");
289                         break;
290                  case SASL_ABORT:
291                         this->user->WriteNumeric(ERR_SASLABORTED, "SASL authentication aborted");
292                         break;
293                  case SASL_FAIL:
294                         this->user->WriteNumeric(ERR_SASLFAIL, "SASL authentication failed");
295                         break;
296                  default:
297                         break;
298                 }
299
300                 this->state_announced = true;
301         }
302 };
303
304 class CommandAuthenticate : public SplitCommand
305 {
306  private:
307          // The maximum length of an AUTHENTICATE request.
308          static const size_t MAX_AUTHENTICATE_SIZE = 400;
309
310  public:
311         SimpleExtItem<SaslAuthenticator>& authExt;
312         Cap::Capability& cap;
313         UserCertificateAPI sslapi;
314
315         CommandAuthenticate(Module* Creator, SimpleExtItem<SaslAuthenticator>& ext, Cap::Capability& Cap)
316                 : SplitCommand(Creator, "AUTHENTICATE", 1)
317                 , authExt(ext)
318                 , cap(Cap)
319                 , sslapi(Creator)
320         {
321                 works_before_reg = true;
322                 allow_empty_last_param = false;
323         }
324
325         CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
326         {
327                 {
328                         if (!cap.get(user))
329                                 return CMD_FAILURE;
330
331                         if (parameters[0].find(' ') != std::string::npos || parameters[0][0] == ':')
332                                 return CMD_FAILURE;
333
334                         if (parameters[0].length() > MAX_AUTHENTICATE_SIZE)
335                         {
336                                 user->WriteNumeric(ERR_SASLTOOLONG, "SASL message too long");
337                                 return CMD_FAILURE;
338                         }
339
340                         SaslAuthenticator *sasl = authExt.get(user);
341                         if (!sasl)
342                                 authExt.set(user, new SaslAuthenticator(user, parameters[0], sslapi));
343                         else if (sasl->SendClientMessage(parameters) == false)  // IAL abort extension --nenolod
344                         {
345                                 sasl->AnnounceState();
346                                 authExt.unset(user);
347                         }
348                 }
349                 return CMD_FAILURE;
350         }
351 };
352
353 class CommandSASL : public Command
354 {
355  public:
356         SimpleExtItem<SaslAuthenticator>& authExt;
357         CommandSASL(Module* Creator, SimpleExtItem<SaslAuthenticator>& ext) : Command(Creator, "SASL", 2), authExt(ext)
358         {
359                 this->flags_needed = FLAG_SERVERONLY; // should not be called by users
360         }
361
362         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE
363         {
364                 User* target = ServerInstance->FindUUID(parameters[1]);
365                 if (!target)
366                 {
367                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User not found in sasl ENCAP event: %s", parameters[1].c_str());
368                         return CMD_FAILURE;
369                 }
370
371                 SaslAuthenticator *sasl = authExt.get(target);
372                 if (!sasl)
373                         return CMD_FAILURE;
374
375                 SaslState state = sasl->ProcessInboundMessage(parameters);
376                 if (state == SASL_DONE)
377                 {
378                         sasl->AnnounceState();
379                         authExt.unset(target);
380                 }
381                 return CMD_SUCCESS;
382         }
383
384         RouteDescriptor GetRouting(User* user, const Params& parameters) CXX11_OVERRIDE
385         {
386                 return ROUTE_BROADCAST;
387         }
388 };
389
390 class ModuleSASL : public Module
391 {
392         SimpleExtItem<SaslAuthenticator> authExt;
393         ServerTracker servertracker;
394         SASLCap cap;
395         CommandAuthenticate auth;
396         CommandSASL sasl;
397         Events::ModuleEventProvider sasleventprov;
398         ClientProtocol::EventProvider protoev;
399
400  public:
401         ModuleSASL()
402                 : authExt("sasl_auth", ExtensionItem::EXT_USER, this)
403                 , servertracker(this)
404                 , cap(this, servertracker)
405                 , auth(this, authExt, cap)
406                 , sasl(this, authExt)
407                 , sasleventprov(this, "event/sasl")
408                 , protoev(this, auth.name)
409         {
410                 saslevprov = &sasleventprov;
411                 g_protoev = &protoev;
412         }
413
414         void init() CXX11_OVERRIDE
415         {
416                 if (!ServerInstance->Modules->Find("m_services_account.so") || !ServerInstance->Modules->Find("m_cap.so"))
417                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: m_services_account and m_cap are not loaded! m_sasl will NOT function correctly until these two modules are loaded!");
418         }
419
420         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
421         {
422                 std::string target = ServerInstance->Config->ConfValue("sasl")->getString("target");
423                 if (target.empty())
424                         throw ModuleException("<sasl:target> must be set to the name of your services server!");
425
426                 sasl_target = target;
427                 servertracker.Reset();
428         }
429
430         void OnDecodeMetaData(Extensible* target, const std::string& extname, const std::string& extdata) CXX11_OVERRIDE
431         {
432                 if ((target == NULL) && (extname == "saslmechlist"))
433                         cap.SetMechlist(extdata);
434         }
435
436         Version GetVersion() CXX11_OVERRIDE
437         {
438                 return Version("Provides support for IRC Authentication Layer (aka: SASL) via AUTHENTICATE", VF_VENDOR);
439         }
440 };
441
442 MODULE_INIT(ModuleSASL)