Lecture 10 - Web Application Security - XSS, CSRF & SSRF

Lecture 10 - Web Application Security - XSS, CSRF & SSRF

Updated 14 Oct 2026

  • Theme: Understanding three different ways attackers abuse browsers, sessions, and servers
AttackFull NameWhat Happens
XSSCross-Site ScriptingBrowser executes attacker-controlled code
CSRFCross-Site Request ForgeryBrowser performs an unwanted action
SSRFServer-Side Request ForgeryServer 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

  1. Attacker injects malicious JavaScript into a webpage (via form, URL, etc.)
  2. The server stores or reflects the script in a response
  3. User visits the compromised page or clicks a malicious link
  4. Browser executes the injected script
  5. Script steals data, impersonates the user, or redirects traffic
  6. Data is sent back to the attacker's server

02 — XSS Types and Their Overlap

TypeDelivery / PersistenceUnsafe Processingส่วนใหญ่อยู่บน
ReflectedInput returns in one responseServer output or client codeBrowser
StoredInput persists for later usersServer output or client codeDatabase / ??
DOM-basedData reaches a browser-side sinkClient-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

  1. Attacker sends a crafted link or form
  2. Victim submits it to the trusted site
  3. Server returns unescaped input
  4. 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 &lt; and > becomes &gt;, 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

  1. The attacker crafts a URL containing the malicious string and sends it to the victim
  2. The user is tricked into opening the link and requesting the malicious URL from the website
  3. The website includes the malicious string in its response to the user
  4. The user's browser interprets the malicious JavaScript in the server's response as part of the legitimate web page and executes the code
  5. 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.
  • 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 ✅

&lt;script&gt;alert("XSS")&lt;/script&gt;
  • The server encodes < as &lt; and > as &gt;
  • 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

CharacterHTML EscapeMeaning
<&lt;less than
>&gt;greater than
&&amp;ampersand
"&quot;double quote
'&#39;single quote
  • Exact mappings:
    • <→&lt;{\texttt{<} \rightarrow \texttt{\&lt;}}
    • >→&gt;{\texttt{>} \rightarrow \texttt{\&gt;}}
    • &→&amp;{\texttt{\&} \rightarrow \texttt{\&amp;}}
    • "→&quot;{\texttt{"} \rightarrow \texttt{\&quot;}}
    • ’→&#39;{\texttt{'} \rightarrow \texttt{\&\#39;}}
  • Use context-aware output encoding and auto-escaping templates
  • For HTML text, escape special characters such as < → &lt; and > → &gt;
  • 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

  1. Attacker posts a malicious comment
  2. Application saves it in a database
  3. Users or admins open the affected page
  4. 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

  1. Attacker injects a malicious payload into a vulnerable website
  2. Malicious payload is stored in the server's database
  3. Victim visits the vulnerable page
  4. Server responds with the page containing the malicious payload
  5. Malicious payload is executed in the victim's browser
  6. 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 innerHTML or eval()
  • Unsafe JavaScript connects the source to a sink
  • Source (untrusted)→Unsafe JS→Sink (innerHTML / eval)=DOM XSS\boxed{\text{Source (untrusted)} \rightarrow \text{Unsafe JS} \rightarrow \text{Sink (innerHTML / eval)} = \text{DOM XSS}}
  • *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;
  • innerHTML parses markup
  • ==textContent displays 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. innerHTML is a sink connected to the engine (it'll burn whatever comes in as fuel); textContent is 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 SinkSafe Text Sink
output.innerHTML = msgoutput.textContent = msg
Parses input as HTMLCreates plain text
DOM gains active markupDOM gains a text node
Event handler can executePayload 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=x is a broken image, so loading fails → the browser fires onerror → the attacker's JavaScript runs. No <script> tag needed!

DOM-Based XSS Diagram Steps

  1. 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
  2. Inject Malicious Input: The attacker supplies harmful JavaScript through one of these client-side inputs
  3. Unsafe DOM Manipulation: The application's JavaScript inserts the attacker-controlled data into the DOM using unsafe methods like innerHTML, outerHTML, document.write(), or insertAdjacentHTML() without proper output encoding or sanitization
  4. 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 user value is attacker-controlled

2. Page Reads the Parameter

const user = params.get("user");
welcome.innerHTML = `Welcome back, ${user}!`;
  • Risky sink: innerHTML treats 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

  • textContent displays 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, or createTextNode()
    • ❌ Avoid: innerHTML, outerHTML, document.write(), or insertAdjacentHTML() when displaying untrusted data
  • 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
  • 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
  • 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's v-html, Angular's bypassSecurityTrust...)

