Understanding XSS Attacks
Cross-Site Scripting (XSS) occurs when malicious scripts are injected into web pages viewed by other users. It's one of the most common web vulnerabilities.
Types of XSS
There are three main types of XSS attacks:
XSS Categories
- Reflected XSS: Malicious script is reflected off the web server
- Stored XSS: Malicious script is stored on the server
- DOM-based XSS: Vulnerability exists in client-side code
Input Validation and Sanitization
// PHP example
$userInput = $_POST['comment'];
$sanitizedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $sanitizedInput;
Always validate and sanitize user input before processing or displaying it:
Output Encoding
// JavaScript encoding for HTML context
function encodeForHTML(str) {
return str.replace(/[&<>"']/g, function(match) {
return {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}[match];
});
}
Encode output based on the context where it will be used:
Content Security Policy (CSP)
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline';
Implement CSP to prevent XSS attacks by controlling which scripts can execute:
Additional Prevention Measures
Other important XSS prevention techniques:
XSS Prevention Checklist
- Use proper input validation and sanitization
- Implement output encoding for all contexts
- Use Content Security Policy (CSP)
- Set secure HTTP headers
- Use templating engines with auto-escaping
- Regular security testing and code reviews