Skip to main content

🎨 XSS

Injecting malicious scripts into websites

The Graffiti Analogy

A public bulletin board in a trusted location:

ScenarioWhat Happens
You put up a noticeMany people trust it's official
Attacker puts up fake noticeMany people may follow the instructions
Nobody questions itBecause the board is "trusted"

XSS is digital graffiti. Attackers inject their code into websites, and visitors' browsers run it as if it were legitimate.


What Is XSS?

XSS = Cross-Site Scripting

StepWhat Happens
1Attacker injects malicious JavaScript into a website
2Other users visit the site
3Their browsers execute the attacker's script
4Browser trusts it because it came from a "trusted" site

What Malicious Scripts Can Do

AttackDamage
Steal cookies/sessionsAccount takeover
Capture keystrokesPassword theft
Redirect to fake pagesPhishing
Modify page contentSpread misinformation
Make requests as userUnauthorized actions

Types of XSS

1. Stored XSS (Most Dangerous)

Attack is saved permanently on the server.

ComponentExample
VectorComment, profile, forum post
PersistenceStored in database
VictimsEvery user who views the page
ImpactMass attack, persistent

Example: Attacker posts a comment containing <script>stealCookies()</script>. Every user who views the comment page runs the script.

2. Reflected XSS

Attack is reflected back from the request.

ComponentExample
VectorSearch query, error message
PersistenceNot stored, in URL
VictimsUsers who click malicious link
ImpactTargeted attack via link

Example: URL site.com/search?q=<script>evil()</script> and page displays the query unsanitized.

3. DOM-Based XSS

Attack manipulates the DOM directly in browser.

ComponentExample
VectorURL fragment, client-side data
PersistenceMostly client-side
VictimsUsers who visit crafted URL
DetectionHarder (server may not see it)

Example: JavaScript reads from location.hash and writes to innerHTML without sanitization.


Attack Examples

Injected script:
  Send document.cookie to attacker's server

Result:
  Attacker has victim's session token
  → Account takeover

Keylogging

Injected script records every keystroke and sends to attacker. Captures passwords, credit cards, private messages.

Fake Login Form

Script replaces page content with fake login form. User sees trusted domain, enters password, credentials go to attacker.


Prevention Methods

1. Output Encoding (Escaping)

Convert special characters to escaped versions:

CharacterEncoded
<&lt;
>&gt;
"&quot;
'&#x27;
&&amp;

Input: <script>alert('XSS')</script> Output: &lt;script&gt;alert('XSS')&lt;/script&gt;

Browser shows text, doesn't execute!

2. Content Security Policy (CSP)

HTTP header that restricts script sources:

CSP PolicyEffect
script-src 'self'Allows same-origin scripts
script-src 'none'No scripts at all
script-src 'self' https://trusted.comSelf + specific CDN

Inline scripts and unknown sources are blocked.

3. HttpOnly Cookies

AttributeEffect
HttpOnlyJavaScript cannot access cookie
HTTPS-onlySent only over HTTPS
SameSitePrevents cross-site sending

Even if XSS exists, session cookies are protected.

4. Input Validation

ValidationExample
Allowlist charactersUsername: letters and numbers
Reject dangerous patternsNo <script>, javascript:
Type checkingAge should be a number

Validation helps but is NOT sufficient alone. Encode output for the right context.


Defense in Depth

No single protection is enough. Use multiple layers:

LayerProtection
InputValidate and sanitize
OutputEncode for context (HTML, JS, URL)
HeadersCSP, X-Content-Type-Options
CookiesHttpOnly, HTTPS-only, SameSite
FrameworkUse built-in XSS protections

Common Mistakes

1. Trusting User Input

❌ Bad✅ Good
Display user input rawEncode before display
Trust hidden fieldsValidate server-side

2. Wrong Encoding Context

ContextRequired Encoding
HTML bodyHTML entity encoding
HTML attributeAttribute encoding
JavaScriptJavaScript string encoding
URLURL encoding

Each context needs different encoding!

3. Allowing innerHTML

innerHTML = userInput is dangerous. Use textContent for text, or sanitize HTML with a library like DOMPurify.

4. Incomplete CSP

CSP with 'unsafe-inline' or 'unsafe-eval' defeats much of its purpose.


Testing for XSS

MethodApproach
Manual testingTry <script>alert(1)</script> in inputs
Automated scannersOWASP ZAP, Burp Suite
Browser DevToolsCheck what's rendered
CSP reportsMonitor blocked violations

FAQ

Q: Is XSS still relevant?

Extremely. XSS is consistently in OWASP Top 10. Modern frameworks help but don't eliminate the risk.

Q: Which is worse: stored or reflected?

Stored XSS is often more dangerous (it can affect many users), but reflected XSS is more common.

Q: Do frameworks protect me automatically?

Most modern frameworks (React, Angular, Vue) escape output by default. But dangerouslySetInnerHTML or v-html bypass protections.

Q: What's the difference between XSS and SQL injection?

XSS attacks users' browsers. SQL injection attacks the database. Both are injection attacks, different targets.


Summary

XSS allows attackers to inject malicious scripts into websites, compromising users who visit.

Key Takeaways:

  • Stored XSS: saved on server, can affect many users
  • Reflected XSS: in URL, requires clicking link
  • DOM-based XSS: client-side manipulation
  • Output encoding: convert < to &lt;
  • CSP headers: restrict script sources
  • HttpOnly cookies: protect sessions
  • Defense in depth: multiple layers
  • Treat user input as untrusted

XSS is a very common web vulnerability - learn to prevent it!

Leave a Comment

Comments (0)

Be the first to comment on this concept.

Comments are approved automatically.