Homemade Hardware Keylogger/PHUKD Hybrid

Regular readers of my site may know I've done a lot of work with hardware keyloggers.

Hardware Key Logging Part 1: An Overview Of USB Hardware Keyloggers, And A Review Of The KeyCarbon USB Home Mini (Text)

Hardware Key Logging Part 2: A Review Of Products From KeeLog and KeyGhost (Text)

Hardware Key Logging Part 3: A Review Of The KeyLlama USB and PS/2 Keyloggers (Text)

Irongeek - Hardware Keyloggers: Use, Review, and Stealth Presentation (Phreaknic 12) (Video)

Hardware Keyloggers In Action 1: The KeyLlama 2MB PS/2 Keylogger (Video)

Hardware Keyloggers In Action 2: The KeyLlama 2GB USB Keylogger (Video)

Bluetooth Wireless Hardware Keylogger Review (Video)

and programmable USB HIDs like the PHUKD (Programmable HID USB Keyboard Dongle):



Programmable HID USB Keystroke Dongle: Using the Teensy as a pen testing device (Defcon 18) (Video)

Programmable HID USB Keystroke Dongle: Using the Teensy as a pen testing device (Text)

and even some about mitigating both types of risks:



Plug and Prey: Malicious USB Devices (Text)

Malicious USB Devices: Is that an attack vector in your pocket or are you just happy to see me? (Video)

But what about combining the two?

I've been doing some work recently on making homemade keyloggers of both the USB and PS/2 persuasion that will take keystrokes, record/replay them, and modify programmable HID payloads accordingly. This hardware and software is not exactly ready for prime time, but I figured I'd share it with you. On this page you will find rough schematics, source code and links that may help you build your own. I plan to put a video up that demos the devices right after Skydogcon.

Here are just a few of the possibilities:

The core goal of this project is to develop the code, circuitry and instructions necessary for building a hardware keylogger that is also a Programmable HID and key repeater with inexpensive hardware. Hardware keyloggers vary in price from around $33 to several hundred dollars. While I doubt I’ll be able to match the price of the very low end, I hope to be able to put together something that is inexpensive and flexible. If I can accomplish this with an Arduino based platform (common amongst hobbyist and with great support for extra peripherals) it will make adding additional features like wireless and network support much easier in the future. I'm using the Teensy because of it's small size and built USB HID support.

My talk from Skydogcon may help:

Presentation Slides

More recent video from NeoISF. I have since fixed the problem of it not working with non Dell keyboards, but you need to update the firmware on the PIC USB Host Module.

Here are a few caveats:

Change log: 0.00: Released to public 0.01: * Holding mod keys did not always work for multi select. Got it working (at least I think I did). * Nulls were getting into the logs, so I made an unhandled keycode exception. 0.02: * Converted ints to bytes in many places. Why take the extra space? :) * Made sure it worked with Arduino 1.0. * Switched to using the SD library that comes with Teensyduino (from the comments, it looks like it's a wrapper by SparkFun Electronics around William Greiman's work). * Changed the variables "file" to "logfile" and "filename" to "logfilename" to be less ambiguous.

Change log: 0.00: Released to public 0.01: * Holding mod keys did not always work for multi select. Got it working by taking out the key replay code, and made held keys function better in the process. Also, it made the code simpler to read as I got rid of a bunch of unneeded cruft code. :) * Nulls were getting into the logs, so I made an unhandled keycode exception. *Changed log brackets from <> to []. 0.02: * Fixed bug in logging unknown keys. * Added logging for keys [KEY_TAB] and [KEY_NON_US_NUM]. * Ctrl+Alt+S toggles the typing of raw bytes as they come in the serial connection. * Converted ints to bytes in many places. I think their was a type casting problem causing weird issues. * Fixed a buffer overflow issue caused by IncomingHIDReportIndex going over 18. * Many other tiny changes. 0.03: * Made sure it worked with Arduino 1.0. * Switched to using the SD library that comes with Teensyduino (from the comments, it looks like it's a wrapper by SparkFun Electronics around William Greiman's work). * Changed the variables "file" to "logfile" and "filename" to "logfilename" to be less ambiguous. 0.04: * If a keyboard was plugged in after the keylogger was already powered on, it would type "i7-". I added code to fix this problem. * Fixed RAW serial debug mode not to print key * Changed name of variable "lasttenletters" to "lastfewletters" and expanded it to 60. * Ctrl+Alt+Y is now used for typing more debugging details. * Implemented likely to fail code for unlocking workstation using captured password. * I had some problems with running out of SRAM because of all of my static strings. I started using the F() function to pull these strings from flash memory to solve this issue. * Fixed a case issue with lastfewletters. I did not know the method changed it in place. * Fixed a bug in HIDtoASCII that made it top row of number keys not work right.

