# Bad Keyboard Attacks: Technical Deep Dive

## Hardware Architecture and Implementation

### USB Controller Microarchitecture

At the heart of every bad keyboard device lies a microcontroller capable of USB communication and HID (Human Interface Device) emulation. Understanding the hardware architecture is crucial for both implementing attacks and developing effective countermeasures.

#### Core Components

**Primary Microcontroller**: The central processing unit that handles USB protocol communication, payload storage, and execution logic. Common choices include:

* **ATmega32U4**: Arduino-compatible microcontroller with native USB support
* **STM32F103**: ARM Cortex-M3 based controller with USB OTG capabilities
* **ESP32-S2**: WiFi-capable microcontroller with USB HID support
* **RP2040**: Raspberry Pi's dual-core ARM processor with flexible PIO for USB

**USB Interface Hardware**: Physical implementation of USB protocol handling:

* USB transceiver circuits for differential signaling
* Crystal oscillators for precise timing (typically 12MHz or 16MHz)
* Voltage regulation for 3.3V/5V operation
* ESD protection circuits

**Memory Architecture**:

* **Flash Memory**: Stores firmware, attack payloads, and configuration (typically 32KB-2MB)
* **SRAM**: Runtime memory for variable storage and execution (typically 2KB-256KB)
* **EEPROM**: Non-volatile storage for persistent configuration (typically 512B-4KB)

#### Advanced Hardware Features

**Multi-Interface Controllers**: Some sophisticated devices implement multiple USB interfaces simultaneously:

* Mass storage controller for appearing as USB drive
* HID controller for keyboard/mouse emulation
* CDC (Communication Device Class) for serial communication
* Custom vendor-specific interfaces

**Wireless Capabilities**: Modern attack devices often include:

* **WiFi modules** for remote command and control
* **Bluetooth LE** for covert communication
* **Sub-GHz radio** (433MHz, 915MHz) for long-range triggering
* **NFC interfaces** for proximity-based activation

**Environmental Sensors**: Advanced devices may include:

* **Accelerometers** to detect insertion/removal
* **Temperature sensors** to detect operating environment
* **Light sensors** to determine if device is concealed
* **Timing circuits** for delayed activation

### USB Protocol Deep Dive

#### USB Enumeration Process

Understanding the detailed USB enumeration process reveals multiple intervention points for both attacks and defenses:

1. **Device Attachment Detection**
   * Host detects device insertion via voltage level changes
   * USB hub reports port status change to host controller
   * Host begins enumeration sequence
2. **Initial Communication Setup**

   ```
   Host → Device: GET_STATUS request (checks device responsiveness)
   Device → Host: Status response
   Host → Device: RESET signal (resets device to known state)
   ```
3. **Device Descriptor Retrieval**

   ```
   Host → Device: GET_DESCRIPTOR (Device) request
   Device → Host: Device descriptor containing:
     - Vendor ID (VID)
     - Product ID (PID)  
     - Device class information
     - Configuration count
   ```
4. **Configuration and Interface Setup**

   ```
   Host → Device: GET_DESCRIPTOR (Configuration) request
   Device → Host: Configuration descriptor detailing:
     - Interface count and types
     - Endpoint configurations
     - Power requirements
   ```
5. **Driver Assignment and Activation**
   * OS matches descriptors against available drivers
   * Appropriate driver loaded (typically usbhid.sys on Windows)
   * Device granted access to input subsystem

#### HID Protocol Implementation

**HID Descriptor Structure**: Defines the device's capabilities and report formats:

```c
typedef struct {
    uint8_t bLength;           // Descriptor length
    uint8_t bDescriptorType;   // HID descriptor type (0x21)
    uint16_t bcdHID;          // HID specification version
    uint8_t bCountryCode;     // Country code for hardware
    uint8_t bNumDescriptors;  // Number of report descriptors
    uint8_t bDescriptorType2; // Report descriptor type (0x22)
    uint16_t wDescriptorLength; // Report descriptor length
} HID_DESCRIPTOR;
```

**HID Report Descriptor**: Defines input/output report formats using a compact binary language:

```c
// Example keyboard report descriptor
static const uint8_t keyboard_report_descriptor[] = {
    0x05, 0x01,        // Usage Page (Generic Desktop)
    0x09, 0x06,        // Usage (Keyboard)
    0xa1, 0x01,        // Collection (Application)
    0x05, 0x07,        //   Usage Page (Keyboard/Keypad)
    0x19, 0xe0,        //   Usage Minimum (224)
    0x29, 0xe7,        //   Usage Maximum (231)
    0x15, 0x00,        //   Logical Minimum (0)
    0x25, 0x01,        //   Logical Maximum (1)
    0x75, 0x01,        //   Report Size (1)
    0x95, 0x08,        //   Report Count (8)
    0x81, 0x02,        //   Input (Data,Var,Abs)
    // ... additional fields for key codes
};
```

