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