Merge 0.10->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 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_boolean("c2s_require_encryption", module:get_option_boolean("require_encryption", false));
20 local allow_unencrypted_plain_auth = module:get_option_boolean("allow_unencrypted_plain_auth", false)
21 local insecure_mechanisms = module:get_option_set("insecure_sasl_mechanisms", allow_unencrypted_plain_auth and {} or {"PLAIN", "LOGIN"});
22 local disabled_mechanisms = module:get_option_set("disable_sasl_mechanisms", { "DIGEST-MD5" });
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 == "failure" then
32                 reply:tag(ret):up();
33                 if err_msg then reply:tag("text"):text(err_msg); end
34         elseif status == "challenge" or status == "success" then
35                 if ret == "" then
36                         reply:text("=")
37                 elseif ret then
38                         reply:text(base64.encode(ret));
39                 end
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         if session.external_auth ~= "offered" then return end -- Unexpected request
126
127         local mechanism = stanza.attr.mechanism;
128
129         if mechanism ~= "EXTERNAL" then
130                 session.sends2s(build_reply("failure", "invalid-mechanism"));
131                 return true;
132         end
133
134         if not session.secure then
135                 session.sends2s(build_reply("failure", "encryption-required"));
136                 return true;
137         end
138
139         local text = stanza[1];
140         if not text then
141                 session.sends2s(build_reply("failure", "malformed-request"));
142                 return true;
143         end
144
145         text = base64.decode(text);
146         if not text then
147                 session.sends2s(build_reply("failure", "incorrect-encoding"));
148                 return true;
149         end
150
151         -- The text value is either "" or equals session.from_host
152         if not ( text == "" or text == session.from_host ) then
153                 session.sends2s(build_reply("failure", "invalid-authzid"));
154                 return true;
155         end
156
157         -- We've already verified the external cert identity before offering EXTERNAL
158         if session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid" then
159                 session.sends2s(build_reply("failure", "not-authorized"));
160                 session:close();
161                 return true;
162         end
163
164         -- Success!
165         session.external_auth = "succeeded";
166         session.sends2s(build_reply("success"));
167         module:log("info", "Accepting SASL EXTERNAL identity from %s", session.from_host);
168         module:fire_event("s2s-authenticated", { session = session, host = session.from_host });
169         session:reset_stream();
170         return true;
171 end
172
173 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:auth", function(event)
174         local session, stanza = event.origin, event.stanza;
175         if session.type == "s2sin_unauthed" then
176                 return s2s_external_auth(session, stanza)
177         end
178
179         if session.type ~= "c2s_unauthed" or module:get_host_type() ~= "local" then return; end
180
181         if session.sasl_handler and session.sasl_handler.selected then
182                 session.sasl_handler = nil; -- allow starting a new SASL negotiation before completing an old one
183         end
184         if not session.sasl_handler then
185                 session.sasl_handler = usermanager_get_sasl_handler(module.host, session);
186         end
187         local mechanism = stanza.attr.mechanism;
188         if not session.secure and (secure_auth_only or insecure_mechanisms:contains(mechanism)) then
189                 session.send(build_reply("failure", "encryption-required"));
190                 return true;
191         elseif disabled_mechanisms:contains(mechanism) then
192                 session.send(build_reply("failure", "invalid-mechanism"));
193                 return true;
194         end
195         local valid_mechanism = session.sasl_handler:select(mechanism);
196         if not valid_mechanism then
197                 session.send(build_reply("failure", "invalid-mechanism"));
198                 return true;
199         end
200         return sasl_process_cdata(session, stanza);
201 end);
202 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:response", function(event)
203         local session = event.origin;
204         if not(session.sasl_handler and session.sasl_handler.selected) then
205                 session.send(build_reply("failure", "not-authorized", "Out of order SASL element"));
206                 return true;
207         end
208         return sasl_process_cdata(session, event.stanza);
209 end);
210 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:abort", function(event)
211         local session = event.origin;
212         session.sasl_handler = nil;
213         session.send(build_reply("failure", "aborted"));
214         return true;
215 end);
216
217 local function tls_unique(self)
218         return self.userdata["tls-unique"]:getpeerfinished();
219 end
220
221 local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' };
222 local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' };
223 local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' };
224 module:hook("stream-features", function(event)
225         local origin, features = event.origin, event.features;
226         if not origin.username then
227                 if secure_auth_only and not origin.secure then
228                         return;
229                 end
230                 local sasl_handler = usermanager_get_sasl_handler(module.host, origin)
231                 origin.sasl_handler = sasl_handler;
232                 if origin.encrypted then
233                         -- check wether LuaSec has the nifty binding to the function needed for tls-unique
234                         -- FIXME: would be nice to have this check only once and not for every socket
235                         if sasl_handler.add_cb_handler then
236                                 local socket = origin.conn:socket();
237                                 if socket.getpeerfinished then
238                                         sasl_handler:add_cb_handler("tls-unique", tls_unique);
239                                 end
240                                 sasl_handler["userdata"] = {
241                                         ["tls-unique"] = socket;
242                                 };
243                         end
244                 end
245                 local mechanisms = st.stanza("mechanisms", mechanisms_attr);
246                 for mechanism in pairs(sasl_handler:mechanisms()) do
247                         if (not disabled_mechanisms:contains(mechanism)) and (origin.secure or not insecure_mechanisms:contains(mechanism)) then
248                                 mechanisms:tag("mechanism"):text(mechanism):up();
249                         end
250                 end
251                 if mechanisms[1] then
252                         features:add_child(mechanisms);
253                 else
254                         (origin.log or log)("warn", "No SASL mechanisms to offer");
255                 end
256         else
257                 features:tag("bind", bind_attr):tag("required"):up():up();
258                 features:tag("session", xmpp_session_attr):tag("optional"):up():up();
259         end
260 end);
261
262 module:hook("s2s-stream-features", function(event)
263         local origin, features = event.origin, event.features;
264         if origin.secure and origin.type == "s2sin_unauthed" then
265                 -- Offer EXTERNAL only if both chain and identity is valid.
266                 if origin.cert_chain_status == "valid" and origin.cert_identity_status == "valid" then
267                         module:log("debug", "Offering SASL EXTERNAL");
268                         origin.external_auth = "offered"
269                         features:tag("mechanisms", { xmlns = xmlns_sasl })
270                                 :tag("mechanism"):text("EXTERNAL")
271                         :up():up();
272                 end
273         end
274 end);
275
276 module:hook("iq/self/urn:ietf:params:xml:ns:xmpp-bind:bind", function(event)
277         local origin, stanza = event.origin, event.stanza;
278         local resource;
279         if stanza.attr.type == "set" then
280                 local bind = stanza.tags[1];
281                 resource = bind:get_child("resource");
282                 resource = resource and #resource.tags == 0 and resource[1] or nil;
283         end
284         local success, err_type, err, err_msg = sm_bind_resource(origin, resource);
285         if success then
286                 origin.send(st.reply(stanza)
287                         :tag("bind", { xmlns = xmlns_bind })
288                         :tag("jid"):text(origin.full_jid));
289                 origin.log("debug", "Resource bound: %s", origin.full_jid);
290         else
291                 origin.send(st.error_reply(stanza, err_type, err, err_msg));
292                 origin.log("debug", "Resource bind failed: %s", err_msg or err);
293         end
294         return true;
295 end);
296
297 local function handle_legacy_session(event)
298         event.origin.send(st.reply(event.stanza));
299         return true;
300 end
301
302 module:hook("iq/self/urn:ietf:params:xml:ns:xmpp-session:session", handle_legacy_session);
303 module:hook("iq/host/urn:ietf:params:xml:ns:xmpp-session:session", handle_legacy_session);