2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
11 local prosody = prosody;
12 local hosts = prosody.hosts;
13 local core_process_stanza = prosody.core_process_stanza;
15 local tostring, type = tostring, type;
16 local t_insert = table.insert;
17 local xpcall, traceback = xpcall, debug.traceback;
20 local add_task = require "util.timer".add_task;
21 local st = require "util.stanza";
22 local initialize_filters = require "util.filters".initialize;
23 local nameprep = require "util.encodings".stringprep.nameprep;
24 local new_xmpp_stream = require "util.xmppstream".new;
25 local s2s_new_incoming = require "core.s2smanager".new_incoming;
26 local s2s_new_outgoing = require "core.s2smanager".new_outgoing;
27 local s2s_destroy_session = require "core.s2smanager".destroy_session;
28 local uuid_gen = require "util.uuid".generate;
29 local cert_verify_identity = require "util.x509".verify_identity;
30 local fire_global_event = prosody.events.fire_event;
32 local s2sout = module:require("s2sout");
34 local connect_timeout = module:get_option_number("s2s_timeout", 90);
35 local stream_close_timeout = module:get_option_number("s2s_close_timeout", 5);
36 local opt_keepalives = module:get_option_boolean("s2s_tcp_keepalives", module:get_option_boolean("tcp_keepalives", true));
37 local secure_auth = module:get_option_boolean("s2s_secure_auth", false); -- One day...
38 local secure_domains, insecure_domains =
39 module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items;
40 local require_encryption = module:get_option_boolean("s2s_require_encryption", false);
42 local sessions = module:shared("sessions");
44 local log = module._log;
46 --- Handle stanzas to remote domains
48 local bouncy_stanzas = { message = true, presence = true, iq = true };
49 local function bounce_sendq(session, reason)
50 local sendq = session.sendq;
51 if not sendq then return; end
52 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
56 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", traceback());
60 for i, data in ipairs(sendq) do
61 local reply = data[2];
62 if reply and not(reply.attr.xmlns) and bouncy_stanzas[reply.name] then
63 reply.attr.type = "error";
64 reply:tag("error", {type = "cancel"})
65 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
67 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"})
68 :text("Server-to-server connection failed: "..reason):up();
70 core_process_stanza(dummy, reply);
77 -- Handles stanzas to existing s2s sessions
78 function route_to_existing_session(event)
79 local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
80 if not hosts[from_host] then
81 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
84 if hosts[to_host] then
85 log("warn", "Attempt to route stanza to a remote %s - a host we do serve?!", from_host);
88 local host = hosts[from_host].s2sout[to_host];
90 -- We have a connection to this host already
91 if host.type == "s2sout_unauthed" and (stanza.name ~= "db:verify" or not host.dialback_key) then
92 (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
94 -- Queue stanza until we are able to send it
95 if host.sendq then t_insert(host.sendq, {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)});
96 else host.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} }; end
97 host.log("debug", "stanza [%s] queued ", stanza.name);
99 elseif host.type == "local" or host.type == "component" then
100 log("error", "Trying to send a stanza to ourselves??")
101 log("error", "Traceback: %s", traceback());
102 log("error", "Stanza: %s", tostring(stanza));
105 (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
107 if host.from_host ~= from_host then
108 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
109 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
111 if host.sends2s(stanza) then
112 host.log("debug", "stanza sent over %s", host.type);
119 -- Create a new outgoing session for a stanza
120 function route_to_new_session(event)
121 local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
122 log("debug", "opening a new outgoing connection for this stanza");
123 local host_session = s2s_new_outgoing(from_host, to_host);
126 host_session.bounce_sendq = bounce_sendq;
127 host_session.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} };
128 log("debug", "stanza [%s] queued until connection complete", tostring(stanza.name));
129 s2sout.initiate_connection(host_session);
130 if (not host_session.connecting) and (not host_session.conn) then
131 log("warn", "Connection to %s failed already, destroying session...", to_host);
132 s2s_destroy_session(host_session, "Connection failed");
138 local function keepalive(event)
139 return event.session.sends2s(' ');
142 module:hook("s2s-read-timeout", keepalive, -1);
144 function module.add_host(module)
145 if module:get_option_boolean("disallow_s2s", false) then
146 module:log("warn", "The 'disallow_s2s' config option is deprecated, please see http://prosody.im/doc/s2s#disabling");
147 return nil, "This host has disallow_s2s set";
149 module:hook("route/remote", route_to_existing_session, -1);
150 module:hook("route/remote", route_to_new_session, -10);
151 module:hook("s2s-authenticated", make_authenticated, -1);
152 module:hook("s2s-read-timeout", keepalive, -1);
153 module:hook_stanza("http://etherx.jabber.org/streams", "features", function (session, stanza)
154 if session.type == "s2sout" then
155 -- Stream is authenticated and we are seem to be done with feature negotiation,
156 -- so the stream is ready for stanzas. RFC 6120 Section 4.3
157 mark_connected(session);
162 -- Stream is authorised, and ready for normal stanzas
163 function mark_connected(session)
164 local sendq, send = session.sendq, session.sends2s;
166 local from, to = session.from_host, session.to_host;
168 session.log("info", "%s s2s connection %s->%s complete", session.direction:gsub("^.", string.upper), from, to);
170 local event_data = { session = session };
171 if session.type == "s2sout" then
172 fire_global_event("s2sout-established", event_data);
173 hosts[from].events.fire_event("s2sout-established", event_data);
175 local host_session = hosts[to];
176 session.send = function(stanza)
177 return host_session.events.fire_event("route/remote", { from_host = to, to_host = from, stanza = stanza });
180 fire_global_event("s2sin-established", event_data);
181 hosts[to].events.fire_event("s2sin-established", event_data);
184 if session.direction == "outgoing" then
186 session.log("debug", "sending %d queued stanzas across new outgoing connection to %s", #sendq, session.to_host);
187 for i, data in ipairs(sendq) do
194 session.ip_hosts = nil;
195 session.srv_hosts = nil;
199 function make_authenticated(event)
200 local session, host = event.session, event.host;
201 if not session.secure then
202 if require_encryption or (secure_auth and not(insecure_domains[host])) or secure_domains[host] then
204 condition = "policy-violation",
205 text = "Encrypted server-to-server communication is required but was not "
206 ..((session.direction == "outgoing" and "offered") or "used")
211 session:close({ condition = "undefined-condition", text = "Attempt to authenticate as a host we serve" });
213 if session.type == "s2sout_unauthed" then
214 session.type = "s2sout";
215 elseif session.type == "s2sin_unauthed" then
216 session.type = "s2sin";
218 if not session.hosts[host] then session.hosts[host] = {}; end
219 session.hosts[host].authed = true;
221 elseif session.type == "s2sin" and host then
222 if not session.hosts[host] then session.hosts[host] = {}; end
223 session.hosts[host].authed = true;
227 session.log("debug", "connection %s->%s is now authenticated for %s", session.from_host, session.to_host, host);
229 if (session.type == "s2sout" and session.external_auth ~= "succeeded") or session.type == "s2sin" then
230 -- Stream either used dialback for authentication or is an incoming stream.
231 mark_connected(session);
237 --- Helper to check that a session peer's certificate is valid
238 local function check_cert_status(session)
239 local host = session.direction == "outgoing" and session.to_host or session.from_host
240 local conn = session.conn:socket()
242 if conn.getpeercertificate then
243 cert = conn:getpeercertificate()
247 local chain_valid, errors;
248 if conn.getpeerverification then
249 chain_valid, errors = conn:getpeerverification();
250 elseif conn.getpeerchainvalid then -- COMPAT mw/luasec-hg
251 chain_valid, errors = conn:getpeerchainvalid();
252 errors = (not chain_valid) and { { errors } } or nil;
254 chain_valid, errors = false, { { "Chain verification not supported by this version of LuaSec" } };
256 -- Is there any interest in printing out all/the number of errors here?
257 if not chain_valid then
258 (session.log or log)("debug", "certificate chain validation result: invalid");
259 for depth, t in pairs(errors or NULL) do
260 (session.log or log)("debug", "certificate error(s) at depth %d: %s", depth-1, table.concat(t, ", "))
262 session.cert_chain_status = "invalid";
264 (session.log or log)("debug", "certificate chain validation result: valid");
265 session.cert_chain_status = "valid";
267 -- We'll go ahead and verify the asserted identity if the
268 -- connecting server specified one.
270 if cert_verify_identity(host, "xmpp-server", cert) then
271 session.cert_identity_status = "valid"
273 session.cert_identity_status = "invalid"
275 (session.log or log)("debug", "certificate identity validation result: %s", session.cert_identity_status);
279 return module:fire_event("s2s-check-certificate", { host = host, session = session, cert = cert });
282 --- XMPP stream event handlers
284 local stream_callbacks = { default_ns = "jabber:server", handlestanza = core_process_stanza };
286 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
288 function stream_callbacks.streamopened(session, attr)
289 local send = session.sends2s;
291 session.version = tonumber(attr.version) or 0;
293 -- TODO: Rename session.secure to session.encrypted
294 if session.secure == false then
295 session.secure = true;
296 session.encrypted = true;
298 local sock = session.conn:socket();
300 local info = sock:info();
301 (session.log or log)("info", "Stream encrypted (%s with %s)", info.protocol, info.cipher);
302 session.compressed = info.compression;
304 (session.log or log)("info", "Stream encrypted");
305 session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
309 if session.direction == "incoming" then
310 -- Send a reply stream header
313 local to, from = nameprep(attr.to), nameprep(attr.from);
314 if not to and attr.to then -- COMPAT: Some servers do not reliably set 'to' (especially on stream restarts)
315 session:close({ condition = "improper-addressing", text = "Invalid 'to' address" });
318 if not from and attr.from then -- COMPAT: Some servers do not reliably set 'from' (especially on stream restarts)
319 session:close({ condition = "improper-addressing", text = "Invalid 'from' address" });
323 -- Set session.[from/to]_host if they have not been set already and if
324 -- this session isn't already authenticated
325 if session.type == "s2sin_unauthed" and from and not session.from_host then
326 session.from_host = from;
327 elseif from ~= session.from_host then
328 session:close({ condition = "improper-addressing", text = "New stream 'from' attribute does not match original" });
331 if session.type == "s2sin_unauthed" and to and not session.to_host then
332 session.to_host = to;
333 elseif to ~= session.to_host then
334 session:close({ condition = "improper-addressing", text = "New stream 'to' attribute does not match original" });
338 -- For convenience we'll put the sanitised values into these variables
339 to, from = session.to_host, session.from_host;
341 session.streamid = uuid_gen();
342 (session.log or log)("debug", "Incoming s2s received %s", st.stanza("stream:stream", attr):top_tag());
344 if not hosts[to] then
345 -- Attempting to connect to a host we don't serve
347 condition = "host-unknown";
348 text = "This host does not serve "..to
351 elseif not hosts[to].modules.s2s then
352 -- Attempting to connect to a host that disallows s2s
354 condition = "policy-violation";
355 text = "Server-to-server communication is disabled for this host";
362 session:close({ condition = "undefined-condition", text = "Attempt to connect from a host we serve" });
366 if session.secure and not session.cert_chain_status then
367 if check_cert_status(session) == false then
372 session:open_stream(session.to_host, session.from_host)
373 if session.version >= 1.0 then
374 local features = st.stanza("stream:features");
377 hosts[to].events.fire_event("s2s-stream-features", { origin = session, features = features });
379 (session.log or log)("warn", "No 'to' on stream header from %s means we can't offer any features", from or session.ip or "unknown host");
382 log("debug", "Sending stream features: %s", tostring(features));
385 elseif session.direction == "outgoing" then
386 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
387 if not attr.id then error("stream response did not give us a streamid!!!"); end
388 session.streamid = attr.id;
390 if session.secure and not session.cert_chain_status then
391 if check_cert_status(session) == false then
396 -- Send unauthed buffer
397 -- (stanzas which are fine to send before dialback)
398 -- Note that this is *not* the stanza queue (which
399 -- we can only send if auth succeeds) :)
400 local send_buffer = session.send_buffer;
401 if send_buffer and #send_buffer > 0 then
402 log("debug", "Sending s2s send_buffer now...");
403 for i, data in ipairs(send_buffer) do
404 session.sends2s(tostring(data));
405 send_buffer[i] = nil;
408 session.send_buffer = nil;
410 -- If server is pre-1.0, don't wait for features, just do dialback
411 if session.version < 1.0 then
412 if not session.dialback_verifying then
413 hosts[session.from_host].events.fire_event("s2sout-authenticate-legacy", { origin = session });
415 mark_connected(session);
419 session.notopen = nil;
422 function stream_callbacks.streamclosed(session)
423 (session.log or log)("debug", "Received </stream:stream>");
424 session:close(false);
427 function stream_callbacks.error(session, error, data)
428 if error == "no-stream" then
429 session:close("invalid-namespace");
430 elseif error == "parse-error" then
431 session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
432 session:close("not-well-formed");
433 elseif error == "stream-error" then
434 local condition, text = "undefined-condition";
435 for child in data:children() do
436 if child.attr.xmlns == xmlns_xmpp_streams then
437 if child.name ~= "text" then
438 condition = child.name;
440 text = child:get_text();
442 if condition ~= "undefined-condition" and text then
447 text = condition .. (text and (" ("..text..")") or "");
448 session.log("info", "Session closed by remote with error: %s", text);
449 session:close(nil, text);
453 local function handleerr(err) log("error", "Traceback[s2s]: %s", traceback(tostring(err), 2)); end
454 function stream_callbacks.handlestanza(session, stanza)
455 if stanza.attr.xmlns == "jabber:client" then --COMPAT: Prosody pre-0.6.2 may send jabber:client
456 stanza.attr.xmlns = nil;
458 stanza = session.filter("stanzas/in", stanza);
460 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
467 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
468 local function session_close(session, reason, remote_reason)
469 local log = session.log or log;
471 if session.notopen then
472 if session.direction == "incoming" then
473 session:open_stream(session.to_host, session.from_host);
475 session:open_stream(session.from_host, session.to_host);
478 if reason then -- nil == no err, initiated by us, false == initiated by remote
479 if type(reason) == "string" then -- assume stream error
480 log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or session.ip or "(unknown host)", session.type, reason);
481 session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
482 elseif type(reason) == "table" then
483 if reason.condition then
484 local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
486 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
489 stanza:add_child(reason.extra);
491 log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or session.ip or "(unknown host)", session.type, tostring(stanza));
492 session.sends2s(stanza);
493 elseif reason.name then -- a stanza
494 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));
495 session.sends2s(reason);
500 session.sends2s("</stream:stream>");
501 function session.sends2s() return false; end
503 local reason = remote_reason or (reason and (reason.text or reason.condition)) or reason;
504 session.log("info", "%s s2s stream %s->%s closed: %s", session.direction:gsub("^.", string.upper), session.from_host or "(unknown host)", session.to_host or "(unknown host)", reason or "stream closed");
506 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
507 local conn = session.conn;
508 if reason == nil and not session.notopen and session.type == "s2sin" then
509 add_task(stream_close_timeout, function ()
510 if not session.destroyed then
511 session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
512 s2s_destroy_session(session, reason);
517 s2s_destroy_session(session, reason);
518 conn:close(); -- Close immediately, as this is an outgoing connection or is not authed
523 function session_stream_attrs(session, from, to, attr)
524 if not from or (hosts[from] and hosts[from].modules.dialback) then
525 attr["xmlns:db"] = 'jabber:server:dialback';
529 -- Session initialization logic shared by incoming and outgoing
530 local function initialize_session(session)
531 local stream = new_xmpp_stream(session, stream_callbacks);
532 local log = session.log or log;
533 session.stream = stream;
535 session.notopen = true;
537 function session.reset_stream()
538 session.notopen = true;
539 session.stream:reset();
542 session.stream_attrs = session_stream_attrs;
544 local filter = initialize_filters(session);
545 local conn = session.conn;
546 local w = conn.write;
548 function session.sends2s(t)
549 log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^[^>]*>?"));
551 t = filter("stanzas/out", t);
554 t = filter("bytes/out", tostring(t));
561 function session.data(data)
562 data = filter("bytes/in", data);
564 local ok, err = stream:feed(data);
565 if ok then return; end
566 log("warn", "Received invalid XML: %s", data);
567 log("warn", "Problem was: %s", err);
568 session:close("not-well-formed");
572 session.close = session_close;
574 local handlestanza = stream_callbacks.handlestanza;
575 function session.dispatch_stanza(session, stanza)
576 return handlestanza(session, stanza);
579 add_task(connect_timeout, function ()
580 if session.type == "s2sin" or session.type == "s2sout" then
581 return; -- Ok, we're connected
582 elseif session.type == "s2s_destroyed" then
583 return; -- Session already destroyed
585 -- Not connected, need to close session and clean up
586 (session.log or log)("debug", "Destroying incomplete session %s->%s due to inactivity",
587 session.from_host or "(unknown)", session.to_host or "(unknown)");
588 session:close("connection-timeout");
592 function listener.onconnect(conn)
593 conn:setoption("keepalive", opt_keepalives);
594 local session = sessions[conn];
595 if not session then -- New incoming connection
596 session = s2s_new_incoming(conn);
597 sessions[conn] = session;
598 session.log("debug", "Incoming s2s connection");
599 initialize_session(session);
600 else -- Outgoing session connected
601 session:open_stream(session.from_host, session.to_host);
603 session.ip = conn:ip();
606 function listener.onincoming(conn, data)
607 local session = sessions[conn];
613 function listener.onstatus(conn, status)
614 if status == "ssl-handshake-complete" then
615 local session = sessions[conn];
616 if session and session.direction == "outgoing" then
617 session.log("debug", "Sending stream header...");
618 session:open_stream(session.from_host, session.to_host);
623 function listener.ondisconnect(conn, err)
624 local session = sessions[conn];
626 sessions[conn] = nil;
627 if err and session.direction == "outgoing" and session.notopen then
628 (session.log or log)("debug", "s2s connection attempt failed: %s", err);
629 if s2sout.attempt_connection(session, err) then
630 return; -- Session lives for now
633 (session.log or log)("debug", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err or "connection closed"));
634 s2s_destroy_session(session, err);
638 function listener.onreadtimeout(conn)
639 local session = sessions[conn];
641 return (hosts[session.host] or prosody).events.fire_event("s2s-read-timeout", { session = session });
645 function listener.register_outgoing(conn, session)
646 sessions[conn] = session;
647 initialize_session(session);
650 function check_auth_policy(event)
651 local host, session = event.host, event.session;
652 local must_secure = secure_auth;
654 if not must_secure and secure_domains[host] then
656 elseif must_secure and insecure_domains[host] then
660 if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") then
661 module:log("warn", "Forbidding insecure connection to/from %s", host or session.ip or "(unknown host)");
662 if session.direction == "incoming" then
663 session:close({ condition = "not-authorized", text = "Your server's certificate is invalid, expired, or not trusted by "..session.to_host });
664 else -- Close outgoing connections without warning
665 session:close(false);
671 module:hook("s2s-check-certificate", check_auth_policy, -1);
673 s2sout.set_listener(listener);
675 module:hook("server-stopping", function(event)
676 local reason = event.reason;
677 for _, session in pairs(sessions) do
678 session:close{ condition = "system-shutdown", text = reason };
684 module:provides("net", {
688 encryption = "starttls";
690 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:server%1.*>";