Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat(prosody): test for escaped CRLF in rayo headers (#17583)
Aaron van Meertend03ae361cb02
diff --git a/resources/prosody-plugins/mod_filter_iq_rayo.lua b/resources/prosody-plugins/mod_filter_iq_rayo.luaindex e7c0984388..31457e18a8 100644--- a/resources/prosody-plugins/mod_filter_iq_rayo.lua+++ b/resources/prosody-plugins/mod_filter_iq_rayo.lua@@ -61,6 +61,15 @@ local function load_config()endload_config();+-- Normalise CR and LF in values sourced outside of XML (e.g. JWT claims) to+-- spaces before inserting them into stanza attributes. Prosody's util.stanza+-- serializer does not escape raw control characters, so this keeps the+-- forwarded attribute values consistent with how expat already normalises+-- whitespace in XML-attribute-sourced values.+local function sanitize_header_value(v)+ return (tostring(v):gsub("[\r\n]", " "));+end+-- Header names to use to push extra data extracted from token, if anylocal OUT_INITIATOR_USER_ATTR_NAME = "X-outbound-call-initiator-user";local OUT_INITIATOR_GROUP_ATTR_NAME = "X-outbound-call-initiator-group";@@ -159,7 +168,7 @@ module:hook("pre-iq/full", function(event)dial:tag("header", {xmlns = "urn:xmpp:rayo:1",name = OUT_INITIATOR_USER_ATTR_NAME,- value = tostring(user_id)});+ value = sanitize_header_value(user_id)});dial:up();-- Add the initiator group information if it is present@@ -167,7 +176,7 @@ module:hook("pre-iq/full", function(event)dial:tag("header", {xmlns = "urn:xmpp:rayo:1",name = OUT_INITIATOR_GROUP_ATTR_NAME,- value = tostring(session.jitsi_meet_context_group) });+ value = sanitize_header_value(session.jitsi_meet_context_group) });dial:up();endend@@ -179,14 +188,14 @@ module:hook("pre-iq/full", function(event)dial:tag("header", {xmlns = "urn:xmpp:rayo:1",name = OUT_ROOM_NAME_ATTR_NAME,- value = roomName+ value = sanitize_header_value(roomName)});dial:up();if roomPassword thendial:tag("header", {xmlns = "urn:xmpp:rayo:1",name = OUT_ROOM_PASS_ATTR_NAME,- value = roomPassword+ value = sanitize_header_value(roomPassword)});dial:up();enddiff --git a/resources/prosody-plugins/mod_test_observer.lua b/resources/prosody-plugins/mod_test_observer.luaindex 44d39af28e..2ad7281fa7 100644--- a/resources/prosody-plugins/mod_test_observer.lua+++ b/resources/prosody-plugins/mod_test_observer.lua@@ -81,6 +81,10 @@ module:hook("iq/full", function(event)room_name_header = headers["JvbRoomName"];room_pass_header = headers["JvbRoomPassword"];headers = headers;+ -- Raw serialized form of the stanza as util.stanza would write it+ -- to the wire. Used by JS tests to inspect the actual byte content+ -- of forwarded attributes.+ raw_xml = tostring(stanza);});endend, 500);diff --git a/tests/prosody/helpers/xmpp_client.js b/tests/prosody/helpers/xmpp_client.jsindex 982fb1fff8..a096fcbff5 100644--- a/tests/prosody/helpers/xmpp_client.js+++ b/tests/prosody/helpers/xmpp_client.js@@ -368,6 +368,66 @@ export async function createXmppClient({ host = 'localhost', domain, params, use);},+ /**+ * Like sendRayoIq but waits for Prosody's IQ response and returns it.+ * Use this when the test needs to inspect the reply stanza (e.g. to+ * assert that Prosody sent back an error rather than routing the IQ).+ *+ * Accepts the same options as sendRayoIq.+ *+ * @param {string} roomJid+ * @param {object} [opts]+ * @param {string} [opts.dialTo]+ * @param {string|null} [opts.roomNameHeader]+ * @param {string|null} [opts.roomPassHeader]+ * @param {object} [opts.extraHeaders]+ * @returns {Promise<object>} the response IQ stanza+ */+ sendRayoIqAndWait(roomJid, {+ dialTo = 'sip:[email protected]',+ roomNameHeader = roomJid,+ roomPassHeader = null,+ extraHeaders = {}+ } = {}) {+ const headers = [];++ if (roomNameHeader !== null) {+ headers.push(xml('header', {+ xmlns: 'urn:xmpp:rayo:1',+ name: 'JvbRoomName',+ value: roomNameHeader+ }));+ }++ if (roomPassHeader !== null) {+ headers.push(xml('header', {+ xmlns: 'urn:xmpp:rayo:1',+ name: 'JvbRoomPassword',+ value: roomPassHeader+ }));+ }++ for (const [ name, value ] of Object.entries(extraHeaders)) {+ headers.push(xml('header', {+ xmlns: 'urn:xmpp:rayo:1',+ name,+ value+ }));+ }++ return sendIq(xmpp, pendingIqs,+ xml('iq', { type: 'set',+ to: `${roomJid}/focus`,+ id: `rayo-${++_counter}` },+ xml('dial', {+ xmlns: 'urn:xmpp:rayo:1',+ to: dialTo,+ from: 'fromdomain'+ }, ...headers)+ )+ );+ },+/*** Sends a disco#info IQ and resolves with the response stanza.* @param {string} targetJiddiff --git a/tests/prosody/lua/rayo_dial_header_crlf_spec.lua b/tests/prosody/lua/rayo_dial_header_crlf_spec.luanew file mode 100644index 0000000000..5e0b80fdd5--- /dev/null+++ b/tests/prosody/lua/rayo_dial_header_crlf_spec.lua@@ -0,0 +1,165 @@+-- Unit test for Rayo dial IQ header serialization.+-- Run with busted from resources/prosody-plugins/:+-- busted spec/lua/+--+-- Purpose: a Rayo "dial" IQ (urn:xmpp:rayo:1) carries client-influenced header+-- values (e.g. JvbRoomName / JvbRoomPassword). If a header value contains a raw+-- carriage-return / line-feed, an unescaped serialization would let a client+-- inject extra lines into the XMPP stream — and, downstream, into the SIP+-- headers jigasi builds from these values (CRLF / header injection).+--+-- Prosody's util.stanza serializer neutralizes this by XML-escaping control+-- characters: "\r" -> " " and "\n" -> " ". This spec produces a dial IQ+-- with such a header and asserts the serialized stanza contains " " and+-- leaks no raw CR/LF bytes.+--+-- It uses Prosody's real util.stanza when it resolves on LUA_PATH; otherwise it+-- falls back to a small in-file serializer that mirrors Prosody's escape table,+-- so the contract is still asserted in CI (where Prosody is not installed).++local RAYO_NS = 'urn:xmpp:rayo:1';++-- ---------------------------------------------------------------------------+-- Obtain a stanza builder: prefer the real util.stanza, else a faithful stub.+-- ---------------------------------------------------------------------------++local st, source;++local ok_real, real = pcall(require, 'util.stanza');+if ok_real and type(real) == 'table' and real.iq then+ st = real;+ source = 'util.stanza (real Prosody)';+else+ source = 'in-file reference serializer';++ -- Mirrors Prosody's util.stanza escape table: control characters are+ -- escaped to numeric entities so they cannot break out of an attribute.+ local escape_table = {+ ["'"] = "'",+ ['"'] = """,+ ["<"] = "<",+ [">"] = ">",+ ["&"] = "&",+ ["\t"] = "	",+ ["\n"] = " ",+ ["\r"] = " ",+ };+ local function xml_escape(str)+ return (str:gsub("['&<>\"\t\n\r]", escape_table));+ end++ local stanza_mt = {};+ stanza_mt.__index = stanza_mt;++ local function new_stanza(name, attr)+ return setmetatable({+ name = name,+ attr = attr or {},+ tags = {},+ last_add = {},+ }, stanza_mt);+ end++ function stanza_mt:tag(name, attr)+ local child = new_stanza(name, attr);+ local parent = self.last_add[#self.last_add] or self;++ table.insert(parent.tags, child);+ table.insert(self.last_add, child);++ return self;+ end++ function stanza_mt:up()+ table.remove(self.last_add);++ return self;+ end++ local function serialize(node, buf)+ table.insert(buf, "<" .. node.name);+ for k, v in pairs(node.attr) do+ table.insert(buf, " " .. k .. '="' .. xml_escape(tostring(v)) .. '"');+ end++ if #node.tags == 0 then+ table.insert(buf, "/>");+ else+ table.insert(buf, ">");+ for _, child in ipairs(node.tags) do+ serialize(child, buf);+ end+ table.insert(buf, "</" .. node.name .. ">");+ end++ return buf;+ end++ stanza_mt.__tostring = function(self)+ return table.concat(serialize(self, {}));+ end++ st = {+ iq = function(attr)+ return new_stanza('iq', attr);+ end,+ };+end++-- ---------------------------------------------------------------------------+-- Test+-- ---------------------------------------------------------------------------++describe("Rayo dial IQ header CRLF escaping [" .. source .. "]", function()++ -- Builds a dial IQ the same shape mod_muc_jigasi_invite.lua produces:+ -- <iq><dial xmlns=rayo><header name=... value=.../></dial></iq>+ -- with a JvbRoomName header whose value is spiked with a raw CRLF.+ local function build_dial_iq(room_value)+ return st.iq({+ xmlns = "jabber:client",+ type = "set",+ to = "[email protected]",+ from = "[email protected]",+ id = "dial-1",+ })+ :tag("dial", { xmlns = RAYO_NS, from = "fromnumber", to = "sip:[email protected]" })+ :tag("header", { xmlns = RAYO_NS, name = "JvbRoomName", value = room_value })+ :up()+ :up();+ end++ it("escapes a CRLF-injected header value to ", function()+ -- A client attempting to smuggle an extra SIP header via CRLF injection.+ local malicious = "[email protected]\r\nInjected-Header: evil";+ local iq = build_dial_iq(malicious);++ local xml = tostring(iq);++ assert.is_truthy(xml:find(" ", 1, true),+ "serialized dial IQ must escape the raw CRLF to ");+ end)++ it("leaks no raw CR or LF bytes in the serialized stanza", function()+ local malicious = "[email protected]\r\nInjected-Header: evil";+ local iq = build_dial_iq(malicious);++ local xml = tostring(iq);++ assert.is_nil(xml:find("[\r\n]"),+ "serialized dial IQ must not contain any raw CR/LF byte");+ end)++ it("preserves the room name text around the escaped CRLF", function()+ local malicious = "[email protected]\r\nInjected-Header: evil";+ local iq = build_dial_iq(malicious);++ local xml = tostring(iq);++ -- The header name and the surrounding value text survive; only the+ -- control characters are entity-encoded.+ assert.is_truthy(xml:find("JvbRoomName", 1, true));+ assert.is_truthy(xml:find("[email protected] Injected%-Header: evil"));+ end)++end);diff --git a/tests/prosody/mod_rayo_dial_header_crlf_spec.js b/tests/prosody/mod_rayo_dial_header_crlf_spec.jsnew file mode 100644index 0000000000..359f509ee6--- /dev/null+++ b/tests/prosody/mod_rayo_dial_header_crlf_spec.js@@ -0,0 +1,217 @@+import assert from 'assert';+import http from 'http';++import { mintAsapToken } from './helpers/jwt.js';+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';++let _roomCounter = 0;+const nextRoom = () => `rayo-crlf-${++_roomCounter}@conference.localhost`;++// Header name that mod_filter_iq_rayo adds to the forwarded dial IQ from the+// JWT context. Its value comes from session.jitsi_meet_context_user.id which+// Prosody decodes directly from the JWT (not via XML), so any CRLF in the+// token claim lands in the Lua string and flows through util.stanza+// serialization without the XML-layer whitespace normalisation that applies+// to attribute-sourced values.+const INITIATOR_HEADER = 'X-outbound-call-initiator-user';++/**+ * Fetches pending dial IQ messages from the test observer.+ *+ * @returns {Promise<Array>}+ */+function getDialIqs() {+ return new Promise((resolve, reject) => {+ http.get('http://localhost:5280/test-observer/dial-iqs', res => {+ let body = '';++ res.on('data', c => {+ body += c;+ });+ res.on('end', () => resolve(JSON.parse(body)));+ }).on('error', reject);+ });+}++/**+ * Clears all dial IQ messages from the test observer.+ *+ * @returns {Promise<void>}+ */+function clearDialIqs() {+ return new Promise((resolve, reject) => {+ const req = http.request(+ 'http://localhost:5280/test-observer/dial-iqs',+ { method: 'DELETE' },+ res => res.resume().on('end', resolve)+ );++ req.on('error', reject);+ req.end();+ });+}++describe('mod_filter_iq_rayo — CRLF escaping in re-serialized headers', () => {++ const clients = [];++ afterEach(async () => {+ await Promise.all(clients.map(c => c.disconnect()));+ clients.length = 0;+ });++ /**+ * Creates a test client whose JWT embeds userId as context.user.id.+ * Joins a fresh room (focus first so the jicofo lock is lifted).+ *+ * @param {string} userId Value to put in context.user.id.+ * @returns {Promise<{client: object, room: string}>}+ */+ async function setup(userId) {+ const room = nextRoom();+ const roomName = room.split('@')[0];+ const token = mintAsapToken({+ room: roomName,+ context: {+ features: { 'outbound-call': true },+ ...userId === undefined ? {} : { user: { id: userId } }+ }+ });+ const focus = await joinWithFocus(room);++ clients.push(focus);++ const c = await createXmppClient({ params: { token } });++ clients.push(c);+ await c.joinRoom(room);++ return { client: c,+ room };+ }++ // ── helper ────────────────────────────────────────────────────────────────++ /**+ * Sends a well-formed dial IQ and waits for at most one forwarded IQ to+ * appear in the test observer. Returns the first captured dial IQ entry.+ *+ * @param {object} client XmppTestClient+ * @param {string} room Full room JID+ * @returns {Promise<object>}+ */+ async function sendAndCapture(client, room) {+ await clearDialIqs();+ await client.sendRayoIq(room);++ // Give Prosody time to route the IQ to the MUC component.+ await new Promise(r => setTimeout(r, 300));++ const iqs = await getDialIqs();++ assert.strictEqual(iqs.length, 1, 'dial IQ must reach the MUC component');++ return iqs[0];+ }++ // ── CRLF in JWT user id → X-outbound-call-initiator-user header ──────────++ /**+ * Asserts that the raw XML captured by the test observer contains no raw+ * CR or LF bytes in any attribute value.+ *+ * @param {string} rawXml The raw_xml field from the observer entry.+ */+ function assertNoRawCrlf(rawXml) {+ assert.ok(!/[\r\n]/.test(rawXml),+ 'raw XML must contain no raw CR or LF bytes');+ }++ it('sanitises CRLF in JWT user-id when building the initiator header', async () => {+ // CRLF embedded in the token claim. Prosody decodes the JWT directly+ // (not via XML), so the Lua string retains the raw \r\n.+ // mod_filter_iq_rayo normalises the value via sanitize_header_value()+ // before inserting it into the forwarded stanza attribute.+ // mod_test_observer captures tostring(stanza) — the serialized bytes+ // that would reach the wire — so asserting no raw CR/LF in raw_xml+ // directly verifies the normalisation.+ const userId = 'legit-user\r\nextra-data';+ const { client: c, room } = await setup(userId);+ const iq = await sendAndCapture(c, room);++ assert.ok(iq.headers?.[INITIATOR_HEADER] !== undefined,+ `forwarded dial IQ must contain ${INITIATOR_HEADER}`);++ assertNoRawCrlf(iq.raw_xml);++ // The CRLF must have been replaced with spaces, not silently dropped.+ assert.ok(iq.headers[INITIATOR_HEADER].includes('legit-user'),+ 'the legitimate part of the user-id must be preserved');+ });++ it('sanitises bare LF in JWT user-id', async () => {+ const { client: c, room } = await setup('user\nextra-data');+ const iq = await sendAndCapture(c, room);++ assertNoRawCrlf(iq.raw_xml);+ });++ it('sanitises bare CR in JWT user-id', async () => {+ const { client: c, room } = await setup('user\rextra-data');+ const iq = await sendAndCapture(c, room);++ assertNoRawCrlf(iq.raw_xml);+ });++ it('passes through a clean user-id unchanged (control)', async () => {+ const userId = 'clean-user-id';+ const { client: c, room } = await setup(userId);+ const iq = await sendAndCapture(c, room);++ assert.strictEqual(iq.headers?.[INITIATOR_HEADER], userId,+ 'a clean user-id must be forwarded verbatim');+ assertNoRawCrlf(iq.raw_xml);+ });++ // ── CRLF sent in a client XML attribute → XML parser normalises it ────────+ //+ // When the JS client puts \r\n inside an XML attribute value, expat's+ // attribute-value normalisation (XML spec §3.3.3) converts each literal+ // whitespace character to a space before the Lua application layer ever+ // sees the value. Prosody therefore never receives raw CRLF from this+ // path; the re-forwarded stanza contains spaces instead.+ // These tests confirm that normalisation end-to-end: the JS client sends+ // a JvbRoomPassword containing CR/LF, the IQ still passes the filter+ // (because JvbRoomName is correct), and the raw_xml captured at the MUC+ // component contains no raw CR or LF bytes in any attribute value.++ it('XML attribute CRLF is normalised to spaces by expat before reaching Lua', async () => {+ // No JWT user context needed here — we are testing the XML-attribute+ // path, not the JWT path.+ const { client: c, room } = await setup(undefined);++ await clearDialIqs();++ // @xmpp/client serialises the value as-is into the XML byte stream;+ // expat on the Prosody side normalises the literal \r and \n to spaces.+ await c.sendRayoIq(room, { roomPassHeader: 'secret\r\nextra-data' });+ await new Promise(r => setTimeout(r, 300));++ const iqs = await getDialIqs();++ assert.strictEqual(iqs.length, 1,+ 'IQ with CRLF in JvbRoomPassword must still reach the MUC component');++ const iq = iqs[0];++ // The password value the Lua application received (after expat+ // normalisation) must not contain raw CR or LF.+ assert.ok(!/[\r\n]/.test(iq.room_pass_header),+ 'room_pass_header must contain no raw CR/LF after XML attribute normalisation');++ // Likewise the serialised wire form must have no raw control bytes.+ assert.ok(!/[\r\n]/.test(iq.raw_xml),+ 'raw_xml must contain no raw CR/LF bytes');+ });+});+