Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JSON.parse() really safer than eval() when web page and ajax call come from same server?

I get that JSON.parse() prevents an attacker from injecting javascript into the response since a JSON parser is just a text parser, not a script parser so please don't close this is a dup of all the other questions that talk about that. This is a different question.

If an attacker can hijaack your Ajax call and put javascript into the Ajax call aren't they just as likely to be able to hijack your actual webpage and put arbitrary javascript into your page from which they could accomplish the exact same attack?

Sure, you have nothing to lose by using JSON.parse() instead of eval() (unless you don't have a JSON parser yet in your environment and have to add more code to get one), but what situations does it really add safety if your web page is being served by the same host as your ajax call?

like image 915
jfriend00 Avatar asked Jul 20 '11 16:07

jfriend00


People also ask

Why is JSON parse more secure than eval?

parse() is safer to use because the eval() function will execute js where json. parse() will only process valid JSON string representations into a JavaScript value or JSON object. json. parse() will throw an error if invalid JSON strings are passed to it.

Is JSON parse safe?

Parsing JSON can be a dangerous procedure if the JSON text contains untrusted data. For example, if you parse untrusted JSON in a browser using the JavaScript “eval” function, and the untrusted JSON text itself contains JavaScript code, the code will execute during parse time.

Why JSON eval is not recommended?

Your server could be compromised and the data source could be tampered with.

Does JSON parse use eval?

A fast and secure JSON parser in JavaScript This JSON parser does not attempt to validate the JSON, so may return a surprising result given a syntactically invalid input, but it does not use eval so is deterministic and is guaranteed not to modify any object other than its return value.


1 Answers

Yes, it is really safer. Every precaution you do not take is a set of potential exploits you don't prevent.

An attacker might be able to have some control over your server's output without being able to change it entirely. Nobody's suggesting it's a magic bullet, but it's potentially faster and you're not creating a potential vulnerability that could come back and hurt you.

Maybe someone running your server is having a bad day, and does something silly like constructing JSON by concatenating unsanitized user input:

<?php
    print '{"foo": ' . $_GET['bar'] . '}';
?>

If you're using JSON.parse, the worst they can do is shove a large object into your memory. If you're using eval they can hijack everything.

like image 75
Jeremy Avatar answered Sep 27 '22 20:09

Jeremy