net.dns: Support for resolving AAAA records
[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                 session.sasl_handler = session.sasl_handler:clean_clone();
52         elseif status == "success" then
53                 local username = nodeprep(session.sasl_handler.username);
54
55                 local ok, err = sm_make_authenticated(session, session.sasl_handler.username);
56                 if ok then
57                         session.sasl_handler = nil;
58                         session:reset_stream();
59                 else
60                         module:log("warn", "SASL succeeded but username was invalid");
61                         session.sasl_handler = session.sasl_handler:clean_clone();
62                         return "failure", "not-authorized", "User authenticated successfully, but username was invalid";
63                 end
64         end
65         return status, ret, err_msg;
66 end
67
68 local function sasl_process_cdata(session, stanza)
69         local text = stanza[1];
70         if text then
71                 text = base64.decode(text);
72                 --log("debug", "AUTH: %s", text:gsub("[%z\001-\008\011\012\014-\031]", " "));
73                 if not text then
74                         session.sasl_handler = nil;
75                         session.send(build_reply("failure", "incorrect-encoding"));
76                         return true;
77                 end
78         end
79         local status, ret, err_msg = session.sasl_handler:process(text);
80         status, ret, err_msg = handle_status(session, status, ret, err_msg);
81         local s = build_reply(status, ret, err_msg);
82         log("debug", "sasl reply: %s", tostring(s));
83         session.send(s);
84         return true;
85 end
86
87 module:hook_stanza(xmlns_sasl, "success", function (session, stanza)
88         if session.type ~= "s2sout_unauthed" or session.external_auth ~= "attempting" then return; end
89         module:log("debug", "SASL EXTERNAL with %s succeeded", session.to_host);
90         session.external_auth = "succeeded"
91         session:reset_stream();
92
93         local default_stream_attr = {xmlns = "jabber:server", ["xmlns:stream"] = "http://etherx.jabber.org/streams",
94                                     ["xmlns:db"] = 'jabber:server:dialback', version = "1.0", to = session.to_host, from = session.from_host};
95         session.sends2s("<?xml version='1.0'?>");
96         session.sends2s(st.stanza("stream:stream", default_stream_attr):top_tag());
97
98         s2s_make_authenticated(session, session.to_host);
99         return true;
100 end)
101
102 module:hook_stanza(xmlns_sasl, "failure", function (session, stanza)
103         if session.type ~= "s2sout_unauthed" or session.external_auth ~= "attempting" then return; end
104
105         module:log("info", "SASL EXTERNAL with %s failed", session.to_host)
106         -- TODO: Log the failure reason
107         session.external_auth = "failed"
108 end, 500)
109
110 module:hook_stanza(xmlns_sasl, "failure", function (session, stanza)
111         -- TODO: Dialback wasn't loaded.  Do something useful.
112 end, 90)
113
114 module:hook_stanza("http://etherx.jabber.org/streams", "features", function (session, stanza)
115         if session.type ~= "s2sout_unauthed" or not session.secure then return; end
116
117         local mechanisms = stanza:get_child("mechanisms", xmlns_sasl)
118         if mechanisms then
119                 for mech in mechanisms:childtags() do
120                         if mech[1] == "EXTERNAL" then
121                                 module:log("debug", "Initiating SASL EXTERNAL with %s", session.to_host);
122                                 local reply = st.stanza("auth", {xmlns = xmlns_sasl, mechanism = "EXTERNAL"});
123                                 reply:text(base64.encode(session.from_host))
124                                 session.sends2s(reply)
125                                 session.external_auth = "attempting"
126                                 return true
127                         end
128                 end
129         end
130 end, 150);
131
132 local function s2s_external_auth(session, stanza)
133         local mechanism = stanza.attr.mechanism;
134
135         if not session.secure then
136                 if mechanism == "EXTERNAL" then
137                         session.sends2s(build_reply("failure", "encryption-required"))
138                 else
139                         session.sends2s(build_reply("failure", "invalid-mechanism"))
140                 end
141                 return true;
142         end
143
144         if mechanism ~= "EXTERNAL" or session.cert_chain_status ~= "valid" then
145                 session.sends2s(build_reply("failure", "invalid-mechanism"))
146                 return true;
147         end
148
149         local text = stanza[1]
150         if not text then
151                 session.sends2s(build_reply("failure", "malformed-request"))
152                 return true
153         end
154
155         -- Either the value is "=" and we've already verified the external
156         -- cert identity, or the value is a string and either matches the
157         -- from_host (
158
159         text = base64.decode(text)
160         if not text then
161                 session.sends2s(build_reply("failure", "incorrect-encoding"))
162                 return true;
163         end
164
165         if session.cert_identity_status == "valid" then
166                 if text ~= "" and text ~= session.from_host then
167                         session.sends2s(build_reply("failure", "invalid-authzid"))
168                         return true
169                 end
170         else
171                 if text == "" then
172                         session.sends2s(build_reply("failure", "invalid-authzid"))
173                         return true
174                 end
175
176                 local cert = session.conn:socket():getpeercertificate()
177                 if (cert_verify_identity(text, "xmpp-server", cert)) then
178                         session.cert_identity_status = "valid"
179                 else
180                         session.cert_identity_status = "invalid"
181                         session.sends2s(build_reply("failure", "invalid-authzid"))
182                         return true
183                 end
184         end
185
186         session.external_auth = "succeeded"
187
188         if not session.from_host then
189                 session.from_host = text;
190         end
191         session.sends2s(build_reply("success"))
192         module:log("info", "Accepting SASL EXTERNAL identity from %s", text or session.from_host);
193         s2s_make_authenticated(session, text or session.from_host)
194         session:reset_stream();
195         return true
196 end
197
198 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:auth", function(event)
199         local session, stanza = event.origin, event.stanza;
200         if session.type == "s2sin_unauthed" then
201                 return s2s_external_auth(session, stanza)
202         end
203
204         if session.type ~= "c2s_unauthed" then return; end
205
206         if session.sasl_handler and session.sasl_handler.selected then
207                 session.sasl_handler = nil; -- allow starting a new SASL negotiation before completing an old one
208         end
209         if not session.sasl_handler then
210                 session.sasl_handler = usermanager_get_sasl_handler(module.host);
211         end
212         local mechanism = stanza.attr.mechanism;
213         if not session.secure and (secure_auth_only or (mechanism == "PLAIN" and not allow_unencrypted_plain_auth)) then
214                 session.send(build_reply("failure", "encryption-required"));
215                 return true;
216         end
217         local valid_mechanism = session.sasl_handler:select(mechanism);
218         if not valid_mechanism then
219                 session.send(build_reply("failure", "invalid-mechanism"));
220                 return true;
221         end
222         return sasl_process_cdata(session, stanza);
223 end);
224 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:response", function(event)
225         local session = event.origin;
226         if not(session.sasl_handler and session.sasl_handler.selected) then
227                 session.send(build_reply("failure", "not-authorized", "Out of order SASL element"));
228                 return true;
229         end
230         return sasl_process_cdata(session, event.stanza);
231 end);
232 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:abort", function(event)
233         local session = event.origin;
234         session.sasl_handler = nil;
235         session.send(build_reply("failure", "aborted"));
236         return true;
237 end);
238
239 local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' };
240 local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' };
241 local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' };
242 module:hook("stream-features", function(event)
243         local origin, features = event.origin, event.features;
244         if not origin.username then
245                 if secure_auth_only and not origin.secure then
246                         return;
247                 end
248                 origin.sasl_handler = usermanager_get_sasl_handler(module.host);
249                 features:tag("mechanisms", mechanisms_attr);
250                 for mechanism in pairs(origin.sasl_handler:mechanisms()) do
251                         if mechanism ~= "PLAIN" or origin.secure or allow_unencrypted_plain_auth then
252                                 features:tag("mechanism"):text(mechanism):up();
253                         end
254                 end
255                 features:up();
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 if chain is valid and either we didn't validate
266                 -- the identity or it passed.
267                 if origin.cert_chain_status == "valid" and origin.cert_identity_status ~= "invalid" then --TODO: Configurable
268                         module:log("debug", "Offering SASL EXTERNAL")
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:child_with_name("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);