Skip to content

Instantly share code, notes, and snippets.

@patoui
Last active July 13, 2023 15:45
Show Gist options
  • Save patoui/fc61e6b16b003214230b33fa29da614d to your computer and use it in GitHub Desktop.
Save patoui/fc61e6b16b003214230b33fa29da614d to your computer and use it in GitHub Desktop.
Prototype pollution example
// see https://learn.snyk.io/lesson/prototype-pollution/ for additional information and great explanations
// recursively update target with source data
function merge(target, source) {
for (const attr in source) {
if (
typeof target[attr] === "object" &&
typeof source[attr] === "object"
) {
merge(target[attr], source[attr])
} else {
// prototype overwrite occurs here
target[attr] = source[attr]
}
}
}
const user = { name: 'John Doe', role: 'viewer' };
const requestData = { name: 'Jane Doe', __proto__: { role: 'admin' } };
console.log(user.role); // viewer
merge(user, requestData);
console.log(user.role); // admin
// more secure approach
const nullUserTwo = Object.create(null);
const userTwo = { name: 'John Doe', role: 'viewer' };
const requestDataTwo = { name: 'Jane Doe', __proto__: { role: 'admin' } };
merge(nullUserTwo, userTwo);
merge(nullUserTwo, requestDataTwo);
console.log(nullUserTwo.role); // viewer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment