CVE-2022-25352: Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') (CWE-1321)
value: The package libnested before 1.5.2 are vulnerable to Prototype Pollution via the set function in index.js. **Note:** This vulnerability derives from an incomplete fix for [CVE-2020-28283](https://security.snyk.io/vuln/SNYK-JS-LIBNESTED-1054930)
CWE description: The product receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype.
CVSS v3 base score: 9.8
Published: 2022-03-17T12:15Z
Repository: https://github.com/dominictarr/libnested
Language: Other
Files changed: .gitignore, LICENSE, README.md, index.js, package.json, test.js
Commit date: 2022-03-08 01:42:19 +1300
Commit message: better fix for prototype pollution vulnerability

cheers Idan Digmi of Snyk Security

Diff: diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6c9de92
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+node_modules
+.npm-debug.log*
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..54a0f6b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) 2016 'Dominic Tarr'
+
+Permission is hereby granted, free of charge, 
+to any person obtaining a copy of this software and 
+associated documentation files (the "Software"), to 
+deal in the Software without restriction, including 
+without limitation the rights to use, copy, modify, 
+merge, publish, distribute, sublicense, and/or sell 
+copies of the Software, and to permit persons to whom 
+the Software is furnished to do so, 
+subject to the following conditions:
+
+The above copyright notice and this permission notice 
+shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
+ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..1629061
--- /dev/null
+++ b/README.md
@@ -0,0 +1,55 @@
+# libnested
+
+basic functions (map, each, get, set, keys) for nested objects.
+
+## api
+
+### each (object, iter(value, path), includeArrays?) => boolean
+
+iterate over an object (depth first) and call `iter` with each value.
+`path` is an array with one or more items, which is the path to value.
+`value` will be any item which is not a `{}` object. Arrays are treated as values.
+
+if `iter` returns false then each will stop traversing the object and return false also.
+
+if `includeArrays` is true (defaults to false) then arrays
+encounted will be treated like objects. If `includeArrays`
+is not true, arrays will be treated like `values`.
+
+### map (object, iter(value, path) => nextValue, output, includeArrays?) => output
+
+map over a nested object (depth first). A new object is returned (unless `output` is given), containing values returned by `iter`.
+
+if `includeArrays` is true, the contents of arrays will be mapped,
+otherwise only the arrays themselves will be.
+
+### paths (object) => [path...]
+
+return an array of paths into an object.
+
+### get(object, path, default) => value
+
+get the `value` at `path` within object.
+if `path` does not exist in the `object`, return `default`.
+
+`path` may be an array of strings or numbers, or a single string or number.
+
+### set(object, path, value)
+
+set `value` at location `path` within `object`.
+If path is deeper than object goes, intermediate `{}`'s are added.
+
+`path` may be an array of strings or numbers, or a single string or number.
+
+`object` will be mutated.
+
+### clone (object)
+
+return a new object with the same structure and primitive values as `object`
+
+cyclic objects are not supported - will produce a `RangeError` (stackoverflow)
+
+## License
+
+MIT
+
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..cb7020e
--- /dev/null
+++ b/index.js
@@ -0,0 +1,108 @@
+function isObject (o, allowArray) {
+  return o && 'object' === typeof o && (allowArray || !Array.isArray(o))
+}
+
+function isBasic (b) {
+  return 'string' === typeof b || 'number' === typeof b
+}
+
+function get (obj, path, dft) {
+  if(!isObject(obj, true)) return dft
+  if(isBasic(path)) return obj[path]
+  for(var i = 0; i < path.length; i++) {
+    if(null == (obj = obj[path[i]])) return dft
+  }
+  return obj
+}
+
+function isNonNegativeInteger (i) {
+  return Number.isInteger(i) && i >= 0
+}
+
+function set (obj, path, value) {
+  if(!obj) throw new Error('libnested.set: first arg must be an object')
+  if(isBasic(path)) return obj[path] = value
+  for(var i = 0; i < path.length; i++) {
+    if (isPrototypePolluted(path[i]))
+      continue
+
+    if(i === path.length - 1)
+      obj[path[i]] = value
+    else if(null == obj[path[i]])
+      obj = (obj[path[i]] = isNonNegativeInteger(path[i+1]) ? [] : {})
+    else
+      obj = obj[path[i]]
+  }
+  return value
+}
+
+function each (obj, iter, includeArrays, path) {
+  path = path || []
+  //handle array separately, so that arrays can have integer keys
+  if(Array.isArray(obj)) {
+    if(!includeArrays) return false
+    for(var k = 0; k < obj.length; k++) {
+      //loop content is duplicated, so that return works
+      var v = obj[k]
+      if(isObject(v, includeArrays)) {
+        if(false === each(v, iter, includeArrays, path.concat(k)))
+          return false
+      } else {
+        if(false === iter(v, path.concat(k))) return false
+      }
+    }
+  }
+  else {
+    for(var k in obj) {
+      //loop content is duplicated, so that return works
+      var v = obj[k]
+      if(isObject(v, includeArrays)) {
+        if(false === each(v, iter, includeArrays, path.concat(k)))
+          return false
+      } else {
+        if(false === iter(v, path.concat(k))) return false
+      }
+    }
+  }
+  return true
+}
+
+function map (obj, iter, out, includeArrays) {
+  var out = out || Array.isArray(obj) ? [] : {}
+  each(obj, function (val, path) {
+    set(out, path, iter(val, path))
+  }, includeArrays)
+  return out
+}
+
+function paths (obj, incluedArrays) {
+  var out = []
+  each(obj, function (_, path) {
+    out.push(path)
+  }, incluedArrays)
+  return out
+}
+
+function id (e) { return e }
+
+//note, cyclic objects are not supported.
+//will cause an stack overflow.
+function clone (obj) {
+  if(!isObject(obj, true)) return obj
+  var _obj
+  _obj = Array.isArray(obj) ? [] : {}
+  for(var k in obj) _obj[k] = clone(obj[k])
+  return _obj
+}
+
+function isPrototypePolluted(key) {
+  return ['__proto__', 'constructor', 'prototype'].includes(key.toString())
+}
+
+exports.get = get
+exports.set = set
+exports.each = each
+exports.map = map
+exports.paths = paths
+exports.clone = clone
+exports.copy = clone
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..a51f74c
--- /dev/null
+++ b/package.json
@@ -0,0 +1,19 @@
+{
+  "name": "libnested",
+  "description": "",
+  "version": "1.5.1",
+  "homepage": "https://github.com/dominictarr/libnested",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/dominictarr/libnested.git"
+  },
+  "dependencies": {},
+  "devDependencies": {
+    "tape": "^4.6.2"
+  },
+  "scripts": {
+    "test": "node test.js"
+  },
+  "author": "'Dominic Tarr' <dominic.tarr@gmail.com> (dominictarr.com)",
+  "license": "MIT"
+}
diff --git a/test.js b/test.js
new file mode 100644
index 0000000..2b65d75
--- /dev/null
+++ b/test.js
@@ -0,0 +1,164 @@
+
+var tape = require('tape')
+var R = require('./')
+
+tape('paths', function (t) {
+
+  t.deepEqual(
+    R.get({foo: true, bar: false}, 'foo'),
+    true
+  )
+  t.deepEqual(
+    R.get({foo: true, bar: false}, 'bar'),
+    false
+  )
+  t.deepEqual(
+    R.get({foo: true, bar: false}, ['foo']),
+    true
+  )
+  t.deepEqual(
+    R.get({foo: true, bar: false}, ['bar']),
+    false
+  )
+
+  t.deepEqual(
+    R.get(null, ['bar']),
+    undefined
+  )
+
+
+  t.deepEqual(
+    R.paths({foo: {bar: true}, baz: 2}),
+    [
+      ['foo', 'bar'],
+      ['baz']
+    ]
+  )
+  t.deepEqual(
+    R.paths({}),
+    []
+  )
+
+  var deep = {foo: {bar: true}, baz: 2, blurg: {fop: {hif: []}}}
+
+  t.deepEqual(
+    R.paths(deep),
+    [
+      ['foo', 'bar'],
+      ['baz'],
+      ['blurg', 'fop', 'hif']
+    ]
+  )
+
+  var o = {}
+  R.each(deep, function (v, path) {
+    t.equal(R.get(deep, path), v)
+    R.set(o, path, v)
+  })
+
+  t.deepEqual(o, deep)
+
+  t.deepEqual(R.map(deep, function (v) { return v }), deep)
+
+  var first
+  t.equal(R.each(deep, function (_, path) {
+    if(path.length === 2) {
+      first = path
+      return false
+    }
+  }), false)
+
+  t.deepEqual(first, ['foo', 'bar'])
+
+  var _a = [1,2,3]
+  var a = R.set(deep, ['rom', 'pan'], _a)
+  t.equal(a, _a)
+
+
+
+  var a = R.set(deep, 'zak', 53)
+  var a = R.set(deep, ['rom', 'pan', 2], 30)
+
+  t.deepEqual(
+    deep,
+    {
+      foo: {bar: true},
+      baz: 2,
+      blurg: {fop: {hif: []}},
+      rom: {pan: [1,2,30]},
+      zak: 53
+    }
+  )
+
+  t.deepEqual(
+    deep,
+    R.clone(deep)
+  )
+
+  t.notEqual(
+    deep,
+    R.clone(deep)
+  )
+
+
+  t.end()
+
+})
+
+tape('include arrays', function (t) {
+  var deep = {foo: {bar: true}, baz: 2, blurg: {fop: {hif: [1,2,3]}}}
+
+  t.deepEqual(
+    R.paths(deep, true),
+    [
+      ['foo', 'bar'],
+      ['baz'],
+      ['blurg', 'fop', 'hif', 0],
+      ['blurg', 'fop', 'hif', 1],
+      ['blurg', 'fop', 'hif', 2]
+    ]
+  )
+
+  var o = {}
+  R.set(o, ['hello', 0, 'okay'], true),
+  t.deepEqual(
+    o,
+    {hello: [{okay: true}]}
+  )
+
+  t.end()
+})
+
+tape('set', function (t) {
+  var o = {}
+  R.set(o, ['foo', 0], true)
+  t.deepEqual(o, {foo: [true]})
+  R.set(o, ['foo', 1], false)
+  t.deepEqual(o, {foo: [true, false]})
+  t.ok(Array.isArray(o.foo), 'created an array in the right place')
+  t.end()
+})
+
+tape('clone does not leave an array reference', function (t) {
+  var a = {foo: [1]}
+  t.deepEqual(R.clone(a), a)
+  t.notEqual(a.foo, R.clone(a).foo)
+  var b = {foo: [{}], bar: {}}
+  t.deepEqual(R.clone(b), b)
+  t.notEqual(b.foo, R.clone(b).foo)
+  t.notEqual(b.foo[0], R.clone(b).foo[0])
+  t.notEqual(b.bar, R.clone(b).bar)
+
+  t.end()
+})
+
+tape('prototype pollution', function (t) {
+  t.notEqual({}.polluted, 'yes')
+  R.set({}, ['__proto__','polluted'], 'yes');
+  t.notEqual({}.polluted, 'yes')
+  R.set({}, [['__proto__'], 'polluted'], 'yes')
+  t.notEqual({}.polluted, 'yes')
+  R.set({}, [['constructor', 'prototype'], 'polluted'], 'yes')
+  t.notEqual({}.polluted, 'yes')
+  t.end()
+})

