Files
usb-server/driver/windows/README.md
duffyduckandClaude Opus 5 9ed473a965 Fix HID transfers, harden the tunnel, add E2E crypto and direct peers
The HID failure came down to the endpoint type map being indexed by
endpoint number without the direction bit. A composite device can have
endpoint 1 as both interrupt IN (0x81) and bulk OUT (0x01); the last one
read won, so interrupt URBs were submitted as bulk and the kernel rejected
them. The device attached and stayed silent.

Endpoint data now comes from the raw descriptors read from /dev/bus/usb
rather than sysfs, which only ever exposes the active alternate setting —
a webcam's isochronous endpoints are invisible there because they only
exist after SET_INTERFACE. Two sysfs parsing bugs fell out of that too:
the numeric endpoint attributes are hex without a prefix (wMaxPacketSize
"0040" was read as 40, not 64), and bInterval was never read at all.

Reliability: three places could freeze the whole process. The share path
fed io.Pipe from the WebSocket read loop, so one slow USB transfer stalled
every tunnel and the keepalives with them. The relay wrote to client
sockets while holding the hub lock, so one peer that stopped reading
blocked routing and registration for everyone. Control transfers ran
inline in the protocol loop behind a 5s timeout. Also fixed: a use-after-
free where a discarded URB's memory could be collected while the kernel
still owned it, a reap loop that spun at 100% CPU on ioctl errors, a
missing attach timeout, a double close(done) panic, and Hash[:8] in the
relay's log line, which let a client with a short hash take the server
down.

Adds mode "both", so one client can offer and consume devices at once.
The tunnel and client-left callbacks became multicast for it: as plain
fields the second manager to register silently unhooked the first.

Tunnel traffic is now AES-256-GCM end to end, on the relay path as well
as directly. The key is derived from the three tokens, not from the group
hash — the relay is told the hash, so a key derived from it would protect
nothing from the one party in the middle. Group IDs are unchanged, so
existing setups keep working; only clients configured without the tokens
drop to unencrypted, relay-only operation.

Peers now try to connect directly, with the relay supplying the public
address neither side can determine for itself. Candidates are raced
because an unreachable address hangs until timeout rather than refusing.
Falling back to the relay is not an error.

Platform reach: cross-compiled targets for ARM, MIPS and RISC-V (the
Linux client needed no code changes — usbdevfs is not architecture
specific), multi-arch Docker images, an Android bridge that accepts
devices over SCM_RIGHTS because apps cannot open /dev/bus/usb, and macOS
builds via system_profiler enumeration.

Adds a Windows KMDF filter driver under driver/windows with its Go side.
UNTESTED: it has never been compiled or run, needs the WDK to build and
an EV certificate to distribute. Treat it as a starting point.

Adds "usb-client diag": says per machine whether sharing and using are
possible, what stands in the way, and what fixes it. Reports can be
uploaded to a relay to get them off machines that are awkward to copy
from.

96 tests, all green under -race. Builds for linux, windows and darwin on
amd64 and arm64.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 22:02:04 +02:00

