-local starttls_attr = { xmlns = xmlns_starttls };
-module:add_event_hook("stream-features",
- function (session, features)
- if session.conn.starttls then
- features:tag("starttls", starttls_attr);
- if secure_auth_only then
- features:tag("required"):up():up();
- else
- features:up();
- end
- end
- end);
+ ssl_config = get_ssl_cfg("s2s");
+ ssl_ctx_s2sin, err = create_context(host.host, "server", ssl_config); -- for incoming server connections
+ ssl_ctx_s2sout = create_context(host.host, "client", ssl_config); -- for outgoing server connections
+ if err then module:log("error", "Error creating context for s2s: %s", err); end -- Both would have the same issue
+end
+
+local function can_do_tls(session)
+ if not session.conn.starttls then
+ return false;
+ elseif session.ssl_ctx then
+ return true;
+ end
+ if session.type == "c2s_unauthed" then
+ session.ssl_ctx = ssl_ctx_c2s;
+ elseif session.type == "s2sin_unauthed" and allow_s2s_tls then
+ session.ssl_ctx = ssl_ctx_s2sin;
+ elseif session.direction == "outgoing" and allow_s2s_tls then
+ session.ssl_ctx = ssl_ctx_s2sout;
+ else
+ return false;
+ end
+ return session.ssl_ctx;
+end
+
+-- Hook <starttls/>
+module:hook("stanza/urn:ietf:params:xml:ns:xmpp-tls:starttls", function(event)
+ local origin = event.origin;
+ if can_do_tls(origin) then
+ (origin.sends2s or origin.send)(starttls_proceed);
+ origin:reset_stream();
+ origin.conn:starttls(origin.ssl_ctx);
+ origin.log("debug", "TLS negotiation started for %s...", origin.type);
+ origin.secure = false;
+ else
+ origin.log("warn", "Attempt to start TLS, but TLS is not available on this %s connection", origin.type);
+ (origin.sends2s or origin.send)(starttls_failure);
+ origin:close();
+ end
+ return true;
+end);