Fixed code: node_modules
.npm-debug.log*
Copyright (c) 2016 'Dominic Tarr'

Permission is hereby granted, free of charge, 
to any person obtaining a copy of this software and 
associated documentation files (the "Software"), to 
deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, 
merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom 
the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice 
shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# libnested

basic functions (map, each, get, set, keys) for nested objects.

## api

### each (object, iter(value, path), includeArrays?) => boolean

iterate over an object (depth first) and call `iter` with each value.
`path` is an array with one or more items, which is the path to value.
`value` will be any item which is not a `{}` object. Arrays are treated as values.

if `iter` returns false then each will stop traversing the object and return false also.

if `includeArrays` is true (defaults to false) then arrays
encounted will be treated like objects. If `includeArrays`
is not true, arrays will be treated like `values`.

### map (object, iter(value, path) => nextValue, output, includeArrays?) => output

map over a nested object (depth first). A new object is returned (unless `output` is given), containing values returned by `iter`.

if `includeArrays` is true, the contents of arrays will be mapped,
otherwise only the arrays themselves will be.

### paths (object) => [path...]

return an array of paths into an object.

### get(object, path, default) => value

get the `value` at `path` within object.
if `path` does not exist in the `object`, return `default`.

`path` may be an array of strings or numbers, or a single string or number.

