XSS Demystified: Understanding and Preventing Cross-Site Scripting

XSS Demystified: Understanding and Preventing Cross-Site Scripting

It allows an attacker to execute a malicious arbitrary Javascript code within the web browser of victim user. This gives the attacker’s script privileged access to make requests to the server (such as same-origin cookies and storage permissions) and steal data.

Examples

Let’s say a vulnerable social media website allows html content in an input field. An attacker can enter malicious html in that input field. This script which will be executed every time any user of the vulnerable website visits that page. Such type of attack can impact mass users with a single attack.

In this particular example whenever John or Alice load their timeline, the script authstealer.js will automatically run in their browsers and Evil will get access to their session data and compromised accounts. Evil can now login to John and Alice’s accounts and see their payment information, PII data etc.

Let’s try XSS! ✨

We’ll just create a simple NodeJS server, and a basic HTML and try injecting some JS into that

Here’s my index.html

<!DOCTYPE html>
    <div>Enter your name</div>
    <input type="text" id="name"></input>
    <button onclick="addData()">Submit</button>
    <script src="test.js" type="text/javascript"></script>
    <br/>
    <br/>
    <div id="self-xss"></div>
</html>
function addData() {
    const name = document.getElementById('name').value;
    const parsedDocument = document.createRange().createContextualFragment(name);
    document.getElementById('self-xss').appendChild(parsedDocument);
}

which renders a web page like this. This website has an input field that takes input names and displays them in a div.

Now, we’ll try doing something evil 😈. Instead of entering any text name, we’ll try injecting a script in the input field here

which is as simple as <script>alert("XSS attack")</script>

What happened here is instead of listing down the input, the script got executed here. And instead of that simple script, I can have the script downloaded from some other source and try to steal the credentials and session data of logged-in user here.

How to prevent XSS?

  1. Safely Validating input fields - Mostly websites allow very limited set of HTML markup or do not allow HTML markup at all in input fields.

  2. HTTP only cookie - This makes cookies unavailable to client side scripts.

  3. Disable JavaScript in browsers. But that would make our website unresponsive. We’ll just be able to load static HTML pages. This might work for some use cases where we have just static HTML websites.

  4. Send a request header 'X-XSS-PROTECTION' and its value can be set to none or some origin value stating that it will accept scripts only from a particular origin. Please note that this also disables inline scripting in html pages.

  5. SameSite cookie parameter