]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_sasl.cpp
Move the <disabled> tag out of the core to a new 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 : public ServerEventListener
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                 : ServerEventListener(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 std::vector<std::string>& parameters)
147 {
148         CommandBase::Params params;
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 static ClientProtocol::EventProvider* g_protoev;
161
162 /**
163  * Tracks SASL authentication state like charybdis does. --nenolod
164  */
165 class SaslAuthenticator
166 {
167  private:
168         std::string agent;
169         LocalUser* user;
170         SaslState state;
171         SaslResult result;
172         bool state_announced;
173
174         void SendHostIP(UserCertificateAPI& sslapi)
175         {
176                 std::vector<std::string> params;
177                 params.push_back(user->GetRealHost());
178                 params.push_back(user->GetIPString());
179                 params.push_back(sslapi && sslapi->GetCertificate(user) ? "S" : "P");
180
181                 SendSASL(user, "*", 'H', params);
182         }
183
184  public:
185         SaslAuthenticator(LocalUser* user_, const std::string& method, UserCertificateAPI& sslapi)
186                 : user(user_)
187                 , state(SASL_INIT)
188                 , state_announced(false)
189         {
190                 SendHostIP(sslapi);
191
192                 std::vector<std::string> params;
193                 params.push_back(method);
194
195                 const std::string fp = sslapi ? sslapi->GetFingerprint(user) : "";
196                 if (fp.size())
197                         params.push_back(fp);
198
199                 SendSASL(user, "*", 'S', params);
200         }
201
202         SaslResult GetSaslResult(const std::string &result_)
203         {
204                 if (result_ == "F")
205                         return SASL_FAIL;
206
207                 if (result_ == "A")
208                         return SASL_ABORT;
209
210                 return SASL_OK;
211         }
212
213         /* checks for and deals with a state change. */
214         SaslState ProcessInboundMessage(const CommandBase::Params& msg)
215         {
216                 switch (this->state)
217                 {
218                  case SASL_INIT:
219                         this->agent = msg[0];
220                         this->state = SASL_COMM;
221                         /* fall through */
222                  case SASL_COMM:
223                         if (msg[0] != this->agent)
224                                 return this->state;
225
226                         if (msg.size() < 4)
227                                 return this->state;
228
229                         if (msg[2] == "C")
230                         {
231                                 ClientProtocol::Message authmsg("AUTHENTICATE");
232                                 authmsg.PushParamRef(msg[3]);
233
234                                 ClientProtocol::Event authevent(*g_protoev, authmsg);
235                                 LocalUser* const localuser = IS_LOCAL(user);
236                                 if (localuser)
237                                         localuser->Send(authevent);
238                         }
239                         else if (msg[2] == "D")
240                         {
241                                 this->state = SASL_DONE;
242                                 this->result = this->GetSaslResult(msg[3]);
243                         }
244                         else if (msg[2] == "M")
245                                 this->user->WriteNumeric(RPL_SASLMECHS, msg[3], "are available SASL mechanisms");
246                         else
247                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Services sent an unknown SASL message \"%s\" \"%s\"", msg[2].c_str(), msg[3].c_str());
248
249                         break;
250                  case SASL_DONE:
251                         break;
252                  default:
253                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WTF: SaslState is not a known state (%d)", this->state);
254                         break;
255                 }
256
257                 return this->state;
258         }
259
260         bool SendClientMessage(const std::vector<std::string>& parameters)
261         {
262                 if (this->state != SASL_COMM)
263                         return true;
264
265                 SendSASL(this->user, this->agent, 'C', parameters);
266
267                 if (parameters[0].c_str()[0] == '*')
268                 {
269                         this->state = SASL_DONE;
270                         this->result = SASL_ABORT;
271                         return false;
272                 }
273
274                 return true;
275         }
276
277         void AnnounceState(void)
278         {
279                 if (this->state_announced)
280                         return;
281
282                 switch (this->result)
283                 {
284                  case SASL_OK:
285                         this->user->WriteNumeric(RPL_SASLSUCCESS, "SASL authentication successful");
286                         break;
287                  case SASL_ABORT:
288                         this->user->WriteNumeric(ERR_SASLABORTED, "SASL authentication aborted");
289                         break;
290                  case SASL_FAIL:
291                         this->user->WriteNumeric(ERR_SASLFAIL, "SASL authentication failed");
292                         break;
293                  default:
294                         break;
295                 }
296
297                 this->state_announced = true;
298         }
299 };
300
301 class CommandAuthenticate : public SplitCommand
302 {
303  private:
304          // The maximum length of an AUTHENTICATE request.
305          static const size_t MAX_AUTHENTICATE_SIZE = 400;
306
307  public:
308         SimpleExtItem<SaslAuthenticator>& authExt;
309         Cap::Capability& cap;
310         UserCertificateAPI sslapi;
311
312         CommandAuthenticate(Module* Creator, SimpleExtItem<SaslAuthenticator>& ext, Cap::Capability& Cap)
313                 : SplitCommand(Creator, "AUTHENTICATE", 1)
314                 , authExt(ext)
315                 , cap(Cap)
316                 , sslapi(Creator)
317         {
318                 works_before_reg = true;
319                 allow_empty_last_param = false;
320         }
321
322         CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
323         {
324                 {
325                         if (!cap.get(user))
326                                 return CMD_FAILURE;
327
328                         if (parameters[0].find(' ') != std::string::npos || parameters[0][0] == ':')
329                                 return CMD_FAILURE;
330
331                         if (parameters[0].length() > MAX_AUTHENTICATE_SIZE)
332                         {
333                                 user->WriteNumeric(ERR_SASLTOOLONG, "SASL message too long");
334                                 return CMD_FAILURE;
335                         }
336
337                         SaslAuthenticator *sasl = authExt.get(user);
338                         if (!sasl)
339                                 authExt.set(user, new SaslAuthenticator(user, parameters[0], sslapi));
340                         else if (sasl->SendClientMessage(parameters) == false)  // IAL abort extension --nenolod
341                         {
342                                 sasl->AnnounceState();
343                                 authExt.unset(user);
344                         }
345                 }
346                 return CMD_FAILURE;
347         }
348 };
349
350 class CommandSASL : public Command
351 {
352  public:
353         SimpleExtItem<SaslAuthenticator>& authExt;
354         CommandSASL(Module* Creator, SimpleExtItem<SaslAuthenticator>& ext) : Command(Creator, "SASL", 2), authExt(ext)
355         {
356                 this->flags_needed = FLAG_SERVERONLY; // should not be called by users
357         }
358
359         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE
360         {
361                 User* target = ServerInstance->FindUUID(parameters[1]);
362                 if (!target)
363                 {
364                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User not found in sasl ENCAP event: %s", parameters[1].c_str());
365                         return CMD_FAILURE;
366                 }
367
368                 SaslAuthenticator *sasl = authExt.get(target);
369                 if (!sasl)
370                         return CMD_FAILURE;
371
372                 SaslState state = sasl->ProcessInboundMessage(parameters);
373                 if (state == SASL_DONE)
374                 {
375                         sasl->AnnounceState();
376                         authExt.unset(target);
377                 }
378                 return CMD_SUCCESS;
379         }
380
381         RouteDescriptor GetRouting(User* user, const Params& parameters) CXX11_OVERRIDE
382         {
383                 return ROUTE_BROADCAST;
384         }
385 };
386
387 class ModuleSASL : public Module
388 {
389         SimpleExtItem<SaslAuthenticator> authExt;
390         ServerTracker servertracker;
391         SASLCap cap;
392         CommandAuthenticate auth;
393         CommandSASL sasl;
394         Events::ModuleEventProvider sasleventprov;
395         ClientProtocol::EventProvider protoev;
396
397  public:
398         ModuleSASL()
399                 : authExt("sasl_auth", ExtensionItem::EXT_USER, this)
400                 , servertracker(this)
401                 , cap(this, servertracker)
402                 , auth(this, authExt, cap)
403                 , sasl(this, authExt)
404                 , sasleventprov(this, "event/sasl")
405                 , protoev(this, auth.name)
406         {
407                 saslevprov = &sasleventprov;
408                 g_protoev = &protoev;
409         }
410
411         void init() CXX11_OVERRIDE
412         {
413                 if (!ServerInstance->Modules->Find("m_services_account.so") || !ServerInstance->Modules->Find("m_cap.so"))
414                         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!");
415         }
416
417         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
418         {
419                 std::string target = ServerInstance->Config->ConfValue("sasl")->getString("target");
420                 if (target.empty())
421                         throw ModuleException("<sasl:target> must be set to the name of your services server!");
422
423                 sasl_target = target;
424                 servertracker.Reset();
425         }
426
427         void OnDecodeMetaData(Extensible* target, const std::string& extname, const std::string& extdata) CXX11_OVERRIDE
428         {
429                 if ((target == NULL) && (extname == "saslmechlist"))
430                         cap.SetMechlist(extdata);
431         }
432
433         Version GetVersion() CXX11_OVERRIDE
434         {
435                 return Version("Provides support for IRC Authentication Layer (aka: SASL) via AUTHENTICATE.", VF_VENDOR);
436         }
437 };
438
439 MODULE_INIT(ModuleSASL)