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