512c903772e55c523dce78bf6eedadd1f3f937da
[prosody.git] / plugins / mod_s2s / mod_s2s.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 module:set_global();
10
11 local prosody = prosody;
12 local hosts = prosody.hosts;
13 local core_process_stanza = prosody.core_process_stanza;
14
15 local tostring, type = tostring, type;
16 local t_insert = table.insert;
17 local xpcall, traceback = xpcall, debug.traceback;
18
19 local add_task = require "util.timer".add_task;
20 local st = require "util.stanza";
21 local initialize_filters = require "util.filters".initialize;
22 local nameprep = require "util.encodings".stringprep.nameprep;
23 local new_xmpp_stream = require "util.xmppstream".new;
24 local s2s_new_incoming = require "core.s2smanager".new_incoming;
25 local s2s_new_outgoing = require "core.s2smanager".new_outgoing;
26 local s2s_destroy_session = require "core.s2smanager".destroy_session;
27 local uuid_gen = require "util.uuid".generate;
28 local cert_verify_identity = require "util.x509".verify_identity;
29 local fire_global_event = prosody.events.fire_event;
30
31 local s2sout = module:require("s2sout");
32
33 local connect_timeout = module:get_option_number("s2s_timeout", 90);
34 local stream_close_timeout = module:get_option_number("s2s_close_timeout", 5);
35
36 local secure_auth = module:get_option_boolean("s2s_secure_auth", false); -- One day...
37 local secure_domains, insecure_domains =
38         module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items;
39 local require_encryption = module:get_option_boolean("s2s_require_encryption", secure_auth);
40
41 local sessions = module:shared("sessions");
42
43 local log = module._log;
44
45 --- Handle stanzas to remote domains
46
47 local bouncy_stanzas = { message = true, presence = true, iq = true };
48 local function bounce_sendq(session, reason)
49         local sendq = session.sendq;
50         if not sendq then return; end
51         session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
52         local dummy = {
53                 type = "s2sin";
54                 send = function(s)
55                         (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", traceback());
56                 end;
57                 dummy = true;
58         };
59         for i, data in ipairs(sendq) do
60                 local reply = data[2];
61                 if reply and not(reply.attr.xmlns) and bouncy_stanzas[reply.name] then
62                         reply.attr.type = "error";
63                         reply:tag("error", {type = "cancel"})
64                                 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
65                         if reason then
66                                 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"})
67                                         :text("Server-to-server connection failed: "..reason):up();
68                         end
69                         core_process_stanza(dummy, reply);
70                 end
71                 sendq[i] = nil;
72         end
73         session.sendq = nil;
74 end
75
76 -- Handles stanzas to existing s2s sessions
77 function route_to_existing_session(event)
78         local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
79         if not hosts[from_host] then
80                 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
81                 return false;
82         end
83         local host = hosts[from_host].s2sout[to_host];
84         if host then
85                 -- We have a connection to this host already
86                 if host.type == "s2sout_unauthed" and (stanza.name ~= "db:verify" or not host.dialback_key) then
87                         (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
88
89                         -- Queue stanza until we are able to send it
90                         if host.sendq then t_insert(host.sendq, {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)});
91                         else host.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} }; end
92                         host.log("debug", "stanza [%s] queued ", stanza.name);
93                         return true;
94                 elseif host.type == "local" or host.type == "component" then
95                         log("error", "Trying to send a stanza to ourselves??")
96                         log("error", "Traceback: %s", traceback());
97                         log("error", "Stanza: %s", tostring(stanza));
98                         return false;
99                 else
100                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
101                         -- FIXME
102                         if host.from_host ~= from_host then
103                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
104                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
105                         end
106                         if host.sends2s(stanza) then
107                                 host.log("debug", "stanza sent over %s", host.type);
108                                 return true;
109                         end
110                 end
111         end
112 end
113
114 -- Create a new outgoing session for a stanza
115 function route_to_new_session(event)
116         local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
117         log("debug", "opening a new outgoing connection for this stanza");
118         local host_session = s2s_new_outgoing(from_host, to_host);
119
120         -- Store in buffer
121         host_session.bounce_sendq = bounce_sendq;
122         host_session.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} };
123         log("debug", "stanza [%s] queued until connection complete", tostring(stanza.name));
124         s2sout.initiate_connection(host_session);
125         if (not host_session.connecting) and (not host_session.conn) then
126                 log("warn", "Connection to %s failed already, destroying session...", to_host);
127                 s2s_destroy_session(host_session, "Connection failed");
128                 return false;
129         end
130         return true;
131 end
132
133 function module.add_host(module)
134         if module:get_option_boolean("disallow_s2s", false) then
135                 module:log("warn", "The 'disallow_s2s' config option is deprecated, please see http://prosody.im/doc/s2s#disabling");
136                 return nil, "This host has disallow_s2s set";
137         end
138         module:hook("route/remote", route_to_existing_session, 200);
139         module:hook("route/remote", route_to_new_session, 100);
140         module:hook("s2s-authenticated", make_authenticated, -1);
141 end
142
143 -- Stream is authorised, and ready for normal stanzas
144 function mark_connected(session)
145         local sendq, send = session.sendq, session.sends2s;
146         
147         local from, to = session.from_host, session.to_host;
148         
149         session.log("info", "%s s2s connection %s->%s complete", session.direction, from, to);
150
151         local event_data = { session = session };
152         if session.type == "s2sout" then
153                 fire_global_event("s2sout-established", event_data);
154                 hosts[from].events.fire_event("s2sout-established", event_data);
155         else
156                 local host_session = hosts[to];
157                 session.send = function(stanza)
158                         return host_session.events.fire_event("route/remote", { from_host = to, to_host = from, stanza = stanza });
159                 end;
160
161                 fire_global_event("s2sin-established", event_data);
162                 hosts[to].events.fire_event("s2sin-established", event_data);
163         end
164         
165         if session.direction == "outgoing" then
166                 if sendq then
167                         session.log("debug", "sending %d queued stanzas across new outgoing connection to %s", #sendq, session.to_host);
168                         for i, data in ipairs(sendq) do
169                                 send(data[1]);
170                                 sendq[i] = nil;
171                         end
172                         session.sendq = nil;
173                 end
174                 
175                 session.ip_hosts = nil;
176                 session.srv_hosts = nil;
177         end
178 end
179
180 function make_authenticated(event)
181         local session, host = event.session, event.host;
182         if not session.secure then
183                 if require_encryption or secure_auth or secure_domains[host] then
184                         session:close({
185                                 condition = "policy-violation",
186                                 text = "Encrypted server-to-server communication is required but was not "
187                                        ..((session.direction == "outgoing" and "offered") or "used")
188                         });
189                 end
190         end
191         if session.type == "s2sout_unauthed" then
192                 session.type = "s2sout";
193         elseif session.type == "s2sin_unauthed" then
194                 session.type = "s2sin";
195                 if host then
196                         if not session.hosts[host] then session.hosts[host] = {}; end
197                         session.hosts[host].authed = true;
198                 end
199         elseif session.type == "s2sin" and host then
200                 if not session.hosts[host] then session.hosts[host] = {}; end
201                 session.hosts[host].authed = true;
202         else
203                 return false;
204         end
205         session.log("debug", "connection %s->%s is now authenticated for %s", session.from_host, session.to_host, host);
206         
207         mark_connected(session);
208         
209         return true;
210 end
211
212 --- Helper to check that a session peer's certificate is valid
213 local function check_cert_status(session)
214         local host = session.direction == "incoming" and session.from_host or session.to_host
215         local conn = session.conn:socket()
216         local cert
217         if conn.getpeercertificate then
218                 cert = conn:getpeercertificate()
219         end
220
221         if cert then
222                 local chain_valid, errors = conn:getpeerverification()
223                 -- Is there any interest in printing out all/the number of errors here?
224                 if not chain_valid then
225                         (session.log or log)("debug", "certificate chain validation result: invalid");
226                         for depth, t in ipairs(errors) do
227                                 (session.log or log)("debug", "certificate error(s) at depth %d: %s", depth-1, table.concat(t, ", "))
228                         end
229                         session.cert_chain_status = "invalid";
230                 else
231                         (session.log or log)("debug", "certificate chain validation result: valid");
232                         session.cert_chain_status = "valid";
233
234                         -- We'll go ahead and verify the asserted identity if the
235                         -- connecting server specified one.
236                         if host then
237                                 if cert_verify_identity(host, "xmpp-server", cert) then
238                                         session.cert_identity_status = "valid"
239                                 else
240                                         session.cert_identity_status = "invalid"
241                                 end
242                         end
243                 end
244         end
245         return module:fire_event("s2s-check-certificate", { host = host, session = session, cert = cert });
246 end
247
248 --- XMPP stream event handlers
249
250 local stream_callbacks = { default_ns = "jabber:server", handlestanza =  core_process_stanza };
251
252 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
253
254 function stream_callbacks.streamopened(session, attr)
255         local send = session.sends2s;
256         
257         session.version = tonumber(attr.version) or 0;
258         
259         -- TODO: Rename session.secure to session.encrypted
260         if session.secure == false then
261                 session.secure = true;
262
263                 -- Check if TLS compression is used
264                 local sock = session.conn:socket();
265                 if sock.info then
266                         session.compressed = sock:info"compression";
267                 elseif sock.compression then
268                         session.compressed = sock:compression(); --COMPAT mw/luasec-hg
269                 end
270         end
271
272         if session.direction == "incoming" then
273                 -- Send a reply stream header
274                 
275                 -- Validate to/from
276                 local to, from = nameprep(attr.to), nameprep(attr.from);
277                 if not to and attr.to then -- COMPAT: Some servers do not reliably set 'to' (especially on stream restarts)
278                         session:close({ condition = "improper-addressing", text = "Invalid 'to' address" });
279                         return;
280                 end
281                 if not from and attr.from then -- COMPAT: Some servers do not reliably set 'from' (especially on stream restarts)
282                         session:close({ condition = "improper-addressing", text = "Invalid 'from' address" });
283                         return;
284                 end
285                 
286                 -- Set session.[from/to]_host if they have not been set already and if
287                 -- this session isn't already authenticated
288                 if session.type == "s2sin_unauthed" and from and not session.from_host then
289                         session.from_host = from;
290                 elseif from ~= session.from_host then
291                         session:close({ condition = "improper-addressing", text = "New stream 'from' attribute does not match original" });
292                         return;
293                 end
294                 if session.type == "s2sin_unauthed" and to and not session.to_host then
295                         session.to_host = to;
296                 elseif to ~= session.to_host then
297                         session:close({ condition = "improper-addressing", text = "New stream 'to' attribute does not match original" });
298                         return;
299                 end
300                 
301                 -- For convenience we'll put the sanitised values into these variables
302                 to, from = session.to_host, session.from_host;
303                 
304                 session.streamid = uuid_gen();
305                 (session.log or log)("debug", "Incoming s2s received %s", st.stanza("stream:stream", attr):top_tag());
306                 if to then
307                         if not hosts[to] then
308                                 -- Attempting to connect to a host we don't serve
309                                 session:close({
310                                         condition = "host-unknown";
311                                         text = "This host does not serve "..to
312                                 });
313                                 return;
314                         elseif not hosts[to].modules.s2s then
315                                 -- Attempting to connect to a host that disallows s2s
316                                 session:close({
317                                         condition = "policy-violation";
318                                         text = "Server-to-server communication is disabled for this host";
319                                 });
320                                 return;
321                         end
322                 end
323
324                 if session.secure and not session.cert_chain_status then
325                         if check_cert_status(session) == false then
326                                 return;
327                         end
328                 end
329
330                 session:open_stream()
331                 if session.version >= 1.0 then
332                         local features = st.stanza("stream:features");
333                         
334                         if to then
335                                 hosts[to].events.fire_event("s2s-stream-features", { origin = session, features = features });
336                         else
337                                 (session.log or log)("warn", "No 'to' on stream header from %s means we can't offer any features", from or "unknown host");
338                         end
339                         
340                         log("debug", "Sending stream features: %s", tostring(features));
341                         send(features);
342                 end
343         elseif session.direction == "outgoing" then
344                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
345                 if not attr.id then error("stream response did not give us a streamid!!!"); end
346                 session.streamid = attr.id;
347
348                 if session.secure and not session.cert_chain_status then
349                         if check_cert_status(session) == false then
350                                 return;
351                         end
352                 end
353
354                 -- Send unauthed buffer
355                 -- (stanzas which are fine to send before dialback)
356                 -- Note that this is *not* the stanza queue (which
357                 -- we can only send if auth succeeds) :)
358                 local send_buffer = session.send_buffer;
359                 if send_buffer and #send_buffer > 0 then
360                         log("debug", "Sending s2s send_buffer now...");
361                         for i, data in ipairs(send_buffer) do
362                                 session.sends2s(tostring(data));
363                                 send_buffer[i] = nil;
364                         end
365                 end
366                 session.send_buffer = nil;
367         
368                 -- If server is pre-1.0, don't wait for features, just do dialback
369                 if session.version < 1.0 then
370                         if not session.dialback_verifying then
371                                 hosts[session.from_host].events.fire_event("s2sout-authenticate-legacy", { origin = session });
372                         else
373                                 mark_connected(session);
374                         end
375                 end
376         end
377         session.notopen = nil;
378 end
379
380 function stream_callbacks.streamclosed(session)
381         (session.log or log)("debug", "Received </stream:stream>");
382         session:close(false);
383 end
384
385 function stream_callbacks.error(session, error, data)
386         if error == "no-stream" then
387                 session:close("invalid-namespace");
388         elseif error == "parse-error" then
389                 session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
390                 session:close("not-well-formed");
391         elseif error == "stream-error" then
392                 local condition, text = "undefined-condition";
393                 for child in data:children() do
394                         if child.attr.xmlns == xmlns_xmpp_streams then
395                                 if child.name ~= "text" then
396                                         condition = child.name;
397                                 else
398                                         text = child:get_text();
399                                 end
400                                 if condition ~= "undefined-condition" and text then
401                                         break;
402                                 end
403                         end
404                 end
405                 text = condition .. (text and (" ("..text..")") or "");
406                 session.log("info", "Session closed by remote with error: %s", text);
407                 session:close(nil, text);
408         end
409 end
410
411 local function handleerr(err) log("error", "Traceback[s2s]: %s: %s", tostring(err), traceback()); end
412 function stream_callbacks.handlestanza(session, stanza)
413         if stanza.attr.xmlns == "jabber:client" then --COMPAT: Prosody pre-0.6.2 may send jabber:client
414                 stanza.attr.xmlns = nil;
415         end
416         stanza = session.filter("stanzas/in", stanza);
417         if stanza then
418                 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
419         end
420 end
421
422 local listener = {};
423
424 --- Session methods
425 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
426 local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
427 local function session_close(session, reason, remote_reason)
428         local log = session.log or log;
429         if session.conn then
430                 if session.notopen then
431                         session:open_stream()
432                 end
433                 if reason then -- nil == no err, initiated by us, false == initiated by remote
434                         if type(reason) == "string" then -- assume stream error
435                                 log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, reason);
436                                 session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
437                         elseif type(reason) == "table" then
438                                 if reason.condition then
439                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
440                                         if reason.text then
441                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
442                                         end
443                                         if reason.extra then
444                                                 stanza:add_child(reason.extra);
445                                         end
446                                         log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, tostring(stanza));
447                                         session.sends2s(stanza);
448                                 elseif reason.name then -- a stanza
449                                         log("debug", "Disconnecting %s->%s[%s], <stream:error> is: %s", session.from_host or "(unknown host)", session.to_host or "(unknown host)", session.type, tostring(reason));
450                                         session.sends2s(reason);
451                                 end
452                         end
453                 end
454
455                 session.sends2s("</stream:stream>");
456                 function session.sends2s() return false; end
457                 
458                 local reason = remote_reason or (reason and (reason.text or reason.condition)) or reason;
459                 session.log("info", "%s s2s stream %s->%s closed: %s", session.direction, session.from_host or "(unknown host)", session.to_host or "(unknown host)", reason or "stream closed");
460                 
461                 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
462                 local conn = session.conn;
463                 if reason == nil and not session.notopen and session.type == "s2sin" then
464                         add_task(stream_close_timeout, function ()
465                                 if not session.destroyed then
466                                         session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
467                                         s2s_destroy_session(session, reason);
468                                         conn:close();
469                                 end
470                         end);
471                 else
472                         s2s_destroy_session(session, reason);
473                         conn:close(); -- Close immediately, as this is an outgoing connection or is not authed
474                 end
475         end
476 end
477
478 function session_open_stream(session, from, to)
479         local from = from or session.from_host;
480         local to = to or session.to_host;
481         local attr = {
482                 ["xmlns:stream"] = 'http://etherx.jabber.org/streams',
483                 xmlns = 'jabber:server',
484                 version = session.version and (session.version > 0 and "1.0" or nil),
485                 ["xml:lang"] = 'en',
486                 id = session.streamid,
487                 from = from, to = to,
488         }
489         local local_host = session.direction == "outgoing" and from or to;
490         if not local_host or hosts[local_host].modules.dialback then
491                 attr["xmlns:db"] = 'jabber:server:dialback';
492         end
493
494         session.sends2s("<?xml version='1.0'?>");
495         session.sends2s(st.stanza("stream:stream", attr):top_tag());
496         return true;
497 end
498
499 -- Session initialization logic shared by incoming and outgoing
500 local function initialize_session(session)
501         local stream = new_xmpp_stream(session, stream_callbacks);
502         session.stream = stream;
503         
504         session.notopen = true;
505                 
506         function session.reset_stream()
507                 session.notopen = true;
508                 session.stream:reset();
509         end
510
511         session.open_stream = session_open_stream;
512         
513         local filter = session.filter;
514         function session.data(data)
515                 data = filter("bytes/in", data);
516                 if data then
517                         local ok, err = stream:feed(data);
518                         if ok then return; end
519                         (session.log or log)("warn", "Received invalid XML: %s", data);
520                         (session.log or log)("warn", "Problem was: %s", err);
521                         session:close("not-well-formed");
522                 end
523         end
524
525         session.close = session_close;
526
527         local handlestanza = stream_callbacks.handlestanza;
528         function session.dispatch_stanza(session, stanza)
529                 return handlestanza(session, stanza);
530         end
531
532         add_task(connect_timeout, function ()
533                 if session.type == "s2sin" or session.type == "s2sout" then
534                         return; -- Ok, we're connected
535                 elseif session.type == "s2s_destroyed" then
536                         return; -- Session already destroyed
537                 end
538                 -- Not connected, need to close session and clean up
539                 (session.log or log)("debug", "Destroying incomplete session %s->%s due to inactivity",
540                 session.from_host or "(unknown)", session.to_host or "(unknown)");
541                 session:close("connection-timeout");
542         end);
543 end
544
545 function listener.onconnect(conn)
546         local session = sessions[conn];
547         if not session then -- New incoming connection
548                 session = s2s_new_incoming(conn);
549                 sessions[conn] = session;
550                 session.log("debug", "Incoming s2s connection");
551
552                 local filter = initialize_filters(session);
553                 local w = conn.write;
554                 session.sends2s = function (t)
555                         log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)"));
556                         if t.name then
557                                 t = filter("stanzas/out", t);
558                         end
559                         if t then
560                                 t = filter("bytes/out", tostring(t));
561                                 if t then
562                                         return w(conn, t);
563                                 end
564                         end
565                 end
566         
567                 initialize_session(session);
568         else -- Outgoing session connected
569                 session:open_stream(session.from_host, session.to_host);
570         end
571 end
572
573 function listener.onincoming(conn, data)
574         local session = sessions[conn];
575         if session then
576                 session.data(data);
577         end
578 end
579         
580 function listener.onstatus(conn, status)
581         if status == "ssl-handshake-complete" then
582                 local session = sessions[conn];
583                 if session and session.direction == "outgoing" then
584                         session.log("debug", "Sending stream header...");
585                         session:open_stream(session.from_host, session.to_host);
586                 end
587         end
588 end
589
590 function listener.ondisconnect(conn, err)
591         local session = sessions[conn];
592         if session then
593                 sessions[conn] = nil;
594                 if err and session.direction == "outgoing" and session.notopen then
595                         (session.log or log)("debug", "s2s connection attempt failed: %s", err);
596                         if s2sout.attempt_connection(session, err) then
597                                 (session.log or log)("debug", "...so we're going to try another target");
598                                 return; -- Session lives for now
599                         end
600                 end
601                 (session.log or log)("debug", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err or "connection closed"));
602                 s2s_destroy_session(session, err);
603         end
604 end
605
606 function listener.register_outgoing(conn, session)
607         session.direction = "outgoing";
608         sessions[conn] = session;
609         initialize_session(session);
610 end
611
612 function check_auth_policy(event)
613         local host, session = event.host, event.session;
614         
615         if not secure_auth and secure_domains[host] then
616                 secure_auth = true;
617         elseif secure_auth and insecure_domains[host] then
618                 secure_auth = false;
619         end
620         
621         if secure_auth and not session.cert_identity_status then
622                 module:log("warn", "Forbidding insecure connection to/from %s", host);
623                 session:close(false);
624                 return false;
625         end
626 end
627
628 module:hook("s2s-check-certificate", check_auth_policy, -1);
629
630 s2sout.set_listener(listener);
631
632 module:hook("server-stopping", function(event)
633         local reason = event.reason;
634         for _, session in pairs(sessions) do
635                 session:close{ condition = "system-shutdown", text = reason };
636         end
637 end,500);
638
639
640
641 module:provides("net", {
642         name = "s2s";
643         listener = listener;
644         default_port = 5269;
645         encryption = "starttls";
646         multiplex = {
647                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:server%1.*>";
648         };
649 });
650