Lecture 10 - Web Application Security - XSS, CSRF & SSRF
- Theme: Understanding three different ways attackers abuse browsers, sessions, and servers
| Attack | Full Name | What Happens |
|---|---|---|
| XSS | Cross-Site Scripting | Browser executes attacker-controlled code |
| CSRF | Cross-Site Request Forgery | Browser performs an unwanted action |
| SSRF | Server-Side Request Forgery | Server sends an attacker-chosen request |
- Quick summary:
- XSS → Code in Browser
- CSRF → Action as Victim
- SSRF → Request from Server
Analogy: Think of a bank.
- XSS = someone slips a fake instruction note into the bank's official brochure, and you follow it because it came from the bank.
- CSRF = someone tricks you (already verified at the counter) into signing a withdrawal slip you didn't mean to sign.
- SSRF = someone tricks a bank employee into walking into the locked back vault and fetching something for them.
01 - Cross-Site Scripting (XSS)
- Definition: Attacker-controlled content executes in a trusted website's browser context
- Attackers inject malicious client-side code — usually JavaScript — into trusted websites
Why It Happens
- The application treats untrusted input as executable markup or code
What an Attacker Can Do
- Read accessible data
- Perform actions as the victim
- Alter pages or capture input
Analogy: A website is like a stage, and the browser is an actor who reads everything in the script out loud. If the website lets an audience member scribble a line into the script, the actor will perform it — no questions asked — because it's on the official script.

Typical XSS Workflow
- Attacker injects malicious JavaScript into a webpage (via form, URL, etc.)
- The server stores or reflects the script in a response
- User visits the compromised page or clicks a malicious link
- Browser executes the injected script
- Script steals data, impersonates the user, or redirects traffic
- Data is sent back to the attacker's server
02 — XSS Types and Their Overlap
| Type | Delivery / Persistence | Unsafe Processing | ส่วนใหญ่อยู่บน |
|---|---|---|---|
| Reflected | Input returns in one response | Server output or client code | Browser |
| Stored | Input persists for later users | Server output or client code | Database / ?? |
| DOM-based | Data reaches a browser-side sink | Client-side JavaScript |
- Delivery and execution are different classification axes
- Delivery = how the payload gets to the victim (one-time vs. saved)
- Execution = where the unsafe processing happens (server vs. browser JS)
- DOM-based XSS can be reflected or stored
- Blind XSS — execution happens in an unseen interface, often an admin page
- The attacker can't see it fire directly; it triggers later when someone else (e.g., admin) views it
Analogy:
- Reflected = a prank caller who has to call each person individually.
- Stored = a prank poster glued to the community board — everyone who walks by sees it.
- DOM-based = the trap is in your own phone's app logic, not in what the server sent.
- Blind = leaving a booby-trapped note in the manager's inbox and never seeing them open it.
Reflected XSS
- The application echoes request input into an executable response context
- Non-persistent: each victim must trigger a crafted request
How the Attack Works
- Attacker sends a crafted link or form
- Victim submits it to the trusted site
- Server returns unescaped input
- Browser executes it with the site's privileges
- Typical sources: search terms, URL parameters, form fields, and error messages
Request and Response Example
- Request parameter
q(decoded):
<script>alert("XSS")</script>- Unsafe HTML response:
<h2>Results for: <script>alert("XSS")</script></h2>- Impact: accessible data theft, page manipulation, or authenticated actions as the victim
Prevention
- Encode for the output context and use auto-escaping templates
- For HTML text:
<becomes<and>becomes>, so input displays as text - Add a restrictive CSP
- ⚠️ Input validation alone cannot prevent XSS
Analogy: It's like a parrot at the bank entrance that repeats whatever you say to it. If you whisper "Open the vault!" into the parrot and send a friend there, the parrot shouts it in the bank's own voice — and the staff obey.

