Cross Site Scripting (XSS)

Cross site scripting is probably the number one vulnerability in websites today. In simple terms, it is the act of a malicious user injecting JavaScript code into a website, usually through an input form. That JavaScript is then loaded later, such as in a comments page and executed by other people's browsers when they load the page. Using XSS, an attacker could potentially steal user's passwords or hijack their sessions.

[Video courtesy of Computerphile]

How do I Prevent it?

XSS is easy enough to prevent, however the trick is to remember to watch out for it every time you accept inputs from the user. Alternatively, you can filter the input every time you output it, but this is probably a lot harder to remember.

To prevent XSS in PHP is to convert the input with htmlspecialchars. If you are not using PHP, then you can manually use string replacement functions to manually convert < and> to &lt; and &gt; accordingly.

The real difficulty comes when you wish to allow user's to input plain html, but not be able to inject javascript. You might try searching for and replacing <script> elements, but the user might inject < script > etc. In these situations, I would recommend allowing users to input markdown text instead, escape this with htmlspecialchars, and then perform the relevant conversions to html when it comes to be rendered.




Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus