Skip to main content

Cross-Site-Scripting

XSS is a vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users, which could lead to unintended actions being performed on behalf of the user.

Types of XSS

  1. Stored — Script stored on server, executes upon view. E.g. Comment section

  1. Reflected — Script embedded in URL, reflected to user in server’s response, then the victim browser will execute the script. E.g. Search param in URL: https://site.com/search?param=<script>alert('XSS')</script>

  1. DOM — E.g. Page that uses fragments — Script in URL also, as site unsafely uses location.hash (E.g. use textContent instead of innerHTML) to update DOM https://site.com/#<img src=link onerror=alert('XSS')>

  1. Blind — E.g. Script in URL, but site does not reflect it back.
    • To identify it, use a side-channel or out-of-band technique (e.g. DNS lookup, HTTP request to attacker-controlled server).
    • Use boolean-based techniques to infer if the payload executed.

Mitigation

  1. Input Validation — Sanitize and validate all user inputs are of correct type and format.

  1. Output Encoding — Encode data before rendering it in the browser (e.g. HTML encode, JavaScript encode). This prevents the browser from interpreting data as code.

  1. Content Security Policy (CSP) —
    • Implement CSP headers to restrict sources from which scripts can be loaded and executed.
    • Example directives:
      • script-src 'self' https://trusted.cdn.com;
      • default-src 'self';

  1. HTTPOnly and Secure Cookies —
    • HttpOnly flag allow only server-side access to cookies, preventing client-side scripts from accessing them.
    • Secure flag ensures cookies are only sent over HTTPS connections, preventing interception.

Other XSS Facts

  • In React, by default, data is escaped when using JSX syntax, mitigating XSS risks. However, using dangerouslySetInnerHTML can introduce vulnerabilities if not handled carefully.