Building USB and PS/2 Hardware Key Loggers and Repeaters Using Inexpensive Hobbyist Microcontrollers

Adrian Crenshaw

Abstract

The core goal of this project was to develop the code, circuitry and instructions necessary for building a hardware keylogger that is also a Programmable USB HID (Human Interface Device) and key repeater with inexpensive hardware. Hardware key loggers vary in price from around $33 to several hundred dollars. While the final results did not match the price of a very low end PS/2 unit, I was able to put together two hardware key loggers and repeaters that are inexpensive and should prove to be flexible. This was accomplished using the Teensy microcontroller with software developed in the Arduino development environment, a PIC microcontroller based USB host module with a modified firmware written in C, and a MicroSD SPI adapter. Since most of the code resides on the Teensy microcontroller development board (an Arduino compatible platform popular amongst hobbyist and with great support for extra peripherals) it should make adding additional features like wireless communication and network support much easier in the future.

Background

While most people are familiar with software keyloggers, my focus for the class project was to create hardware key loggers that directly monitor the electrical signals between the computer and the keyboard. I also added the functionality of a Programmable HID to the key logging devices.

The concept of a hardware key logger is fairly simple. It is connected between the key board and the computer and logs all of the keystrokes that the user makes. There are commercial version of both USB and PS/2 key loggers, and normally they are marketed as filling the following niches:

1. Writers: Users can install them on their own systems as a backup for the work they've typed. My personal feeling is this is not the most practical use. Maybe if the user types in long continuous strings and rarely copies and pastes or backspaces over mistakes it would work well for them. Because of the way I work on my articles I doubt it would be very useful to me since my writing style is hardly linear (and even less so when programming). I go back over the same article many times making little changes here and there, making the keylog rather unworkable as a recovery mechanism. However, for those that are better typists than I, and who have thought processes more coherent, this weak form of backup may work.

2. Businesses: Some companies may use key loggers for monitoring employees for misconduct. In my opinion large companies might be better off rolling out a custom software key logger via a GPO since a software key logger can give a much greater level of detail about when and in what application the keystrokes were made. Only the highest end hardware key loggers seem to support time/date stamping, and even then they can't tell the snooper in what application or context the keystrokes were made. If someone were doing a serious investigation into misconduct, time/date stamping would be a must.

3. Parents: Some parents may choose to use a hardware keylogger to monitor their children. My thoughts on the subject are that parents would be better served by using filtering software, since the child does not have to be very bright or tech savvy to just physically remove a hardware keylogger if they know that it is installed.

4. Pen-testers/Crackers/Spies: If an attacker is trying to get someone else’s password or proprietary information, hardware key loggers could come in quite handy. The high price tag and difficulty of gaining physical access to the monitored machines may limit this use to only internal corporate spies and well financed tiger teams, but it's still a conceivable use.

Now that the reader is aware of why someone might want to use a hardware key logger I'll cover some of their pros and cons. I'll cover the downside of hardware vs. software key loggers first:

1. Most of the time hardware key loggers have to be physically recovered to obtain the logs. Having to have physical access can be a serious obstacle to installing and retrieving the key logger. That said, commercial models have come on the market in recent years that use wireless protocols to dump the key stroke captures, so close physical access may only be needed for the installation step. These wireless key loggers are rather expensive however. Also keep in mind that there are ways to socially engineer a target into installing and retrieving the keylogger for the attacker.

2. The hardware keylogger gives little to no information on what app was active when the keystrokes happened. Without knowing the context of the keystrokes it's much harder to tell if a string of characters is from a document, an IM session or a password. For Windows logons this is somewhat mitigated by the fact that the attacker can look for Ctrl-Alt-Del to narrow down where the credentials may be.

