XSS(Cross site scripting) attacks are one one of the easiest attacks to perform, and are often the starting point for many attackers looking to compromise your website. Fortunately, they are also one of the easiest to avoid.

The best way to explain what XSS is, is to dive right into an example. This is an HTML element :

<div id="status">
  I am feeling alright
</div>

Letโ€™s assume this div is used to show your status on a popular social media site. It will be seen by many of your friends on their news feed and be seen as : โ€œI am feeling alrightโ€. As a user, you can update your status to whatever you want, and it will appear inside this div element.

If you were to be a malicious user, you could change your status from โ€œI am feeling alrightโ€ to โ€œ<script>alert(โ€˜I am feeling great!โ€™)</script>โ€, but the thing is, your friends would not see your status as โ€œ<script>alert(โ€˜I am feeling great!โ€™)</script>โ€, but instead, they would get an alert message which would look something like this :

xss

This is because the text you just put in is rendered to HTML by default, which will make the content inside the div look like this :

<div id="status">
  <script>
    alert('I am feeling great!')
  </script>
</div>

Everything inside the script tag is considered as javascript code and executed. Thus, everyone across the site has this script executed, and the attacker has now compromised the site.

Although this was a rather innocent example, there are a lot of more sinister things that can be done this way, like submitting a form on someone elseโ€™s behalf.

Preventing XSS

Make sure all information being rendered on the browser is HTML encoded first. This means converting some special characters to their HTML encoded equivalents first.

Hereโ€™s a list of all special characters in HTML and their character code in HTML.

Try it out for yourself! Enter some text with some sensitive HTML characters, and see the encoded output on the right :

Many frameworks and tools like jQuery, angular, and react have this built in so you donโ€™t normally have to worry. But this is still something you should keep an eye out for.

If you want to learn more about security on the web, be sure to read my other posts on web security essentials :

SQL Injection
CORS (Cross origin resource sharing)
Password storage
Sessions and cookies
CSRF (Cross site request forgery)
Human Error and UI/UX design