Plug It In, I Dare You: Build a BadUSB Tripwire for Your Linux Laptop in 20 Minutes

2026-12-05来源 dev.toEnglish

One Python script that knows the difference between a flash drive and a flash drive that types, plus the USBGuard rule that slams the door on it.

Somebody leaves a USB stick on your desk with a sticky note that says "Q3 photos," and in the half second before your file manager opens, that stick can introduce itself to your laptop as a keyboard and start typing. By the end of this post that half second becomes a red line in your terminal, a push notification on your phone, and a USBGuard policy that refuses the device before it gets a single keystroke in.

Everything here runs on your own machine against your own hardware. The "attacker" we build to test it carries no payload at all, which turns out to be the most interesting part.

The Lie Lives in the Descriptor

A USB device tells your computer what it is. Your computer believes it.

That handshake happens through interface descriptors, small blocks of bytes that carry a class code. Class 03 is HID, which covers keyboards and mice. Class 08 is mass storage. Classes 02 and 0a are CDC serial, the kind a dev board uses for its console. Class 0b is a smart card reader. One physical device can present several interfaces at once, and the operating system cheerfully loads a driver for each.

Karsten Nohl and Jakob Lell put the name BadUSB on this back in 2014, and the industry has been relearning it ever since. In January 2022 the FBI warned that FIN7 had been mailing LilyGO-branded USB devices to U.S. companies in transportation, insurance and defense, packaged as letters from the Department of Health and Human Services or as Amazon gift boxes with a fake gift card inside. Plugged in, each one registered as a keyboard and typed PowerShell that pulled down the next stage. Ransomware followed in some cases.

The keyboard needed no exploit. A cursor and somebody curious were plenty.

Read What Your Laptop Already Knows

Linux already sees all of this. It just doesn't say anything.

$ lsusb -t /: Bus 001.Port 001: Dev 001, Class=root_hub, Driver=xhci_hcd/12p, 480M |__ Port 002: Dev 004, If 0, Class=Human Interface Device, Driver=usbhid, 12M |__ Port 002: Dev 004, If 1, Class=Human Interface Device, Driver=usbhid, 12M |__ Port 002: Dev 004, If 2, Class=Chip/SmartCard, Driver=usbfs, 12M 

(Synthetic sample, trimmed.)

The live feed is better. Open a terminal and run udev's monitor filtered to whole devices:

$ udevadm monitor --udev --subsystem-match=usb/usb_device --property 

Plug something in and watch a block of KEY=value lines scroll past. The one that matters is ID_USB_INTERFACES, which udev fills in from the device's own descriptors:

ID_VENDOR_ID=1050 ID_MODEL_ID=0407 ID_USB_INTERFACES=:030101:030000:0b0000: 

Each six-character chunk is class, subclass and protocol. 030101 is a boot-protocol keyboard. 030000 is generic HID. 0b0000 is a smart card.

That example is a YubiKey 5 NFC, and yes, your security key is a keyboard. Yubico's own documentation says the OTP interface "presents itself to the operating system as a USB keyboard," which is how it types a one-time code when you touch it. Keep that in your pocket for the next section. A tripwire that screams at every HID device will scream at the most trustworthy thing you own, and you'll mute it inside a week.

HID alone proves nothing. The tripwire has to read context.

The Tripwire: usbsnitch.py

The logic fits on an index card. Snapshot every device plugged in right now as your baseline. Then watch udev and judge each new arrival against four questions:

  • NEW: has this vendor and product ID ever been here before?
  • SHAPESHIFT: is this a device you know, presenting a different set of interfaces than last time? A flash drive that suddenly grew a keyboard lands here.
  • HID+STORAGE: does one device claim to be both a drive and a keyboard? That's the classic BadUSB costume.
  • HID+SERIAL: does it claim keyboard plus a serial console? That's how a lot of hobby boards enumerate, including the cheap ones people repurpose for keystroke injection, so it earns a yellow note rather than a siren.

A known device that shows up looking exactly like itself stays silent. A new device with HID, a shapeshifter, or a keyboard-drive hybrid goes red, gets logged as JSON, and pings your phone through ntfy if you give it a topic.

#!/usr/bin/env python3 """usbsnitch: yell when a USB device shows up as something it wasn't before. learn: sudo python3 usbsnitch.py --learn watch: sudo python3 usbsnitch.py --ntfy https://ntfy.sh/your-random-topic replay: python3 usbsnitch.py --replay captured.txt """ import argparse, glob, json, os, shutil, subprocess, sys, time, urllib.request SYS = "/sys/bus/usb/devices" BASE = os.path.expanduser("~/.usbsnitch.json") LOG = os.path.expanduser("~/.usbsnitch.jsonl") RED, AMB, DIM, OFF = "\033[1;31m", "\033[1;33m", "\033[2m", "\033[0m" def read(path): try: with open(path) as f: return f.read().strip() except OSError: return "" def sysfs_devices(root): """Yield (vid:pid, name, interface set) for every device plugged in now.""" for dev in sorted(glob.glob(os.path.join(root, "*"))): vid, pid = read(f"{dev}/idVendor"), read(f"{dev}/idProduct") if not vid: continue # interface dirs and root hubs without ids ifaces = set() for i in glob.glob(os.path.join(dev, "*:*")): # 1-2:1.0, 1-2:1.1 ... c, s, p = (read(f"{i}/bInterface{k}") for k in ("Class", "SubClass", "Protocol")) if c: ifaces.add(c + s + p) name = " ".join(filter(None, [read(f"{dev}/manufacturer"), read(f"{dev}/product")])) yield f"{vid}:{pid}", name or "unnamed", ifaces def learn(root): base = {k: {"name": n, "ifaces": sorted(i)} for k, n, i in sysfs_devices(root)} with open(BASE, "w") as f: json.dump(base, f, indent=2) print(f"learned {len(base)} devices -> {BASE}") def classify(key, ifaces, base): classes = {i[:2] for i in ifaces} hid, storage, serial = "03" in classes, "08" in classes, bool({"02", "0a"} & classes) flags = [] if key not in base: flags.append("NEW") elif set(base[key]["ifaces"]) != ifaces: flags.append("SHAPESHIFT") if hid: flags.append("HID") if hid and storage: flags.append("HID+STORAGE") elif hid and serial: flags.append("HID+SERIAL") loud = {"SHAPESHIFT", "HID+STORAGE"} & set(flags) or ("NEW" in flags and hid) return flags, ("RED" if loud else "NOTE" if flags else None) def events(stream): """Turn `udevadm monitor --property` text into dicts, one per event.""" ev = {} for line in stream: line = line.rstrip("\n") if not line: if ev: yield ev ev = {} elif "=" in line and not line.startswith(("UDEV", "KERNEL")): k, _, v = line.partition("=") ev[k] = v if ev: yield ev def alert(level, key, name, flags, ifaces, ntfy): stamp = time.strftime("%H:%M:%S") color = RED if level == "RED" else AMB print(f"{color}[{stamp}] {level:4} {key} {name!r} {' '.join(flags)}{OFF}" f" {DIM}ifaces={','.join(sorted(ifaces))}{OFF}", flush=True) with open(LOG, "a") as f: f.write(json.dumps({"t": time.time(), "level": level, "id": key, "name": name, "flags": flags, "ifaces": sorted(ifaces)}) + "\n") if level != "RED": return msg = f"{key} {name} {' '.join(flags)}" if ntfy: try: urllib.request.urlopen(urllib.request.Request( ntfy, data=msg.encode(), headers={"Title": "usbsnitch", "Priority": "high"}), timeout=5) except OSError as e: print(f"{DIM}ntfy failed: {e}{OFF}", file=sys.stderr) if shutil.which("notify-send") and os.environ.get("DISPLAY"): subprocess.run(["notify-send", "-u", "critical", "usbsnitch", msg], check=False) def watch(stream, ntfy): base = json.load(open(BASE)) if os.path.exists(BASE) else {} if not base: print(f"{AMB}no baseline at {BASE}; everything will look new. run --learn first.{OFF}") for ev in events(stream): if ev.get("ACTION") != "add" or ev.get("DEVTYPE") != "usb_device": continue key = f"{ev.get('ID_VENDOR_ID', '????')}:{ev.get('ID_MODEL_ID', '????')}" ifaces = {i for i in ev.get("ID_USB_INTERFACES", "").split(":") if i} name = (ev.get("ID_VENDOR_FROM_DATABASE") or ev.get("ID_VENDOR", "")) + " " + ev.get("ID_MODEL", "") flags, level = classify(key, ifaces, base) if level: alert(level, key, name.strip(), flags, ifaces, ntfy) def main(): ap = argparse.ArgumentParser() ap.add_argument("--learn", action="store_true", help="snapshot what's plugged in now") ap.add_argument("--replay", help="parse saved udevadm monitor output instead of live") ap.add_argument("--ntfy", help="ntfy topic URL for RED alerts") ap.add_argument("--sys", default=SYS, help=argparse.SUPPRESS) a = ap.parse_args() if a.learn: return learn(a.sys) if a.replay: with open(a.replay) as f: return watch(f, a.ntfy) cmd = ["udevadm", "monitor", "--udev", "--subsystem-match=usb/usb_device", "--property"] with subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) as p: print(f"{DIM}watching usb. plug something in.{OFF}", flush=True) try: watch(p.stdout, a.ntfy) except KeyboardInterrupt: p.terminate() if __name__ == "__main__": main() 

Standard library only. The baseline comes from sysfs, where every plugged-in device exposes idVendor, idProduct and a folder per interface with its class bytes, so learning takes a fraction of a second:

$ sudo python3 usbsnitch.py --learn learned 7 devices -> /root/.usbsnitch.json $ sudo python3 usbsnitch.py --ntfy https://ntfy.sh/pick-a-long-random-topic watching usb. plug something in. 

Your YubiKey, your mouse receiver and the flash drive you already own are now furniture. Plug any of them back in and nothing happens. That silence is the whole point.

Build a Bad USB That Isn't Bad

Testing a tripwire with a real malicious device is a great way to own yourself. You don't need one. You need a board that enumerates the same way and does nothing.

A Raspberry Pi Pico 2 is perfect for this, and the trick is that stock CircuitPython already wears the costume. Hold BOOTSEL, plug the board in, and it mounts as a drive. Drag the CircuitPython .uf2 for the Pico 2 onto it. The board reboots and comes back presenting a CIRCUITPY drive, a serial console and USB HID by default, so it can act as a keyboard the moment someone writes code for it. You write nothing. The descriptor alone is the test.

Here's the run, replayed against a captured feed:

watching usb. plug something in. [06:53:55] NOTE 2e8a:000f 'Raspberry_Pi RP2350_Boot' NEW ifaces=080650,ff0000 [06:53:55] RED 239a:80f4 'Raspberry_Pi Pico_2' NEW HID HID+STORAGE ifaces=010100,010300,020200,030000,080650,0a0000 [06:53:55] RED 0781:5583 'SanDisk Ultra_Fit' SHAPESHIFT HID HID+STORAGE ifaces=030101,080650 

(Synthetic sample from the replay test. Your vendor and product IDs will differ by board and firmware version.)

Read it top to bottom. The BOOTSEL drive is new but harmless, so it gets a quiet yellow note. Thirty seconds later the same physical board comes back as a drive that can type, and the line goes red while your phone buzzes. The third line is the nightmare case staged in a fixture: a SanDisk ID your baseline knows as plain storage, now carrying a keyboard interface. Somebody reflashed a familiar-looking stick, and the shapeshift flag catches it even though the vendor ID is one you trust.

The device is in. You watched it walk through the door.

The JSON log lands in ~/.usbsnitch.jsonl, one line per event, ready for whatever watches your logs.

Slam the Door With USBGuard

The snitch tells you. USBGuard stops it. It's a daemon that sits on the kernel's USB authorization switch and decides, per device, whether drivers ever bind.

Install it from your distro (apt install usbguard, dnf install usbguard or pacman -S usbguard), then generate a policy from what's plugged in right now before the daemon starts enforcing:

$ sudo sh -c 'usbguard generate-policy > /etc/usbguard/rules.conf' $ sudo chmod 0600 /etc/usbguard/rules.conf 

Open the file. Each line is an allow rule pinned to a device's ID, serial, port and a hash of its descriptors. Above all of them, add one line of your own:

reject with-interface all-of { 08:*:* 03:*:* } 

That's straight out of USBGuard's rule language: any device presenting mass storage and HID together gets rejected before a driver touches it. Rules match top to bottom, so keep it first. Then turn it on and watch it work:

$ sudo systemctl enable --now usbguard $ sudo usbguard watch 

Plug in the Pico and usbguard watch prints the device and a reject target while usbsnitch prints its red line beside it. Two witnesses, one verdict. When you plug in something legitimate that's new, a fresh keyboard or a dev board you actually want, find it and allow it on purpose:

$ sudo usbguard list-devices --blocked $ sudo usbguard allow-device 14 -p 

The -p makes it permanent by writing the rule into your policy.

One warning written in blood. On a desktop with a USB keyboard, a policy generated with the keyboard unplugged locks you out of your own machine. Generate with everything connected, and keep SSH or a second way in until you've rebooted once and confirmed you can still type.

USB is only one door on a modern laptop. Thunderbolt and USB4 ports can expose PCIe, and PCIe means a device can ask for direct memory access, which is a different class of trust problem than a fake keyboard. If your machine has those ports, STRIKE//DMA: Laptop Peripheral Trust & DMA Security ($80) is the next read. It's a 20-chapter defensive guide to peripheral trust boundaries, Thunderbolt, PCIe and DMA threat modeling, how to inspect what your ports actually allow, and safer laptop configurations, which is the part this script can't see.

Make It Run While You Sleep

A tripwire you have to remember to start is a tripwire you won't start. Drop the script in /usr/local/bin, learn as root, and give it a unit file:

$ sudo install -m 0755 usbsnitch.py /usr/local/bin/usbsnitch.py $ sudo HOME=/root python3 /usr/local/bin/usbsnitch.py --learn 
# /etc/systemd/system/usbsnitch.service [Unit] Description=usbsnitch USB tripwire After=systemd-udevd.service [Service] Environment=HOME=/root ExecStart=/usr/bin/python3 /usr/local/bin/usbsnitch.py --ntfy https://ntfy.sh/pick-a-long-random-topic Restart=on-failure [Install] WantedBy=multi-user.target 
$ sudo systemctl daemon-reload && sudo systemctl enable --now usbsnitch $ journalctl -u usbsnitch -f 

Public ntfy topics are readable by anyone who guesses the name, so make it long and random, or point --ntfy at your own self-hosted ntfy server.

Once usbsnitch.jsonl is accumulating, the next problem is noise. You'll have USB events, SSH logins, failed units and a dozen other logs, and nobody reads twelve logs. OpenClaw Black: Local Log-Watching Agent with Reviewed Alerts ($40) builds a local watcher on a Raspberry Pi that does exactly this: deterministic checks first, optional model reasoning layered on top, state and memory kept locally, and Telegram alerts you review before anything acts. Feed it this log and a red USB line becomes one item in a nightly digest instead of another tab you forgot to check.

Software is half the habit. When you charge from a hotel lamp or an airport kiosk, a PortaPow USB-A data blocker passes power and physically drops the data lines, so there's no descriptor to lie with in the first place. Get the version that matches your cable ends and confirm the listing says data pins are disconnected, since some cheap "blockers" are just short adapters.

Ports you never use don't need to be ports at all. Lindy USB Type-A port blockers snap into empty sockets and need a key to pull out. They won't stop a determined person with pliers. They will stop the casual "can I just plug this in real quick" that most of these attacks actually rely on.

Leave the Pico on your desk with a sticky note that says "Q3 photos." Plug it in every few months. If nothing turns red, something broke, and you'd rather learn that from your own decoy than from somebody else's.

原文:https://www.a8q9.cn/en/article/plug-it-in-i-dare-you-build-a-badusb-tripwire-for-your-linux-laptop-in-20-minute-91804a.html

相关文章