Cross-Site Scripting (XSS) Defense


Cross-Site Scripting (XSS) is one of the most common web security vulnerabilities that allows attackers to inject malicious scripts into web pages viewed by other users.

Types of XSS

1. Stored XSS (Persistent)

  • Malicious script is permanently stored on the target server
  • Executed when victims visit the infected page
  • Most dangerous type

2. Reflected XSS (Non-Persistent)

  • Script is reflected off a web server
  • Typically delivered via malicious URL
  • Executes immediately

3. DOM-based XSS

  • Vulnerability exists in client-side code
  • Payload never sent to server
  • Manipulates the DOM environment

Common Attack Vectors

<!-- Basic script injection -->
<script>
  alert("XSS");
</script>

<!-- Image tag with onerror -->
<img src="x" onerror="alert('XSS')" />

<!-- Event handlers -->
<button onclick="alert('XSS')">Click me</button>

Prevention Techniques

1. Input Validation

  • Whitelist acceptable characters
  • Reject suspicious patterns
  • Validate on both client and server side

2. Output Encoding

  • HTML entity encoding
  • JavaScript encoding
  • URL encoding
  • CSS encoding

3. Content Security Policy (CSP)

<meta
  http-equiv="Content-Security-Policy"
  content="default-src 'self'; script-src 'self' 'unsafe-inline'"
/>

4. Sanitization Libraries

  • DOMPurify for client-side
  • OWASP Java Encoder
  • Microsoft AntiXSS Library

Framework-Specific Protection

React

// Safe by default - automatically escapes
const userInput = "<script>alert('xss')</script>";
return <div>{userInput}</div>; // Renders as text

// Dangerous - use with caution
return <div dangerouslySetInnerHTML={{ __html: userInput }} />;

Vue.js

<!-- Safe -->
<div>{{ userInput }}</div>

<!-- Dangerous -->
<div v-html="userInput"></div>

Testing for XSS

Manual Testing

  • Try common payloads
  • Test all input fields
  • Check URL parameters
  • Inspect HTTP headers

Automated Tools

  • OWASP ZAP
  • Burp Suite
  • XSStrike
  • Nuclei

Best Practices

  1. Never trust user input
  2. Use security headers (CSP, X-XSS-Protection)
  3. Keep frameworks updated
  4. Implement proper session management
  5. Use HTTPS everywhere
  6. Regular security audits

Resources