119 lines
5.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# usbshare — USB-Filtertreiber für Windows
Ein KMDF-Upper-Filtertreiber, der Userspace-Zugriff auf ein USB-Gerät
ermöglicht, **ohne** den vorhandenen Gerätetreiber zu ersetzen. Das ist der
Ansatz, den VirtualHere verwendet, und der Grund, warum es dort kein Zadig
braucht und das Gerät lokal funktionsfähig bleibt.
> ## Lies das zuerst
>
> **Dieser Code ist nie gelaufen.** Ich habe ihn geschrieben, aber weder
> kompiliert noch getestet — dafür braucht es Windows mit dem WDK, und das
> stand mir nicht zur Verfügung. Er ist als Ausgangspunkt gedacht, nicht als
> fertiges Produkt.
>
> Kernel-Code verzeiht nichts: ein Fehler ist ein Bluescreen, kein
> Stacktrace. Ein Treiber, der beim Booten geladen wird und dabei abstürzt,
> kann ein System unbootbar machen. **Teste ausschließlich in einer VM mit
> Snapshot**, bis er stabil läuft.
>
> Rechne mit mehreren Runden Debugging. Die Struktur sollte stimmen, die
> Details fast sicher nicht.
## Warum ein Filtertreiber
Windows hat kein Äquivalent zu Linux' usbdevfs. Um URBs an ein Gerät zu
senden, braucht es Kernel-Code. Die Alternativen:
| Ansatz | Gerät lokal nutzbar | Installation | HID/Massenspeicher |
|--------|---------------------|--------------|--------------------|
| WinUSB | Nein — ersetzt den Treiber | Zadig, pro Gerät | Meist blockiert |
| **Filtertreiber** | **Ja** | INF, pro Gerät oder klassenweit | Ja |
Der Filter setzt sich *über* den vorhandenen Treiber in den Stack. Im
Normalbetrieb reicht er alles unverändert durch. Erst wenn Userspace ein Gerät
beansprucht, fängt er die IRPs des Klassentreibers ab und leitet stattdessen
die URBs aus dem Userspace an den USB-Hub weiter.
```
Ohne Beanspruchung Während des Teilens
┌────────────────────┐ ┌────────────────────┐
│ Klassentreiber │ │ Klassentreiber │
│ (usbhid, usbstor) │ │ (bekommt nichts) │
└─────────┬──────────┘ └─────────┬──────────┘
abgefangen
┌─────────▼──────────┐ ┌─────────▼──────────┐
│ usbshare (Filter) │ │ usbshare (Filter) │◄── usb-client
└─────────┬──────────┘ └─────────┬──────────┘ via IOCTL
│ durchgereicht │ URBs
┌─────────▼──────────┐ ┌─────────▼──────────┐
│ USB-Hub-Treiber │ │ USB-Hub-Treiber │
└────────────────────┘ └────────────────────┘
```
## Dateien
| Datei | Inhalt |
|-------|--------|
| `driver.c` | Treiber-Einstieg, Geräte-Hinzufügen, PnP |
| `queue.c` | IOCTL-Verarbeitung, URB-Weiterleitung |
| `filter.c` | Abfangen der Klassentreiber-Anfragen im beanspruchten Zustand |
| `usbshare.h` | Interne Strukturen |
| `public.h` | IOCTL-Schnittstelle — auch von der Go-Seite verwendet |
| `usbshare.inf` | Installationsdatei |
| `usbshare.vcxproj` | Visual-Studio-Projekt |
## Bauen
Voraussetzungen: Visual Studio 2022 mit „Desktop development with C++",
Windows SDK und [WDK](https://learn.microsoft.com/windows-hardware/drivers/download-the-wdk).
```cmd
msbuild usbshare.vcxproj /p:Configuration=Release /p:Platform=x64
```
## Testen (nur in einer VM)
```cmd
:: Testsignierung erlauben — danach neu starten
bcdedit /set testsigning on
bcdedit /set nointegritychecks on
:: Selbst signieren
makecert -r -pe -ss PrivateCertStore -n "CN=usbshare-test" test.cer
signtool sign /v /s PrivateCertStore /n usbshare-test /t http://timestamp.digicert.com usbshare.sys
:: Installieren: Rechtsklick auf usbshare.inf → Installieren, dann Gerät neu einstecken
```
Für Kernel-Debugging: zweite Maschine oder Host mit WinDbg, verbunden über
`bcdedit /debug on` und `/dbgsettings net`.
## Verteilen
Für den Einsatz außerhalb einer Testmaschine muss der Treiber von Microsoft
gegengezeichnet sein. Dafür brauchst du:
1. **EV-Code-Signing-Zertifikat** — auf eine geprüfte reale Identität
(Firma oder Einzelperson), etwa 300500 €/Jahr, Ausstellung dauert Tage bis
Wochen wegen der Identitätsprüfung.
2. **Microsoft-Partner-Center-Konto**, verifiziert mit demselben Zertifikat.
3. **Attestation Signing**: Treiber hochladen, Microsoft zeichnet gegen.
Ausreichend für die meisten Fälle; volle WHQL-Zertifizierung braucht
zusätzlich HLK-Testläufe.
Diesen Teil kann nur jemand mit einer realen Identität erledigen — er läuft
auf deinen Namen, nicht auf meinen. Das ist die eigentliche Hürde, nicht der
Code.
## Was fehlt
Der Treiber deckt Control-, Bulk- und Interrupt-Transfers ab. Nicht
implementiert:
- **Isochrone Transfers** (Webcams, Audio). Sie brauchen eine andere
URB-Struktur mit Paketdeskriptoren und Bandbreitenreservierung.
- **Auswahl der Konfiguration/Alt-Settings** über den Filter — derzeit wird
die vom Klassentreiber gesetzte übernommen.
- **Reset und Halt-Clear** sind angelegt, aber ungetestet.