### set(object, path, value)

set `value` at location `path` within `object`.
If path is deeper than object goes, intermediate `{}`'s are added.

`path` may be an array of strings or numbers, or a single string or number.

`object` will be mutated.

### clone (object)

return a new object with the same structure and primitive values as `object`

cyclic objects are not supported - will produce a `RangeError` (stackoverflow)

## License

MIT

function isObject (o, allowArray) {
  return o && 'object' === typeof o && (allowArray || !Array.isArray(o))
}

function isBasic (b) {
  return 'string' === typeof b || 'number' === typeof b
}

function get (obj, path, dft) {
  if(!isObject(obj, true)) return dft
  if(isBasic(path)) return obj[path]
  for(var i = 0; i < path.length; i++) {
    if(null == (obj = obj[path[i]])) return dft
  }
  return obj
}

function isNonNegativeInteger (i) {
  return Number.isInteger(i) && i >= 0
}

function set (obj, path, value) {
  if(!obj) throw new Error('libnested.set: first arg must be an object')
  if(isBasic(path)) return obj[path] = value
  for(var i = 0; i < path.length; i++) {
    if (isPrototypePolluted(path[i]))
      continue

    if(i === path.length - 1)
      obj[path[i]] = value
    else if(null == obj[path[i]])
      obj = (obj[path[i]] = isNonNegativeInteger(path[i+1]) ? [] : {})
    else
      obj = obj[path[i]]
  }
  return value
}

