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:

  1. Attacker sends or stores a malicious script on a trusted website.
  2. Victim visits the website.
  3. Browser executes the script as part of the page.
  4. 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

RiskImpact
Cookie TheftHijack sessions by stealing authentication tokens
KeyloggingCapture keystrokes to steal credentials
PhishingInject fake login forms
DefacementModify the appearance of the page
Browser ExploitsDeliver further malware or spyware
CSRF AutomationChain 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:
    • <&lt;
    • >&gt;
    • "&quot;
    • '&#x27;

✅ Use Security Libraries

  • Use frameworks that auto-escape HTML (e.g., React, Angular).
  • Use DOMPurify or 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 textContent instead of innerHTML to prevent script injection.
  • Never use eval() on untrusted inputs.

XSS Prevention in JavaScript

function escapeHTML(str) {
  return str.replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#x27;");
}

XSS Testing and Detection

Tool / MethodPurpose
Burp SuiteAutomated scanning
OWASP ZAPIntercept and modify requests
Manual TestingCraft payloads to inject in parameters
Selenium + ScriptsTest in browser context
Browser DevToolsMonitor and edit DOM in real time

XSS in Modern Front-End Frameworks

FrameworkXSS Defense Mechanism
ReactEscapes output by default in JSX
AngularUses Angular Sanitizer and strict binding
Vue.jsAuto-escapes text, but needs caution with v-html
jQueryDoes 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