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