function each (obj, iter, includeArrays, path) {
  path = path || []
  //handle array separately, so that arrays can have integer keys
  if(Array.isArray(obj)) {
    if(!includeArrays) return false
    for(var k = 0; k < obj.length; k++) {
      //loop content is duplicated, so that return works
      var v = obj[k]
      if(isObject(v, includeArrays)) {
        if(false === each(v, iter, includeArrays, path.concat(k)))
          return false
      } else {
        if(false === iter(v, path.concat(k))) return false
      }
    }
  }
  else {
    for(var k in obj) {
      //loop content is duplicated, so that return works
      var v = obj[k]
      if(isObject(v, includeArrays)) {
        if(false === each(v, iter, includeArrays, path.concat(k)))
          return false
      } else {
        if(false === iter(v, path.concat(k))) return false
      }
    }
  }
  return true
}

function map (obj, iter, out, includeArrays) {
  var out = out || Array.isArray(obj) ? [] : {}
  each(obj, function (val, path) {
    set(out, path, iter(val, path))
  }, includeArrays)
  return out
}

function paths (obj, incluedArrays) {
  var out = []
  each(obj, function (_, path) {
    out.push(path)
  }, incluedArrays)
  return out
}

function id (e) { return e }

//note, cyclic objects are not supported.
//will cause an stack overflow.
function clone (obj) {
  if(!isObject(obj, true)) return obj
  var _obj
  _obj = Array.isArray(obj) ? [] : {}
  for(var k in obj) _obj[k] = clone(obj[k])
  return _obj
}

function isPrototypePolluted(key) {
  return ['__proto__', 'constructor', 'prototype'].includes(key.toString())
}

exports.get = get
exports.set = set
exports.each = each
exports.map = map
exports.paths = paths
exports.clone = clone
exports.copy = clone
{
  "name": "libnested",
  "description": "",
  "version": "1.5.1",
  "homepage": "https://github.com/dominictarr/libnested",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/libnested.git"
  },
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.6.2"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "'Dominic Tarr' <dominic.tarr@gmail.com> (dominictarr.com)",
  "license": "MIT"
}