#### USB Communication Timing

**Critical Timing Windows**: Understanding USB timing is essential for both attack optimization and detection:

* **Device Recognition**: 10-100ms for initial enumeration
* **Driver Loading**: 100-1000ms depending on system performance
* **First Input Capability**: 200-2000ms total from insertion
* **Polling Interval**: Typically 10ms for keyboard devices (configurable)

### Dual-Function USB Drive Architecture

#### The Microcontroller Revolution in USB Storage

Modern USB flash drives increasingly use sophisticated microcontrollers rather than simple storage controllers, creating opportunities for dual-function implementations that can act as both storage devices and HID input devices.

#### Hardware Implementation Details

**Controller Selection**: Advanced USB drives use microcontrollers capable of implementing multiple USB device classes:

* **Alcor Micro AU6989**: Common in consumer USB drives, supports mass storage and HID
* **Phison PS2251**: High-performance controller with custom firmware capabilities
* **SMI (Silicon Motion) SM3267**: Supports multiple interface configurations
* **Realtek RTS5561**: Dual-interface capable with large flash memory support

**Memory Architecture in Dual-Function Devices**:

```
[Flash Memory Layout]
├── Firmware Partition (32-128KB)
│   ├── USB Mass Storage Driver
│   ├── HID Keyboard Driver  
│   ├── Attack Payload Code
│   └── Configuration Data
├── Storage Partition (Remaining Space)
│   ├── Legitimate Files (for cover)
│   ├── Additional Payloads
│   └── Exfiltrated Data Storage
└── Hidden Partition (Optional)
    ├── Advanced Payloads
    └── Persistence Mechanisms
```

#### USB Composite Device Implementation

**Composite Device Architecture**: A single USB device presenting multiple interfaces simultaneously:

```c
// USB Configuration Descriptor for Composite Device
typedef struct {
    USB_CONFIG_DESCRIPTOR config;
    
    // Mass Storage Interface
    USB_INTERFACE_DESCRIPTOR msc_interface;
    USB_ENDPOINT_DESCRIPTOR msc_bulk_in;
    USB_ENDPOINT_DESCRIPTOR msc_bulk_out;
    
    // HID Keyboard Interface  
    USB_INTERFACE_DESCRIPTOR hid_interface;
    HID_DESCRIPTOR hid_descriptor;
    USB_ENDPOINT_DESCRIPTOR hid_interrupt_in;
    
} COMPOSITE_CONFIG_DESCRIPTOR;
```

**Interface Coordination**: The microcontroller firmware must handle multiple USB interfaces concurrently:

* **Mass Storage Class (MSC)**: Implements SCSI commands over USB for file system access
* **Human Interface Device (HID)**: Handles keyboard input reports and LED status
* **Endpoint Management**: Separate endpoints for storage data and HID reports
* **Power Management**: Coordinating power states across multiple interfaces

#### Firmware Reflashing and Customization

**Factory Firmware Vulnerabilities**: Many USB drive controllers can be reflashed with custom firmware:

**Common Reflashing Methods**:

1. **Vendor Tools**: Manufacturers provide firmware update utilities

   ```
   # Example using Phison tools
   GetInfo.exe [device] # Identify controller and current firmware
   UDiskMP.exe [firmware.bin] [device] # Flash custom firmware
   ```
2. **JTAG Interface**: Hardware debugging interface for direct firmware access

   ```
   [USB Controller] ---- [JTAG Debugger] ---- [Development PC]
                  ↓
              [Custom Firmware Upload]
   ```
3. **Bootloader Exploitation**: Exploiting firmware update mechanisms

   ```c
   // Example bootloader entry sequence
   while (bootloader_pin_active()) {
       if (receive_firmware_signature_valid()) {
           flash_firmware(received_data);
           restart_with_new_firmware();
       }
   }
   ```

**Custom Firmware Capabilities**:

* **Dynamic Interface Switching**: Alternating between storage and HID modes
* **Conditional Activation**: HID functionality triggered by specific conditions
* **Steganographic Storage**: Hiding attack data within legitimate files
* **Anti-Forensics**: Firmware that can destroy evidence when detected

#### Implementation Example: BadUSB on USB Drive

**Firmware Structure** for a dual-function attack device:

```c
// Main firmware loop
void main_loop() {
    switch (current_mode) {
        case MODE_STORAGE:
            handle_mass_storage_requests();
            if (attack_trigger_detected()) {
                switch_to_hid_mode();
            }
            break;
            
        case MODE_HID:
            execute_attack_payload();
            if (attack_complete()) {
                switch_to_storage_mode();
            }
            break;
    }
}

// Attack trigger detection
bool attack_trigger_detected() {
    // Examples of trigger conditions:
    return (specific_file_accessed() ||
            time_delay_expired() ||
            remote_activation_received());
}

// Mode switching implementation
void switch_to_hid_mode() {
    usb_disconnect();
    reconfigure_usb_descriptors(HID_DESCRIPTORS);
    usb_reconnect();
    current_mode = MODE_HID;
}
```

### Software Implementation Deep Dive

#### Attack Payload Development Framework

**DuckyScript Interpreter**: Most attack devices implement a DuckyScript interpreter in firmware:

```c
typedef struct {
    uint8_t command;
    uint16_t parameter;
    uint8_t data[];
} DUCKY_COMMAND;

// Command processing loop
void execute_ducky_script(uint8_t* script, size_t length) {
    DUCKY_COMMAND* cmd = (DUCKY_COMMAND*)script;
    
    while (cmd < script + length) {
        switch (cmd->command) {
            case CMD_STRING:
                type_string((char*)cmd->data);
                break;
            case CMD_DELAY:
                delay_ms(cmd->parameter);
                break;
            case CMD_KEY:
                send_key_combination(cmd->parameter);
                break;
            // ... additional commands
        }
        cmd = next_command(cmd);
    }
}
```

**Advanced Payload Capabilities**:

* **Environment Detection**: Identifying target OS, security software, and system configuration
* **Adaptive Execution**: Modifying behavior based on detected environment
* **Error Handling**: Graceful failure and recovery mechanisms
* **Logging and Reporting**: Recording attack success/failure for later analysis

#### Operating System Integration Points

**Windows HID Stack Interaction**:

```
Application Layer
    ↓
Win32 API (User32.dll, Kernel32.dll)
    ↓  
Windows Message Queue
    ↓
Raw Input/Legacy Input APIs
    ↓
HID Class Driver (hidclass.sys)
    ↓
HID USB Transport (hidusb.sys)
    ↓
USB Hub Driver (usbhub.sys)
    ↓
USB Host Controller (ehci.sys/xhci.sys)
    ↓
Hardware (USB Controller)
```

**Linux HID Processing Pipeline**:

```
Userspace Applications
    ↓
Input Subsystem (/dev/input/eventX)
    ↓
Input Core (input.c)
    ↓
HID Core (hid-core.c)
    ↓
USB HID Driver (usbhid/hid-core.c)
    ↓
USB Subsystem (usb-core)
    ↓
USB Host Controller Driver
    ↓
Hardware
```

#### Kernel-Level Attack Implementation

**Direct Kernel Memory Manipulation**: Advanced attacks may attempt to modify kernel structures:

```c
// Example Windows kernel structure manipulation
typedef struct _DEVICE_OBJECT {
    CSHORT Type;
    USHORT Size;
    LONG ReferenceCount;
    struct _DRIVER_OBJECT *DriverObject;
    // ... additional fields
} DEVICE_OBJECT, *PDEVICE_OBJECT;

// Hypothetical attack modifying device permissions
NTSTATUS modify_device_permissions(PDEVICE_OBJECT device) {
    // Locate security descriptor
    PSECURITY_DESCRIPTOR sec_desc = get_device_security_descriptor(device);
    
    // Modify ACL to grant additional access
    modify_acl_permissions(sec_desc, GENERIC_ALL);
    
    return STATUS_SUCCESS;
}
```

### Advanced Attack Techniques

#### Firmware-Level Persistence

**UEFI/BIOS Modification**: Some sophisticated attacks target system firmware:

```c
// Example UEFI DXE driver installation
EFI_STATUS InstallMaliciousDxeDriver() {
    EFI_HANDLE ImageHandle;
    EFI_DEVICE_PATH_PROTOCOL* DevicePath;
    
    // Load malicious driver from embedded storage
    Status = gBS->LoadImage(FALSE, gImageHandle, DevicePath, 
                           MaliciousDriverImage, DriverSize, &ImageHandle);
    
    if (!EFI_ERROR(Status)) {
        // Start the malicious driver
        Status = gBS->StartImage(ImageHandle, NULL, NULL);
    }
    
    return Status;
}
```

#### Hardware Security Module Bypass

**TPM Interaction**: Advanced attacks may attempt to interact with hardware security modules:

```c
// Example TPM command construction
typedef struct {
    uint16_t tag;
    uint32_t paramSize;
    uint32_t ordinal;
    uint8_t authHandle[4];
    uint8_t nonceOdd[20];
    uint8_t continueAuthSession;
    uint8_t authData[20];
} TPM_COMMAND_HEADER;

// Attempt to extract stored keys or certificates
uint32_t attempt_tpm_key_extraction() {
    TPM_COMMAND_HEADER cmd;
    cmd.ordinal = TPM_ORD_GetPubKey;
    // ... construct command
    
    return send_tpm_command(&cmd);
}
```

### Detection and Analysis Techniques

#### Hardware-Level Detection

**USB Traffic Analysis**: Monitoring USB communication patterns:

```c
// USB packet capture structure
typedef struct {
    uint64_t timestamp;
    uint8_t endpoint;
    uint8_t direction;
    uint16_t length;
    uint8_t data[];
} USB_PACKET;

// Anomaly detection in USB timing
bool detect_automated_input(USB_PACKET* packets, size_t count) {
    for (size_t i = 1; i < count; i++) {
        uint64_t interval = packets[i].timestamp - packets[i-1].timestamp;
        
        // Detect impossibly fast or perfectly regular timing
        if (interval < MIN_HUMAN_INTERVAL || 
            interval == EXACT_AUTOMATED_INTERVAL) {
            return true;
        }
    }
    return false;
}
```

#### Firmware Analysis Techniques

**Firmware Extraction and Reverse Engineering**:

```bash
# Extract firmware from USB device
dd if=/dev/sdb of=firmware.bin bs=512 count=64

# Analyze firmware structure
binwalk firmware.bin
strings firmware.bin | grep -i "ducky\|payload\|attack"

# Disassemble firmware code
objdump -D -m arm firmware.bin
```

**Static Analysis of Attack Payloads**:

```python
# DuckyScript payload analysis
def analyze_ducky_script(script_content):
    suspicious_patterns = [
        r'powershell.*-w.*hidden',
        r'cmd.*\/c.*echo.*\|.*certutil',
        r'START.*iexplore.*data:',
        r'STRING.*http.*\.exe'
    ]
    
    threats = []
    for pattern in suspicious_patterns:
        if re.search(pattern, script_content, re.IGNORECASE):
            threats.append(f"Suspicious pattern: {pattern}")
    
    return threats
```

### Countermeasure Implementation

#### Hardware-Based Protection

**USB Port Filtering Hardware**:

```c
// Hardware USB filter implementation
typedef struct {
    uint16_t vid;
    uint16_t pid;
    uint8_t device_class;
    bool authorized;
} DEVICE_POLICY;

bool evaluate_device_policy(USB_DEVICE_DESCRIPTOR* desc) {
    DEVICE_POLICY* policy = lookup_device_policy(desc->idVendor, desc->idProduct);
    
    if (!policy) {
        // Unknown device - request authorization
        return request_user_authorization(desc);
    }
    
    return policy->authorized;
}
```

#### Software-Based Monitoring

**Real-Time Input Analysis**:

```c
// Keystroke timing analysis
typedef struct {
    uint64_t timestamp;
    uint8_t keycode;
    bool is_press;
} KEYSTROKE_EVENT;

bool detect_automated_typing(KEYSTROKE_EVENT* events, size_t count) {
    double avg_interval = calculate_average_interval(events, count);
    double variance = calculate_variance(events, count);
    
    // Human typing has high variance, automated typing is regular
    return (variance < AUTOMATED_VARIANCE_THRESHOLD);
}
```

## Conclusion: The Technical Landscape

The technical implementation of bad keyboard attacks represents a sophisticated intersection of hardware engineering, firmware development, USB protocol manipulation, and operating system exploitation. Understanding these technical details is crucial for cybersecurity professionals developing effective countermeasures.

The evolution toward dual-function USB devices with reflashable firmware represents a significant escalation in attack sophistication. These devices blur the line between legitimate storage devices and malicious input devices, making detection and prevention significantly more challenging.

Key technical takeaways include:

1. **Hardware Complexity**: Modern attack devices use sophisticated microcontrollers with multiple interface capabilities
2. **Firmware Flexibility**: Reflashable firmware enables dynamic attack capabilities and evasion techniques
3. **USB Protocol Exploitation**: Deep understanding of USB enumeration and HID protocols enables sophisticated attacks
4. **Operating System Integration**: Attacks leverage trusted input pathways that bypass traditional security controls
5. **Detection Challenges**: Technical countermeasures must operate at multiple levels from hardware to application

This technical landscape continues to evolve as attackers develop more sophisticated techniques and defenders implement more advanced detection and prevention mechanisms. The arms race between attack and defense in this domain requires deep technical expertise and continuous innovation on both sides.
