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