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