Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/commons/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,19 @@ export const _ = {
merge(target: any, source: any) {
if (_.isObject(target) && _.isObject(source)) {
Object.keys(source).forEach((key) => {
// Skip prototype-chain-mutating keys. `Object.keys` returns
// `__proto__` as an own enumerable when the source object came
// from `JSON.parse('{"__proto__":...}')`; without this filter
// the recursive `_.merge(target[key], source[key])` below
// resolves `target['__proto__']` to `Object.prototype` and
// writes attacker-controlled keys onto it.
if (
key === '__proto__' ||
key === 'constructor' ||
key === 'prototype'
) {
return
}
if (_.isObject(source[key])) {
if (!target[key]) {
Object.assign(target, { [key]: {} })
Expand Down
20 changes: 20 additions & 0 deletions packages/commons/test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,5 +212,25 @@ describe('@feathersjs/commons utils', () => {

assert.equal(_.merge('hello', {}), 'hello')
})

it('merge does not mutate Object.prototype via __proto__ keys', () => {
// `Object.keys` returns `__proto__` as an own enumerable key when the
// source object came from `JSON.parse('{"__proto__":...}')`. Without
// the filter in the merge implementation, the recursive call resolves
// `target['__proto__']` to `Object.prototype` and writes attacker-
// controlled keys onto it (affecting every plain object in the
// process).
const target = {} as any
_.merge(target, JSON.parse('{"__proto__":{"polluted":"X"}}'))
assert.strictEqual(({} as any).polluted, undefined)
assert.strictEqual((Object.prototype as any).polluted, undefined)
assert.strictEqual(target.polluted, undefined)

// Same protection for `constructor` and `prototype` keys (the rest
// of the standard prototype-mutating triad).
_.merge(target, JSON.parse('{"constructor":{"prototype":{"polluted2":"Y"}}}'))
assert.strictEqual(({} as any).polluted2, undefined)
assert.strictEqual((Object.prototype as any).polluted2, undefined)
})
})
})