Description
Cross-Site Scripting (XSS) is a common security vulnerability found in web applications. It allows an attacker to inject malicious scripts (usually JavaScript) into content that other users will view. When victims visit a compromised web page, the malicious script executes in their browser, potentially stealing sensitive data, manipulating DOM, hijacking sessions, or performing actions on behalf of the user.
XSS is one of the most prevalent web vulnerabilities and is categorized in the OWASP Top 10 list of critical security risks.
How It Works
In XSS attacks, untrusted user input is injected into a web page and executed in the context of another user’s browser session.
Flow:
- Attacker sends or stores a malicious script on a trusted website.
- Victim visits the website.
- Browser executes the script as part of the page.
- Script can access cookies, session tokens, DOM, etc.
Types of XSS
1. Stored XSS (Persistent)
- The malicious script is stored on the server (e.g., in a database or comment field).
- Every time the data is retrieved, the script executes for all users.
- Most dangerous as it impacts many users.
Example:
<!-- Attacker posts a comment -->
<script>alert('Hacked!');</script>
2. Reflected XSS
- The script is included in a URL or input, and is immediately reflected back in the response.
- Requires the victim to click a malicious link.
Example:
https://example.com/search?q=<script>alert('XSS')</script>
3. DOM-Based XSS
- The vulnerability is in the client-side JavaScript code, not server-side rendering.
- The page contains a script that dynamically manipulates DOM using unsanitized user input.
Example:
let search = location.hash.substring(1);
document.body.innerHTML += "Search: " + search;
If #<script>alert(1)</script> is added to the URL, the script executes.
Real-World Risks
| Risk | Impact |
|---|---|
| Cookie Theft | Hijack sessions by stealing authentication tokens |
| Keylogging | Capture keystrokes to steal credentials |
| Phishing | Inject fake login forms |
| Defacement | Modify the appearance of the page |
| Browser Exploits | Deliver further malware or spyware |
| CSRF Automation | Chain with Cross-Site Request Forgery for deeper attacks |
XSS Payload Examples
<script>alert('XSS')</script>
<img src="x" onerror="alert('Hacked')" />
<a href="javascript:alert('XSS')">Click me</a>
<svg onload=alert('XSS')>
<iframe src="javascript:alert('XSS')"></iframe>
XSS in Action: Example
HTML Vulnerable Form
<form method="get">
Search: <input name="q" value="">
</form>
Server Output:
Search results for: <b>[user input here]</b>
If q=<script>alert(1)</script> → Output:
Search results for: <b><script>alert(1)</script></b>
Mitigation Techniques
✅ Input Validation
- Validate input formats (e.g., email, phone number).
- Reject unexpected or dangerous characters.
✅ Output Encoding
- Convert special characters before rendering in HTML:
<→<>→>"→"'→'
✅ Use Security Libraries
- Use frameworks that auto-escape HTML (e.g., React, Angular).
- Use
DOMPurifyor similar libraries for HTML sanitization.
✅ Content Security Policy (CSP)
- Defines allowed sources for scripts and blocks inline JavaScript:
Content-Security-Policy: default-src 'self'; script-src 'self'
✅ HTTPOnly and Secure Cookies
- Prevent JavaScript access to sensitive cookies:
Set-Cookie: sessionId=abc123; HttpOnly; Secure
✅ Avoid eval() and innerHTML
- Use
textContentinstead ofinnerHTMLto prevent script injection. - Never use
eval()on untrusted inputs.
XSS Prevention in JavaScript
function escapeHTML(str) {
return str.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
XSS Testing and Detection
| Tool / Method | Purpose |
|---|---|
| Burp Suite | Automated scanning |
| OWASP ZAP | Intercept and modify requests |
| Manual Testing | Craft payloads to inject in parameters |
| Selenium + Scripts | Test in browser context |
| Browser DevTools | Monitor and edit DOM in real time |
XSS in Modern Front-End Frameworks
| Framework | XSS Defense Mechanism |
|---|---|
| React | Escapes output by default in JSX |
| Angular | Uses Angular Sanitizer and strict binding |
| Vue.js | Auto-escapes text, but needs caution with v-html |
| jQuery | Does not auto-escape—developers must sanitize manually |
Legal and Ethical Concerns
- Exploiting XSS without permission is illegal.
- Ethical hackers use responsible disclosure to inform organizations.
- XSS vulnerabilities are often eligible for bug bounty programs.
Conclusion
XSS (Cross-Site Scripting) remains a serious threat in modern web applications due to its ability to exploit trust between users and websites. It’s deceptively simple to implement and highly effective if left unmitigated.
Web developers, testers, and security engineers must understand how XSS works to build secure applications, audit codebases, and protect users from malicious exploits. When combined with strong security headers and development best practices, XSS vulnerabilities can be drastically reduced—if not completely eliminated.
Related Terms
- CSP (Content Security Policy)
- XSRF / CSRF (Cross-Site Request Forgery)
- DOM-Based XSS
- Injection
- Sanitization
- URL Encoding
- HTML Encoding
- Session Hijacking
- Cookie Theft
- JavaScript Injection
- OWASP Top 10
- Web Application Firewall (WAF)
- Bug Bounty
- Input Validation
- Browser Sandbox









