Your Order Lookup Passed the Email Straight to MongoDB and Someone Sent an Object Instead
Guest checkout needed a way to see your order without an account. Order number. Email address. Both must match. app.use(express.json()); app.post("/order", async (req, res) => { const order = await orders.findOne({
Guest checkout
needed a way
to see your order
without an account.
Order number.
Email address.
Both must match.
app.use(express.json());
app.post("/order", async (req, res) => {
const order = await orders.findOne({
number: req.body.number,
email: req.body.email,
});
...
});
The form sends two strings.
The attacker
does not use the form.
{
"number": { "$gt": "" },
"email": { "$ne": "" }
}
express.json
parses that body
into real objects.
The driver
passes them to MongoDB
as written.
And to MongoDB
an object with a dollar key
is not a value.
It is an operator.
Number greater than nothing.
Email not equal to nothing.
That matches every order
in the collection.
findOne
returns the first.
A name,
a delivery address,
what they bought.
Change the condition,
step through the range,
and the next order comes back.
And the next.
No quotes were broken.
No string was built.
Nobody concatenated anything.
That is why it gets past
people who know about
SQL injection.
The code looks
completely parameterised.
It passed review.
It passed every test,
because every test
sent strings.
The problem is the type.
You expected a string,
and JSON
can carry far more
than strings.
Mongoose
does not save you by default.
It casts the operand
inside the operator,
and keeps the operator.
Here is what to do.
Check the type
before the query:
if (typeof req.body.email !== "string")
return res.sendStatus(400);
Better,
validate the whole body
against a schema,
with zod or similar,
so only the shapes you expect
get through.
In Mongoose,
turn on sanitizeFilter.
It wraps any dollar key
in a request value
inside $eq,
so it is compared,
not executed.
And try it yourself.
Send an object
to every endpoint
that queries by user input.
The form only sends
what the form sends.
Your server
accepts what anyone sends.
– Serguey Asael Shinder
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.