Skip to main content

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

        While I was at Shmoocon 2010, I was given a Phantom Keystroker. It's a neat little USB dongle which looks like a thumbdrive that you could surreptitiously install in the back of someone's computer.
The Phantom Keystroker acts as a keyboard/mouse USB HID (Human Interface Device) to send keystrokes, move the mouse pointer around randomly, toggle caps lock and other things to annoy your co-workers and loved ones. This started me thinking, what if you could make something like this that was programmable? There are all sorts of things you could do with it.
        The Hak5 U3 USB switch blade is pretty cool, but lots of folks have autorun turned off by default now. That said, they don't turn off the adding of a new USB keyboard! A programmable USB key stroke dongle could replace U3 switchblades in places where autorun from removable storage it is disabled. A USB HID device also does not need special drivers installed on modern operating systems, much like how a thumbdrive does not need drivers if the host supports USB mass storage. This would allow for doing things on a terminal quickly, and without drawing as much attention as sitting down in front of the terminal would. The person turns their head for a minute, the pen-tester plugs in their programmable USB key stroke dongle, and Bob's your uncle, instant pwnage. All sorts of command could be run, but more on that later in the examples section.
        The programmable key stroke dongle could be set to run by a timer. The pen-tester programs the dongle to wait for a certain amount of time after install before doing its thing, a time when the pen-tester suspects that a user with extra privileges will be logged into the target workstation. If timed right, all sorts of privilege escalation can happen. There are more options than just a timer however. If the dongle has heat sensor or a photo resistor built in it could be programmed to dump its key stroke/mouse payload when the heater kicks in or the lights come on in an office. Think of the possibilities!
While at Shmoocon I saw the Hak5 crew setting up, and went by to talk to Daren and Snubs. I mentioned the Phantom Keystroker to Darren, and how I thought it would be great to be able to make a programmable one. Daren told me he had something to tell me later. It seems Darren ( and Robin Wood (digininja had been working on just such a project. Cool, great (or devious) minds think alike! I was looking forward to their product.
        After the con, I decided to see if I could come up with a ghetto way to make a programmable USB keystroker. I started looking around, and found programmable promotional USB buttons used for marketing that took people to a predefined website. Neat, but not easily reprogrammed. I then started looking into Arduino, since my buddy Morgellon turned me on to them. But implementing a USB HID with the standard Arduino is a bit of a pain. Then I found a related device called the Teensy ( ) which you could program in C, or the easier Arduino development environment, and that already supported USB HID out of the box! Rock on, and it was only $18 to $27 depending on how you got it. I opted for the Teensy over the Teensy++ since it was cheaper, smaller and I did not need many I/O pins.

        For those who want a more professional device with nicer packaging, Daren and Robin have a product coming soon. I encourage you to buy theirs when it comes out to help promote their work, and so Daren can spend more time on the Hak5 projects we so love. For those who have an electronics/DIY bent, and like to "Go ugly early" what follows are details on how I made my programmable USB key stroke dongle.
So, why would a pen-tester want one?
1. Likely types faster than you can, without errors. This is important when physical access time to the target system is limited.
2. Works even if U3 autorun is turned off.
3. Draws less attention than sitting down in front of the terminal would. The person turns their head for a minute, the pen-tester plugs in their programmable USB key stroke dongle, and the box is popped as Dave Kennedy likes to say.
5. The HID can also be set to go off on a timer when you know a target will be logged in, or by sensor when certain conditions are met.
6. You could embed a hub and a flash drive in your package so that you have storage and the programmable USB HID all in one nice neat package.
7. Embed your device in a USB toy or peripheral (lots of spare room in a printer or dancing USB penguin) and give it to your target as a 'gift'. Packaging that looks like a normal thumb drive is also an option.
8. After your Trojan USB device is in place, program it to "wake up", mount onboard storage, run a program that fakes an error to cover what it is doing (fake BSOD for example), do its thing, then stop (leaving the target to think "it's just one of those things").
Just use your imagination!
What sort of commands would you use?
        All sorts of things could be done:
1. Add a user to the box or the domain.
2. Run a program that sets up a back door.
3. Copy files to your thumbdrive (see example code for how to find the flash drive by volume name)
4. Go to a website they have a cookie for, and do some sort of transaction (sort of like CSRF, but hardware based).
        I'd like to note one disadvantage of the device. The first time you plug in a USB HID it takes a bit of time to enumerate. This seems to take a little longer with a USB HID than a new U3 thumbdrive does. Still, I think there are many applications for this USB keyboard/mouse device.
What's in a name?
        You know, 'A programmable USB keystroke dongle' is kind of a mouthful to say. I needed a shorter name for this sort of device. Lots of folks build their electronics projects in Altoids tins, so I thought about calling it MintyPwn, in honor of LadyAda's MintyBoost. Also, since it's a USB stick, and I planned to use DIP switched to select what keystrokes/mouse movements to send, DIPStick sounded like a cool name. Neither of those however really seem to describe what the device was, so I thought maybe an acronym was in order:
Programmable HID USB Keystroke Dongle,
or PHUKD for short.
How it's built
        What follows is a rough schematic (with light sensor) and set of pictures that should be enough for you to build your own. Please keep in mind, my soldering and rotary tool skills are not yet up to snuff, so the packaging can be made better/smaller. Also included is some sample code for the Arduino development environment. I plan to add more code and pictures as the project matures. If you have any ideas for useful payloads for the PHUKD type, please let me know.
More Pics and Videos
    People requested I add more photos so they know what is soldered where, so I hope the following helps them out.
A few updated pics (added 4/1/2010):
Notice how I soldered in the photoresistor and 10kΩ resistor, it's ugly but it works with the code below.
I used a 24 pin IC mount and soldered it on backward, that way I could use the pin holes as sort of a mini bread board. The DIP switch I'm using in the pic requires the use of something like a paper clip to set the switches, but at least I won't accidently set them wrong in my pocket as easily.
I used heat shrink tubing to make the package a little neater, and hold it all together.
A few even newer pics (added 6/3/2010):
These are two new units I've put together, one with a normal Teensy 2.0 and an SD adapter, the other with a Teensy++ 2.0. Notice I used heat shrink to make the shell, this works pretty well as I can start shrinking it, cut holes for the switches as it shrinks, and then slit the whole thing so I can take it on and off as needed.
The Teensy 2.0 unit, disassembled
The naked Teensy++. Yes, my soldering skills need work. I've added a momentary push button for diagnostic and demo help.
Here is the other side, with the shield taken off. I really like using the shield concept, as headers are cheap and easy to solder. Now I can repurpose the unit anytime I like by just swapping shields made on cheap perf board.
I've also made a trojaned mouse. The way this one works is there is a USB hub, and a microSD USB adapter soldered into the mouse along with the Teensy. I've got this one set to run it's payload when scroll lock is toggled. The following video should explain more:

Short presentation I did for the Bob talks at Outerz0ne 2010 on the concept
This video will show you the basics of setting up the Teensyduino environment in Windows


Programming examples and my PHUKD library
        To make things a little easier on you, I've made a simple library for common tasks. 
(Note: Most of the code on this page is for versions of the library before 0.3, but it should be easy to adapt.)
To use the library, copy the files phukdlib.h and phukdlib.cpp into <arduino folder>\libraries\PhukdLib\, then add this include line to your sketch:

#include <phukdlib.h>

I've put a little demo sketch in the zip file under examples to help illustrate how it can be used. Keep in mind, I've been mostly implementing for Windows so far. Linux and OS X will take other keystrokes to accomplish the same effects. The function names are fairly self explanatory, but just in case:
CommandAtRunBarMSWIN(char *SomeCommand)
Opens the MS Windows run bar and executes the given command.
CommandAtRunBarGnome(char *SomeCommand)
Opens a run bar in Gnome under Linux and executes the given command.
CommandAtRunBarOSX(char *SomeCommand);
Opens Spotlight under OS X and executes the given command.
CommandAtNewTerminal(char *SomeCommand);
Opens a Terminal under OS X and executes the given command.
Shrinks the active window to help hide it in MS Windows.
Shrinks the active window to help hide it in Gnome.
Shrinks the active window to help hide it in OS X.
PressAndRelease(int KeyCode, int KeyCount)
This function simplifies the pressing and releasing of a key. You can also specify how many times to hit the key (really useful for tabbing to where you need to be on web sites).
Just sends diagnostic info out the keyboard interface. Things like the reading on analog pin 0, and the state of each input. Should work on both types of Teensy, but I've not done a lot of testing.
Not really a function, but a string you can set in your sketch that ShowDiag will print out. I kept forgetting which DIP switch I had set to run which function, so I use this as a reminder at runtime.
int ledkeys(void)
I noticed when I logged into a box, the Num Lock LED would often toggle (depending on how it was set last). I thought this would make a great way to know when someone just logged in, since the Num lock, Caps lock and Scroll lock events are sent to every attached keyboard on the system. Now we can have a sort of two way communication giving us a better idea of when a user is really sitting at the system, and it's logged in and ready for mischief. Also, thanks to KennyG for the CAPS lock trap idea. All we do is turn on CAPS lock, and when we see it go off we know someone is at the keyboard to turn it off.
ledkeys returns the setting of the "lock keys"
     Num Lock = 1
     CAPS Lock = 2
     Scroll Lock = 4
Add them together to get combos, for example if all threm are on 7 would be the result. You can use binary operators to separate out just the lock keys you are looking for, but I've made that a little easier with the IsXOn functions below.
boolean IsNumbOn(void)
Returns TRUE if NUM Lock LED is on and FALSE otherwise.
boolean IsCapsOn(void)
Returns TRUE if Caps Lock LED is on and FALSE otherwise.
boolean IsScrlOn(void)
Returns TRUE if Scroll Lock LED is on and FALSE otherwise.
I'm also open to adding more functions, and taking code contributions.
        The following are some simple examples of programming the PHUKD using the Arduino environment (from before I made my PHUKD library, so look at the example code that came with the PHUKD library if you intend to use it). More details on the language can be found at the following two links:
        When I started this project I had to delve into the Teensyduino source code to figure out how to send some control keys. Since then, Paul has done a lot of work on the Teensyduino documentation, especially when it comes to USB HID support. Check out these two pages:
Also, while it's not PHUKD related, Paul has some great docs on the peculiarities of using the Teensy to control servos:
I'm working on a laser projector and a hexapod project that these docs will help greatly.

Hopefully my sample code will help you figure it out how to use this functionality as well. If you wish to change the USB Vendor and Product ID look in arduino-xxxx\hardware\teensy\cores\tensy_hid\usb_private.h
If you come up with any useful keyboard commands, please send them to me as functions that are easy to include in other's projects. Note that in the code below, I have one DIP switch determine one function, but with an 8 position dip I could program it so I had the choice of 256 different functions.


Popular posts from this blog

Как найти реального заливщика

Своего первого реального заливщика, который показал мне как можно скачать деньги в интернет с банковских счетов, я нашел случайно, когда еще трудился в Укртелекоме сменным инженером немного подрабатывая продавая трафик налево, но потом этот человек отошел от дел в связи со слишком уж скользкой ситуацией в данной сфере, и я решил поискать партнера на форумах, разместив рекламу на трёх электронных досках объявлений. Честно говоря поначалу даже был готов сразу закинуть 500 000 гривен в Гарант, но потом призадумался, а стоит ли?

Ко мне начал обращаться народ обращается разных категорий

1. Дебильная школота, которая что-то любит повтирать про свою серьезность и просит закинуть 10 000 USD им на Вебмани в качестве аванса 
2. Реальные мэны, которые льют сразу большую сумму по SWIFT без разговоров про гарантии и прочую шнягу, но после того, как им отдаёшь нал, они сразу пропадают, суть данных действий я так и не понял. зачем пропадать, если всё прошло гладко? 3. Мутные личности, берущие реквизиты …

Black Hat SEO или бот для скликивания контекстной рекламы

На днях мне стало интересно, а каким образом с точки зрения «черных» методов SEO могут быть использованы хакерские программы – например, путем генерации трафика для заинтересованных ресурсов или скликивания контекстной рекламы AdWords или Яндекс.Директ
Понятно, что увеличение числа посетителей на сайте интернет-магазина или компании, занимающейся недвижимостью, вероятнее всего положительно скажется на их доходах. Поэтому разработка подобного типа программ — вполне себе обыденное дело, и появились такие программы уже давно. По большей части таких ботов можно разделить на два класса — это различного рода Adware, которое распространяется вместе с популярными программами, или трояны, которые осуществляют более серьезную модификацию системы.  Win32/Patched.P Давай для начала рассмотрим достаточно экзотический, но от этого не менее интересный способ подмены результатов поиска в популярных поисковых сервисах Яндекс и Google, который был реализован в троянской программе Win32/Patched.P (ESET)…

Новые онлайн-игры с выводом денег

Одним из видов получения стабильного сетевого дохода является заработок в он-лайн играх, с выводом денег через электронные платежные системы, такие как Яндекс.Деньги или Webmoney или через любые другие электронные платёжные системы. Причем, способов заработать на играх в интернете существует несколько, и зарабатывать таким образом можно довольно внушительные суммы.

Как правильно играть на деньги в онлайн играх
1. Играть самому, без каких-либо денежных вложений в игру. Такой способ заработка занимает довольно много времени, а доход приносит весьма скромный. К тому же, в некоторых онлайн играх с выводом средств зарабатывать подобным способом просто невозможно, так как игры с возможностью заработать могут являться инвестиционными проектами (финансовыми онлайн играми), которые требуют обязательных минимальных вложений.

2. Играть самому, вкладывая деньги с банковской карты. Наверное, это самый оптимальный способ заработка реальных денег в онлайн играх. Сумма дохода здесь зависит от того, ско…

Залив на карту без предоплаты по SWIFT или SEPA

В последнее время наблюдается такая ситуация, что нальщиков и дропов на рынке много, а адекватных заливщиков, можно сказать, совсем нет.

Например, один мой хороший знакомый, имеющий свой собственный офшор, работает с заливщиками на условиях партнерства, предоставляя им трафик и взамен получая 20% от поведенных транзакций на свой счет в офшорном банке. Мне он рассказал по большому секрету, как такое ему удается, а начинал он как и все с малого - продажи дебетовых карт и игре на рынке FOREX.

Просто так искать Заливщиков на различных форумах, посвящённых обналу и отмыванию денег - достаточно муторное и нудное занятие, потому как после общения с десятым по счету заливщиком, начинаешь понимать, что просто так на карты и счета никто лить не будет.

Однако моему другу попался один довольно интересный вариант - Заливщик предложил сделать перевод в размере 375 000 EUR по SEPA в день предоставления готового к работе счета и активной системы Multihomed AS.

Остальные предложения были более мутные …

Чем рискуют дропы и нальщики принимая заливы на свои карты

Зам.начальника управления Следственного департамента МВД Павел Сычев рассказал о криминальном бизнесе «нальщиков»
- Глава Банка России Эльвира Набиуллина заявила о снижении объемов теневого оборота в конце 2013 года. Что показывает ваша статистика по выявлению незаконных операций?

- В последние годы объем денежных средств, выведенных в теневой сектор, увеличивался, и криминогенная обстановка ухудшалась. Проблема находится в поле зрения президента -  в декабрьском послании Федеральному Собранию, он призвал избавить нашу финансовую систему от разного рода «отмывочных контор» и так называемых «прачечных». Оперативники уже получили ориентировку на более активное выявление этих преступлений.

По уголовным делам, расследованным МВД только в первом полугодии 2013 года, проходит 145 млрд рублей, обналиченных и незаконно выведенных заграницу. Это неуплаченные налоги, незаконный бизнес, хищения, взятки. Финансовый доход посредников от этих операций составил 8 млрд рублей. Расследовано 89 таких дел …

Как работает банк со своими корреспондентами по SWIFT

Итак, наш банк имеет открытые корреспондентские счета в США (CITIBANK N.A. NEW YORK), в Европе (VTB BANK DEUTSCHLAND AG), в России (Промсвязьбанк Москва и Собинбанк Москва).

Соответственно, все расследования по платежам происходят через эти банки согласно  установленным корреспондентским отношениям с использованием соответствующих форматов SWIFT MT-195/295, MT-196/296, MT-199/299 и MT-192/292

Кроме прямых корреспондентских отношений с банками, нашим банком установлены отношения и с другими финансовыми организациями через процедуру обмена ключами, что даёт возможность использовать SWIFT-форматы МТ-195, МТ-196 и МТ-199 для проведения процедуры расследования по стандартным платежам и платежам с покрытием:

- CITIBANK N.A. London
- CITIBANK N.A. Brussels

В среднем процедура расследования занимает от 3 до 14 дней (если необходимо уточнить дета…