3. Hardware key loggers are rather expensive. One of the cheaper PS/2 models I've found was $33; others can range up to a few hundred dollars depending on their supported features.

4. If found, external hardware key loggers are much easier to remove than software key loggers. A target could just pluck them off of the keyboard's cord if they are spotted. Removing software key loggers depends on the user’s privilege level, or how knowledgeable they are about gaining a higher privilege level. This is not a disadvantage equally shared by all hardware key loggers as some can be installed internally on a PC or keyboard, and thus not as easily noticed.

As for advantages of hardware key loggers over software key loggers there are many:

1. Most software key loggers seem to be detected by anti-malware apps. Depending on which software package is used, the anti-virus system will likely detect the software key logger and remove it, or at the very least report it to the user. Hardware key loggers, on the other hand, are very hard to detect without physical inspection. This is not to say that it is impossible to detect a hardware key logger using software running on the host, some USB hardware key loggers will appear as a USB hub or cause spurious problems when other USB devices are plugged in-line with them (reduced speed, not connecting at all, etc.). The presence of odd USB vendor and product IDs might be detected if the hardware key logger is not completely passive.

2. Hardware keystroke loggers can record keystrokes from before the OS is even loaded (capturing BIOS password), or from around software that limits what processes can access the keystrokes (like the Windows GINA logon after the old three finger salute of Ctrl-Alt-Del).

3. Hardware key loggers can support logging regardless of the Operating System being ran on a computer as long as the keyboard is a fairly standard USB HID or PS/2 model. Windows, Linux, Mac OS X - it makes little difference to a hardware key logger as long as the connection type (USB or PS/2) is supported.

Now that I've given an overview of what hardware key loggers are and their given advantages/disadvantages, let's cover what is meant by a Programmable HID and keyboard repeater.

In the recent past I have been working on the Programmable HID (Human Interface Device) project. The core idea was to bypass autorun restrictions by using a Programmable HID (Keyboard, Mouse, Joystick) to send the needed keystrokes to run commands. This could be for any of the following tasks and more:

· Add a user

· Run a program

· Copy files to a thumb drive for later retrieval

· Upload local files

· Download and install apps

· Go to a website that the victim has a cookie/session for, and do a sort of CSRF (sic)

The main idea of this project is to combine the two concepts, and have a Programmable HID that can also log and interpret keystrokes to vary the payloads. For example: Grab the username and password when a user types them in, then reuse those credentials later to log in when the user is not around to watch the nefarious deeds that are about to take place.

Overview

In this section I will discuss similar projects to mine, and other’s work that I have built on or took inspiration from.

While there are many commercial hardware key loggers on the market, very little material seems to be available on creating your own with hobbyist components. Keelog, a manufacturer of commercial key loggers, has published a website [1] on making your own PS/2 hardware keyloggers. They even have details on making a PS/2 key logger who’s keystroke logs can be recovered wirelessly [2]. Keelog’s “Do It Yourself” PS/2 key logger is fairly primitive however, and may require more electronics experience then some would prefer. As for USB hardware keyloggers, there is an Instructables article on the subject [2], but it requires a USB to PS/2 converter meaning the computer would have to have a PS/2 port, and as such it is not a complete USB hardware key logger. None of these resources were of direct use to me for this project.

There is a fair amount of research on making Programmable USB HIDs. Some of the projects that follow are based on work the author has written about previously [4], but try to extend it in some way. There were four different presentations at DefCon 18 and surrounding conferences (Black Hat USA 2010 and B-Sides Las Vegas 2010) that involved using Programmable HIDs, so we might expect to see more use of this class of device soon. The highlights from these conference presentations are as follows:

Dave Kennedy used a Programmable HID (also known as a PHUKD, short for Programmable HID USB Keyboard/Mouse Dongle) in his “SET 0.6 Release with Special PHUKD Key” talk at B-Sides Las Vegas 2010. Since Mr. Kennedy integrated the PHUKD with his Social Engineering Toolkit (SET) we can probably anticipate others trying out this vector of attack. Dave Kennedy and Josh Kelly also used the device in their talk “Powershell...omfg” at Defcon 18 and Black Hat Las Vegas 2010 the same week. In this talk they demonstrated using Metasploit type functionality by leveraging Microsoft Powershell with the PHUKD. Josh Kelly has also apparently done some work on PS/2 key logging with the Teensy, though I’ve not used his code.