var tape = require('tape')
var R = require('./')

tape('paths', function (t) {

  t.deepEqual(
    R.get({foo: true, bar: false}, 'foo'),
    true
  )
  t.deepEqual(
    R.get({foo: true, bar: false}, 'bar'),
    false
  )
  t.deepEqual(
    R.get({foo: true, bar: false}, ['foo']),
    true
  )
  t.deepEqual(
    R.get({foo: true, bar: false}, ['bar']),
    false
  )

  t.deepEqual(
    R.get(null, ['bar']),
    undefined
  )


  t.deepEqual(
    R.paths({foo: {bar: true}, baz: 2}),
    [
      ['foo', 'bar'],
      ['baz']
    ]
  )
  t.deepEqual(
    R.paths({}),
    []
  )

  var deep = {foo: {bar: true}, baz: 2, blurg: {fop: {hif: []}}}

  t.deepEqual(
    R.paths(deep),
    [
      ['foo', 'bar'],
      ['baz'],
      ['blurg', 'fop', 'hif']
    ]
  )

  var o = {}
  R.each(deep, function (v, path) {
    t.equal(R.get(deep, path), v)
    R.set(o, path, v)
  })

  t.deepEqual(o, deep)

  t.deepEqual(R.map(deep, function (v) { return v }), deep)

  var first
  t.equal(R.each(deep, function (_, path) {
    if(path.length === 2) {
      first = path
      return false
    }
  }), false)

  t.deepEqual(first, ['foo', 'bar'])

  var _a = [1,2,3]
  var a = R.set(deep, ['rom', 'pan'], _a)
  t.equal(a, _a)



  var a = R.set(deep, 'zak', 53)
  var a = R.set(deep, ['rom', 'pan', 2], 30)

  t.deepEqual(
    deep,
    {
      foo: {bar: true},
      baz: 2,
      blurg: {fop: {hif: []}},
      rom: {pan: [1,2,30]},
      zak: 53
    }
  )

  t.deepEqual(
    deep,
    R.clone(deep)
  )

  t.notEqual(
    deep,
    R.clone(deep)
  )


  t.end()

})

tape('include arrays', function (t) {
  var deep = {foo: {bar: true}, baz: 2, blurg: {fop: {hif: [1,2,3]}}}

  t.deepEqual(
    R.paths(deep, true),
    [
      ['foo', 'bar'],
      ['baz'],
      ['blurg', 'fop', 'hif', 0],
      ['blurg', 'fop', 'hif', 1],
      ['blurg', 'fop', 'hif', 2]
    ]
  )

  var o = {}
  R.set(o, ['hello', 0, 'okay'], true),
  t.deepEqual(
    o,
    {hello: [{okay: true}]}
  )

  t.end()
})

tape('set', function (t) {
  var o = {}
  R.set(o, ['foo', 0], true)
  t.deepEqual(o, {foo: [true]})
  R.set(o, ['foo', 1], false)
  t.deepEqual(o, {foo: [true, false]})
  t.ok(Array.isArray(o.foo), 'created an array in the right place')
  t.end()
})

tape('clone does not leave an array reference', function (t) {
  var a = {foo: [1]}
  t.deepEqual(R.clone(a), a)
  t.notEqual(a.foo, R.clone(a).foo)
  var b = {foo: [{}], bar: {}}
  t.deepEqual(R.clone(b), b)
  t.notEqual(b.foo, R.clone(b).foo)
  t.notEqual(b.foo[0], R.clone(b).foo[0])
  t.notEqual(b.bar, R.clone(b).bar)

  t.end()
})

tape('prototype pollution', function (t) {
  t.notEqual({}.polluted, 'yes')
  R.set({}, ['__proto__','polluted'], 'yes');
  t.notEqual({}.polluted, 'yes')
  R.set({}, [['__proto__'], 'polluted'], 'yes')
  t.notEqual({}.polluted, 'yes')
  R.set({}, [['constructor', 'prototype'], 'polluted'], 'yes')
  t.notEqual({}.polluted, 'yes')
  t.end()
})