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