Richard Rushing gave a talk called “USB - HID, The Hacking Interface Design” at Black Hat USA 2010.

Monta Elkins demonstrated a radio controlled version of the Programmable HID concept in his talk “Hacking with Hardware: Introducing the Universal RF USB Keyboard Emulation Device – URFUKED”. Instead of having the programmable HID wait for a timer, or for certain environmental conditions to be met, Mr. Elkins’ device was triggered via an RF based remote control.

Finally, there was the author’s talk “Programmable HID USB Keystroke Dongle: Using the Teensy as a Pen Testing Device”. It covered the basics of constructing a Programmable HID. Also covered were potential ways to hide the device in other hardware or cubicle toys, and socially engineering a target into installing the device.

The work most directly useful to this project came from libraries and software developed by others for the Arduino development environment and the PIC based USB host module. Specifically, my own Programmable HID USB Keyboard/Mouse Dongle Library [5], the Teensy/Arduino PS/2 library [5], the SDFat16Lib library [6], sections of the HID to ASCII code from Circuits@Home [7] and the source code to the firmware of the Sure Electronics USB host module [8]. Most of these sources had to be modified to work for the project, and I have made the source code available [10].

My Work

Starting off I had to do some research to find the hardware to support the functionality I wished to implement. I was already familiar with the Teensy and the Arduino development environment, so I used that as the basis for my project. Since the Teensy already has support for acting as a USB HID this made things somewhat easier. The choice for storage was also fairly easy as a MicroSD adapter and source code examples were already available for the Teensy. Another major component was needed for the keyboard input. For the PS/2 hardware key logger the only extra component I needed was a female PS/2 connector (please note that while the input on my PS/2 key logger is PS/2, the output is a USB connector that plugs into the computer). The female PS/2 connector was cut from an unused KVM cable. For the USB keyboard input, something more complex was needed. There is a USB host shield for Arduino Pro Mini, but it will not quite fit on a Teensy. Paul Stoffregen is working on his own form factor compatible USB host shield, but I wanted to find something that was available already. I found Sure Electronics’ USB host module which seemed like it could provide the needed functionality. For the sake of reference, here is a rough bill of parts (minus commodity things like wire, solder, etc.) along with prices and where they can be purchased online:

· Teensy ($16)

http://pjrc.com/store/teensy.html

· PS/2 Female Cable

This part is only used for the PS/2 hardware key logger; I cut mine off of a KVM cable as I recall.

· MicroSD Adapter ($8)

http://pjrc.com/store/sd_adaptor.html

MicroSD card not included.

· USB Host Adapter ($14.90)

http://www.sure-electronics.com/goods.php?id=1140

Only used for the USB hardware key logger.

Assuming the builder is good at salvaging parts, this brings the cost of the PS/2 unit to about $24 and the USB unit to about $39 (not including shipping and handling, and assuming they already have a MicroSD card to use for storage).

For development work I had to obtain the following compilers, packages and tools:

· Arduino Development Package

http://arduino.cc/en/Main/Software

Most of the code for both key loggers was written in the Arduino environment. The majority of the development work was done in Arduino 0022/0023, but has been tested and works on Arduino 1.0 as well.

· Teensyduino and the Teensy serial driver

http://www.pjrc.com/teensy/td_download.html

These are the extra libraries and hardware definitions needed to use the Arduino development environment with the Teensy.

· Teensy Loader

http://www.pjrc.com/teensy/loader.html

The Teensy Loader application is used to load the compiled sketch onto the Teensy. Just press the surface mounted button on the Teensy, and the Teensy Loader will upload the sketch. No external programmer was needed as the Teensy only requires a Mini USB cable to write sketches to its ROM.

· PICKit 2 Programmer (clone)

http://www.sureelectronics.net/goods.php?id=21

