javascript / expert
Snippet
Hardening Objects against Prototype Pollution
Prototype Pollution occurs when an attacker can modify Object.prototype. Using Object.create(null) creates an object without a prototype chain, making it immune to inherited property injections. Freezing the object prevents further modifications to its structure.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const createSecureConfig = (data) => {const config = Object.assign(Object.create(null), data);Object.freeze(config);return config;};const userSupplied = JSON.parse('{"__proto__": {"admin": true}}');const secure = createSecureConfig(userSupplied);console.log(secure.admin); // undefinedconsole.log(secure.__proto__); // undefined
nodejs
Breakdown
1
Object.create(null)
Creates a 'pure' object that has no prototype, meaning it doesn't inherit methods like toString or properties from Object.prototype.
2
Object.freeze(config)
Makes the object immutable, preventing the addition, deletion, or modification of its properties.