XSS (Cross-Site Scripting) is one of the most common web application vulnerabilities. It allows attackers to inject malicious client-side scripts (usually JavaScript) into web pages that other users view, bypassing the same-origin policy and potentially stealing credentials, session tokens or performing actions on behalf of the victim.
Types of XSS
- Reflected XSS — The malicious script is embedded in a URL. When the victim clicks the link, the script is reflected off the server and executed in their browser. Not stored; requires the victim to click a crafted link.
- Stored XSS — The script is permanently stored in a database (e.g. in a comment or profile field) and executed whenever any user views the affected page. The most dangerous type.
- DOM-based XSS — The vulnerability exists in client-side JavaScript code that reads from the DOM without sanitisation. The server is not involved in the attack path.
What Attackers Can Do with XSS
- Steal session cookies and hijack accounts.
- Log keystrokes and capture passwords.
- Redirect users to phishing sites.
- Perform actions on behalf of the user (like a CSRF attack).
- Deface web pages or display fake content.
Preventing XSS
- Output encoding — HTML-encode user-supplied data before rendering it in the browser. This is the primary defence.
- Content Security Policy (CSP) — Restricts which scripts can execute on a page.
- HttpOnly cookies — Prevent JavaScript from accessing session cookies.
- Input validation — Reject obviously malicious input on the server side.
- Use a framework — Modern frameworks like React, Angular and ASP.NET Core encode output by default.