0

I'm using eval to interpret some variables input.

Possible inputs are

"somevar"

"someobj.someprop['somekey'].someprop"

"window.someprop"

etc.

However I dont want it to 'execute' any action. Like calling any function, changing any value of anything, declaring any variable.

So those should not be accepted (and any that change state of anything):

alert()
var somewar = 0
mywar = somewar

Is it possible via native js?

My target is just to interpret complex input variable "address" and return it.

Adam Pietrasiak
  • 12,773
  • 9
  • 78
  • 91

1 Answers1

3

For something like this, you may be better parsing the value.

var steps = input.match(/\['(?:[^']|\\.)+'\]|\["(?:[^"]|\\.)+"\]|[a-zA-Z0-9_]+/g);
var src = window;
var step;
while(step = steps.shift()) {
    if( step.charAt(0)) {
        // ['...'] or ["..."]
        step = step.substring(2,step.length-2);
    }
    src = src[step];
}
alert(src);

Since you're parsing out the string, there's no opportunity for malicious code to be executed.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592