Reflected XSS Diagram Steps
- The attacker crafts a URL containing the malicious string and sends it to the victim
- The user is tricked into opening the link and requesting the malicious URL from the website
- The website includes the malicious string in its response to the user
- The user's browser interprets the malicious JavaScript in the server's response as part of the legitimate web page and executes the code
- The user's sensitive information is sent to the attacker's server
Why a Legitimate Server Returns Malicious Code
- A search page repeats the search term. Unsafe HTML construction creates the flaw.
1. Normal Search
- User input:
laptop - Server response:
<h2>You searched for: laptop</h2>2. Vulnerable Server Code
html = "<h2>You searched for: " + userInput + "</h2>";- The server joins input directly into HTML (string concatenation)
3. Attacker-Controlled Input
<script>alert("XSS")</script>4. Response from the Legitimate Site
<h2>You searched for:
<script>alert("XSS")</script>
</h2>- The victim's browser treats the injected part as code under the legitimate site's origin
Key Points
- The server intends to display a search term
- Missing output encoding lets input become code
- Fix: use an auto-escaping template so the payload displays as plain text
Analogy: It's like a sign-maker who prints exactly what customers write on the order form. Normally "Happy Birthday" gets printed. But if someone writes "OFFICIAL NOTICE: Give your password to the bearer of this sign," it gets printed on the official company letterhead too.
Unescaped Input and Safe Output
- Escaping encodes special characters so the browser displays input as text
User Input
<script>alert("XSS")</script>Unescaped Output ❌
<script>alert("XSS")</script>- The server inserts the input directly into HTML
- The browser interprets it as executable code
- Result: the script may run
Escaped Output for HTML Text ✅
<script>alert("XSS")</script>- The server encodes
<as<and>as> - The browser displays the original input as text
- Result: this input does not execute as a script
- Correct encoding depends on the output context: HTML text, attributes, URLs, or JavaScript
- HTML encode/escape tool: https://emn178.github.io/online-tools/html_encode.html
Analogy: Escaping is like putting quotation marks around something someone said. "Fire the manager" in quotes is just a reported sentence, not an order. Escaping turns commands into quotes.
HTML Escaping / HTML Encoding
| Character | HTML Escape | Meaning |
|---|---|---|
< | < | less than |
> | > | greater than |
& | & | ampersand |
" | " | double quote |
' | ' | single quote |
- Exact mappings:
- Use context-aware output encoding and auto-escaping templates
- For HTML text, escape special characters such as
<→<and>→> - This causes untrusted input to be rendered as text instead of executable HTML/JavaScript
Memory trick:
lt= less than,gt= greater than,amp= ampersand,quot= quote,#39= ASCII code 39 for'.
Stored (Persistent) XSS
- The application saves malicious input and renders it unsafely for later viewers
- One submission can affect many users during normal browsing
How the Attack Works
- Attacker posts a malicious comment
- Application saves it in a database
- Users or admins open the affected page
- Browser executes the stored content with the trusted site's privileges
- Entry points: comments, reviews, profiles, shared messages, support tickets, and logs
Comment Example
- Stored comment (harmless demo):
<script>alert("XSS")</script>- Unsafe server-generated HTML:
<div class="comment">
<script>alert("XSS")</script>
</div>- Impact: accessible data theft or actions as a victim
- Admin views may expose higher privileges
Prevention
- Plain text: encode at each output context and use safe DOM APIs such as
textContent - Rich HTML: use a maintained sanitizer to allow only safe markup
- Add a restrictive CSP
- ⚠️ Storing content in a database does not make it safe
Analogy: Reflected XSS is a prank call; Stored XSS is a landmine buried in a public park. The attacker plants it once, and every visitor who steps there is hit — including the park ranger (admin), who has the keys to everything.

