mod_saslauth: Fire authentication-failure if make_authenticated() failed.
[prosody.git] / plugins / mod_saslauth.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10
11 local st = require "util.stanza";
12 local sm_bind_resource = require "core.sessionmanager".bind_resource;
13 local sm_make_authenticated = require "core.sessionmanager".make_authenticated;
14 local s2s_make_authenticated = require "core.s2smanager".make_authenticated;
15 local base64 = require "util.encodings".base64;
16
17 local cert_verify_identity = require "util.x509".verify_identity;
18
19 local nodeprep = require "util.encodings".stringprep.nodeprep;
20 local usermanager_get_sasl_handler = require "core.usermanager".get_sasl_handler;
21 local tostring = tostring;
22
23 local secure_auth_only = module:get_option("c2s_require_encryption") or module:get_option("require_encryption");
24 local allow_unencrypted_plain_auth = module:get_option("allow_unencrypted_plain_auth")
25
26 local log = module._log;
27
28 local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl';
29 local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind';
30 local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
31
32 local function build_reply(status, ret, err_msg)
33         local reply = st.stanza(status, {xmlns = xmlns_sasl});
34         if status == "challenge" then
35                 --log("debug", "CHALLENGE: %s", ret or "");
36                 reply:text(base64.encode(ret or ""));
37         elseif status == "failure" then
38                 reply:tag(ret):up();
39                 if err_msg then reply:tag("text"):text(err_msg); end
40         elseif status == "success" then
41                 --log("debug", "SUCCESS: %s", ret or "");
42                 reply:text(base64.encode(ret or ""));
43         else
44                 module:log("error", "Unknown sasl status: %s", status);
45         end
46         return reply;
47 end
48
49 local function handle_status(session, status, ret, err_msg)
50         if status == "failure" then
51                 module:fire_event("authentication-failure", { session = session, condition = ret, text = err_msg });
52                 session.sasl_handler = session.sasl_handler:clean_clone();
53         elseif status == "success" then
54                 local username = nodeprep(session.sasl_handler.username);
55
56                 local ok, err = sm_make_authenticated(session, session.sasl_handler.username);
57                 if ok then
58                         module:fire_event("authentication-success", { session = session });
59                         session.sasl_handler = nil;
60                         session:reset_stream();
61                 else
62                         module:log("warn", "SASL succeeded but username was invalid");
63                         module:fire_event("authentication-failure", { session = session, condition = "not-authorized", text = err });
64                         session.sasl_handler = session.sasl_handler:clean_clone();
65                         return "failure", "not-authorized", "User authenticated successfully, but username was invalid";
66                 end
67         end
68         return status, ret, err_msg;
69 end
70
71 local function sasl_process_cdata(session, stanza)
72         local text = stanza[1];
73         if text then
74                 text = base64.decode(text);
75                 --log("debug", "AUTH: %s", text:gsub("[%z\001-\008\011\012\014-\031]", " "));
76                 if not text then
77                         session.sasl_handler = nil;
78                         session.send(build_reply("failure", "incorrect-encoding"));
79                         return true;
80                 end
81         end
82         local status, ret, err_msg = session.sasl_handler:process(text);
83         status, ret, err_msg = handle_status(session, status, ret, err_msg);
84         local s = build_reply(status, ret, err_msg);
85         log("debug", "sasl reply: %s", tostring(s));
86         session.send(s);
87         return true;
88 end
89
90 module:hook_stanza(xmlns_sasl, "success", function (session, stanza)
91         if session.type ~= "s2sout_unauthed" or session.external_auth ~= "attempting" then return; end
92         module:log("debug", "SASL EXTERNAL with %s succeeded", session.to_host);
93         session.external_auth = "succeeded"
94         session:reset_stream();
95
96         local default_stream_attr = {xmlns = "jabber:server", ["xmlns:stream"] = "http://etherx.jabber.org/streams",
97                                     ["xmlns:db"] = 'jabber:server:dialback', version = "1.0", to = session.to_host, from = session.from_host};
98         session.sends2s("<?xml version='1.0'?>");
99         session.sends2s(st.stanza("stream:stream", default_stream_attr):top_tag());
100
101         s2s_make_authenticated(session, session.to_host);
102         return true;
103 end)
104
105 module:hook_stanza(xmlns_sasl, "failure", function (session, stanza)
106         if session.type ~= "s2sout_unauthed" or session.external_auth ~= "attempting" then return; end
107
108         module:log("info", "SASL EXTERNAL with %s failed", session.to_host)
109         -- TODO: Log the failure reason
110         session.external_auth = "failed"
111 end, 500)
112
113 module:hook_stanza(xmlns_sasl, "failure", function (session, stanza)
114         -- TODO: Dialback wasn't loaded.  Do something useful.
115 end, 90)
116
117 module:hook_stanza("http://etherx.jabber.org/streams", "features", function (session, stanza)
118         if session.type ~= "s2sout_unauthed" or not session.secure then return; end
119
120         local mechanisms = stanza:get_child("mechanisms", xmlns_sasl)
121         if mechanisms then
122                 for mech in mechanisms:childtags() do
123                         if mech[1] == "EXTERNAL" then
124                                 module:log("debug", "Initiating SASL EXTERNAL with %s", session.to_host);
125                                 local reply = st.stanza("auth", {xmlns = xmlns_sasl, mechanism = "EXTERNAL"});
126                                 reply:text(base64.encode(session.from_host))
127                                 session.sends2s(reply)
128                                 session.external_auth = "attempting"
129                                 return true
130                         end
131                 end
132         end
133 end, 150);
134
135 local function s2s_external_auth(session, stanza)
136         local mechanism = stanza.attr.mechanism;
137
138         if not session.secure then
139                 if mechanism == "EXTERNAL" then
140                         session.sends2s(build_reply("failure", "encryption-required"))
141                 else
142                         session.sends2s(build_reply("failure", "invalid-mechanism"))
143                 end
144                 return true;
145         end
146
147         if mechanism ~= "EXTERNAL" or session.cert_chain_status ~= "valid" then
148                 session.sends2s(build_reply("failure", "invalid-mechanism"))
149                 return true;
150         end
151
152         local text = stanza[1]
153         if not text then
154                 session.sends2s(build_reply("failure", "malformed-request"))
155                 return true
156         end
157
158         -- Either the value is "=" and we've already verified the external
159         -- cert identity, or the value is a string and either matches the
160         -- from_host (
161
162         text = base64.decode(text)
163         if not text then
164                 session.sends2s(build_reply("failure", "incorrect-encoding"))
165                 return true;
166         end
167
168         if session.cert_identity_status == "valid" then
169                 if text ~= "" and text ~= session.from_host then
170                         session.sends2s(build_reply("failure", "invalid-authzid"))
171                         return true
172                 end
173         else
174                 if text == "" then
175                         session.sends2s(build_reply("failure", "invalid-authzid"))
176                         return true
177                 end
178
179                 local cert = session.conn:socket():getpeercertificate()
180                 if (cert_verify_identity(text, "xmpp-server", cert)) then
181                         session.cert_identity_status = "valid"
182                 else
183                         session.cert_identity_status = "invalid"
184                         session.sends2s(build_reply("failure", "invalid-authzid"))
185                         return true
186                 end
187         end
188
189         session.external_auth = "succeeded"
190
191         if not session.from_host then
192                 session.from_host = text;
193         end
194         session.sends2s(build_reply("success"))
195
196         local domain = text ~= "" and text or session.from_host;
197         module:log("info", "Accepting SASL EXTERNAL identity from %s", domain);
198         s2s_make_authenticated(session, domain);
199         session:reset_stream();
200         return true
201 end
202
203 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:auth", function(event)
204         local session, stanza = event.origin, event.stanza;
205         if session.type == "s2sin_unauthed" then
206                 return s2s_external_auth(session, stanza)
207         end
208
209         if session.type ~= "c2s_unauthed" then return; end
210
211         if session.sasl_handler and session.sasl_handler.selected then
212                 session.sasl_handler = nil; -- allow starting a new SASL negotiation before completing an old one
213         end
214         if not session.sasl_handler then
215                 session.sasl_handler = usermanager_get_sasl_handler(module.host);
216         end
217         local mechanism = stanza.attr.mechanism;
218         if not session.secure and (secure_auth_only or (mechanism == "PLAIN" and not allow_unencrypted_plain_auth)) then
219                 session.send(build_reply("failure", "encryption-required"));
220                 return true;
221         end
222         local valid_mechanism = session.sasl_handler:select(mechanism);
223         if not valid_mechanism then
224                 session.send(build_reply("failure", "invalid-mechanism"));
225                 return true;
226         end
227         return sasl_process_cdata(session, stanza);
228 end);
229 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:response", function(event)
230         local session = event.origin;
231         if not(session.sasl_handler and session.sasl_handler.selected) then
232                 session.send(build_reply("failure", "not-authorized", "Out of order SASL element"));
233                 return true;
234         end
235         return sasl_process_cdata(session, event.stanza);
236 end);
237 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:abort", function(event)
238         local session = event.origin;
239         session.sasl_handler = nil;
240         session.send(build_reply("failure", "aborted"));
241         return true;
242 end);
243
244 local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' };
245 local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' };
246 local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' };
247 module:hook("stream-features", function(event)
248         local origin, features = event.origin, event.features;
249         if not origin.username then
250                 if secure_auth_only and not origin.secure then
251                         return;
252                 end
253                 origin.sasl_handler = usermanager_get_sasl_handler(module.host);
254                 local mechanisms = st.stanza("mechanisms", mechanisms_attr);
255                 for mechanism in pairs(origin.sasl_handler:mechanisms()) do
256                         if mechanism ~= "PLAIN" or origin.secure or allow_unencrypted_plain_auth then
257                                 mechanisms:tag("mechanism"):text(mechanism):up();
258                         end
259                 end
260                 if mechanisms[1] then features:add_child(mechanisms); end
261         else
262                 features:tag("bind", bind_attr):tag("required"):up():up();
263                 features:tag("session", xmpp_session_attr):tag("optional"):up():up();
264         end
265 end);
266
267 module:hook("s2s-stream-features", function(event)
268         local origin, features = event.origin, event.features;
269         if origin.secure and origin.type == "s2sin_unauthed" then
270                 -- Offer EXTERNAL if chain is valid and either we didn't validate
271                 -- the identity or it passed.
272                 if origin.cert_chain_status == "valid" and origin.cert_identity_status ~= "invalid" then --TODO: Configurable
273                         module:log("debug", "Offering SASL EXTERNAL")
274                         features:tag("mechanisms", { xmlns = xmlns_sasl })
275                                 :tag("mechanism"):text("EXTERNAL")
276                         :up():up();
277                 end
278         end
279 end);
280
281 module:hook("iq/self/urn:ietf:params:xml:ns:xmpp-bind:bind", function(event)
282         local origin, stanza = event.origin, event.stanza;
283         local resource;
284         if stanza.attr.type == "set" then
285                 local bind = stanza.tags[1];
286                 resource = bind:child_with_name("resource");
287                 resource = resource and #resource.tags == 0 and resource[1] or nil;
288         end
289         local success, err_type, err, err_msg = sm_bind_resource(origin, resource);
290         if success then
291                 origin.send(st.reply(stanza)
292                         :tag("bind", { xmlns = xmlns_bind })
293                         :tag("jid"):text(origin.full_jid));
294                 origin.log("debug", "Resource bound: %s", origin.full_jid);
295         else
296                 origin.send(st.error_reply(stanza, err_type, err, err_msg));
297                 origin.log("debug", "Resource bind failed: %s", err_msg or err);
298         end
299         return true;
300 end);
301
302 local function handle_legacy_session(event)
303         event.origin.send(st.reply(event.stanza));
304         return true;
305 end
306
307 module:hook("iq/self/urn:ietf:params:xml:ns:xmpp-session:session", handle_legacy_session);
308 module:hook("iq/host/urn:ietf:params:xml:ns:xmpp-session:session", handle_legacy_session);