The PIC based USB host module I used required an external programmer. I bought a cloned version from Sure Electronics. If someone does not already have access to a PIC programmer this would increase the total price of the project by about $20.

· PICkit 2 Development Programmer/Debugger Official Software

http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1406&dDocName=en023805

This software is used with the chip programmer listed above to write a compiled HEX file of the firmware onto the USB Host Module.

· MPLAB IDE X Beta 7.02MPLAB C30 Lite Compiler for dsPIC DSCs and PIC24 MCUs

http://www.microchip.com/en_us/family/mplabx/index.html

I provided a precompiled HEX file of my firmware along with the other project downloads, but if modifications are required to the USB host module’s firmware this is the needed development package to recompile it.

PS/2 Hardware Key Logger

Wiring the components together is fairly easy once the pin outs are known. First I’ll cover how the PS/2 hardware key logger is wired together by using a rough schematic. I obtained the following PS/2 pin out table from Wikipedia (along with the PS/2 connector image I used in the schematic).

Pin 1 +DATA Pin 2 Not connected Pin 3 GND Pin 4 VCC Pin 5 +CLK Pin 6 Not connected

The software for the Teensy required the Arduino PS/2 library for interpreting the electric signals (scan codes) that the keyboard sends, and this library had to be heavily modified so that it would recognize more keystrokes. My version of the PS/2 library is included with the source code for the PS/2 key logger. The SD library that comes with the Arduino environment was used to write to, and to read from, the MicroSD card. Once a key press is identified it is logged to the MicroSD card and replayed to the host computer via the Teensy’s USB connection.

USB Hardware Key Logger

The USB hardware key logger required wiring in the USB host module. The USB host module’s communications were done over the UART interface. The original firmware from Sure Electronic had extra unneeded characters that made parsing the input more difficult. The original output looked like the text on the left in the table below, my modified code’s output is what is displayed on the right via a PuTTY session into the serial port created by using a USB to TTL FTDI serial cable:

Key(s) Code a 0000040000000000 Left Ctrl+Shift+Alt 0700000000000000 Right Ctrl+Shift+Alt 7000000000000000 a+b+c 0000050406000000

The output of the USB host module comes across the serial connection as a stream of numbers (and a character, along with line breaks). These numbers correspond to HID codes that identify which keys are being pressed (as illustrated in the table above). The SD library that comes with the Arduino environment was used to write to, and to read from, the MicroSD card. Once a pressed key is identified, it is logged to the MicroSD card and replayed to the host computer via the Teensy’s USB connection.

Here is the rough schematic of the USB hardware key logger:

Pictures of both units as wired:

Programmable HID payloads based on keystrokes

Both the PS/2 and the USB key logging units could record the key presses as they came in, and base Programmable HID payloads on them. In the past I have used this functionality to look for the key pattern “CTRL-ALT-DEL <some user name> TAB <some password> ENTER” to try to find usernames and passwords and then have the payload use these found credentials later. For the demo code of this project I implemented the following payloads instead:

1. Ctrl+Alt+L types out the keylog. The MicroSD card could also just be removed from the key logger and the text file read in any editor.

2. Ctrl+Alt+Y shows the last few keys, for debugging things like payload 3.

3. Typing "Adrian" in UPPER or lower case automatically adds “ is awesome” to what is being typed.

4. Ctrl+Alt+D clears the keylog.

5. F12 enables LOL speak, which forces the user of the keyboard to type like a LOL Cat.

Granted, a few of these payloads are not particularly useful, but they hopefully demonstrate the possibilities. A more useful function might be to look for the typing of “http://something<ENTER>” and force a set of actions on the target site, or to redirect the web browser to another site altogether (note that care needs to be taken by the attacker to prevent false triggers). By parsing keystrokes the attacker will have a better idea of what the user is doing, when to use the attack payload, and how to modify it for best effect.

Evaluation

In my proposal I said I would ultimately judge the results of my project on whether or not others found it useful. In that regard I’ve not heard much back from others who have tried to implemented this project themselves, but the first schematics and code have only been public since November 2nd 2011. I think I’ve reached the goal of creating a basic hardware key logger and repeater for under $60. There were several problems I mentioned that I would like to solve or mitigate, and I will flesh out my current progress on those in the following points:

