4

I have the following code at hand

var finalCompleteData = eval("("+jsonresponse.responseText+")");

When I used this, I received a security flaw error in Fortify saying that it might lead to Javascript Hacking. So, I changed it to

var finalCompleteData = window.json.parse(jsonresponse.responseText);

For this, Fortify did not show the error. What the window.json.parse method do ?

Can you please explain. Thanks in advance :-)

3 Answers 3

6

eval will execute any JavaScript code which it is supposed to evaluate, and it evaluates with the highest level of security. This means that if your response text returns non-json code, but valid javascript, the eval will execute it. The sky is the limit with this, it can add new functions, change variables, redirect the page.

With window.json.parse only json will be evaluated, so the risk of rogue code getting entered is much much less.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the answer .. I actually wanted to mitigate the chances of non-JSON entry into my code .. So, thinking of using $.parseJSON instead of window.json.parse. Will that be fine ?
1

eval is able to run any kind of javascript code - not just simple objects/arrays as JSON.parse would (it examines the contents - validating json). For this reason eval should be avoided in places where you cannot guarantee the input.

Comments

1

As others have mentioned, eval will execute any valid JavaScript code. Thus the following would cause an alert:

var jsObject = eval("alert('blah')");

You're essentially trusting any input from a given source, which is not safe in general. A malicious user could take advantage of the eval and execute harmful JavaScript.

JSON.parse, however, will only return successfully if the string passed in is valid JSON:

// gives "SyntaxError: JSON.parse"
var jsObject = JSON.parse("alert('blah')");

Thus it's not executing just anything it's given the way eval is.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.