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
- Never trust user input
- Use security headers (CSP, X-XSS-Protection)
- Keep frameworks updated
- Implement proper session management
- Use HTTPS everywhere
- Regular security audits