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