1. Making the hardware reliably with different makes and models of keyboards that are plugged in could be a problem. This will vary, and from past experience I can say even commercial hardware key loggers are hit and miss depending on the keyboards being hooked to them. So far my key loggers have seemed to work with most of the keyboards I’ve tested them on. The PS/2 unit had some issues with the IBM Model M keyboard I use, but I think this may be a power issue and I know a lot of PS/2 to USB keyboard adapters also have problems working with the IBM Model M. As for the USB unit, it has worked with all the USB keyboards I remember testing it on except for ones that have a built in hub. The PIC based USB host module I’m using does not support having hubs connected to it. I’ve only used a few keyboards as test examples for both units so more tests are needed to know how reliable the key loggers really would be in the field.

2. Packaging is a big issue. For this project I mostly used bread boards for building and testing the circuits. I’ve made a smaller USB unit by wiring things together with a proto board, but the results are still rather crude. Eventually I would like to come up with more surreptitious packaging.

3. One of my goals was to keep the costs low. At $24 for the PS/2 unit and about $39 for the USB unit I think this has been accomplished, even with the additional cost of a MicroSD card.

Discussion/Future Work

There are several things I would like to work on in the future to advance the project. Some of these should be fairly easy to implement. One of the reasons an Arduino compatible platform was chosen was to make use of all of the work the community has done with integrating peripherals. A few of my future plans include:

1. Adding wireless support for retrieving the logs and sending keystrokes. I have ordered a Bluetooth to serial module for testing this idea, but it has not arrived yet.

2. Better packaging to make the key logger more robust and more professional looking.

3. Adding a real time clock so that the key stroke logs can contain a time/date stamp.

4. Adding an Ethernet interface for retrieving the logs and sending keystrokes over an IP network.

5. Make the key loggers more passive. Currently they show up with their own USB vendor and product IDs. These IDs can be changed in the code, but I would like for the units to either be completely passive, or automatically clone the USB vendor and product IDs of whatever keyboard is plugged into them.

I plan to present more on this project at future conferences, so these additions may be implemented in the coming year.

Conclusion

I set out to create my own PS/2 and USB hardware key loggers, and this has been accomplished. I also wanted to add key stroke parsing to my Programmable HID project, and that has also been successful. Work still needs to take place to test the units in real world environments for reliability and detectability, but I’m very happy with the results so far. A website about the project, with source code and schematics, can be found at:

http://www.irongeek.com/i.php?page=security/homemade-hardware-keylogger-phukd

Works Cited

x

[1] Open source DIY hardware keylogger. [Online]. http://www.keelog.com/diy.html [2] Wireless Keylogger - Do It Yourself! [Online]. www.keelog.com/wireless_keylogger.html [3] How to build your own USB Keylogger. [Online]. http://www.instructables.com/id/How-to-build-your-own-USB-Keylogger/ [4] Adrian Crenshaw. (2010, Aug.) Irongeek.com. [Online]. http://www.irongeek.com/i.php?page=security/programmable-hid-usb-keystroke-dongle [5] Adrian Crenshaw. (2009-2011) Programmable HID USB Keyboard/Mouse Dongle Library. [Online]. http://www.irongeek.com/i.php?page=security/programmable-hid-usb-keystroke-dongle#Programming_examples_and_my_PHUKD_library [6] Christian Weichel, L. Abraham Smith, and Cuningan Paul Stoffregen. PS2Keyboard Library. [Online]. http://www.pjrc.com/teensy/td_libs_PS2Keyboard.html [7] Bill Greiman. SDFat16Lib. [Online]. http://code.google.com/p/sdfatlib/ [8] How to drive USB keyboard from Arduino. [Online]. http://www.circuitsathome.com/mcu/how-to-drive-usb-keyboard-from-arduino [9] Source code to the firmware of the Sure Electronics USB host module. [Online]. http://www.sure-electronics.net/download/index.php?name=MB-CM13111&type=0 [10] Homemade Hardware Keylogger/PHUKD Hybrid. Adrian Crenshaw. [Online]. http://www.irongeek.com/i.php?page=security/homemade-hardware-keylogger-phukd

x