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