Cross-Site Scripting (XSS) in JavaScript

Cross-Site Scripting (XSS) is a web security vulnerability that allows an attacker to inject malicious code into a web page that is viewed by other users.

XSS can compromise the user's interaction with the web application, steal their cookies or session tokens, redirect them to malicious sites, or perform other actions on their behalf.

Types of XSS Attacks

Reflected XSS

This type of XSS occurs when the user input is reflected back to the user without proper validation or encoding.

For example, if a web application takes a search query as a parameter and displays it in the result page, an attacker can craft a malicious URL that contains a script tag and send it to the victim. If the victim clicks on the URL, the script will execute in their browser.

Stored XSS

This type of XSS occurs when the user input is stored in the web server's database and displayed to other users without proper validation or encoding.

For example, if a web application allows users to post comments on a blog, an attacker can post a comment that contains a script tag and it will be stored in the database. When other users view the blog, the script will execute in their browsers.

DOM-based XSS

This type of XSS occurs when the user input is manipulated by the client-side code, such as JavaScript, that changes the DOM of the web page.

For example, if a web application uses the user input to set the value of an HTML element, an attacker can inject a script tag as the user input and it will be executed by the browser.

Prevent XSS Attacks

Sanitize User Input

Before displaying any user input on a webpage, sanitize it thoroughly.

Sanitization involves neutralizing special characters that could be misinterpreted as code or markup. Specifically, focus on escaping characters like > and <.

function escapeHTML (html) {
    return html
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
}

By doing so, you prevent the creation of unintended HTML tags during content display.

Use a Content Security Policy

Content Security Policy allows web developers to control which resources the browser is allowed to load for a specific page.

You can use either HTTP headers and a <meta /> tag to enable the Content Security Policy.

<meta
    http-equiv="Content-Security-Policy"
    content="default-src 'self'; img-src https://*; child-src 'none';" 
/>

Use HTTP-Only Cookie

HTTP-only cookies are cookies that can only be accessed by the web server, not by client-side JavaScript code. This prevents attackers from reading the sensitive information stored in the cookies.

app.post('/login', (req, res) => {
    res.cookie('myCookie', 'myValue', {
        httpOnly: true
    });
});

Subscribe to read the full content