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