2

I am writing a simple library that will read values from an object given a string property.

Is it possible to read the property but have a function execute without actually invoking the function?

something like:

var obj = {

fn : (function malicious(){    deleteLotsOfFiles();
})()

}

if I do

var foo = obj.fn;

is there a way just by reading the property to execute a (malicious) function?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 3
    You can define a getter for a property using [MDN: Object.defineProperty()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) you could also look at that question [how to use javascript Object.defineProperty](http://stackoverflow.com/questions/18524652/how-to-use-javascript-object-defineproperty) – t.niese Feb 11 '16 at 18:47
  • Why would you not trust your arguments? – Bergi Feb 11 '16 at 18:50

3 Answers3

2

The malicious function would have already executed anyway before you even referenced it. Once the function is parsed by the engine, it is executed straight away (self-invoking).

Reda
  • 1,361
  • 10
  • 12
2
var obj = {
    get fn() { deleteLotsOfFiles(); }
};

// later
var o = obj; // deleteLotsOfFiles has not been executed
console.log(o.fn); // you just deleted lots of files
yurisich
  • 6,991
  • 7
  • 42
  • 63
1

An alternative

var o = Object.defineProperty(o, 'baz', {
    get: function(){
        console.log("Delete Everything!");
    } 
});

Then access o.baz and they are deleted

More Information on getters from MDN

Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls.

Seems pretty much like what you want to do.

Matt
  • 4,462
  • 5
  • 25
  • 35