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, such as a comments section. That JavaScript is then executed by other users when they visit the site. XSS allows an attacker to do a lot of damage, such as 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 <
and >
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.
Try It Yourself
For a quick and easy way to try it for yourself safely, you can download and run my example site on github. Below is a demonstration:
References
First published: 16th August 2018