Understanding XSS and preventing it using Pure JavaScript
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users.
Sounds fancy, ehh !
Let’s jump to some code so that you can get a flavor of it.
Here is a plunkr which is written in pure javascript. We have created an array which we are rendering in HTML table.
Everything seems to be working fine. Now, lets start exploiting the loopholes of our code and put below code in the name property of array object.
<img onerror='window.document.body.innerHTML = \"<h1>You have been hacked !</h1>\";' src=''>
Now, let’s run the code in plunkr and BOOOOOM….
We are greeted with a weird message which we never expected to see.
So, what just happened ?
Basically, we introduced XSS attack by injecting an fishy <img /> tag with an unwanted execution of below script
window.document.body.innerHTML = \"<h1>You have been hacked !</h1>\";
The onerror executes as expected whenever there is an error while loading the image and so we have a <h1> added to our HTML without our approval.
Prevention
In modern frameworks such as Angular, AngularJS and ReactJS, we have inbuilt functions to handle such attacks and use sanitize functions.
To prevent this attack in pure JS, let’s write a custom function that looks out for special characters such as “<” , “>” and “&” , which can cause XSS attacks. For better usability we can create a escape() function over String prototype itself.
and use it directly in renderData() function:
WoooHoooo ! We have prevented one hell of an XSS attack on our little demo site.
And we have a safe working site.
To checkout the final plunkr, click here.
Cheers !!