Content Security Policy (CSP): Defense Against XSS

  • CSP is defined by the website/server and enforced by the browser

How It Works

  1. Web Server - defines the security policy
  2. CSP Header - specifies allowed script sources
  3. 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
  • The website defines CSP; the browser enforces it\boxed{\text{The website defines CSP; the browser enforces it}}

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

SituationDefense
Rendering plain textUse context-aware encoding and auto-escaping templates
Updating the DOMPrefer textContent and safe element APIs. Avoid eval()
Allowing rich HTMLUse a maintained sanitizer. Keep it patched
Handling URLsValidate allowed schemes and encode URL components
Adding browser controlsDeploy a restrictive Content Security Policy. Consider Trusted Types
Protecting sessionsUse 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 via document.cookie)
  • Secure → cookie only sent over HTTPS
  • SameSite → controls cross-site sending (mainly a CSRF defense)

CSRF and SSRF

Cross-Site Request Forgery (CSRF)

CSRF Diagram Steps

  1. Victim logs into bank account
  2. Bank assigns victim a validation token (session)
  3. Hacker sends forged request disguised as legitimate communication from the bank
  4. Victim unknowingly forwards the request to the bank
  5. 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/Strict on 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

  1. evil.com — attacker triggers a forged state-changing request
  2. Victim's Browser — decides whether the bank.com session cookie can be attached
    • SameSite=Lax/Strict blocks the cookie in many cross-site request contexts
  3. bank.com — request is accepted only if a valid session is present

Three SameSite Modes

ModeBehaviorCSRF Protection
SameSite=StrictCookie only in same-site contextsStrongest CSRF protection
SameSite=LaxAlso allows some top-level cross-site navigationGood default for most apps
SameSite=NoneCookie may be sent cross-site; requires SecureNo 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=Lax

Analogy:

  • 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

  1. Attacker manipulates the original request (request A carries a hidden request B)
  2. The vulnerable application receives the manipulated request and processes it
  3. 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

  1. Attacker — supplies a crafted URL
  2. Vulnerable Web App — accepts the destination without sufficient validation
  3. Server HTTP Client — makes the request on the attacker's behalf
  4. 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)
  • 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)

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

AspectCSRF (Cross-Site Request Forgery)SSRF (Server-Side Request Forgery)
TargetThe user's authenticated sessionThe server itself (backend)
VictimA user/browser tricked into sending a requestThe server tricked into sending a request
Attacker goalMake a logged-in user perform unwanted actionsMake the server access unintended internal/external resources
Attack originMalicious site or page in user's browserMalicious input sent to a vulnerable server
Execution placeClient-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
XSSCSRFSSRF
What's trickedTrick the BROWSER to execute codeTrick the BROWSER to send an actionTrick the SERVER to send a request
FlowAttacker → Web App → BrowserAttacker Site → Victim Browser → Target ServerAttacker → Web Server → Internal Service
DescriptionMalicious script is injected into content and executes under the vulnerable site's originA logged-in victim is induced to send an unwanted request; the browser may attach session cookiesThe vulnerable server is induced to fetch an attacker-chosen URL, possibly reaching internal resources
ExampleUnescaped <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 AreaCSRF — Protect the User SessionSSRF — Protect Server Outbound Access
1Token / request proofUse anti-CSRF tokens; set session cookies to SameSite=Lax/StrictNot applicable — SSRF does not rely on the victim's browser session
2Request validationValidate Origin and, where appropriate, Referer on state-changing requestsParse and validate destination URLs; allow only required schemes/hosts
3Least privilegeDo not let ambient cookie authentication authorize unnecessary sensitive actionsRestrict server egress to only the networks and services the application needs
4Network hardeningUsually not a primary CSRF controlBlock loopback, link-local, private/internal and cloud-metadata destinations as appropriate
5Framework supportEnable built-in CSRF middleware/protection in frameworks such as Django, Laravel, or Spring SecurityUse centralized URL validation/allowlists; reject unsafe redirects and unexpected schemes
6Logging & monitoringLog failed CSRF checks, suspicious origins, and abnormal state-changing requestsMonitor 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