Skip to content

Instantly share code, notes, and snippets.

@rgrove
Last active February 8, 2019 18:33
Show Gist options
  • Save rgrove/3ea9421b3912235e978f55e291f19d5d to your computer and use it in GitHub Desktop.
Save rgrove/3ea9421b3912235e978f55e291f19d5d to your computer and use it in GitHub Desktop.
How to protect against prototype poisoning when using the Express body-parser library
/*
The Express body-parser library, which you may be using to parse incoming JSON
request bodies, doesn't currently protect against prototype poisoning via the
`__proto__` key.
The dangers of prototype poisoning are described in detail here:
https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061
Until body-parser provides its own fix, you can protect yourself by adding a
reviver function that throws an error if it sees any key named "__proto__". This
is as effective as the technique used by https://github.com/hapijs/bourne, but
it's quite a bit slower because the reviver function prevents V8 from using its
faster native JSON parser.
*/
// BEFORE
//
// You're probably using body-parser like this. You may be vulnerable to
// prototype poisoning.
app.use(bodyParser.json());
// AFTER
//
// To prevent prototype poisoning, add this reviver function to body-parser's
// options object.
app.use(bodyParser.json({
reviver(key, value) {
if (key === '__proto__') {
throw new SyntaxError('JSON object contains forbidden __proto__ property');
}
return value;
}
}));
@rgrove
Copy link
Author

rgrove commented Feb 8, 2019

A faster approach that uses Bourne.scan() is described here:

expressjs/body-parser#347 (comment)

It's significantly faster than the reviver-based approach in this gist, though still not as fast as Bourne.parse().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment