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