Stored XSS Diagram Steps
- Attacker injects a malicious payload into a vulnerable website
- Malicious payload is stored in the server's database
- Victim visits the vulnerable page
- Server responds with the page containing the malicious payload
- Malicious payload is executed in the victim's browser
- Browser sends victim's sensitive information back to the attacker
DOM-Based XSS
- DOM = Document Object Model
- The browser represents an HTML page as a tree of objects (nodes)
- JavaScript uses this model to read or change elements, attributes, and text
How the Vulnerability Occurs
- Source: attacker-controlled data, such as a URL parameter, fragment, or message
- Sink: an API that interprets data as HTML or code, such as
innerHTMLoreval() - Unsafe JavaScript connects the source to a sink
- *The flaw occurs in browser-side processing
- The server need not echo the payload
Vulnerable Code
const output = document.getElementById("output");
const msg = new URLSearchParams(location.search).get("msg");
output.innerHTML = msg;Safer Output for Plain Text
output.textContent = msg;innerHTMLparses markup- ==
textContentdisplays the input as text== - If rich HTML is required, sanitize it
- Add restrictive CSP and consider Trusted Types
- Content Security Policy (CSP), enforce at the browser
Analogy: Source = the water coming from an unknown pipe. Sink = where it ends up.
innerHTMLis a sink connected to the engine (it'll burn whatever comes in as fuel);textContentis a sink that just pours it into a display glass for you to look at.
DOM-Based XSS: Unsafe and Safe Paths
- DOM: the browser's tree of page elements and text that JavaScript can modify
Flow

- Attacker-controlled data: URL query parameter
msg= untrusted input - Browser JavaScript reads
msg - Then it goes one of two ways:
| Unsafe Sink | Safe Text Sink |
|---|---|
output.innerHTML = msg | output.textContent = msg |
| Parses input as HTML | Creates plain text |
| DOM gains active markup | DOM gains a text node |
| Event handler can execute | Payload displays as text |
- Example
msg(decoded):
<img src=x onerror=alert("XSS")>- Same input, different handling: HTML parsing can activate code; plain text output displays it
Why
<img src=x onerror=...>works:src=xis a broken image, so loading fails → the browser firesonerror→ the attacker's JavaScript runs. No<script>tag needed!

DOM-Based XSS Diagram Steps
- Identify Attacker-Controlled Input: The attacker identifies data sources controlled by the client, such as:
- URL parameters
- URL fragments (
location.hash) - Cookies
localStorage,sessionStorage- Other browser-controlled values
- Inject Malicious Input: The attacker supplies harmful JavaScript through one of these client-side inputs
- Unsafe DOM Manipulation: The application's JavaScript inserts the attacker-controlled data into the DOM using unsafe methods like
innerHTML,outerHTML,document.write(), orinsertAdjacentHTML()without proper output encoding or sanitization - Script Execution: The browser interprets the injected content as executable HTML or JavaScript and runs the attacker's code
Example: DOM-Based XSS from a URL Parameter
- The problem: untrusted URL input is inserted into the page as HTML
1. Attacker Crafts a URL
https://bank.example/welcome?user=<img src=x onerror=alert('XSS')>
- The
uservalue is attacker-controlled
2. Page Reads the Parameter
const user = params.get("user");
welcome.innerHTML = `Welcome back, ${user}!`;- Risky sink:
innerHTMLtreats input as markup
3. Browser Interprets It
Welcome back, <img src=x onerror=...> !- The injected HTML creates an element; its event handler can execute JavaScript
Safer Version
welcome.textContent = `Welcome back, ${user}!`;Why This Is Safer
textContentdisplays the value as text instead of parsing it as HTML- Also validate input and use a restrictive Content Security Policy as defense in depth
- Key rule: XSS occurs when untrusted data reaches an HTML/JS execution context without safe output handling
DOM XSS Mitigation (IMPORTANT MAK!)
- Use Safe DOM APIs
- ✅ Use:
textContent,innerText, orcreateTextNode() - ❌ Avoid:
innerHTML,outerHTML,document.write(), orinsertAdjacentHTML()when displaying untrusted data
- ✅ Use:
- Treat Client-Side Input as Untrusted
- Treat data from URL parameters, URL fragments (
location.hash), cookies,localStorage,sessionStorage, and other browser-controlled sources as untrusted - Apply appropriate encoding or sanitization before inserting any data into the DOM
- Treat data from URL parameters, URL fragments (
- Avoid Dangerous JavaScript Functions
- Steer clear of
eval(),Function(),setTimeout()with string arguments,setInterval()with string arguments, and other APIs that execute dynamically generated code
- Steer clear of
- Implement Content Security Policy (CSP)
- Use CSP headers to restrict which sources can execute scripts and reduce the impact of any injected JavaScript
- Use Modern Frameworks Safely
- Use frameworks that automatically escape user input by default
- Avoid bypassing built-in protections unless the content has been properly sanitized
- (e.g., React's
dangerouslySetInnerHTML, Vue'sv-html, Angular'sbypassSecurityTrust...)
- (e.g., React's
Content Security Policy (CSP): Defense Against XSS
Related
- CSP is defined by the website/server and enforced by the browser
How It Works
- Web Server - defines the security policy
- CSP Header - specifies allowed script sources
- Browser - enforces: allow or block
Example CSP Response Header
Content-Security-Policy: script-src 'self'- → Allow JavaScript only from the site's own origin
Injected XSS Attempt
<script src="https://evil.example/attack.js"></script>- ✕ Browser blocks the unauthorized external script
CSP = Defense in Depth
- Primary XSS defense: safe output handling / encoding → avoid unsafe
innerHTML→ validate input - Additional layer: CSP limits what injected code is allowed to execute
Analogy: CSP is like a guest list at a club. The club owner (server) writes the list; the bouncer (browser) enforces it. Even if a troublemaker sneaks a fake invitation inside (XSS), the bouncer says "you're not from
'self', you're not getting in." But the list is a backup — you still shouldn't be handing out blank invitations in the first place.
06 — XSS Prevention
| Situation | Defense |
|---|---|
| Rendering plain text | Use context-aware encoding and auto-escaping templates |
| Updating the DOM | Prefer textContent and safe element APIs. Avoid eval() |
| Allowing rich HTML | Use a maintained sanitizer. Keep it patched |
| Handling URLs | Validate allowed schemes and encode URL components |
| Adding browser controls | Deploy a restrictive Content Security Policy. Consider Trusted Types |
| Protecting sessions | Use HttpOnly and Secure cookies, with suitable SameSite |
- Encoding depends on context
- ⚠️ CSP and cookie flags add protection but cannot repair unsafe rendering
Note on cookie flags:
HttpOnly→ JavaScript cannot read the cookie (so XSS can't steal it viadocument.cookie)Secure→ cookie only sent over HTTPSSameSite→ controls cross-site sending (mainly a CSRF defense)
CSRF and SSRF
Cross-Site Request Forgery (CSRF)

CSRF Diagram Steps
- Victim logs into bank account
- Bank assigns victim a validation token (session)
- Hacker sends forged request disguised as legitimate communication from the bank
- Victim unknowingly forwards the request to the bank
- Forged request is executed by the bank using the previously assigned validation token
CSRF Example
- Victim is logged into
bank.com(with a valid session cookie) - Attacker hosts a malicious page:
<img src="https://bank.com/transfer?to=attacker&amount=5000">- Victim visits the attacker's page; the browser automatically sends the request with the valid cookie
- Bank's server processes the transfer believing the user initiated it
- Attack vector: Browser auto-sends credentials (cookies/session)
- Impact: Unauthorized action as the victim user
Analogy: You're wearing a VIP wristband at a festival (session cookie). A stranger hands you a sealed envelope and says "drop this at the bar." The bartender sees your wristband and pours free drinks onto your tab — they never check whether you actually wanted to order. The wristband is checked, not your intent.
Key insight: The attacker never sees the cookie. They just make the victim's browser use it.
CSRF Signals (Detection)
- Requests with no/invalid CSRF token but containing a valid session cookie and performing a state change
- High volume of similar cross-origin requests targeting state-changing endpoints (check Referer/Origin)
- New account actions initiated immediately after login (possible login CSRF)
- Login CSRF: attacker logs the victim into the attacker's account, so the victim's activity is recorded where the attacker can see it
CSRF Mitigation
- Implement per-request anti-CSRF tokens (synchronizer token in body/header)
- Enforce
SameSite=Lax/Stricton cookies (Lax covers most cases)- It is set by the server/application, but enforced by the browser (client side)
- Validate Origin (or Referer) for state-changing requests
- Require re-auth (2FA/password) for sensitive transactions
Analogy for CSRF tokens: Besides your wristband, the bartender now also asks for a secret word that was printed only on your menu card. The stranger's envelope doesn't contain that word, so the order is rejected.
SameSite Cookies — How They Mitigate CSRF
- SameSite tells the browser when a cookie may be sent with a request initiated from another site
Flow
- evil.com — attacker triggers a forged state-changing request
- Victim's Browser — decides whether the
bank.comsession cookie can be attachedSameSite=Lax/Strictblocks the cookie in many cross-site request contexts
- bank.com — request is accepted only if a valid session is present
Three SameSite Modes
| Mode | Behavior | CSRF Protection |
|---|---|---|
SameSite=Strict | Cookie only in same-site contexts | Strongest CSRF protection |
SameSite=Lax | Also allows some top-level cross-site navigation | Good default for most apps |
SameSite=None | Cookie may be sent cross-site; requires Secure | No SameSite-based CSRF protection |
- Key idea: CSRF relies on the browser automatically sending authentication cookies. SameSite restricts when that can happen.
- Server sends:
Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=LaxAnalogy:
- Strict = your house key only works if you walk in through your own front gate.
- Lax = it also works if a friend's link brings you to your front door normally (top-level navigation, e.g., clicking a link), but not via sneaky side windows (
<img>, hidden form POSTs).- None = the key works no matter who sends you there (must at least be on a secure road — HTTPS).
SSRF (Server-Side Request Forgery)
- Definition: A type of vulnerability that allows an attacker to force an application to issue requests on behalf of the attacker, to unintended resources

SSRF Diagram Steps
- Attacker manipulates the original request (request A carries a hidden request B)
- The vulnerable application receives the manipulated request and processes it
- The malicious request ("B") is executed by the application against target server(s)/network(s)
Analogy: The server is a trusted office assistant who can walk anywhere in the building, including restricted floors. You can't get past security yourself, so you hand the assistant a note: "Please go fetch the file from Room 127 (the admin office)." The assistant does it — because they're allowed in, and nobody checked where the note was pointing.
SSRF Example: Server-Side Request Forgery
- SSRF tricks a vulnerable server into making a request to a destination chosen by the attacker
Normal Function
https://example.com/fetch?url=https://images.example/image.jpg
- The server fetches an expected external image
Attack Flow
- Attacker — supplies a crafted URL
- Vulnerable Web App — accepts the destination without sufficient validation
- Server HTTP Client — makes the request on the attacker's behalf
- Internal Service —
127.0.0.1:8080/admin
Crafted Request
https://example.com/fetch?url=http://127.0.0.1:8080/admin
Why This Matters
- The server may reach internal services that the attacker cannot access directly from the Internet
Possible Cloud Impact
- In some cloud configurations, SSRF may expose metadata or credentials if metadata protections are insufficient
- (e.g., the cloud instance metadata service at
169.254.169.254)
- (e.g., the cloud instance metadata service at
- Attack vector: unvalidated user-controlled destination → server-side HTTP client
- Potential impact: internal access, data exposure, reconnaissance
- Key idea: the attacker does not access the internal service directly — the vulnerable server makes the request
Why
127.0.0.1? It's localhost — "this machine itself." From the outside it means nothing, but from the server's point of view it's its own private back door.
SSRF Signals (Detection)
- Server making outbound connections to unusual internal IPs or cloud metadata addresses
- Outbound = inside → out
- Unexpected spikes of outbound requests to internal ranges from web processes
- Application logs showing fetches to attacker-controlled domains
- DNS logs showing lookups for odd subdomains created by the attacker (rebind or interactsh)
- interactsh = an out-of-band interaction tool attackers use to confirm a server reached out to them
Exploitation Techniques
CSRF
- Attacker tricks user's browser to send authenticated requests
- Techniques:
- Malicious pages using
<img> - Auto-submitted forms
- Login CSRF
- XSS-assisted CSRF (XSS can read the CSRF token and bypass the defense)
- Malicious pages using
SSRF
- Attacker tricks server to make requests
- Techniques:
- Attacker-supplied URL fetch
- Localhost / metadata access
- Port scanning (probe internal ports via the server)
- Protocol abuse (
gopher://,file://) - DNS rebinding (domain resolves to a safe IP at check time, then to an internal IP at fetch time)
- Encoding tricks (e.g., alternate IP notations to bypass filters)
CSRF vs SSRF
| Aspect | CSRF (Cross-Site Request Forgery) | SSRF (Server-Side Request Forgery) |
|---|---|---|
| Target | The user's authenticated session | The server itself (backend) |
| Victim | A user/browser tricked into sending a request | The server tricked into sending a request |
| Attacker goal | Make a logged-in user perform unwanted actions | Make the server access unintended internal/external resources |
| Attack origin | Malicious site or page in user's browser | Malicious input sent to a vulnerable server |
| Execution place | Client-side (through user's browser) | Server-side (through backend HTTP requests) |
Memory trick: CSRF → Client gets fooled. SSRF → Server gets fooled.
XSS vs. CSRF vs. SSRF — What Is Being Tricked?
- They are different web attacks:
- XSS executes code in the browser
- CSRF abuses the browser's authenticated session (mostly from cookie)
- SSRF abuses the server's network access
| XSS | CSRF | SSRF | |
|---|---|---|---|
| What's tricked | Trick the BROWSER to execute code | Trick the BROWSER to send an action | Trick the SERVER to send a request |
| Flow | Attacker → Web App → Browser | Attacker Site → Victim Browser → Target Server | Attacker → Web Server → Internal Service |
| Description | Malicious script is injected into content and executes under the vulnerable site's origin | A logged-in victim is induced to send an unwanted request; the browser may attach session cookies | The vulnerable server is induced to fetch an attacker-chosen URL, possibly reaching internal resources |
| Example | Unescaped <script>…</script> | Forged POST /transfer | /fetch?url=http://127.0.0.1/admin |
- Remember:
- XSS = execute code in browser
- CSRF = perform action as victim (client)
- SSRF = make server request another resource
CSRF vs. SSRF: Detection & Prevention
- Different attack paths require different defensive controls
| # | Defense Area | CSRF — Protect the User Session | SSRF — Protect Server Outbound Access |
|---|---|---|---|
| 1 | Token / request proof | Use anti-CSRF tokens; set session cookies to SameSite=Lax/Strict | Not applicable — SSRF does not rely on the victim's browser session |
| 2 | Request validation | Validate Origin and, where appropriate, Referer on state-changing requests | Parse and validate destination URLs; allow only required schemes/hosts |
| 3 | Least privilege | Do not let ambient cookie authentication authorize unnecessary sensitive actions | Restrict server egress to only the networks and services the application needs |
| 4 | Network hardening | Usually not a primary CSRF control | Block loopback, link-local, private/internal and cloud-metadata destinations as appropriate |
| 5 | Framework support | Enable built-in CSRF middleware/protection in frameworks such as Django, Laravel, or Spring Security | Use centralized URL validation/allowlists; reject unsafe redirects and unexpected schemes |
| 6 | Logging & monitoring | Log failed CSRF checks, suspicious origins, and abnormal state-changing requests | Monitor unexpected outbound requests, blocked destinations, and repeated URL-validation failures |
- Key distinction: CSRF abuses the browser's authenticated session; SSRF abuses the server's ability to make outbound requests
Address cheat sheet for SSRF blocking:
- Loopback:
127.0.0.0/8,::1- Link-local (incl. cloud metadata):
169.254.0.0/16- Private:
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16