Last active
July 13, 2023 15:45
-
-
Save patoui/fc61e6b16b003214230b33fa29da614d to your computer and use it in GitHub Desktop.
Prototype pollution example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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