Search code examples
javascriptprototype

Prototype pollution between functions and plain objects


There seems to be some asymmetry in prototype pollution between functions and "plain"1 objects:

var a = {}
function foo(){}

a.__proto__.something = 32;
foo.__proto__.bar = 67;

console.log(a.bar) // <--- not polluted
console.log(foo.something) // <--- polluted

  • The example shows that plain objects can pollute functions
  • Is the other way around possible too? (functions polluting plain objects)

1 terminology is not a consensus (see here)


Solution

  • There seems to be some asymmetry between functions and "plain" objects

    Sure. A plain object inherits from Object.prototype, but a function inherits from Function.prototype, which in turn inherits from Object.prototype. Object.prototype inherits from nothing (null), not from Function.prototype.

    Is it possible to do prototype pollution of plain objects from functions?

    Yes, you just have to chain a bit longer:

    var a = {}
    function foo(){}
    
    foo.__proto__.__proto__.bar = 42;
    foo.prototype.__proto__.qux = 67;
    
    console.log(a.bar) // <--- polluted
    console.log(a.qux) // <--- polluted